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