Skip to main content

agentmux_srv_core/backend/
agent_config.rs

1// Copyright 2024-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pure config-building logic for agent definitions.
5//!
6//! Builds an agent launch's config files (the startup file, settings, skills, `.mcp.json`) and expands
7//! the `{{...}}` template variables. `agent.open` and the window's Launch both render them here.
8//! Most functions here are pure — no I/O, no async. The exception is the
9//! `managed skill files manifest` section near the end: real filesystem
10//! I/O shared by the two independent RPC handlers that materialize config
11//! files to disk (`agent.open`'s `write_agent_config_files` in
12//! `server/app_api/agent_open.rs`, and `writeagentconfig` in
13//! `server/editor_handlers.rs` — the latter is the actual "click Launch"
14//! path used on every normal agent launch). Lives here rather than in
15//! either handler file so the two callers can't drift out of sync on the
16//! manifest format or the path-traversal defense (reagent P1, PR #2322 —
17//! `writeagentconfig` initially had no cleanup at all).
18
19use std::collections::{HashMap, HashSet};
20
21use chrono::Utc;
22use serde_json::{json, Value};
23
24use crate::backend::storage::store::{derive_slug, AgentSkill};
25
26/// `skill_type` value that materializes a skill as an Agent Skills-format
27/// `.claude/skills/<slug>/SKILL.md` instead of a `.claude/commands/<trigger>.md`
28/// slash command. Any other value (in practice, always `"prompt"` today) keeps
29/// the pre-existing slash-command behavior. See
30/// `docs/specs/REPORT_ARMORY_BUNDLE_STANDARD_RESEARCH_2026_07_16.md` Phase 0 —
31/// `skill_type` already existed end-to-end but was never branched on before
32/// this, making it the lowest-friction place to hang the format discriminator
33/// rather than adding a new column.
34pub const SKILL_TYPE_AGENT_SKILL: &str = "agent-skill";
35
36/// A single file to be written to the agent working directory.
37#[derive(Debug, Clone)]
38pub struct AgentConfigFile {
39    /// Path relative to the agent working directory (e.g. `"CLAUDE.md"`, `".mcp.json"`).
40    pub filename: String,
41    /// UTF-8 file content.
42    pub content: String,
43}
44
45/// The startup file's skills index, each skill by its `/<trigger>`; empty when
46/// it lists none. Claude Code lists the skills it has a file for
47/// (.claude/commands, .claude/skills) by itself, so for it the index carries
48/// only those without one (LC3, §4.4). By the resolved provider, so an alias
49/// (`claude-code`) counts as Claude. Shared with `memory:launchcost`.
50///
51/// Any other provider has no skill loader, so for it an Agent Skill's line names the `SKILL.md` that
52/// `build_config_files` wrote for it (`.claude/skills/<slug>/SKILL.md`, written for every provider) and
53/// the heading's sentence tells the agent to read that file before it acts (Skills B6). Claude's index
54/// keeps the sentence an older AgentMux wrote, which `is_legacy_agentmux_claude_md` still matches.
55pub fn skills_index_text(skills: &[AgentSkill], provider_id: &str) -> String {
56    let is_claude = crate::backend::providers::get_provider(provider_id).is_some_and(|p| p.id == "claude");
57    let own_file = skills_with_their_own_file(skills);
58    let slugs = crate::backend::skill_slugs::agent_skill_slugs(skills);
59    let indexed: Vec<_> = skills.iter().zip(slugs).enumerate().filter(|(i, _)| !is_claude || !own_file[*i]).map(|(_, s)| s).collect();
60    if indexed.is_empty() {
61        return String::new();
62    }
63    let usage = if is_claude {
64        "Use `/<trigger>` to invoke a skill."
65    } else {
66        "Read a skill's file before you act on what its line describes; the line is all you have until you do. \
67         A skill with a trigger can also be run as `/<trigger>`. The `Skills` tool (`list`, then `get`) reads any skill."
68    };
69    let mut out = format!("\n# Available Skills\n\n{usage}\n\n");
70    for (skill, slug) in indexed {
71        let trigger_part = if skill.trigger.is_empty() { String::new() } else { format!(" (trigger: /{})", skill.trigger) };
72        let desc_part = if skill.description.is_empty() { String::new() } else { format!(" \u{2014} {}", skill.description) };
73        let file_part = match slug {
74            Some(slug) if !is_claude => format!(" (file: `.claude/skills/{slug}/SKILL.md`)"),
75            _ => String::new(),
76        };
77        out.push_str(&format!("- **{}**{}{}{}\n", skill.name, trigger_part, desc_part, file_part));
78    }
79    out
80}
81
82/// Build the list of config files to write to the agent working directory.
83///
84/// Assembles the startup instructions file (`CLAUDE.md`, `AGENTS.md`,
85/// `GEMINI.md`, ... — resolved per `provider_id` via
86/// `providers::get_provider(provider_id).startup_instructions_filename`;
87/// see docs/specs/SPEC_PROVIDER_AWARE_STARTUP_INSTRUCTIONS_2026_08_24.md)
88/// from `soul` + `agentmd` + `memory` + skills index, writes each skill as
89/// a slash command under `.claude/commands/<trigger>.md`, writes
90/// `.claude/hooks.json` if a `hooks` content entry is present, auto-injects
91/// the AgentMux MCP server entry, and applies `{{VARIABLE}}` template
92/// substitution throughout. An unrecognized `provider_id`, or one with no
93/// confirmed native file, gets no instructions
94/// file written at all — never a silent `CLAUDE.md` fallback.
95///
96/// The one builder of an agent launch's config files; both launch entry points call it through `render_agent_config_files`.
97pub fn build_config_files(
98    content_map: &HashMap<String, String>,
99    skills: &[AgentSkill],
100    agent_name: &str,
101    agent_id: &str,
102    agent_slug: &str,
103    working_directory: &str,
104    provider_id: &str,
105) -> Vec<AgentConfigFile> {
106    let mut files: Vec<AgentConfigFile> = Vec::new();
107
108    // Template variables for {{}} substitution
109    let mut template_vars: HashMap<String, String> = HashMap::new();
110    template_vars.insert("AGENT".to_string(), agent_name.to_string());
111    template_vars.insert("AGENT_DISPLAY".to_string(), agent_name.to_string());
112    template_vars.insert("AGENT_SLUG".to_string(), agent_slug.to_string());
113    template_vars.insert("AGENT_ID".to_string(), agent_id.to_string());
114    template_vars.insert("WORKING_DIR".to_string(), working_directory.to_string());
115    // DATE in YYYY-MM-DD format, UTC
116    template_vars.insert("DATE".to_string(), Utc::now().format("%Y-%m-%d").to_string());
117
118    // ----------------------------------------------------------------
119    // Build the startup instructions file: Soul + AgentMD + Memory + Skills index
120    // ----------------------------------------------------------------
121    let mut instructions_parts: Vec<String> = Vec::new();
122
123    if let Some(soul) = content_map.get("soul") {
124        instructions_parts.push(expand_template(soul, &template_vars));
125    }
126    if let Some(agentmd) = content_map.get("agentmd") {
127        if !instructions_parts.is_empty() {
128            instructions_parts.push("\n---\n".to_string());
129        }
130        instructions_parts.push(expand_template(agentmd, &template_vars));
131    }
132    if let Some(memory) = content_map.get("memory") {
133        instructions_parts.push(format!("\n{BUNDLE_SECTION_HEADING}\n"));
134        instructions_parts.push(memory.clone());
135    }
136
137    instructions_parts.push(skills_index_text(skills, provider_id));
138
139    // Resolved per-provider — `None` for an unrecognized provider_id or one
140    // with no confirmed native file skips writing this file
141    // entirely rather than guessing "CLAUDE.md".
142    // Written even when empty: srv injects the Global Memory into it at write
143    // time (`inject_global_bundles`), and with the skills index gone for
144    // Claude (LC3) an agent with no soul, instructions or memory would
145    // otherwise get no startup file, and no Global Memory in it, at all.
146    let instructions_filename = crate::backend::providers::get_provider(provider_id)
147        .and_then(|p| p.startup_instructions_filename);
148    if let Some(filename) = instructions_filename {
149        files.push(AgentConfigFile {
150            filename: filename.to_string(),
151            content: instructions_parts.join(""),
152        });
153    }
154
155    // ----------------------------------------------------------------
156    // Write each skill as either a slash command
157    // (.claude/commands/{trigger}.md, default) or an Agent Skills-format
158    // SKILL.md (.claude/skills/{slug}/SKILL.md, skill_type ==
159    // SKILL_TYPE_AGENT_SKILL) for native Claude Code consumption.
160    // ----------------------------------------------------------------
161    let slugs = crate::backend::skill_slugs::agent_skill_slugs(skills);
162    for (skill, slug) in skills.iter().zip(slugs) {
163        if skill.content.is_empty() {
164            continue;
165        }
166        if let Some(slug) = slug {
167            let content = expand_template(&skill.content, &template_vars);
168            files.push(AgentConfigFile {
169                filename: format!(".claude/skills/{slug}/SKILL.md"),
170                content: render_skill_md(&slug, &skill.description, &content),
171            });
172        } else if let Some(safe_trigger) = sanitize_trigger(&skill.trigger) {
173            let content = expand_template(&skill.content, &template_vars);
174            files.push(AgentConfigFile {
175                filename: format!(".claude/commands/{safe_trigger}.md"),
176                content,
177            });
178        }
179    }
180
181    // ----------------------------------------------------------------
182    // Write .claude/hooks.json — always includes a PreToolUse:Bash
183    // entry pointing at `agentmux-bashwrap hook` so the streaming
184    // wrapper is invoked for every Bash tool call, plus two
185    // PreCompact entries (matcher "manual" / "auto") pointing at
186    // `agentmux-bashwrap precompact` so a live "compaction started"
187    // signal reaches the sidecar. User-provided hooks (from
188    // content_map["hooks"]) are merged on top, with the user's
189    // entries winning on key collisions, EXCEPT that our PreToolUse
190    // and PreCompact entries are always appended to any user array
191    // for those keys so streaming / compaction visibility stay on
192    // regardless. See docs/specs/SPEC_STREAMING_BASH_RUNNER_2026_05_11.md
193    // §5 and docs/specs/SPEC_COMPACTION_DETECTION_AND_HANDLING_2026_07_31.md
194    // §4.2.
195    // ----------------------------------------------------------------
196    let user_hooks = content_map.get("hooks").map(|s| s.as_str());
197    let user_settings = content_map.get("settings").map(|s| s.as_str());
198    if let Some(settings_json) = build_settings_with_hooks(user_settings, user_hooks) {
199        files.push(AgentConfigFile {
200            filename: ".claude/settings.json".to_string(),
201            content: settings_json,
202        });
203    }
204
205    // ----------------------------------------------------------------
206    // Build .mcp.json with auto-injected AgentMux MCP server
207    // ----------------------------------------------------------------
208    // agent_bus_id is not in the function signature; callers that have it
209    // should call build_mcp_config directly and push the result themselves,
210    // or use the variant below.
211    let mcp_content = content_map.get("mcp").map(|s| s.as_str());
212    if let Some(mcp_json) = build_mcp_config(mcp_content, agent_slug, "") {
213        files.push(AgentConfigFile {
214            filename: ".mcp.json".to_string(),
215            content: mcp_json,
216        });
217    }
218
219    files
220}
221
222/// Build `.mcp.json` content with the auto-injected AgentMux MCP server entry.
223///
224/// The AgentMux server is always present as `mcpServers.agentmux`.
225/// If `user_mcp_content` is `Some`, its `mcpServers` entries are merged on top
226/// (user entries win over the auto-injected entry if the key collides).
227/// If the user content is not valid JSON the auto-injected-only config is
228/// returned and no error is propagated (mirrors TS behavior).
229///
230/// Returns `None` only if serialization unexpectedly fails (should never happen).
231///
232/// Mirrors `buildMcpConfig()` in `frontend/app/view/agent/agent-model.ts`.
233pub fn build_mcp_config(
234    user_mcp_content: Option<&str>,
235    agent_slug: &str,
236    agent_bus_id: &str,
237) -> Option<String> {
238    // Auto-injected AgentMux MCP server entry.
239    // agent_slug must be the pre-computed stable role slug (e.g. "korp"),
240    // NOT the display name — callers are responsible for passing the right
241    // value so renamed agents always advertise the same routing ID.
242    let mut env_map = serde_json::Map::new();
243    if !agent_slug.is_empty() {
244        env_map.insert("AGENTMUX_AGENT_ID".to_string(), json!(agent_slug));
245    }
246    if !agent_bus_id.is_empty() {
247        env_map.insert("AGENTMUX_AGENT_BUS_ID".to_string(), json!(agent_bus_id));
248    }
249
250    let agentmux_server = json!({
251        "type": "stdio",
252        "command": "agentmux-mcp",
253        "args": [],
254        "env": Value::Object(env_map),
255    });
256
257    let mut mcp_servers = serde_json::Map::new();
258    mcp_servers.insert("agentmux".to_string(), agentmux_server);
259
260    // Merge user-provided MCP config if present
261    if let Some(raw) = user_mcp_content {
262        match serde_json::from_str::<Value>(raw) {
263            Ok(Value::Object(user_obj)) => {
264                if let Some(Value::Object(user_servers)) = user_obj.get("mcpServers") {
265                    for (k, v) in user_servers {
266                        mcp_servers.insert(k.clone(), v.clone());
267                    }
268                }
269            }
270            Ok(_) => {
271                // User content parsed but isn't an object — skip merge silently
272            }
273            Err(_) => {
274                // Invalid JSON in agent content — keep auto-injected only (mirrors TS behavior)
275                tracing::error!("agent_config: invalid MCP JSON in agent content, using auto-injected only");
276            }
277        }
278    }
279
280    let result = json!({ "mcpServers": Value::Object(mcp_servers) });
281    match serde_json::to_string_pretty(&result) {
282        Ok(s) => Some(s),
283        Err(e) => {
284            tracing::error!("agent_config: failed to serialize MCP config: {e}");
285            None
286        }
287    }
288}
289
290/// Build `.mcp.json` from standalone McpServer ref rows (v1 composable model).
291///
292/// Layering (later wins on key collision, except the reserved `agentmux` key):
293///   1. synthetic `agentmux` entry (always injected)
294///   2. `user_mcp_blob`'s `mcpServers` — the legacy per-agent blob, merged when
295///      the caller passes it (used so a global-only ref set never wipes a
296///      legacy agent's user servers)
297///   3. `servers` ref rows (the agent's own bound servers + globals)
298/// For each ref row the `config` field is a JSON object used as the server
299/// value directly. Falls back to `build_mcp_config` when there are no ref rows
300/// and no blob.
301pub fn build_mcp_config_from_refs(
302    servers: &[crate::backend::storage::McpServer],
303    user_mcp_blob: Option<&str>,
304    agent_slug: &str,
305    agent_bus_id: &str,
306) -> Option<String> {
307    if servers.is_empty() {
308        return build_mcp_config(user_mcp_blob, agent_slug, agent_bus_id);
309    }
310
311    let mut env_map = serde_json::Map::new();
312    if !agent_slug.is_empty() {
313        env_map.insert("AGENTMUX_AGENT_ID".to_string(), json!(agent_slug));
314    }
315    if !agent_bus_id.is_empty() {
316        env_map.insert("AGENTMUX_AGENT_BUS_ID".to_string(), json!(agent_bus_id));
317    }
318    let agentmux_server = json!({
319        "type": "stdio",
320        "command": "agentmux-mcp",
321        "args": [],
322        "env": Value::Object(env_map),
323    });
324
325    let mut mcp_servers = serde_json::Map::new();
326    mcp_servers.insert("agentmux".to_string(), agentmux_server);
327
328    // Layer 2: merge the legacy user blob's servers (skip the reserved key).
329    if let Some(raw) = user_mcp_blob {
330        match serde_json::from_str::<Value>(raw) {
331            Ok(Value::Object(user_obj)) => {
332                if let Some(Value::Object(user_servers)) = user_obj.get("mcpServers") {
333                    for (k, v) in user_servers {
334                        if k == "agentmux" {
335                            continue;
336                        }
337                        mcp_servers.insert(k.clone(), v.clone());
338                    }
339                }
340            }
341            Ok(_) => {}
342            Err(_) => {
343                tracing::error!("agent_config: invalid MCP JSON in legacy blob; skipping blob merge");
344            }
345        }
346    }
347
348    // Layer 3: ref rows (own + global) overlay the blob.
349    crate::backend::mcp_launch::insert_server_rows(&mut mcp_servers, servers);
350
351    let result = json!({ "mcpServers": Value::Object(mcp_servers) });
352    match serde_json::to_string_pretty(&result) {
353        Ok(s) => Some(s),
354        Err(e) => {
355            tracing::error!("agent_config: failed to serialize ref-based MCP config: {e}");
356            None
357        }
358    }
359}
360
361/// Convert standalone Skill records into the AgentSkill shape expected by
362/// `build_config_files`. Used when the v1 ref tables are non-empty.
363pub fn skills_to_agent_skills(
364    skills: &[crate::backend::storage::Skill],
365    agent_id: &str,
366) -> Vec<crate::backend::storage::AgentSkill> {
367    skills
368        .iter()
369        .map(|s| crate::backend::storage::AgentSkill {
370            id: s.id.clone(),
371            agent_id: agent_id.to_string(),
372            name: s.name.clone(),
373            trigger: s.trigger.clone(),
374            skill_type: s.skill_type.clone(),
375            description: s.description.clone(),
376            content: s.content.clone(),
377            created_at: s.created_at,
378        })
379        .collect()
380}
381
382/// Merge a user-supplied `settings.json`-level hook-array (`PreToolUse`
383/// or `PreCompact`) with whatever is already staged in `hooks_obj`
384/// under `key` (our auto-injected entries, possibly already carrying
385/// legacy `content_map["hooks"]`-merged user entries from the earlier
386/// pass in [`build_settings_with_hooks`]). User entries are PREPENDED
387/// so their matchers/gates get first refusal; AgentMux's own entries
388/// always stay last. A non-array value is warned and dropped rather
389/// than silently discarded — same discipline as every other branch in
390/// this function (reagent P1 on PR #813).
391fn prepend_user_hook_array(
392    hooks_obj: &mut serde_json::Map<String, Value>,
393    key: &str,
394    user_value: Value,
395) {
396    match user_value {
397        Value::Array(mut user_arr) => {
398            if let Some(Value::Array(ours)) = hooks_obj.remove(key) {
399                user_arr.extend(ours);
400            }
401            hooks_obj.insert(key.to_string(), Value::Array(user_arr));
402        }
403        _ => {
404            tracing::warn!(
405                "agent_config: user settings.hooks.{key} is not an array; dropped"
406            );
407        }
408    }
409}
410
411/// The `SessionStart` hook entry: one `agentmux-bashwrap sessionstart --part N`
412/// command per memory part, `N` = 1..=`HOOK_PARTS`
413/// (`backend::memory::delivery`). The commands run in parallel, and each
414/// prints its own part (or nothing).
415fn agentmux_sessionstart_entry() -> serde_json::Value {
416    let commands: Vec<serde_json::Value> = (1..=crate::backend::memory::delivery::HOOK_PARTS)
417        .map(|n| json!({ "type": "command", "command": format!("agentmux-bashwrap sessionstart --part {n}") }))
418        .collect();
419    json!({ "hooks": commands })
420}
421
422/// Build `.claude/settings.json` content with the auto-injected
423/// PreToolUse Bash hook and PreCompact hooks (under the `"hooks"`
424/// key). PreToolUse redirects Bash invocations into the streaming
425/// wrapper (`agentmux-bashwrap exec`); PreCompact (two entries,
426/// matcher `"manual"` / `"auto"`) pings the sidecar the instant
427/// compaction starts (`agentmux-bashwrap precompact`) — see
428/// `docs/specs/SPEC_COMPACTION_DETECTION_AND_HANDLING_2026_07_31.md`
429/// §4.2. User-supplied settings.json (from the agent's
430/// `content_map["settings"]`) is parsed and merged at the top level;
431/// user-supplied legacy hooks content (from `content_map["hooks"]`)
432/// is merged into `settings.hooks`.
433///
434/// **File location matters.** Claude Code reads project hooks from
435/// `<project>/.claude/settings.json` under the `"hooks"` key.
436/// A standalone `.claude/hooks.json` is NOT a Claude Code
437/// discovery location — that was the v0.33.804 streaming-bug root
438/// cause: the file was written but Claude never read it, so the
439/// PreToolUse hook never fired and live streaming silently failed.
440///
441/// See `docs/specs/SPEC_STREAMING_BASH_RUNNER_2026_05_11.md` §5
442/// and Claude Code docs: https://code.claude.com/docs/en/hooks.md
443pub fn build_settings_with_hooks(
444    user_settings_content: Option<&str>,
445    user_hooks_content: Option<&str>,
446) -> Option<String> {
447    use serde_json::Value;
448    let agentmux_pretooluse = json!({
449        "matcher": "^(Bash|.*[Bb]ash.*)$",
450        "hooks": [
451            {
452                "type": "command",
453                "command": "agentmux-bashwrap hook"
454            }
455        ]
456    });
457    // `PreCompact` requires an explicit `matcher` (`"manual"` or
458    // `"auto"`) — Claude Code has no confirmed wildcard-all value for
459    // this hook — so two separate entries are registered, each with a
460    // different static `--trigger=` argv baked in so the binary knows
461    // which fired without needing it from stdin (PreCompact's stdin
462    // payload carries no `trigger` field; see `precompact.rs`). See
463    // `docs/specs/SPEC_COMPACTION_DETECTION_AND_HANDLING_2026_07_31.md`
464    // §4.2.
465    let agentmux_precompact_manual = json!({
466        "matcher": "manual",
467        "hooks": [
468            {
469                "type": "command",
470                "command": "agentmux-bashwrap precompact --trigger=manual"
471            }
472        ]
473    });
474    let agentmux_precompact_auto = json!({
475        "matcher": "auto",
476        "hooks": [
477            {
478                "type": "command",
479                "command": "agentmux-bashwrap precompact --trigger=auto"
480            }
481        ]
482    });
483    // `SessionStart`: one command per memory part, so the agent's memory
484    // reaches the model at every new session, `/clear` and compaction
485    // without a visible turn — see
486    // docs/specs/SPEC_GLOBAL_MEMORY_DELIVERY_2026_09_27.md §7 P2. The CLI
487    // delivers about 10,000 characters of `additionalContext` per hook
488    // command, so the memory is split into parts and each command asks the
489    // sidecar for its own. No matcher: the sidecar itself answers "nothing"
490    // for `resume` and `fork` (the conversation is intact, D10).
491    let agentmux_sessionstart = agentmux_sessionstart_entry();
492    let mut hooks_obj = serde_json::Map::new();
493    let mut pretooluse_entries: Vec<Value> = Vec::new();
494    let mut precompact_entries: Vec<Value> = Vec::new();
495    let mut sessionstart_entries: Vec<Value> = Vec::new();
496
497    // Start with user hooks if present + parseable. Parse failures or
498    // non-Object top-levels are logged at WARN so the diagnostic trail
499    // surfaces — silent swallowing made user hooks disappear with no
500    // signal (reagent P2 on PR #809).
501    if let Some(raw) = user_hooks_content {
502        match serde_json::from_str::<Value>(raw) {
503            Ok(Value::Object(user_obj)) => {
504                for (k, v) in user_obj {
505                    if k == "PreToolUse" {
506                        if let Value::Array(arr) = v {
507                            pretooluse_entries.extend(arr);
508                        } else {
509                            tracing::warn!(
510                                "agent_config: user hooks.PreToolUse is not an array; dropped"
511                            );
512                        }
513                    } else if k == "PreCompact" {
514                        if let Value::Array(arr) = v {
515                            precompact_entries.extend(arr);
516                        } else {
517                            tracing::warn!(
518                                "agent_config: user hooks.PreCompact is not an array; dropped"
519                            );
520                        }
521                    } else if k == "SessionStart" {
522                        if let Value::Array(arr) = v {
523                            sessionstart_entries.extend(arr);
524                        } else {
525                            tracing::warn!(
526                                "agent_config: user hooks.SessionStart is not an array; dropped"
527                            );
528                        }
529                    } else {
530                        hooks_obj.insert(k, v);
531                    }
532                }
533            }
534            Ok(other) => {
535                tracing::warn!(
536                    kind = ?other,
537                    "agent_config: user hooks top-level value is not an object; dropped"
538                );
539            }
540            Err(e) => {
541                tracing::warn!(
542                    error = %e,
543                    "agent_config: failed to parse user hooks JSON; dropped"
544                );
545            }
546        }
547    }
548    // Append our entries last so user matchers (deny rules etc.) get a chance
549    // to short-circuit before our rewrite / observation hooks. PreCompact
550    // gets both matcher entries, in matcher order (manual, then auto).
551    pretooluse_entries.push(agentmux_pretooluse);
552    hooks_obj.insert("PreToolUse".to_string(), Value::Array(pretooluse_entries));
553    precompact_entries.push(agentmux_precompact_manual);
554    precompact_entries.push(agentmux_precompact_auto);
555    hooks_obj.insert("PreCompact".to_string(), Value::Array(precompact_entries));
556    sessionstart_entries.push(agentmux_sessionstart);
557    hooks_obj.insert("SessionStart".to_string(), Value::Array(sessionstart_entries));
558
559    // Build the settings.json object: start from user-supplied settings.json
560    // (if any), then overlay our hooks key. User keys other than `hooks`
561    // pass through unchanged.
562    let mut settings_obj = serde_json::Map::new();
563    if let Some(raw) = user_settings_content {
564        match serde_json::from_str::<Value>(raw) {
565            Ok(Value::Object(user_obj)) => {
566                for (k, v) in user_obj {
567                    settings_obj.insert(k, v);
568                }
569            }
570            Ok(_other) => {
571                tracing::warn!(
572                    "agent_config: user settings.json top-level is not an object; dropped"
573                );
574            }
575            Err(e) => {
576                tracing::warn!(
577                    error = %e,
578                    "agent_config: failed to parse user settings.json; dropped"
579                );
580            }
581        }
582    }
583    // Merge: any existing hooks key from user settings is merged with our
584    // additions. For PreToolUse and PreCompact specifically, user matchers
585    // from settings.json are PREPENDED (not dropped) so they short-circuit
586    // before our auto-injected entries — same ordering rule we apply to
587    // legacy content_map["hooks"] entries for these two keys. For other
588    // event types (PostToolUse, Stop, etc.) we keep user's entries
589    // verbatim. Reagent P1 on PR #813 (the `continue` was a silent drop —
590    // caught a real merge bug); PreCompact is deliberately folded into the
591    // same array-merge discipline rather than the generic `or_insert`
592    // below, or a user-supplied PreCompact entry would hit that path and
593    // be silently and permanently dropped the moment PreCompact became
594    // auto-injected too — the exact bug class this file already guards
595    // PreToolUse against. See
596    // `docs/specs/SPEC_COMPACTION_DETECTION_AND_HANDLING_2026_07_31.md`
597    // §4.2. SessionStart joins them for the same reason now that it is
598    // auto-injected too (SPEC_GLOBAL_MEMORY_DELIVERY_2026_09_27.md §7 P2).
599    if let Some(Value::Object(existing_hooks)) = settings_obj.get("hooks").cloned() {
600        for (k, v) in existing_hooks {
601            if k == "PreToolUse" || k == "PreCompact" || k == "SessionStart" {
602                prepend_user_hook_array(&mut hooks_obj, &k, v);
603                continue;
604            }
605            hooks_obj.entry(k).or_insert(v);
606        }
607    }
608    settings_obj.insert("hooks".to_string(), Value::Object(hooks_obj));
609
610    // No `permissions.allow` entry for the wrapper is written. One for `Bash(agentmux-bashwrap *)` used to be:
611    // checked against the pinned CLI, it changes nothing. In prefix mode the CLI's rules see the model's own
612    // command, which that pattern never matches; in rewrite mode the hook's own `allow` decision already
613    // lets the call run, trusted workspace or not. And a project's allow entries are ignored by the CLI until
614    // the workspace is trusted ("Ignoring 1 permissions.allow entry ... this workspace has not been trusted"),
615    // which AgentMux must not grant: a trusted project lets whatever lands in its `.claude` folder take effect.
616    // A user's own `permissions` in their settings are left as they wrote them.
617
618    // No AI attribution in commits or PR descriptions: the repos' checks
619    // (`.github/workflows/no-coauthor-trailers.yml`) reject Co-Authored-By
620    // trailers and "Generated with" lines, and Claude Code adds both by
621    // default. An empty string hides each. An agent's own string `commit` or
622    // `pr` wins; a field it leaves out or sets to a non-string is replaced
623    // with "", and so is a non-object `attribution`, because Claude Code falls
624    // back to its default attribution for any of those.
625    let attribution = settings_obj.entry("attribution").or_insert_with(|| json!({}));
626    if !attribution.is_object() {
627        *attribution = json!({});
628    }
629    if let Value::Object(fields) = attribution {
630        for field in ["commit", "pr"] {
631            let value = fields.entry(field).or_insert_with(|| Value::String(String::new()));
632            if !value.is_string() {
633                *value = Value::String(String::new());
634            }
635        }
636    }
637
638    match serde_json::to_string_pretty(&Value::Object(settings_obj)) {
639        Ok(s) => Some(s),
640        Err(e) => {
641            tracing::error!("agent_config: failed to serialize settings.json: {e}");
642            None
643        }
644    }
645}
646
647/// Replace `{{VARIABLE}}` placeholders in `content` with values from `vars`.
648///
649/// Placeholders that have no corresponding key in `vars` are left unchanged
650/// (the original `{{VARIABLE}}` text is preserved).
651///
652/// Mirrors `expandTemplate()` in `frontend/app/view/agent/agent-model.ts`.
653pub fn expand_template(content: &str, vars: &HashMap<String, String>) -> String {
654    // Hand-rolled replacement to avoid pulling in a regex dependency.
655    // Scans for `{{`, extracts the key name up to `}}`, and substitutes.
656    let mut result = String::with_capacity(content.len());
657    let bytes = content.as_bytes();
658    let len = bytes.len();
659    let mut i = 0;
660
661    while i < len {
662        // Look for '{{'
663        if i + 1 < len && bytes[i] == b'{' && bytes[i + 1] == b'{' {
664            // Find closing '}}'
665            if let Some(rel) = content[i + 2..].find("}}") {
666                let key = &content[i + 2..i + 2 + rel];
667                // Only substitute if key is a simple word (alphanumeric + underscore)
668                if key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
669                    if let Some(val) = vars.get(key) {
670                        result.push_str(val);
671                    } else {
672                        // No match — preserve the original placeholder
673                        result.push_str(&content[i..i + 2 + rel + 2]);
674                    }
675                    i += 2 + rel + 2; // skip past '}}'
676                    continue;
677                }
678            }
679        }
680        // Not a placeholder start — copy character verbatim
681        // Safety: i is always on a valid char boundary because we only advance
682        // by 1 when not inside a placeholder, and UTF-8 single-byte characters
683        // are the only ones we index directly.
684        let ch = content[i..].chars().next().unwrap();
685        result.push(ch);
686        i += ch.len_utf8();
687    }
688
689    result
690}
691
692/// Agent Skills spec caps `description` at 1024 characters.
693const SKILL_DESCRIPTION_MAX_LEN: usize = 1024;
694
695/// Truncate `s` to at most `max_units` UTF-16 code units, on a UTF-8 char
696/// boundary. Mirrors JS `.slice(0, n)` semantics (JS strings are indexed in
697/// UTF-16 code units, so a Rust byte-length cap diverges from the TS mirror
698/// for any non-ASCII text — reagent P2, PR #2322).
699fn truncate_utf16_units(s: &str, max_units: usize) -> String {
700    let mut units = 0usize;
701    for (byte_idx, ch) in s.char_indices() {
702        units += ch.len_utf16();
703        if units > max_units {
704            return s[..byte_idx].to_string();
705        }
706    }
707    s.to_string()
708}
709
710/// Render an Agent Skills-format `SKILL.md`: YAML frontmatter with the two
711/// required fields (`name`, `description` — per the spec's six-field
712/// frontmatter; AgentMux doesn't populate the four optional ones today:
713/// `license`, `compatibility`, `metadata`, `allowed-tools`), followed by the
714/// skill's content as the Markdown body. See https://agentskills.io/specification.
715///
716/// `slug` (not the skill's raw display name) is REQUIRED here — the spec
717/// requires `name` be lowercase/hyphenated and match its parent directory;
718/// callers must pass the same value used to build the `.claude/skills/<slug>/`
719/// path (reagent P1, PR #2322). `description` is validated: the spec requires
720/// a non-empty value (falls back to a placeholder) capped at 1024 **UTF-16
721/// code units** — matching the TS mirror's `.slice(0, 1024)` (JS string
722/// indexing is UTF-16-code-unit based), since the UI permits arbitrary-length
723/// free text with no spec-awareness and non-ASCII descriptions previously
724/// truncated to different byte vs. UTF-16 lengths between the two paths
725/// (reagent P2, PR #2322).
726///
727/// YAML double-quoted scalars use JSON-compatible escaping (YAML 1.2
728/// §7.3.1), so `serde_json::to_string` on a plain string produces a valid,
729/// correctly-escaped YAML value — this avoids hand-rolling YAML escaping or
730/// adding a yaml crate dependency (this workspace has neither today) just
731/// for two scalar fields.
732pub fn render_skill_md(slug: &str, description: &str, body: &str) -> String {
733    let owned_description;
734    let description = if description.trim().is_empty() {
735        "No description provided."
736    } else {
737        owned_description = truncate_utf16_units(description, SKILL_DESCRIPTION_MAX_LEN);
738        owned_description.as_str()
739    };
740    let name_yaml =
741        serde_json::to_string(slug).expect("string serialization is infallible");
742    let description_yaml =
743        serde_json::to_string(description).expect("string serialization is infallible");
744    format!("---\nname: {name_yaml}\ndescription: {description_yaml}\n---\n\n{body}")
745}
746
747/// For each skill, whether `build_config_files` leaves it a file of its own
748/// that Claude Code lists natively: an Agent Skill's `SKILL.md` (slugs are
749/// made unique), or a command with a usable trigger that no later skill's
750/// command overwrites. Triggers are compared case-insensitively, as a
751/// case-insensitive filesystem would. Trigger uniqueness isn't enforced by
752/// the skill store (Codex on #4131). A non-ASCII trigger never counts as
753/// owning its file: a normalization-insensitive filesystem (macOS) folds
754/// Unicode-equivalent names together, and keeping such a skill in the index
755/// costs at most a repeated line, never a lost skill.
756fn skills_with_their_own_file(skills: &[AgentSkill]) -> Vec<bool> {
757    let command_key = |s: &AgentSkill| {
758        (!s.content.is_empty() && s.skill_type != SKILL_TYPE_AGENT_SKILL)
759            .then(|| sanitize_trigger(&s.trigger).filter(|t| t.is_ascii()).map(str::to_lowercase))
760            .flatten()
761    };
762    let mut last_writer: HashMap<String, usize> = HashMap::new();
763    for (i, s) in skills.iter().enumerate() {
764        if let Some(key) = command_key(s) {
765            last_writer.insert(key, i);
766        }
767    }
768    skills
769        .iter()
770        .enumerate()
771        .map(|(i, s)| {
772            // A non-ASCII trigger maps to no key: it never owns a file here,
773            // and doesn't count as overwriting anyone (it may, harmlessly).
774            !s.content.is_empty()
775                && (s.skill_type == SKILL_TYPE_AGENT_SKILL || command_key(s).is_some_and(|k| last_writer.get(&k) == Some(&i)))
776        })
777        .collect()
778}
779
780/// Validate a skill's `trigger` is safe to use as a single path segment in
781/// `.claude/commands/<trigger>.md`. `trigger` is free-form user input with
782/// no format validation anywhere upstream (the skill create/update RPCs and
783/// the frontend form all accept it as-is), so a trigger containing a path
784/// separator or a `..` segment previously let the resulting filename
785/// resolve OUTSIDE the agent's working directory -- both for this write and,
786/// once stale-file cleanup existed, for the corresponding delete (reagent
787/// P1, PR #2322). Rejects (returns `None`) anything containing `/` or `\`,
788/// or that is exactly `.`/`..`; callers skip writing that skill's command
789/// file entirely rather than silently rewriting the trigger into something
790/// the user didn't ask for.
791fn sanitize_trigger(trigger: &str) -> Option<&str> {
792    if trigger.is_empty() || trigger == "." || trigger == ".." {
793        return None;
794    }
795    if trigger.contains('/') || trigger.contains('\\') {
796        return None;
797    }
798    Some(trigger)
799}
800
801/// Derive a slug for an Agent Skill name that is valid per the Agent Skills
802/// `name` grammar: lowercase letters, digits, and hyphens ONLY (no
803/// underscores). `derive_slug` is shared with agent role-slugs, which
804/// deliberately DO permit underscores, so it isn't spec-valid here as-is —
805/// hyphenate underscores (and re-collapse any resulting run of hyphens)
806/// rather than reusing it directly (Codex P1, PR #2322).
807fn skill_name_slug(name: &str) -> String {
808    let base = derive_slug(name).replace('_', "-");
809    let collapsed: String = base
810        .split('-')
811        .filter(|s| !s.is_empty())
812        .collect::<Vec<_>>()
813        .join("-");
814    if collapsed.is_empty() {
815        "skill".to_string()
816    } else {
817        collapsed
818    }
819}
820
821/// Derive a filesystem-safe, COLLISION-FREE, spec-valid slug for an Agent
822/// Skill name within one caller-scoped `used` set. `skill_name_slug` alone
823/// can produce identical output for distinct names that differ only in
824/// punctuation/whitespace (e.g. "Deploy Checklist" and "Deploy!!!Checklist"
825/// both -> "deploy-checklist"), which would otherwise silently overwrite one
826/// skill's `SKILL.md` with another's on disk (reagent P1, PR #2322). Appends
827/// `-2`, `-3`, ... until the slug is unique within `used`, truncating the
828/// base first so the suffixed result never exceeds the spec's 64-character
829/// max (Codex P2, PR #2322 — a 64-char base plus `-2` was previously 66
830/// chars).
831pub(crate) fn unique_skill_slug(name: &str, used: &mut HashSet<String>) -> String {
832    const MAX_LEN: usize = 64;
833    let base = skill_name_slug(name);
834    if used.insert(base.clone()) {
835        return base;
836    }
837    let mut n: u32 = 2;
838    loop {
839        let suffix = format!("-{n}");
840        let max_base_len = MAX_LEN.saturating_sub(suffix.len());
841        let mut truncated_base = base.clone();
842        if truncated_base.len() > max_base_len {
843            let mut end = max_base_len;
844            while end > 0 && !truncated_base.is_char_boundary(end) {
845                end -= 1;
846            }
847            truncated_base.truncate(end);
848        }
849        let candidate = format!("{truncated_base}{suffix}");
850        if used.insert(candidate.clone()) {
851            return candidate;
852        }
853        n += 1;
854    }
855}
856
857// ============================================================
858// Managed skill files manifest (I/O — see module doc comment)
859// ============================================================
860
861/// Hidden manifest (relative to the agent working directory) tracking which
862/// skill-derived paths (`.claude/commands/*.md`, `.claude/skills/*/SKILL.md`)
863/// AgentMux itself wrote on the last materialization, so a subsequent one
864/// can delete ones that are no longer current without touching any
865/// user-authored `.claude/commands`/`.claude/skills` content.
866pub const MANAGED_SKILL_FILES_MANIFEST: &str = ".claude/.agentmux-managed-skill-files.json";
867
868/// Compute the subset of `filenames` that are skill-derived managed paths
869/// (the ones tracked in [`MANAGED_SKILL_FILES_MANIFEST`]) — everything else
870/// (`CLAUDE.md`, `.mcp.json`, `.claude/settings.json`, ...) is always fully
871/// regenerated at a fixed path every launch, so it has no staleness problem
872/// to track.
873pub fn managed_skill_file_paths<'a>(
874    filenames: impl Iterator<Item = &'a str>,
875) -> std::collections::BTreeSet<String> {
876    filenames
877        .filter(|f| f.starts_with(".claude/commands/") || f.starts_with(".claude/skills/"))
878        .map(|f| f.to_string())
879        .collect()
880}
881
882/// Delete skill-derived files a PREVIOUS materialization wrote (per the
883/// on-disk manifest) but that are no longer part of `new_managed_paths` --
884/// e.g. a skill's format switched between `"prompt"`/`"agent-skill"`, or it
885/// was renamed/removed. Without this, the stale file stays on disk and
886/// Claude keeps treating it as active alongside the newly selected format
887/// (reagent P1 + Codex P1/P2, PR #2322).
888///
889/// MUST be called before writing the new files (so a deletion never races a
890/// write to the same path); callers must call
891/// [`write_managed_skill_file_manifest`] after writing to record the new
892/// set for the next materialization. Best-effort: any individual read/parse
893/// failure is treated as "no prior manifest" (nothing to clean up yet)
894/// rather than propagated, since a missing/corrupt manifest must never
895/// block the write that follows.
896///
897/// Every path is resolved through [`crate::backend::base::safe_join_within_base`]
898/// before deletion — defense in depth against a manifest path that somehow
899/// escapes the working directory (e.g. a future bypass of trigger
900/// sanitization upstream, or manual tampering with the manifest file
901/// itself); such a path is skipped with a warning, never followed.
902pub fn cleanup_stale_managed_skill_files(
903    base_path: &std::path::Path,
904    new_managed_paths: &std::collections::BTreeSet<String>,
905) {
906    let manifest_path = base_path.join(MANAGED_SKILL_FILES_MANIFEST);
907    let Ok(raw) = std::fs::read_to_string(&manifest_path) else {
908        return;
909    };
910    let Ok(old_paths) = serde_json::from_str::<Vec<String>>(&raw) else {
911        return;
912    };
913    let Ok(wd) = crate::backend::workdir_fs::Workdir::open(base_path) else {
914        return;
915    };
916    for old in &old_paths {
917        if new_managed_paths.contains(old) {
918            continue;
919        }
920        // Through the workdir: a manifest path outside it, or under a
921        // `.claude` that links out of it, is refused, never deleted.
922        match wd.remove_file(old) {
923            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
924                tracing::warn!(
925                    work_dir = %base_path.display(),
926                    path = %old,
927                    error = %e,
928                    "cleanup_stale_managed_skill_files: refusing to delete a manifest path outside the working directory"
929                );
930                continue;
931            }
932            _ => {}
933        }
934        // Agent Skills format nests under .claude/skills/<slug>/ -- clean up
935        // the now-empty slug directory too (no-op/fails silently if
936        // anything else still lives there, e.g. a future scripts/ dir).
937        if let Some(parent) = std::path::Path::new(old).parent().and_then(|p| p.to_str()).filter(|p| !p.is_empty()) {
938            let _ = wd.remove_dir(parent);
939        }
940    }
941}
942
943/// Record `new_managed_paths` as the manifest for the NEXT call to
944/// [`cleanup_stale_managed_skill_files`]. Best-effort: a write failure is
945/// logged, not propagated — losing this write only means the next
946/// materialization's stale-file cleanup is skipped once, not a correctness
947/// issue for the current one.
948pub fn write_managed_skill_file_manifest(
949    base_path: &std::path::Path,
950    new_managed_paths: &std::collections::BTreeSet<String>,
951) {
952    if let Ok(manifest_json) = serde_json::to_string(new_managed_paths) {
953        let written = crate::backend::workdir_fs::Workdir::open(base_path)
954            .and_then(|wd| wd.write(MANAGED_SKILL_FILES_MANIFEST, manifest_json.as_bytes(), false));
955        if let Err(e) = written {
956            tracing::warn!(
957                work_dir = %base_path.display(),
958                error = %e,
959                "write_managed_skill_file_manifest: failed to write manifest; \
960                 stale file cleanup may be skipped on the next materialization"
961            );
962        }
963    }
964}
965
966// ============================================================
967// CLAUDE.md ownership protection (I/O — see module doc comment)
968// ============================================================
969
970/// First line AgentMux writes on any `CLAUDE.md` it fully owns (freshly
971/// created, or regenerated on every launch since). Its ABSENCE on an
972/// EXISTING file is what marks that file as foreign — predates AgentMux
973/// touching this working directory, or a human replaced AgentMux's file
974/// with their own — and is never overwritten again. See
975/// `docs/specs/SPEC_CLAUDE_MD_OWNERSHIP_PROTECTION_2026_08_22.md`.
976pub const CLAUDE_MD_MANAGED_MARKER: &str = "<!-- agentmux:managed-claude-md -->";
977
978/// AgentMux-owned side file carrying the full Soul+AgentMD+Bundle+Skills
979/// composition when the real `CLAUDE.md` is foreign — always safe to
980/// regenerate in place every launch, unlike `CLAUDE.md` itself in that case.
981pub const AGENTMUX_MEMORY_FILENAME: &str = ".claude/AGENTMUX_MEMORY.md";
982
983/// Heading of the bundle-content section in a generated `CLAUDE.md`.
984///
985/// Persisted format marker, NOT an internal identifier: files already written carry it, and
986/// `editor_handlers::inject_global_bundles` searches for it to prepend the global block ahead of
987/// per-agent content, so the string stays `# Memory`
988/// (SPEC_ARMORY_NAMING_CONSOLIDATION_2026_09_09.md §4 do-not-rename list).
989pub const BUNDLE_SECTION_HEADING: &str = "# Memory";
990
991/// One-time marker recording whether the `@import` line (below) has
992/// already been offered for this working directory. Checked INSTEAD of
993/// re-scanning `CLAUDE.md` content on every launch — without it, a user
994/// who deliberately deletes the import line (opting out of AgentMux
995/// content entirely) would see it silently reappear on their next launch.
996const CLAUDE_MD_OWNERSHIP_MARKER_PATH: &str = ".claude/.agentmux-claude-md-ownership.json";
997
998/// Where an adopted legacy `CLAUDE.md` is kept (`is_legacy_agentmux_claude_md`).
999pub const CLAUDE_MD_PRE_ADOPT_BACKUP: &str = ".claude/CLAUDE.md.pre-adopt";
1000
1001/// A skills-index row exactly as `build_config_files` renders it:
1002/// `- **<name>**`, then optionally ` (trigger: /<trigger>)`, then optionally
1003/// ` — <description>` (Codex on #4131: a bare `- **note` is a person's).
1004fn is_generated_skill_row(line: &str) -> bool {
1005    let Some(rest) = line.strip_prefix("- **") else { return false };
1006    let Some(close) = rest.find("**") else { return false };
1007    if close == 0 {
1008        return false;
1009    }
1010    let mut rest = &rest[close + 2..];
1011    if let Some(after) = rest.strip_prefix(" (trigger: /") {
1012        let Some(end) = after.find(')') else { return false };
1013        if end == 0 {
1014            return false;
1015        }
1016        rest = &after[end + 1..];
1017    }
1018    rest.is_empty() || rest.strip_prefix(" \u{2014} ").is_some_and(|d| !d.is_empty())
1019}
1020
1021
1022/// Whether `content` is exactly what an older AgentMux wrote as `CLAUDE.md`,
1023/// in its order, ignoring blank lines: the `# Available Skills` heading, its
1024/// usage line, at least one skill row (`- **…`; AgentMux wrote the section
1025/// only when there were skills), then optionally the managed import (its
1026/// comment and line, or the line alone). Anything else means a person wrote
1027/// there, and it stays theirs.
1028pub fn is_legacy_agentmux_claude_md(content: &str) -> bool {
1029    let import_line = format!("@{AGENTMUX_MEMORY_FILENAME}");
1030    let mut lines = content.lines().map(str::trim_end).filter(|l| !l.trim().is_empty()).peekable();
1031    if lines.next() != Some("# Available Skills") || lines.next() != Some("Use `/<trigger>` to invoke a skill.") {
1032        return false;
1033    }
1034    let mut skill_rows = 0;
1035    while lines.next_if(|l| is_generated_skill_row(l)).is_some() {
1036        skill_rows += 1;
1037    }
1038    let tail: Vec<&str> = lines.collect();
1039    skill_rows > 0
1040        && (tail.is_empty()
1041            || tail == [import_line.as_str()]
1042            || tail == [CLAUDE_MD_IMPORT_MARKER_COMMENT, import_line.as_str()])
1043}
1044
1045/// Comment wrapping the `@import` line so its origin — and how to remove
1046/// it — is unambiguous to anyone reading a foreign `CLAUDE.md` by hand.
1047const CLAUDE_MD_IMPORT_MARKER_COMMENT: &str =
1048    "<!-- agentmux:managed-import (safe to delete this line to opt out) -->";
1049
1050#[derive(serde::Serialize, serde::Deserialize, Default)]
1051struct ClaudeMdOwnershipMarker {
1052    import_line_offered: bool,
1053}
1054
1055/// Materialize `generated_content` (the composed Soul+AgentMD+Bundle+Skills
1056/// `CLAUDE.md` body `build_config_files` already produced) against whatever
1057/// is already on disk at `base_path/CLAUDE.md`, WITHOUT ever overwriting a
1058/// foreign file's content:
1059///
1060/// - No file yet, or the existing file starts with
1061///   [`CLAUDE_MD_MANAGED_MARKER`]: AgentMux owns it — write `CLAUDE.md`
1062///   directly (marker + `generated_content`), exactly as every call site
1063///   did unconditionally before this function existed. **This is the one
1064///   path that still hard-fails on an I/O error** (propagated via `?`,
1065///   same as every call site's pre-existing behavior) — AgentMux's own
1066///   config file failing to write is a real launch-blocking problem.
1067/// - Existing file present WITHOUT the marker, **or present but
1068///   unreadable** (permission denied, non-UTF-8 content, transient I/O
1069///   error — a `read_to_string` error here must never collapse into "no
1070///   file yet," or an unreadable foreign file gets silently clobbered,
1071///   defeating this whole function's purpose; reagent P0 + codex P1 on
1072///   PR #2747): treated identically as foreign. `CLAUDE.md` itself is
1073///   never written to again. `generated_content` instead goes to
1074///   [`AGENTMUX_MEMORY_FILENAME`] (always safe to regenerate — it's 100%
1075///   AgentMux's own content), pulled in via a single `@import` line
1076///   appended to the real `CLAUDE.md` — offered at most once per working
1077///   directory (see [`CLAUDE_MD_OWNERSHIP_MARKER_PATH`]'s doc comment).
1078///   If the file is unreadable specifically, the `@import` offer is
1079///   skipped for this launch (nothing to safely append to/check
1080///   idempotency against) — retried on the next launch.
1081///
1082/// Everything in the foreign-file branch is best-effort, in the same
1083/// spirit as [`write_managed_skill_file_manifest`] and unlike the
1084/// AgentMux-owned branch above: an I/O failure writing the side file,
1085/// appending the import line, or writing the ownership marker is logged
1086/// and this function still returns `Ok(())` — losing one of these only
1087/// means the import line isn't offered (or the side file isn't
1088/// refreshed) on this one launch, not a correctness issue serious enough
1089/// to fail the whole agent launch (codex P1 on PR #2747: the original
1090/// version used `?` throughout this branch, contradicting this doc
1091/// comment and propagating a side-file write failure into a hard launch
1092/// failure).
1093///
1094/// The `@import` append is a true O_APPEND write
1095/// (`OpenOptions::append(true)`), never a read-modify-write of the whole
1096/// file — if the foreign file changes between this function's read and
1097/// the append (edited by the user or another process mid-launch), a
1098/// full-file rewrite would silently discard that intervening edit; a
1099/// true append can only ever add bytes at whatever the end happens to be
1100/// (codex P2 on PR #2747).
1101///
1102/// Every new path this function writes ([`AGENTMUX_MEMORY_FILENAME`],
1103/// [`CLAUDE_MD_OWNERSHIP_MARKER_PATH`]) is resolved through
1104/// [`crate::backend::base::safe_join_within_base`] and verified against
1105/// [`crate::backend::base::verify_no_symlink_escape`] before any write —
1106/// both constants are fixed, not user-controllable, but `.claude/` itself
1107/// could exist as a symlink escaping the working directory, and without
1108/// this check a write would silently follow it outside the selected
1109/// project (codex P1 on PR #2747, same defense-in-depth the other
1110/// config-file write loops already apply to their own paths).
1111///
1112/// First line AgentMux writes on any non-`CLAUDE.md` startup-instructions
1113/// file it fully owns (freshly created, or one it wrote on a prior
1114/// launch) — mirrors [`CLAUDE_MD_MANAGED_MARKER`]'s role for `CLAUDE.md`,
1115/// generic across filenames since `AGENTS.md`/`GEMINI.md`/`QWEN.md`/pi's
1116/// `APPEND_SYSTEM.md` don't each need distinct marker text. An HTML
1117/// comment renders invisibly in every markdown viewer and every one of
1118/// these providers reads its instructions file as plain text fed into a
1119/// prompt, so a leading comment line is universally harmless regardless
1120/// of provider — no per-provider syntax needed for the marker itself
1121/// (only the `@import`-equivalent side-file fallback CLAUDE.md also gets
1122/// would need that, and this function deliberately doesn't attempt it —
1123/// see the doc comment below).
1124const STARTUP_INSTRUCTIONS_MANAGED_MARKER: &str = "<!-- agentmux:managed-startup-instructions -->";
1125
1126/// Does this file's content say AgentMux wrote it?
1127///
1128/// There are two markers, not one: `CLAUDE.md` carries
1129/// [`CLAUDE_MD_MANAGED_MARKER`] and every other startup-instructions file
1130/// carries [`STARTUP_INSTRUCTIONS_MANAGED_MARKER`], because the two writers
1131/// grew separately. Anything asking "is this ours" has to know both — a check
1132/// against only the first reports every AgentMux-generated `AGENTS.md`,
1133/// `GEMINI.md`, `QWEN.md` and `.pi/APPEND_SYSTEM.md` as foreign, inverting the
1134/// answer for most providers (Codex, PR #3144).
1135///
1136/// Deliberately content-based rather than path-based: the marker is what makes
1137/// the claim, and a file's name says nothing about who wrote it. Phase 3 of
1138/// `SPEC_INSTRUCTION_AND_MEMORY_PORTABILITY_2026_09_09.md` reuses this to
1139/// label tracked instruction files `agentmux` or `foreign`, which is the one
1140/// field that decides whether a file is ours to touch.
1141///
1142/// **The two writers below deliberately do NOT use this**, and that is not an
1143/// oversight. Each asks a narrower question — "did I write this file, in my
1144/// own format, such that I may rewrite it" — and each answer must stay pinned
1145/// to its own marker. A `CLAUDE.md`-marked file is ours, but it is not
1146/// `write_startup_instructions_respecting_existing`'s to rewrite. This helper
1147/// answers the broader question, which is the one a read-only tracker asks.
1148pub fn is_agentmux_managed_instructions(content: &str) -> bool {
1149    content.starts_with(CLAUDE_MD_MANAGED_MARKER)
1150        || content.starts_with(STARTUP_INSTRUCTIONS_MANAGED_MARKER)
1151}
1152
1153/// Write a NON-`CLAUDE.md` startup-instructions file (`AGENTS.md`,
1154/// `GEMINI.md`, `QWEN.md`, `.pi/APPEND_SYSTEM.md`, ...) WITHOUT ever
1155/// overwriting a pre-existing, non-AgentMux-authored file at that path.
1156///
1157/// codex P1, PR #2788: before
1158/// `docs/specs/SPEC_PROVIDER_AWARE_STARTUP_INSTRUCTIONS_2026_08_24.md`,
1159/// every provider's agent got `CLAUDE.md` written regardless of provider —
1160/// wrong, but harmless to a real Codex/Gemini/etc. project, since AgentMux
1161/// was never writing to the filename that project's own real `AGENTS.md`/
1162/// `GEMINI.md` actually lived at. Once `build_config_files` started
1163/// resolving the CORRECT native filename per provider, an unconditional
1164/// write (the plain `std::fs::write` every other config file still uses)
1165/// would silently destroy a pre-existing, user-authored project file the
1166/// moment its name collided with the now-correctly-resolved target — a
1167/// real, novel data-loss regression introduced BY fixing the filename,
1168/// not present before.
1169///
1170/// Mirrors [`write_claude_md_respecting_ownership`]'s OWNED-vs-foreign
1171/// marker check (freely regenerate if AgentMux wrote it, either freshly or
1172/// on a prior launch; never touch it otherwise) — WITHOUT that function's
1173/// `@import`-line side-file fallback offer for the foreign case. That
1174/// fuller mechanism is deliberately Claude-Code-`@import`-syntax-specific;
1175/// whether `AGENTS.md`/`GEMINI.md`/`QWEN.md`/pi's `APPEND_SYSTEM.md`
1176/// support an equivalent include directive their own harness actually
1177/// honors is unverified per-provider research this spec didn't do (§5/§6
1178/// of the spec above). The tradeoff accepted here: if the target file is
1179/// foreign, this agent's Soul/AgentMD/Bundle content is simply not
1180/// delivered via a file for this launch (logged, not silently dropped) —
1181/// a real capability gap, but strictly safer than overwriting a stranger's
1182/// file. Revisit once each provider's own include syntax is confirmed.
1183pub fn write_startup_instructions_respecting_existing(
1184    base_path: &std::path::Path,
1185    filename: &str,
1186    content: &str,
1187) -> std::io::Result<()> {
1188    let path = base_path.join(filename);
1189
1190    // `None` = genuinely no file yet. `Some(Ok(content))` = read fine.
1191    // `Some(Err(_))` = exists but unreadable — MUST be treated the same as
1192    // "foreign," never as "no file yet" (same reasoning as
1193    // write_claude_md_respecting_ownership's own doc comment).
1194    let existing = match std::fs::read_to_string(&path) {
1195        Ok(content) => Some(Ok(content)),
1196        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
1197        Err(e) => Some(Err(e)),
1198    };
1199    let agentmux_owns_it =
1200        matches!(&existing, Some(Ok(content)) if content.starts_with(STARTUP_INSTRUCTIONS_MANAGED_MARKER));
1201
1202    if agentmux_owns_it || existing.is_none() {
1203        let marked_content = format!("{STARTUP_INSTRUCTIONS_MANAGED_MARKER}\n\n{content}");
1204        crate::backend::git_exclude::keep_out_of_git(base_path, &[filename]);
1205        // Through the workdir: never written through a symlink (dangling or
1206        // not), nor under a folder that links out of it (`.pi/` for pi).
1207        // A refusal leaves the file alone, like a foreign one.
1208        let written = crate::backend::workdir_fs::Workdir::open(base_path)
1209            .and_then(|wd| wd.write(filename, marked_content.as_bytes(), false));
1210        return match written {
1211            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
1212                tracing::warn!(path = %path.display(), error = %e, "write_startup_instructions_respecting_existing: not writing");
1213                Ok(())
1214            }
1215            other => other,
1216        };
1217    }
1218
1219    tracing::warn!(
1220        path = %path.display(),
1221        "write_startup_instructions_respecting_existing: pre-existing, \
1222         non-AgentMux-authored file — leaving it untouched; this agent's \
1223         Global Bundle/Soul/AgentMD content is not delivered via this file \
1224         for this launch"
1225    );
1226    Ok(())
1227}
1228
1229/// Names of the `mcpServers` entries AgentMux wrote into a working
1230/// directory's `.mcp.json` on the last materialization — see
1231/// [`write_mcp_json_respecting_user_servers`]. Lives beside
1232/// [`MANAGED_SKILL_FILES_MANIFEST`] for the same reason: it lets the next
1233/// launch tell entries it owns from entries the user put there.
1234pub const MANAGED_MCP_SERVERS_MANIFEST: &str = ".claude/.agentmux-managed-mcp-servers.json";
1235
1236/// Held (exclusively) for the whole read-merge-write in
1237/// [`write_mcp_json_respecting_user_servers`]. See its doc comment.
1238pub const MCP_JSON_WRITE_LOCK: &str = ".claude/.agentmux-mcp-json.lock";
1239
1240/// Write `.mcp.json` into `base_path` without destroying a user's own MCP
1241/// server entries (issue #3680). Shared by `agent.open` and the
1242/// `WriteAgentConfig` "click Launch" path — the two config-materializing call
1243/// sites this module keeps in sync.
1244///
1245/// An agent's `working_directory` may be the user's own project, where a
1246/// `.mcp.json` often already exists (and is often committed). A plain
1247/// `fs::write` replaced it, dropping every server entry the agent definition
1248/// didn't duplicate. Instead:
1249///
1250/// - **Merge.** Every existing `mcpServers` entry is kept, except the ones a
1251///   previous materialization wrote (per [`MANAGED_MCP_SERVERS_MANIFEST`]),
1252///   which are replaced by this launch's set — so a server unbound in
1253///   Connectors still disappears. Other top-level keys in the existing file are
1254///   kept too. On a name clash this launch's entry wins (the `agentmux` entry
1255///   must always be ours).
1256/// - **No manifest yet** (first launch after this change, or a user's file):
1257///   a file that already has an `agentmux` entry was written by AgentMux, so
1258///   all its entries are treated as managed — the old regenerate-every-launch
1259///   behavior, once. A file without one is the user's; all of it is kept.
1260/// - **Unreadable or not a JSON object** → left untouched and logged, never
1261///   overwritten — the same "never overwrite a stranger's file" rule
1262///   [`write_claude_md_respecting_ownership`] follows. Claude Code couldn't
1263///   parse such a file either.
1264/// - **Owner-only.** The file holds the agent's id and channel and no signing
1265///   value (`inject_jekt_signing_keys_into_mcp_json`), and is still written
1266///   `0600` on Unix, via a temp file renamed into place so it is never briefly
1267///   visible with the default mode.
1268/// - **One launch at a time per directory.** `.mcp.json` and its manifest
1269///   must describe the same launch, or a server AgentMux wrote gets mistaken
1270///   for the user's and is never removed. Neither call site serializes by
1271///   directory (`agent_open`'s lock is per agent; `WriteAgentConfig` has
1272///   none), so the whole read-merge-write holds an exclusive lock on
1273///   [`MCP_JSON_WRITE_LOCK`]. A file lock rather than an in-process mutex, so
1274///   two AgentMux instances pointed at one project are serialized too; it is
1275///   released when the handle drops, including on error or panic.
1276///
1277/// No signing value is written here: the agent's MCP server asks srv for its
1278/// keys, and a start removes any an older launch left (`mcp_json_identity`).
1279/// Not addressed here: a user's project not git-ignoring `.mcp.json`.
1280///
1281pub fn write_mcp_json_respecting_user_servers(
1282    base_path: &std::path::Path,
1283    generated_content: &str,
1284) -> std::io::Result<()> {
1285    use serde_json::{Map, Value};
1286
1287    let wd = crate::backend::workdir_fs::Workdir::open(base_path)?;
1288    // Refused (a symlink, or outside the workdir) before anything is read
1289    // or locked: this file carries the agent's signing keys. A refusal
1290    // leaves the link alone and the launch goes on, as for `CLAUDE.md`
1291    // (ReAgent on #4141). So does a refused ownership manifest (a `.claude`
1292    // linking out): without it the next merge would take the user's own
1293    // servers for AgentMux's and drop them (Codex on #4141).
1294    let path = match wd.resolve(MANAGED_MCP_SERVERS_MANIFEST).and_then(|_| wd.resolve(".mcp.json")) {
1295        Ok(path) => path,
1296        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
1297            tracing::warn!(error = %e, "write_mcp_json_respecting_user_servers: not writing .mcp.json");
1298            return Ok(());
1299        }
1300        Err(e) => return Err(e),
1301    };
1302    let generated: Value = serde_json::from_str(generated_content).map_err(|e| {
1303        std::io::Error::new(std::io::ErrorKind::InvalidData, format!("generated .mcp.json is not JSON: {e}"))
1304    })?;
1305    let Some(generated_obj) = generated.as_object() else {
1306        return Err(std::io::Error::new(
1307            std::io::ErrorKind::InvalidData,
1308            "generated .mcp.json is not a JSON object",
1309        ));
1310    };
1311    // Serialize concurrent launches into this directory — see the doc comment.
1312    // The exclusive per-directory write lock; released on drop. A `.claude`
1313    // linking out of the workdir refuses the lock file: the write then goes
1314    // ahead unlocked (it is still atomic) rather than failing the launch.
1315    let _dir_lock = match wd.open_lock_file(MCP_JSON_WRITE_LOCK) {
1316        Ok(file) => {
1317            file.lock()?;
1318            Some(file)
1319        }
1320        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
1321            tracing::warn!(error = %e, "write_mcp_json_respecting_user_servers: writing .mcp.json without the directory lock");
1322            None
1323        }
1324        Err(e) => return Err(e),
1325    };
1326
1327    let ours: Map<String, Value> = generated_obj
1328        .get("mcpServers")
1329        .and_then(Value::as_object)
1330        .cloned()
1331        .unwrap_or_default();
1332
1333    let existing: Option<Map<String, Value>> = match std::fs::read_to_string(&path) {
1334        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
1335        Err(e) => {
1336            tracing::warn!(
1337                path = %path.display(),
1338                error = %e,
1339                "write_mcp_json_respecting_user_servers: existing .mcp.json is unreadable — \
1340                 leaving it untouched; this agent's MCP servers are not written for this launch"
1341            );
1342            return Ok(());
1343        }
1344        Ok(raw) => match serde_json::from_str::<Value>(&raw) {
1345            Ok(Value::Object(obj))
1346                if obj.get("mcpServers").map_or(true, Value::is_object) =>
1347            {
1348                Some(obj)
1349            }
1350            _ => {
1351                tracing::warn!(
1352                    path = %path.display(),
1353                    "write_mcp_json_respecting_user_servers: existing .mcp.json is not a JSON \
1354                     object with an object `mcpServers` — leaving it untouched; this agent's MCP \
1355                     servers are not written for this launch"
1356                );
1357                return Ok(());
1358            }
1359        },
1360    };
1361
1362    let merged = match existing {
1363        None => generated_obj.clone(),
1364        Some(mut obj) => {
1365            let existing_servers = obj
1366                .get("mcpServers")
1367                .and_then(Value::as_object)
1368                .cloned()
1369                .unwrap_or_default();
1370            let previously_managed: std::collections::BTreeSet<String> =
1371                match read_managed_mcp_server_names(base_path) {
1372                    Some(names) => names,
1373                    None if existing_servers.contains_key("agentmux") => {
1374                        existing_servers.keys().cloned().collect()
1375                    }
1376                    None => Default::default(),
1377                };
1378            let mut servers: Map<String, Value> = existing_servers
1379                .into_iter()
1380                .filter(|(name, _)| !previously_managed.contains(name) && !ours.contains_key(name))
1381                .collect();
1382            servers.extend(ours.clone());
1383            for (k, v) in generated_obj {
1384                if k != "mcpServers" {
1385                    obj.insert(k.clone(), v.clone());
1386                }
1387            }
1388            obj.insert("mcpServers".to_string(), Value::Object(servers));
1389            obj
1390        }
1391    };
1392
1393    let body = serde_json::to_string_pretty(&Value::Object(merged))
1394        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
1395    wd.write(".mcp.json", body.as_bytes(), true)?;
1396    write_managed_mcp_server_names(&wd, ours.keys());
1397    Ok(())
1398}
1399
1400fn read_managed_mcp_server_names(base_path: &std::path::Path) -> Option<std::collections::BTreeSet<String>> {
1401    let raw = std::fs::read_to_string(base_path.join(MANAGED_MCP_SERVERS_MANIFEST)).ok()?;
1402    serde_json::from_str(&raw).ok()
1403}
1404
1405/// Best-effort, like [`write_managed_skill_file_manifest`]: losing this write
1406/// only means the next launch falls back to the no-manifest rule once.
1407fn write_managed_mcp_server_names<'a>(
1408    wd: &crate::backend::workdir_fs::Workdir,
1409    names: impl Iterator<Item = &'a String>,
1410) {
1411    let names: std::collections::BTreeSet<&String> = names.collect();
1412    // Atomic (the workdir's write is) for the same reason as the .mcp.json
1413    // write itself: concurrent launches into one directory must not
1414    // interleave into one manifest.
1415    let result = serde_json::to_string(&names)
1416        .map_err(std::io::Error::other)
1417        .and_then(|json| wd.write(MANAGED_MCP_SERVERS_MANIFEST, json.as_bytes(), true));
1418    if let Err(e) = result {
1419        tracing::warn!(
1420            work_dir = %wd.base().display(),
1421            error = %e,
1422            "write_managed_mcp_server_names: failed to write manifest; the next launch \
1423             falls back to treating an agentmux-bearing .mcp.json as fully managed"
1424        );
1425    }
1426}
1427
1428/// Shared by `agent.open` (`server/app_api/agent_open.rs`) and the
1429/// `WriteAgentConfig` "click Launch" path (`server/editor_handlers.rs`) —
1430/// per this module's own doc comment, the two config-materializing call
1431/// sites that must not drift out of sync. See
1432/// `docs/specs/SPEC_CLAUDE_MD_OWNERSHIP_PROTECTION_2026_08_22.md`.
1433pub fn write_claude_md_respecting_ownership(
1434    base_path: &std::path::Path,
1435    generated_content: &str,
1436) -> std::io::Result<()> {
1437    let claude_md_path = base_path.join("CLAUDE.md");
1438
1439    // `None` = genuinely no file yet. `Some(Ok(content))` = read fine.
1440    // `Some(Err(_))` = exists but unreadable — MUST be treated the same
1441    // as "foreign," never as "no file yet" (see doc comment above).
1442    let existing = match std::fs::read_to_string(&claude_md_path) {
1443        Ok(content) => Some(Ok(content)),
1444        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
1445        Err(e) => Some(Err(e)),
1446    };
1447
1448    let mut agentmux_owns_it =
1449        matches!(&existing, Some(Ok(content)) if content.starts_with(CLAUDE_MD_MANAGED_MARKER));
1450
1451    // Every write below goes through the workdir
1452    // (SPEC_WORKDIR_SAFE_WRITES_2026_10_01): a `CLAUDE.md` that is a symlink
1453    // (dangling or not), or a `.claude` linking out of the workspace, is
1454    // refused rather than written through (Codex P1s on #4131).
1455    let wd = crate::backend::workdir_fs::Workdir::open(base_path)?;
1456    let claude_md_writable = wd.resolve("CLAUDE.md").is_ok();
1457
1458    // A CLAUDE.md an older AgentMux wrote, before the managed marker existed:
1459    // nothing in it but the skills index and the managed import line. It was
1460    // taken for the user's and frozen, so its agent kept a stale skills list
1461    // forever. Adopt it, keeping a copy (LC3,
1462    // SPEC_LAUNCH_CONTEXT_WORKSPACE_RULE_AND_STARTUP_FILES_2026_09_30.md §4.4).
1463    if let Some(Ok(content)) = &existing {
1464        if !agentmux_owns_it && claude_md_writable && is_legacy_agentmux_claude_md(content) {
1465            match back_up_legacy_claude_md(&wd, content) {
1466                Ok(()) => {
1467                    tracing::info!(path = %claude_md_path.display(), "CLAUDE.md written by an older AgentMux: adopting it as managed");
1468                    agentmux_owns_it = true;
1469                }
1470                Err(e) => tracing::warn!(
1471                    path = %claude_md_path.display(),
1472                    error = %e,
1473                    "write_claude_md_respecting_ownership: couldn't back up a legacy CLAUDE.md; leaving it as is"
1474                ),
1475            }
1476        }
1477    }
1478
1479    // Nothing is written to a CLAUDE.md the workdir refuses, not even the
1480    // @import append below: every write would land on a link's target.
1481    if !claude_md_writable {
1482        tracing::warn!(path = %claude_md_path.display(), "write_claude_md_respecting_ownership: CLAUDE.md is a symlink or outside the workspace; not writing through it");
1483        return Ok(());
1484    }
1485    // Known, accepted TOCTOU window (codex P2, third review round on
1486    // PR #2747): a foreign CLAUDE.md created between the read above and this
1487    // write would be replaced once. Closing it needs file locking across the
1488    // read-decide-write, which no sibling write here has either.
1489    if agentmux_owns_it || existing.is_none() {
1490        let content = format!("{CLAUDE_MD_MANAGED_MARKER}\n\n{generated_content}");
1491        crate::backend::git_exclude::keep_out_of_git(base_path, &["CLAUDE.md"]);
1492        return wd.write("CLAUDE.md", content.as_bytes(), false);
1493    }
1494
1495    // Foreign (or unreadable) file — CLAUDE.md's own content is never
1496    // written to from here on. Everything from here down is best-effort
1497    // (see doc comment): a failure must not fail the whole agent launch.
1498    crate::backend::git_exclude::keep_out_of_git(base_path, &[AGENTMUX_MEMORY_FILENAME]);
1499    if let Err(e) = wd.write(AGENTMUX_MEMORY_FILENAME, generated_content.as_bytes(), false) {
1500        tracing::warn!(work_dir = %base_path.display(), error = %e, "write_claude_md_respecting_ownership: failed to write AGENTMUX_MEMORY.md this launch");
1501        return Ok(());
1502    }
1503
1504    // Unreadable (not just "no marker") — nothing safe to check
1505    // idempotency against or append to. Skip the @import offer this
1506    // launch; the side file above is still fresh and ready whenever the
1507    // file becomes readable again.
1508    let Some(Ok(existing_content)) = existing else {
1509        tracing::warn!(path = %claude_md_path.display(), "write_claude_md_respecting_ownership: existing CLAUDE.md unreadable; treating as foreign, skipping @import offer this launch");
1510        return Ok(());
1511    };
1512
1513    // Atomic "am I the first to offer this" gate, not a read-then-write
1514    // check: `create_new` reports an existing marker if another concurrent
1515    // call already won this race. Two agents sharing a working directory
1516    // (agent_open.rs's shared-workdir fallback, `~/.agentmux/agents/<slug>`,
1517    // launching concurrently) previously could both read "not yet offered"
1518    // and both append the import line, duplicating it (reagent P2, second
1519    // review round on PR #2747). Only the caller that creates the marker
1520    // proceeds to append; every other caller skips straight past.
1521    let marker_json = serde_json::to_string(&ClaudeMdOwnershipMarker { import_line_offered: true })
1522        .unwrap_or_default();
1523    match wd.create_new(CLAUDE_MD_OWNERSHIP_MARKER_PATH, marker_json.as_bytes()) {
1524        Ok(true) => {
1525            let import_needle = format!("@{AGENTMUX_MEMORY_FILENAME}");
1526            // Idempotent even having won the race: don't duplicate if
1527            // the import somehow already appears (e.g. a user copied it
1528            // in by hand before AgentMux ever ran here).
1529            if !existing_content.contains(&import_needle) {
1530                let import_block = format!("\n\n{CLAUDE_MD_IMPORT_MARKER_COMMENT}\n{import_needle}\n");
1531                // True append (never a read-modify-write of the whole
1532                // file) — an edit racing this function's earlier read is
1533                // preserved (codex P2 on PR #2747).
1534                if let Err(e) = wd.append("CLAUDE.md", import_block.as_bytes()) {
1535                    tracing::warn!(path = %claude_md_path.display(), error = %e, "write_claude_md_respecting_ownership: failed to append the @import line this launch");
1536                    // Roll back the marker we just created — winning the
1537                    // race doesn't mean the offer completed; a marker left
1538                    // behind would record "offered" forever with no retry
1539                    // (reagent P1 + codex, third review round on PR #2747).
1540                    let _ = wd.remove_file(CLAUDE_MD_OWNERSHIP_MARKER_PATH);
1541                }
1542            }
1543        }
1544        Ok(false) => {
1545            // Already offered — by us on a prior launch, or a concurrent
1546            // racer that won just now. Nothing to do.
1547        }
1548        Err(e) => {
1549            tracing::warn!(work_dir = %base_path.display(), error = %e, "write_claude_md_respecting_ownership: failed to create ownership marker");
1550        }
1551    }
1552
1553    Ok(())
1554}
1555
1556/// Copy a legacy `CLAUDE.md` to [`CLAUDE_MD_PRE_ADOPT_BACKUP`] before it is
1557/// adopted. Whole or not at all (a failed write removes its partial copy);
1558/// a copy left by an earlier attempt counts only if it is this file, whole
1559/// (Codex on #4131).
1560fn back_up_legacy_claude_md(wd: &crate::backend::workdir_fs::Workdir, content: &str) -> std::io::Result<()> {
1561    if wd.create_new(CLAUDE_MD_PRE_ADOPT_BACKUP, content.as_bytes())? {
1562        return Ok(());
1563    }
1564    let existing = std::fs::read_to_string(wd.resolve(CLAUDE_MD_PRE_ADOPT_BACKUP)?)?;
1565    if existing == content {
1566        Ok(())
1567    } else {
1568        Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "a different .pre-adopt copy already exists"))
1569    }
1570}
1571
1572/// Best-effort: make sure `agent_slug` has its jekt/LAN signing keys
1573/// (`SPEC_JEKT_TRUST_LAYER_COMPLETION_2026_08_13.md` §2.2,
1574/// `SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md` §2.1), and write the rest of
1575/// what a `.mcp.json` file's `mcpServers.agentmux.env` block carries for
1576/// them. The file holds references, not values: no signing value is written,
1577/// and one an older version wrote is removed. The agent's MCP server asks srv
1578/// for its keys with its own token (`/agentmux/agents/self/keys`).
1579///
1580/// Returns `None` on a parse failure, a missing `mcpServers.agentmux.env` object, or
1581/// if no key could be ensured: callers keep the original content, and this must never block writing the agent's config.
1582/// Shared by `agent.open` (`server/app_api/agent_open.rs`) and the
1583/// `WriteAgentConfig` "click Launch" path (`server/editor_handlers.rs`), per
1584/// this module's own doc comment the two `.mcp.json`-materializing call sites
1585/// that must not drift out of sync.
1586pub fn inject_jekt_signing_keys_into_mcp_json(
1587    content: &str,
1588    mstore: &crate::backend::storage::store::Store,
1589    agent_slug: &str,
1590) -> Option<String> {
1591    let mut mcp_json: Value = serde_json::from_str(content).ok()?;
1592    let env = mcp_json
1593        .pointer_mut("/mcpServers/agentmux/env")
1594        .and_then(|v| v.as_object_mut())?;
1595
1596    let mut ensured = false;
1597    // Keys are stored under the folded name: two rows folding to it (`Victim`
1598    // beside `victim`) get none, and old ones are removed (actor::uid_owns_name).
1599    if mstore.agent_ids_for_slug_folded(agent_slug).is_ok_and(|ids| ids.len() > 1) {
1600        for k in ["AGENTMUX_JEKT_KEY", "AGENTMUX_LAN_KEY", "AGENTMUX_WAN_KEY", "AGENTMUX_HOST_LABEL"] { env.remove(k); }
1601        return serde_json::to_string_pretty(&mcp_json).ok();
1602    }
1603    // Ensured in the store for the agent's fetch; a value is never written.
1604    ensured |= mstore.agent_jekt_key_ensure(agent_slug).is_ok();
1605    if mstore.agent_lan_key_ensure(agent_slug).is_ok() {
1606        // SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md §D5 (Phase B): the
1607        // cross-channel signature binds the sending channel into the signed
1608        // material, so the MCP process must know its channel by the SAME
1609        // string a receiver reads off this instance's shared registry entry.
1610        // Written explicitly rather than relying on the ambient
1611        // `AGENTMUX_CHANNEL` leaking into the agent's shell: a nested
1612        // portable, or an agent launched with a scrubbed env, would
1613        // otherwise sign as "stable" while registered under its real
1614        // channel, and every cross-channel jekt it sent would fail to verify.
1615        env.insert(
1616            "AGENTMUX_CHANNEL".to_string(),
1617            json!(crate::backend::reactive::registry::local_channel_id()),
1618        );
1619        ensured = true;
1620    }
1621    // No signing value at rest: remove what an older version wrote (srv serves the keys).
1622    for stale in crate::backend::mcp_json_identity::SIGNING_SECRETS.into_iter().chain(["AGENTMUX_HOST_LABEL"]) {
1623        env.remove(stale);
1624    }
1625    // Still ensured and published at spawn, so it is in the directory before
1626    // the first WAN jekt. No `wan.db`, nothing minted anywhere else.
1627    if let Some(wan) = mstore.wan_identity() {
1628        match (
1629            wan.instance_ensure(&crate::backend::reactive::registry::local_host_label()),
1630            mstore.channel_wan_key(&wan, agent_slug),
1631        ) {
1632            (Ok(_), Ok(_)) => crate::muxbus::wan_publish::nudge(),
1633            (instance, key) => tracing::warn!(
1634                agent = agent_slug,
1635                instance_error = ?instance.err(),
1636                key_error = ?key.err(),
1637                "wan identity: could not provision this agent's WAN key — its WAN jekts go unsigned"
1638            ),
1639        }
1640    }
1641    if !ensured {
1642        return None;
1643    }
1644    serde_json::to_string_pretty(&mcp_json).ok()
1645}
1646
1647// ============================================================
1648// Tests
1649// ============================================================
1650
1651#[cfg(test)]
1652mod tests {
1653    use super::*;
1654
1655    fn make_skill(name: &str, trigger: &str, description: &str, content: &str) -> AgentSkill {
1656        AgentSkill {
1657            id: format!("skill-{}", trigger),
1658            agent_id: "agent-1".to_string(),
1659            name: name.to_string(),
1660            trigger: trigger.to_string(),
1661            skill_type: "prompt".to_string(),
1662            description: description.to_string(),
1663            content: content.to_string(),
1664            created_at: 0,
1665        }
1666    }
1667
1668    fn make_agent_skill(name: &str, description: &str, content: &str) -> AgentSkill {
1669        AgentSkill {
1670            id: format!("skill-{}", derive_slug(name)),
1671            agent_id: "agent-1".to_string(),
1672            name: name.to_string(),
1673            trigger: String::new(),
1674            skill_type: SKILL_TYPE_AGENT_SKILL.to_string(),
1675            description: description.to_string(),
1676            content: content.to_string(),
1677            created_at: 0,
1678        }
1679    }
1680
1681    #[test]
1682    fn test_sanitize_trigger_rejects_path_traversal() {
1683        // reagent P1, PR #2322: a trigger with a path separator or ".."
1684        // must never be allowed to steer .claude/commands/<trigger>.md
1685        // outside the working directory.
1686        assert_eq!(sanitize_trigger("../../../../.ssh/authorized_keys"), None);
1687        assert_eq!(sanitize_trigger("../evil"), None);
1688        assert_eq!(sanitize_trigger("sub/evil"), None);
1689        assert_eq!(sanitize_trigger("sub\\evil"), None);
1690        assert_eq!(sanitize_trigger(".."), None);
1691        assert_eq!(sanitize_trigger("."), None);
1692        assert_eq!(sanitize_trigger(""), None);
1693        assert_eq!(sanitize_trigger("deploy"), Some("deploy"));
1694    }
1695
1696    #[test]
1697    fn test_build_config_files_skips_prompt_skill_with_traversal_trigger() {
1698        // reagent P1, PR #2322: build_config_files must not materialize a
1699        // command file for a malicious trigger, not even under a sanitized
1700        // name -- skip it outright.
1701        let content_map = HashMap::new();
1702        let skills = vec![make_skill(
1703            "Evil",
1704            "../../../../.ssh/authorized_keys",
1705            "desc",
1706            "malicious content",
1707        )];
1708        let files = build_config_files(&content_map, &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
1709        assert!(
1710            files.iter().all(|f| !f.filename.contains("..")),
1711            "no config file path may contain '..': {:?}",
1712            files.iter().map(|f| &f.filename).collect::<Vec<_>>()
1713        );
1714        assert!(!files.iter().any(|f| f.filename.starts_with(".claude/commands/")));
1715    }
1716
1717    #[test]
1718    fn test_expand_template_basic() {
1719        let mut vars = HashMap::new();
1720        vars.insert("AGENT".to_string(), "Aria".to_string());
1721        vars.insert("DATE".to_string(), "2026-04-10".to_string());
1722
1723        let out = expand_template("Hello {{AGENT}}, today is {{DATE}}.", &vars);
1724        assert_eq!(out, "Hello Aria, today is 2026-04-10.");
1725    }
1726
1727    #[test]
1728    fn test_expand_template_unknown_placeholder_preserved() {
1729        let vars = HashMap::new();
1730        let out = expand_template("Value: {{UNKNOWN}}", &vars);
1731        assert_eq!(out, "Value: {{UNKNOWN}}");
1732    }
1733
1734    #[test]
1735    fn test_expand_template_empty_vars() {
1736        let vars = HashMap::new();
1737        let out = expand_template("No placeholders here.", &vars);
1738        assert_eq!(out, "No placeholders here.");
1739    }
1740
1741    #[test]
1742    fn test_build_mcp_config_no_user_content() {
1743        let result = build_mcp_config(None, "aria", "bus-42").unwrap();
1744        let parsed: Value = serde_json::from_str(&result).unwrap();
1745        let servers = &parsed["mcpServers"];
1746        assert!(servers["agentmux"].is_object());
1747        assert_eq!(servers["agentmux"]["command"], "agentmux-mcp");
1748        assert_eq!(servers["agentmux"]["env"]["AGENTMUX_AGENT_ID"], "aria");
1749        assert_eq!(servers["agentmux"]["env"]["AGENTMUX_AGENT_BUS_ID"], "bus-42");
1750    }
1751
1752    #[test]
1753    fn test_build_mcp_config_merges_user_servers() {
1754        let user_mcp = r#"{"mcpServers": {"mytool": {"type": "stdio", "command": "mytool"}}}"#;
1755        let result = build_mcp_config(Some(user_mcp), "aria", "").unwrap();
1756        let parsed: Value = serde_json::from_str(&result).unwrap();
1757        let servers = &parsed["mcpServers"];
1758        assert!(servers["agentmux"].is_object());
1759        assert!(servers["mytool"].is_object());
1760    }
1761
1762    #[test]
1763    fn test_build_mcp_config_invalid_user_json_uses_auto_injected() {
1764        let result = build_mcp_config(Some("not json {{"), "aria", "").unwrap();
1765        let parsed: Value = serde_json::from_str(&result).unwrap();
1766        assert!(parsed["mcpServers"]["agentmux"].is_object());
1767    }
1768
1769    #[test]
1770    fn test_build_config_files_claude_md_assembled() {
1771        let mut content_map = HashMap::new();
1772        content_map.insert("soul".to_string(), "You are {{AGENT}}.".to_string());
1773        content_map.insert("agentmd".to_string(), "## Instructions\nDo stuff.".to_string());
1774
1775        let files = build_config_files(&content_map, &[], "Aria", "agent-1", "aria", "/tmp/aria", "claude");
1776        let claude_md = files.iter().find(|f| f.filename == "CLAUDE.md").unwrap();
1777        assert!(claude_md.content.contains("You are Aria."));
1778        assert!(claude_md.content.contains("---"));
1779        assert!(claude_md.content.contains("## Instructions"));
1780    }
1781
1782    // docs/specs/SPEC_PROVIDER_AWARE_STARTUP_INSTRUCTIONS_2026_08_24.md §7:
1783    // per-provider filename resolution, pinned against §2's researched
1784    // table so it can't silently drift.
1785    #[test]
1786    fn test_build_config_files_resolves_provider_specific_filename() {
1787        let cases: &[(&str, &str)] = &[
1788            ("claude", "CLAUDE.md"),
1789            ("codex", "AGENTS.md"),
1790            ("gemini", "GEMINI.md"),
1791            ("copilot", "AGENTS.md"),
1792            ("pi", "AGENTS.md"),
1793        ];
1794        for (provider_id, expected_filename) in cases {
1795            let mut content_map = HashMap::new();
1796            content_map.insert("soul".to_string(), "You are Aria.".to_string());
1797            let files = build_config_files(&content_map, &[], "Aria", "agent-1", "aria", "/tmp/aria", provider_id);
1798            let instructions_files: Vec<&str> = files
1799                .iter()
1800                .filter(|f| f.filename == *expected_filename)
1801                .map(|f| f.content.as_str())
1802                .collect();
1803            assert_eq!(
1804                instructions_files.len(),
1805                1,
1806                "provider '{provider_id}' should produce exactly one file named '{expected_filename}': {:?}",
1807                files.iter().map(|f| &f.filename).collect::<Vec<_>>()
1808            );
1809            assert!(instructions_files[0].contains("You are Aria."));
1810        }
1811    }
1812
1813    #[test]
1814    fn test_build_config_files_unrecognized_provider_gets_no_instructions_file() {
1815        // An unrecognized provider_id (typo, not-yet-registered) must not
1816        // silently fall back to "CLAUDE.md" — the no-op path of a provider with no native file.
1817        // .claude/settings.json and .mcp.json are still written (they're
1818        // provider-unconditional today, unaffected by this spec — §5's
1819        // ".claude/-namespaced files... out of scope"), so this checks
1820        // specifically for the absence of any known instructions filename,
1821        // not an empty result.
1822        let mut content_map = HashMap::new();
1823        content_map.insert("soul".to_string(), "You are Aria.".to_string());
1824        let files = build_config_files(&content_map, &[], "Aria", "agent-1", "aria", "/tmp/aria", "not-a-real-provider");
1825        let known_instructions_filenames = [
1826            "CLAUDE.md", "AGENTS.md", "GEMINI.md", "QWEN.md", ".pi/APPEND_SYSTEM.md",
1827        ];
1828        assert!(
1829            !files.iter().any(|f| known_instructions_filenames.contains(&f.filename.as_str())),
1830            "no instructions file should be written for an unrecognized provider: {:?}",
1831            files.iter().map(|f| &f.filename).collect::<Vec<_>>()
1832        );
1833    }
1834
1835    #[test]
1836    fn test_build_config_files_skills_index_and_commands() {
1837        let content_map = HashMap::new();
1838        let skills = vec![
1839            make_skill("Deploy", "deploy", "Deploy the app", "Run: deploy all"),
1840            make_skill("Test", "test", "Run tests", "Run: test suite"),
1841        ];
1842
1843        let files = build_config_files(&content_map, &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
1844
1845        // Claude Code lists skills with a file by itself: no index (LC3).
1846        let claude_md = files.iter().find(|f| f.filename == "CLAUDE.md");
1847        assert!(claude_md.is_none_or(|f| !f.content.contains("Available Skills")), "{claude_md:?}");
1848
1849        // Individual skill command files
1850        assert!(files.iter().any(|f| f.filename == ".claude/commands/deploy.md"));
1851        assert!(files.iter().any(|f| f.filename == ".claude/commands/test.md"));
1852
1853        // Another provider reads only its instructions file: it keeps the index.
1854        let codex = build_config_files(&content_map, &skills, "Aria", "agent-1", "aria", "/tmp/aria", "codex");
1855        let agents_md = codex.iter().find(|f| f.filename == "AGENTS.md").unwrap();
1856        assert!(agents_md.content.contains("Available Skills"));
1857        assert!(agents_md.content.contains("/deploy"));
1858        assert!(agents_md.content.contains("/test"));
1859    }
1860
1861    /// An alias of Claude (`claude-code`) is Claude: no index for skills with
1862    /// files (ReAgent on #4131).
1863    #[test]
1864    fn a_claude_alias_gets_no_index_for_file_backed_skills() {
1865        let skills = vec![make_skill("Deploy", "deploy", "Deploy the app", "Run: deploy all")];
1866        for alias in ["claude-code", "claude_code"] {
1867            if crate::backend::providers::get_provider(alias).is_none() {
1868                continue;
1869            }
1870            let files = build_config_files(&HashMap::new(), &skills, "Aria", "agent-1", "aria", "/tmp/aria", alias);
1871            let md = files.iter().find(|f| f.filename == "CLAUDE.md").unwrap();
1872            assert!(!md.content.contains("Available Skills"), "{alias}");
1873        }
1874    }
1875
1876    /// A skill with no file of its own (no usable trigger) is still indexed
1877    /// for Claude: dropping it from the index would hide it entirely.
1878    #[test]
1879    fn claude_still_indexes_a_skill_that_has_no_file() {
1880        let skills = vec![
1881            make_skill("Deploy", "deploy", "Deploy the app", "Run: deploy all"),
1882            make_skill("Notes", "", "Read the notes", "Look in NOTES.md"),
1883        ];
1884        let files = build_config_files(&HashMap::new(), &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
1885        let claude_md = files.iter().find(|f| f.filename == "CLAUDE.md").unwrap();
1886        assert!(claude_md.content.contains("Available Skills"));
1887        assert!(claude_md.content.contains("**Notes**"));
1888        assert!(!claude_md.content.contains("/deploy"), "Deploy has a command file");
1889    }
1890
1891    /// Skills B6: a provider with no skill loader is told to read the Agent Skill's file, and the line
1892    /// names it, so the skill reaches it as text it can open (the path is the one the file is written to).
1893    #[test]
1894    fn a_non_claude_provider_is_told_where_an_agent_skill_file_is() {
1895        let skills = vec![
1896            make_agent_skill("Deploy Checklist", "Use before a deploy", "1. Test\n2. Ship"),
1897            make_skill("Test", "test", "Run tests", "Run: test suite"),
1898        ];
1899        for provider in ["codex", "gemini"] {
1900            let files = build_config_files(&HashMap::new(), &skills, "Aria", "agent-1", "aria", "/tmp/aria", provider);
1901            let startup = files.iter().find(|f| f.filename != ".claude/skills/deploy-checklist/SKILL.md" && f.content.contains("Available Skills")).unwrap();
1902            assert!(startup.content.contains("Read a skill's file before you act"), "{provider}");
1903            assert!(
1904                startup.content.contains("**Deploy Checklist** \u{2014} Use before a deploy (file: `.claude/skills/deploy-checklist/SKILL.md`)"),
1905                "{provider}: {}",
1906                startup.content
1907            );
1908            // The path it names is a file that is written.
1909            assert!(files.iter().any(|f| f.filename == ".claude/skills/deploy-checklist/SKILL.md"), "{provider}");
1910            // A slash command has no skill file to name.
1911            assert!(startup.content.contains("**Test** (trigger: /test) \u{2014} Run tests\n"), "{provider}");
1912        }
1913    }
1914
1915    /// An Agent Skill with no body writes no file, so its line names none.
1916    #[test]
1917    fn a_skill_with_no_body_names_no_file() {
1918        let skills = vec![make_agent_skill("Empty", "Nothing here", "")];
1919        let text = skills_index_text(&skills, "codex");
1920        assert!(text.contains("**Empty** \u{2014} Nothing here\n"), "{text}");
1921        assert!(!text.contains("(file:"), "{text}");
1922    }
1923
1924    /// Claude's index is unchanged: its sentence is the one `is_legacy_agentmux_claude_md` matches, and a
1925    /// skill it lists (one with no file) names no path.
1926    #[test]
1927    fn claude_keeps_its_index_sentence() {
1928        let skills = vec![make_agent_skill("Empty", "Nothing here", "")];
1929        let text = skills_index_text(&skills, "claude");
1930        assert!(text.starts_with("\n# Available Skills\n\nUse `/<trigger>` to invoke a skill.\n\n"), "{text}");
1931        assert!(!text.contains("(file:"), "{text}");
1932    }
1933
1934    /// An agent whose skills all have files, and nothing else, still gets its
1935    /// instructions file: srv puts the Global Memory in it (LC3 live check —
1936    /// without this the launch wrote no CLAUDE.md at all).
1937    #[test]
1938    fn the_instructions_file_is_written_even_when_empty() {
1939        let skills = vec![make_skill("Deploy", "deploy", "Deploy the app", "Run: deploy all")];
1940        let files = build_config_files(&HashMap::new(), &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
1941        assert!(files.iter().any(|f| f.filename == "CLAUDE.md"), "{:?}", files.iter().map(|f| &f.filename).collect::<Vec<_>>());
1942        let unknown = build_config_files(&HashMap::new(), &skills, "Aria", "agent-1", "aria", "/tmp/aria", "not-a-real-provider");
1943        assert!(!unknown.iter().any(|f| f.filename == "CLAUDE.md" || f.filename == "AGENTS.md"), "an unknown provider has no file");
1944    }
1945
1946    const LEGACY_CLAUDE_MD: &str = "\n# Available Skills\n\nUse `/<trigger>` to invoke a skill.\n\n\
1947        - **Test-Driven Development** (trigger: /tdd) \u{2014} write the test first.\n\
1948        - **Code Review** (trigger: /code-review) \u{2014} review.\n\n\n\
1949        <!-- agentmux:managed-import (safe to delete this line to opt out) -->\n\
1950        @.claude/AGENTMUX_MEMORY.md\n";
1951
1952    /// Two skills on one trigger write one command file, the later winning:
1953    /// the earlier one has no file and stays in the index (Codex on #4131).
1954    #[test]
1955    fn a_skill_whose_command_file_a_later_one_overwrites_stays_indexed() {
1956        let skills = vec![
1957            make_skill("Deploy", "deploy", "Deploy the app", "Run: deploy all"),
1958            make_skill("Deploy Staging", "Deploy", "Deploy staging", "Run: deploy staging"),
1959        ];
1960        let files = build_config_files(&HashMap::new(), &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
1961        let md = files.iter().find(|f| f.filename == "CLAUDE.md").unwrap();
1962        assert!(md.content.contains("**Deploy**"), "the overwritten one is indexed");
1963        assert!(!md.content.contains("**Deploy Staging**"), "the one that owns the file isn't");
1964    }
1965
1966    /// A non-ASCII trigger stays indexed: Unicode-equivalent names can share
1967    /// one file on macOS (Codex on #4131).
1968    #[test]
1969    fn a_skill_with_a_non_ascii_trigger_stays_indexed() {
1970        let skills = vec![make_skill("Caf\u{e9}", "caf\u{e9}", "coffee", "brew")];
1971        let files = build_config_files(&HashMap::new(), &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
1972        let md = files.iter().find(|f| f.filename == "CLAUDE.md").unwrap();
1973        assert!(md.content.contains("Caf\u{e9}"), "{}", md.content);
1974    }
1975
1976    #[test]
1977    fn only_rows_as_agentmux_rendered_them_count() {
1978        assert!(is_generated_skill_row("- **TDD** (trigger: /tdd) \u{2014} write the test first."));
1979        assert!(is_generated_skill_row("- **TDD** (trigger: /tdd)"));
1980        assert!(is_generated_skill_row("- **TDD** \u{2014} write it first"));
1981        assert!(is_generated_skill_row("- **TDD**"));
1982        assert!(!is_generated_skill_row("- **this is my hand-written note"));
1983        assert!(!is_generated_skill_row("- **TDD** and also a note"));
1984        assert!(!is_generated_skill_row("- **TDD** (trigger: /tdd"));
1985        assert!(!is_legacy_agentmux_claude_md(
1986            "# Available Skills\nUse `/<trigger>` to invoke a skill.\n- **this is my hand-written note\n"
1987        ));
1988    }
1989
1990    #[test]
1991    fn recognises_only_exactly_what_an_older_agentmux_wrote() {
1992        assert!(is_legacy_agentmux_claude_md(LEGACY_CLAUDE_MD));
1993        // AgentMux wrote the section only with skills: no rows, not ours (Codex on #4131).
1994        assert!(!is_legacy_agentmux_claude_md("# Available Skills\n\nUse `/<trigger>` to invoke a skill.\n"));
1995        // Its order: skill rows after the import mean someone rearranged it.
1996        assert!(!is_legacy_agentmux_claude_md(
1997            "# Available Skills\nUse `/<trigger>` to invoke a skill.\n@.claude/AGENTMUX_MEMORY.md\n- **A** x\n"
1998        ));
1999        assert!(is_legacy_agentmux_claude_md(
2000            "# Available Skills\nUse `/<trigger>` to invoke a skill.\n- **A** \u{2014} x\n@.claude/AGENTMUX_MEMORY.md\n"
2001        ));
2002        assert!(is_legacy_agentmux_claude_md("# Available Skills\n\nUse `/<trigger>` to invoke a skill.\n\n- **A** \u{2014} x\n"));
2003        assert!(!is_legacy_agentmux_claude_md(&format!("{LEGACY_CLAUDE_MD}\nAlways run the tests.\n")), "a person's line");
2004        assert!(!is_legacy_agentmux_claude_md(&format!("{CLAUDE_MD_MANAGED_MARKER}\n\n# Memory\n")));
2005        assert!(!is_legacy_agentmux_claude_md("# Project\n\n# Available Skills\n"));
2006        assert!(!is_legacy_agentmux_claude_md(""));
2007    }
2008
2009    #[test]
2010    fn a_legacy_claude_md_is_adopted_with_a_backup() {
2011        let dir = tempfile::tempdir().unwrap();
2012        std::fs::write(dir.path().join("CLAUDE.md"), LEGACY_CLAUDE_MD).unwrap();
2013        write_claude_md_respecting_ownership(dir.path(), "# Memory\nfresh\n").unwrap();
2014
2015        let now = std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap();
2016        assert!(now.starts_with(CLAUDE_MD_MANAGED_MARKER), "{now}");
2017        assert!(now.contains("fresh"));
2018        let backup = std::fs::read_to_string(dir.path().join(CLAUDE_MD_PRE_ADOPT_BACKUP)).unwrap();
2019        assert_eq!(backup, LEGACY_CLAUDE_MD);
2020
2021        // Managed from now on; the original copy is never overwritten.
2022        write_claude_md_respecting_ownership(dir.path(), "# Memory\nnewer\n").unwrap();
2023        assert!(std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap().contains("newer"));
2024        assert_eq!(std::fs::read_to_string(dir.path().join(CLAUDE_MD_PRE_ADOPT_BACKUP)).unwrap(), LEGACY_CLAUDE_MD);
2025    }
2026
2027    /// A `.claude` linked outside the workspace gets no backup written
2028    /// through it, and the file isn't adopted (Codex on #4131).
2029    #[test]
2030    fn a_legacy_claude_md_is_not_adopted_through_a_symlinked_claude_dir() {
2031        let dir = tempfile::tempdir().unwrap();
2032        let outside = tempfile::tempdir().unwrap();
2033        #[cfg(unix)]
2034        let made = std::os::unix::fs::symlink(outside.path(), dir.path().join(".claude")).is_ok();
2035        #[cfg(windows)]
2036        let made = std::os::windows::fs::symlink_dir(outside.path(), dir.path().join(".claude")).is_ok();
2037        if !made {
2038            // Windows needs privilege for symlinks; the guard is exercised
2039            // wherever one can be made.
2040            return;
2041        }
2042        std::fs::write(dir.path().join("CLAUDE.md"), LEGACY_CLAUDE_MD).unwrap();
2043        write_claude_md_respecting_ownership(dir.path(), "# Memory\nfresh\n").unwrap();
2044        assert!(!outside.path().join("CLAUDE.md.pre-adopt").exists(), "no backup outside the workspace");
2045        let now = std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap();
2046        assert!(!now.starts_with(CLAUDE_MD_MANAGED_MARKER), "not adopted: {now}");
2047    }
2048
2049    /// A copy left by an earlier attempt that isn't this file whole (a
2050    /// partial write) blocks adoption; the original stays.
2051    #[test]
2052    fn a_mismatched_backup_blocks_adoption() {
2053        let dir = tempfile::tempdir().unwrap();
2054        std::fs::write(dir.path().join("CLAUDE.md"), LEGACY_CLAUDE_MD).unwrap();
2055        std::fs::create_dir_all(dir.path().join(".claude")).unwrap();
2056        std::fs::write(dir.path().join(CLAUDE_MD_PRE_ADOPT_BACKUP), &LEGACY_CLAUDE_MD[..20]).unwrap();
2057        write_claude_md_respecting_ownership(dir.path(), "# Memory\nfresh\n").unwrap();
2058        assert_eq!(std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap(), LEGACY_CLAUDE_MD);
2059
2060        // The same copy, whole: adopted.
2061        std::fs::write(dir.path().join(CLAUDE_MD_PRE_ADOPT_BACKUP), LEGACY_CLAUDE_MD).unwrap();
2062        write_claude_md_respecting_ownership(dir.path(), "# Memory\nfresh\n").unwrap();
2063        assert!(std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap().starts_with(CLAUDE_MD_MANAGED_MARKER));
2064    }
2065
2066    /// A `CLAUDE.md` that is a symlink is never adopted: the managed write
2067    /// would follow it (Codex P1 on #4131).
2068    #[test]
2069    fn a_symlinked_legacy_claude_md_is_not_adopted() {
2070        let dir = tempfile::tempdir().unwrap();
2071        let outside = tempfile::tempdir().unwrap();
2072        let target = outside.path().join("CLAUDE.md");
2073        std::fs::write(&target, LEGACY_CLAUDE_MD).unwrap();
2074        #[cfg(unix)]
2075        let made = std::os::unix::fs::symlink(&target, dir.path().join("CLAUDE.md")).is_ok();
2076        #[cfg(windows)]
2077        let made = std::os::windows::fs::symlink_file(&target, dir.path().join("CLAUDE.md")).is_ok();
2078        if !made {
2079            return; // Windows needs privilege for symlinks.
2080        }
2081        write_claude_md_respecting_ownership(dir.path(), "# Memory\nfresh\n").unwrap();
2082        assert_eq!(std::fs::read_to_string(&target).unwrap(), LEGACY_CLAUDE_MD, "the outside file is untouched");
2083    }
2084
2085    /// A symlinked `CLAUDE.md` whose target already looks managed is not
2086    /// written through either (Codex on #4131).
2087    #[test]
2088    fn a_symlinked_managed_claude_md_is_not_written_through() {
2089        let dir = tempfile::tempdir().unwrap();
2090        let outside = tempfile::tempdir().unwrap();
2091        let target = outside.path().join("CLAUDE.md");
2092        let managed = format!("{CLAUDE_MD_MANAGED_MARKER}\n\n# Memory\nold\n");
2093        std::fs::write(&target, &managed).unwrap();
2094        #[cfg(unix)]
2095        let made = std::os::unix::fs::symlink(&target, dir.path().join("CLAUDE.md")).is_ok();
2096        #[cfg(windows)]
2097        let made = std::os::windows::fs::symlink_file(&target, dir.path().join("CLAUDE.md")).is_ok();
2098        if !made {
2099            return; // Windows needs privilege for symlinks.
2100        }
2101        write_claude_md_respecting_ownership(dir.path(), "# Memory\nfresh\n").unwrap();
2102        assert_eq!(std::fs::read_to_string(&target).unwrap(), managed, "the outside file is untouched");
2103    }
2104
2105    /// A symlinked non-Claude instructions file is never written through,
2106    /// dangling or pointing at an already-managed file (Codex on #4131).
2107    #[test]
2108    fn a_symlinked_startup_instructions_file_is_not_written_through() {
2109        let dir = tempfile::tempdir().unwrap();
2110        let outside = tempfile::tempdir().unwrap();
2111        let target = outside.path().join("AGENTS.md");
2112        let managed = format!("{STARTUP_INSTRUCTIONS_MANAGED_MARKER}\n\nold\n");
2113        std::fs::write(&target, &managed).unwrap();
2114        #[cfg(unix)]
2115        let made = std::os::unix::fs::symlink(&target, dir.path().join("AGENTS.md")).is_ok();
2116        #[cfg(windows)]
2117        let made = std::os::windows::fs::symlink_file(&target, dir.path().join("AGENTS.md")).is_ok();
2118        if !made {
2119            return; // Windows needs privilege for symlinks.
2120        }
2121        write_startup_instructions_respecting_existing(dir.path(), "AGENTS.md", "fresh").unwrap();
2122        assert_eq!(std::fs::read_to_string(&target).unwrap(), managed, "the outside file is untouched");
2123
2124        // Dangling: nothing is created at the link's target either.
2125        let gone = outside.path().join("GEMINI.md");
2126        #[cfg(unix)]
2127        let made = std::os::unix::fs::symlink(&gone, dir.path().join("GEMINI.md")).is_ok();
2128        #[cfg(windows)]
2129        let made = std::os::windows::fs::symlink_file(&gone, dir.path().join("GEMINI.md")).is_ok();
2130        if made {
2131            write_startup_instructions_respecting_existing(dir.path(), "GEMINI.md", "fresh").unwrap();
2132            assert!(!gone.exists(), "no file created through a dangling link");
2133        }
2134    }
2135
2136    #[test]
2137    fn a_plain_startup_instructions_file_is_still_written() {
2138        let dir = tempfile::tempdir().unwrap();
2139        write_startup_instructions_respecting_existing(dir.path(), "AGENTS.md", "fresh").unwrap();
2140        assert!(std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap().contains("fresh"));
2141        write_startup_instructions_respecting_existing(dir.path(), ".pi/APPEND_SYSTEM.md", "pi").unwrap();
2142        assert!(std::fs::read_to_string(dir.path().join(".pi/APPEND_SYSTEM.md")).unwrap().contains("pi"));
2143    }
2144
2145    #[test]
2146    fn a_users_claude_md_is_still_left_alone() {
2147        let dir = tempfile::tempdir().unwrap();
2148        let mine = format!("{LEGACY_CLAUDE_MD}\nAlways run the tests.\n");
2149        std::fs::write(dir.path().join("CLAUDE.md"), &mine).unwrap();
2150        write_claude_md_respecting_ownership(dir.path(), "# Memory\nfresh\n").unwrap();
2151        assert_eq!(std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap(), mine);
2152        assert!(!dir.path().join(CLAUDE_MD_PRE_ADOPT_BACKUP).exists());
2153    }
2154
2155    #[test]
2156    fn test_build_config_files_agent_skill_format_writes_skill_md() {
2157        let content_map = HashMap::new();
2158        let skills = vec![make_agent_skill(
2159            "Deploy Checklist",
2160            "Runs the pre-deploy checklist",
2161            "1. Run tests\n2. Check migrations\n3. Deploy",
2162        )];
2163
2164        let files = build_config_files(&content_map, &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
2165
2166        // Materializes to .claude/skills/<slug>/SKILL.md, not .claude/commands/
2167        let skill_file = files
2168            .iter()
2169            .find(|f| f.filename == ".claude/skills/deploy-checklist/SKILL.md")
2170            .expect("expected .claude/skills/deploy-checklist/SKILL.md");
2171        assert!(!files.iter().any(|f| f.filename.starts_with(".claude/commands/")));
2172
2173        // YAML frontmatter with the two required Agent Skills fields.
2174        // `name` is the slug (matching its parent directory per the Agent
2175        // Skills spec), NOT the raw display name -- reagent P1 on #2322.
2176        assert!(skill_file.content.starts_with("---\n"));
2177        assert!(skill_file.content.contains("name: \"deploy-checklist\""));
2178        assert!(skill_file
2179            .content
2180            .contains("description: \"Runs the pre-deploy checklist\""));
2181        assert!(skill_file.content.contains("---\n\n1. Run tests"));
2182
2183        // Claude Code lists a SKILL.md itself, so CLAUDE.md doesn't index it (LC3).
2184        let claude_md = files.iter().find(|f| f.filename == "CLAUDE.md");
2185        assert!(claude_md.is_none_or(|f| !f.content.contains("Deploy Checklist")), "{claude_md:?}");
2186    }
2187
2188    #[test]
2189    fn test_build_config_files_agent_skill_format_escapes_yaml_special_chars() {
2190        // Names/descriptions with colons, quotes, or newlines must not
2191        // corrupt the YAML frontmatter -- serde_json's escaping (valid YAML
2192        // double-quoted-scalar syntax per YAML 1.2 §7.3.1) is what protects
2193        // this; regression-test it explicitly rather than trusting the
2194        // dependency silently.
2195        let content_map = HashMap::new();
2196        let skills = vec![make_agent_skill(
2197            "Weird: \"Name\"",
2198            "Has a colon: and \"quotes\"",
2199            "body",
2200        )];
2201
2202        let files = build_config_files(&content_map, &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
2203        let skill_file = files
2204            .iter()
2205            .find(|f| f.filename.starts_with(".claude/skills/") && f.filename.ends_with("SKILL.md"))
2206            .expect("expected a SKILL.md file");
2207
2208        // Frontmatter must parse as exactly 3 lines before the closing ---
2209        // (name, description, and nothing else leaking onto a new line).
2210        let end = skill_file.content.find("\n---\n\n").expect("closing frontmatter delimiter");
2211        let frontmatter = &skill_file.content[4..end]; // skip leading "---\n"
2212        let lines: Vec<&str> = frontmatter.lines().collect();
2213        assert_eq!(lines.len(), 2, "frontmatter should be exactly name + description lines, got: {lines:?}");
2214    }
2215
2216    #[test]
2217    fn test_build_config_files_agent_skill_format_name_is_the_slug_not_display_name() {
2218        // reagent P1 (PR #2322): the Agent Skills spec requires `name` be
2219        // lowercase/hyphenated and match its parent directory -- the raw
2220        // display name (e.g. "Deploy Checklist") is spec-invalid.
2221        let content_map = HashMap::new();
2222        let skills = vec![make_agent_skill("Deploy Checklist", "desc", "body")];
2223        let files = build_config_files(&content_map, &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
2224        let skill_file = files.iter().find(|f| f.filename.ends_with("SKILL.md")).unwrap();
2225        assert!(skill_file.content.contains("name: \"deploy-checklist\""));
2226        assert!(!skill_file.content.contains("name: \"Deploy Checklist\""));
2227    }
2228
2229    #[test]
2230    fn test_build_config_files_agent_skill_format_empty_description_gets_fallback() {
2231        // reagent P1 (PR #2322): the Agent Skills spec requires a non-empty
2232        // description; the UI permits creating a skill with none.
2233        let content_map = HashMap::new();
2234        let skills = vec![make_agent_skill("Deploy Checklist", "", "body")];
2235        let files = build_config_files(&content_map, &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
2236        let skill_file = files.iter().find(|f| f.filename.ends_with("SKILL.md")).unwrap();
2237        assert!(!skill_file.content.contains("description: \"\""), "empty description must not reach the spec-invalid empty string: {}", skill_file.content);
2238        assert!(skill_file.content.contains("description: \"No description provided.\""));
2239    }
2240
2241    #[test]
2242    fn test_build_config_files_agent_skill_format_truncates_long_description() {
2243        // reagent P1 (PR #2322): the Agent Skills spec caps description at
2244        // 1024 characters.
2245        let content_map = HashMap::new();
2246        let long_description = "x".repeat(2000);
2247        let skills = vec![make_agent_skill("Deploy Checklist", &long_description, "body")];
2248        let files = build_config_files(&content_map, &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
2249        let skill_file = files.iter().find(|f| f.filename.ends_with("SKILL.md")).unwrap();
2250        // Extract the description value between the quotes on its line.
2251        let desc_line = skill_file.content.lines().find(|l| l.starts_with("description: ")).unwrap();
2252        let quoted = desc_line.trim_start_matches("description: ");
2253        let inner_len = quoted.len() - 2; // strip surrounding quotes
2254        assert!(inner_len <= 1024, "description exceeds spec max of 1024 chars: {inner_len}");
2255    }
2256
2257    #[test]
2258    fn test_build_config_files_agent_skill_format_dedupes_colliding_slugs() {
2259        // reagent P1 (PR #2322): two distinct skill names that derive_slug
2260        // collapses to the same slug must NOT silently overwrite each
2261        // other's SKILL.md file.
2262        let content_map = HashMap::new();
2263        let skills = vec![
2264            make_agent_skill("Deploy Checklist", "First skill", "body one"),
2265            make_agent_skill("Deploy!!!Checklist", "Second skill", "body two"),
2266            make_agent_skill("Deploy   Checklist", "Third skill", "body three"),
2267        ];
2268
2269        let files = build_config_files(&content_map, &skills, "Aria", "agent-1", "aria", "/tmp/aria", "claude");
2270
2271        let skill_files: Vec<&AgentConfigFile> = files
2272            .iter()
2273            .filter(|f| f.filename.starts_with(".claude/skills/") && f.filename.ends_with("SKILL.md"))
2274            .collect();
2275        assert_eq!(skill_files.len(), 3, "all three skills must materialize to distinct files");
2276
2277        let filenames: HashSet<&str> = skill_files.iter().map(|f| f.filename.as_str()).collect();
2278        assert_eq!(filenames.len(), 3, "filenames must be unique: {filenames:?}");
2279        assert!(filenames.contains(".claude/skills/deploy-checklist/SKILL.md"));
2280        assert!(filenames.contains(".claude/skills/deploy-checklist-2/SKILL.md"));
2281        assert!(filenames.contains(".claude/skills/deploy-checklist-3/SKILL.md"));
2282
2283        // Each file's content must correspond to the correct skill (not just
2284        // present -- verify no cross-contamination from the dedup logic).
2285        let first = skill_files.iter().find(|f| f.filename.ends_with("deploy-checklist/SKILL.md")).unwrap();
2286        assert!(first.content.contains("body one"));
2287        let second = skill_files.iter().find(|f| f.filename.ends_with("deploy-checklist-2/SKILL.md")).unwrap();
2288        assert!(second.content.contains("body two"));
2289        let third = skill_files.iter().find(|f| f.filename.ends_with("deploy-checklist-3/SKILL.md")).unwrap();
2290        assert!(third.content.contains("body three"));
2291    }
2292
2293    #[test]
2294    fn test_unique_skill_slug_replaces_underscores_with_hyphens() {
2295        // Codex P1, PR #2322: derive_slug (shared with agent role-slugs) keeps
2296        // underscores, which is spec-invalid for an Agent Skills `name`.
2297        let mut used = HashSet::new();
2298        assert_eq!(unique_skill_slug("code_review", &mut used), "code-review");
2299    }
2300
2301    #[test]
2302    fn test_unique_skill_slug_suffixed_slug_stays_within_64_chars() {
2303        // Codex P2, PR #2322: a 64-char base plus "-2" was previously 66 chars.
2304        let mut used = HashSet::new();
2305        let long = "a".repeat(100);
2306        let first = unique_skill_slug(&long, &mut used);
2307        assert_eq!(first.len(), 64);
2308        let second = unique_skill_slug(&long, &mut used);
2309        assert!(second.len() <= 64, "suffixed slug exceeds 64 chars: {second} ({})", second.len());
2310        assert!(second.ends_with("-2"));
2311    }
2312
2313    #[test]
2314    fn test_render_skill_md_truncates_by_utf16_units_matching_ts_slice() {
2315        // reagent P2, PR #2322: Rust previously capped by byte length while
2316        // the TS mirror caps by UTF-16 code units (`.slice(0, 1024)`), so
2317        // non-ASCII descriptions truncated to different lengths between the
2318        // two paths. A 3-byte-per-char UTF-8 string (each char = 1 UTF-16
2319        // unit) makes the byte-vs-unit divergence obvious: byte-based
2320        // truncation would cut this off around char 341, not 1024.
2321        let description: String = "\u{4e2d}".repeat(2000); // "中" x2000 (3 bytes each, 1 UTF-16 unit each)
2322        let md = render_skill_md("slug", &description, "body");
2323        let desc_line = md.lines().find(|l| l.starts_with("description: ")).unwrap();
2324        let quoted = desc_line.trim_start_matches("description: ");
2325        let inner = &quoted[1..quoted.len() - 1]; // strip surrounding quotes
2326        let utf16_len: usize = inner.chars().map(|c| c.len_utf16()).sum();
2327        assert_eq!(utf16_len, 1024, "expected exactly 1024 UTF-16 units, got {utf16_len}");
2328    }
2329
2330    #[test]
2331    fn test_build_config_files_settings_merges_user_hooks() {
2332        // PR #813 moved hooks from `.claude/hooks.json` (a Claude Code
2333        // dead-letter path) to `.claude/settings.json` under the
2334        // `"hooks"` key. This test exercises the merge path: user
2335        // PreToolUse entries must be PREPENDED (not silently
2336        // dropped) to the auto-injected bashwrap entry so streaming
2337        // stays on while user-supplied gates fire first.
2338        let mut content_map = HashMap::new();
2339        content_map.insert(
2340            "hooks".to_string(),
2341            r#"{"PreToolUse":[{"matcher":"Read","hooks":[{"type":"command","command":"my-audit"}]}]}"#
2342                .to_string(),
2343        );
2344        let files = build_config_files(&content_map, &[], "Aria", "agent-1", "aria", "/tmp/aria", "claude");
2345        let settings = files
2346            .iter()
2347            .find(|f| f.filename == ".claude/settings.json")
2348            .expect("settings.json emitted");
2349        let parsed: Value = serde_json::from_str(&settings.content).unwrap();
2350        let pre_tool_use = parsed["hooks"]["PreToolUse"]
2351            .as_array()
2352            .expect("PreToolUse is an array");
2353        // User's "Read" matcher prepended first, then our Bash matcher.
2354        assert!(
2355            pre_tool_use
2356                .iter()
2357                .any(|e| e["matcher"].as_str() == Some("Read")),
2358            "user-supplied PreToolUse:Read must survive the merge"
2359        );
2360        assert!(
2361            pre_tool_use
2362                .iter()
2363                .any(|e| e["matcher"].as_str().unwrap_or("").contains("Bash")),
2364            "auto-injected PreToolUse:Bash must still be present"
2365        );
2366    }
2367
2368    #[test]
2369    fn test_build_config_files_settings_merges_user_precompact_hooks() {
2370        // SPEC_COMPACTION_DETECTION_AND_HANDLING_2026_07_31.md §4.2:
2371        // PreCompact becomes auto-injected (two entries, matcher
2372        // "manual"/"auto") the same way PreToolUse already is. This is
2373        // the exact regression class PR #813's PreToolUse fix guards
2374        // against — a user-supplied PreCompact entry (from the legacy
2375        // content_map["hooks"] path) must survive the merge, not get
2376        // silently and permanently dropped by the generic
2377        // `hooks_obj.entry(k).or_insert(v)` path once PreCompact stops
2378        // being "just another key".
2379        let mut content_map = HashMap::new();
2380        content_map.insert(
2381            "hooks".to_string(),
2382            r#"{"PreCompact":[{"matcher":"manual","hooks":[{"type":"command","command":"my-precompact-audit"}]}]}"#
2383                .to_string(),
2384        );
2385        let files = build_config_files(&content_map, &[], "Aria", "agent-1", "aria", "/tmp/aria", "claude");
2386        let settings = files
2387            .iter()
2388            .find(|f| f.filename == ".claude/settings.json")
2389            .expect("settings.json emitted");
2390        let parsed: Value = serde_json::from_str(&settings.content).unwrap();
2391        let pre_compact = parsed["hooks"]["PreCompact"]
2392            .as_array()
2393            .expect("PreCompact is an array");
2394        assert_eq!(
2395            pre_compact.len(),
2396            3,
2397            "expected user entry + 2 auto-injected (manual, auto) entries, got {pre_compact:?}"
2398        );
2399        assert!(
2400            pre_compact
2401                .iter()
2402                .any(|e| e["hooks"][0]["command"].as_str() == Some("my-precompact-audit")),
2403            "user-supplied PreCompact entry must survive the merge"
2404        );
2405        assert!(
2406            pre_compact.iter().any(|e| e["hooks"][0]["command"].as_str()
2407                == Some("agentmux-bashwrap precompact --trigger=manual")),
2408            "auto-injected PreCompact manual entry must still be present"
2409        );
2410        assert!(
2411            pre_compact.iter().any(|e| e["hooks"][0]["command"].as_str()
2412                == Some("agentmux-bashwrap precompact --trigger=auto")),
2413            "auto-injected PreCompact auto entry must still be present"
2414        );
2415    }
2416
2417    #[test]
2418    fn test_build_config_files_settings_json_merges_user_precompact_hooks() {
2419        // Same regression as above, but exercising the OTHER merge
2420        // branch: a user-supplied PreCompact entry living in
2421        // settings.json's own `"hooks"` key (content_map["settings"])
2422        // rather than the legacy content_map["hooks"] path. Both
2423        // branches in `build_settings_with_hooks` needed the fix.
2424        let mut content_map = HashMap::new();
2425        content_map.insert(
2426            "settings".to_string(),
2427            r#"{"hooks":{"PreCompact":[{"matcher":"auto","hooks":[{"type":"command","command":"my-settings-precompact"}]}]}}"#
2428                .to_string(),
2429        );
2430        let files = build_config_files(&content_map, &[], "Aria", "agent-1", "aria", "/tmp/aria", "claude");
2431        let settings = files
2432            .iter()
2433            .find(|f| f.filename == ".claude/settings.json")
2434            .expect("settings.json emitted");
2435        let parsed: Value = serde_json::from_str(&settings.content).unwrap();
2436        let pre_compact = parsed["hooks"]["PreCompact"]
2437            .as_array()
2438            .expect("PreCompact is an array");
2439        assert!(
2440            pre_compact
2441                .iter()
2442                .any(|e| e["hooks"][0]["command"].as_str() == Some("my-settings-precompact")),
2443            "user-supplied settings.json PreCompact entry must survive the merge"
2444        );
2445        assert!(
2446            pre_compact.iter().any(|e| e["hooks"][0]["command"].as_str()
2447                == Some("agentmux-bashwrap precompact --trigger=manual")),
2448            "auto-injected PreCompact manual entry must still be present"
2449        );
2450        assert!(
2451            pre_compact.iter().any(|e| e["hooks"][0]["command"].as_str()
2452                == Some("agentmux-bashwrap precompact --trigger=auto")),
2453            "auto-injected PreCompact auto entry must still be present"
2454        );
2455        // Settings-level user entries PREPEND before AgentMux's own, per
2456        // this merge path's ordering rule (mirrors PreToolUse).
2457        assert_eq!(
2458            pre_compact[0]["hooks"][0]["command"].as_str(),
2459            Some("my-settings-precompact"),
2460            "user PreCompact entries must prepend before AgentMux's own"
2461        );
2462    }
2463
2464    /// SPEC_GLOBAL_MEMORY_DELIVERY_2026_09_27.md §7 P2: one SessionStart
2465    /// entry, a command per memory part, no matcher; a user's own
2466    /// SessionStart hooks survive both merge paths, before ours.
2467    #[test]
2468    fn test_build_settings_injects_sessionstart_memory_parts_and_keeps_user_hooks() {
2469        let ours: Vec<String> = (1..=crate::backend::memory::delivery::HOOK_PARTS)
2470            .map(|n| format!("agentmux-bashwrap sessionstart --part {n}"))
2471            .collect();
2472        let commands = |entry: &Value| -> Vec<String> {
2473            entry["hooks"].as_array().unwrap().iter().map(|h| h["command"].as_str().unwrap().to_string()).collect()
2474        };
2475        let session_start = |settings: Option<&str>, hooks: Option<&str>| -> Vec<Value> {
2476            let parsed: Value = serde_json::from_str(&build_settings_with_hooks(settings, hooks).unwrap()).unwrap();
2477            parsed["hooks"]["SessionStart"].as_array().unwrap().clone()
2478        };
2479
2480        let plain = session_start(None, None);
2481        assert_eq!(plain.len(), 1);
2482        assert!(plain[0].get("matcher").is_none(), "the sidecar answers per source; no matcher");
2483        assert_eq!(commands(&plain[0]), ours);
2484
2485        let legacy = session_start(None, Some(r#"{"SessionStart":[{"hooks":[{"type":"command","command":"my-start"}]}]}"#));
2486        assert_eq!(legacy.len(), 2);
2487        assert_eq!(commands(&legacy[0]), vec!["my-start"]);
2488        assert_eq!(commands(&legacy[1]), ours);
2489
2490        let settings = session_start(
2491            Some(r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"my-settings-start"}]}]}}"#),
2492            None,
2493        );
2494        assert_eq!(settings.len(), 2, "a settings.json SessionStart hook is kept, not dropped");
2495        assert_eq!(commands(&settings[0]), vec!["my-settings-start"]);
2496        assert_eq!(commands(&settings[1]), ours);
2497    }
2498
2499    /// Claude Code adds a Co-Authored-By trailer and a "Generated with" line
2500    /// unless `attribution` is empty; the repos' checks reject both.
2501    #[test]
2502    fn test_build_settings_hides_attribution_unless_the_agent_sets_it() {
2503        let attribution = |settings: Option<&str>| -> Value {
2504            let parsed: Value = serde_json::from_str(&build_settings_with_hooks(settings, None).unwrap()).unwrap();
2505            parsed["attribution"].clone()
2506        };
2507        assert_eq!(attribution(None), json!({ "commit": "", "pr": "" }));
2508        assert_eq!(attribution(Some(r#"{"model":"opus"}"#)), json!({ "commit": "", "pr": "" }));
2509        assert_eq!(
2510            attribution(Some(r#"{"attribution":{"commit":"Agent: Aria","pr":"Agent: Aria"}}"#)),
2511            json!({ "commit": "Agent: Aria", "pr": "Agent: Aria" }),
2512            "an agent's own attribution wins"
2513        );
2514        assert_eq!(
2515            attribution(Some(r#"{"attribution":{"commit":"Agent: Aria"}}"#)),
2516            json!({ "commit": "Agent: Aria", "pr": "" }),
2517            "a field the agent leaves out is still hidden, not Claude Code's default"
2518        );
2519        for malformed in [r#"null"#, r#"[]"#, r#""text""#, r#"{"commit":null,"pr":7}"#] {
2520            assert_eq!(
2521                attribution(Some(&format!(r#"{{"attribution":{malformed}}}"#))),
2522                json!({ "commit": "", "pr": "" }),
2523                "a malformed attribution ({malformed}) is replaced, not passed through"
2524            );
2525        }
2526        assert_eq!(
2527            attribution(Some(r#"{"attribution":{"commit":"Agent: Aria","pr":false}}"#)),
2528            json!({ "commit": "Agent: Aria", "pr": "" }),
2529        );
2530    }
2531
2532    #[test]
2533    fn test_build_config_files_mcp_written() {
2534        let content_map = HashMap::new();
2535        let files = build_config_files(&content_map, &[], "Aria", "agent-1", "aria", "/tmp/aria", "claude");
2536        let mcp = files.iter().find(|f| f.filename == ".mcp.json").unwrap();
2537        let parsed: Value = serde_json::from_str(&mcp.content).unwrap();
2538        assert!(parsed["mcpServers"]["agentmux"].is_object());
2539    }
2540
2541    #[test]
2542    fn test_build_config_files_expands_agent_slug_and_working_dir() {
2543        // REPORT_REPO_HEALTH_AUDIT_2026_07_20.md §1.3: AGENT_SLUG/WORKING_DIR
2544        // were missing from build_config_files's template vars, so any soul/agentmd content
2545        // using {{AGENT_SLUG}} or {{WORKING_DIR}} was left unexpanded.
2546        let mut content_map = HashMap::new();
2547        content_map.insert(
2548            "soul".to_string(),
2549            "I am {{AGENT_SLUG}}, working in {{WORKING_DIR}}.".to_string(),
2550        );
2551        let files = build_config_files(
2552            &content_map,
2553            &[],
2554            "Aria",
2555            "agent-1",
2556            "aria",
2557            "/home/user/my-project",
2558            "claude",
2559        );
2560        let claude_md = files.iter().find(|f| f.filename == "CLAUDE.md").unwrap();
2561        assert!(claude_md.content.contains("I am aria, working in /home/user/my-project."));
2562    }
2563
2564    // docs/specs/REPORT_JEKT_SIGNING_KEY_INJECTION_GAP_2026_08_16.md: this
2565    // function exists specifically so `agent.open` and `WriteAgentConfig`
2566    // (the actual "click Launch" path) can't drift out of sync on jekt/LAN
2567    // key injection the way they did before this fix.
2568    #[test]
2569    fn inject_jekt_signing_keys_into_mcp_json_ensures_the_keys_and_writes_no_value_into_the_env_block() {
2570        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
2571        let (_wan_dir, wan) = crate::backend::storage::wan_identity::attach_temp_wan_identity(&store);
2572        let content = serde_json::to_string(&json!({
2573            "mcpServers": { "agentmux": { "type": "stdio", "command": "agentmux-mcp", "env": { "AGENTMUX_AGENT_ID": "aria" } } }
2574        }))
2575        .unwrap();
2576        let rewritten = inject_jekt_signing_keys_into_mcp_json(&content, &store, "aria")
2577            .expect("both keys should ensure successfully against a fresh in-memory store");
2578        let parsed: Value = serde_json::from_str(&rewritten).unwrap();
2579        let env = &parsed["mcpServers"]["agentmux"]["env"];
2580        assert_eq!(env["AGENTMUX_AGENT_ID"], "aria", "existing fields must survive the patch");
2581        // The file holds references, not values: neither key is written, and the agent's MCP server asks srv.
2582        for name in crate::backend::mcp_json_identity::SIGNING_SECRETS.into_iter().chain(["AGENTMUX_HOST_LABEL"]) {
2583            assert!(env.get(name).is_none(), "{name} in {rewritten}");
2584        }
2585        use base64::Engine as _;
2586        let jekt = base64::engine::general_purpose::STANDARD.encode(store.agent_jekt_key_load("aria").unwrap().expect("ensured in the store"));
2587        let lan = store.agent_lan_key_load("aria").unwrap().expect("ensured in the store").private_key;
2588        assert!(!rewritten.contains(&jekt) && !rewritten.contains(&lan), "no value of either key is in the file");
2589        // The keys are minted at spawn, so srv has them ready for the agent's first fetch and WAN
2590        // (SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md) is published before use.
2591        assert!(wan.agent_key_load("aria").unwrap().is_some(), "minted at spawn, so it is published before use");
2592        // SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md Phase B: the channel the
2593        // sender signs under must be the one the shared registry publishes.
2594        assert_eq!(
2595            env["AGENTMUX_CHANNEL"],
2596            json!(crate::backend::reactive::registry::local_channel_id()),
2597            "the MCP env must carry the same channel id the shared registry entry is written under"
2598        );
2599    }
2600
2601    #[test]
2602    fn inject_jekt_signing_keys_into_mcp_json_reuses_the_same_key_on_a_second_call() {
2603        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
2604        let content = serde_json::to_string(&json!({
2605            "mcpServers": { "agentmux": { "env": { "AGENTMUX_AGENT_ID": "aria" } } }
2606        }))
2607        .unwrap();
2608
2609        inject_jekt_signing_keys_into_mcp_json(&content, &store, "aria").unwrap();
2610        let (jekt, lan) = (store.agent_jekt_key_load("aria").unwrap().unwrap(), store.agent_lan_key_load("aria").unwrap().unwrap());
2611        inject_jekt_signing_keys_into_mcp_json(&content, &store, "aria").unwrap();
2612        assert_eq!(store.agent_jekt_key_load("aria").unwrap().unwrap(), jekt, "minted-on-first-use key must be reused, not re-minted");
2613        assert_eq!(store.agent_lan_key_load("aria").unwrap().unwrap(), lan);
2614    }
2615
2616    /// W3-S §2.2: without a `wan.db` nothing is minted in `objects.db` for WAN. Host and LAN keys are
2617    /// ensured in the store as before, and none of them is written to the file.
2618    #[test]
2619    fn inject_jekt_signing_keys_gives_no_wan_key_without_a_wan_identity_store() {
2620        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
2621        let content = serde_json::to_string(&json!({
2622            "mcpServers": { "agentmux": { "env": { "AGENTMUX_AGENT_ID": "aria" } } }
2623        }))
2624        .unwrap();
2625        let rewritten = inject_jekt_signing_keys_into_mcp_json(&content, &store, "aria").unwrap();
2626        let env = serde_json::from_str::<Value>(&rewritten).unwrap()["mcpServers"]["agentmux"]["env"].clone();
2627        assert!(env.get("AGENTMUX_JEKT_KEY").is_none() && env.get("AGENTMUX_LAN_KEY").is_none());
2628        assert!(env.get("AGENTMUX_WAN_KEY").is_none());
2629        assert!(env.get("AGENTMUX_HOST_LABEL").is_none());
2630        assert!(store.agent_jekt_key_load("aria").unwrap().is_some() && store.agent_lan_key_load("aria").unwrap().is_some());
2631        assert!(store.agent_wan_key_load("aria").unwrap().is_none(), "nothing minted in objects.db");
2632    }
2633
2634    /// W3-S §2.2: an agent's existing `objects.db` WAN key is carried into
2635    /// `wan.db` on first use, so an agent upgraded onto D1 keeps its key.
2636    #[test]
2637    fn inject_jekt_signing_keys_imports_the_legacy_wan_key_once() {
2638        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
2639        let legacy = store.agent_wan_key_ensure("aria").unwrap();
2640        let (_wan_dir, wan) = crate::backend::storage::wan_identity::attach_temp_wan_identity(&store);
2641        let content = serde_json::to_string(&json!({
2642            "mcpServers": { "agentmux": { "env": { "AGENTMUX_AGENT_ID": "aria" } } }
2643        }))
2644        .unwrap();
2645        inject_jekt_signing_keys_into_mcp_json(&content, &store, "aria").unwrap();
2646        let key = wan.agent_key_load("aria").unwrap().unwrap();
2647        assert!(key.imported);
2648        assert_eq!(key.private_key, legacy.private_key);
2649    }
2650
2651    /// A config written by an older version loses every signing value it holds: the host jekt key, the
2652    /// LAN key, and the WAN key and instance label of before srv signed WAN jekts
2653    /// (SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md §3.3).
2654    #[test]
2655    fn inject_jekt_signing_keys_removes_every_signing_value_an_older_config_holds() {
2656        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
2657        let content = serde_json::to_string(&json!({
2658            "mcpServers": { "agentmux": { "env": {
2659                "AGENTMUX_AGENT_ID": "aria",
2660                "AGENTMUX_JEKT_KEY": "old-jekt-value",
2661                "AGENTMUX_LAN_KEY": "old-lan-value",
2662                "AGENTMUX_WAN_KEY": "old-private-key",
2663                "AGENTMUX_HOST_LABEL": "old-instance"
2664            } } }
2665        }))
2666        .unwrap();
2667        let rewritten = inject_jekt_signing_keys_into_mcp_json(&content, &store, "aria").unwrap();
2668        for old in ["old-jekt-value", "old-lan-value", "old-private-key", "AGENTMUX_HOST_LABEL"] {
2669            assert!(!rewritten.contains(old), "{old} in {rewritten}");
2670        }
2671        assert!(rewritten.contains("\"AGENTMUX_AGENT_ID\""), "{rewritten}");
2672    }
2673
2674    #[test]
2675    fn inject_jekt_signing_keys_into_mcp_json_returns_none_when_theres_no_env_object_to_patch() {
2676        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
2677        // No mcpServers.agentmux.env at all -- nothing to patch into.
2678        let content = serde_json::to_string(&json!({"hello": "world"})).unwrap();
2679        assert!(inject_jekt_signing_keys_into_mcp_json(&content, &store, "aria").is_none());
2680    }
2681
2682    #[test]
2683    fn inject_jekt_signing_keys_into_mcp_json_returns_none_on_malformed_json() {
2684        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
2685        assert!(inject_jekt_signing_keys_into_mcp_json("not json", &store, "aria").is_none());
2686    }
2687
2688    // ============================================================
2689    // write_startup_instructions_respecting_existing
2690    // (SPEC_PROVIDER_AWARE_STARTUP_INSTRUCTIONS_2026_08_24.md — codex P1, PR #2788)
2691    // ============================================================
2692
2693    #[test]
2694    fn startup_instructions_fresh_working_dir_writes_directly_with_the_marker() {
2695        let dir = tempfile::tempdir().unwrap();
2696        write_startup_instructions_respecting_existing(dir.path(), "AGENTS.md", "Soul + AgentMD content")
2697            .unwrap();
2698
2699        let content = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
2700        assert!(content.starts_with(STARTUP_INSTRUCTIONS_MANAGED_MARKER));
2701        assert!(content.contains("Soul + AgentMD content"));
2702    }
2703
2704    #[test]
2705    fn startup_instructions_agentmux_owned_file_is_freely_regenerated() {
2706        let dir = tempfile::tempdir().unwrap();
2707        write_startup_instructions_respecting_existing(dir.path(), "QWEN.md", "first version").unwrap();
2708        write_startup_instructions_respecting_existing(dir.path(), "QWEN.md", "second version").unwrap();
2709
2710        let content = std::fs::read_to_string(dir.path().join("QWEN.md")).unwrap();
2711        assert!(content.contains("second version"));
2712        assert!(!content.contains("first version"), "regeneration must replace, not accumulate");
2713    }
2714
2715    #[test]
2716    fn startup_instructions_foreign_file_content_is_never_touched() {
2717        // The exact regression codex P1 (PR #2788) flagged: a real project's
2718        // own AGENTS.md must survive an agent launch untouched, byte for
2719        // byte — no AgentMux marker, no partial merge, nothing.
2720        let dir = tempfile::tempdir().unwrap();
2721        let human_content = "# My real project\n\nHand-written AGENTS.md, no AgentMux involvement.";
2722        std::fs::write(dir.path().join("AGENTS.md"), human_content).unwrap();
2723
2724        write_startup_instructions_respecting_existing(dir.path(), "AGENTS.md", "AgentMux's generated content")
2725            .unwrap();
2726
2727        let content = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
2728        assert_eq!(content, human_content, "every byte of the original file must survive");
2729        assert!(!content.contains("AgentMux's generated content"));
2730    }
2731
2732    #[test]
2733    fn startup_instructions_foreign_empty_file_is_never_touched() {
2734        // An empty pre-existing file (no marker) is still foreign — the
2735        // decision hinges on the marker prefix, not on non-emptiness.
2736        let dir = tempfile::tempdir().unwrap();
2737        std::fs::write(dir.path().join("GEMINI.md"), "").unwrap();
2738
2739        write_startup_instructions_respecting_existing(dir.path(), "GEMINI.md", "AgentMux's generated content")
2740            .unwrap();
2741
2742        let content = std::fs::read_to_string(dir.path().join("GEMINI.md")).unwrap();
2743        assert_eq!(content, "");
2744    }
2745
2746    #[test]
2747    fn startup_instructions_non_utf8_file_is_treated_as_foreign_not_missing() {
2748        let dir = tempfile::tempdir().unwrap();
2749        let path = dir.path().join("AGENTS.md");
2750        std::fs::write(&path, [0x23, 0x20, 0xFF, 0xFE, 0x0A]).unwrap();
2751        let raw_before = std::fs::read(&path).unwrap();
2752
2753        write_startup_instructions_respecting_existing(dir.path(), "AGENTS.md", "generated content").unwrap();
2754
2755        let raw_after = std::fs::read(&path).unwrap();
2756        assert_eq!(raw_before, raw_after, "an unreadable file must be treated as foreign, never as absent");
2757    }
2758
2759    #[test]
2760    fn startup_instructions_creates_parent_directories_for_nested_paths() {
2761        // pi's target is .pi/APPEND_SYSTEM.md — a nested path with no
2762        // existing parent directory on a fresh working dir.
2763        let dir = tempfile::tempdir().unwrap();
2764        write_startup_instructions_respecting_existing(dir.path(), ".pi/APPEND_SYSTEM.md", "content").unwrap();
2765
2766        let content = std::fs::read_to_string(dir.path().join(".pi/APPEND_SYSTEM.md")).unwrap();
2767        assert!(content.contains("content"));
2768    }
2769
2770    // ============================================================
2771    // write_claude_md_respecting_ownership
2772    // (SPEC_CLAUDE_MD_OWNERSHIP_PROTECTION_2026_08_22.md)
2773    // ============================================================
2774
2775    #[test]
2776    fn claude_md_fresh_working_dir_writes_directly_with_the_marker() {
2777        let dir = tempfile::tempdir().unwrap();
2778        write_claude_md_respecting_ownership(dir.path(), "Soul + AgentMD + Memory + Skills").unwrap();
2779
2780        let content = std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap();
2781        assert!(content.starts_with(CLAUDE_MD_MANAGED_MARKER));
2782        assert!(content.contains("Soul + AgentMD + Memory + Skills"));
2783        // No foreign-file side effects on the common (fresh dir) path.
2784        assert!(!dir.path().join(AGENTMUX_MEMORY_FILENAME).exists());
2785    }
2786
2787    #[test]
2788    fn claude_md_agentmux_owned_file_is_freely_regenerated() {
2789        let dir = tempfile::tempdir().unwrap();
2790        write_claude_md_respecting_ownership(dir.path(), "first version").unwrap();
2791        write_claude_md_respecting_ownership(dir.path(), "second version").unwrap();
2792
2793        let content = std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap();
2794        assert!(content.contains("second version"));
2795        assert!(!content.contains("first version"), "regeneration must replace, not accumulate");
2796    }
2797
2798    #[test]
2799    fn claude_md_foreign_file_content_is_never_touched() {
2800        let dir = tempfile::tempdir().unwrap();
2801        let human_content = "# My real project\n\nHand-written rules, no AgentMux marker.";
2802        std::fs::write(dir.path().join("CLAUDE.md"), human_content).unwrap();
2803
2804        write_claude_md_respecting_ownership(dir.path(), "AgentMux's generated content").unwrap();
2805
2806        let content = std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap();
2807        assert!(content.starts_with(human_content), "every byte of the original file must survive, at the start");
2808        assert!(!content.contains("AgentMux's generated content"), "generated content must never land in the real file");
2809    }
2810
2811    #[test]
2812    fn claude_md_non_utf8_file_is_treated_as_foreign_not_missing() {
2813        // reagent P0 + codex P1 on PR #2747: read_to_string(...).ok()
2814        // collapsed ANY read error (not just NotFound) into "no file
2815        // yet," so a non-UTF-8 (or otherwise unreadable) foreign file
2816        // got silently clobbered — the exact data-loss bug this whole
2817        // function exists to prevent.
2818        let dir = tempfile::tempdir().unwrap();
2819        let claude_md_path = dir.path().join("CLAUDE.md");
2820        // Invalid UTF-8: a lone continuation byte. read_to_string must
2821        // fail on this (not silently lossy-convert it).
2822        std::fs::write(&claude_md_path, [0x23, 0x20, 0xFF, 0xFE, 0x0A]).unwrap();
2823        let raw_before = std::fs::read(&claude_md_path).unwrap();
2824
2825        write_claude_md_respecting_ownership(dir.path(), "AgentMux's generated content").unwrap();
2826
2827        let raw_after = std::fs::read(&claude_md_path).unwrap();
2828        assert_eq!(raw_before, raw_after, "an unreadable foreign file's bytes must be completely untouched, not overwritten");
2829        // Best-effort side file is still written even though the
2830        // @import offer itself is skipped (nothing safe to append to).
2831        let side_file = std::fs::read_to_string(dir.path().join(AGENTMUX_MEMORY_FILENAME)).unwrap();
2832        assert_eq!(side_file, "AgentMux's generated content");
2833    }
2834
2835    #[test]
2836    fn claude_md_foreign_file_gets_a_side_file_and_one_import_line() {
2837        let dir = tempfile::tempdir().unwrap();
2838        std::fs::write(dir.path().join("CLAUDE.md"), "# Real project\n").unwrap();
2839
2840        write_claude_md_respecting_ownership(dir.path(), "the generated body").unwrap();
2841
2842        let side_file = std::fs::read_to_string(dir.path().join(AGENTMUX_MEMORY_FILENAME)).unwrap();
2843        assert_eq!(side_file, "the generated body");
2844
2845        let claude_md = std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap();
2846        assert!(claude_md.contains(&format!("@{AGENTMUX_MEMORY_FILENAME}")));
2847        assert!(claude_md.contains(CLAUDE_MD_IMPORT_MARKER_COMMENT));
2848    }
2849
2850    #[test]
2851    fn claude_md_import_line_is_never_duplicated_across_launches() {
2852        let dir = tempfile::tempdir().unwrap();
2853        std::fs::write(dir.path().join("CLAUDE.md"), "# Real project\n").unwrap();
2854
2855        write_claude_md_respecting_ownership(dir.path(), "v1").unwrap();
2856        write_claude_md_respecting_ownership(dir.path(), "v2").unwrap();
2857        write_claude_md_respecting_ownership(dir.path(), "v3").unwrap();
2858
2859        let claude_md = std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap();
2860        let import_needle = format!("@{AGENTMUX_MEMORY_FILENAME}");
2861        assert_eq!(claude_md.matches(&import_needle).count(), 1, "the import line must appear exactly once, no matter how many launches");
2862        // The side file, unlike CLAUDE.md, keeps regenerating freely.
2863        let side_file = std::fs::read_to_string(dir.path().join(AGENTMUX_MEMORY_FILENAME)).unwrap();
2864        assert_eq!(side_file, "v3");
2865    }
2866
2867    #[test]
2868    fn claude_md_concurrent_launches_against_a_shared_workdir_never_duplicate_the_import() {
2869        // reagent P2 (second review round) on PR #2747: two agents
2870        // sharing a working directory (agent_open.rs's shared-workdir
2871        // fallback) launching concurrently previously could both read
2872        // "not yet offered" and both append the import line — the only
2873        // existing serialization (agent_open_lock) is keyed by
2874        // agent_id, not by working directory. Real threads, not a
2875        // sequential simulation, to actually exercise the race.
2876        let dir = tempfile::tempdir().unwrap();
2877        std::fs::write(dir.path().join("CLAUDE.md"), "# Real project\n").unwrap();
2878        let dir_path = dir.path().to_path_buf();
2879
2880        let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
2881        let handles: Vec<_> = (0..8)
2882            .map(|i| {
2883                let dir_path = dir_path.clone();
2884                let barrier = barrier.clone();
2885                std::thread::spawn(move || {
2886                    barrier.wait(); // maximize actual overlap
2887                    write_claude_md_respecting_ownership(&dir_path, &format!("content-{i}")).unwrap();
2888                })
2889            })
2890            .collect();
2891        for h in handles {
2892            h.join().unwrap();
2893        }
2894
2895        let claude_md = std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap();
2896        let import_needle = format!("@{AGENTMUX_MEMORY_FILENAME}");
2897        assert_eq!(
2898            claude_md.matches(&import_needle).count(),
2899            1,
2900            "8 concurrent launches against the same foreign CLAUDE.md must still produce exactly one import line, not one per racer"
2901        );
2902    }
2903
2904    #[test]
2905    fn claude_md_marker_is_rolled_back_when_the_append_fails() {
2906        // reagent P1 + codex, third review round on PR #2747: winning the
2907        // create_new race must not permanently record "offered" if the
2908        // append itself then fails -- otherwise every later launch's
2909        // create_new hits AlreadyExists and the import is never offered
2910        // again, with no retry path.
2911        let dir = tempfile::tempdir().unwrap();
2912        let claude_md_path = dir.path().join("CLAUDE.md");
2913        std::fs::write(&claude_md_path, "# Real project\n").unwrap();
2914
2915        // Read-only so the append's .open(...) fails, even though the
2916        // read earlier in the function (which only needs read access)
2917        // succeeds fine.
2918        let mut perms = std::fs::metadata(&claude_md_path).unwrap().permissions();
2919        perms.set_readonly(true);
2920        std::fs::set_permissions(&claude_md_path, perms).unwrap();
2921
2922        write_claude_md_respecting_ownership(dir.path(), "v1").unwrap();
2923
2924        let marker_path = dir.path().join(CLAUDE_MD_OWNERSHIP_MARKER_PATH);
2925        assert!(!marker_path.exists(), "a failed append must roll back the ownership marker so a future launch can retry");
2926
2927        // Restore write access and confirm a later launch actually succeeds.
2928        let mut perms = std::fs::metadata(&claude_md_path).unwrap().permissions();
2929        #[allow(clippy::permissions_set_readonly_false)]
2930        perms.set_readonly(false);
2931        std::fs::set_permissions(&claude_md_path, perms).unwrap();
2932
2933        write_claude_md_respecting_ownership(dir.path(), "v2").unwrap();
2934        let claude_md = std::fs::read_to_string(&claude_md_path).unwrap();
2935        let import_needle = format!("@{AGENTMUX_MEMORY_FILENAME}");
2936        assert_eq!(claude_md.matches(&import_needle).count(), 1, "retry after the file becomes writable again must succeed");
2937    }
2938
2939    #[test]
2940    fn claude_md_user_deleted_import_line_is_never_reinserted() {
2941        // The whole point of the ownership marker file: once offered, a
2942        // user's deliberate removal of the import line must stick.
2943        let dir = tempfile::tempdir().unwrap();
2944        std::fs::write(dir.path().join("CLAUDE.md"), "# Real project\n").unwrap();
2945        write_claude_md_respecting_ownership(dir.path(), "v1").unwrap();
2946
2947        // User opts out: deletes the import line by hand.
2948        std::fs::write(dir.path().join("CLAUDE.md"), "# Real project\n").unwrap();
2949
2950        write_claude_md_respecting_ownership(dir.path(), "v2").unwrap();
2951
2952        let claude_md = std::fs::read_to_string(dir.path().join("CLAUDE.md")).unwrap();
2953        assert_eq!(claude_md, "# Real project\n", "import line must not silently reappear after the user removed it");
2954        // The side file still refreshes even though nothing links to it
2955        // from CLAUDE.md anymore — harmless, and keeps it ready if the
2956        // user re-adds the import line themselves later.
2957        let side_file = std::fs::read_to_string(dir.path().join(AGENTMUX_MEMORY_FILENAME)).unwrap();
2958        assert_eq!(side_file, "v2");
2959    }
2960}
2961
2962#[cfg(test)]
2963mod bundle_section_heading_tests {
2964    use super::BUNDLE_SECTION_HEADING;
2965
2966    /// Pins the persisted heading: files already written carry it, and if it changes the global-bundle
2967    /// injector falls back to appending a second heading after the per-agent content.
2968    #[test]
2969    fn the_persisted_heading_is_unchanged() {
2970        assert_eq!(BUNDLE_SECTION_HEADING, "# Memory");
2971    }
2972}
2973
2974#[cfg(test)]
2975mod is_agentmux_managed_instructions_tests {
2976    use super::*;
2977
2978    #[test]
2979    fn recognizes_both_marker_classes() {
2980        // The bug this exists to prevent: a check against CLAUDE.md's marker
2981        // alone reports every generated AGENTS.md / GEMINI.md / QWEN.md /
2982        // .pi/APPEND_SYSTEM.md as foreign (Codex, PR #3144).
2983        assert!(is_agentmux_managed_instructions(&format!(
2984            "{CLAUDE_MD_MANAGED_MARKER}\n\n# Memory\n"
2985        )));
2986        assert!(is_agentmux_managed_instructions(&format!(
2987            "{STARTUP_INSTRUCTIONS_MANAGED_MARKER}\n\nBe helpful.\n"
2988        )));
2989    }
2990
2991    #[test]
2992    fn a_foreign_file_is_not_ours_however_it_starts() {
2993        assert!(!is_agentmux_managed_instructions("# My project\n\nRules.\n"));
2994        assert!(!is_agentmux_managed_instructions(""));
2995        // The marker has to be at the START — a file that merely mentions it
2996        // further down was not written by us.
2997        assert!(!is_agentmux_managed_instructions(&format!(
2998            "Someone pasted this below:\n{CLAUDE_MD_MANAGED_MARKER}\n"
2999        )));
3000    }
3001}
3002
3003#[cfg(test)]
3004mod mcp_json_tests {
3005    //! #3680: `.mcp.json` keeps a user's own servers and is owner-only.
3006    use super::*;
3007
3008    fn mcp_servers_of(dir: &std::path::Path) -> serde_json::Map<String, serde_json::Value> {
3009        let raw = std::fs::read_to_string(dir.join(".mcp.json")).unwrap();
3010        let v: serde_json::Value = serde_json::from_str(&raw).unwrap();
3011        v["mcpServers"].as_object().unwrap().clone()
3012    }
3013
3014    const GENERATED_MCP: &str = r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp","env":{"AGENTMUX_AGENT_ID":"a1"}},"github":{"command":"gh-mcp"}}}"#;
3015
3016    #[test]
3017    fn mcp_json_fresh_dir_is_written_as_generated() {
3018        let dir = tempfile::tempdir().unwrap();
3019        write_mcp_json_respecting_user_servers(dir.path(), GENERATED_MCP).unwrap();
3020        let servers = mcp_servers_of(dir.path());
3021        assert_eq!(servers.keys().collect::<Vec<_>>(), vec!["agentmux", "github"]);
3022    }
3023
3024    /// ReAgent on #4141: a symlinked `.mcp.json`, even one pointing inside
3025    /// the workdir, is left alone and the launch goes on.
3026    #[test]
3027    fn mcp_json_a_symlinked_file_is_left_alone_without_failing_the_launch() {
3028        let dir = tempfile::tempdir().unwrap();
3029        let target = dir.path().join("my-mcp.json");
3030        std::fs::write(&target, r#"{"mcpServers":{}}"#).unwrap();
3031        #[cfg(unix)]
3032        let made = std::os::unix::fs::symlink(&target, dir.path().join(".mcp.json")).is_ok();
3033        #[cfg(windows)]
3034        let made = std::os::windows::fs::symlink_file(&target, dir.path().join(".mcp.json")).is_ok();
3035        if !made {
3036            return;
3037        }
3038        write_mcp_json_respecting_user_servers(dir.path(), GENERATED_MCP).unwrap();
3039        assert!(std::fs::symlink_metadata(dir.path().join(".mcp.json")).unwrap().file_type().is_symlink());
3040        assert_eq!(std::fs::read_to_string(&target).unwrap(), r#"{"mcpServers":{}}"#);
3041    }
3042
3043    /// Codex on #4141: with `.claude` linking outside, the ownership manifest
3044    /// can't be written, so `.mcp.json` isn't either; otherwise the second
3045    /// launch would take the user's own server for AgentMux's and drop it.
3046    #[test]
3047    fn mcp_json_a_users_server_survives_two_launches_with_claude_linking_outside() {
3048        let dir = tempfile::tempdir().unwrap();
3049        let outside = tempfile::tempdir().unwrap();
3050        #[cfg(unix)]
3051        let made = std::os::unix::fs::symlink(outside.path(), dir.path().join(".claude")).is_ok();
3052        #[cfg(windows)]
3053        let made = std::os::windows::fs::symlink_dir(outside.path(), dir.path().join(".claude")).is_ok();
3054        if !made {
3055            return;
3056        }
3057        let users = r#"{"mcpServers":{"mine":{"command":"my-mcp"}}}"#;
3058        std::fs::write(dir.path().join(".mcp.json"), users).unwrap();
3059        write_mcp_json_respecting_user_servers(dir.path(), GENERATED_MCP).unwrap();
3060        write_mcp_json_respecting_user_servers(dir.path(), GENERATED_MCP).unwrap();
3061        assert!(mcp_servers_of(dir.path()).contains_key("mine"));
3062        assert!(std::fs::read_dir(outside.path()).unwrap().next().is_none(), "nothing written outside");
3063    }
3064
3065    #[test]
3066    fn mcp_json_a_users_own_servers_and_keys_survive_the_launch() {
3067        let dir = tempfile::tempdir().unwrap();
3068        std::fs::write(
3069            dir.path().join(".mcp.json"),
3070            r#"{"mcpServers":{"postgres":{"command":"pg-mcp"}},"someOtherKey":true}"#,
3071        )
3072        .unwrap();
3073        write_mcp_json_respecting_user_servers(dir.path(), GENERATED_MCP).unwrap();
3074        let servers = mcp_servers_of(dir.path());
3075        assert!(servers.contains_key("postgres"), "the user's server must survive");
3076        assert!(servers.contains_key("agentmux"));
3077        assert!(servers.contains_key("github"));
3078        let raw = std::fs::read_to_string(dir.path().join(".mcp.json")).unwrap();
3079        assert!(raw.contains("someOtherKey"), "other top-level keys must survive");
3080    }
3081
3082    #[test]
3083    fn mcp_json_a_server_unbound_since_the_last_launch_is_removed_but_the_users_is_not() {
3084        let dir = tempfile::tempdir().unwrap();
3085        std::fs::write(dir.path().join(".mcp.json"), r#"{"mcpServers":{"postgres":{"command":"pg-mcp"}}}"#).unwrap();
3086        write_mcp_json_respecting_user_servers(dir.path(), GENERATED_MCP).unwrap();
3087        // Next launch: `github` was unbound in Connectors.
3088        write_mcp_json_respecting_user_servers(dir.path(), r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"}}}"#)
3089            .unwrap();
3090        let servers = mcp_servers_of(dir.path());
3091        assert!(!servers.contains_key("github"), "a server AgentMux wrote and no longer wants must go");
3092        assert!(servers.contains_key("postgres"), "the user's server must still be there");
3093        assert!(servers.contains_key("agentmux"));
3094    }
3095
3096    #[test]
3097    fn mcp_json_without_a_manifest_an_agentmux_written_file_is_regenerated_as_before() {
3098        // A file an older AgentMux wrote: has our `agentmux` entry, no manifest.
3099        // All of it is ours, so a stale server from an old definition goes.
3100        let dir = tempfile::tempdir().unwrap();
3101        std::fs::write(
3102            dir.path().join(".mcp.json"),
3103            r#"{"mcpServers":{"agentmux":{"command":"old"},"stale":{"command":"x"}}}"#,
3104        )
3105        .unwrap();
3106        write_mcp_json_respecting_user_servers(dir.path(), GENERATED_MCP).unwrap();
3107        let servers = mcp_servers_of(dir.path());
3108        assert!(!servers.contains_key("stale"));
3109        assert_eq!(servers["agentmux"]["command"], "agentmux-mcp");
3110    }
3111
3112    #[test]
3113    fn mcp_json_our_entry_wins_a_name_clash() {
3114        let dir = tempfile::tempdir().unwrap();
3115        std::fs::write(dir.path().join(".mcp.json"), r#"{"mcpServers":{"github":{"command":"users-own"}}}"#).unwrap();
3116        write_mcp_json_respecting_user_servers(dir.path(), GENERATED_MCP).unwrap();
3117        assert_eq!(mcp_servers_of(dir.path())["github"]["command"], "gh-mcp");
3118    }
3119
3120    #[test]
3121    fn mcp_json_a_file_that_is_not_a_json_object_is_left_untouched() {
3122        for body in ["{ not json", "[1,2]", r#"{"mcpServers":[]}"#] {
3123            let dir = tempfile::tempdir().unwrap();
3124            std::fs::write(dir.path().join(".mcp.json"), body).unwrap();
3125            write_mcp_json_respecting_user_servers(dir.path(), GENERATED_MCP).unwrap();
3126            assert_eq!(std::fs::read_to_string(dir.path().join(".mcp.json")).unwrap(), body);
3127        }
3128    }
3129
3130    #[test]
3131    fn mcp_json_rejects_generated_content_that_is_not_json() {
3132        let dir = tempfile::tempdir().unwrap();
3133        assert!(write_mcp_json_respecting_user_servers(dir.path(), "nope").is_err());
3134        assert!(!dir.path().join(".mcp.json").exists());
3135    }
3136
3137    #[test]
3138    fn mcp_json_leaves_no_temp_file_behind() {
3139        let dir = tempfile::tempdir().unwrap();
3140        write_mcp_json_respecting_user_servers(dir.path(), GENERATED_MCP).unwrap();
3141        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
3142            .unwrap()
3143            .filter_map(|e| e.ok())
3144            .filter(|e| e.file_name().to_string_lossy().contains("agentmux-tmp"))
3145            .collect();
3146        assert!(leftovers.is_empty());
3147    }
3148
3149    #[test]
3150    fn mcp_json_concurrent_launches_into_one_dir_never_publish_corrupt_json() {
3151        // ReAgent P1 on #3803: a per-process temp name let two same-srv writes
3152        // interleave into one temp file before either rename. Many writers of
3153        // differently sized content maximise the chance of interleaving.
3154        let dir = tempfile::tempdir().unwrap();
3155        let base = dir.path().to_path_buf();
3156        let handles: Vec<_> = (0..16)
3157            .map(|i| {
3158                let base = base.clone();
3159                std::thread::spawn(move || {
3160                    // Each "agent" brings its own extra server, so a manifest from
3161                    // one launch paired with the file from another is detectable.
3162                    let padding = "x".repeat(i * 4096);
3163                    let content = format!(
3164                        r#"{{"mcpServers":{{"agentmux":{{"command":"agentmux-mcp","env":{{"AGENTMUX_AGENT_ID":"a{i}","PAD":"{padding}"}}}},"srv{i}":{{"command":"s{i}"}}}}}}"#
3165                    );
3166                    for _ in 0..10 {
3167                        write_mcp_json_respecting_user_servers(&base, &content).unwrap();
3168                    }
3169                })
3170            })
3171            .collect();
3172        for h in handles {
3173            h.join().unwrap();
3174        }
3175        let raw = std::fs::read_to_string(base.join(".mcp.json")).unwrap();
3176        let v: serde_json::Value = serde_json::from_str(&raw).expect("published .mcp.json must be valid JSON");
3177        assert!(v["mcpServers"]["agentmux"].is_object());
3178        let manifest = std::fs::read_to_string(base.join(MANAGED_MCP_SERVERS_MANIFEST)).unwrap();
3179        let managed: std::collections::BTreeSet<String> =
3180            serde_json::from_str(&manifest).expect("the manifest must not be interleaved either");
3181        // ReAgent P1 (round 2) on #3803: the manifest must describe the SAME
3182        // launch as the file. With no user servers here, that means exactly
3183        // the file's server names — and exactly one agent's set.
3184        let on_disk: std::collections::BTreeSet<String> =
3185            v["mcpServers"].as_object().unwrap().keys().cloned().collect();
3186        assert_eq!(managed, on_disk, "manifest and .mcp.json describe different launches");
3187        assert_eq!(on_disk.len(), 2, "exactly one launch's servers (agentmux + its own), got {on_disk:?}");
3188        for d in [base.clone(), base.join(".claude")] {
3189            let leftovers = std::fs::read_dir(&d)
3190                .unwrap()
3191                .filter_map(|e| e.ok())
3192                .filter(|e| e.file_name().to_string_lossy().contains("agentmux-tmp"))
3193                .count();
3194            assert_eq!(leftovers, 0, "temp files left in {}", d.display());
3195        }
3196    }
3197
3198    #[cfg(unix)]
3199    #[test]
3200    fn mcp_json_is_owner_only_on_unix_even_when_replacing_a_0644_file() {
3201        use std::os::unix::fs::PermissionsExt;
3202        let dir = tempfile::tempdir().unwrap();
3203        let path = dir.path().join(".mcp.json");
3204        std::fs::write(&path, r#"{"mcpServers":{}}"#).unwrap();
3205        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
3206        write_mcp_json_respecting_user_servers(dir.path(), GENERATED_MCP).unwrap();
3207        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
3208    }
3209}