mindfork 0.11.0

A terminal AI chat written in Rust: local models via llama.cpp or OpenAI, Anthropic, Gemini and Grok in the cloud, with persistent memory, notes, RAG and tools.
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
//! Orchestrator tests (no UI, no real model): the generation state machine, races,
//! the agentic loop, sampling priorities, list/profile/RAG operations.

use super::engines::EngineManager;
use super::impersonation::{build_impersonation_request, swap_role_message};
use super::request::{PromptContext, build_request};
use super::restart_queue::RestartQueue;
use super::save_queue::SaveQueue;
use super::title::{TitleOrigin, TitleResult, salvage_title_source};
use super::*;

use crate::app::events::RagProgress;
use crate::entities::chat::FeedView;
use crate::entities::message::{Message, MessageRole};
use crate::features::profiles::ProfileEdit;
use crate::shared::api::{ChatChunk, Embedder, EngineBackend};

use crate::app::supervisor::MockSupervisor;
use crate::shared::api::mock::{MockBackend, MockEmbedder};
use crate::shared::paths::Paths;

fn test_embedder() -> Arc<dyn Embedder> {
    Arc::new(MockEmbedder::new(16))
}

/// The default config with the **automatic chat titling off** (spec §11.2).
///
/// For tests whose engine is a finite script or a last-request capture: the
/// title request the first exchange fires (on by default) would consume a
/// scripted entry out of turn or overwrite the captured request. The trigger
/// itself is covered in `tests/title.rs`, on the real default config.
fn no_auto_cfg() -> AppConfig {
    let mut cfg = AppConfig::default();
    cfg.interface.auto_title = crate::shared::config::AutoTitleMode::Off;
    // The reply cap is **pinned** here rather than inherited from the shipped
    // default. It is not cosmetic: every stream reserves its cap in the managed
    // server's shared KV pool (admission-by-budget §4.2), so the admission suites
    // measure concurrency in units of this number — and when the shipped default
    // rose to 16384 to stop reasoning models truncating their answers
    // (docs/research/robustness-and-defaults.md F5), two of them changed verdict
    // for a reason that had nothing to do with what they test.
    cfg.default_sampling.max_tokens = Some(2048);
    cfg
}

/// An engine that remembers the last request it was given and replies with a fixed
/// text — lets a test assert what actually *reached the model*, which is the only way to
/// check an injection (a file in the system prompt, an image on a message) rather than
/// the bookkeeping around it.
///
/// Shared by the attachment and image suites: they ask the same question of the same
/// object, and two copies would drift apart exactly where they must not.
pub(super) struct CapturingBackend {
    pub(super) last: std::sync::Mutex<Option<crate::shared::api::ChatRequest>>,
}

impl CapturingBackend {
    pub(super) fn new() -> Arc<Self> {
        Arc::new(Self {
            last: std::sync::Mutex::new(None),
        })
    }

    /// The last request the engine was handed. Panics if no turn has run — a test that
    /// asserts on "the request" when there was none is broken, not passing.
    pub(super) fn last_request(&self) -> crate::shared::api::ChatRequest {
        self.last.lock().unwrap().clone().expect("a request")
    }
}

#[async_trait::async_trait]
impl EngineBackend for CapturingBackend {
    async fn chat_stream(
        &self,
        req: crate::shared::api::ChatRequest,
        _cancel: tokio_util::sync::CancellationToken,
    ) -> anyhow::Result<crate::shared::api::contract::ChatStream> {
        *self.last.lock().unwrap() = Some(req);
        let s = async_stream::stream! {
            yield ChatChunk::Text("ок".to_string());
            yield ChatChunk::Finished(crate::shared::api::FinishReason::Stop);
        };
        Ok(Box::pin(s))
    }
}

/// Like [`spawn_orch_cfg`], but hands the [`MockSupervisor`] back too — for tests that
/// inspect what the orchestrator *asked of* it: how often a server was raised, and with
/// which resolved key (`MockSupervisor::chat_keys`).
fn spawn_orch_sup(
    config: AppConfig,
) -> (
    tempfile::TempDir,
    Arc<MockSupervisor>,
    UnboundedSender<AppCommand>,
    UnboundedReceiver<AppEvent>,
    tokio::task::JoinHandle<()>,
) {
    let dir = tempfile::tempdir().unwrap();
    let sup = Arc::new(MockSupervisor::with_backend(None));
    let storage = Arc::new(Storage::open(Paths::with_root(dir.path())).unwrap());
    let (cmd_tx, cmd_rx) = unbounded_channel();
    let (evt_tx, evt_rx) = unbounded_channel();
    let handle = tokio::spawn(run(OrchestratorDeps {
        cmd_rx,
        evt_tx,
        storage,
        config,
        supervisor: sup.clone(),
        default_language: crate::shared::i18n::Lang::default(),
        extra_tools: Vec::new(),
    }));
    (dir, sup, cmd_tx, evt_rx, handle)
}

/// Spins up the orchestrator on a temp storage. Returns the channels and a handle.
fn spawn_orch(
    backend: Option<Arc<dyn EngineBackend>>,
) -> (
    tempfile::TempDir,
    UnboundedSender<AppCommand>,
    UnboundedReceiver<AppEvent>,
    tokio::task::JoinHandle<()>,
) {
    spawn_orch_cfg(backend, AppConfig::default())
}

/// Like [`spawn_orch`], but with a given config (max_tool_rounds, etc.).
fn spawn_orch_cfg(
    backend: Option<Arc<dyn EngineBackend>>,
    config: AppConfig,
) -> (
    tempfile::TempDir,
    UnboundedSender<AppCommand>,
    UnboundedReceiver<AppEvent>,
    tokio::task::JoinHandle<()>,
) {
    let dir = tempfile::tempdir().unwrap();
    // Deliberately **file-backed**, even though this fixture never restarts:
    // roughly thirty tests built on it reopen storage afterwards
    // (`Storage::open(Paths::with_root(&root))`) to assert what reached disk.
    // In-memory would not merely fail them — the ones asserting *absence*
    // (`removing_an_attachment_drops_its_index`, `an_inline_file_is_not_indexed`)
    // would keep passing against an always-empty store, i.e. pass vacuously.
    // Measured while trying: 6 of those tests failed outright and 2 more passed
    // for the wrong reason. `bare_orch_rx` and `orchestrator::rag::test_deps`
    // are in memory because no test on them reopens storage.
    let (cmd_tx, evt_rx, handle) = spawn_orch_at(dir.path(), backend, config);
    (dir, cmd_tx, evt_rx, handle)
}

/// Like [`spawn_orch_cfg`], with instrumented tools registered on top of the
/// standard set (`OrchestratorDeps::extra_tools`) — the concurrent-segment
/// tests need a read that counts and delays inside a real turn.
fn spawn_orch_tools(
    backend: Option<Arc<dyn EngineBackend>>,
    config: AppConfig,
    extra_tools: Vec<Arc<dyn crate::features::tools::Tool>>,
) -> (
    tempfile::TempDir,
    UnboundedSender<AppCommand>,
    UnboundedReceiver<AppEvent>,
    tokio::task::JoinHandle<()>,
) {
    let dir = tempfile::tempdir().unwrap();
    let (cmd_tx, evt_rx, handle) = spawn_orch_at_tools(dir.path(), backend, config, extra_tools);
    (dir, cmd_tx, evt_rx, handle)
}

/// Like [`spawn_orch_cfg`], but on an **existing** data root — for two-phase
/// tests that restart the app on the same data (what survived to disk, what a
/// fresh bootstrap makes of it).
///
/// Deliberately **file-backed**, unlike [`spawn_orch_cfg`]: an in-memory
/// database dies with its connection, so a second phase would silently start
/// from an empty `cache.db` and exercise the *rebuild* path instead of the
/// restore one — the test would still pass while covering something else.
fn spawn_orch_at(
    root: &std::path::Path,
    backend: Option<Arc<dyn EngineBackend>>,
    config: AppConfig,
) -> (
    UnboundedSender<AppCommand>,
    UnboundedReceiver<AppEvent>,
    tokio::task::JoinHandle<()>,
) {
    spawn_orch_at_tools(root, backend, config, Vec::new())
}

/// [`spawn_orch_at`] with instrumented tools on top of the standard set.
fn spawn_orch_at_tools(
    root: &std::path::Path,
    backend: Option<Arc<dyn EngineBackend>>,
    config: AppConfig,
    extra_tools: Vec<Arc<dyn crate::features::tools::Tool>>,
) -> (
    UnboundedSender<AppCommand>,
    UnboundedReceiver<AppEvent>,
    tokio::task::JoinHandle<()>,
) {
    let storage = Arc::new(Storage::open(Paths::with_root(root)).unwrap());
    let (cmd_tx, cmd_rx) = unbounded_channel();
    let (evt_tx, evt_rx) = unbounded_channel();
    let deps = OrchestratorDeps {
        cmd_rx,
        evt_tx,
        storage,
        config,
        supervisor: Arc::new(MockSupervisor::with_backend(backend)),
        default_language: crate::shared::i18n::Lang::default(),
        extra_tools,
    };
    let handle = tokio::spawn(run(deps));
    (cmd_tx, evt_rx, handle)
}

/// Drains events until the first one matching the predicate (or the channel closes).
async fn wait_for<F: Fn(&AppEvent) -> bool>(
    rx: &mut UnboundedReceiver<AppEvent>,
    pred: F,
) -> Option<AppEvent> {
    while let Some(ev) = rx.recv().await {
        if pred(&ev) {
            return Some(ev);
        }
    }
    None
}

/// Assembles a "bare" orchestrator for unit-testing pure methods (no loop),
/// discarding the event stream.
fn bare_orch() -> (tempfile::TempDir, Orchestrator) {
    let (dir, orch, _rx) = bare_orch_rx();
    (dir, orch)
}

/// Like [`bare_orch`], but also returns the event receiver (to check emission).
fn bare_orch_rx() -> (tempfile::TempDir, Orchestrator, UnboundedReceiver<AppEvent>) {
    let dir = tempfile::tempdir().unwrap();
    // In-memory: a bare orchestrator is built directly and never restarted.
    let storage = Arc::new(Storage::open_in_memory(Paths::with_root(dir.path())).unwrap());
    let (evt_tx, evt_rx) = unbounded_channel();
    let (done_tx, _done_rx) = unbounded_channel();
    let (status_tx, _status_rx) = unbounded_channel();
    let (title_tx, _title_rx) = unbounded_channel();
    let (imp_status_tx, _imp_status_rx) = unbounded_channel();
    let (embed_status_tx, _embed_status_rx) = unbounded_channel();
    let (imp_done_tx, _imp_done_rx) = unbounded_channel();
    let config = AppConfig {
        default_sampling: SamplingConfig {
            temperature: Some(0.1),
            ..Default::default()
        },
        ..Default::default()
    };
    let registry = Arc::new(build_registry(&config, storage.json().sandbox_dir(), None));
    // The server manager: immediately "ready" with a test embedder (as the bare
    // orchestrator used to be). Tests set the chat engine themselves when needed.
    let mut engines = EngineManager::new(
        Arc::new(MockSupervisor::with_backend(None)),
        status_tx,
        imp_status_tx,
        embed_status_tx,
    );
    engines.server_status = ServerStatus::Ready;
    engines.embedder = test_embedder();
    let orch = Orchestrator {
        evt_tx,
        engines,
        mcp: McpManager::new(unbounded_channel().0),
        confirm: None,
        inflight: None,
        background_runs: Vec::new(),
        bg_run_tx: unbounded_channel().0,
        background_slots: Arc::new(super::generation::BackgroundSlots::new(
            crate::shared::config::DEFAULT_SUBAGENT_BACKGROUND_MAX,
        )),
        pending_landings: Vec::new(),
        session_budget_memo: None,
        imp_cancel: None,
        imp_gen: None,
        imp_done_tx,
        budget_tx: unbounded_channel().0,
        context: Default::default(),
        images_withheld_noted: Default::default(),
        model_tx: unbounded_channel().0,
        model: Default::default(),
        slots_tx: unbounded_channel().0,
        slots: Default::default(),
        tts_cancel: None,
        tts_gen: None,
        tts_playback: None,
        tts_done_tx: unbounded_channel().0,
        storage,
        config,
        registry,
        title_tx,
        // No loop drains this either: compaction tests that need a roll's result
        // go through `spawn_orch_cfg` (the real `run` loop), the ones about
        // *applying* one call `handle_compact_result` directly.
        compact_tx: unbounded_channel().0,
        profiles: Vec::new(),
        chats: Vec::new(),
        active_id: None,
        gen_state: GenState::Idle,
        done_tx,
        rag_cancel: None,
        // The bare orchestrator has no loop draining this channel; attachment
        // tests go through `spawn_orch` (the real `run` loop) end to end.
        attach_tx: unbounded_channel().0,
        // Same for images: staging is exercised through the real loop.
        image_tx: unbounded_channel().0,
        // And launches: what the bare tests assert is the plan and the landing, each
        // called directly (`plan_open`, `handle_open_result`).
        open_tx: unbounded_channel().0,
        staged_images: Default::default(),
        bg: std::collections::HashMap::new(),
        bg_done_tx: unbounded_channel().0,
        consolidate_counts: std::collections::HashMap::new(),
        self_consolidate_counts: std::collections::HashMap::new(),
        saves: SaveQueue::default(),
        restarts: RestartQueue::default(),
        default_language: crate::shared::i18n::Lang::default(),
        extra_tools: Vec::new(),
    };
    (dir, orch, evt_rx)
}

/// A bare orchestrator holding one chat with `messages` — the shared opening
/// of non-async tests that need a conversation in place (title, the list's
/// fold), under the same fixture rule.
fn bare_with_chat(
    messages: Vec<Message>,
) -> (
    tempfile::TempDir,
    Orchestrator,
    UnboundedReceiver<AppEvent>,
    Uuid,
) {
    let (d, mut orch, rx) = bare_orch_rx();
    let profile = Profile::new("P", "sys");
    let mut chat = Chat::from_profile(&profile, "Новый чат");
    for m in messages {
        chat.push_message(m);
    }
    let chat_id = chat.id;
    orch.profiles.push(profile);
    orch.chats.push(chat);
    (d, orch, rx, chat_id)
}

/// An assistant message carrying one sub-agent transcript on its record, plus
/// the run's id — the opening of a test that needs a chat with a child
/// (spec §9.3.2).
fn carrier_with_run(title: &str, texts: &[&str]) -> (Message, Uuid) {
    let run = crate::entities::subagent::SubagentRun::fixture(title, texts);
    let run_id = run.id;
    let mut carrier = Message::assistant("делегировал");
    carrier.tool_calls = vec![run.on_record()];
    (carrier, run_id)
}

/// Enables the whole tool catalog on the profile (including the control followup/
/// rewrite tools) — for control-tool tests. Returns the profile's id.
async fn enable_all_tools(
    cmd_tx: &UnboundedSender<AppCommand>,
    evt_rx: &mut UnboundedReceiver<AppEvent>,
) -> Uuid {
    use crate::features::tools::all_tool_ids;
    let pl = wait_for(evt_rx, |e| matches!(e, AppEvent::ProfileList(_)))
        .await
        .unwrap();
    let pid = match pl {
        AppEvent::ProfileList(v) => v[0].id,
        _ => unreachable!(),
    };
    cmd_tx
        .send(AppCommand::UpdateProfile {
            id: pid,
            edit: Box::new(ProfileEdit {
                enabled_tools: Some(all_tool_ids()),
                ..Default::default()
            }),
        })
        .unwrap();
    pid
}

/// The real chat engine from `MINDFORK_ENGINE_URL` (for end-to-end smokes against a live
/// model). `None` — the variable isn't set (the test is skipped).
///
/// **Wrapped in `RetryBackend`, exactly as the supervisor wraps an external
/// server** (spec §6.8). Without this the whole live e2e set would bypass the
/// decorator that sits on every real cloud and external turn — it would be covered
/// by unit tests alone, and a mistake in how it hands a stream over (the head it
/// replays, the commit point, the delegated `context_budget` the compaction trigger
/// reads) would not show up against a real model. Since this backend does not fail
/// transiently in practice, the wrapper is invisible here apart from being
/// exercised.
fn live_backend() -> Option<Arc<dyn EngineBackend>> {
    let client = crate::shared::api::live_client("MINDFORK_ENGINE_URL", "MINDFORK_ENGINE_KEY")?;
    Some(crate::shared::api::retry::RetryBackend::wrap(Arc::new(
        client,
    )))
}

/// The real embedder from `MINDFORK_EMBED_URL` (for live smokes — bge-m3 etc.);
/// `None` when unset → the live smoke falls back to the test `MockEmbedder`.
fn live_embedder() -> Option<Arc<dyn Embedder>> {
    let client = crate::shared::api::live_client("MINDFORK_EMBED_URL", "MINDFORK_EMBED_KEY")?;
    Some(Arc::new(client) as Arc<dyn Embedder>)
}

/// The tuple of a spun-up orchestrator (like [`spawn_orch`]): the data directory,
/// the command channel, the event receiver, the loop's handle.
type OrchHandle = (
    tempfile::TempDir,
    UnboundedSender<AppCommand>,
    UnboundedReceiver<AppEvent>,
    tokio::task::JoinHandle<()>,
);

/// Spins up the orchestrator for a live smoke: chat from `MINDFORK_ENGINE_URL`, an
/// embedder from `MINDFORK_EMBED_URL` (a real server; otherwise a deterministic `MockEmbedder`).
/// `None` when `MINDFORK_ENGINE_URL` is unset (the smoke is skipped).
fn spawn_orch_live() -> Option<OrchHandle> {
    spawn_orch_live_cfg(AppConfig::default())
}

/// Like [`spawn_orch_live`], but with an explicit config (e.g. an MCP host enabled
/// with a real server for an e2e smoke).
fn spawn_orch_live_cfg(config: AppConfig) -> Option<OrchHandle> {
    spawn_orch_live_with(config, true)
}

/// Like [`spawn_orch_live_cfg`], but deliberately **without** an embedder, even
/// when `MINDFORK_EMBED_URL` is set.
///
/// For smokes that must exercise a path the model would otherwise be able to
/// shortcut. With an embedder present a by-reference attachment gets indexed,
/// and `attachment_search` becomes a legitimate — often better — route, so
/// "the model paged through the file" stops being a property of the code and
/// becomes a property of the model's mood that day. Removing the embedder
/// removes the alternative instead of hoping it is not taken.
///
/// Note `MockSupervisor::with_backend_no_embedder`: passing `None` as the
/// embedder is **not** enough, since the mock then falls back to a
/// `MockEmbedder` and the attachment still gets indexed.
fn spawn_orch_live_no_embed(config: AppConfig) -> Option<OrchHandle> {
    spawn_orch_live_with(config, false)
}

fn spawn_orch_live_with(config: AppConfig, with_embedder: bool) -> Option<OrchHandle> {
    spawn_orch_live_paths(config, with_embedder, None)
}

/// Like [`spawn_orch_live_cfg`], with the sandbox at `sandbox` — a provisioned
/// `MINDFORK_SANDBOX_DIR` — rather than the temporary data root's empty one
/// (docs/history/sandbox-file-exchange.md §11 S13).
fn spawn_orch_live_sandbox(config: AppConfig, sandbox: std::path::PathBuf) -> Option<OrchHandle> {
    spawn_orch_live_paths(config, true, Some(sandbox))
}

fn spawn_orch_live_paths(
    config: AppConfig,
    with_embedder: bool,
    sandbox: Option<std::path::PathBuf>,
) -> Option<OrchHandle> {
    let backend = live_backend()?;
    let supervisor: Arc<dyn crate::app::supervisor::ServerSupervisor> = if with_embedder {
        Arc::new(MockSupervisor::with_backend_and_embedder(
            Some(backend),
            live_embedder(),
        ))
    } else {
        Arc::new(MockSupervisor::with_backend_no_embedder(Some(backend)))
    };
    let dir = tempfile::tempdir().unwrap();
    let mut paths = Paths::with_root(dir.path());
    if let Some(sandbox) = sandbox {
        paths = paths.with_sandbox_dir(sandbox);
    }
    let storage = Arc::new(Storage::open(paths).unwrap());
    let (cmd_tx, cmd_rx) = unbounded_channel();
    let (evt_tx, evt_rx) = unbounded_channel();
    let deps = OrchestratorDeps {
        cmd_rx,
        evt_tx,
        storage,
        config,
        supervisor,
        default_language: crate::shared::i18n::Lang::default(),
        extra_tools: Vec::new(),
    };
    let handle = tokio::spawn(run(deps));
    Some((dir, cmd_tx, evt_rx, handle))
}

/// Drains events until `Finished` (or the channel closes), flagging whether a
/// `pred`-matching event occurred along the way. For control-tool end-to-end smokes.
async fn drain_until_finished<F: Fn(&AppEvent) -> bool>(
    rx: &mut UnboundedReceiver<AppEvent>,
    pred: F,
) -> bool {
    let mut saw = false;
    while let Some(ev) = rx.recv().await {
        if pred(&ev) {
            saw = true;
        }
        if matches!(ev, AppEvent::Finished { .. }) {
            break;
        }
    }
    saw
}

/// Runs one turn: sends a message, drains events until `Finished`, collecting
/// the reply text and the names of called tools. For live smokes.
#[cfg(test)]
async fn run_turn_live(
    cmd_tx: &UnboundedSender<AppCommand>,
    evt_rx: &mut UnboundedReceiver<AppEvent>,
    text: &str,
) -> (String, Vec<String>) {
    cmd_tx.send(AppCommand::SendMessage(text.into())).unwrap();
    let mut out = String::new();
    let mut tools = Vec::new();
    while let Some(ev) = evt_rx.recv().await {
        match &ev {
            AppEvent::Chunk { text, .. } => out.push_str(text),
            AppEvent::ToolCall { name, .. } => tools.push(name.clone()),
            AppEvent::Finished { .. } => break,
            _ => {}
        }
    }
    (out, tools)
}

/// Like [`run_turn_live`], but collects pairs (tool name, result) — to check the
/// result text (e.g. the `add_insight` gate firing).
async fn run_turn_capture(
    cmd_tx: &UnboundedSender<AppCommand>,
    evt_rx: &mut UnboundedReceiver<AppEvent>,
    text: &str,
) -> (String, Vec<(String, String)>) {
    let (out, calls) = run_turn_capture_args(cmd_tx, evt_rx, text).await;
    (out, calls.into_iter().map(|(n, _, r)| (n, r)).collect())
}

/// Like [`run_turn_capture`], but keeps the call **arguments** too — triples
/// (tool name, arguments, result). Needed when the result's shape depends on
/// what the model passed, so the assertion can be made against the shape it
/// actually chose rather than the one it was expected to choose.
async fn run_turn_capture_args(
    cmd_tx: &UnboundedSender<AppCommand>,
    evt_rx: &mut UnboundedReceiver<AppEvent>,
    text: &str,
) -> (String, Vec<(String, String, String)>) {
    cmd_tx.send(AppCommand::SendMessage(text.into())).unwrap();
    let mut out = String::new();
    let mut calls = Vec::new();
    while let Some(ev) = evt_rx.recv().await {
        match &ev {
            AppEvent::Chunk { text, .. } => out.push_str(text),
            AppEvent::ToolCall {
                name,
                arguments,
                result,
                ..
            } => calls.push((name.clone(), arguments.clone(), result.clone())),
            AppEvent::Finished { .. } => break,
            _ => {}
        }
    }
    (out, calls)
}

/// Prepares a bare orchestrator with a profile + an active chat (for F3 edits).
fn orch_with_active_profile() -> (tempfile::TempDir, Orchestrator, Uuid) {
    let (dir, mut orch) = bare_orch();
    let profile = Profile::new("P", "sys");
    let pid = profile.id;
    let chat = Chat::from_profile(&profile, "t");
    let chat_id = chat.id;
    orch.profiles.push(profile);
    orch.chats.push(chat);
    orch.active_id = Some(chat_id);
    (dir, orch, pid)
}

/// Prepares an orchestrator with a chat (user+assistant) and a profile that enabled the
/// self-model; `auto_reflect_every=1`. Returns `(dir, orch, chat_id)`.
fn orch_ready_for_reflection() -> (tempfile::TempDir, Orchestrator, Uuid) {
    use crate::features::tools::self_model::GET_SELF_MODEL_ID;
    let (dir, mut orch) = bare_orch();
    orch.config.self_model.auto_reflect_every = 1;
    let mut profile = Profile::new("P", "sys");
    profile.enabled_tools = vec![GET_SELF_MODEL_ID.into()];
    let mut chat = Chat::from_profile(&profile, "t");
    chat.push_message(Message::user("привет"));
    chat.push_message(Message::assistant("здравствуй"));
    let chat_id = chat.id;
    orch.profiles.push(profile);
    orch.chats.push(chat);
    orch.active_id = Some(chat_id);
    (dir, orch, chat_id)
}

/// Prepares an orchestrator with a chat (user+assistant), a profile with the self-model
/// enabled, and two `@self` observation-notes in the DB (the signal "there's something
/// to consolidate"); `auto_consolidate_every=1`. Returns `(dir, orch, chat_id)`.
/// See docs/history/self-model-consolidation.md (stage A1).
fn orch_ready_for_self_consolidation() -> (tempfile::TempDir, Orchestrator, Uuid) {
    use crate::entities::note::Note;
    use crate::features::tools::notes::SELF_NOTE_TAG;
    use crate::features::tools::self_model::GET_SELF_MODEL_ID;
    let (dir, mut orch) = bare_orch();
    orch.config.self_model.auto_consolidate_every = 1;
    let mut profile = Profile::new("P", "sys");
    profile.enabled_tools = vec![
        GET_SELF_MODEL_ID.into(),
        "note_merge".into(),
        "update_self_model".into(),
    ];
    let pid = profile.id;
    let mut chat = Chat::from_profile(&profile, "t");
    chat.push_message(Message::user("привет"));
    chat.push_message(Message::assistant("здравствуй"));
    let chat_id = chat.id;
    // Two observation-notes (@self) — the self-consolidation overview is non-empty (observations ≥ 2).
    for text in ["я ценю краткость", "пользователь любит лаконичность"]
    {
        let note = Note::new(pid, text, vec![SELF_NOTE_TAG.to_string()]);
        orch.storage.db().note_insert(&note).unwrap();
    }
    orch.profiles.push(profile);
    orch.chats.push(chat);
    orch.active_id = Some(chat_id);
    (dir, orch, chat_id)
}

// ---------- test submodules (god-object breakup: docs/history/refactoring-god-objects.md, stage 3) ----------

mod attachments;
mod background;
mod background_dialogue;
mod chats;
mod compaction;
mod concurrent;
mod confirm;
mod demo;
mod dialogue;
mod files;
mod generation;
mod images;
mod impersonation;
mod live;
mod llm_history;
mod mcp;
mod model_name;
mod parallel;
mod profiles;
mod project;
mod rag;
mod reflection;
mod request;
mod search;
mod self_consolidation;
mod self_model;
mod settings;
mod silent;
mod subagent;
mod tasks;
mod title;
mod tts;

/// A tool that made a request of its own and reports the engine's timing of
/// it — the page summary's shape (docs/research/page-summary-usage.md §3.2)
/// without the page: the turn and the silent loop fold what it reports into
/// the sample they keep for the slow-prefill note.
struct SampledTool {
    id: &'static str,
    sample: Option<crate::shared::api::contract::Prefill>,
}

#[async_trait::async_trait]
impl crate::features::tools::Tool for SampledTool {
    fn id(&self) -> crate::entities::profile::ToolId {
        self.id.into()
    }
    fn description(&self, _loc: &crate::shared::i18n::Locale) -> String {
        "sampled".into()
    }
    fn parameters(&self, _loc: &crate::shared::i18n::Locale) -> serde_json::Value {
        serde_json::json!({"type": "object", "properties": {}})
    }
    async fn invoke(
        &self,
        _ctx: &crate::features::tools::ToolContext,
        _args: serde_json::Value,
    ) -> anyhow::Result<crate::features::tools::ToolOutcome> {
        Ok(crate::features::tools::ToolOutcome::text("sampled").with_prefill(self.sample))
    }
    fn group(&self) -> crate::features::tools::meta::ToolGroup {
        crate::features::tools::meta::ToolGroup::Files
    }
    fn ui_label(&self) -> &'static str {
        "sampled"
    }
}