Skip to main content

ertangle_core/
lib.rs

1//! `ertangle-core` — Domain model.
2//!
3//! Contains environment-agnostic types only: agent kinds, sessions, events, message bus, tasks.
4//! The daemon, adapter, and TUI all share this set of types, making it the contract for the entire system.
5//!
6//! Design principles:
7//! * **Event is the single source of truth**: all state is the result of folding events into [`State`].
8//! * Events are serializable, persistable, and replayable, enabling TUIs to rebuild views seamlessly after disconnects.
9
10pub mod i18n;
11
12/// Package version with short git commit hash when available.
13pub const VERSION_WITH_HASH: &str = env!("ERTANGLE_VERSION_WITH_HASH");
14
15use serde::{Deserialize, Serialize};
16use std::collections::{BTreeMap, HashMap, VecDeque};
17use std::time::{SystemTime, UNIX_EPOCH};
18use tr::tr;
19
20/// Environment variable prefix for the legacy name (termade); compatibility layer retained until v1.0.
21const LEGACY_ENV_PREFIX: &str = "TERMADE_";
22const ENV_PREFIX: &str = "ERTANGLE_";
23
24/// Maps `ERTANGLE_X` to legacy `TERMADE_X`; names not starting with `ERTANGLE_` have no legacy counterpart.
25fn legacy_env_name(name: &str) -> Option<String> {
26    name.strip_prefix(ENV_PREFIX)
27        .map(|rest| format!("{LEGACY_ENV_PREFIX}{rest}"))
28}
29
30/// Reads environment variable with injected lookup function: reads new name first, falls back to legacy name if unset.
31fn env_lookup<T>(name: &str, get: impl Fn(&str) -> Option<T>) -> Option<T> {
32    get(name).or_else(|| legacy_env_name(name).and_then(|old| get(&old)))
33}
34
35/// Reads environment variable (`ERTANGLE_X`, falling back to legacy `TERMADE_X` if unset); non-unicode values treated as unset.
36pub fn env_var(name: &str) -> Option<String> {
37    env_lookup(name, |k| std::env::var(k).ok())
38}
39
40/// Same as [`env_var`], but returns raw `OsString`.
41pub fn env_var_os(name: &str) -> Option<std::ffi::OsString> {
42    env_lookup(name, |k| std::env::var_os(k))
43}
44
45#[cfg(test)]
46mod env_compat_tests {
47    use super::*;
48    use std::collections::HashMap;
49
50    fn lookup(map: &HashMap<&str, &str>, name: &str) -> Option<String> {
51        env_lookup(name, |k| map.get(k).map(|v| v.to_string()))
52    }
53
54    #[test]
55    fn prefers_new_name() {
56        let m = HashMap::from([("ERTANGLE_X", "new"), ("TERMADE_X", "old")]);
57        assert_eq!(lookup(&m, "ERTANGLE_X").as_deref(), Some("new"));
58    }
59
60    #[test]
61    fn falls_back_to_legacy_name() {
62        let m = HashMap::from([("TERMADE_X", "old")]);
63        assert_eq!(lookup(&m, "ERTANGLE_X").as_deref(), Some("old"));
64    }
65
66    #[test]
67    fn unset_returns_none_and_other_prefixes_have_no_legacy() {
68        let m = HashMap::from([("TERMADE_X", "old")]);
69        assert_eq!(lookup(&m, "ERTANGLE_Y"), None);
70        assert_eq!(lookup(&m, "OTHER_X"), None);
71        assert_eq!(legacy_env_name("HOME"), None);
72    }
73}
74
75/// Current time (Unix epoch milliseconds).
76pub fn now_millis() -> u64 {
77    SystemTime::now()
78        .duration_since(UNIX_EPOCH)
79        .map(|d| d.as_millis() as u64)
80        .unwrap_or(0)
81}
82
83/// Generates a prefixed random ID, e.g. `ses_3f2a…`.
84pub fn new_id(prefix: &str) -> String {
85    let u = uuid::Uuid::new_v4().simple().to_string();
86    format!("{prefix}_{}", &u[..12])
87}
88
89pub type SessionId = String;
90pub type MsgId = String;
91pub type TaskId = String;
92
93/// Monotonic sequence number for each event, used for incremental sync (`since`).
94pub type Seq = u64;
95
96// ---------------------------------------------------------------------------
97// Agent
98// ---------------------------------------------------------------------------
99
100/// Supported agent kinds.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(rename_all = "snake_case")]
103pub enum AgentKind {
104    OpenCode,
105    ClaudeCode,
106    Codex,
107    Antigravity,
108    /// Custom user agent: specifies executable directly.
109    Custom(String),
110}
111
112impl AgentKind {
113    /// Stable identifier (for CLI / configuration).
114    pub fn id(&self) -> &str {
115        match self {
116            AgentKind::OpenCode => "opencode",
117            AgentKind::ClaudeCode => "claude",
118            AgentKind::Codex => "codex",
119            AgentKind::Antigravity => "antigravity",
120            AgentKind::Custom(name) => name,
121        }
122    }
123
124    pub fn parse(s: &str) -> Option<AgentKind> {
125        Some(match s.to_ascii_lowercase().as_str() {
126            "opencode" | "oc" => AgentKind::OpenCode,
127            "claude" | "claude-code" | "claudecode" => AgentKind::ClaudeCode,
128            "codex" => AgentKind::Codex,
129            "antigravity" | "agy" | "gemini" => AgentKind::Antigravity,
130            _ => return None,
131        })
132    }
133
134    /// Four built-in selectable agents (excluding Custom).
135    pub fn builtins() -> [AgentKind; 4] {
136        [
137            AgentKind::OpenCode,
138            AgentKind::ClaudeCode,
139            AgentKind::Codex,
140            AgentKind::Antigravity,
141        ]
142    }
143
144    /// Launch command for interactive mode (PTY passthrough).
145    pub fn pty_command(&self) -> (&str, Vec<&'static str>) {
146        match self {
147            AgentKind::OpenCode => ("opencode", vec![]),
148            AgentKind::ClaudeCode => ("claude", vec![]),
149            AgentKind::Codex => ("codex", vec![]),
150            AgentKind::Antigravity => ("agy", vec![]),
151            AgentKind::Custom(cmd) => (cmd.as_str(), vec![]),
152        }
153    }
154
155    /// Launch command for native structured protocol (if supported).
156    ///
157    /// OpenCode and Antigravity provide native ACP directly (`opencode acp` / `agy acp`),
158    /// without extra npm packages; Claude and Codex use their respective structured interfaces (see adapter crate).
159    pub fn acp_command(&self) -> Option<(&str, Vec<&'static str>)> {
160        match self {
161            AgentKind::OpenCode => Some(("opencode", vec!["acp"])),
162            AgentKind::Antigravity => Some(("agy", vec!["acp"])),
163            _ => None,
164        }
165    }
166}
167
168impl std::fmt::Display for AgentKind {
169    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170        f.write_str(self.id())
171    }
172}
173
174// ---------------------------------------------------------------------------
175// Session
176// ---------------------------------------------------------------------------
177
178/// Role of an agent in this system.
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
180#[serde(rename_all = "snake_case")]
181pub enum Role {
182    /// Breaks down tasks, spawns workers, and integrates results.
183    Coordinator,
184    /// Directly modifies files.
185    #[default]
186    Worker,
187    /// Read-only, responsible for review.
188    Reviewer,
189    Custom(String),
190}
191
192impl Role {
193    pub fn id(&self) -> &str {
194        match self {
195            Role::Coordinator => "coordinator",
196            Role::Worker => "worker",
197            Role::Reviewer => "reviewer",
198            Role::Custom(n) => n,
199        }
200    }
201    pub fn parse(s: &str) -> Role {
202        match s.to_ascii_lowercase().as_str() {
203            "coordinator" | "coord" => Role::Coordinator,
204            "reviewer" | "review" => Role::Reviewer,
205            "worker" => Role::Worker,
206            other => Role::Custom(other.to_string()),
207        }
208    }
209}
210
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
212#[serde(rename_all = "snake_case")]
213pub enum SessionStatus {
214    Starting,
215    Idle,
216    Busy,
217    WaitingApproval,
218    /// Idle sleep (process paused with SIGSTOP, automatically resumed with SIGCONT on new messages or wakeup).
219    Sleeping,
220    Exited,
221    Failed,
222}
223
224impl SessionStatus {
225    /// Single-character indicator for TUI display.
226    pub fn glyph(self) -> &'static str {
227        match self {
228            SessionStatus::Starting => "◌",
229            SessionStatus::Idle => "○",
230            SessionStatus::Busy => "●",
231            SessionStatus::WaitingApproval => "⏸",
232            SessionStatus::Sleeping => "☾",
233            SessionStatus::Exited => "✓",
234            SessionStatus::Failed => "✗",
235        }
236    }
237    pub fn is_live(self) -> bool {
238        !matches!(self, SessionStatus::Exited | SessionStatus::Failed)
239    }
240}
241
242#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
243pub struct Cost {
244    pub usd: f64,
245    pub input_tokens: u64,
246    pub output_tokens: u64,
247}
248
249/// Current context usage of a session (tokens used by conversation and the model context window).
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
251pub struct ContextUsage {
252    pub used: u64,
253    /// Model context window size; `None` when the agent has not yet reported.
254    pub window: Option<u64>,
255}
256
257impl ContextUsage {
258    pub fn percent(&self) -> Option<f32> {
259        self.window
260            .filter(|w| *w > 0)
261            .map(|w| self.used as f32 * 100.0 / w as f32)
262    }
263
264    /// `36k/1M 4%`; displays only `36k` when window size is unknown.
265    pub fn short(&self) -> String {
266        match (self.window, self.percent()) {
267            (Some(w), Some(p)) => {
268                format!("{}/{} {:.0}%", human_tokens(self.used), human_tokens(w), p)
269            }
270            _ => human_tokens(self.used),
271        }
272    }
273}
274
275/// Short representation of token count: `950`, `36k`, `1.5M`.
276pub fn human_tokens(n: u64) -> String {
277    match n {
278        0..=999 => n.to_string(),
279        1_000..=999_999 => format!("{}k", (n as f64 / 1000.0).round() as u64),
280        _ => {
281            let m = n as f64 / 1_000_000.0;
282            if (m - m.round()).abs() < 0.05 {
283                format!("{}M", m.round() as u64)
284            } else {
285                format!("{m:.1}M")
286            }
287        }
288    }
289}
290
291/// Formats USD budget into short string: omits decimals for whole amounts (`$5`), otherwise retains two decimals (`$2.50`).
292pub fn format_usd_limit(limit: f64) -> String {
293    if (limit - limit.round()).abs() < 1e-6 {
294        format!("${:.0}", limit)
295    } else {
296        format!("${:.2}", limit)
297    }
298}
299
300/// A running instance of an agent.
301#[derive(Debug, Clone, Serialize, Deserialize)]
302pub struct Session {
303    pub id: SessionId,
304    pub kind: AgentKind,
305    /// Human-readable label, e.g. `worker/eu-zip`.
306    pub label: String,
307    /// Working directory (may be a worktree path).
308    pub cwd: String,
309    /// Records branch name if within a worktree.
310    pub branch: Option<String>,
311    pub role: Role,
312    pub status: SessionStatus,
313    pub model: Option<String>,
314    pub cost: Cost,
315    /// Creator (human or session ID).
316    pub parent: Option<SessionId>,
317    pub created_ms: u64,
318    /// Transport used by adapter (for display).
319    pub transport: String,
320    /// Short progress note reported by the agent via `ertangle_status`.
321    #[serde(default)]
322    pub status_note: Option<String>,
323    /// Root directory of the main repo when creating a worktree (for merge/gc/pr).
324    #[serde(default)]
325    pub repo_root: Option<String>,
326    /// Permission policy for this session (`auto` if absent in older logs).
327    #[serde(default)]
328    pub permission: PermissionPolicy,
329    /// Context usage (reported by agent; absent in older logs).
330    #[serde(default)]
331    pub context: Option<ContextUsage>,
332    /// Native conversation ID of the agent (Claude session id, Codex thread id, ACP sessionId) for resumption.
333    /// `None` indicates this session cannot be resumed (older logs, PTY, or agent did not declare load capability).
334    #[serde(default)]
335    pub native_id: Option<String>,
336    /// Cost limit for this session (USD; resolved actual limit).
337    #[serde(default)]
338    pub budget_usd: Option<f64>,
339    /// Whether the cost limit has been reached (interrupts turn and rejects new prompts until manually raised).
340    #[serde(default)]
341    pub over_budget: bool,
342    /// Successor session (set by `Event::SessionHandedOff` after handoff; absent in older logs).
343    #[serde(default)]
344    pub handed_off_to: Option<SessionId>,
345    /// Current reasoning effort (resolved at startup or updated at runtime; absent in older logs).
346    #[serde(default)]
347    pub effort: Option<String>,
348    /// Native slash commands reported by agent (without `/`; Claude `slash_commands`, ACP `available_commands_update`).
349    #[serde(default)]
350    pub slash_commands: Vec<String>,
351    /// Currently executing tools or subagents.
352    #[serde(default)]
353    pub active_tools: Vec<ActiveTool>,
354    /// List of remaining background child processes.
355    #[serde(default)]
356    pub bg_procs: Vec<BgProc>,
357    /// Cumulative tool call count (counts start events only; approximate turn count, absent in older logs).
358    #[serde(default)]
359    pub tool_calls: u32,
360    /// When the session last stopped being live (ms since epoch). Drives the retention
361    /// clocks for ended sessions and archived entries; absent in older logs.
362    #[serde(default)]
363    pub ended_ms: Option<u64>,
364}
365
366impl Session {
367    /// Time the session ended, falling back to creation time for older logs.
368    pub fn ended_or_created_ms(&self) -> u64 {
369        self.ended_ms.unwrap_or(self.created_ms)
370    }
371
372    /// Which project this session belongs to: main repo for worktrees, otherwise working directory.
373    pub fn project_root(&self) -> &str {
374        self.repo_root.as_deref().unwrap_or(&self.cwd)
375    }
376
377    /// Returns string formatted as `$1.20/$5` when cost limit is configured.
378    pub fn format_budget(&self) -> Option<String> {
379        self.budget_usd
380            .map(|limit| format!("${:.2}/{}", self.cost.usd, format_usd_limit(limit)))
381    }
382}
383
384/// Currently executing tool or subagent.
385#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
386pub struct ActiveTool {
387    pub name: String,
388    pub summary: String,
389    pub started_ms: u64,
390    pub is_subagent: bool,
391}
392
393/// Remaining background child process.
394#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
395pub struct BgProc {
396    pub pid: u32,
397    pub name: String,
398    pub cmdline: String,
399    #[serde(default)]
400    pub elapsed_secs: u64,
401}
402
403/// Checks if a tool name represents a native subagent tool.
404pub fn is_subagent_tool(name: &str) -> bool {
405    let lower = name.to_ascii_lowercase();
406    matches!(
407        lower.as_str(),
408        "task" | "agent" | "dispatch_agent" | "invoke_subagent" | "spawn_agent" | "subagent"
409    )
410}
411
412// ---------------------------------------------------------------------------
413// Bus / Task / Artifact
414// ---------------------------------------------------------------------------
415
416/// Recipient of a message.
417#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
418#[serde(rename_all = "snake_case")]
419pub enum Target {
420    Direct(SessionId),
421    Channel(String),
422    Broadcast,
423}
424
425impl Target {
426    /// Parses recipient target from string:
427    /// * `*` or `broadcast` -> [`Target::Broadcast`]
428    /// * `#name` or `channel:name` -> [`Target::Channel`]
429    /// * `@id` or other string -> [`Target::Direct`]
430    pub fn parse(s: &str) -> Target {
431        let s = s.trim();
432        if s == "*" || s.eq_ignore_ascii_case("broadcast") {
433            Target::Broadcast
434        } else if let Some(ch) = s.strip_prefix('#').or_else(|| s.strip_prefix("channel:")) {
435            Target::Channel(ch.to_string())
436        } else if let Some(d) = s.strip_prefix('@') {
437            Target::Direct(d.to_string())
438        } else {
439            Target::Direct(s.to_string())
440        }
441    }
442}
443
444#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
445#[serde(rename_all = "snake_case")]
446pub enum MsgKind {
447    #[default]
448    Chat,
449    /// Hands off task.
450    Handoff,
451    Question,
452    Answer,
453    Status,
454    /// Shares artifacts (file / branch / diff).
455    Artifact,
456}
457
458impl MsgKind {
459    pub fn id(self) -> &'static str {
460        match self {
461            MsgKind::Chat => "chat",
462            MsgKind::Handoff => "handoff",
463            MsgKind::Question => "question",
464            MsgKind::Answer => "answer",
465            MsgKind::Status => "status",
466            MsgKind::Artifact => "artifact",
467        }
468    }
469
470    pub fn parse(s: &str) -> Option<MsgKind> {
471        Some(match s.to_ascii_lowercase().as_str() {
472            "chat" | "message" => MsgKind::Chat,
473            "handoff" => MsgKind::Handoff,
474            "question" | "ask" => MsgKind::Question,
475            "answer" | "reply" => MsgKind::Answer,
476            "status" => MsgKind::Status,
477            "artifact" => MsgKind::Artifact,
478            _ => return None,
479        })
480    }
481}
482
483#[derive(Debug, Clone, Serialize, Deserialize)]
484pub struct BusMessage {
485    pub id: MsgId,
486    pub from: SessionId,
487    pub to: Target,
488    #[serde(default)]
489    pub kind: MsgKind,
490    pub body: String,
491    pub reply_to: Option<MsgId>,
492    pub ts: u64,
493}
494
495impl BusMessage {
496    /// Whether this message should enter a specific session's inbox.
497    ///
498    /// * Broadcast/channel messages sent by self are not delivered to own inbox.
499    /// * `Direct` matches both `session_id` and human-readable `label`.
500    pub fn matches_recipient(&self, session_id: &str, label: Option<&str>) -> bool {
501        match &self.to {
502            Target::Broadcast | Target::Channel(_) => self.from != session_id,
503            Target::Direct(target) => target == session_id || label.is_some_and(|l| l == target),
504        }
505    }
506}
507
508#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
509#[serde(rename_all = "snake_case")]
510pub enum TaskStatus {
511    Todo,
512    Doing,
513    Blocked,
514    Review,
515    Done,
516}
517
518impl TaskStatus {
519    pub fn id(self) -> &'static str {
520        match self {
521            TaskStatus::Todo => "todo",
522            TaskStatus::Doing => "doing",
523            TaskStatus::Blocked => "blocked",
524            TaskStatus::Review => "review",
525            TaskStatus::Done => "done",
526        }
527    }
528
529    pub fn parse(s: &str) -> Option<TaskStatus> {
530        Some(match s.to_ascii_lowercase().as_str() {
531            "todo" | "open" => TaskStatus::Todo,
532            "doing" | "in_progress" | "in-progress" | "working" => TaskStatus::Doing,
533            "blocked" => TaskStatus::Blocked,
534            "review" => TaskStatus::Review,
535            "done" | "completed" | "closed" => TaskStatus::Done,
536            _ => return None,
537        })
538    }
539}
540
541#[derive(Debug, Clone, Serialize, Deserialize)]
542pub struct Task {
543    pub id: TaskId,
544    pub title: String,
545    #[serde(default)]
546    pub detail: String,
547    pub status: TaskStatus,
548    pub assignee: Option<SessionId>,
549    #[serde(default)]
550    pub created_by: Option<SessionId>,
551    #[serde(default)]
552    pub depends_on: Vec<TaskId>,
553    pub updated_ms: u64,
554}
555
556#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
557#[serde(rename_all = "snake_case")]
558pub enum ArtifactKind {
559    #[default]
560    File,
561    Branch,
562    Diff,
563}
564
565impl ArtifactKind {
566    pub fn id(self) -> &'static str {
567        match self {
568            ArtifactKind::File => "file",
569            ArtifactKind::Branch => "branch",
570            ArtifactKind::Diff => "diff",
571        }
572    }
573
574    pub fn parse(s: &str) -> Option<ArtifactKind> {
575        Some(match s.to_ascii_lowercase().as_str() {
576            "file" | "path" => ArtifactKind::File,
577            "branch" => ArtifactKind::Branch,
578            "diff" | "patch" => ArtifactKind::Diff,
579            _ => return None,
580        })
581    }
582}
583
584/// Artifact shared by agent (file, branch, or diff).
585#[derive(Debug, Clone, Serialize, Deserialize)]
586pub struct Artifact {
587    pub id: String,
588    pub session: SessionId,
589    pub kind: ArtifactKind,
590    pub path: String,
591    #[serde(default)]
592    pub note: String,
593    pub ts: u64,
594}
595
596/// Inline review comment on a diff line (M3 review loop).
597#[derive(Debug, Clone, Serialize, Deserialize)]
598pub struct ReviewComment {
599    pub id: String,
600    pub session: SessionId,
601    /// File and line number or summary of diff line content.
602    pub location: String,
603    pub comment: String,
604    pub ts: u64,
605}
606
607/// Worktree summary information (M3 workspace management).
608#[derive(Debug, Clone, Serialize, Deserialize)]
609pub struct WorktreeInfo {
610    pub session: SessionId,
611    pub label: String,
612    pub path: String,
613    pub branch: String,
614    pub live: bool,
615    pub changed_files: usize,
616    pub summary: String,
617}
618
619// ---------------------------------------------------------------------------
620// Permissions
621// ---------------------------------------------------------------------------
622
623/// Unified permission policy: determines whether agent tool execution requires human approval.
624///
625/// Each adapter translates this policy into its protocol-supported form:
626/// * ACP (OpenCode / Antigravity): `Ask` = forwards `session/request_permission`;
627///   `Auto` / `Bypass` = auto-approved directly by adapter.
628/// * Claude: maps to `--permission-mode` flags.
629/// * Codex: maps to `approvalPolicy` in `thread/start`.
630#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
631#[serde(rename_all = "snake_case")]
632pub enum PermissionPolicy {
633    /// Prompts for each item (ACP forwards requests to client; unsupported protocols remain conservative).
634    Ask,
635    /// Auto-approves safe operations (default): does not interrupt workflows while maintaining protocol boundaries.
636    #[default]
637    Auto,
638    /// Bypasses all permission checks; agent can perform any operation (dangerous).
639    Bypass,
640}
641
642impl PermissionPolicy {
643    /// Permissiveness: `ask` < `auto` < `bypass`.
644    pub fn rank(&self) -> u8 {
645        match self {
646            PermissionPolicy::Ask => 0,
647            PermissionPolicy::Auto => 1,
648            PermissionPolicy::Bypass => 2,
649        }
650    }
651
652    /// Takes the more restrictive of the two.
653    pub fn min_policy(self, other: PermissionPolicy) -> PermissionPolicy {
654        if other.rank() < self.rank() {
655            other
656        } else {
657            self
658        }
659    }
660
661    pub fn id(&self) -> &'static str {
662        match self {
663            PermissionPolicy::Ask => "ask",
664            PermissionPolicy::Auto => "auto",
665            PermissionPolicy::Bypass => "bypass",
666        }
667    }
668
669    pub fn parse(s: &str) -> Option<PermissionPolicy> {
670        Some(match s.to_ascii_lowercase().as_str() {
671            "ask" | "manual" => PermissionPolicy::Ask,
672            "auto" | "accept-edits" | "acceptedits" => PermissionPolicy::Auto,
673            "bypass" | "yolo" | "dangerous" => PermissionPolicy::Bypass,
674            _ => return None,
675        })
676    }
677
678    /// Whether the adapter auto-approves requests directly (without forwarding to human).
679    pub fn auto_approves(&self) -> bool {
680        matches!(self, PermissionPolicy::Auto | PermissionPolicy::Bypass)
681    }
682
683    /// CLI flags for Claude Code.
684    pub fn claude_flags(&self) -> Vec<&'static str> {
685        match self {
686            PermissionPolicy::Ask => vec!["--permission-mode", "manual"],
687            PermissionPolicy::Auto => vec!["--permission-mode", "acceptEdits"],
688            PermissionPolicy::Bypass => vec!["--dangerously-skip-permissions"],
689        }
690    }
691
692    /// CLI flags for Codex app-server.
693    ///
694    /// `codex app-server` does not accept permission settings via CLI flags; it uses
695    /// `approvalPolicy` (see [`PermissionPolicy::codex_approval_policy`]), so this is always empty.
696    pub fn codex_flags(&self) -> Vec<&'static str> {
697        vec![]
698    }
699
700    /// `approvalPolicy` value for Codex `thread/start`.
701    pub fn codex_approval_policy(&self) -> &'static str {
702        match self {
703            PermissionPolicy::Ask => "untrusted",
704            PermissionPolicy::Auto => "on-request",
705            PermissionPolicy::Bypass => "never",
706        }
707    }
708}
709
710impl std::fmt::Display for PermissionPolicy {
711    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
712        f.write_str(self.id())
713    }
714}
715
716#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
717#[serde(rename_all = "snake_case")]
718pub enum Decision {
719    Allow,
720    /// Always allows similar requests within this session.
721    AllowAlways,
722    Deny,
723}
724
725/// Single option for interactive user question.
726#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
727pub struct QuestionOption {
728    pub label: String,
729    #[serde(default, skip_serializing_if = "Option::is_none")]
730    pub description: Option<String>,
731    /// Value submitted to the agent when this option is selected. Defaults to `label`.
732    #[serde(default, skip_serializing_if = "Option::is_none")]
733    pub value: Option<String>,
734}
735
736impl QuestionOption {
737    pub fn new(label: impl Into<String>, description: Option<&str>) -> Self {
738        Self {
739            label: label.into(),
740            description: description.map(str::to_string),
741            value: None,
742        }
743    }
744
745    pub fn plain(label: impl Into<String>) -> Self {
746        Self {
747            label: label.into(),
748            description: None,
749            value: None,
750        }
751    }
752
753    /// Builds an option whose submitted value differs from its display label.
754    pub fn with_value(
755        label: impl Into<String>,
756        description: Option<&str>,
757        value: impl Into<String>,
758    ) -> Self {
759        Self {
760            label: label.into(),
761            description: description.map(str::to_string),
762            value: Some(value.into()),
763        }
764    }
765}
766
767/// Normalized interactive question from agent to user.
768#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
769pub struct UserQuestion {
770    /// Internal request ID (e.g. `qst_...`), returned when answered.
771    pub id: String,
772    pub session: SessionId,
773    #[serde(default, skip_serializing_if = "Option::is_none")]
774    pub header: Option<String>,
775    pub question: String,
776    #[serde(default)]
777    pub options: Vec<QuestionOption>,
778    #[serde(default)]
779    pub multi_select: bool,
780    #[serde(default)]
781    pub custom: bool,
782    /// Groups questions that must be answered or dismissed together.
783    #[serde(default, skip_serializing_if = "Option::is_none")]
784    pub group: Option<String>,
785}
786
787/// Answer payload for an interactive user question.
788#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
789pub struct QuestionAnswer {
790    pub id: String,
791    pub session: SessionId,
792    pub answers: Vec<String>,
793}
794
795/// Normalized permission request sent by agent (regardless of source protocol).
796#[derive(Debug, Clone, Serialize, Deserialize)]
797pub struct PermissionRequest {
798    /// Internal request ID for adapter, returned upon reply.
799    pub req: String,
800    pub session: SessionId,
801    /// Short title, e.g. `Bash`, `Edit`.
802    pub title: String,
803    /// Details (command, path, diff summary).
804    pub detail: String,
805}
806
807// ---------------------------------------------------------------------------
808// Event
809// ---------------------------------------------------------------------------
810
811/// System events. Append-only, serializable, replayable.
812#[derive(Debug, Clone, Serialize, Deserialize)]
813#[serde(tag = "kind", rename_all = "snake_case")]
814#[allow(clippy::large_enum_variant)]
815pub enum Event {
816    /// Complete state written to first line of new log file after rotation; replay begins from here. seq inherits value from rotation time.
817    Snapshot {
818        state: Box<State>,
819    },
820    SessionStarted {
821        session: Session,
822    },
823    SessionStatus {
824        session: SessionId,
825        status: SessionStatus,
826    },
827    /// Agent reports session context usage.
828    SessionContext {
829        session: SessionId,
830        used: u64,
831        window: Option<u64>,
832    },
833    /// Agent reports account quota (usage percentage and reset time).
834    QuotaUpdated {
835        quota: Quota,
836    },
837    /// Agent reports quota exhausted / rate limited (can hand off to other agents).
838    SessionLimited {
839        session: SessionId,
840        detail: String,
841    },
842    /// Session removed from list (startup failure or user cleared terminated session).
843    SessionRemoved {
844        session: SessionId,
845    },
846    /// Archived sessions dropped by retention (count or age limit).
847    ArchivePruned {
848        sessions: Vec<SessionId>,
849    },
850    /// Actual model reported by agent (or specified in settings).
851    SessionModel {
852        session: SessionId,
853        model: String,
854    },
855    /// Native slash commands reported by agent.
856    SessionCommands {
857        session: SessionId,
858        commands: Vec<String>,
859    },
860    /// Reasoning effort switched at runtime (or configured at startup).
861    SessionEffort {
862        session: SessionId,
863        effort: String,
864    },
865    /// Native conversation ID reported by agent (for resumption).
866    SessionNativeId {
867        session: SessionId,
868        native_id: String,
869    },
870    /// Context reset (`Request::Clear`): the agent restarts with a fresh native conversation
871    /// under the same ertangle session id. Drops native id, cost, context, transcript and live tool state.
872    SessionCleared {
873        session: SessionId,
874    },
875    SessionLabel {
876        session: SessionId,
877        label: String,
878    },
879    /// Short status note updated by agent via `ertangle_status`.
880    SessionNote {
881        session: SessionId,
882        note: String,
883    },
884    /// Handoff complete: `to` takes over work from `from` (bus messages are routed to successor).
885    SessionHandedOff {
886        from: SessionId,
887        to: SessionId,
888    },
889    /// Prompt sent to agent (displayed in transcript for conversational context).
890    UserPrompt {
891        session: SessionId,
892        text: String,
893        /// Sender: `None` = user; otherwise sender agent session ID, or [`PROMPT_FROM_ERTANGLE`]
894        /// (daemon-generated reminders, notifications, and handoff briefs).
895        #[serde(default, skip_serializing_if = "Option::is_none")]
896        from: Option<String>,
897    },
898    /// Text output from agent (streaming chunk or complete line).
899    Output {
900        session: SessionId,
901        text: String,
902    },
903    /// Continuation of an unterminated [`Event::Output`] line: the first segment of `text`
904    /// is appended to the last transcript line instead of starting a new one.
905    OutputAppend {
906        session: SessionId,
907        text: String,
908    },
909    /// A session's inbox read cursor advanced to `msg` (persisted so restarts do not redeliver).
910    InboxRead {
911        session: SessionId,
912        msg: String,
913    },
914    /// Session background child process list updated.
915    SessionBgProcs {
916        session: SessionId,
917        procs: Vec<BgProc>,
918    },
919    ToolCall {
920        session: SessionId,
921        name: String,
922        #[serde(default)]
923        input: String,
924        /// `None` = in progress; `Some(true/false)` = completed with success/failure.
925        ok: Option<bool>,
926        #[serde(default)]
927        output: Option<String>,
928    },
929    PermissionRequested {
930        request: PermissionRequest,
931    },
932    PermissionResolved {
933        session: SessionId,
934        req: String,
935        decision: Decision,
936    },
937    QuestionRequested {
938        question: UserQuestion,
939    },
940    QuestionResolved {
941        session: SessionId,
942        id: String,
943        #[serde(default)]
944        answers: Vec<String>,
945    },
946    BusMessage {
947        message: BusMessage,
948    },
949    TaskChanged {
950        task: Task,
951    },
952    ArtifactShared {
953        artifact: Artifact,
954    },
955    ReviewCommented {
956        review: ReviewComment,
957    },
958    SessionExited {
959        session: SessionId,
960        code: Option<i32>,
961    },
962    Cost {
963        session: SessionId,
964        cost: Cost,
965    },
966    /// Session reached cost limit (interrupted current turn and set `over_budget` to `true`).
967    SessionOverBudget {
968        session: SessionId,
969        spent: f64,
970        limit: f64,
971    },
972    /// Manually adjusted session cost limit (also clears `over_budget`).
973    SessionBudget {
974        session: SessionId,
975        budget_usd: Option<f64>,
976    },
977    /// Event log write health status (`ok == false` indicates write failure, TUI displays `log ✗`).
978    LogHealth {
979        ok: bool,
980    },
981    /// Session queued prompts changed (`items` contains raw input text list, excluding attachment content).
982    QueueChanged {
983        session: SessionId,
984        items: Vec<String>,
985    },
986}
987
988/// Event + sequence number + timestamp; unit of external communication (socket / log).
989#[derive(Debug, Clone, Serialize, Deserialize)]
990pub struct Record {
991    pub seq: Seq,
992    pub ts: u64,
993    #[serde(flatten)]
994    pub event: Event,
995}
996
997// ---------------------------------------------------------------------------
998// State: fold result of events
999// ---------------------------------------------------------------------------
1000
1001/// Maximum transcript lines retained per session (prevents memory growth on long conversations).
1002pub const TRANSCRIPT_CAP: usize = 4000;
1003/// Value of `UserPrompt.from`: daemon-generated prompt (unread reminder, conflict notification, handoff brief, auto-resume).
1004pub const PROMPT_FROM_ERTANGLE: &str = "ertangle";
1005/// Prefix for the first line of user prompts in transcript.
1006pub const USER_PROMPT_MARK: &str = "❯ ";
1007/// Prefix for the first line of non-user prompts (other agents or ertangle) in transcript, followed by `[source] `.
1008pub const OTHER_PROMPT_MARK: &str = "» ";
1009
1010/// If a transcript line is the first line of a prompt, returns (source name, `None` = user; prompt text).
1011pub fn parse_prompt_line(line: &str) -> Option<(Option<&str>, &str)> {
1012    if let Some(rest) = line.strip_prefix(USER_PROMPT_MARK) {
1013        return Some((None, rest));
1014    }
1015    let rest = line.strip_prefix(OTHER_PROMPT_MARK)?.strip_prefix('[')?;
1016    let (name, text) = rest.split_once("] ")?;
1017    Some((Some(name), text))
1018}
1019/// Default maximum retained archived sessions with `native_id` (for browsing in resumption selector).
1020pub const ARCHIVED_SESSIONS_CAP: usize = 100;
1021/// Default maximum age of archived sessions, counted from when they ended.
1022pub const ARCHIVED_MAX_DAYS: u64 = 30;
1023/// Maximum transcript lines retained for archived historical sessions.
1024pub const ARCHIVED_TRANSCRIPT_CAP: usize = 200;
1025/// Maximum retained bus messages.
1026pub const MESSAGE_CAP: usize = 1000;
1027/// Maximum retained artifacts.
1028pub const ARTIFACT_CAP: usize = 500;
1029
1030fn default_true() -> bool {
1031    true
1032}
1033
1034#[derive(Debug, Clone, Serialize, Deserialize)]
1035pub struct State {
1036    pub seq: Seq,
1037    pub sessions: BTreeMap<SessionId, Session>,
1038    /// Historical sessions removed from active list with `native_id` (for resuming original conversation).
1039    #[serde(default)]
1040    pub archived_sessions: BTreeMap<SessionId, Session>,
1041    pub tasks: BTreeMap<TaskId, Task>,
1042    pub messages: Vec<BusMessage>,
1043    #[serde(default)]
1044    pub artifacts: Vec<Artifact>,
1045    #[serde(default)]
1046    pub reviews: Vec<ReviewComment>,
1047    /// Pending approval requests.
1048    pub pending_permissions: BTreeMap<String, PermissionRequest>,
1049    /// Pending interactive user questions.
1050    #[serde(default)]
1051    pub pending_questions: BTreeMap<String, UserQuestion>,
1052    /// Session ID -> output text lines.
1053    pub transcripts: HashMap<SessionId, VecDeque<String>>,
1054    /// Event log write health status (defaults to normal).
1055    #[serde(default = "default_true")]
1056    pub log_ok: bool,
1057    /// Latest quota reported by each agent (agent ID -> quota).
1058    #[serde(default)]
1059    pub quotas: BTreeMap<String, Quota>,
1060    /// Queued raw prompt text list per session (session ID -> items).
1061    #[serde(default)]
1062    pub queues: BTreeMap<SessionId, Vec<String>>,
1063    /// Last bus message id already delivered to each session (session ID -> message ID).
1064    #[serde(default)]
1065    pub inbox_cursors: BTreeMap<SessionId, String>,
1066}
1067
1068impl Default for State {
1069    fn default() -> Self {
1070        State {
1071            seq: 0,
1072            sessions: BTreeMap::new(),
1073            archived_sessions: BTreeMap::new(),
1074            tasks: BTreeMap::new(),
1075            messages: Vec::new(),
1076            artifacts: Vec::new(),
1077            reviews: Vec::new(),
1078            pending_permissions: BTreeMap::new(),
1079            pending_questions: BTreeMap::new(),
1080            transcripts: HashMap::new(),
1081            log_ok: true,
1082            quotas: BTreeMap::new(),
1083            queues: BTreeMap::new(),
1084            inbox_cursors: BTreeMap::new(),
1085        }
1086    }
1087}
1088
1089impl State {
1090    pub fn new() -> Self {
1091        Self::default()
1092    }
1093
1094    /// Drops pending questions owned by a session that exited or was removed.
1095    fn remove_session_questions(&mut self, session: &str) {
1096        let ids: Vec<String> = self
1097            .pending_questions
1098            .values()
1099            .filter(|q| q.session == session)
1100            .map(|q| q.id.clone())
1101            .collect();
1102        for id in ids {
1103            self.pending_questions.remove(&id);
1104        }
1105    }
1106
1107    fn push_transcript_line(&mut self, session: &str, line: String) {
1108        let buf = self.transcripts.entry(session.to_string()).or_default();
1109        buf.push_back(line);
1110        while buf.len() > TRANSCRIPT_CAP {
1111            buf.pop_front();
1112        }
1113    }
1114
1115    /// Moves terminated session from active list; archives to `archived_sessions` if possessing `native_id` for future resumption.
1116    pub fn archive_session(&mut self, session: &str) {
1117        self.remove_session_questions(session);
1118        if let Some(mut s) = self.sessions.remove(session) {
1119            if s.native_id.is_some() {
1120                s.status = SessionStatus::Exited;
1121                s.active_tools.clear();
1122                s.bg_procs.clear();
1123                let need_summary = s
1124                    .status_note
1125                    .as_deref()
1126                    .is_none_or(|n| n.is_empty() || n.contains(":resume"));
1127                if need_summary {
1128                    if let Some(last_prompt) = self.transcripts.get(session).and_then(|buf| {
1129                        buf.iter()
1130                            .rev()
1131                            .find_map(|line| parse_prompt_line(line).map(|(_, t)| t))
1132                    }) {
1133                        let snippet: String = last_prompt.trim().chars().take(80).collect();
1134                        if !snippet.is_empty() {
1135                            s.status_note = Some(snippet);
1136                        }
1137                    }
1138                }
1139                if let Some(buf) = self.transcripts.get_mut(session) {
1140                    while buf.len() > ARCHIVED_TRANSCRIPT_CAP {
1141                        buf.pop_front();
1142                    }
1143                }
1144                self.archived_sessions.insert(session.to_string(), s);
1145            } else {
1146                self.transcripts.remove(session);
1147            }
1148        } else {
1149            self.transcripts.remove(session);
1150        }
1151        self.queues.remove(session);
1152        self.pending_permissions.retain(|_, p| p.session != session);
1153        self.pending_questions.retain(|_, q| q.session != session);
1154    }
1155
1156    /// Archived session ids that exceed the retention limits: older than `max_days`
1157    /// (counted from when they ended) or beyond the newest `max_count` entries.
1158    pub fn archived_to_prune(
1159        &self,
1160        now_ms: u64,
1161        max_count: usize,
1162        max_days: u64,
1163    ) -> Vec<SessionId> {
1164        let max_age_ms = max_days.saturating_mul(86_400_000);
1165        let mut by_age: Vec<(&SessionId, u64)> = self
1166            .archived_sessions
1167            .iter()
1168            .map(|(id, s)| (id, s.ended_or_created_ms()))
1169            .collect();
1170        // Newest first; ties broken by id for determinism.
1171        by_age.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
1172        by_age
1173            .into_iter()
1174            .enumerate()
1175            .filter(|(i, (_, ended))| *i >= max_count || now_ms.saturating_sub(*ended) > max_age_ms)
1176            .map(|(_, (id, _))| id.clone())
1177            .collect()
1178    }
1179
1180    /// Applies an event to state. `rec.seq` updates `self.seq`.
1181    pub fn apply(&mut self, rec: &Record) {
1182        self.seq = self.seq.max(rec.seq);
1183        match &rec.event {
1184            Event::Snapshot { state } => {
1185                *self = (**state).clone();
1186                self.seq = rec.seq;
1187            }
1188            Event::SessionStarted { session } => {
1189                self.archived_sessions.remove(&session.id);
1190                let mut session = session.clone();
1191                if session.status.is_live() {
1192                    session.ended_ms = None;
1193                }
1194                self.sessions.insert(session.id.clone(), session);
1195            }
1196            Event::SessionStatus { session, status } => {
1197                if let Some(s) = self.sessions.get_mut(session) {
1198                    s.status = *status;
1199                    s.ended_ms = if status.is_live() {
1200                        None
1201                    } else {
1202                        s.ended_ms.or(Some(rec.ts))
1203                    };
1204                    if *status != SessionStatus::Busy && *status != SessionStatus::WaitingApproval {
1205                        s.active_tools.clear();
1206                    }
1207                }
1208            }
1209            Event::InboxRead { session, msg } => {
1210                self.inbox_cursors.insert(session.clone(), msg.clone());
1211            }
1212            Event::SessionBgProcs { session, procs } => {
1213                if let Some(s) = self.sessions.get_mut(session) {
1214                    s.bg_procs = procs.clone();
1215                }
1216            }
1217            Event::SessionContext {
1218                session,
1219                used,
1220                window,
1221            } => {
1222                if let Some(s) = self.sessions.get_mut(session) {
1223                    // Window size is updated only when reported by agent; reuses previous size otherwise.
1224                    let window = window.or(s.context.and_then(|c| c.window));
1225                    // used == 0 indicates window size update only; reuses previous usage.
1226                    let used = if *used == 0 {
1227                        s.context.map_or(0, |c| c.used)
1228                    } else {
1229                        *used
1230                    };
1231                    s.context = Some(ContextUsage { used, window });
1232                }
1233            }
1234            Event::QuotaUpdated { quota } => {
1235                self.quotas.insert(quota.agent.clone(), quota.clone());
1236            }
1237            Event::SessionLimited { session, detail } => {
1238                if let Some(s) = self.sessions.get_mut(session) {
1239                    s.status = SessionStatus::Failed;
1240                    s.ended_ms = s.ended_ms.or(Some(rec.ts));
1241                    let d: String = detail.chars().take(80).collect();
1242                    s.status_note = Some(tr!("額度用完:{d} (可用 handoff 交接)", d = d));
1243                }
1244            }
1245            Event::SessionRemoved { session } => {
1246                self.archive_session(session);
1247            }
1248            Event::ArchivePruned { sessions } => {
1249                for id in sessions {
1250                    self.archived_sessions.remove(id);
1251                    self.transcripts.remove(id);
1252                }
1253            }
1254            Event::SessionModel { session, model } => {
1255                if let Some(s) = self.sessions.get_mut(session) {
1256                    s.model = Some(model.clone());
1257                }
1258            }
1259            Event::SessionCommands { session, commands } => {
1260                if let Some(s) = self.sessions.get_mut(session) {
1261                    s.slash_commands = commands.clone();
1262                }
1263            }
1264            Event::SessionEffort { session, effort } => {
1265                if let Some(s) = self.sessions.get_mut(session) {
1266                    s.effort = Some(effort.clone());
1267                }
1268            }
1269            Event::SessionNativeId { session, native_id } => {
1270                if let Some(s) = self.sessions.get_mut(session) {
1271                    s.native_id = Some(native_id.clone());
1272                }
1273            }
1274            Event::SessionCleared { session } => {
1275                self.remove_session_questions(session);
1276                self.pending_permissions
1277                    .retain(|_, p| p.session != *session);
1278                self.transcripts.remove(session);
1279                if let Some(s) = self.sessions.get_mut(session) {
1280                    s.native_id = None;
1281                    s.cost = Cost::default();
1282                    s.context = None;
1283                    s.status_note = None;
1284                    s.slash_commands.clear();
1285                    s.active_tools.clear();
1286                    s.bg_procs.clear();
1287                    s.tool_calls = 0;
1288                    s.over_budget = false;
1289                }
1290            }
1291            Event::SessionLabel { session, label } => {
1292                if let Some(s) = self.sessions.get_mut(session) {
1293                    s.label = label.clone();
1294                }
1295            }
1296            Event::SessionNote { session, note } => {
1297                if let Some(s) = self.sessions.get_mut(session) {
1298                    s.status_note = if note.is_empty() {
1299                        None
1300                    } else {
1301                        Some(note.clone())
1302                    };
1303                }
1304            }
1305            Event::SessionHandedOff { from, to } => {
1306                if let Some(s) = self.sessions.get_mut(from) {
1307                    s.handed_off_to = Some(to.clone());
1308                }
1309            }
1310            Event::UserPrompt {
1311                session,
1312                text,
1313                from,
1314            } => {
1315                // Prefix first line: `❯ ` for user, `» [source] ` for other sources (agent shown by label);
1316                // indent subsequent lines of multi-line prompts.
1317                let head = match from {
1318                    None => USER_PROMPT_MARK.to_string(),
1319                    Some(f) => {
1320                        let name = self
1321                            .sessions
1322                            .get(f)
1323                            .map(|s| s.label.clone())
1324                            .unwrap_or_else(|| f.clone());
1325                        format!("{OTHER_PROMPT_MARK}[{name}] ")
1326                    }
1327                };
1328                let buf = self.transcripts.entry(session.clone()).or_default();
1329                let text = text.trim_end_matches('\n');
1330                if !text.is_empty() {
1331                    for (i, line) in text.split('\n').enumerate() {
1332                        if i == 0 {
1333                            buf.push_back(format!("{head}{line}"));
1334                        } else {
1335                            buf.push_back(format!("  {line}"));
1336                        }
1337                    }
1338                }
1339                while buf.len() > TRANSCRIPT_CAP {
1340                    buf.pop_front();
1341                }
1342            }
1343            Event::Output { session, text } => {
1344                let buf = self.transcripts.entry(session.clone()).or_default();
1345                // Trailing newline should not produce an empty line; intermediate empty lines are preserved.
1346                let mut parts: Vec<&str> = text.split('\n').collect();
1347                if parts.last() == Some(&"") {
1348                    parts.pop();
1349                }
1350                for line in parts {
1351                    buf.push_back(line.to_string());
1352                }
1353                while buf.len() > TRANSCRIPT_CAP {
1354                    buf.pop_front();
1355                }
1356            }
1357            Event::OutputAppend { session, text } => {
1358                let buf = self.transcripts.entry(session.clone()).or_default();
1359                let mut parts = text.split('\n');
1360                if let Some(first) = parts.next() {
1361                    match buf.back_mut() {
1362                        Some(last) => last.push_str(first),
1363                        None => buf.push_back(first.to_string()),
1364                    }
1365                }
1366                let rest: Vec<&str> = parts.collect();
1367                // Same rule as `Output`: a trailing newline does not make an empty line.
1368                let rest = match rest.split_last() {
1369                    Some((&"", init)) => init,
1370                    _ => &rest[..],
1371                };
1372                for line in rest {
1373                    buf.push_back((*line).to_string());
1374                }
1375                while buf.len() > TRANSCRIPT_CAP {
1376                    buf.pop_front();
1377                }
1378            }
1379            Event::ToolCall {
1380                session,
1381                name,
1382                input,
1383                ok,
1384                output,
1385            } => {
1386                if let Some(s) = self.sessions.get_mut(session) {
1387                    if ok.is_none() && !name.is_empty() {
1388                        s.tool_calls = s.tool_calls.saturating_add(1);
1389                        let is_sub = is_subagent_tool(name);
1390                        let sum = tool_summary(input).unwrap_or_default();
1391                        s.active_tools.push(ActiveTool {
1392                            name: name.clone(),
1393                            summary: sum,
1394                            started_ms: now_millis(),
1395                            is_subagent: is_sub,
1396                        });
1397                    } else if ok.is_some() {
1398                        if !name.is_empty() {
1399                            if let Some(pos) = s.active_tools.iter().position(|t| t.name == *name) {
1400                                s.active_tools.remove(pos);
1401                            } else if !s.active_tools.is_empty() {
1402                                s.active_tools.remove(0);
1403                            }
1404                        } else if !s.active_tools.is_empty() {
1405                            s.active_tools.remove(0);
1406                        }
1407                    }
1408                }
1409                if ok.is_none() && !name.is_empty() {
1410                    let line = match tool_summary(input) {
1411                        Some(sum) => format!("▸ {name}: {sum}"),
1412                        None => format!("▸ {name}"),
1413                    };
1414                    self.push_transcript_line(session, line);
1415                } else if let Some(ok) = ok {
1416                    // Tool results: show one-line summary on success, show failure reason on error.
1417                    let out = output.as_deref().unwrap_or("");
1418                    let first = out.lines().find(|l| !l.trim().is_empty()).unwrap_or("");
1419                    let extra = out
1420                        .lines()
1421                        .filter(|l| !l.trim().is_empty())
1422                        .count()
1423                        .saturating_sub(1);
1424                    let mut text: String = first.trim().chars().take(100).collect();
1425                    if first.trim().chars().count() > 100 || extra > 0 {
1426                        text.push_str(&if extra > 0 {
1427                            tr!(" …(+{extra} 行)", extra = extra)
1428                        } else {
1429                            "…".into()
1430                        });
1431                    }
1432                    let line = match (ok, text.is_empty()) {
1433                        (true, true) => "  ✓".to_string(),
1434                        (true, false) => format!("  ✓ {text}"),
1435                        (false, true) => format!("  ✗ {}", tr!("失敗")),
1436                        (false, false) => format!("  ✗ {text}"),
1437                    };
1438                    self.push_transcript_line(session, line);
1439                }
1440            }
1441            Event::PermissionRequested { request } => {
1442                self.pending_permissions
1443                    .insert(request.req.clone(), request.clone());
1444                if let Some(s) = self.sessions.get_mut(&request.session) {
1445                    s.status = SessionStatus::WaitingApproval;
1446                }
1447            }
1448            Event::PermissionResolved { req, .. } => {
1449                self.pending_permissions.remove(req);
1450            }
1451            Event::QuestionRequested { question } => {
1452                self.pending_questions
1453                    .insert(question.id.clone(), question.clone());
1454                if let Some(s) = self.sessions.get_mut(&question.session) {
1455                    s.status = SessionStatus::WaitingApproval;
1456                }
1457            }
1458            Event::QuestionResolved { id, .. } => {
1459                self.pending_questions.remove(id);
1460            }
1461            Event::BusMessage { message } => {
1462                self.messages.push(message.clone());
1463                while self.messages.len() > MESSAGE_CAP {
1464                    self.messages.remove(0);
1465                }
1466            }
1467            Event::TaskChanged { task } => {
1468                self.tasks.insert(task.id.clone(), task.clone());
1469            }
1470            Event::ArtifactShared { artifact } => {
1471                self.artifacts.push(artifact.clone());
1472                while self.artifacts.len() > ARTIFACT_CAP {
1473                    self.artifacts.remove(0);
1474                }
1475            }
1476            Event::ReviewCommented { review } => {
1477                let line = format!("💬 review [{}]: {}", review.location, review.comment);
1478                self.push_transcript_line(&review.session, line);
1479                self.reviews.push(review.clone());
1480                while self.reviews.len() > ARTIFACT_CAP {
1481                    self.reviews.remove(0);
1482                }
1483            }
1484            Event::SessionExited { session, .. } => {
1485                self.remove_session_questions(session);
1486                if let Some(s) = self.sessions.get_mut(session) {
1487                    if s.status.is_live() {
1488                        s.status = SessionStatus::Exited;
1489                    }
1490                    s.ended_ms = s.ended_ms.or(Some(rec.ts));
1491                }
1492            }
1493            Event::Cost { session, cost } => {
1494                if let Some(s) = self.sessions.get_mut(session) {
1495                    s.cost = *cost;
1496                }
1497            }
1498            Event::SessionOverBudget { session, .. } => {
1499                if let Some(s) = self.sessions.get_mut(session) {
1500                    s.over_budget = true;
1501                }
1502            }
1503            Event::SessionBudget {
1504                session,
1505                budget_usd,
1506            } => {
1507                if let Some(s) = self.sessions.get_mut(session) {
1508                    s.budget_usd = *budget_usd;
1509                    s.over_budget = false;
1510                }
1511            }
1512            Event::LogHealth { ok } => {
1513                self.log_ok = *ok;
1514            }
1515            Event::QueueChanged { session, items } => {
1516                if items.is_empty() {
1517                    self.queues.remove(session);
1518                } else {
1519                    self.queues.insert(session.clone(), items.clone());
1520                }
1521            }
1522        }
1523    }
1524
1525    /// Calculates depth of `sid` (human-created sessions are level 0, child agents increment sequentially).
1526    pub fn session_depth(&self, sid: &str) -> usize {
1527        let mut depth = 0;
1528        let mut cur = sid;
1529        let mut seen = std::collections::HashSet::new();
1530        while seen.insert(cur) {
1531            let Some(parent) = self
1532                .sessions
1533                .get(cur)
1534                .and_then(|s| s.parent.as_deref())
1535                .filter(|p| self.sessions.contains_key(*p))
1536            else {
1537                break;
1538            };
1539            depth += 1;
1540            cur = parent;
1541        }
1542        depth
1543    }
1544
1545    /// Traverses upward along `parent` to find the root session ID of the tree.
1546    pub fn tree_root(&self, sid: &str) -> SessionId {
1547        let mut cur = sid;
1548        let mut seen = std::collections::HashSet::new();
1549        while seen.insert(cur) {
1550            let Some(parent) = self
1551                .sessions
1552                .get(cur)
1553                .and_then(|s| s.parent.as_deref())
1554                .filter(|p| self.sessions.contains_key(*p))
1555            else {
1556                break;
1557            };
1558            cur = parent;
1559        }
1560        cur.to_string()
1561    }
1562
1563    /// Returns all session IDs in the same tree as `sid` (root and all descendants).
1564    pub fn tree_sessions(&self, sid: &str) -> Vec<SessionId> {
1565        let root = self.tree_root(sid);
1566        self.sessions
1567            .keys()
1568            .filter(|id| self.tree_root(id) == root)
1569            .cloned()
1570            .collect()
1571    }
1572
1573    /// Calculates total USD cost for the same tree as `sid` (root and all descendants).
1574    pub fn tree_cost_usd(&self, sid: &str) -> f64 {
1575        let root = self.tree_root(sid);
1576        self.sessions
1577            .values()
1578            .filter(|s| self.tree_root(&s.id) == root)
1579            .map(|s| s.cost.usd)
1580            .sum()
1581    }
1582
1583    /// Counts live direct child sessions currently running under `parent_id`.
1584    pub fn live_children_count(&self, parent_id: &str) -> usize {
1585        self.sessions
1586            .values()
1587            .filter(|s| s.parent.as_deref() == Some(parent_id) && s.status.is_live())
1588            .count()
1589    }
1590
1591    /// Helper for TUI to retrieve sessions sorted by creation time.
1592    pub fn sessions_sorted(&self) -> Vec<&Session> {
1593        let mut v: Vec<&Session> = self.sessions.values().collect();
1594        v.sort_by_key(|s| s.created_ms);
1595        v
1596    }
1597
1598    pub fn live_sessions(&self) -> impl Iterator<Item = &Session> {
1599        self.sessions.values().filter(|s| s.status.is_live())
1600    }
1601
1602    /// Calculates cumulative cost and token usage across all sessions.
1603    pub fn total_cost(&self) -> Cost {
1604        let mut total = Cost::default();
1605        for s in self.sessions.values() {
1606            total.usd += s.cost.usd;
1607            total.input_tokens += s.cost.input_tokens;
1608            total.output_tokens += s.cost.output_tokens;
1609        }
1610        total
1611    }
1612
1613    /// Incomplete prerequisite tasks (present in `depends_on` with status other than `done`).
1614    /// Missing IDs do not count: they will never complete, and counting them would deadlock the task.
1615    pub fn unfinished_deps(&self, task: &Task) -> Vec<&Task> {
1616        task.depends_on
1617            .iter()
1618            .filter_map(|id| self.tasks.get(id))
1619            .filter(|t| t.status != TaskStatus::Done)
1620            .collect()
1621    }
1622
1623    /// Resolves session ID by `id` or `label` (prefers exact ID match, then live session with matching label).
1624    pub fn resolve_session_id(&self, id_or_label: &str) -> Option<SessionId> {
1625        let needle = id_or_label.trim().trim_start_matches('@');
1626        if self.sessions.contains_key(needle) {
1627            return Some(needle.to_string());
1628        }
1629        self.sessions
1630            .values()
1631            .filter(|s| s.label == needle && s.status.is_live())
1632            .max_by_key(|s| s.created_ms)
1633            .or_else(|| {
1634                self.sessions
1635                    .values()
1636                    .filter(|s| s.label == needle)
1637                    .max_by_key(|s| s.created_ms)
1638            })
1639            .map(|s| s.id.clone())
1640    }
1641
1642    /// Finds target session for `:resume` by `id`, `label`, or `native_id`; returns `(Session, is_archived)`.
1643    pub fn resolve_resumable_session(&self, id_or_label: &str) -> Option<(Session, bool)> {
1644        let needle = id_or_label.trim().trim_start_matches('@');
1645        if needle.is_empty() {
1646            return None;
1647        }
1648        if let Some(s) = self.sessions.get(needle) {
1649            return Some((s.clone(), false));
1650        }
1651        if let Some(s) = self.archived_sessions.get(needle) {
1652            return Some((s.clone(), true));
1653        }
1654        if let Some(s) = self
1655            .sessions
1656            .values()
1657            .filter(|s| s.label == needle && !s.status.is_live())
1658            .max_by_key(|s| s.created_ms)
1659        {
1660            return Some((s.clone(), false));
1661        }
1662        if let Some(s) = self
1663            .archived_sessions
1664            .values()
1665            .filter(|s| s.label == needle)
1666            .max_by_key(|s| s.created_ms)
1667        {
1668            return Some((s.clone(), true));
1669        }
1670        if let Some(s) = self
1671            .sessions
1672            .values()
1673            .filter(|s| s.label == needle)
1674            .max_by_key(|s| s.created_ms)
1675        {
1676            return Some((s.clone(), false));
1677        }
1678        if let Some(s) = self
1679            .sessions
1680            .values()
1681            .filter(|s| s.native_id.as_deref() == Some(needle))
1682            .max_by_key(|s| s.created_ms)
1683        {
1684            return Some((s.clone(), false));
1685        }
1686        if let Some(s) = self
1687            .archived_sessions
1688            .values()
1689            .filter(|s| s.native_id.as_deref() == Some(needle))
1690            .max_by_key(|s| s.created_ms)
1691        {
1692            return Some((s.clone(), true));
1693        }
1694        None
1695    }
1696
1697    /// Follows `handed_off_to` chain to final successor; stops at current node on cycles or exceeding 16 levels.
1698    pub fn successor_of(&self, id: &str) -> SessionId {
1699        let mut cur = id.to_string();
1700        let mut seen = vec![cur.clone()];
1701        for _ in 0..16 {
1702            let Some(next) = self
1703                .sessions
1704                .get(&cur)
1705                .and_then(|s| s.handed_off_to.clone())
1706            else {
1707                break;
1708            };
1709            if seen.contains(&next) {
1710                break;
1711            }
1712            seen.push(next.clone());
1713            cur = next;
1714        }
1715        cur
1716    }
1717
1718    /// Retrieves messages received by a session after `after_msg_id`.
1719    pub fn inbox_for(&self, session_id: &str, after_msg_id: Option<&str>) -> Vec<BusMessage> {
1720        let resolved = self
1721            .resolve_session_id(session_id)
1722            .unwrap_or_else(|| session_id.to_string());
1723        let label = self.sessions.get(&resolved).map(|s| s.label.as_str());
1724        let start = after_msg_id
1725            .and_then(|id| self.messages.iter().position(|m| m.id == id))
1726            .map(|idx| idx + 1)
1727            .unwrap_or(0);
1728        self.messages[start..]
1729            .iter()
1730            .filter(|m| m.matches_recipient(&resolved, label))
1731            .cloned()
1732            .collect()
1733    }
1734
1735    /// Exports a session (and optionally entire child session tree) into a Markdown report suitable for PR / Issue description.
1736    ///
1737    /// Includes metadata, child session hierarchy, associated tasks, transcript, and optional git diff;
1738    /// entire output is masked with [`redact_secrets`] to prevent leaking keys to external services.
1739    pub fn export_markdown(
1740        &self,
1741        root_id: &str,
1742        include_tree: bool,
1743        diff: Option<&str>,
1744    ) -> Result<String, String> {
1745        let root = self
1746            .resolve_session_id(root_id)
1747            .ok_or_else(|| tr!("找不到 session:{id}", id = root_id))?;
1748        let root_session = self
1749            .sessions
1750            .get(&root)
1751            .ok_or_else(|| tr!("找不到 session:{id}", id = root))?;
1752
1753        let mut members: Vec<&Session> = if include_tree {
1754            let mut v: Vec<&Session> = self
1755                .tree_sessions(&root)
1756                .iter()
1757                .filter_map(|id| self.sessions.get(id))
1758                .collect();
1759            v.sort_by_key(|s| (self.session_depth(&s.id), s.created_ms, s.id.clone()));
1760            v
1761        } else {
1762            vec![root_session]
1763        };
1764        // Root session always comes first, even if child sessions were created earlier.
1765        if let Some(pos) = members.iter().position(|s| s.id == root) {
1766            let root_ref = members.remove(pos);
1767            members.insert(0, root_ref);
1768        }
1769
1770        let member_ids: Vec<&str> = members.iter().map(|s| s.id.as_str()).collect();
1771        let total_usd: f64 = members.iter().map(|s| s.cost.usd).sum();
1772        let total_in: u64 = members.iter().map(|s| s.cost.input_tokens).sum();
1773        let total_out: u64 = members.iter().map(|s| s.cost.output_tokens).sum();
1774
1775        let mut out = String::new();
1776        out.push_str(&tr!("# 協作報告:{label}\n\n", label = root_session.label));
1777
1778        out.push_str(&format!("## {}\n\n", tr!("元資料")));
1779        out.push_str(&format!("| {} | {} |\n", tr!("項目"), tr!("值")));
1780        out.push_str("| --- | --- |\n");
1781        let row = |k: String, v: String| format!("| {k} | {v} |\n");
1782        out.push_str(&row(tr!("標籤"), root_session.label.clone()));
1783        out.push_str(&row(
1784            tr!("Agent / Model"),
1785            format!(
1786                "{}{}{}",
1787                root_session.kind.id(),
1788                root_session
1789                    .model
1790                    .as_deref()
1791                    .map(|m| format!(" / {m}"))
1792                    .unwrap_or_default(),
1793                root_session
1794                    .effort
1795                    .as_deref()
1796                    .map(|e| format!(" (effort: {e})"))
1797                    .unwrap_or_default()
1798            ),
1799        ));
1800        out.push_str(&row(tr!("角色"), root_session.role.id().to_string()));
1801        out.push_str(&row(
1802            tr!("分支"),
1803            root_session.branch.clone().unwrap_or_else(|| "-".into()),
1804        ));
1805        out.push_str(&row(
1806            tr!("狀態"),
1807            format!(
1808                "{} {}",
1809                root_session.status.glyph(),
1810                status_text(root_session.status)
1811            ),
1812        ));
1813        out.push_str(&row(
1814            tr!("總花費"),
1815            format!(
1816                "${total_usd:.4} ({} in / {} out tokens)",
1817                total_in, total_out
1818            ),
1819        ));
1820        out.push('\n');
1821
1822        if include_tree && members.len() > 1 {
1823            out.push_str(&format!("## {}\n\n", tr!("子 Session 階層")));
1824            out.push_str(&format!(
1825                "| {} | {} | {} | {} | {} |\n",
1826                tr!("標籤"),
1827                tr!("角色"),
1828                tr!("Agent / Model"),
1829                tr!("狀態"),
1830                tr!("花費")
1831            ));
1832            out.push_str("| --- | --- | --- | --- | --- |\n");
1833            for s in &members {
1834                let indent = "  ".repeat(self.session_depth(&s.id));
1835                out.push_str(&format!(
1836                    "| {indent}{} | {} | {}{} | {} {} | ${:.4} |\n",
1837                    s.label,
1838                    s.role.id(),
1839                    s.kind.id(),
1840                    s.model
1841                        .as_deref()
1842                        .map(|m| format!(" / {m}"))
1843                        .unwrap_or_default(),
1844                    s.status.glyph(),
1845                    status_text(s.status),
1846                    s.cost.usd,
1847                ));
1848            }
1849            out.push('\n');
1850        }
1851
1852        let related: Vec<&Task> = self
1853            .tasks
1854            .values()
1855            .filter(|t| {
1856                t.assignee
1857                    .as_deref()
1858                    .is_some_and(|id| member_ids.contains(&id))
1859                    || t.created_by
1860                        .as_deref()
1861                        .is_some_and(|id| member_ids.contains(&id))
1862            })
1863            .collect();
1864        if !related.is_empty() {
1865            out.push_str(&format!("## {}\n\n", tr!("關聯任務")));
1866            out.push_str(&format!(
1867                "| {} | {} | {} | {} |\n",
1868                tr!("編號"),
1869                tr!("標題"),
1870                tr!("狀態"),
1871                tr!("負責人")
1872            ));
1873            out.push_str("| --- | --- | --- | --- |\n");
1874            for t in related {
1875                let assignee = t.assignee.as_deref().and_then(|id| self.sessions.get(id));
1876                out.push_str(&format!(
1877                    "| {} | {} | {} | {} |\n",
1878                    t.id,
1879                    t.title,
1880                    t.status.id(),
1881                    assignee.map(|s| s.label.as_str()).unwrap_or("-")
1882                ));
1883            }
1884            out.push('\n');
1885        }
1886
1887        out.push_str(&format!("## {}\n\n", tr!("對話與執行紀錄")));
1888        for s in &members {
1889            out.push_str(&format!("### {} ({})\n\n", s.label, s.role.id()));
1890            let lines = self.transcripts.get(&s.id);
1891            match lines {
1892                Some(lines) if !lines.is_empty() => {
1893                    out.push_str("```text\n");
1894                    // Successful tool results are noise in transcripts; failures (`✗`) and user prompts (`❯`) are retained.
1895                    for line in lines.iter().filter(|l| !l.starts_with("  ✓")) {
1896                        out.push_str(line);
1897                        out.push('\n');
1898                    }
1899                    out.push_str("```\n\n");
1900                }
1901                _ => {
1902                    out.push_str(&format!("_{}_\n\n", tr!("(尚無逐字稿)")));
1903                }
1904            }
1905        }
1906
1907        if let Some(diff) = diff.filter(|d| !d.trim().is_empty()) {
1908            out.push_str(&format!(
1909                "## Git Diff\n\n```diff\n{}\n```\n",
1910                diff.trim_end()
1911            ));
1912        }
1913
1914        Ok(redact_secrets(&out))
1915    }
1916}
1917
1918/// Human-readable text for `SessionStatus` (for reports).
1919fn status_text(status: SessionStatus) -> String {
1920    match status {
1921        SessionStatus::Starting => tr!("啟動中"),
1922        SessionStatus::Idle => tr!("閒置"),
1923        SessionStatus::Busy => tr!("執行中"),
1924        SessionStatus::WaitingApproval => tr!("等待核准"),
1925        SessionStatus::Sleeping => tr!("休眠"),
1926        SessionStatus::Exited => tr!("已結束"),
1927        SessionStatus::Failed => tr!("失敗"),
1928    }
1929}
1930
1931// ---------------------------------------------------------------------------
1932// Policy Engine & Secret Protection (M4)
1933// ---------------------------------------------------------------------------
1934
1935/// Permission rule engine: filters unambiguously safe and high-risk operations before `PermissionPolicy`.
1936///
1937/// Overridable via `~/.config/ertangle/policy.toml` (or project `.ertangle/policy.toml`):
1938/// ```toml
1939/// allow = ["Read", "Grep", "Glob", "git status"]
1940/// deny = ["rm -rf /", "git push --force", "/.ssh/"]
1941/// ```
1942#[derive(Debug, Clone, Serialize, Deserialize)]
1943pub struct PolicyEngine {
1944    pub allow: Vec<String>,
1945    pub deny: Vec<String>,
1946}
1947
1948impl Default for PolicyEngine {
1949    fn default() -> Self {
1950        Self {
1951            allow: vec![
1952                "Read".into(),
1953                "Grep".into(),
1954                "Glob".into(),
1955                "git status".into(),
1956                "git diff".into(),
1957                "git log".into(),
1958            ],
1959            deny: vec![
1960                "rm -rf /".into(),
1961                "rm -rf ~".into(),
1962                "git push --force".into(),
1963                "git push -f".into(),
1964                "/.ssh/".into(),
1965                "id_rsa".into(),
1966                "mkfs.".into(),
1967            ],
1968        }
1969    }
1970}
1971
1972impl PolicyEngine {
1973    /// Parses rules from simple TOML text (unspecified sections retain default values).
1974    pub fn parse_toml(src: &str) -> Self {
1975        let mut engine = Self::default();
1976        for raw_line in src.lines() {
1977            let line = raw_line.split('#').next().unwrap_or("").trim();
1978            if line.is_empty() {
1979                continue;
1980            }
1981            if let Some((k, v)) = line.split_once('=') {
1982                let key = k.trim();
1983                let list = parse_string_array(v.trim());
1984                if key == "allow" && !list.is_empty() {
1985                    engine.allow = list;
1986                } else if key == "deny" && !list.is_empty() {
1987                    engine.deny = list;
1988                }
1989            }
1990        }
1991        engine
1992    }
1993
1994    /// Evaluates a permission request:
1995    /// * Matches `deny` -> `Some(Decision::Deny)`
1996    /// * Matches `allow` -> `Some(Decision::Allow)`
1997    /// * Otherwise -> `None` (deferred to session `PermissionPolicy` or human)
1998    pub fn evaluate(&self, title: &str, detail: &str) -> Option<Decision> {
1999        let combined = format!("{title} {detail}");
2000        // deny maintains conservative substring matching: prefer false positives.
2001        for pat in &self.deny {
2002            if !pat.is_empty() && combined.contains(pat.as_str()) {
2003                return Some(Decision::Deny);
2004            }
2005        }
2006        // allow must be strict: exact tool name match, or command matches rule as full-word prefix,
2007        // preventing `Read` from matching `README`.
2008        let command = command_text(detail);
2009        for pat in &self.allow {
2010            if pat.is_empty() {
2011                continue;
2012            }
2013            let title_tool = title.split_whitespace().next().unwrap_or("");
2014            if title_tool == pat
2015                || word_prefix(title, pat)
2016                || command.as_deref().is_some_and(|c| word_prefix(c, pat))
2017            {
2018                return Some(Decision::Allow);
2019            }
2020        }
2021        None
2022    }
2023
2024    /// Layers repo-level rules: `deny` takes union (cannot remove global deny), `allow` also merges.
2025    pub fn merged_with(&self, local: &PolicyEngine) -> PolicyEngine {
2026        let mut out = self.clone();
2027        for d in &local.deny {
2028            if !out.deny.contains(d) {
2029                out.deny.push(d.clone());
2030            }
2031        }
2032        for a in &local.allow {
2033            if !out.allow.contains(a) {
2034                out.allow.push(a.clone());
2035            }
2036        }
2037        out
2038    }
2039}
2040
2041/// Whether `text` starts with `pat` and ends at a word boundary (whitespace or end of string).
2042fn word_prefix(text: &str, pat: &str) -> bool {
2043    let t = text.trim_start();
2044    t.starts_with(pat)
2045        && t[pat.len()..]
2046            .chars()
2047            .next()
2048            .is_none_or(char::is_whitespace)
2049}
2050
2051/// Extracts command string from permission request `detail` (usually JSON rawInput).
2052fn command_text(detail: &str) -> Option<String> {
2053    // When not JSON, treat entire string as command text.
2054    let Ok(v) = serde_json::from_str::<serde_json::Value>(detail) else {
2055        return Some(detail.to_string());
2056    };
2057    match &v {
2058        serde_json::Value::String(s) => Some(s.clone()),
2059        serde_json::Value::Object(m) => ["command", "cmd"]
2060            .iter()
2061            .find_map(|k| m.get(*k).and_then(|x| x.as_str()))
2062            .map(str::to_string),
2063        _ => None,
2064    }
2065}
2066
2067fn parse_string_array(s: &str) -> Vec<String> {
2068    let s = s.trim().trim_start_matches('[').trim_end_matches(']');
2069    s.split(',')
2070        .map(|item| item.trim().trim_matches('"').trim_matches('\'').to_string())
2071        .filter(|item| !item.is_empty())
2072        .collect()
2073}
2074
2075/// Summarizes tool input (JSON string) into a human-readable one-line summary: prefers command/file_path/pattern fields.
2076pub fn tool_summary(input: &str) -> Option<String> {
2077    let v: serde_json::Value = serde_json::from_str(input).ok()?;
2078    let one_line = |s: &str| -> String {
2079        let t: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
2080        if t.chars().count() > 100 {
2081            format!("{}…", t.chars().take(100).collect::<String>())
2082        } else {
2083            t
2084        }
2085    };
2086    match &v {
2087        serde_json::Value::Null => None,
2088        serde_json::Value::String(s) if !s.trim().is_empty() => Some(one_line(s)),
2089        serde_json::Value::Object(m) => {
2090            for k in [
2091                "command",
2092                "cmd",
2093                "file_path",
2094                "path",
2095                "pattern",
2096                "url",
2097                "query",
2098                "description",
2099                "prompt",
2100            ] {
2101                if let Some(x) = m.get(k).and_then(|x| x.as_str()) {
2102                    if !x.trim().is_empty() {
2103                        return Some(one_line(x));
2104                    }
2105                }
2106            }
2107            // Shell tool in ACP only provides `cwd` during `tool_call`; dumping the full JSON is noise.
2108            if m.keys()
2109                .all(|k| matches!(k.as_str(), "cwd" | "workdir" | "timeout"))
2110            {
2111                None
2112            } else {
2113                Some(one_line(&v.to_string()))
2114            }
2115        }
2116        _ => None,
2117    }
2118}
2119
2120#[cfg(test)]
2121mod tool_summary_tests {
2122    use super::tool_summary;
2123
2124    #[test]
2125    fn picks_the_descriptive_field() {
2126        assert_eq!(
2127            tool_summary(r#"{"command":"cargo fmt","cwd":"/tmp"}"#).as_deref(),
2128            Some("cargo fmt")
2129        );
2130        assert!(
2131            tool_summary(r#"{"cwd":"/mnt"}"#).is_none(),
2132            "只有 cwd 的物件沒有資訊量,不該印 JSON"
2133        );
2134        assert!(tool_summary(r#"{"workdir":"/mnt","timeout":10}"#).is_none());
2135        let other = tool_summary(r#"{"mcp":"x","args":["a"]}"#);
2136        assert!(
2137            other.as_deref().is_some_and(|s| s.contains("\"mcp\"")),
2138            "未知欄位仍要能看到原文:{other:?}"
2139        );
2140        assert!(tool_summary("not json").is_none());
2141    }
2142}
2143
2144/// A specific quota window (e.g. Claude 5 hours / 7 days).
2145#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2146pub struct QuotaWindow {
2147    /// Display name: `5h`, `7d`, `30d`…
2148    pub name: String,
2149    pub used_percent: f32,
2150    /// Reset timestamp (epoch milliseconds).
2151    pub resets_at_ms: Option<u64>,
2152}
2153
2154/// Current quota status for an agent account (reported by agent itself, not estimated by ertangle).
2155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2156pub struct Quota {
2157    /// Agent kind ID, e.g. `claude`, `codex`.
2158    pub agent: String,
2159    pub windows: Vec<QuotaWindow>,
2160    /// Quota limit reached / rate limited.
2161    pub reached: bool,
2162    /// Agent reported approaching limit warning (e.g. Claude `allowed_warning`), still usable.
2163    #[serde(default)]
2164    pub warning: bool,
2165    pub updated_ms: u64,
2166}
2167
2168/// Converts remaining milliseconds into `2h13m` / `45m` / `3d4h`.
2169pub fn format_remaining(ms: u64) -> String {
2170    let mins = ms / 60_000;
2171    match mins {
2172        0 => "<1m".into(),
2173        1..=59 => format!("{mins}m"),
2174        60..=1439 => format!("{}h{:02}m", mins / 60, mins % 60),
2175        _ => format!("{}d{}h", mins / 1440, (mins % 1440) / 60),
2176    }
2177}
2178
2179impl Quota {
2180    fn is_inactive_window(&self, window: &QuotaWindow) -> bool {
2181        // Antigravity 3p windows cover third-party models only and must not drive agent-level quota decisions.
2182        self.agent == "antigravity" && window.name.starts_with("3p-")
2183    }
2184
2185    /// One-line summary: `claude 5h 39% (reset 1h20m) 7d 22%`. Windows past reset time show `reset`.
2186    pub fn summary(&self, now_ms: u64) -> String {
2187        let parts: Vec<String> = self
2188            .windows
2189            .iter()
2190            .map(|w| match w.resets_at_ms {
2191                Some(r) if r <= now_ms => tr!("{name} 已重置", name = w.name),
2192                Some(r) => tr!(
2193                    "{name} {pct}% (重置 {remaining})",
2194                    name = w.name,
2195                    pct = format!("{:.0}", w.used_percent),
2196                    remaining = format_remaining(r - now_ms)
2197                ),
2198                None => format!("{} {:.0}%", w.name, w.used_percent),
2199            })
2200            .collect();
2201        let reached = if self.is_reached(now_ms) {
2202            format!(" {}", tr!("✗額度已滿"))
2203        } else {
2204            String::new()
2205        };
2206        format!("{}{} {}", self.agent, reached, parts.join(" · "))
2207    }
2208
2209    /// Whether this agent's quota is currently reached/exhausted at `now_ms`.
2210    ///
2211    /// If there are no windows (e.g. error-only rate limit without window timestamps),
2212    /// falls back to `self.reached`. Otherwise, returns `true` if any active live window
2213    /// has `used_percent >= 100.0`, OR if `self.reached` is `true` and no active window
2214    /// has reset yet.
2215    pub fn is_reached(&self, now_ms: u64) -> bool {
2216        if self.windows.is_empty() {
2217            return self.reached;
2218        }
2219        let any_live_exhausted = self
2220            .windows
2221            .iter()
2222            .filter(|w| !self.is_inactive_window(w))
2223            .filter(|w| w.resets_at_ms.is_none_or(|r| r > now_ms))
2224            .any(|w| w.used_percent >= 100.0);
2225        if any_live_exhausted {
2226            return true;
2227        }
2228        if self.reached {
2229            let any_reset = self.windows.iter().any(|w| {
2230                !self.is_inactive_window(w) && w.resets_at_ms.is_some_and(|r| r <= now_ms)
2231            });
2232            if !any_reset {
2233                return true;
2234            }
2235        }
2236        false
2237    }
2238
2239    /// Tightest window usage (percentage).
2240    pub fn max_used(&self) -> f32 {
2241        self.windows
2242            .iter()
2243            .filter(|w| !self.is_inactive_window(w))
2244            .map(|w| w.used_percent)
2245            .fold(0.0, f32::max)
2246    }
2247
2248    /// Tightest usage among windows that have not reset yet (percentage).
2249    pub fn max_used_live(&self, now_ms: u64) -> f32 {
2250        self.windows
2251            .iter()
2252            .filter(|w| !self.is_inactive_window(w))
2253            .filter(|w| w.resets_at_ms.is_none_or(|reset| reset > now_ms))
2254            .map(|w| w.used_percent)
2255            .fold(0.0, f32::max)
2256    }
2257}
2258
2259/// Converts window duration (minutes) to display name.
2260pub fn window_name(mins: u64) -> String {
2261    match mins {
2262        300 => "5h".into(),
2263        10080 => "7d".into(),
2264        43200 => "30d".into(),
2265        m if m % 1440 == 0 => format!("{}d", m / 1440),
2266        m if m % 60 == 0 => format!("{}h", m / 60),
2267        m => format!("{m}m"),
2268    }
2269}
2270
2271/// Whether error text resembles quota exhaustion / rate limiting (conservative keyword matching across diverse agent messages).
2272pub fn looks_like_limit(text: &str) -> bool {
2273    let t = text.to_ascii_lowercase();
2274    (t.contains("limit")
2275        && (t.contains("hit your")
2276            || t.contains("usage")
2277            || t.contains("rate")
2278            || t.contains("resets")))
2279        || t.contains("rate_limit")
2280        || t.contains("rate limit")
2281        || t.contains("insufficient_quota")
2282        || t.contains("quota exceeded")
2283        || t.contains("exceeded your current quota")
2284        || t.contains("429")
2285}
2286
2287/// Attachments sent with a prompt (files or images). Content is read and inlined by the sender (TUI/CLI),
2288/// so the remote daemon does not need access to the same filesystem.
2289#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2290pub struct Attachment {
2291    /// Display filename.
2292    pub name: String,
2293    /// MIME type, e.g. `image/png`, `text/plain`.
2294    pub mime: String,
2295    /// Original path (for reference / PTY use only).
2296    #[serde(default)]
2297    pub path: Option<String>,
2298    /// Base64 content of image.
2299    #[serde(default)]
2300    pub data: Option<String>,
2301    /// Content of text file.
2302    #[serde(default)]
2303    pub text: Option<String>,
2304    pub size: u64,
2305    /// Raw user input text (including `@filename`, for queue preview and `:unqueue` restoration).
2306    #[serde(default, skip_serializing_if = "Option::is_none")]
2307    pub raw_prompt: Option<String>,
2308}
2309
2310/// Image attachment size limit (5 MB) and text file embedding limit (256 KB).
2311pub const MAX_IMAGE_BYTES: u64 = 5 * 1024 * 1024;
2312pub const MAX_TEXT_BYTES: u64 = 256 * 1024;
2313
2314/// Guesses image MIME type from file extension; returns `None` if not an image.
2315pub fn image_mime(path: &std::path::Path) -> Option<&'static str> {
2316    match path.extension()?.to_str()?.to_ascii_lowercase().as_str() {
2317        "png" => Some("image/png"),
2318        "jpg" | "jpeg" => Some("image/jpeg"),
2319        "gif" => Some("image/gif"),
2320        "webp" => Some("image/webp"),
2321        _ => None,
2322    }
2323}
2324
2325/// Standard base64 encoding (with padding).
2326pub fn base64_encode(bytes: &[u8]) -> String {
2327    const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2328    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
2329    for chunk in bytes.chunks(3) {
2330        let n = (u32::from(chunk[0]) << 16)
2331            | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8)
2332            | u32::from(*chunk.get(2).unwrap_or(&0));
2333        out.push(T[(n >> 18) as usize & 63] as char);
2334        out.push(T[(n >> 12) as usize & 63] as char);
2335        out.push(if chunk.len() > 1 {
2336            T[(n >> 6) as usize & 63] as char
2337        } else {
2338            '='
2339        });
2340        out.push(if chunk.len() > 2 {
2341            T[n as usize & 63] as char
2342        } else {
2343            '='
2344        });
2345    }
2346    out
2347}
2348
2349impl Attachment {
2350    /// Reads file into an attachment: inlines base64 for images (up to 5 MB); inlines content for UTF-8 text files
2351    /// (up to 256 KB; carries path only if exceeded); other binary files carry path only.
2352    pub fn load(path: &std::path::Path) -> Result<Attachment, String> {
2353        let meta = std::fs::metadata(path)
2354            .map_err(|e| tr!("無法讀取 {path}:{e}", path = path.display(), e = e))?;
2355        if !meta.is_file() {
2356            return Err(tr!("{path} 不是檔案", path = path.display()));
2357        }
2358        let name = path
2359            .file_name()
2360            .map(|n| n.to_string_lossy().to_string())
2361            .unwrap_or_else(|| path.display().to_string());
2362        let abs = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
2363        let mut att = Attachment {
2364            name,
2365            mime: "application/octet-stream".into(),
2366            path: Some(abs.to_string_lossy().to_string()),
2367            size: meta.len(),
2368            ..Default::default()
2369        };
2370        if let Some(mime) = image_mime(path) {
2371            if meta.len() > MAX_IMAGE_BYTES {
2372                return Err(tr!(
2373                    "圖片 {name} 太大 ({size} KB,上限 {max} KB)",
2374                    name = att.name,
2375                    size = meta.len() / 1024,
2376                    max = MAX_IMAGE_BYTES / 1024
2377                ));
2378            }
2379            let bytes = std::fs::read(path)
2380                .map_err(|e| tr!("讀取 {name} 失敗:{e}", name = att.name, e = e))?;
2381            att.mime = mime.into();
2382            att.data = Some(base64_encode(&bytes));
2383            return Ok(att);
2384        }
2385        if meta.len() <= MAX_TEXT_BYTES {
2386            let bytes = std::fs::read(path)
2387                .map_err(|e| tr!("讀取 {name} 失敗:{e}", name = att.name, e = e))?;
2388            if !bytes.contains(&0) {
2389                if let Ok(text) = String::from_utf8(bytes) {
2390                    att.mime = "text/plain".into();
2391                    att.text = Some(text);
2392                }
2393            }
2394        }
2395        Ok(att)
2396    }
2397
2398    pub fn is_image(&self) -> bool {
2399        self.mime.starts_with("image/")
2400    }
2401
2402    /// One-line summary for transcript: `📎 name (image/png, 12 KB)`.
2403    pub fn summary(&self) -> String {
2404        format!(
2405            "📎 {} ({}, {} KB)",
2406            self.name,
2407            self.mime,
2408            self.size.div_ceil(1024)
2409        )
2410    }
2411}
2412
2413/// Merges attachments into prompt text: inlines text files in fenced blocks; converts images to a descriptive line
2414/// when `images_as_text` is true (for agents without image block support).
2415pub fn compose_text(text: &str, atts: &[Attachment], images_as_text: bool) -> String {
2416    let mut out = text.to_string();
2417    for a in atts {
2418        if a.is_image() {
2419            if images_as_text {
2420                out.push_str(&format!(
2421                    "\n\n[圖片附件:{}{}]",
2422                    a.name,
2423                    a.path
2424                        .as_deref()
2425                        .map(|p| format!(",路徑 {p}"))
2426                        .unwrap_or_default()
2427                ));
2428            }
2429        } else if let Some(t) = &a.text {
2430            out.push_str(&format!(
2431                "\n\n[檔案:{}]\n```\n{}\n```",
2432                a.name,
2433                t.trim_end()
2434            ));
2435        } else {
2436            out.push_str(&format!(
2437                "\n\n[檔案附件:{}{} (內容未內嵌)]",
2438                a.name,
2439                a.path
2440                    .as_deref()
2441                    .map(|p| format!(",路徑 {p}"))
2442                    .unwrap_or_default()
2443            ));
2444        }
2445    }
2446    out
2447}
2448
2449/// Masks common secrets and token patterns in text (protects secrets before writing to event log).
2450pub fn redact_secrets(input: &str) -> String {
2451    const PREFIXES: &[&str] = &[
2452        "github_pat_",
2453        "glpat-",
2454        "xoxb-",
2455        "xoxp-",
2456        "ghp_",
2457        "gho_",
2458        "ghu_",
2459        "AKIA",
2460        "AIza",
2461        "sk-",
2462    ];
2463    let mut out = String::with_capacity(input.len());
2464    let bytes = input.as_bytes();
2465    let mut i = 0;
2466    while i < bytes.len() {
2467        let Some(rest) = input.get(i..) else {
2468            break;
2469        };
2470        if let Some(pref) = PREFIXES.iter().find(|&&p| rest.starts_with(p)) {
2471            let after = &rest[pref.len()..];
2472            let token_len = after
2473                .bytes()
2474                .take_while(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'-')
2475                .count();
2476            if token_len >= 12 {
2477                out.push_str(pref);
2478                out.push_str("<REDACTED>");
2479                i += pref.len() + token_len;
2480                continue;
2481            }
2482        }
2483        let Some(ch) = rest.chars().next() else {
2484            break;
2485        };
2486        out.push(ch);
2487        i += ch.len_utf8();
2488    }
2489    out
2490}
2491
2492#[cfg(test)]
2493pub(crate) mod tests {
2494    use super::*;
2495
2496    fn rec(seq: u64, event: Event) -> Record {
2497        Record { seq, ts: 0, event }
2498    }
2499
2500    pub(crate) fn sample_session(id: &str) -> Session {
2501        Session {
2502            id: id.to_string(),
2503            kind: AgentKind::OpenCode,
2504            label: "worker".into(),
2505            cwd: "/tmp".into(),
2506            branch: None,
2507            role: Role::Worker,
2508            status: SessionStatus::Starting,
2509            model: None,
2510            cost: Cost::default(),
2511            parent: None,
2512            created_ms: 1,
2513            transport: "acp".into(),
2514            status_note: None,
2515            repo_root: None,
2516            context: None,
2517            native_id: None,
2518            permission: Default::default(),
2519            budget_usd: None,
2520            over_budget: false,
2521            handed_off_to: None,
2522            effort: None,
2523            slash_commands: Vec::new(),
2524            active_tools: Vec::new(),
2525            bg_procs: Vec::new(),
2526            tool_calls: 0,
2527            ended_ms: None,
2528        }
2529    }
2530
2531    #[test]
2532    fn output_append_continues_last_line() {
2533        let mut st = State::new();
2534        let mut seq = 0;
2535        let mut feed = |ev: Event| {
2536            seq += 1;
2537            st.apply(&rec(seq, ev));
2538        };
2539        let out = |text: &str| Event::Output {
2540            session: "s1".into(),
2541            text: text.into(),
2542        };
2543        let app = |text: &str| Event::OutputAppend {
2544            session: "s1".into(),
2545            text: text.into(),
2546        };
2547        feed(out("| a | b"));
2548        feed(app(" |\n| c"));
2549        feed(app(" | d |\n"));
2550        feed(out("next\n"));
2551        // Bare newline closes a dangling line without producing an empty one.
2552        feed(out("tail"));
2553        feed(app("\n"));
2554        let lines: Vec<_> = st.transcripts["s1"].iter().cloned().collect();
2555        assert_eq!(lines, ["| a | b |", "| c | d |", "next", "tail"]);
2556    }
2557
2558    #[test]
2559    fn output_append_on_empty_transcript_starts_a_line() {
2560        let mut st = State::new();
2561        st.apply(&rec(
2562            1,
2563            Event::OutputAppend {
2564                session: "s1".into(),
2565                text: "x\n".into(),
2566            },
2567        ));
2568        let lines: Vec<_> = st.transcripts["s1"].iter().cloned().collect();
2569        assert_eq!(lines, ["x"]);
2570    }
2571
2572    #[test]
2573    fn fold_tracks_status_and_transcript() {
2574        let mut st = State::new();
2575        st.apply(&rec(
2576            1,
2577            Event::SessionStarted {
2578                session: crate::tests::sample_session("s1"),
2579            },
2580        ));
2581        st.apply(&rec(
2582            2,
2583            Event::Output {
2584                session: "s1".into(),
2585                text: "hello\nworld".into(),
2586            },
2587        ));
2588        st.apply(&rec(
2589            3,
2590            Event::SessionStatus {
2591                session: "s1".into(),
2592                status: SessionStatus::Busy,
2593            },
2594        ));
2595
2596        assert_eq!(st.seq, 3);
2597        assert_eq!(st.sessions["s1"].status, SessionStatus::Busy);
2598        let lines: Vec<_> = st.transcripts["s1"].iter().cloned().collect();
2599        assert_eq!(lines, vec!["hello".to_string(), "world".to_string()]);
2600    }
2601
2602    #[test]
2603    fn permission_lifecycle() {
2604        let mut st = State::new();
2605        st.apply(&rec(
2606            1,
2607            Event::SessionStarted {
2608                session: crate::tests::sample_session("s1"),
2609            },
2610        ));
2611        st.apply(&rec(
2612            2,
2613            Event::PermissionRequested {
2614                request: PermissionRequest {
2615                    req: "r1".into(),
2616                    session: "s1".into(),
2617                    title: "Bash".into(),
2618                    detail: "rm -rf /".into(),
2619                },
2620            },
2621        ));
2622        assert_eq!(st.sessions["s1"].status, SessionStatus::WaitingApproval);
2623        assert_eq!(st.pending_permissions.len(), 1);
2624
2625        st.apply(&rec(
2626            3,
2627            Event::PermissionResolved {
2628                session: "s1".into(),
2629                req: "r1".into(),
2630                decision: Decision::Allow,
2631            },
2632        ));
2633        assert!(st.pending_permissions.is_empty());
2634    }
2635
2636    #[test]
2637    fn question_requested_and_resolved() {
2638        let mut st = State::new();
2639        st.apply(&rec(
2640            1,
2641            Event::SessionStarted {
2642                session: crate::tests::sample_session("s1"),
2643            },
2644        ));
2645        st.apply(&rec(
2646            2,
2647            Event::QuestionRequested {
2648                question: UserQuestion {
2649                    id: "q1".into(),
2650                    session: "s1".into(),
2651                    header: Some("Database".into()),
2652                    question: "Which database?".into(),
2653                    options: vec![
2654                        QuestionOption::new("PostgreSQL", Some("Recommended")),
2655                        QuestionOption::new("SQLite", None),
2656                    ],
2657                    multi_select: false,
2658                    custom: true,
2659                    group: None,
2660                },
2661            },
2662        ));
2663        assert_eq!(st.sessions["s1"].status, SessionStatus::WaitingApproval);
2664        assert_eq!(st.pending_questions.len(), 1);
2665        assert_eq!(st.pending_questions["q1"].options[0].label, "PostgreSQL");
2666
2667        st.apply(&rec(
2668            3,
2669            Event::QuestionResolved {
2670                session: "s1".into(),
2671                id: "q1".into(),
2672                answers: vec!["PostgreSQL".into()],
2673            },
2674        ));
2675        assert!(st.pending_questions.is_empty());
2676    }
2677
2678    #[test]
2679    fn session_exit_clears_pending_questions() {
2680        let mut st = State::new();
2681        st.apply(&rec(
2682            1,
2683            Event::SessionStarted {
2684                session: crate::tests::sample_session("s1"),
2685            },
2686        ));
2687        st.apply(&rec(
2688            2,
2689            Event::QuestionRequested {
2690                question: UserQuestion {
2691                    id: "q1".into(),
2692                    session: "s1".into(),
2693                    header: None,
2694                    question: "Pick one".into(),
2695                    options: Vec::new(),
2696                    multi_select: false,
2697                    custom: true,
2698                    group: None,
2699                },
2700            },
2701        ));
2702        assert_eq!(st.pending_questions.len(), 1);
2703
2704        st.apply(&rec(
2705            3,
2706            Event::SessionExited {
2707                session: "s1".into(),
2708                code: Some(0),
2709            },
2710        ));
2711        assert!(st.pending_questions.is_empty());
2712    }
2713
2714    #[test]
2715    fn session_cleared_resets_context_but_keeps_identity() {
2716        let mut st = State::new();
2717        let mut s = sample_session("s1");
2718        s.native_id = Some("nat".into());
2719        s.cost = Cost {
2720            usd: 1.5,
2721            input_tokens: 10,
2722            output_tokens: 20,
2723        };
2724        s.context = Some(ContextUsage {
2725            used: 5,
2726            window: None,
2727        });
2728        s.status_note = Some("note".into());
2729        s.tool_calls = 7;
2730        let label = s.label.clone();
2731        st.apply(&rec(1, Event::SessionStarted { session: s }));
2732        st.transcripts
2733            .entry("s1".into())
2734            .or_default()
2735            .push_back("❯ hi".into());
2736        st.apply(&rec(
2737            2,
2738            Event::SessionCleared {
2739                session: "s1".into(),
2740            },
2741        ));
2742        let s = &st.sessions["s1"];
2743        assert_eq!(s.native_id, None);
2744        assert_eq!(s.cost, Cost::default());
2745        assert_eq!(s.context, None);
2746        assert_eq!(s.status_note, None);
2747        assert_eq!(s.tool_calls, 0);
2748        assert_eq!(s.label, label, "label 應保留");
2749        assert!(!st.transcripts.contains_key("s1"));
2750        // 清除後 agent 回報的新 native id 會被套用。
2751        st.apply(&rec(
2752            3,
2753            Event::SessionNativeId {
2754                session: "s1".into(),
2755                native_id: "fresh".into(),
2756            },
2757        ));
2758        assert_eq!(st.sessions["s1"].native_id.as_deref(), Some("fresh"));
2759    }
2760
2761    #[test]
2762    fn agent_kind_roundtrip() {
2763        for k in AgentKind::builtins() {
2764            assert_eq!(AgentKind::parse(k.id()).as_ref(), Some(&k));
2765        }
2766        assert_eq!(AgentKind::OpenCode.acp_command().unwrap().0, "opencode");
2767        assert!(AgentKind::Codex.acp_command().is_none());
2768    }
2769
2770    #[test]
2771    fn resolve_session_by_label_and_filter_inbox() {
2772        let mut st = State::new();
2773        let mut s1 = sample_session("ses_1");
2774        s1.label = "worker/impl".into();
2775        let mut s2 = sample_session("ses_2");
2776        s2.label = "worker/test".into();
2777        st.apply(&rec(1, Event::SessionStarted { session: s1 }));
2778        st.apply(&rec(2, Event::SessionStarted { session: s2 }));
2779
2780        assert_eq!(
2781            st.resolve_session_id("worker/impl"),
2782            Some("ses_1".to_string())
2783        );
2784        assert_eq!(
2785            st.resolve_session_id("@worker/test"),
2786            Some("ses_2".to_string())
2787        );
2788
2789        st.apply(&rec(
2790            3,
2791            Event::BusMessage {
2792                message: BusMessage {
2793                    id: "m1".into(),
2794                    from: "ses_2".into(),
2795                    to: Target::Direct("worker/impl".into()),
2796                    kind: MsgKind::Question,
2797                    body: "API shape?".into(),
2798                    reply_to: None,
2799                    ts: 10,
2800                },
2801            },
2802        ));
2803        st.apply(&rec(
2804            4,
2805            Event::BusMessage {
2806                message: BusMessage {
2807                    id: "m2".into(),
2808                    from: "ses_1".into(),
2809                    to: Target::Broadcast,
2810                    kind: MsgKind::Chat,
2811                    body: "ready".into(),
2812                    reply_to: None,
2813                    ts: 11,
2814                },
2815            },
2816        ));
2817
2818        let inbox1 = st.inbox_for("ses_1", None);
2819        assert_eq!(inbox1.len(), 1);
2820        assert_eq!(inbox1[0].id, "m1");
2821
2822        let inbox1_after = st.inbox_for("ses_1", Some("m1"));
2823        assert!(inbox1_after.is_empty());
2824
2825        let inbox2 = st.inbox_for("ses_2", None);
2826        assert_eq!(inbox2.len(), 1);
2827        assert_eq!(inbox2[0].id, "m2");
2828    }
2829
2830    #[test]
2831    fn policy_engine_and_secret_redaction() {
2832        let policy = PolicyEngine::default();
2833        assert_eq!(
2834            policy.evaluate("Bash", "rm -rf / --no-preserve-root"),
2835            Some(Decision::Deny)
2836        );
2837        assert_eq!(
2838            policy.evaluate("Read", "src/main.rs"),
2839            Some(Decision::Allow)
2840        );
2841        assert_eq!(policy.evaluate("Bash", "cargo test"), None);
2842
2843        let custom = PolicyEngine::parse_toml(
2844            r#"
2845            allow = ["cargo test", "Read"]
2846            deny = ["curl http"]
2847            "#,
2848        );
2849        assert_eq!(custom.evaluate("Bash", "cargo test"), Some(Decision::Allow));
2850        assert_eq!(
2851            custom.evaluate("Bash", "curl http://evil"),
2852            Some(Decision::Deny)
2853        );
2854
2855        let raw = "key is sk-1234567890abcdefghij and ghp_abcdefghijklmnopqrst1234";
2856        let scrubbed = redact_secrets(raw);
2857        assert!(scrubbed.contains("sk-<REDACTED>"));
2858        assert!(scrubbed.contains("ghp_<REDACTED>"));
2859        assert!(!scrubbed.contains("1234567890abcdefghij"));
2860    }
2861
2862    #[test]
2863    fn redact_secrets_tricky_input() {
2864        assert_eq!(redact_secrets(""), "");
2865        assert_eq!(redact_secrets("sk-short"), "sk-short");
2866        assert_eq!(
2867            redact_secrets("金鑰 sk-1234567890abcdefghij 結束"),
2868            "金鑰 sk-<REDACTED> 結束"
2869        );
2870        assert_eq!(
2871            redact_secrets("🦀 ghp_1234567890abcdefghij 🦀"),
2872            "🦀 ghp_<REDACTED> 🦀"
2873        );
2874        assert_eq!(redact_secrets("sk-"), "sk-");
2875        assert_eq!(redact_secrets("ghp_12345678901"), "ghp_12345678901");
2876        assert_eq!(redact_secrets("ghp_123456789012"), "ghp_<REDACTED>");
2877        assert_eq!(redact_secrets("xoxb-123456789012"), "xoxb-<REDACTED>");
2878        assert_eq!(
2879            redact_secrets("github_pat_123456789012"),
2880            "github_pat_<REDACTED>"
2881        );
2882        assert_eq!(redact_secrets("gho_123456789012"), "gho_<REDACTED>");
2883        assert_eq!(redact_secrets("ghu_123456789012"), "ghu_<REDACTED>");
2884        assert_eq!(redact_secrets("glpat-123456789012"), "glpat-<REDACTED>");
2885        assert_eq!(redact_secrets("xoxp-123456789012"), "xoxp-<REDACTED>");
2886        assert_eq!(redact_secrets("AIza123456789012"), "AIza<REDACTED>");
2887        assert_eq!(redact_secrets("AIzashort"), "AIzashort");
2888    }
2889
2890    #[test]
2891    fn session_model_event_updates_state() {
2892        let mut st = State::new();
2893        st.apply(&Record {
2894            seq: 1,
2895            ts: 0,
2896            event: Event::SessionStarted {
2897                session: crate::tests::sample_session("s1"),
2898            },
2899        });
2900        st.apply(&Record {
2901            seq: 2,
2902            ts: 0,
2903            event: Event::SessionModel {
2904                session: "s1".into(),
2905                model: "opus".into(),
2906            },
2907        });
2908        assert_eq!(st.sessions["s1"].model.as_deref(), Some("opus"));
2909    }
2910
2911    #[test]
2912    fn native_id_event_updates_state_and_old_json_parses_without_it() {
2913        let mut st = State::new();
2914        st.apply(&rec(
2915            1,
2916            Event::SessionStarted {
2917                session: sample_session("s1"),
2918            },
2919        ));
2920        assert_eq!(st.sessions["s1"].native_id, None);
2921        st.apply(&rec(
2922            2,
2923            Event::SessionNativeId {
2924                session: "s1".into(),
2925                native_id: "abc".into(),
2926            },
2927        ));
2928        assert_eq!(st.sessions["s1"].native_id.as_deref(), Some("abc"));
2929        // After resumption the agent changed its ID: latest takes precedence.
2930        st.apply(&rec(
2931            3,
2932            Event::SessionNativeId {
2933                session: "s1".into(),
2934                native_id: "def".into(),
2935            },
2936        ));
2937        assert_eq!(st.sessions["s1"].native_id.as_deref(), Some("def"));
2938
2939        // Sessions in older logs do not have the native_id field.
2940        let mut v = serde_json::to_value(sample_session("old")).unwrap();
2941        v.as_object_mut().unwrap().remove("native_id");
2942        let s: Session = serde_json::from_value(v).unwrap();
2943        assert_eq!(s.native_id, None);
2944    }
2945
2946    #[test]
2947    fn log_health_event_updates_state_and_defaults_to_true() {
2948        let mut st = State::new();
2949        assert!(st.log_ok);
2950        st.apply(&rec(1, Event::LogHealth { ok: false }));
2951        assert!(!st.log_ok);
2952        st.apply(&rec(2, Event::LogHealth { ok: true }));
2953        assert!(st.log_ok);
2954    }
2955
2956    #[test]
2957    fn old_session_json_without_permission_parses() {
2958        let mut v = serde_json::to_value(sample_session("s1")).unwrap();
2959        v.as_object_mut().unwrap().remove("permission");
2960        let s: Session = serde_json::from_value(v).unwrap();
2961        assert_eq!(s.permission, PermissionPolicy::Auto);
2962    }
2963
2964    #[test]
2965    fn allow_rules_match_whole_words_only() {
2966        let p = PolicyEngine::default();
2967        // `cat README.md` must not be allowed because of `Read`
2968        assert_eq!(
2969            p.evaluate("cat README.md", r#"{"command":"cat README.md"}"#),
2970            None
2971        );
2972        assert_eq!(p.evaluate("Read", "{}"), Some(Decision::Allow));
2973        assert_eq!(
2974            p.evaluate("bash", r#"{"command":"git status -s"}"#),
2975            Some(Decision::Allow)
2976        );
2977        assert_eq!(p.evaluate("bash", r#"{"command":"git statusx"}"#), None);
2978    }
2979
2980    #[test]
2981    fn deny_beats_allow_and_repo_cannot_remove_deny() {
2982        let p = PolicyEngine::default();
2983        assert_eq!(
2984            p.evaluate("bash", r#"{"command":"git status && git push --force"}"#),
2985            Some(Decision::Deny)
2986        );
2987        let local = PolicyEngine {
2988            allow: vec![],
2989            deny: vec!["curl".into()],
2990        };
2991        let m = p.merged_with(&local);
2992        assert!(m.deny.contains(&"git push --force".to_string()));
2993        assert!(m.deny.contains(&"curl".to_string()));
2994    }
2995
2996    #[test]
2997    fn tool_calls_render_readable_summary_and_results() {
2998        let mut st = State::new();
2999        st.apply(&rec(
3000            1,
3001            Event::SessionStarted {
3002                session: crate::tests::sample_session("s1"),
3003            },
3004        ));
3005        st.apply(&rec(
3006            2,
3007            Event::ToolCall {
3008                session: "s1".into(),
3009                name: "Bash".into(),
3010                input: r#"{"command":"git status\n  -s","description":"x"}"#.into(),
3011                ok: None,
3012                output: None,
3013            },
3014        ));
3015        st.apply(&rec(
3016            3,
3017            Event::ToolCall {
3018                session: "s1".into(),
3019                name: String::new(),
3020                input: String::new(),
3021                ok: Some(false),
3022                output: Some("fatal: not a repo\nmore".into()),
3023            },
3024        ));
3025        let t: Vec<_> = st.transcripts["s1"].iter().cloned().collect();
3026        assert_eq!(t[0], "▸ Bash: git status -s");
3027        assert_eq!(t[1], "  ✗ fatal: not a repo …(+1 行)");
3028    }
3029
3030    #[test]
3031    fn prompts_from_others_are_marked_with_source() {
3032        let mut st = State::new();
3033        st.apply(&rec(
3034            1,
3035            Event::UserPrompt {
3036                session: "w".into(),
3037                text: "do it".into(),
3038                from: Some("ghost".into()),
3039            },
3040        ));
3041        st.apply(&rec(
3042            2,
3043            Event::UserPrompt {
3044                session: "w".into(),
3045                text: "提醒\n第二行".into(),
3046                from: Some(PROMPT_FROM_ERTANGLE.into()),
3047            },
3048        ));
3049        st.apply(&rec(
3050            3,
3051            Event::UserPrompt {
3052                session: "w".into(),
3053                text: "mine".into(),
3054                from: None,
3055            },
3056        ));
3057        let t: Vec<&str> = st.transcripts["w"].iter().map(String::as_str).collect();
3058        assert_eq!(
3059            t,
3060            ["» [ghost] do it", "» [ertangle] 提醒", "  第二行", "❯ mine"]
3061        );
3062        assert_eq!(parse_prompt_line(t[0]), Some((Some("ghost"), "do it")));
3063        assert_eq!(parse_prompt_line(t[3]), Some((None, "mine")));
3064        assert_eq!(parse_prompt_line("» quote"), None);
3065        assert_eq!(parse_prompt_line("plain"), None);
3066        // Older events do not have `from`: treat as user.
3067        let old: Event =
3068            serde_json::from_str(r#"{"kind":"user_prompt","session":"w","text":"x"}"#).unwrap();
3069        assert!(matches!(old, Event::UserPrompt { from: None, .. }));
3070    }
3071
3072    #[test]
3073    fn record_wire_format_is_flat() {
3074        // Web version (applyRecord in `web/index.html`) relies on top-level event fields; nesting would break all real-time updates.
3075        let r = Record {
3076            seq: 7,
3077            ts: 1,
3078            event: Event::Output {
3079                session: "s1".into(),
3080                text: "hi".into(),
3081            },
3082        };
3083        let v: serde_json::Value = serde_json::to_value(&r).unwrap();
3084        assert_eq!(v["seq"], 7);
3085        assert_eq!(v["kind"], "output");
3086        assert_eq!(v["session"], "s1");
3087        assert!(v.get("event").is_none());
3088    }
3089
3090    #[test]
3091    fn tool_calls_count_only_start_events() {
3092        let mut st = State::new();
3093        st.apply(&rec(
3094            1,
3095            Event::SessionStarted {
3096                session: sample_session("s1"),
3097            },
3098        ));
3099        let call = |ok: Option<bool>, name: &str| Event::ToolCall {
3100            session: "s1".into(),
3101            name: name.into(),
3102            input: String::new(),
3103            ok,
3104            output: None,
3105        };
3106        st.apply(&rec(2, call(None, "Bash")));
3107        st.apply(&rec(3, call(Some(true), "Bash")));
3108        st.apply(&rec(4, call(None, "Read")));
3109        // Start events without a name do not count.
3110        st.apply(&rec(5, call(None, "")));
3111        assert_eq!(st.sessions["s1"].tool_calls, 2);
3112    }
3113
3114    #[test]
3115    fn active_tools_and_bg_procs_lifecycle() {
3116        assert!(is_subagent_tool("Task"));
3117        assert!(is_subagent_tool("Agent"));
3118        assert!(is_subagent_tool("invoke_subagent"));
3119        assert!(is_subagent_tool("spawn_agent"));
3120        assert!(!is_subagent_tool("Bash"));
3121
3122        let mut st = State::new();
3123        st.apply(&rec(
3124            1,
3125            Event::SessionStarted {
3126                session: sample_session("s1"),
3127            },
3128        ));
3129
3130        // Tool starts executing
3131        st.apply(&rec(
3132            2,
3133            Event::ToolCall {
3134                session: "s1".into(),
3135                name: "Bash".into(),
3136                input: r#"{"command":"cargo test"}"#.into(),
3137                ok: None,
3138                output: None,
3139            },
3140        ));
3141        assert_eq!(st.sessions["s1"].active_tools.len(), 1);
3142        assert_eq!(st.sessions["s1"].active_tools[0].name, "Bash");
3143        assert!(!st.sessions["s1"].active_tools[0].is_subagent);
3144
3145        // Native subagent starts executing
3146        st.apply(&rec(
3147            3,
3148            Event::ToolCall {
3149                session: "s1".into(),
3150                name: "Task".into(),
3151                input: r#"{"prompt":"review"}"#.into(),
3152                ok: None,
3153                output: None,
3154            },
3155        ));
3156        assert_eq!(st.sessions["s1"].active_tools.len(), 2);
3157        assert!(st.sessions["s1"].active_tools[1].is_subagent);
3158
3159        // First tool completes
3160        st.apply(&rec(
3161            4,
3162            Event::ToolCall {
3163                session: "s1".into(),
3164                name: "Bash".into(),
3165                input: String::new(),
3166                ok: Some(true),
3167                output: Some("ok".into()),
3168            },
3169        ));
3170        assert_eq!(st.sessions["s1"].active_tools.len(), 1);
3171        assert_eq!(st.sessions["s1"].active_tools[0].name, "Task");
3172
3173        // Turn ends and transitions to Idle, clearing remaining active_tools
3174        st.apply(&rec(
3175            5,
3176            Event::SessionStatus {
3177                session: "s1".into(),
3178                status: SessionStatus::Idle,
3179            },
3180        ));
3181        assert!(st.sessions["s1"].active_tools.is_empty());
3182
3183        // Background process event updates
3184        st.apply(&rec(
3185            6,
3186            Event::SessionBgProcs {
3187                session: "s1".into(),
3188                procs: vec![BgProc {
3189                    pid: 1234,
3190                    name: "node".into(),
3191                    cmdline: "node server.js".into(),
3192                    elapsed_secs: 15,
3193                }],
3194            },
3195        ));
3196        assert_eq!(st.sessions["s1"].bg_procs.len(), 1);
3197        assert_eq!(st.sessions["s1"].bg_procs[0].pid, 1234);
3198    }
3199
3200    #[test]
3201    fn export_markdown_includes_tree_tasks_cost_diff_and_redacts_secrets() {
3202        let mut st = State::new();
3203        let mut root = sample_session("root");
3204        root.label = "coord/main".into();
3205        root.role = Role::Coordinator;
3206        root.branch = Some("ertangle/main".into());
3207        root.status = SessionStatus::Exited;
3208        root.cost = Cost {
3209            usd: 1.25,
3210            input_tokens: 1000,
3211            output_tokens: 200,
3212        };
3213        st.apply(&rec(1, Event::SessionStarted { session: root }));
3214
3215        for (id, label, usd) in [("c1", "worker/impl", 0.5), ("c2", "reviewer/code", 0.25)] {
3216            let mut child = sample_session(id);
3217            child.label = label.into();
3218            child.parent = Some("root".into());
3219            child.role = if id == "c2" {
3220                Role::Reviewer
3221            } else {
3222                Role::Worker
3223            };
3224            child.status = SessionStatus::Exited;
3225            child.cost = Cost {
3226                usd,
3227                input_tokens: 100,
3228                output_tokens: 20,
3229            };
3230            st.apply(&rec(2, Event::SessionStarted { session: child }));
3231        }
3232        st.apply(&rec(
3233            3,
3234            Event::TaskChanged {
3235                task: Task {
3236                    id: "task_1".into(),
3237                    title: "完成匯出功能".into(),
3238                    detail: String::new(),
3239                    status: TaskStatus::Done,
3240                    assignee: Some("c1".into()),
3241                    created_by: Some("root".into()),
3242                    depends_on: vec![],
3243                    updated_ms: 0,
3244                },
3245            },
3246        ));
3247        st.apply(&rec(
3248            4,
3249            Event::UserPrompt {
3250                session: "root".into(),
3251                text: "API key: sk-1234567890abcdefghijklmnop".into(),
3252                from: None,
3253            },
3254        ));
3255        st.apply(&rec(
3256            5,
3257            Event::Output {
3258                session: "c1".into(),
3259                text: "done".into(),
3260            },
3261        ));
3262
3263        let md = st
3264            .export_markdown("coord/main", true, Some("diff --git a/x b/x\n+new"))
3265            .unwrap();
3266        assert!(md.starts_with("# 協作報告:coord/main"));
3267        assert!(md.contains("子 Session 階層"), "{md}");
3268        assert!(
3269            md.contains("worker/impl") && md.contains("reviewer/code"),
3270            "{md}"
3271        );
3272        assert!(md.contains("$2.0000"), "{md}"); // 1.25 + 0.5 + 0.25
3273        assert!(md.contains("1200 in / 240 out"), "{md}");
3274        assert!(md.contains("task_1") && md.contains("完成匯出功能"), "{md}");
3275        assert!(md.contains("```diff") && md.contains("+new"), "{md}");
3276        assert!(md.contains("sk-<REDACTED>"), "{md}");
3277        assert!(!md.contains("sk-1234567890abcdefghijklmnop"), "{md}");
3278
3279        // Without subtree, contains only root session tasks and costs.
3280        let md_flat = st.export_markdown("root", false, None).unwrap();
3281        assert!(!md_flat.contains("子 Session 階層"), "{md_flat}");
3282        assert!(!md_flat.contains("### worker/impl"), "{md_flat}");
3283        assert!(md_flat.contains("$1.2500"), "{md_flat}");
3284
3285        assert!(st.export_markdown("nope", true, None).is_err());
3286    }
3287}
3288
3289#[cfg(test)]
3290mod attachment_tests {
3291    use super::*;
3292
3293    #[test]
3294    fn limit_detection_matches_real_messages_but_not_normal_errors() {
3295        assert!(looks_like_limit(
3296            "You've hit your 5-hour limit · resets 4:30am (Asia/Taipei)"
3297        ));
3298        assert!(looks_like_limit("Error: 429 Too Many Requests"));
3299        assert!(looks_like_limit("exceeded your current quota"));
3300        assert!(!looks_like_limit("File not found: limits.rs"));
3301        assert!(!looks_like_limit("compile error"));
3302    }
3303
3304    #[test]
3305    fn quota_summary_and_reset_handling() {
3306        let q = Quota {
3307            agent: "claude".into(),
3308            windows: vec![
3309                QuotaWindow {
3310                    name: "5h".into(),
3311                    used_percent: 39.0,
3312                    resets_at_ms: Some(10_000_000 + 80 * 60_000),
3313                },
3314                QuotaWindow {
3315                    name: "7d".into(),
3316                    used_percent: 22.0,
3317                    resets_at_ms: Some(1),
3318                },
3319            ],
3320            reached: false,
3321            warning: false,
3322            updated_ms: 0,
3323        };
3324        let s = q.summary(10_000_000);
3325        assert!(s.contains("5h 39% (重置 1h20m)"), "{s}");
3326        assert!(s.contains("7d 已重置"));
3327        assert_eq!(window_name(300), "5h");
3328        assert_eq!(window_name(43200), "30d");
3329        assert_eq!(format_remaining(30_000), "<1m");
3330        assert_eq!(format_remaining(90 * 60_000), "1h30m");
3331        assert_eq!(format_remaining(50 * 3_600_000), "2d2h");
3332    }
3333
3334    #[test]
3335    fn quota_maxima_exclude_inactive_and_reset_windows() {
3336        let q = Quota {
3337            agent: "antigravity".into(),
3338            windows: vec![
3339                QuotaWindow {
3340                    name: "3p-7d".into(),
3341                    used_percent: 90.33,
3342                    resets_at_ms: Some(300),
3343                },
3344                QuotaWindow {
3345                    name: "7d".into(),
3346                    used_percent: 61.0,
3347                    resets_at_ms: Some(300),
3348                },
3349                QuotaWindow {
3350                    name: "5h".into(),
3351                    used_percent: 99.0,
3352                    resets_at_ms: Some(100),
3353                },
3354            ],
3355            reached: false,
3356            warning: false,
3357            updated_ms: 0,
3358        };
3359
3360        assert_eq!(q.max_used(), 99.0);
3361        assert_eq!(q.max_used_live(200), 61.0);
3362        assert_eq!(q.max_used_live(300), 0.0);
3363        assert!(q.summary(0).contains("3p-7d 90%"));
3364    }
3365
3366    #[test]
3367    fn quota_is_reached_clears_after_exhausted_window_resets() {
3368        let mut q = Quota {
3369            agent: "claude".into(),
3370            windows: vec![
3371                QuotaWindow {
3372                    name: "5h".into(),
3373                    used_percent: 100.0,
3374                    resets_at_ms: Some(100),
3375                },
3376                QuotaWindow {
3377                    name: "7d".into(),
3378                    used_percent: 51.0,
3379                    resets_at_ms: Some(500),
3380                },
3381            ],
3382            reached: true,
3383            warning: false,
3384            updated_ms: 0,
3385        };
3386
3387        // Before 5h reset: still reached, summary contains ✗額度已滿.
3388        assert!(q.is_reached(50));
3389        let sum_before = q.summary(50);
3390        assert!(sum_before.contains("✗額度已滿"), "{sum_before}");
3391
3392        // After 5h reset: is_reached is false, summary no longer contains ✗額度已滿.
3393        assert!(!q.is_reached(150));
3394        let sum_after = q.summary(150);
3395        assert!(!sum_after.contains("✗額度已滿"), "{sum_after}");
3396        assert!(sum_after.contains("5h 已重置"), "{sum_after}");
3397
3398        // If another active live window is >= 100%: still reached.
3399        q.windows[1].used_percent = 100.0;
3400        assert!(q.is_reached(150));
3401        assert!(q.summary(150).contains("✗額度已滿"));
3402
3403        // If windows is empty: falls back to self.reached.
3404        let empty_reached = Quota {
3405            agent: "claude".into(),
3406            windows: vec![],
3407            reached: true,
3408            warning: false,
3409            updated_ms: 0,
3410        };
3411        assert!(empty_reached.is_reached(150));
3412
3413        let empty_not_reached = Quota {
3414            agent: "claude".into(),
3415            windows: vec![],
3416            reached: false,
3417            warning: false,
3418            updated_ms: 0,
3419        };
3420        assert!(!empty_not_reached.is_reached(150));
3421    }
3422
3423    #[test]
3424    fn third_party_windows_remain_active_for_other_agents() {
3425        let q = Quota {
3426            agent: "claude".into(),
3427            windows: vec![QuotaWindow {
3428                name: "3p-7d".into(),
3429                used_percent: 90.0,
3430                resets_at_ms: None,
3431            }],
3432            reached: false,
3433            warning: false,
3434            updated_ms: 0,
3435        };
3436        assert_eq!(q.max_used(), 90.0);
3437        assert_eq!(q.max_used_live(0), 90.0);
3438    }
3439
3440    #[test]
3441    fn context_usage_formats_and_keeps_last_used_when_only_window_arrives() {
3442        assert_eq!(human_tokens(950), "950");
3443        assert_eq!(human_tokens(36_267), "36k");
3444        assert_eq!(human_tokens(1_000_000), "1M");
3445        assert_eq!(human_tokens(1_500_000), "1.5M");
3446        let c = ContextUsage {
3447            used: 36_000,
3448            window: Some(1_000_000),
3449        };
3450        assert_eq!(c.short(), "36k/1M 4%");
3451        assert_eq!(
3452            ContextUsage {
3453                used: 5_000,
3454                window: None
3455            }
3456            .short(),
3457            "5k"
3458        );
3459        let mut st = State::new();
3460        st.apply(&Record {
3461            seq: 1,
3462            ts: 0,
3463            event: Event::SessionStarted {
3464                session: crate::tests::sample_session("s1"),
3465            },
3466        });
3467        st.apply(&Record {
3468            seq: 2,
3469            ts: 0,
3470            event: Event::SessionContext {
3471                session: "s1".into(),
3472                used: 36_000,
3473                window: None,
3474            },
3475        });
3476        st.apply(&Record {
3477            seq: 3,
3478            ts: 0,
3479            event: Event::SessionContext {
3480                session: "s1".into(),
3481                used: 0,
3482                window: Some(200_000),
3483            },
3484        });
3485        let c = st.sessions["s1"].context.unwrap();
3486        assert_eq!((c.used, c.window), (36_000, Some(200_000)));
3487        // Reuses window when only usage updates later
3488        st.apply(&Record {
3489            seq: 4,
3490            ts: 0,
3491            event: Event::SessionContext {
3492                session: "s1".into(),
3493                used: 50_000,
3494                window: None,
3495            },
3496        });
3497        assert_eq!(st.sessions["s1"].context.unwrap().window, Some(200_000));
3498    }
3499
3500    #[test]
3501    fn base64_matches_known_vectors() {
3502        assert_eq!(base64_encode(b""), "");
3503        assert_eq!(base64_encode(b"f"), "Zg==");
3504        assert_eq!(base64_encode(b"fo"), "Zm8=");
3505        assert_eq!(base64_encode(b"foo"), "Zm9v");
3506        assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
3507    }
3508
3509    #[test]
3510    fn compose_text_embeds_files_and_notes_images() {
3511        let f = Attachment {
3512            name: "a.rs".into(),
3513            mime: "text/plain".into(),
3514            text: Some("fn main() {}\n".into()),
3515            ..Default::default()
3516        };
3517        let img = Attachment {
3518            name: "p.png".into(),
3519            mime: "image/png".into(),
3520            path: Some("/tmp/p.png".into()),
3521            data: Some("AAAA".into()),
3522            ..Default::default()
3523        };
3524        let t = compose_text("看", &[f.clone(), img.clone()], true);
3525        assert!(t.contains("```\nfn main() {}\n```") && t.contains("圖片附件:p.png"));
3526        let t2 = compose_text("看", &[f, img], false);
3527        assert!(!t2.contains("圖片附件"));
3528    }
3529
3530    #[test]
3531    fn old_session_json_without_budget_fields_parses() {
3532        let mut val = serde_json::to_value(crate::tests::sample_session("s1")).unwrap();
3533        let obj = val.as_object_mut().unwrap();
3534        obj.remove("budget_usd");
3535        obj.remove("over_budget");
3536        let parsed: Session = serde_json::from_value(val).unwrap();
3537        assert_eq!(parsed.budget_usd, None);
3538        assert!(!parsed.over_budget);
3539    }
3540
3541    #[test]
3542    fn old_session_json_without_handed_off_to_parses() {
3543        let mut val = serde_json::to_value(crate::tests::sample_session("s1")).unwrap();
3544        val.as_object_mut().unwrap().remove("handed_off_to");
3545        let parsed: Session = serde_json::from_value(val).unwrap();
3546        assert_eq!(parsed.handed_off_to, None);
3547    }
3548
3549    fn handoff(st: &mut State, seq: u64, from: &str, to: &str) {
3550        st.apply(&Record {
3551            seq,
3552            ts: 0,
3553            event: Event::SessionHandedOff {
3554                from: from.into(),
3555                to: to.into(),
3556            },
3557        });
3558    }
3559
3560    #[test]
3561    fn successor_follows_chain_and_survives_cycles() {
3562        let mut st = State::new();
3563        for (i, id) in ["a", "b", "c"].into_iter().enumerate() {
3564            st.apply(&Record {
3565                seq: i as u64,
3566                ts: 0,
3567                event: Event::SessionStarted {
3568                    session: crate::tests::sample_session(id),
3569                },
3570            });
3571        }
3572        assert_eq!(st.successor_of("a"), "a");
3573        handoff(&mut st, 10, "a", "b");
3574        assert_eq!(st.successor_of("a"), "b");
3575        handoff(&mut st, 11, "b", "c");
3576        assert_eq!(st.successor_of("a"), "c");
3577        assert_eq!(st.successor_of("unknown"), "unknown");
3578        // Cycle: c -> a, terminates on the last new node in the cycle without infinite looping.
3579        handoff(&mut st, 12, "c", "a");
3580        assert_eq!(st.successor_of("a"), "c");
3581        // Handoff to itself.
3582        handoff(&mut st, 13, "a", "a");
3583        assert_eq!(st.successor_of("a"), "a");
3584    }
3585
3586    #[test]
3587    fn session_budget_formatting_and_state_events() {
3588        let mut s = crate::tests::sample_session("s1");
3589        s.cost.usd = 1.2;
3590        assert_eq!(s.format_budget(), None);
3591        s.budget_usd = Some(5.0);
3592        assert_eq!(s.format_budget().as_deref(), Some("$1.20/$5"));
3593        s.budget_usd = Some(2.5);
3594        assert_eq!(s.format_budget().as_deref(), Some("$1.20/$2.50"));
3595
3596        let mut st = State::new();
3597        st.apply(&Record {
3598            seq: 1,
3599            ts: 0,
3600            event: Event::SessionStarted { session: s },
3601        });
3602        st.apply(&Record {
3603            seq: 2,
3604            ts: 0,
3605            event: Event::SessionOverBudget {
3606                session: "s1".into(),
3607                spent: 2.5,
3608                limit: 2.5,
3609            },
3610        });
3611        assert!(st.sessions["s1"].over_budget);
3612
3613        st.apply(&Record {
3614            seq: 3,
3615            ts: 0,
3616            event: Event::SessionBudget {
3617                session: "s1".into(),
3618                budget_usd: Some(10.0),
3619            },
3620        });
3621        assert!(!st.sessions["s1"].over_budget);
3622        assert_eq!(st.sessions["s1"].budget_usd, Some(10.0));
3623    }
3624
3625    #[test]
3626    fn removed_resumable_session_is_archived_and_resolvable() {
3627        let mut st = State::new();
3628        let mut s = crate::tests::sample_session("ses_arch");
3629        s.label = "worker/arch".into();
3630        s.native_id = Some("nat-arch-1".into());
3631        st.apply(&Record {
3632            seq: 1,
3633            ts: 100,
3634            event: Event::SessionStarted { session: s },
3635        });
3636        st.apply(&Record {
3637            seq: 2,
3638            ts: 101,
3639            event: Event::UserPrompt {
3640                session: "ses_arch".into(),
3641                text: "請幫我檢查這份報表".into(),
3642                from: None,
3643            },
3644        });
3645        st.apply(&Record {
3646            seq: 3,
3647            ts: 102,
3648            event: Event::SessionRemoved {
3649                session: "ses_arch".into(),
3650            },
3651        });
3652        assert!(!st.sessions.contains_key("ses_arch"));
3653        let arch = st
3654            .archived_sessions
3655            .get("ses_arch")
3656            .expect("具備 native_id 的已移除 session 應被封存");
3657        assert_eq!(arch.status, SessionStatus::Exited);
3658        assert_eq!(arch.status_note.as_deref(), Some("請幫我檢查這份報表"));
3659        assert!(
3660            st.transcripts.contains_key("ses_arch"),
3661            "封存的 session 應保留逐字稿"
3662        );
3663
3664        for query in ["ses_arch", "worker/arch", "nat-arch-1"] {
3665            let (found, is_arch) = st
3666                .resolve_resumable_session(query)
3667                .unwrap_or_else(|| panic!("應能以 {query} 解析封存的 session"));
3668            assert!(is_arch);
3669            assert_eq!(found.id, "ses_arch");
3670        }
3671
3672        // Upon relaunch (resumption), it should be removed from archived_sessions and return to sessions.
3673        st.apply(&Record {
3674            seq: 4,
3675            ts: 103,
3676            event: Event::SessionStarted {
3677                session: arch.clone(),
3678            },
3679        });
3680        assert!(!st.archived_sessions.contains_key("ses_arch"));
3681        assert!(st.sessions.contains_key("ses_arch"));
3682    }
3683}
3684
3685#[cfg(test)]
3686mod inbox_cursor_tests {
3687    use super::*;
3688
3689    #[test]
3690    fn inbox_read_event_sets_cursor_and_roundtrips() {
3691        let mut st = State::new();
3692        st.apply(&Record {
3693            seq: 1,
3694            ts: 0,
3695            event: Event::InboxRead {
3696                session: "s1".into(),
3697                msg: "m9".into(),
3698            },
3699        });
3700        assert_eq!(st.inbox_cursors.get("s1").map(String::as_str), Some("m9"));
3701        let back: State = serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap();
3702        assert_eq!(back.inbox_cursors, st.inbox_cursors);
3703    }
3704}
3705
3706#[cfg(test)]
3707mod archive_retention_tests {
3708    use super::*;
3709
3710    const DAY: u64 = 86_400_000;
3711
3712    fn archived(id: &str, ended_ms: Option<u64>, created_ms: u64) -> Session {
3713        let mut s = crate::tests::sample_session(id);
3714        s.created_ms = created_ms;
3715        s.ended_ms = ended_ms;
3716        s
3717    }
3718
3719    fn rec(seq: u64, ts: u64, event: Event) -> Record {
3720        Record { seq, ts, event }
3721    }
3722
3723    #[test]
3724    fn ended_ms_is_set_once_on_exit_and_cleared_when_live_again() {
3725        let mut st = State::new();
3726        st.apply(&rec(
3727            1,
3728            10,
3729            Event::SessionStarted {
3730                session: crate::tests::sample_session("a"),
3731            },
3732        ));
3733        st.apply(&rec(
3734            2,
3735            100,
3736            Event::SessionExited {
3737                session: "a".into(),
3738                code: Some(0),
3739            },
3740        ));
3741        assert_eq!(st.sessions["a"].ended_ms, Some(100));
3742        st.apply(&rec(
3743            3,
3744            200,
3745            Event::SessionStatus {
3746                session: "a".into(),
3747                status: SessionStatus::Failed,
3748            },
3749        ));
3750        assert_eq!(st.sessions["a"].ended_ms, Some(100), "first end time wins");
3751        st.apply(&rec(
3752            4,
3753            300,
3754            Event::SessionStatus {
3755                session: "a".into(),
3756                status: SessionStatus::Idle,
3757            },
3758        ));
3759        assert_eq!(st.sessions["a"].ended_ms, None);
3760    }
3761
3762    #[test]
3763    fn retention_drops_entries_older_than_max_days_by_ended_time() {
3764        let mut st = State::new();
3765        let now = 100 * DAY;
3766        // Created long ago but ended recently: kept. Ended 31 days ago: dropped.
3767        st.archived_sessions
3768            .insert("fresh".into(), archived("fresh", Some(now - DAY), 0));
3769        st.archived_sessions
3770            .insert("old".into(), archived("old", Some(now - 31 * DAY), 0));
3771        // Old logs without ended time fall back to creation time.
3772        st.archived_sessions
3773            .insert("legacy".into(), archived("legacy", None, now - 40 * DAY));
3774        let mut dropped = st.archived_to_prune(now, 100, 30);
3775        dropped.sort();
3776        assert_eq!(dropped, vec!["legacy".to_string(), "old".to_string()]);
3777    }
3778
3779    #[test]
3780    fn retention_keeps_newest_entries_within_count_limit() {
3781        let mut st = State::new();
3782        let now = 10 * DAY;
3783        for (i, id) in ["a", "b", "c"].into_iter().enumerate() {
3784            st.archived_sessions
3785                .insert(id.into(), archived(id, Some(now - 3 + i as u64), 0));
3786        }
3787        assert_eq!(st.archived_to_prune(now, 2, 30), vec!["a".to_string()]);
3788        assert!(st.archived_to_prune(now, 3, 30).is_empty());
3789    }
3790
3791    #[test]
3792    fn archive_pruned_event_removes_entries_and_transcripts() {
3793        let mut st = State::new();
3794        st.archived_sessions
3795            .insert("x".into(), archived("x", Some(1), 0));
3796        st.transcripts
3797            .insert("x".into(), VecDeque::from(["l".to_string()]));
3798        st.apply(&rec(
3799            1,
3800            2,
3801            Event::ArchivePruned {
3802                sessions: vec!["x".into()],
3803            },
3804        ));
3805        assert!(st.archived_sessions.is_empty());
3806        assert!(!st.transcripts.contains_key("x"));
3807    }
3808
3809    #[test]
3810    fn version_with_hash_starts_with_pkg_version() {
3811        assert!(VERSION_WITH_HASH.starts_with(env!("CARGO_PKG_VERSION")));
3812    }
3813}