Skip to main content

agentmux_srv_core/backend/subagent_watcher/
parse.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Free-standing parsing/path utilities used by the rest of `subagent_watcher`
5//! — none of these need `&self`. Covers: JSONL line parsing, journal-count
6//! reading, workflow/session id derivation from a path, the block-delete
7//! cascade subscriber, and Claude config dir resolution.
8
9use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12
13use super::types::{SubagentEvent, SubagentEventType};
14use super::SubagentWatcher;
15
16// ── Tool-call payload bounds ────────────────────────────────────────────
17//
18// Both limits are in CHARS, never bytes, so a cut can't split a codepoint.
19// See docs/reports/REPORT_TOOL_SUMMARY_FORMATTING_ARCHITECTURE_2026_09_06.md
20// §4.1 and §9 (measured input sizes).
21
22/// Chars kept per top-level field of a tool call's input. Every subagent
23/// call measured fits whole; an Edit's file contents or an Agent prompt
24/// does not, and only needs to show its start.
25const MAX_INPUT_FIELD_CHARS: usize = 500;
26
27/// Chars of a tool result kept for the same feed. Larger than the input
28/// budget because a result is the thing a reader is usually scanning.
29const MAX_RESULT_PREVIEW_CHARS: usize = 500;
30
31/// Cut to `max` CHARS (never mid-codepoint), appending an ellipsis when it
32/// actually cut something.
33fn truncate_chars(s: &str, max: usize) -> String {
34    match s.char_indices().nth(max) {
35        Some((byte_idx, _)) => format!("{}...", &s[..byte_idx]),
36        None => s.to_string(),
37    }
38}
39
40/// A tool call's `input`, kept structured but bounded: each top-level string
41/// is cut to `MAX_INPUT_FIELD_CHARS`, and a nested array/object whose JSON is
42/// longer becomes that JSON, cut the same way.
43///
44/// Which field to show is decided by the frontend's `toolDetail`
45/// (`frontend/app/agent-model/tool-descriptors.ts`), the same rule
46/// the agent pane uses, so the Swarm feed can't drift from it.
47fn bounded_tool_input(input: &serde_json::Value) -> serde_json::Value {
48    use serde_json::Value;
49    fn bound(v: &Value) -> Value {
50        match v {
51            Value::String(s) => Value::String(truncate_chars(s, MAX_INPUT_FIELD_CHARS)),
52            Value::Array(_) | Value::Object(_) => {
53                let json = v.to_string();
54                if json.chars().count() <= MAX_INPUT_FIELD_CHARS {
55                    v.clone()
56                } else {
57                    Value::String(truncate_chars(&json, MAX_INPUT_FIELD_CHARS))
58                }
59            }
60            scalar => scalar.clone(),
61        }
62    }
63    match input {
64        Value::Object(map) => Value::Object(map.iter().map(|(k, v)| (k.clone(), bound(v))).collect()),
65        other => bound(other),
66    }
67}
68
69/// A tool result's text. A plain string is used as-is; anything else (the
70/// common `[{"type":"text","text":…}]` block array, or a bare object) falls
71/// back to compact JSON, same as before.
72fn result_content_text(content: &serde_json::Value) -> String {
73    match content.as_str() {
74        Some(s) => s.to_string(),
75        None => content.to_string(),
76    }
77}
78
79// ── Block-delete cascade subscriber ─────────────────────────────────────
80
81/// Subscribe to the reducer's `srv_events_tx` broadcast and prune `watcher`'s
82/// per-block state on `Event::BlockDeleted`/`TabDeleted`/`WorkspaceDeleted` —
83/// the robust backstop described on `SubagentWatcher::prune_block`'s doc
84/// comment. Mirrors `crates/cef/src/srv_ipc.rs`'s cascaded-block-id
85/// extraction (same three-arm match, same rationale: `TabDeleted`/
86/// `WorkspaceDeleted` never emit a per-block event of their own — see
87/// `reducer/tab.rs::handle_delete_tab`'s doc comment — so `block_ids` is the
88/// only signal for a block that cascaded out via its tab/workspace) and
89/// `server/mux_obj_bridge.rs::run_mux_obj_bridge`'s subscribe-loop
90/// plumbing (lag/close handling).
91pub fn spawn_block_prune_subscriber(
92    watcher: Arc<SubagentWatcher>,
93    mut events_rx: tokio::sync::broadcast::Receiver<agentmux_common::ipc::Event>,
94) -> tokio::task::JoinHandle<()> {
95    tokio::spawn(async move {
96        loop {
97            match events_rx.recv().await {
98                Ok(event) => {
99                    let cascaded_block_ids: &[String] = match &event {
100                        agentmux_common::ipc::Event::BlockDeleted { block_id, .. } => {
101                            std::slice::from_ref(block_id)
102                        }
103                        agentmux_common::ipc::Event::TabDeleted { block_ids, .. } => block_ids.as_slice(),
104                        agentmux_common::ipc::Event::WorkspaceDeleted { block_ids, .. } => block_ids.as_slice(),
105                        _ => &[],
106                    };
107                    for block_id in cascaded_block_ids {
108                        watcher.prune_block_and_notify(block_id);
109                    }
110                }
111                Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
112                    // Same non-fatal, no-automatic-recovery handling as
113                    // mux_obj_bridge.rs's identical arm: a lag here means a
114                    // stale swarm-pane row could persist until its block's
115                    // next delete-adjacent event, not silent data loss.
116                    tracing::warn!(
117                        skipped = n,
118                        "subagent block-prune subscriber lagged; some BlockDeleted/TabDeleted/WorkspaceDeleted events were dropped"
119                    );
120                }
121                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
122                    tracing::info!("subagent block-prune subscriber exiting: events channel closed");
123                    return;
124                }
125            }
126        }
127    })
128}
129
130// ── JSONL parsing ─────────────────────────────────────────────────────────
131
132/// Metadata extracted from the first JSONL line (the subagent init record).
133pub(super) struct JsonlMeta {
134    pub(super) slug: String,
135    pub(super) model: Option<String>,
136    /// The line's own `"parentUuid"` field, verbatim (SPEC §9.2 — `SubAgent.
137    /// spawned_from_agent_id`). `None` in every real transcript checked so
138    /// far; captured defensively since this line is already parsed.
139    pub(super) parent_uuid: Option<String>,
140}
141
142/// Read a JSONL file from a byte offset, parsing new subagent events.
143/// Returns (events, new_offset, optional_meta).
144pub(super) fn read_jsonl_from_offset(
145    path: &Path,
146    offset: u64,
147) -> Result<(Vec<SubagentEvent>, u64, Option<JsonlMeta>), String> {
148    read_jsonl_range(path, offset, u64::MAX, usize::MAX)
149}
150
151/// The newest `limit` events in the transcript's first `end` bytes: the history of a subagent whose
152/// events are no longer kept in memory, up to where the watcher has read. A line past `end` is one
153/// the watcher has not announced yet; it is left for the watcher, so nobody is shown it twice.
154pub(super) fn read_events_before(path: &Path, end: u64, limit: usize) -> Result<Vec<SubagentEvent>, String> {
155    let (mut events, _, _) = read_jsonl_range(path, 0, end, limit)?;
156    let excess = events.len().saturating_sub(limit);
157    events.drain(..excess);
158    Ok(events)
159}
160
161/// `read_jsonl_from_offset`, stopping at byte `end` of the file and holding no more than twice
162/// `keep_newest` events while it reads: a long transcript read for its last events does not sit in
163/// memory whole. The events returned are the newest; there can be more than `keep_newest` of them.
164fn read_jsonl_range(
165    path: &Path,
166    offset: u64,
167    end: u64,
168    keep_newest: usize,
169) -> Result<(Vec<SubagentEvent>, u64, Option<JsonlMeta>), String> {
170    let file = std::fs::File::open(path).map_err(|e| format!("open: {e}"))?;
171    let file_len = file.metadata().map_err(|e| format!("metadata: {e}"))?.len();
172
173    if file_len <= offset {
174        return Ok((Vec::new(), offset, None));
175    }
176
177    let mut reader = BufReader::new(file);
178    reader
179        .seek(SeekFrom::Start(offset))
180        .map_err(|e| format!("seek: {e}"))?;
181
182    let mut events = Vec::new();
183    let mut meta = None;
184    let mut current_offset = offset;
185
186    for line_result in reader.take(end.saturating_sub(offset)).lines() {
187        let line = match line_result {
188            Ok(l) => l,
189            Err(_) => break,
190        };
191        current_offset += line.len() as u64 + 1; // +1 for newline
192
193        if line.trim().is_empty() {
194            continue;
195        }
196
197        let value: serde_json::Value = match serde_json::from_str(&line) {
198            Ok(v) => v,
199            Err(_) => continue,
200        };
201
202        // Extract metadata from init/config lines
203        if offset == 0 && meta.is_none() {
204            let parent_uuid = value
205                .get("parentUuid")
206                .and_then(|v| v.as_str())
207                .map(|s| s.to_string());
208            if let Some(slug) = value.get("slug").and_then(|v| v.as_str()) {
209                meta = Some(JsonlMeta {
210                    slug: slug.to_string(),
211                    model: value
212                        .get("model")
213                        .and_then(|v| v.as_str())
214                        .map(|s| s.to_string()),
215                    parent_uuid: parent_uuid.clone(),
216                });
217            }
218            if meta.is_none() {
219                if let Some(agent_id) = value.get("agentId").and_then(|v| v.as_str()) {
220                    meta = Some(JsonlMeta {
221                        slug: value
222                            .get("slug")
223                            .and_then(|v| v.as_str())
224                            .unwrap_or(agent_id)
225                            .to_string(),
226                        model: value
227                            .get("model")
228                            .and_then(|v| v.as_str())
229                            .map(|s| s.to_string()),
230                        parent_uuid,
231                    });
232                }
233            }
234        }
235
236        let timestamp = value
237            .get("timestamp")
238            .and_then(parse_event_timestamp)
239            .unwrap_or_else(now_millis);
240
241        let event_type = parse_event_type(&value);
242        if let Some(et) = event_type {
243            let line_agent_id = value
244                .get("agentId")
245                .and_then(|v| v.as_str())
246                .unwrap_or("")
247                .to_string();
248
249            events.push(SubagentEvent {
250                agent_id: line_agent_id,
251                event_type: et,
252                timestamp,
253            });
254            if events.len() >= keep_newest.saturating_mul(2) {
255                events.drain(..events.len() - keep_newest);
256            }
257        }
258    }
259
260    Ok((events, current_offset, meta))
261}
262
263/// Read just the subagent's own initial task prompt from the first JSONL
264/// line (a `"type":"user"` init record) — used by `subagent.GenerateName` as
265/// the source text for the Haiku naming call. Deliberately bypasses the
266/// events cache/offset machinery `read_jsonl_from_offset` uses: naming only
267/// ever needs the first line, is called at most once per subagent (cached
268/// via `display_name` thereafter), and must work even for a subagent whose
269/// events haven't been scanned into `SubagentState` yet.
270///
271/// `message.content` is either a plain string or an array of content blocks
272/// (mirrors the two shapes `parse_event_type`'s "assistant" arm already
273/// handles) — both are accepted here.
274pub(crate) fn read_task_prompt(jsonl_path: &str) -> Option<String> {
275    let file = std::fs::File::open(jsonl_path).ok()?;
276    let mut reader = BufReader::new(file);
277    let mut first_line = String::new();
278    reader.read_line(&mut first_line).ok()?;
279
280    let value: serde_json::Value = serde_json::from_str(first_line.trim()).ok()?;
281    if value.get("type").and_then(|v| v.as_str()) != Some("user") {
282        return None;
283    }
284    let content = value.get("message")?.get("content")?;
285
286    if let Some(text) = content.as_str() {
287        let trimmed = text.trim();
288        return (!trimmed.is_empty()).then(|| trimmed.to_string());
289    }
290
291    if let Some(arr) = content.as_array() {
292        let texts: Vec<&str> = arr
293            .iter()
294            .filter_map(|block| {
295                if block.get("type").and_then(|t| t.as_str()) == Some("text") {
296                    block.get("text").and_then(|t| t.as_str())
297                } else {
298                    None
299                }
300            })
301            .collect();
302        let joined = texts.join("\n").trim().to_string();
303        return (!joined.is_empty()).then_some(joined);
304    }
305
306    None
307}
308
309/// Parse a JSONL line into a SubagentEventType based on the `type` field.
310pub(super) fn parse_event_type(value: &serde_json::Value) -> Option<SubagentEventType> {
311    let event_type = value.get("type").and_then(|v| v.as_str())?;
312
313    match event_type {
314        "assistant" => {
315            let content = value
316                .get("message")
317                .and_then(|m| m.get("content"))
318                .and_then(|c| {
319                    if let Some(arr) = c.as_array() {
320                        let texts: Vec<&str> = arr
321                            .iter()
322                            .filter_map(|block| {
323                                if block.get("type").and_then(|t| t.as_str()) == Some("text") {
324                                    block.get("text").and_then(|t| t.as_str())
325                                } else {
326                                    None
327                                }
328                            })
329                            .collect();
330                        if texts.is_empty() {
331                            None
332                        } else {
333                            Some(texts.join("\n"))
334                        }
335                    } else {
336                        c.as_str().map(|s| s.to_string())
337                    }
338                })
339                .unwrap_or_default();
340            Some(SubagentEventType::Text { content })
341        }
342        "tool_use" => {
343            let name = value
344                .get("name")
345                .or_else(|| value.get("tool_name"))
346                .and_then(|v| v.as_str())
347                .unwrap_or("unknown")
348                .to_string();
349            let input = value.get("input").map(bounded_tool_input).unwrap_or_default();
350            Some(SubagentEventType::ToolUse { name, input })
351        }
352        "tool_result" => {
353            let is_error = value
354                .get("is_error")
355                .and_then(|v| v.as_bool())
356                .unwrap_or(false);
357            let preview = value
358                .get("content")
359                .or_else(|| value.get("output"))
360                .map(|v| truncate_chars(&result_content_text(v), MAX_RESULT_PREVIEW_CHARS))
361                .unwrap_or_default();
362            Some(SubagentEventType::ToolResult { is_error, preview })
363        }
364        "progress" => {
365            let output = value
366                .get("output")
367                .or_else(|| value.get("content"))
368                .and_then(|v| v.as_str())
369                .unwrap_or("")
370                .to_string();
371            Some(SubagentEventType::Progress { output })
372        }
373        "result" => {
374            let content = value
375                .get("result")
376                .or_else(|| value.get("content"))
377                .map(|v| {
378                    if let Some(s) = v.as_str() {
379                        s.to_string()
380                    } else {
381                        v.to_string()
382                    }
383                })
384                .unwrap_or_else(|| "Subagent completed".to_string());
385            Some(SubagentEventType::Result { content })
386        }
387        _ => None,
388    }
389}
390
391/// Epoch-millis for a subagent JSONL line's `timestamp` field, tolerant of
392/// BOTH shapes that occur in real transcripts.
393///
394/// Claude Code writes an ISO-8601 STRING (`"2026-07-03T08:09:20.743Z"`), but
395/// this was read with a bare `as_u64()`, which returns `None` for a string
396/// and silently fell through to `now_millis()`. Every replayed historical
397/// event therefore claimed to have happened *at replay time*.
398///
399/// That is not a cosmetic timestamp bug: `last_event_at` becomes
400/// `subagentToActivity`'s `endedAt` (activity/subagent-adapter.ts), and the
401/// Activity Dock keeps a terminal row only while
402/// `now - endedAt < RETENTION_MS[status]`. With `endedAt ≈ now`, every
403/// long-dead subagent replayed on pane (re)open passed that window and
404/// rendered as a live-looking dock row, then vanished a few seconds later
405/// when it aged out — the "dock flashes on load, then disappears" report.
406/// With real historical timestamps these rows are filtered out immediately
407/// and never paint at all.
408///
409/// Numeric epoch-millis are still accepted unchanged (other providers, and
410/// any future writer that emits a number). An unparseable value returns
411/// `None` so the caller keeps its existing `now_millis()` fallback — a
412/// genuinely-live event with a malformed timestamp is better dated "now"
413/// than dropped to the epoch.
414///
415/// See docs/retro/retro-activitydock-appears-on-agent-pane-load-2026-09-02.md.
416pub(super) fn parse_event_timestamp(v: &serde_json::Value) -> Option<u64> {
417    if let Some(n) = v.as_u64() {
418        return Some(n);
419    }
420    let s = v.as_str()?;
421    chrono::DateTime::parse_from_rfc3339(s)
422        .ok()
423        .map(|dt| dt.timestamp_millis())
424        .filter(|ms| *ms >= 0)
425        .map(|ms| ms as u64)
426}
427
428/// Modification time of `path`, or `UNIX_EPOCH` if it can't be read (a
429/// vanished/permission-denied file sorts oldest — excluded first by
430/// `scan_subagents_dir`'s recency cap rather than crashing the scan).
431pub(super) fn file_mtime(path: &Path) -> std::time::SystemTime {
432    std::fs::metadata(path)
433        .and_then(|m| m.modified())
434        .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
435}
436
437/// Walk up `path`'s ancestors (parent, grandparent, ...) and return the
438/// first one that already exists on disk. Used by `watch_agent` when the
439/// target directory doesn't exist yet — `notify::Watcher::watch` fails
440/// outright on a nonexistent path, so this finds the closest directory that
441/// can actually be watched right now (a later-created descendant is still
442/// picked up, since the watch is recursive).
443///
444/// Never walks above the user's home directory. Without a floor, a fresh
445/// environment where even `~/.config` doesn't exist yet (ephemeral
446/// dev/CI/container — this project's own docs describe several such setups)
447/// would walk all the way to `$HOME` or further, and
448/// `watcher.watch(&watched_dir, RecursiveMode::Recursive)` performs a
449/// synchronous, blocking directory walk of whatever it's handed — recursing
450/// the entire home directory (or beyond) from inside the async
451/// `handle_reactive_register` request handler risks a long stall and, on
452/// Linux, exhausting the OS-wide inotify watch-count limit. Returns `None`
453/// (giving up on watching rather than risking an unbounded walk) if `path`
454/// isn't under the home directory at all, or if no existing ancestor is
455/// found within that bound.
456pub(super) fn nearest_existing_ancestor(path: &Path) -> Option<PathBuf> {
457    let floor = dirs::home_dir()?;
458    path.ancestors()
459        .skip(1)
460        .take_while(|p| p.starts_with(&floor))
461        .find(|p| p.exists())
462        .map(|p| p.to_path_buf())
463}
464
465/// Extract the workflow id from a path under `.../subagents/workflows/<id>/...`.
466/// Returns None for direct (non-workflow) subagent files.
467pub(super) fn parse_workflow_id(path: &Path) -> Option<String> {
468    let comps: Vec<&str> = path.iter().filter_map(|c| c.to_str()).collect();
469    comps.windows(3).find_map(|w| {
470        (w[0] == "subagents" && w[1] == "workflows" && !w[2].ends_with(".jsonl"))
471            .then(|| w[2].to_string())
472    })
473}
474
475/// Session id = the name of the directory containing `subagents/`. Workflow
476/// member files are nested (`subagents/workflows/<wf>/agent-*.jsonl`), so walk
477/// ancestors instead of assuming a fixed depth.
478pub(super) fn derive_session_id(path: &Path) -> String {
479    let mut dir = path.parent();
480    while let Some(d) = dir {
481        if d.file_name().and_then(|n| n.to_str()) == Some("subagents") {
482            return d
483                .parent()
484                .and_then(|p| p.file_name())
485                .and_then(|n| n.to_str())
486                .unwrap_or("unknown")
487                .to_string();
488        }
489        dir = d.parent();
490    }
491    "unknown".to_string()
492}
493
494/// Count new `started` / `result` records in a workflow journal from `offset`.
495/// Returns (started, results, new_offset).
496///
497/// Reads line-by-line via `read_until(b'\n', ..)` rather than `BufRead::lines()`
498/// so a trailing line with no `\n` yet (the writer racing a partial append) is
499/// never counted or consumed: `new_offset` only ever advances past complete,
500/// newline-terminated lines, so the next call re-reads that partial line whole
501/// once the rest of it lands, instead of seeking mid-line and silently losing
502/// the record's leading bytes (and the record itself, since the resulting
503/// truncated JSON fails to parse).
504pub(super) fn read_journal_counts(path: &Path, offset: u64) -> Result<(usize, usize, u64), String> {
505    let file = std::fs::File::open(path).map_err(|e| format!("open: {e}"))?;
506    let file_len = file.metadata().map_err(|e| format!("metadata: {e}"))?.len();
507    if file_len <= offset {
508        return Ok((0, 0, offset));
509    }
510
511    let mut reader = BufReader::new(file);
512    reader
513        .seek(SeekFrom::Start(offset))
514        .map_err(|e| format!("seek: {e}"))?;
515
516    let (mut started, mut results) = (0usize, 0usize);
517    let mut current_offset = offset;
518    loop {
519        let mut buf = Vec::new();
520        let bytes_read = reader
521            .read_until(b'\n', &mut buf)
522            .map_err(|e| format!("read_until: {e}"))?;
523        if bytes_read == 0 {
524            break; // EOF
525        }
526        if !buf.ends_with(b"\n") {
527            break; // trailing partial line — leave it unconsumed for next time
528        }
529        current_offset += bytes_read as u64;
530
531        let line = String::from_utf8_lossy(&buf);
532        let trimmed = line.trim_end_matches(['\n', '\r']);
533        let value: serde_json::Value = match serde_json::from_str(trimmed) {
534            Ok(v) => v,
535            Err(_) => continue,
536        };
537        match value.get("type").and_then(|v| v.as_str()) {
538            Some("started") => started += 1,
539            Some("result") => results += 1,
540            _ => {}
541        }
542    }
543    Ok((started, results, current_offset))
544}
545
546pub(super) use agentmux_common::time::now_ms_u64 as now_millis;
547
548/// Derive the Claude Code config directory for a host agent. Only matches
549/// reality for an agent with an explicit per-account auth dir —
550/// prefer `resolve_claude_config_dir` when the block's meta is available.
551pub fn derive_claude_config_dir(agent_id: &str) -> Option<PathBuf> {
552    let home = dirs::home_dir()?;
553    let config_dir = home
554        .join(".config")
555        .join(format!("claude-{}", agent_id.to_lowercase()));
556    Some(config_dir)
557}
558
559/// The authoritative Claude Code config directory for a block.
560///
561/// `bound_dir` — pass `identity::resolver::resolve_bound_oauth_config_dir`'s
562/// result here. It wins when present: for an agent bound to an explicit
563/// account, it's the ONLY correct answer — `cmd:env.CLAUDE_CONFIG_DIR`
564/// below is a write-once launch-time snapshot of the generic shared-provider
565/// dir, while the identity-bound agent's CLI actually runs (and writes
566/// subagent files) under its own identity dir, re-resolved fresh on every
567/// turn (`inject_identity_env_with_broker`,
568/// `SPEC_PROVIDER_ISOLATION_2026_06_20.md` §4.3) — `cmd:env` is never
569/// updated to match. Confirmed live: a real dispatch's transcript landed
570/// under the identity dir while the watcher, following `cmd:env` alone, was
571/// watching the generic dir and never saw it — see
572/// `SPEC_SUBAGENT_WATCHER_IDENTITY_BOUND_CONFIG_DIR_2026_08_22.md`.
573///
574/// Falls back to `cmd:env.CLAUDE_CONFIG_DIR` (written by the launch flow
575/// before spawn — see srv's `provider.ensureauthdir`) when `bound_dir`
576/// is `None` (an ambient/unbound agent, where `cmd:env` IS correct and
577/// stays correct — nothing to re-resolve). Falls back further to
578/// `derive_claude_config_dir`'s legacy `~/.config/claude-<agent_id>` guess
579/// only when `cmd:env` isn't set yet either.
580///
581/// This distinction matters: `derive_claude_config_dir`'s guess only holds
582/// for an agent with an explicit per-account auth dir. Any agent
583/// without one launches under the shared default at
584/// `~/.agentmux/shared/providers/claude/`, a completely different path that
585/// the guess never matches — silently disabling subagent tracking for that
586/// agent forever (confirmed live: repeated "config dir does not exist yet"
587/// over 38+ minutes and multiple re-registrations, for an agent that had, in
588/// fact, already spawned subagents — just under the real shared path). See
589/// docs/specs/archive/REPORT_SWARM_SUBAGENT_HISTORY_FLOOD_2026_07_07.md.
590pub fn resolve_claude_config_dir(
591    meta: &crate::backend::obj::MetaMapType,
592    agent_id: &str,
593    bound_dir: Option<PathBuf>,
594) -> Option<PathBuf> {
595    resolve_claude_config_dir_with(meta, agent_id, bound_dir, crate::identity::foreign_dir::is_foreign_to_this_channel)
596}
597
598/// [`resolve_claude_config_dir`] with the "another channel's dir" test given (the process's own
599/// channel is not something a unit test can set).
600pub(crate) fn resolve_claude_config_dir_with(
601    meta: &crate::backend::obj::MetaMapType,
602    agent_id: &str,
603    bound_dir: Option<PathBuf>,
604    is_foreign: impl Fn(&Path) -> bool,
605) -> Option<PathBuf> {
606    if bound_dir.is_some() {
607        return bound_dir;
608    }
609    match crate::backend::blockcontroller::cmd_env_of(meta).remove("CLAUDE_CONFIG_DIR").map(PathBuf::from) {
610        // A snapshot left by a build that kept its accounts under its own channel: not a dir this
611        // agent runs in, and not one to guess a replacement for either. `None` leaves the watch where it is.
612        Some(dir) if is_foreign(&dir) => None,
613        Some(dir) => Some(dir),
614        None => derive_claude_config_dir(agent_id),
615    }
616}
617
618#[cfg(test)]
619mod summary_tests {
620    use super::*;
621    use serde_json::json;
622
623    // The wire shape `swarm-model.ts`'s `SubagentEventType` mirrors: the
624    // structured input, not a pre-formatted string.
625    #[test]
626    fn a_tool_use_line_carries_its_input_structured() {
627        let line = json!({
628            "type": "tool_use",
629            "name": "WebFetch",
630            "input": { "url": "https://example.com/a?b=1", "prompt": "summarise" },
631        });
632        let event = parse_event_type(&line).expect("tool_use parses");
633        assert_eq!(
634            serde_json::to_value(&event).unwrap(),
635            json!({
636                "type": "tool_use",
637                "name": "WebFetch",
638                "input": { "url": "https://example.com/a?b=1", "prompt": "summarise" },
639            })
640        );
641    }
642
643    #[test]
644    fn a_tool_use_line_without_input_carries_null() {
645        let event = parse_event_type(&json!({ "type": "tool_use", "name": "Bash" })).unwrap();
646        assert!(matches!(event, SubagentEventType::ToolUse { input: serde_json::Value::Null, .. }));
647    }
648
649    #[test]
650    fn a_small_input_crosses_unchanged() {
651        let input = json!({ "command": "ls -la", "timeout": 5, "run_in_background": false, "opts": ["a"] });
652        assert_eq!(bounded_tool_input(&input), input);
653    }
654
655    #[test]
656    fn long_string_fields_are_cut_per_field() {
657        // An Edit's file contents is the measured tail; its path must survive.
658        let input = json!({ "file_path": "/x/y.rs", "new_string": "x".repeat(5000) });
659        let got = bounded_tool_input(&input);
660        assert_eq!(got["file_path"], "/x/y.rs");
661        let cut = got["new_string"].as_str().unwrap();
662        assert_eq!(cut.chars().count(), MAX_INPUT_FIELD_CHARS + 3, "cut plus the three-dot marker");
663    }
664
665    #[test]
666    fn a_large_nested_value_becomes_its_cut_json() {
667        let edits: Vec<_> = (0..100).map(|i| json!({ "old_string": i, "new_string": i })).collect();
668        let got = bounded_tool_input(&json!({ "file_path": "/f", "edits": edits }));
669        assert_eq!(got["file_path"], "/f");
670        let cut = got["edits"].as_str().expect("oversized array is replaced by a string");
671        assert!(cut.starts_with("[{"), "{cut}");
672        assert_eq!(cut.chars().count(), MAX_INPUT_FIELD_CHARS + 3);
673    }
674
675    #[test]
676    fn a_non_object_input_is_bounded_too() {
677        assert_eq!(bounded_tool_input(&json!("short")), json!("short"));
678        let got = bounded_tool_input(&json!("é".repeat(MAX_INPUT_FIELD_CHARS + 1)));
679        assert_eq!(got.as_str().unwrap().chars().count(), MAX_INPUT_FIELD_CHARS + 3);
680    }
681
682    #[test]
683    fn a_string_result_is_used_verbatim() {
684        assert_eq!(result_content_text(&json!("plain output")), "plain output");
685    }
686
687    #[test]
688    fn a_block_array_result_falls_back_to_json() {
689        let content = json!([{ "type": "text", "text": "hi" }]);
690        assert_eq!(result_content_text(&content), content.to_string());
691    }
692
693    #[test]
694    fn truncation_counts_chars_and_marks_that_it_cut() {
695        assert_eq!(truncate_chars("abcdef", 3), "abc...");
696        assert_eq!(truncate_chars("abc", 3), "abc", "exact length must not gain an ellipsis");
697        assert_eq!(truncate_chars("ab", 3), "ab");
698    }
699
700    #[test]
701    fn truncation_never_splits_a_multibyte_char() {
702        // The old code tested byte length and cut by char index, so a string
703        // over the byte budget but under the char budget silently escaped
704        // truncation entirely (§4.1 of the report).
705        let s = "é".repeat(150); // 300 bytes, 150 chars
706        assert_eq!(truncate_chars(&s, 200), s, "under the CHAR budget — unchanged");
707        let long = "é".repeat(250);
708        let got = truncate_chars(&long, 200);
709        assert_eq!(got.chars().count(), 203, "200 chars + the three-dot marker");
710    }
711}