Skip to main content

wcode_harness/
agent.rs

1use std::path::{Path, PathBuf};
2use std::sync::Arc;
3
4use futures::StreamExt as _;
5use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
6use tokio::sync::watch;
7use tokio_util::sync::CancellationToken;
8
9use crate::compaction::{self, CompactOutcome, CompactionPolicy};
10use crate::event::{AgentEvent, LlmStreamEvent};
11use crate::hooks::{HooksSet, PlanModeHandle};
12use crate::loop_::{LoopConfig, LoopError, run_loop};
13use crate::message::{AgentMessage, StopReason, Usage};
14use crate::session::{Session, SessionEntry};
15use crate::streamfn::{LlmOpts, StreamFn};
16use crate::tool::Tool;
17
18/// The system-prompt section appended while plan mode is on (D2). The kernel owns
19/// it so a socket client never has to compose the server's prompt.
20pub const PLAN_SECTION: &str = "# Plan mode\nYou are planning, not executing. Explore and propose only — do NOT modify the\nworkspace: the editing tools are disabled and mutating shell commands are refused.\nFine-tune the plan with the user first. When the plan is final, record it as a\ntodo list (status pending), then tell the user to run `/plan off` to execute.";
21
22pub struct AgentConfig {
23    pub system: String,
24    pub tools: Vec<Tool>,
25    pub llm: LlmOpts,
26    pub stream_fn: StreamFn,
27    pub hooks: HooksSet,
28    pub session: Option<Session>, // None = no persistence
29    /// Prior messages seeding the conversation (e.g. resumed session history).
30    pub context: Vec<AgentMessage>,
31    /// Working directory for tool execution; empty falls back to the process
32    /// cwd (bash runs here, file paths resolve) — plumb it so embeddings can
33    /// run against a directory other than `current_dir()`.
34    pub working_dir: PathBuf,
35    /// Maximum number of LLM turns in a single `run`; caps a runaway tool loop
36    /// (see [`crate::loop_::LoopConfig::max_turns`]). Use
37    /// [`crate::loop_::DEFAULT_MAX_TURNS`] for the kernel default.
38    pub max_turns: usize,
39    /// Run concurrency-safe tool calls in one batch in parallel. `false`
40    /// restores strictly-sequential execution.
41    pub parallel_tools: bool,
42    /// When to compact and how much recent context to keep
43    /// (see [`crate::compaction`]). Use [`CompactionPolicy::default`].
44    pub compaction: CompactionPolicy,
45    /// The shared plan-mode switch; the same handle is held by the
46    /// `PlanModeHooks` in `hooks`, so `set_plan_mode` flips both.
47    pub plan_mode: PlanModeHandle,
48}
49
50pub struct Agent {
51    system: String,
52    /// The composed prompt as passed (plan mode off); `system` derives from it.
53    base_system: String,
54    tools: Vec<Tool>,
55    llm: LlmOpts,
56    stream_fn: StreamFn,
57    hooks: HooksSet,
58    session: Option<Session>,
59    working_dir: PathBuf,
60    max_turns: usize,
61    parallel_tools: bool,
62    compaction: CompactionPolicy,
63    plan_mode: PlanModeHandle,
64    ctx: Vec<AgentMessage>,
65    steer_tx: UnboundedSender<AgentMessage>,
66    steer_rx: Option<UnboundedReceiver<AgentMessage>>,
67    follow_tx: UnboundedSender<AgentMessage>,
68    follow_rx: Option<UnboundedReceiver<AgentMessage>>,
69    cancel: CancellationToken,
70    /// The context snapshot the run republishes at each turn boundary (see
71    /// `LoopConfig::ctx_snapshot`); [`Agent::side_handle`] clones it so the actor
72    /// can answer a mid-run read without the `&mut` the run holds.
73    ctx_snapshot: watch::Sender<Vec<AgentMessage>>,
74}
75
76impl Agent {
77    pub fn new(mut cfg: AgentConfig) -> Agent {
78        // Stable routing id for providers (OpenCode Go `x-opencode-session`):
79        // session header wins (a resumed Agent inherits `llm` from the old
80        // one, so the opt may be stale), else explicit opt, else a per-agent
81        // id (covers --no-session / in-memory).
82        cfg.llm.session_id = cfg
83            .session
84            .as_ref()
85            .and_then(session_header_id)
86            .or_else(|| cfg.llm.session_id.clone())
87            .or_else(|| Some(uuid::Uuid::new_v4().to_string()));
88        let (steer_tx, steer_rx) = mpsc::unbounded_channel();
89        let (follow_tx, follow_rx) = mpsc::unbounded_channel();
90        // Seeded with the initial context so a read before the first turn sees
91        // it; `run_loop` republishes at each boundary. `send_replace` is
92        // infallible even with no receivers, so only the sender is held.
93        let (ctx_snapshot, _ctx_rx) = watch::channel(cfg.context.clone());
94        // An empty working_dir means "process cwd" (the historical default).
95        let working_dir = if cfg.working_dir.as_os_str().is_empty() {
96            default_working_dir()
97        } else {
98            cfg.working_dir
99        };
100        Agent {
101            system: cfg.system.clone(),
102            base_system: cfg.system,
103            tools: cfg.tools,
104            llm: cfg.llm,
105            stream_fn: cfg.stream_fn,
106            hooks: cfg.hooks,
107            session: cfg.session,
108            working_dir,
109            max_turns: cfg.max_turns,
110            parallel_tools: cfg.parallel_tools,
111            compaction: cfg.compaction,
112            plan_mode: cfg.plan_mode,
113            ctx: cfg.context,
114            steer_tx,
115            steer_rx: Some(steer_rx),
116            follow_tx,
117            follow_rx: Some(follow_rx),
118            cancel: CancellationToken::new(),
119            ctx_snapshot,
120        }
121    }
122
123    /// Queued for injection at the next turn start (this run or a later one).
124    pub fn steer(&self, m: AgentMessage) {
125        let _ = self.steer_tx.send(m);
126    }
127
128    /// Toggle plan mode: flips the shared handle and recomposes `system` from
129    /// `base_system` — appending [`PLAN_SECTION`] when on, restoring the base
130    /// prompt exactly when off. Takes effect on the NEXT run (the in-flight one
131    /// cloned `system` into its `LoopConfig` at start). Not persisted.
132    pub fn set_plan_mode(&mut self, on: bool) {
133        self.plan_mode.set(on);
134        self.system = if on {
135            format!("{}\n\n{}", self.base_system, PLAN_SECTION)
136        } else {
137            self.base_system.clone()
138        };
139    }
140    /// Swaps the model mid-conversation (takes effect on the next run) and
141    /// logs a `ModelChange` entry when a session is open. The new id's
142    /// `[models.<id>]` profile re-points `endpoint`/`base_url`/`api_key` by
143    /// settling on the launch provider first, so an unmapped id — and a switch
144    /// back to a previous model — falls back to it (the switch is reversible).
145    pub fn set_model(&mut self, model: String) -> std::io::Result<()> {
146        // Log first: a failed append must not leave the agent and the session
147        // disagreeing about which model runs next.
148        if let Some(session) = &mut self.session {
149            session.append(SessionEntry::ModelChange {
150                id: uuid::Uuid::new_v4().to_string(),
151                model: model.clone(),
152            })?;
153        }
154        self.llm.model = model;
155        // Settle the new id's provider: the launch provider, then this model's
156        // `[models.<id>]` overlay (a no-op when no profiles are configured).
157        self.llm.settle_provider();
158        Ok(())
159    }
160
161    /// Current reasoning effort (None = send nothing).
162    pub fn effort(&self) -> Option<&str> {
163        self.llm.effort.as_deref()
164    }
165
166    /// Swaps the reasoning effort mid-conversation (next run) and logs an
167    /// `EffortChange` entry when a session is open. None clears it.
168    pub fn set_effort(&mut self, effort: Option<String>) -> std::io::Result<()> {
169        if let Some(session) = &mut self.session {
170            session.append(SessionEntry::EffortChange {
171                id: uuid::Uuid::new_v4().to_string(),
172                effort: effort.clone(),
173            })?;
174        }
175        self.llm.effort = effort;
176        Ok(())
177    }
178
179    /// Sender clone for steering while `run` holds the `&mut` borrow (UI tasks).
180    ///
181    /// `run_loop` hands the lent channels back at the end of every run, so a
182    /// clone taken once stays valid across runs and a message sent while a run
183    /// is in flight — even one the loop never drained — reaches the next run.
184    /// (Only an *error* exit reboots the channels, invalidating old clones.)
185    pub fn steer_sender(&self) -> UnboundedSender<AgentMessage> {
186        self.steer_tx.clone()
187    }
188
189    /// Runs after the loop would stop.
190    pub fn follow_up(&self, m: AgentMessage) {
191        let _ = self.follow_tx.send(m);
192    }
193
194    /// Sender clone for injecting a follow-up while `run` holds the `&mut`
195    /// borrow (the mirror of [`Agent::steer_sender`], for a UI/actor task that
196    /// cannot reach `follow_up` directly).
197    pub fn follow_up_sender(&self) -> UnboundedSender<AgentMessage> {
198        self.follow_tx.clone()
199    }
200
201    pub fn cancel(&self) {
202        self.cancel.cancel();
203    }
204
205    /// Token for the run in flight or the next one; re-acquire after each
206    /// `run()` (a fresh token is minted at the end of every run).
207    pub fn cancel_token(&self) -> CancellationToken {
208        self.cancel.clone()
209    }
210
211    /// The hook set, exposed so the actor can run the inbound policy
212    /// ([`HooksSet::before_inbound`]) while `run` holds the `&mut` borrow.
213    pub fn hooks(&self) -> &HooksSet {
214        &self.hooks
215    }
216
217    pub async fn run(
218        &mut self,
219        user_text: &str,
220        sink: UnboundedSender<AgentEvent>,
221    ) -> Result<StopReason, LoopError> {
222        // The user message is persisted before the loop takes over; the loop
223        // records every subsequent message as it enters ctx, so a crash
224        // mid-run loses at most the in-flight message instead of the whole
225        // turn (see `record_session` in loop_).
226        let user = AgentMessage::user_text(user_text);
227        if let Some(session) = &mut self.session {
228            session
229                .append(SessionEntry::Message {
230                    id: uuid::Uuid::new_v4().to_string(),
231                    parent_id: None,
232                    message: user.clone(),
233                })
234                .map_err(LoopError::Session)?;
235        }
236        self.ctx.push(user);
237
238        // Cover the window between the submit and the first turn boundary: a
239        // read arriving before the loop's first publish still sees the question.
240        let _ = self.ctx_snapshot.send_replace(self.ctx.clone());
241
242        let steering = self.steer_rx.take().expect("steer_rx present between runs");
243        let follow_ups = self
244            .follow_rx
245            .take()
246            .expect("follow_rx present between runs");
247        let cfg = LoopConfig {
248            system: self.system.clone(),
249            tools: self.tools.clone(),
250            llm: self.llm.clone(),
251            stream_fn: Arc::clone(&self.stream_fn),
252            hooks: self.hooks.clone(),
253            steering,
254            follow_ups,
255            cancel: self.cancel.clone(),
256            working_dir: self.working_dir.clone(),
257            max_turns: self.max_turns,
258            parallel: self.parallel_tools,
259            compaction: self.compaction,
260            ctx_snapshot: self.ctx_snapshot.clone(),
261            session: self.session.as_mut(),
262        };
263        let res = run_loop(&mut self.ctx, cfg, sink).await;
264
265        // Fresh token for the next run: CancellationToken has no reset, so a
266        // cancel from this run must not poison the next one.
267        self.cancel = CancellationToken::new();
268
269        match res {
270            Ok(result) => {
271                // run_loop hands the lent channels back, so steer()/follow_up()
272                // and any sender clone taken before the run keep working, and a
273                // message sent while the run was in flight — even one the loop
274                // never drained — reaches the next run.
275                self.steer_rx = Some(result.steering);
276                self.follow_rx = Some(result.follow_ups);
277                // An `after_run` hook may act on the finished run (the A2A
278                // auto-report forwards a worker's result to its orchestrator).
279                self.hooks.after_run(&self.ctx, result.stop_reason).await;
280                Ok(result.stop_reason)
281            }
282            Err(e) => {
283                // Error exit: the channels were dropped with the error. Reboot
284                // both sides so a later steer()/follow_up() still work
285                // (pre-run sender clones are stale after an error).
286                let (steer_tx, steer_rx) = mpsc::unbounded_channel();
287                self.steer_tx = steer_tx;
288                self.steer_rx = Some(steer_rx);
289                let (follow_tx, follow_rx) = mpsc::unbounded_channel();
290                self.follow_tx = follow_tx;
291                self.follow_rx = Some(follow_rx);
292                Err(e)
293            }
294        }
295    }
296
297    pub fn messages(&self) -> &[AgentMessage] {
298        &self.ctx
299    }
300
301    /// Record an inbound peer message into the conversation *without* starting a
302    /// turn (the `Request::Notify` semantic): persist it as a user message and
303    /// push it onto the context, so the next run sees it. Returns the recorded
304    /// message so the actor can surface it. Idle-only — the actor routes a
305    /// `Notify` that arrives mid-run through steering instead.
306    pub fn notify(&mut self, content: String) -> std::io::Result<AgentMessage> {
307        let message = AgentMessage::user_text(content);
308        if let Some(session) = &mut self.session {
309            session.append(SessionEntry::Message {
310                id: uuid::Uuid::new_v4().to_string(),
311                parent_id: None,
312                message: message.clone(),
313            })?;
314        }
315        self.ctx.push(message.clone());
316        Ok(message)
317    }
318
319    /// Answer `text` tool-free, from the current context, as a one-off side call.
320    ///
321    /// CLONES `ctx`, appends the (framed) question, runs the raw `stream_fn` once
322    /// with an EMPTY tool list, and folds `TextDelta` → text until `Done`
323    /// (capturing `usage`). `self.ctx` and `self.session` are never mutated or
324    /// appended — hence `&self`, so it stays callable while the actor holds
325    /// `&mut Agent` for a run.
326    ///
327    /// Errors become [`LoopError::Stream`]: a stream `Error`, or a call that
328    /// ended with no text. No retry loop of its own — it inherits whatever
329    /// retry/idle-timeout the configured `stream_fn` adapter applies internally,
330    /// exactly as [`crate::compaction::summarize`] does. No cancel path in v1.
331    pub async fn side_ask(&self, text: &str) -> Result<SideAnswer, LoopError> {
332        side_ask_with(&self.stream_fn, &self.ctx, &self.system, &self.llm, text).await
333    }
334
335    /// A read-only handle the actor takes *before* a run borrows the agent, so a
336    /// mid-run `GetHistory`/`SideAsk` is answered from the context snapshot
337    /// `run_loop` republishes each turn, instead of waiting for the whole run.
338    /// See [`SideHandle`].
339    pub fn side_handle(&self) -> SideHandle {
340        SideHandle {
341            stream_fn: Arc::clone(&self.stream_fn),
342            system: self.system.clone(),
343            llm: self.llm.clone(),
344            ctx: self.ctx_snapshot.clone(),
345        }
346    }
347
348    /// Summarize the older part of the conversation in place: keep the newest
349    /// messages per [`CompactionPolicy`] and replace the rest with a single
350    /// summary message. `instructions` focuses the summary (the
351    /// `/compact <prompt>` argument).
352    ///
353    /// When a session is open, the boundary is persisted
354    /// ([`crate::session::SessionEntry::Compaction`]), so a resumed session
355    /// rebuilds to the same `summary + kept` view instead of re-expanding.
356    pub async fn compact(&mut self, instructions: Option<&str>) -> Result<CompactOutcome, String> {
357        compaction::compact_ctx(
358            &mut self.ctx,
359            &self.compaction,
360            &self.stream_fn,
361            &self.llm,
362            instructions,
363            self.session.as_mut(),
364        )
365        .await
366    }
367
368    pub fn session_path(&self) -> Option<&Path> {
369        self.session.as_ref().and_then(|s| s.path())
370    }
371
372    /// The session's stable id (from its `Header`), if a session is open. The
373    /// address a [`SessionHandle`](crate::actor::SessionHandle)'s frames carry.
374    pub fn session_id(&self) -> Option<String> {
375        self.session.as_ref().and_then(session_header_id)
376    }
377}
378
379/// The reply to a `/btw` side question: the answer text and the turn's token
380/// usage (`None` when the provider reported none). Harness data — no styling.
381#[derive(Clone, Debug, Default, PartialEq)]
382pub struct SideAnswer {
383    pub text: String,
384    pub usage: Option<Usage>,
385}
386
387/// A read-only view of an [`Agent`] the actor can mine *while a run holds the
388/// agent's `&mut`. It carries the same clones the run uses (`stream_fn`/
389/// `system`/`llm`) plus the context snapshot `run_loop` republishes each turn,
390/// so a mid-run `GetHistory`/`SideAsk` is answered from the latest completed
391/// turns instead of waiting for the whole run to finish.
392#[derive(Clone)]
393pub struct SideHandle {
394    stream_fn: StreamFn,
395    system: String,
396    llm: LlmOpts,
397    ctx: watch::Sender<Vec<AgentMessage>>,
398}
399
400impl SideHandle {
401    /// The latest turn-boundary context snapshot, owned (`send_replace` keeps
402    /// the value even with no receivers, so a read after the run still sees it).
403    pub fn history(&self) -> Vec<AgentMessage> {
404        self.ctx.subscribe().borrow().to_vec()
405    }
406
407    /// The latest snapshot's last-assistant text — a compact status read
408    /// (`crate::protocol::Request::Status`) that borrows the watch value instead
409    /// of cloning the whole transcript.
410    pub fn last_assistant_text(&self) -> Option<String> {
411        let rx = self.ctx.subscribe();
412        let messages = rx.borrow();
413        crate::message::last_assistant_text(&messages[..])
414    }
415
416    /// Answer `text` tool-free from the latest snapshot; semantics match
417    /// [`Agent::side_ask`].
418    pub async fn side_ask(&self, text: &str) -> Result<SideAnswer, LoopError> {
419        side_ask_with(&self.stream_fn, &self.history(), &self.system, &self.llm, text).await
420    }
421}
422
423/// The shared body of a side ask: frame `text` as a tool-free aside, run the raw
424/// `stream_fn` once with an EMPTY tool list, and fold `TextDelta` → text until
425/// `Done` (capturing `usage`). [`Agent::side_ask`] passes `&self.ctx`;
426/// [`SideHandle::side_ask`] passes the latest mid-run snapshot.
427async fn side_ask_with(
428    stream_fn: &StreamFn,
429    ctx: &[AgentMessage],
430    system: &str,
431    llm: &LlmOpts,
432    text: &str,
433) -> Result<SideAnswer, LoopError> {
434    let mut msgs = ctx.to_vec();
435    msgs.push(AgentMessage::user_text(frame_btw(text)));
436    let mut stream = (stream_fn)(&msgs, system, &[], llm);
437    let mut out = String::new();
438    let mut usage = None;
439    while let Some(ev) = stream.next().await {
440        match ev {
441            LlmStreamEvent::TextDelta(delta) => out.push_str(&delta),
442            LlmStreamEvent::Done { usage: u, .. } => {
443                usage = u;
444                break;
445            }
446            LlmStreamEvent::Error { message, .. } => return Err(LoopError::Stream(message)),
447            _ => {}
448        }
449    }
450    let text = out.trim().to_string();
451    if text.is_empty() {
452        return Err(LoopError::Stream("side answer produced no text".to_string()));
453    }
454    Ok(SideAnswer { text, usage })
455}
456
457/// Frame a raw `/btw` question so the model knows it is a tool-free aside: the
458/// tools are simply absent, so without a hint it may try to call one and fail.
459fn frame_btw(q: &str) -> String {
460    format!("[side question — no tools available; answer briefly and directly from the conversation above]\n{q}")
461}
462
463/// Process cwd, used only when `AgentConfig.working_dir` is left empty.
464fn default_working_dir() -> PathBuf {
465    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
466}
467
468/// Id from the session's `Header` entry, if present (old files may lack one).
469fn session_header_id(session: &Session) -> Option<String> {
470    session.entries().iter().find_map(|e| match e {
471        SessionEntry::Header { id, .. } => Some(id.clone()),
472        _ => None,
473    })
474}
475
476#[cfg(test)]
477mod tests {
478    use super::*;
479    use crate::compaction::CompactionPolicy;
480    use crate::hooks::HooksSet;
481    use crate::streamfn::{LlmStream, StreamFn};
482
483    /// A `StreamFn` that replays `script` on each call.
484    fn scripted(script: Vec<LlmStreamEvent>) -> StreamFn {
485        Arc::new(move |_ctx: &[AgentMessage], _system, _tools, _opts: &LlmOpts| {
486            Box::pin(futures::stream::iter(script.clone())) as LlmStream
487        })
488    }
489
490    fn make_agent(session: Option<Session>, stream_fn: StreamFn, context: Vec<AgentMessage>) -> Agent {
491        Agent::new(AgentConfig {
492            system: "sys".into(),
493            tools: vec![],
494            llm: LlmOpts {
495                model: "m1".into(),
496                ..LlmOpts::default()
497            },
498            stream_fn,
499            hooks: HooksSet::default(),
500            session,
501            context,
502            working_dir: PathBuf::new(),
503            max_turns: crate::loop_::DEFAULT_MAX_TURNS,
504            parallel_tools: true,
505            compaction: CompactionPolicy::default(),
506            plan_mode: PlanModeHandle::new(),
507        })
508    }
509
510    #[tokio::test]
511    async fn side_ask_leaves_ctx_and_session_untouched() {
512        let dir = tempfile::tempdir().unwrap();
513        let session = Session::create(dir.path()).unwrap();
514        let stream = scripted(vec![
515            LlmStreamEvent::TextDelta("an".into()),
516            LlmStreamEvent::TextDelta("swer".into()),
517            LlmStreamEvent::Done {
518                stop_reason: StopReason::Stop,
519                usage: None,
520            },
521        ]);
522        let agent = make_agent(Some(session), stream, vec![AgentMessage::user_text("earlier")]);
523
524        let ctx_before = agent.ctx.clone();
525        let path = agent.session.as_ref().unwrap().path().unwrap().to_path_buf();
526        let entries_before = agent.session.as_ref().unwrap().entries().to_vec();
527        let bytes_before = std::fs::read(&path).unwrap();
528
529        let answer = agent.side_ask("why?").await.unwrap();
530        assert_eq!(answer.text, "answer");
531
532        assert_eq!(agent.ctx, ctx_before, "ctx is unchanged");
533        assert_eq!(agent.messages(), &ctx_before[..]);
534        assert_eq!(
535            agent.session.as_ref().unwrap().entries(),
536            &entries_before[..],
537            "session entries unchanged"
538        );
539        assert_eq!(
540            std::fs::read(&path).unwrap(),
541            bytes_before,
542            "session file bytes unchanged"
543        );
544    }
545
546    #[tokio::test]
547    async fn side_ask_folds_deltas_and_captures_usage() {
548        let usage = Usage {
549            input_tokens: 7,
550            output_tokens: 3,
551            cache_read_tokens: Some(2),
552            cache_write_tokens: None,
553        };
554        let stream = scripted(vec![
555            LlmStreamEvent::TextDelta("he".into()),
556            LlmStreamEvent::TextDelta("llo".into()),
557            LlmStreamEvent::Done {
558                stop_reason: StopReason::Stop,
559                usage: Some(usage),
560            },
561        ]);
562        let agent = make_agent(None, stream, vec![]);
563        assert_eq!(
564            agent.side_ask("hi").await.unwrap(),
565            SideAnswer {
566                text: "hello".into(),
567                usage: Some(usage),
568            }
569        );
570    }
571
572    #[tokio::test]
573    async fn side_ask_surfaces_a_stream_error() {
574        let stream = scripted(vec![LlmStreamEvent::Error {
575            message: "boom".into(),
576            fatal: true,
577        }]);
578        let agent = make_agent(None, stream, vec![]);
579        let err = agent.side_ask("hi").await.unwrap_err();
580        assert!(err.to_string().contains("boom"), "{err}");
581    }
582
583    #[tokio::test]
584    async fn side_ask_errors_on_empty_output() {
585        let stream = scripted(vec![LlmStreamEvent::Done {
586            stop_reason: StopReason::Stop,
587            usage: None,
588        }]);
589        let agent = make_agent(None, stream, vec![]);
590        let err = agent.side_ask("hi").await.unwrap_err();
591        assert!(err.to_string().contains("no text"), "{err}");
592    }
593
594    #[test]
595    fn frame_btw_wraps_the_question() {
596        let framed = frame_btw("why?");
597        assert!(framed.starts_with("[side question"));
598        assert!(framed.ends_with("\nwhy?"));
599    }
600
601    #[test]
602    fn set_plan_mode_appends_and_restores_the_section() {
603        let mut agent = make_agent(None, scripted(vec![]), vec![]);
604        let base = agent.system.clone();
605
606        agent.set_plan_mode(true);
607        assert!(agent.plan_mode.get());
608        assert_eq!(agent.system, format!("{base}\n\n{PLAN_SECTION}"));
609        assert!(agent.system.contains("# Plan mode"));
610        assert!(
611            agent.system.contains("record it as a\ntodo list (status pending)"),
612            "the P2 plan\u{2192}todo instruction is present"
613        );
614
615        agent.set_plan_mode(false);
616        assert!(!agent.plan_mode.get());
617        assert_eq!(agent.system, base, "restored exactly");
618    }
619}