arabica-cli 0.13.1

Arabica: a terminal coding agent with a fullscreen TUI, ACP support for Zed, and one-shot runs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! Composes the production crates into one CLI-shaped runtime.
//!
//! This module owns nothing a UI surface would (see
//! `docs/protocol.md` ยง1 and `docs/runtime_core_architecture.md` Appendix B):
//! it only wires `arabica-provider`, `arabica-runner`, and
//! `arabica-runtime` into a concrete `CoreRuntime` and picks the fixed
//! policy a coding CLI needs. Terminal chat, `arabica acp`, and `structure -p` build on
//! this; neither adds a second way to do it.

use std::collections::BTreeMap;
use std::collections::VecDeque;
use std::path::{Path, PathBuf};

use arabica_protocol::{RunId, SessionId};
use arabica_provider::{
    ApiModelProvider, ApiProviderConfig, BlendProvider, ModelProgressSink, ModelProvider,
    ModelRunRequest, ModelRunResult, ProviderError,
};
pub use arabica_runner::LocalRunnerPolicy;
use arabica_runner::{
    LocalRunner, RunnerEnvironment, RunnerError, ToolExecutionRequest, ToolExecutionResult,
};
use arabica_runtime::{
    CoreRuntime, RuntimeArchiveStore, RuntimeCompactionStrategy, ShortMemoryPolicy,
    memory_read_definition, memory_search_definition,
};
use arabica_session::IdAllocator;
use clap::Args;
use sha2::{Digest, Sha256};

/// A run cap generous enough for a real coding task, short enough that a
/// runaway loop cannot bill forever. The user can always cancel; see
/// `RunControl` in `arabica-runtime`.
const MAX_MODEL_STEPS_PER_RUN: usize = 100;

/// Unique ids across terminal processes sharing one session store.
#[derive(Debug, Default)]
pub struct UuidIds;

impl IdAllocator for UuidIds {
    fn session_id(&mut self) -> SessionId {
        SessionId::new(uuid::Uuid::now_v7().to_string())
    }

    fn run_id(&mut self) -> RunId {
        RunId::new(uuid::Uuid::now_v7().to_string())
    }
}

/// Invocation overrides for the default Blend alias. Credentials have no CLI
/// flag so they cannot enter shell history or process listings.
#[derive(Args, Clone, Debug, Default)]
pub struct HostConfigArgs {
    /// Override the default Blend alias model ID (ARABICA__MODEL).
    #[arg(long)]
    pub model: Option<String>,
    /// Select a configured model alias as the policy's default model.
    #[arg(long, conflicts_with = "model")]
    pub model_alias: Option<String>,
    /// Select a configured Blend policy.
    #[arg(long)]
    pub policy: Option<String>,
    /// Override reasoning effort for the selected default model.
    #[arg(long)]
    pub thinking: Option<String>,
    /// Override ARABICA__API_TYPE for the default alias's provider.
    #[arg(long)]
    pub api_type: Option<String>,
    /// Override ARABICA__BASE_URL for the default alias's provider.
    #[arg(long)]
    pub base_url: Option<String>,
}

/// Shared model-pool configuration consumed by terminal, one-shot, and ACP
/// hosts. Protocol adapters may expose different controls, but model
/// construction and alias validation stay here.
#[derive(Clone, Debug)]
pub struct HostModelCatalog {
    pub provider: ApiProviderConfig,
    pub models: BTreeMap<String, String>,
    pub blend_policy: Option<arabica_runtime::BlendRoutingPolicy>,
    pub model_configs: BTreeMap<String, ApiProviderConfig>,
}

impl HostModelCatalog {
    pub fn build_model(&self) -> Result<HostModel, ProviderError> {
        if self.models.is_empty() {
            return ApiModelProvider::new(self.provider.clone()).map(HostModel::Api);
        }
        let default_alias = self
            .blend_policy
            .as_ref()
            .map(|policy| policy.default_model.as_str())
            .unwrap_or_else(|| self.models.keys().next().expect("non-empty model catalog"));
        if self.model_configs.is_empty() {
            BlendProvider::from_shared_config(
                self.provider.clone(),
                default_alias,
                self.models.clone(),
            )
            .map(HostModel::Blend)
        } else {
            BlendProvider::from_configs(default_alias, self.model_configs.clone())
                .map(HostModel::Blend)
        }
    }
}

/// The real environment, for the CLI configuration resolver's `lookup`.
pub fn process_environment(name: &str) -> Option<String> {
    std::env::var(name).ok()
}

/// The model this host talks to.
///
/// A concrete enum, not a boxed trait object, following `arabica-server`'s
/// `ServerModel`: an ACP host's `session/prompt` handler spawns the run on
/// its own task (`cx.spawn`, see Appendix B), and only a concrete type lets
/// the compiler prove that future is `Send`.
#[derive(Debug)]
pub enum HostModel {
    Api(ApiModelProvider),
    Blend(BlendProvider),
    StreamingApi(ApiModelProvider, ModelProgressSink),
    /// A fixed sequence of responses, consumed one per call. Used by this
    /// crate's own tests; never selected from user-facing configuration.
    Scripted(ScriptedModel),
}

impl ModelProvider for HostModel {
    fn model_id(&self) -> Option<&str> {
        match self {
            Self::Api(model) | Self::StreamingApi(model, _) => model.model_id(),
            Self::Blend(model) => model.model_id(),
            Self::Scripted(model) => model.model_id(),
        }
    }

    fn model_registry_snapshot(&self) -> String {
        match self {
            Self::Blend(model) => model.model_registry_snapshot(),
            Self::Api(model) | Self::StreamingApi(model, _) => model.model_registry_snapshot(),
            Self::Scripted(model) => model.model_registry_snapshot(),
        }
    }

    fn supports_model_alias(&self, alias: &str) -> bool {
        match self {
            Self::Api(model) | Self::StreamingApi(model, _) => model.supports_model_alias(alias),
            Self::Blend(model) => model.supports_model_alias(alias),
            Self::Scripted(model) => model.supports_model_alias(alias),
        }
    }

    async fn complete(
        &mut self,
        request: ModelRunRequest,
    ) -> Result<ModelRunResult, ProviderError> {
        match self {
            Self::Api(model) => model.complete(request).await,
            Self::Blend(model) => model.complete(request).await,
            Self::StreamingApi(model, progress) => {
                model.complete_with_progress(request, progress).await
            }
            Self::Scripted(model) => model.complete(request).await,
        }
    }

    async fn complete_with_model(
        &mut self,
        request: ModelRunRequest,
        model_alias: &str,
    ) -> Result<ModelRunResult, ProviderError> {
        match self {
            Self::Blend(model) => model.complete_with_model(request, model_alias).await,
            Self::Api(model) | Self::StreamingApi(model, _) => {
                model.complete_with_model(request, model_alias).await
            }
            Self::Scripted(model) => model.complete_with_model(request, model_alias).await,
        }
    }

    async fn cancel(&mut self, run_id: &RunId) -> Result<bool, ProviderError> {
        match self {
            Self::Api(model) => model.cancel(run_id).await,
            Self::Blend(model) => model.cancel(run_id).await,
            Self::StreamingApi(model, _) => model.cancel(run_id).await,
            Self::Scripted(model) => model.cancel(run_id).await,
        }
    }
}

/// Replays a fixed sequence of results, one per call, erroring once
/// exhausted.
#[derive(Debug, Default)]
pub struct ScriptedModel {
    results: VecDeque<ModelRunResult>,
}

impl ScriptedModel {
    pub fn new(results: impl IntoIterator<Item = ModelRunResult>) -> Self {
        Self {
            results: results.into_iter().collect(),
        }
    }
}

impl ModelProvider for ScriptedModel {
    async fn complete(
        &mut self,
        _request: ModelRunRequest,
    ) -> Result<ModelRunResult, ProviderError> {
        self.results
            .pop_front()
            .ok_or_else(|| ProviderError::new("scripted model has no more responses"))
    }

    async fn cancel(&mut self, _run_id: &RunId) -> Result<bool, ProviderError> {
        Ok(false)
    }
}

/// Routes local tools to the confined runner and session-scoped MCP tools to
/// their originating server. With a remote runner, the built-in tools run
/// there instead of in this process.
#[derive(Debug)]
pub struct HostRunner {
    local: LocalRunner,
    remote: Option<arabica_runner_remote::RemoteRunner>,
    /// The remote tool generation and names last advertised to the model;
    /// see [`sync_remote_tools`].
    remote_tools: (u64, Vec<String>),
    mcp: crate::mcp::McpTools,
    /// Workspace root, for reading the file snapshots the write journal
    /// takes and restores.
    root: PathBuf,
    /// Checkpoints for the terminal `/diff` and `/undo` commands, shared
    /// with the session layer through [`Self::write_journal`].
    writes: std::sync::Arc<std::sync::Mutex<crate::checkpoint::WriteJournal>>,
}

impl HostRunner {
    /// The write journal `/diff` and `/undo` read; `execute` records into
    /// the same handle.
    pub(crate) fn write_journal(
        &self,
    ) -> std::sync::Arc<std::sync::Mutex<crate::checkpoint::WriteJournal>> {
        std::sync::Arc::clone(&self.writes)
    }

    /// The remote runner tools currently advertised to the model.
    pub fn remote_tool_names(&self) -> &[String] {
        &self.remote_tools.1
    }

    /// Run one local tool call, checkpointing the three write tools:
    /// snapshot every path the call names before and after, and record the
    /// call when anything actually moved. MCP tools are routed before this
    /// and are never checkpointed -- a server's side effects are not
    /// visible to this host.
    async fn execute_with_checkpoint(
        &mut self,
        request: ToolExecutionRequest,
    ) -> Result<ToolExecutionResult, RunnerError> {
        let paths = crate::checkpoint::mutating_paths(&request.call);
        if paths.is_empty() {
            return self.local.execute(request).await;
        }
        let call_id = request.call.call_id.clone();
        let tool = request.call.name.clone();
        let mut before = Vec::with_capacity(paths.len());
        for path in &paths {
            before.push(tokio::fs::read(self.root.join(path)).await.ok());
        }
        let result = self.local.execute(request).await;
        let mut movements = Vec::with_capacity(paths.len());
        for (path, before) in paths.iter().zip(before) {
            let after = tokio::fs::read(self.root.join(path)).await.ok();
            // A call that changed nothing leaves nothing to undo; one that
            // failed halfway but moved a file is still worth a checkpoint.
            if before != after {
                movements.push(crate::checkpoint::FileMovement {
                    path: path.clone(),
                    before,
                    after,
                });
            }
        }
        if !movements.is_empty() {
            self.writes
                .lock()
                .expect("write journal lock poisoned")
                .record(crate::checkpoint::WriteCheckpoint {
                    call_id,
                    tool,
                    movements,
                });
        }
        result
    }
}

impl RunnerEnvironment for HostRunner {
    fn classify(
        &self,
        call: &arabica_model::ToolCallItem,
    ) -> arabica_protocol::ToolInteractionKind {
        if matches!(
            call.name.as_str(),
            arabica_runtime::CREATE_PLAN_TOOL_NAME | arabica_runtime::UPDATE_PLAN_TOOL_NAME
        ) {
            arabica_protocol::ToolInteractionKind::Plan
        } else if self.mcp.contains(&call.name) {
            self.mcp.classify(call)
        } else if let Some(remote) = &self.remote {
            remote.classify(call)
        } else {
            self.local.classify(call)
        }
    }

    async fn execute(
        &mut self,
        request: ToolExecutionRequest,
    ) -> Result<ToolExecutionResult, RunnerError> {
        if self.mcp.contains(&request.call.name) {
            self.mcp.execute(request).await
        } else if let Some(remote) = &mut self.remote {
            // The files live on the runner, so this host cannot snapshot
            // them for `/diff` and `/undo`.
            remote.execute(request).await
        } else {
            self.execute_with_checkpoint(request).await
        }
    }

    async fn cancel(&mut self, run_id: &RunId) -> Result<bool, RunnerError> {
        let local = self.local.cancel(run_id).await?;
        let mcp = self.mcp.cancel(run_id).await?;
        let remote = match &mut self.remote {
            Some(remote) => remote.cancel(run_id).await?,
            None => false,
        };
        Ok(local || mcp || remote)
    }
}

pub type HostRuntime = CoreRuntime<HostModel, HostRunner>;

/// Re-advertise the remote runner's tools after it sent `tools.changed`,
/// keeping every other tool in place. Returns whether the list changed.
/// Call it between runs: a run keeps the tools it started with, and a call
/// to a tool the runner withdrew comes back as a tool error.
pub fn sync_remote_tools(runtime: &mut HostRuntime) -> bool {
    let runner = runtime.runner_mut();
    let Some(remote) = &runner.remote else {
        return false;
    };
    let (generation, definitions) = remote.tools_snapshot();
    if generation == runner.remote_tools.0 {
        return false;
    }
    let names = definitions.iter().map(|tool| tool.name.clone()).collect();
    let (_, withdrawn) = std::mem::replace(&mut runner.remote_tools, (generation, names));
    let mut tools = definitions;
    tools.extend(
        runtime
            .tools()
            .iter()
            .filter(|tool| !withdrawn.contains(&tool.name))
            .cloned(),
    );
    runtime.set_tools(tools);
    true
}

/// The standing instruction every coding CLI run carries: where it is, what
/// it is running on, and the one rule the confined tools already enforce.
/// Rendered through `system_instructions`
/// (`crates/arabica-runtime/src/lib.rs`), which places it as one message
/// right after the base system prompt, distinct from turn-scoped control
/// language.
pub fn coding_system_instructions(root: &Path) -> String {
    format!(
        "You are Arabica, an autonomous coding agent working in {}. \
         The host operating system is {}. Use paths relative to that \
         workspace root for every tool call; the tools refuse absolute \
         paths and any path that would escape the root. A user may refer to \
         workspace files as @path; inspect those files with read_file before \
         relying on their contents.",
        root.display(),
        std::env::consts::OS,
    )
}

/// The standing instructions for a CLI run: the fixed coding preamble from
/// [`coding_system_instructions`], then any `AGENTS.md` discovered in the
/// workspace (`instructions.rs`), each annotated with the file it came from.
/// Every build site calls this, and terminal chat plus ACP re-call it before
/// each turn, so all three surfaces send the same instructions and a file
/// edited mid-session reaches the next model request.
pub fn system_instructions(root: &Path) -> Vec<String> {
    let mut instructions = vec![coding_system_instructions(root)];
    instructions.extend(crate::instructions::rendered(root, root));
    instructions
}

/// Derives a stable [`arabica_protocol::WorkspaceId`] from a working
/// directory: the same `cwd` always maps to the same id, distinct `cwd`s
/// (almost certainly) do not collide, and the id never leaks the path
/// itself. Shared by every host binding that opens a session from a `cwd`
/// (`acp::AcpState::new_session`, `print::run`) so the same project looks
/// like the same workspace regardless of which binding opened it.
pub fn workspace_id_for(cwd: &Path) -> arabica_protocol::WorkspaceId {
    let digest = Sha256::digest(cwd.to_string_lossy().as_bytes());
    arabica_protocol::WorkspaceId::new(format!("ws-{:.16}", hex::encode(digest)))
}

/// Build a [`HostRuntime`] fixed to the CLI profile: provider-safe Policy
/// history with file-backed archival under the Structure home, a longer step budget than
/// `CoreRuntime::new`'s default with its no-progress guard disabled (cost is
/// bounded by the step count, and the user can cancel at any time), and the
/// tool list this exact policy both advertises and will execute.
pub fn build_host_runtime(
    model: HostModel,
    runner_root: &Path,
    tool_policy: LocalRunnerPolicy,
    arabica_home: &Path,
) -> HostRuntime {
    build_host_runtime_with_mcp(
        model,
        runner_root,
        tool_policy,
        arabica_home,
        crate::mcp::McpTools::default(),
    )
}

pub fn build_host_runtime_with_mcp(
    model: HostModel,
    runner_root: &Path,
    tool_policy: LocalRunnerPolicy,
    arabica_home: &Path,
    mcp: crate::mcp::McpTools,
) -> HostRuntime {
    build_host_runtime_with_runner(model, runner_root, tool_policy, arabica_home, mcp, None)
}

/// [`build_host_runtime_with_mcp`] with an optional remote runner. A remote
/// runner replaces the local built-in tools with the ones its lease offers.
pub fn build_host_runtime_with_runner(
    model: HostModel,
    runner_root: &Path,
    tool_policy: LocalRunnerPolicy,
    arabica_home: &Path,
    mcp: crate::mcp::McpTools,
    remote: Option<arabica_runner_remote::RemoteRunner>,
) -> HostRuntime {
    let (remote_generation, mut tools) = match &remote {
        Some(remote) => remote.tools_snapshot(),
        None => (0, arabica_runner::tool_definitions(&tool_policy)),
    };
    let remote_names = if remote.is_some() {
        tools.iter().map(|tool| tool.name.clone()).collect()
    } else {
        Vec::new()
    };
    let remote_tools = (remote_generation, remote_names);
    tools.extend(arabica_runtime::plan_tool_definitions());
    tools.push(memory_search_definition());
    tools.push(memory_read_definition());
    tools.extend_from_slice(mcp.definitions());
    let context_identities = mcp.context_identities();
    let runner = HostRunner {
        local: LocalRunner::with_policy(runner_root, tool_policy),
        remote,
        remote_tools,
        mcp,
        root: runner_root.to_path_buf(),
        writes: std::sync::Arc::new(std::sync::Mutex::new(
            crate::checkpoint::WriteJournal::default(),
        )),
    };
    let archive_root = arabica_home
        .join("runtime-memory")
        .join(workspace_id_for(runner_root).to_string());
    let mut runtime = CoreRuntime::with_memory_configuration(
        model,
        runner,
        ShortMemoryPolicy::default(),
        false,
        RuntimeArchiveStore::File { root: archive_root },
    );
    runtime.set_compaction_strategy(RuntimeCompactionStrategy::FileBackedGc);
    runtime.set_async_file_backed_gc(true);
    runtime.set_tools(tools);
    runtime.set_context_identities(context_identities);
    runtime.set_max_model_steps_per_run(MAX_MODEL_STEPS_PER_RUN);
    runtime.set_max_model_steps_without_progress(usize::MAX);
    runtime.set_system_instructions(system_instructions(runner_root));
    runtime
}

pub fn build_host_runtime_with_blend(
    model: HostModel,
    runner_root: &Path,
    tool_policy: LocalRunnerPolicy,
    arabica_home: &Path,
    mcp: crate::mcp::McpTools,
    blend_policy: Option<arabica_runtime::BlendRoutingPolicy>,
) -> Result<HostRuntime, arabica_runtime::RuntimeError> {
    build_host_runtime_with_blend_and_runner(
        model,
        runner_root,
        tool_policy,
        arabica_home,
        mcp,
        None,
        blend_policy,
    )
}

pub fn build_host_runtime_with_blend_and_runner(
    model: HostModel,
    runner_root: &Path,
    tool_policy: LocalRunnerPolicy,
    arabica_home: &Path,
    mcp: crate::mcp::McpTools,
    remote: Option<arabica_runner_remote::RemoteRunner>,
    blend_policy: Option<arabica_runtime::BlendRoutingPolicy>,
) -> Result<HostRuntime, arabica_runtime::RuntimeError> {
    let mut runtime =
        build_host_runtime_with_runner(model, runner_root, tool_policy, arabica_home, mcp, remote);
    runtime.set_blend_policy(blend_policy)?;
    let context_policy = crate::config::user_config_context(arabica_home).map_err(|_| {
        arabica_runtime::RuntimeError::new(
            arabica_runtime::RuntimeErrorKind::InvalidConfiguration,
            "invalid context configuration",
        )
    })?;
    runtime.set_context_policy(context_policy)?;
    let roots = crate::config::user_config_skill_roots(arabica_home).map_err(|_| {
        arabica_runtime::RuntimeError::new(
            arabica_runtime::RuntimeErrorKind::InvalidConfiguration,
            "invalid skill source configuration",
        )
    })?;
    if !roots.is_empty() {
        let source = crate::skills::LocalSkillSource::new(roots);
        // Validate before advertising a session; refresh and pin on every run.
        let _ = arabica_runtime::SkillSource::load(&source)?;
        runtime.set_skill_source(Box::new(source));
    }
    Ok(runtime)
}

/// Compose the production persistence adapter; entry-point behavior uses its port.
pub(crate) fn session_store(home: &Path) -> std::sync::Arc<dyn arabica_session::SessionStore> {
    std::sync::Arc::new(arabica_adapters::SqliteSessionRepository::new(home))
}

#[cfg(test)]
mod tests {
    use super::*;
    use arabica_runtime::HistoryProjection;

    #[tokio::test]
    async fn host_model_dispatches_to_the_scripted_variant() {
        let mut model = HostModel::Scripted(ScriptedModel::new([ModelRunResult {
            final_output: Some("done".to_owned()),
            prepared_request: None,
            response: None,
        }]));
        let request = ModelRunRequest {
            images: Vec::new(),
            session_id: arabica_protocol::SessionId::new("s"),
            run_id: RunId::new("r"),
            input: "hi".to_owned(),
            short_memory: Vec::new(),
            run_memory: Vec::new(),
            long_memory: Vec::new(),
            tools: Vec::new(),
            tool_choice: arabica_model::ToolChoice::Auto,
            continuation: Vec::new(),
            disclosure: arabica_protocol::DisclosureLevel::Detail,
            system_instructions: Vec::new(),
        };
        let result = model.complete(request).await.expect("scripted response");
        assert_eq!(result.final_output.as_deref(), Some("done"));
    }

    fn temp_root(label: &str) -> std::path::PathBuf {
        let unique = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("clock is valid")
            .as_nanos();
        let root = std::env::temp_dir().join(format!("arabica-cli-host-{label}-{unique}"));
        std::fs::create_dir(&root).expect("test root is created");
        root
    }

    #[test]
    fn build_host_runtime_fixes_the_cli_profile() {
        let root = temp_root("profile");
        let runtime = build_host_runtime(
            HostModel::Scripted(ScriptedModel::default()),
            &root,
            LocalRunnerPolicy::coding(),
            &root.join("state"),
        );

        assert_eq!(
            runtime.compaction_strategy(),
            RuntimeCompactionStrategy::FileBackedGc
        );
        assert_eq!(runtime.history_projection(), HistoryProjection::Policy);
        assert_eq!(
            runtime.archive_store(),
            &RuntimeArchiveStore::File {
                root: root
                    .join("state/runtime-memory")
                    .join(workspace_id_for(&root).to_string()),
            }
        );
        assert_eq!(runtime.max_model_steps_per_run(), MAX_MODEL_STEPS_PER_RUN);
        assert_eq!(runtime.max_model_steps_without_progress(), usize::MAX);
        assert_eq!(runtime.system_instructions().len(), 1);
        assert!(runtime.system_instructions()[0].contains(&root.display().to_string()));
        assert!(runtime.system_instructions()[0].contains(std::env::consts::OS));

        // The CLI advertises the coding and planning tools but does not
        // expose the unrelated runtime_complete control tool.
        let names: Vec<&str> = runtime
            .tools()
            .iter()
            .map(|tool| tool.name.as_str())
            .collect();
        assert_eq!(
            names,
            vec![
                "read_file",
                "list_dir",
                "grep",
                "find_files",
                "write_file",
                "edit_files",
                "delete_file",
                "create_plan",
                "update_plan",
                "memory_search",
                "memory_read",
            ]
        );
        assert!(!names.contains(&"runtime_complete"));

        std::fs::remove_dir_all(root).expect("cleanup");
    }

    #[test]
    fn build_host_runtime_includes_discovered_project_instructions() {
        let root = temp_root("agents-md");
        std::fs::write(root.join("AGENTS.md"), "Never edit generated files.\n")
            .expect("instruction file is written");
        let runtime = build_host_runtime(
            HostModel::Scripted(ScriptedModel::default()),
            &root,
            LocalRunnerPolicy::coding(),
            &root.join("state"),
        );
        let instructions = runtime.system_instructions();
        assert_eq!(instructions.len(), 2);
        assert!(
            instructions[1].starts_with("Project instructions from AGENTS.md at AGENTS.md:\n\n")
        );
        assert!(instructions[1].contains("Never edit generated files."));
        std::fs::remove_dir_all(root).expect("cleanup");
    }

    #[test]
    fn build_host_runtime_honors_a_policy_without_shell() {
        let root = temp_root("no-shell");
        let runtime = build_host_runtime(
            HostModel::Scripted(ScriptedModel::default()),
            &root,
            LocalRunnerPolicy::read_only(),
            &root.join("state"),
        );
        assert!(!runtime.tools().iter().any(|tool| tool.name == "shell"));
        std::fs::remove_dir_all(root).expect("cleanup");
    }

    #[tokio::test]
    async fn a_local_write_is_checkpointed_and_undoable() {
        let root = temp_root("checkpoint");
        let mut runner = HostRunner {
            local: arabica_runner::LocalRunner::with_policy(&root, LocalRunnerPolicy::coding()),
            remote: None,
            remote_tools: (0, Vec::new()),
            mcp: crate::mcp::McpTools::default(),
            root: root.clone(),
            writes: std::sync::Arc::new(std::sync::Mutex::new(
                crate::checkpoint::WriteJournal::default(),
            )),
        };
        let request = ToolExecutionRequest {
            run_id: RunId::new("r"),
            call: arabica_model::ToolCallItem {
                id: None,
                call_id: "call-1".to_owned(),
                name: "write_file".to_owned(),
                arguments: serde_json::json!({
                    "path": "note.txt",
                    "content": "agent content"
                }),
                provider_state: None,
            },
        };
        let result = runner.execute(request).await.expect("write executes");
        assert!(!result.result.is_error);
        assert!(root.join("note.txt").exists());
        let journal = runner.write_journal();
        let mut journal = journal.lock().expect("write journal lock poisoned");
        assert!(!journal.is_empty());
        assert!(matches!(
            journal.undo_last(&root),
            crate::checkpoint::UndoOutcome::Reverted { .. }
        ));
        // The agent created the file, so undoing removes it again.
        assert!(!root.join("note.txt").exists());
        std::fs::remove_dir_all(root).expect("cleanup");
    }

    #[test]
    fn workspace_id_is_stable_for_the_same_cwd_and_differs_for_another() {
        let a = workspace_id_for(std::path::Path::new("/workspace/one"));
        let a_again = workspace_id_for(std::path::Path::new("/workspace/one"));
        let b = workspace_id_for(std::path::Path::new("/workspace/two"));
        assert_eq!(a, a_again);
        assert_ne!(a, b);
        assert!(a.to_string().starts_with("ws-"));
    }
}