interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-cli / src / main.rs

1726 lines · 63577 bytes Raw Blame History
1#![allow(clippy::type_complexity, clippy::needless_range_loop)]
2// SPDX-License-Identifier: Apache-2.0
3// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17mod allen;
18mod approval;
19mod checkpoint;
20mod client;
21mod commands;
22pub mod compaction;
23mod compose;
24mod context7;
25pub mod cortex;
26mod crumbs;
27mod fs_bind;
28pub mod goals;
29mod hive;
30pub mod hooks;
31mod nesting;
32mod objective;
33pub mod platform;
34pub mod rules;
35mod safety;
36pub mod sandbox;
37pub mod science_context;
38pub mod skills;
39pub mod subagents;
40mod telemetry;
41pub mod tool_batch;
42pub mod tool_plan;
43pub mod tool_spill;
44mod tools;
45pub mod turn_journal;
46pub mod turn_recovery;
47mod ui;
48pub mod vault;
49mod walkthrough;
50
51use colored::*;
52use rustyline::error::ReadlineError;
53use rustyline::DefaultEditor;
54use serde_json::{json, Value};
55use std::env;
56use std::fs;
57
58use client::{extract_tool_calls, get_system_prompt, ChatClient};
59use commands::{handle_slash_command, run_doctor};
60use nesting::perform_nesting_ritual;
61use tools::dispatch_tool;
62use ui::print_banner;
63
64#[tokio::main]
65async fn main() {
66 let args: Vec<String> = env::args().collect();
67 if let Some(pos) = args.iter().position(|a| a == "--approval-mode") {
68 if let Some(value) = args.get(pos + 1) {
69 crate::approval::set_cli_approval_mode(value);
70 }
71 }
72
73 if args.len() > 1 {
74 if args[1] == "--daemon" || args[1] == "daemon" {
75 commands::run_daemon_server().await;
76 return;
77 }
78 if args[1] == "--swarm" || args[1] == "swarm" {
79 commands::handle_swarm_command(&args[2..]).await;
80 return;
81 }
82 if args[1] == "--start" || args[1] == "start" {
83 commands::handle_start_command().await;
84 return;
85 }
86 if args[1] == "--stop" || args[1] == "stop" {
87 commands::handle_stop_command().await;
88 return;
89 }
90 if args[1] == "allen" {
91 allen::handle_allen_command(&args[2..]).await;
92 return;
93 }
94 if args[1] == "objective" {
95 objective::handle_objective_command(&args[2..]);
96 return;
97 }
98 if args[1] == "compose" {
99 compose::handle_compose_command(&args[2..]).await;
100 return;
101 }
102 if args[1] == "--status" || args[1] == "status" {
103 commands::handle_status_command().await;
104 return;
105 }
106 if args[1] == "--cockpit" || args[1] == "cockpit" {
107 commands::handle_cockpit_command().await;
108 return;
109 }
110 if args[1] == "--harness" || args[1] == "harness" {
111 commands::handle_harness_command().await;
112 return;
113 }
114 if args[1] == "--aegis" || args[1] == "aegis" {
115 commands::handle_aegis_command().await;
116 return;
117 }
118 if args[1] == "--adapter" || args[1] == "adapter" || args[1] == "--adapters" {
119 let cmd = if args.len() > 2 {
120 format!("/adapter {}", args[2..].join(" "))
121 } else {
122 "/adapter".to_string()
123 };
124 let _ = handle_slash_command(&cmd).await;
125 return;
126 }
127 if args[1] == "--skill" || args[1] == "skill" || args[1] == "--skills" {
128 let cmd = if args.len() > 2 {
129 format!("/skill {}", args[2..].join(" "))
130 } else {
131 "/skill".to_string()
132 };
133 let _ = handle_slash_command(&cmd).await;
134 return;
135 }
136 if (args[1] == "--auto" || args[1] == "auto") && args.len() > 2 {
137 run_autonomous_goal(&args[2]).await;
138 return;
139 }
140 if (args[1] == "--goal" || args[1] == "goal") && args.len() > 3 && args[2] == "auto" {
141 run_autonomous_goal(&args[3]).await;
142 return;
143 }
144 if args[1] == "--goal" || args[1] == "goal" || args[1] == "--goals" {
145 let cmd = if args.len() > 2 {
146 format!("/goal {}", args[2..].join(" "))
147 } else {
148 "/goal".to_string()
149 };
150 let _ = handle_slash_command(&cmd).await;
151 return;
152 }
153 if args[1] == "context7-sync" || args[1] == "--context7-sync" {
154 let code = context7::sync_to_cortex().await;
155 std::process::exit(code);
156 }
157 if args[1] == "--cortex" || args[1] == "cortex" {
158 let cmd = if args.len() > 2 {
159 format!("/cortex {}", args[2..].join(" "))
160 } else {
161 "/cortex".to_string()
162 };
163 let _ = handle_slash_command(&cmd).await;
164 return;
165 }
166 if args[1] == "--crumb" || args[1] == "crumb" {
167 let target = if args.len() > 2 {
168 std::path::Path::new(&args[2])
169 } else {
170 std::path::Path::new(".")
171 };
172 println!("{}", crumbs::format_dir_crumb_tui(target));
173 return;
174 }
175 if args[1] == "--doctor" || args[1] == "doctor" {
176 run_doctor().await;
177 return;
178 }
179 if args[1] == "--rules" || args[1] == "rules" {
180 let _ = handle_slash_command("/rules").await;
181 return;
182 }
183 if args[1] == "--vault" || args[1] == "vault" {
184 let _ = handle_slash_command("/vault").await;
185 return;
186 }
187 if args[1] == "--nest" || args[1] == "nest" {
188 perform_nesting_ritual("manual-nest", true).await;
189 return;
190 }
191 if args[1] == "--help" || args[1] == "-h" || args[1] == "help" {
192 let _ = handle_slash_command("/help").await;
193 return;
194 }
195 if args[1] == "--version" || args[1] == "-v" {
196 let surface = aien_inference_abi::ExecutionSurface::detect();
197 println!("AIEN CLI v0.1.0 (Host: {})", surface.display_name());
198 return;
199 }
200 if args[1] == "--walkthrough"
201 || args[1] == "-w"
202 || args[1] == "--roadmap"
203 || args[1] == "walkthrough"
204 {
205 let card = walkthrough::render_walkthrough_tui();
206 println!("{}", card);
207 let platform = crate::platform::PlatformContext::detect();
208 let dest = platform.home_dir.join("basecamp/WALKTHROUGH.md");
209 let _ = walkthrough::generate_and_save_walkthrough_md(&dest);
210 return;
211 }
212 if args[1] == "--sandbox" || args[1] == "sandbox" {
213 let cmd = if args.len() > 2 {
214 format!("/sandbox {}", args[2..].join(" "))
215 } else {
216 "/sandbox".to_string()
217 };
218 let _ = handle_slash_command(&cmd).await;
219 return;
220 }
221 if args[1] == "--browser" || args[1] == "browser" || args[1] == "--mirror" {
222 let cmd = if args.len() > 2 {
223 format!("/browser {}", args[2..].join(" "))
224 } else {
225 "/browser".to_string()
226 };
227 let _ = handle_slash_command(&cmd).await;
228 return;
229 }
230 if args[1] == "--subagents"
231 || args[1] == "subagents"
232 || args[1] == "--subagent"
233 || args[1] == "subagent"
234 {
235 let cmd = if args.len() > 2 {
236 format!("/subagents {}", args[2..].join(" "))
237 } else {
238 "/subagents".to_string()
239 };
240 let _ = handle_slash_command(&cmd).await;
241 return;
242 }
243 if args[1] == "--skill" || args[1] == "skill" {
244 let cmd = if args.len() > 2 {
245 format!("/skill {}", args[2..].join(" "))
246 } else {
247 "/skill".to_string()
248 };
249 let _ = handle_slash_command(&cmd).await;
250 return;
251 }
252 if (args[1] == "-p" || args[1] == "--prompt") && args.len() > 2 {
253 let prompt = args[2..].join(" ");
254 if prompt.starts_with("/") {
255 let _ = handle_slash_command(&prompt).await;
256 return;
257 }
258 run_single_prompt(&prompt).await;
259 return;
260 }
261 }
262
263 // Interactive REPL Mode
264 // sc#665: `aien-cli --resume <session-id>` continues a session from its journal.
265 let resume_id: Option<String> =
266 if args.len() > 2 && (args[1] == "--resume" || args[1] == "resume") {
267 Some(args[2].clone())
268 } else {
269 None
270 };
271 print_banner();
272
273 let platform = crate::platform::PlatformContext::detect();
274 let sessions_dir = platform.home_dir.join("basecamp/sessions");
275 let _ = fs::create_dir_all(&sessions_dir);
276
277 // sc#665: every message and tool request is on disk before the loop acts on it.
278 let (session_id, mut journal, resumed) = match &resume_id {
279 Some(id) => {
280 let path = sessions_dir.join(format!("{}.journal.jsonl", id));
281 match turn_journal::Journal::resume(&path) {
282 Ok((j, rep)) => (id.clone(), j, Some(rep)),
283 Err(e) => {
284 eprintln!("{}", format!("Cannot resume {}: {}", id, e).red().bold());
285 return;
286 }
287 }
288 }
289 None => {
290 let id = format!("session-{}", chrono::Utc::now().timestamp());
291 let path = sessions_dir.join(format!("{}.journal.jsonl", id));
292 match turn_journal::Journal::create(&path) {
293 Ok(j) => (id, j, None),
294 Err(e) => {
295 eprintln!(
296 "{}",
297 format!(
298 "Cannot start the session journal, so no tool could run safely: {}",
299 e
300 )
301 .red()
302 .bold()
303 );
304 return;
305 }
306 }
307 }
308 };
309 // sc#667: open the checkpoint store once the session id is known, before
310 // nesting, resume settlement, or any tool. A store that cannot open is
311 // reported inside start_checkpoints; the session still runs.
312 start_checkpoints(&platform.home_dir, &session_id);
313
314 let client = ChatClient::new(None, None);
315 let mut messages: Vec<Value> = Vec::new();
316
317 match resumed {
318 Some(rep) if !rep.messages.is_empty() => {
319 messages = rep.messages;
320 println!(
321 "{}",
322 format!("Resumed {}: {} messages.", session_id, messages.len()).cyan()
323 );
324 for reason in &rep.stops {
325 println!("{}", format!(" earlier: {}", reason).dimmed());
326 }
327 if rep.torn_tail {
328 println!(
329 "{}",
330 " The last line of the journal was cut off mid-write and was dropped."
331 .dimmed()
332 );
333 }
334 if !rep.in_doubt.is_empty() {
335 match turn_journal::settle_in_doubt(
336 &mut journal,
337 &mut messages,
338 &rep.in_doubt,
339 dispatch_tool,
340 ) {
341 Ok(steps) => {
342 for step in steps {
343 match step {
344 turn_journal::ResumeStep::Rerun(i) => println!(
345 "{}",
346 format!(" {} ({}) was a read; ran it again.", i.name, i.call_id)
347 .dimmed()
348 ),
349 turn_journal::ResumeStep::ReportUnknown { intent, .. } => println!(
350 "{}",
351 format!(
352 " {} ({}) was recorded but its result was not; not run again. Allen has been told it is not known whether it happened.",
353 intent.name, intent.call_id
354 )
355 .yellow()
356 ),
357 }
358 }
359 if let Err(e) = journal.snapshot(&messages) {
360 eprintln!("{}", format!("warning: {}", e).yellow());
361 }
362 }
363 Err(stop) => {
364 eprintln!("{}", stop.describe().red().bold());
365 return;
366 }
367 }
368 }
369 }
370 _ => {
371 // Mandatory Nesting Ritual: Circle, Check Wind, Leave Scent, Flatten Terrain
372 let nesting = perform_nesting_ritual(&session_id, true).await;
373
374 let cwd = std::env::current_dir().unwrap_or_else(|_| platform.home_dir.clone());
375 let rules = crate::rules::discover_rules(&cwd);
376 let rules_prompt = crate::rules::format_rules_for_prompt(&rules);
377
378 let mut full_system_prompt = get_system_prompt();
379 if !rules_prompt.is_empty() {
380 full_system_prompt.push_str(&rules_prompt);
381 }
382
383 let opening = [
384 json!({"role": "system", "content": full_system_prompt}),
385 json!({"role": "user", "content": format!("<system_grounding>\n{}\n</system_grounding>\nPerform your mandatory nesting initiation. Confirm your verified terrain, wind, scent mark, and operational readiness before taking commands.", nesting.grounding_context)}),
386 ];
387 for m in opening {
388 if let Err(stop) = journal.push(&mut messages, m) {
389 eprintln!("{}", stop.describe().red().bold());
390 return;
391 }
392 }
393
394 print!("{}", "AIEN Initiation: ".magenta().bold());
395 let init_resp = match client.stream_turn(&messages, true).await {
396 Ok(text) => text,
397 Err(e) => {
398 eprintln!(
399 "\n{}",
400 format!("Failed during model nesting initiation: {}", e)
401 .red()
402 .bold()
403 );
404 return;
405 }
406 };
407 if let Err(stop) = journal.push(
408 &mut messages,
409 json!({"role": "assistant", "content": init_resp}),
410 ) {
411 eprintln!("{}", stop.describe().red().bold());
412 return;
413 }
414 }
415 }
416 println!(
417 "{}",
418 format!(
419 "Session {} (continue it later with: aien-cli --resume {})",
420 session_id, session_id
421 )
422 .dimmed()
423 );
424
425 let mut rl = match DefaultEditor::new() {
426 Ok(editor) => editor,
427 Err(e) => {
428 eprintln!("Failed to initialize readline: {}", e);
429 return;
430 }
431 };
432
433 let history_path = platform.home_dir.join("basecamp/.aien_history");
434 let history_file = history_path.to_str().unwrap_or(".aien_history");
435 let _ = rl.load_history(history_file);
436
437 println!(
438 "{}",
439 "Type your request, or /help for slash commands. Press Ctrl+C or /exit to exit.\n".dimmed()
440 );
441
442 // sc#397: one compactor per session. Originals of every altered or removed
443 // message are written under the session store before the list changes.
444 let compactor = crate::compaction::ContextCompactor::default()
445 .with_store(crate::compaction::CompactionStore::new(
446 sessions_dir.join(format!("{}-compaction", session_id)),
447 ))
448 .with_redactor(crate::vault::redact_secrets)
449 .with_counter_from_env();
450 let micro_compact = crate::compaction::micro_compact_enabled_from_env();
451 // sc#666: tool batches; large results spill into the session's own folder.
452 let batch = tool_batch::BatchConfig::new(
453 compactor.max_tokens,
454 Some(sessions_dir.join(format!("{}-spill", session_id))),
455 );
456
457 loop {
458 let prompt_str = format!("{}{}", "AIEN".magenta().bold(), " ❯ ".cyan().bold());
459 match rl.readline(&prompt_str) {
460 Ok(line) => {
461 let trimmed = line.trim();
462 if trimmed.is_empty() {
463 continue;
464 }
465 let _ = rl.add_history_entry(trimmed);
466
467 if trimmed.starts_with("/") && handle_slash_command(trimmed).await {
468 continue;
469 }
470
471 let mut user_turn = trimmed.to_string();
472 let hook_registry = crate::hooks::HookRegistry::default_sovereign_registry();
473 let _ = hook_registry.run_pre_turn(&mut user_turn).await;
474
475 // sc#667: a turn boundary before the message is recorded, so later
476 // agent writes belong to this turn and `/rollback` can undo them.
477 crate::checkpoint::begin_turn();
478 if let Err(stop) =
479 journal.push(&mut messages, json!({"role": "user", "content": user_turn}))
480 {
481 println!("\n{}", stop.describe().red().bold());
482 continue;
483 }
484
485 let report = compactor.compact_if_needed(&mut messages);
486 if let Err(stop) = record_compaction(&report, &messages, &mut journal) {
487 println!("\n{}", stop.describe().red().bold());
488 journal.stop(&stop);
489 break;
490 }
491
492 // Multi-turn tool execution loop (sc#665: persist-before-act, one-shot recovery)
493 if let Some(stop) = run_model_steps(
494 &client,
495 &mut messages,
496 &mut journal,
497 Some(&compactor),
498 &hook_registry,
499 true,
500 &batch,
501 )
502 .await
503 {
504 println!("\n{}", stop.describe().red().bold());
505 journal.stop(&stop);
506 // The compacted transcript is only in memory. Another step
507 // would act on a history the journal does not hold.
508 if matches!(stop, turn_journal::TurnStop::CompactionUnrecorded(_)) {
509 break;
510 }
511 }
512
513 // sc#664: opt-in per-turn folding of one exchange
514 // (AIEN_MICRO_COMPACT=1). The operator's words are never folded.
515 if micro_compact {
516 let report = compactor.absorb_oldest_exchange(&mut messages);
517 if let Err(stop) = record_compaction(&report, &messages, &mut journal) {
518 println!("\n{}", stop.describe().red().bold());
519 journal.stop(&stop);
520 break;
521 }
522 }
523
524 // The end of the turn: the journal snapshot is the record of this
525 // session; the plain JSON file is kept for readers that expect it.
526 if let Err(e) = journal.snapshot(&messages) {
527 eprintln!(
528 "{}",
529 format!("warning: could not record the end of this turn: {}", e).yellow()
530 );
531 }
532 write_session_file(
533 &sessions_dir.join(format!("{}.json", session_id)),
534 &messages,
535 );
536 println!();
537 }
538 Err(ReadlineError::Interrupted) => {
539 println!("\n{}", "^C (type /exit to quit)".dimmed());
540 }
541 Err(ReadlineError::Eof) => {
542 println!("\n{}", "Exiting AIEN.".cyan());
543 break;
544 }
545 Err(err) => {
546 eprintln!("Readline error: {}", err);
547 break;
548 }
549 }
550 }
551
552 let _ = rl.save_history(history_file);
553}
554
555async fn run_single_prompt(prompt: &str) {
556 let session_id = format!("session-single-{}", chrono::Utc::now().timestamp());
557 let platform = crate::platform::PlatformContext::detect();
558 let sessions_dir = platform.home_dir.join("basecamp/sessions");
559 let _ = fs::create_dir_all(&sessions_dir);
560 start_checkpoints(&platform.home_dir, &session_id);
561 crate::checkpoint::begin_turn();
562
563 // Mandatory Nesting Ritual: Required at startup across all modes
564 let nesting = perform_nesting_ritual(&session_id, true).await;
565
566 let mut turn_prompt = prompt.to_string();
567 let hook_registry = crate::hooks::HookRegistry::default_sovereign_registry();
568 let _ = hook_registry.run_pre_turn(&mut turn_prompt).await;
569
570 let cwd = std::env::current_dir().unwrap_or_else(|_| platform.home_dir.clone());
571 let rules = crate::rules::discover_rules(&cwd);
572 let rules_prompt = crate::rules::format_rules_for_prompt(&rules);
573
574 let mut full_system_prompt = get_system_prompt();
575 if !rules_prompt.is_empty() {
576 full_system_prompt.push_str(&rules_prompt);
577 }
578
579 let client = ChatClient::new(None, None);
580 let mut messages: Vec<Value> = Vec::new();
581
582 // sc#665: same persist-before-act discipline as the interactive loop.
583 let mut journal = match turn_journal::Journal::create(
584 &sessions_dir.join(format!("{}.journal.jsonl", session_id)),
585 ) {
586 Ok(j) => j,
587 Err(e) => {
588 eprintln!(
589 "Error: cannot start the session journal, so no tool could run safely: {}",
590 e
591 );
592 return;
593 }
594 };
595 let batch = tool_batch::BatchConfig::new(
596 crate::compaction::ContextCompactor::default().max_tokens,
597 Some(sessions_dir.join(format!("{}-spill", session_id))),
598 );
599 let opening = [
600 json!({"role": "system", "content": full_system_prompt}),
601 json!({"role": "user", "content": format!("<system_grounding>\n{}\n</system_grounding>\n{}", nesting.grounding_context, turn_prompt)}),
602 ];
603 for m in opening {
604 if let Err(stop) = journal.push(&mut messages, m) {
605 eprintln!("Error: {}", stop.describe());
606 return;
607 }
608 }
609
610 if let Some(stop) = run_model_steps(
611 &client,
612 &mut messages,
613 &mut journal,
614 None,
615 &hook_registry,
616 false,
617 &batch,
618 )
619 .await
620 {
621 eprintln!("Error: {}", stop.describe());
622 journal.stop(&stop);
623 }
624
625 let _ = journal.snapshot(&messages);
626 write_session_file(
627 &sessions_dir.join(format!("{}.json", session_id)),
628 &messages,
629 );
630}
631
632/// Writes the plain session file whole or not at all (temp file, then rename).
633fn write_session_file(path: &std::path::Path, messages: &[Value]) {
634 let tmp = path.with_extension("json.tmp");
635 let body = serde_json::to_string_pretty(messages).unwrap_or_default();
636 if fs::write(&tmp, body).is_ok() {
637 let _ = fs::rename(&tmp, path);
638 }
639}
640
641/// sc#665: one operator turn of model calls and tool rounds.
642///
643/// Each assistant message is on disk before its tool calls run, and each tool
644/// request is on disk before the tool runs (`turn_journal`). A failed model call
645/// gets at most one recovery per failure class (`turn_recovery`), so a turn can
646/// never loop on recovery. A reply cut off inside a tool call is never executed:
647/// it is asked again once with a higher output limit.
648async fn run_model_steps(
649 client: &ChatClient,
650 messages: &mut Vec<Value>,
651 journal: &mut turn_journal::Journal,
652 compactor: Option<&crate::compaction::ContextCompactor>,
653 hook_registry: &crate::hooks::HookRegistry,
654 label: bool,
655 batch: &tool_batch::BatchConfig,
656) -> Option<turn_journal::TurnStop> {
657 use turn_journal::TurnStop;
658 use turn_recovery::{
659 classify, tool_call_truncated, FailureClass, Recovery, RecoveryFlags, BASE_OUTPUT_CAP,
660 };
661
662 let mut flags = RecoveryFlags::default();
663 let mut cap = BASE_OUTPUT_CAP;
664 let mut steps_left = 10;
665 while steps_left > 0 {
666 if label {
667 print!("\n{}", "AIEN: ".magenta().bold());
668 }
669 let mut assistant_resp = match client.stream_turn_with_limit(messages, true, cap).await {
670 Ok(text) => text,
671 Err(e) => match flags.next(classify(&e)) {
672 Recovery::Retry { wait } => {
673 println!(
674 "\n{}",
675 format!("(model call failed: {}; trying once more)", e).dimmed()
676 );
677 tokio::time::sleep(wait).await;
678 continue;
679 }
680 Recovery::CompactThenRetry => match compactor {
681 Some(c) => {
682 println!(
683 "\n{}",
684 "(the conversation is too long for the model; compacting and trying once more)"
685 .dimmed()
686 );
687 let report = c.compact_if_needed(messages);
688 if let Err(stop) = record_compaction(&report, messages, journal) {
689 return Some(stop);
690 }
691 continue;
692 }
693 None => {
694 println!(
695 "\n{}",
696 format!("Error during inference: {}", e).red().bold()
697 );
698 return Some(TurnStop::Recovery(
699 "context-overflow: too long, and this mode has no compactor",
700 ));
701 }
702 },
703 Recovery::Stop { reason } => {
704 println!(
705 "\n{}",
706 format!("Error during inference: {}", e).red().bold()
707 );
708 return Some(TurnStop::Recovery(reason));
709 }
710 Recovery::RaiseCapThenRetry { .. } => {
711 // classify() never yields OutputTruncated for a transport error.
712 println!(
713 "\n{}",
714 format!("Error during inference: {}", e).red().bold()
715 );
716 return Some(TurnStop::Recovery(
717 "model-error: an error with no safe recovery",
718 ));
719 }
720 },
721 };
722
723 if tool_call_truncated(&assistant_resp) {
724 match flags.next(FailureClass::OutputTruncated) {
725 Recovery::RaiseCapThenRetry { max_tokens } => {
726 println!(
727 "\n{}",
728 "(the reply was cut off inside a tool call, so that call was not run; asking again with a higher output limit)"
729 .dimmed()
730 );
731 cap = max_tokens;
732 continue;
733 }
734 Recovery::Stop { reason } => return Some(TurnStop::Recovery(reason)),
735 _ => return Some(TurnStop::Recovery("tool-call-truncated")),
736 }
737 }
738 steps_left -= 1;
739
740 hook_registry.run_post_turn(&mut assistant_resp).await;
741 if let Err(stop) = journal.push(
742 messages,
743 json!({"role": "assistant", "content": assistant_resp.clone()}),
744 ) {
745 return Some(stop);
746 }
747
748 if let Some(c) = compactor {
749 let report = c.compact_if_needed(messages);
750 if let Err(stop) = record_compaction(&report, messages, journal) {
751 return Some(stop);
752 }
753 }
754
755 let tool_calls = match extract_tool_calls(&assistant_resp) {
756 Ok(calls) => calls,
757 Err(error) => {
758 eprintln!("{}", error);
759 return Some(TurnStop::Recovery("malformed-tool-markup"));
760 }
761 };
762 if tool_calls.is_empty() {
763 // Completed turn
764 return None;
765 }
766 match run_tools(journal, messages, tool_calls, batch) {
767 Ok(r) => report_batch(&r),
768 Err(stop) => return Some(stop),
769 }
770 }
771 None
772}
773
774/// What one autonomous assistant reply did, after it was recorded.
775#[derive(Debug)]
776enum AutonomousStep {
777 /// The reply had no tool call, or its tool markup was malformed.
778 StoppedTalking(String),
779 /// Tools ran; none of them asked to complete the milestone.
780 Acted,
781 /// The goal tool accepted a completion request for the active milestone.
782 Completed,
783 /// A completion request named the wrong goal/milestone (not dispatched)
784 /// or the goal tool refused it.
785 Refused(String),
786}
787
788/// One autonomous assistant reply under persist-before-act.
789///
790/// The reply is on disk before any tool runs. Each tool request is on disk
791/// before that tool runs. A failed journal write returns `Err` and does not
792/// call `dispatch`. Only a `goal` `milestone_done`/`advance` request naming
793/// exactly `goal_id` and `milestone_id`, answered with `status: ok`, completes
794/// the milestone; any other completion request is refused before dispatch.
795fn apply_autonomous_reply<F>(
796 journal: &mut turn_journal::Journal,
797 messages: &mut Vec<Value>,
798 assistant_resp: &str,
799 goal_id: &str,
800 milestone_id: usize,
801 mut dispatch: F,
802) -> Result<AutonomousStep, turn_journal::TurnStop>
803where
804 F: FnMut(&str, &Value) -> Value,
805{
806 journal.push(
807 messages,
808 json!({"role": "assistant", "content": assistant_resp}),
809 )?;
810 let tool_calls = match extract_tool_calls(assistant_resp) {
811 Ok(calls) => calls,
812 Err(error) => return Ok(AutonomousStep::StoppedTalking(error)),
813 };
814 if tool_calls.is_empty() {
815 return Ok(AutonomousStep::StoppedTalking(
816 "reply did not request milestone completion".into(),
817 ));
818 }
819 for (name, args) in tool_calls {
820 let action = args["action"].as_str();
821 let completion_request = name == "goal"
822 && matches!(
823 action,
824 Some("milestone_done" | "advance" | "done" | "complete")
825 );
826 if completion_request
827 && (!matches!(action, Some("milestone_done" | "advance"))
828 || args["id"].as_str() != Some(goal_id)
829 || args["milestone_id"].as_u64() != Some(milestone_id as u64))
830 {
831 return Ok(AutonomousStep::Refused(
832 "completion request does not identify the active goal/milestone".into(),
833 ));
834 }
835 let mut result = Value::Null;
836 turn_journal::run_tool_calls(journal, messages, vec![(name, args)], |n, a| {
837 result = dispatch(n, a);
838 result.clone()
839 })?;
840 if completion_request {
841 if result["status"].as_str() == Some("ok") {
842 return Ok(AutonomousStep::Completed);
843 }
844 return Ok(AutonomousStep::Refused(format!(
845 "milestone completion refused: {}",
846 result
847 )));
848 }
849 }
850 Ok(AutonomousStep::Acted)
851}
852
853/// sc#666: one reply's tool calls as a planned batch. Reads of the same or
854/// different paths run together; a write never runs beside a call on an
855/// overlapping path; shell commands, unknown tools and any call that would ask
856/// the operator run alone, so two approval prompts never share the screen.
857fn run_tools(
858 journal: &mut turn_journal::Journal,
859 messages: &mut Vec<Value>,
860 calls: Vec<(String, Value)>,
861 batch: &tool_batch::BatchConfig,
862) -> Result<tool_batch::BatchReport, turn_journal::TurnStop> {
863 let cwd = std::env::current_dir().unwrap_or_default();
864 let safety = crate::safety::SafetyEngine::default_sovereign_engine();
865 let access = |name: &str, args: &Value| match safety.evaluate(name, args) {
866 crate::safety::SafetyDecision::AskUser(_) => tool_plan::Access::Barrier,
867 _ => tool_plan::access_of(name, args, &cwd),
868 };
869 // Tools reach the async runtime from their own threads through the handle.
870 let handle = tokio::runtime::Handle::current();
871 let dispatch = move |name: &str, args: &Value| {
872 let _runtime = handle.enter();
873 dispatch_tool(name, args)
874 };
875 tool_batch::run_batch(journal, messages, calls, batch, access, dispatch)
876}
877
878fn report_batch(r: &tool_batch::BatchReport) {
879 if r.ran_together > 0 {
880 println!(
881 "{}",
882 format!(
883 " ⚡ tools: {} ran side by side ({} steps)",
884 r.ran_together, r.segments
885 )
886 .cyan()
887 .dimmed()
888 );
889 }
890 for p in &r.spilled {
891 println!(
892 "{}",
893 format!(
894 " ⚡ tools: a large result was saved to {} (Allen sees a preview)",
895 p.display()
896 )
897 .cyan()
898 .dimmed()
899 );
900 }
901}
902
903pub async fn run_autonomous_goal(goal_id: &str) {
904 let manifest = goals::load_goals();
905 let goal = match goals::goal_index(&manifest.goals, goal_id).map(|index| &manifest.goals[index])
906 {
907 Some(g) => g.clone(),
908 None => {
909 eprintln!(
910 "{}",
911 format!("Goal '{}' not found in goals.json", goal_id).red()
912 );
913 return;
914 }
915 };
916
917 println!(
918 "{}",
919 format!(
920 "\n🚀 Launching Autonomous Execution Loop for Goal: {}",
921 goal.title
922 )
923 .cyan()
924 .bold()
925 );
926 println!(
927 "{}",
928 format!(
929 "ID: {} | Total Milestones: {}",
930 goal.id,
931 goal.milestones.len()
932 )
933 .dimmed()
934 );
935
936 let session_id = format!("auto-goal-{}", chrono::Utc::now().timestamp());
937 let platform = crate::platform::PlatformContext::detect();
938 let sessions_dir = platform.home_dir.join("basecamp/sessions");
939 let _ = fs::create_dir_all(&sessions_dir);
940 // Same persist-before-act rule as the chat loop: no tool runs unless its
941 // request is on disk, and a failed write ends the goal.
942 let mut journal = match turn_journal::Journal::create(
943 &sessions_dir.join(format!("{}.journal.jsonl", session_id)),
944 ) {
945 Ok(j) => j,
946 Err(e) => {
947 eprintln!(
948 "{}",
949 format!(
950 "Cannot start the session journal, so no tool could run safely: {}",
951 e
952 )
953 .red()
954 .bold()
955 );
956 return;
957 }
958 };
959 println!(
960 "{}",
961 format!(
962 "Session {} (continue it later with: aien-cli --resume {})",
963 session_id, session_id
964 )
965 .dimmed()
966 );
967 let nesting = perform_nesting_ritual(&session_id, true).await;
968 let client = ChatClient::new(None, None);
969
970 for m in &goal.milestones {
971 if m.completed {
972 println!(
973 "{}",
974 format!(
975 " ✓ Milestone {} already completed: {}",
976 m.id, m.description
977 )
978 .green()
979 );
980 continue;
981 }
982
983 println!(
984 "{}",
985 format!("\n▶ Commencing Milestone {}: {}", m.id, m.description)
986 .yellow()
987 .bold()
988 );
989
990 let mut task_directive = format!(
991 "<system_grounding>\n{}\n</system_grounding>\nAUTONOMOUS TASK DIRECTIVE:\nGoal: '{}' (ID: {})\nActive Milestone {}: {}\n\nExecute the necessary commands, write/edit files, run verifications, and accomplish this milestone.\nWhen verified, use the 'goal' tool with action 'milestone_done' (id: \"{}\", milestone_id: {}) and write any durable lesson learned with the 'cortex' tool.\nBegin now.",
992 nesting.grounding_context,
993 goal.title,
994 goal.id,
995 m.id,
996 m.description,
997 goal.id,
998 m.id
999 );
1000 let hook_registry = crate::hooks::HookRegistry::default_sovereign_registry();
1001 let _ = hook_registry.run_pre_turn(&mut task_directive).await;
1002
1003 let mut messages = Vec::new();
1004 let opening = [
1005 json!({"role": "system", "content": get_system_prompt()}),
1006 json!({"role": "user", "content": task_directive}),
1007 ];
1008 for message in opening {
1009 if let Err(stop) = journal.push(&mut messages, message) {
1010 eprintln!("{}", stop.describe().red().bold());
1011 journal.stop(&stop);
1012 return;
1013 }
1014 }
1015
1016 if let Err(error) = execute_autonomous_milestone(
1017 &client,
1018 &mut journal,
1019 &mut messages,
1020 &goal.id,
1021 m.id,
1022 &hook_registry,
1023 dispatch_tool,
1024 )
1025 .await
1026 {
1027 eprintln!("Milestone {} not completed: {}", m.id, error);
1028 return;
1029 }
1030
1031 println!(
1032 "{}",
1033 format!(" ✓ Milestone {} accomplished: {}", m.id, m.description)
1034 .green()
1035 .bold()
1036 );
1037 }
1038
1039 println!(
1040 "{}",
1041 format!(
1042 "\n🏆 All milestones for goal '{}' completed successfully!",
1043 goal.title
1044 )
1045 .green()
1046 .bold()
1047 );
1048}
1049
1050trait MilestoneChat {
1051 async fn reply(&self, messages: &[Value]) -> Result<String, String>;
1052}
1053
1054impl MilestoneChat for ChatClient {
1055 async fn reply(&self, messages: &[Value]) -> Result<String, String> {
1056 self.stream_turn(messages, true).await
1057 }
1058}
1059
1060/// Runs one milestone: at most fifteen tool-bearing replies, each applied
1061/// under persist-before-act by `apply_autonomous_reply`. Anything but an
1062/// accepted completion request for exactly this goal/milestone is `Err`.
1063/// A journal failure is recorded with `journal.stop` before returning.
1064async fn execute_autonomous_milestone(
1065 client: &impl MilestoneChat,
1066 journal: &mut turn_journal::Journal,
1067 messages: &mut Vec<Value>,
1068 goal_id: &str,
1069 milestone_id: usize,
1070 hook_registry: &crate::hooks::HookRegistry,
1071 mut dispatch: impl FnMut(&str, &Value) -> Value,
1072) -> Result<(), String> {
1073 for _ in 0..15 {
1074 print!(
1075 "\n{}",
1076 format!("AIEN [Milestone {}]: ", milestone_id)
1077 .magenta()
1078 .bold()
1079 );
1080 let mut response = client.reply(messages).await?;
1081 hook_registry.run_post_turn(&mut response).await;
1082 match apply_autonomous_reply(
1083 journal,
1084 messages,
1085 &response,
1086 goal_id,
1087 milestone_id,
1088 &mut dispatch,
1089 ) {
1090 Ok(AutonomousStep::Acted) => {}
1091 Ok(AutonomousStep::Completed) => return Ok(()),
1092 Ok(AutonomousStep::StoppedTalking(why) | AutonomousStep::Refused(why)) => {
1093 return Err(why)
1094 }
1095 Err(stop) => {
1096 journal.stop(&stop);
1097 return Err(stop.describe());
1098 }
1099 }
1100 }
1101 Err("milestone exhausted its 15 tool-bearing turns without completion".into())
1102}
1103
1104#[cfg(test)]
1105mod autonomous_tests {
1106 use super::*;
1107 struct FakeChat(std::cell::RefCell<std::collections::VecDeque<String>>);
1108 impl MilestoneChat for FakeChat {
1109 async fn reply(&self, _: &[Value]) -> Result<String, String> {
1110 Ok(self
1111 .0
1112 .borrow_mut()
1113 .pop_front()
1114 .expect("unexpected inference"))
1115 }
1116 }
1117 fn request(args: Value) -> String {
1118 format!(
1119 "<tool_call>{}</tool_call>",
1120 json!({"name":"goal","arguments":args})
1121 )
1122 }
1123 async fn run(
1124 replies: Vec<String>,
1125 dispatch: impl FnMut(&str, &Value) -> Value,
1126 ) -> Result<(), String> {
1127 let d = tempfile::tempdir().unwrap();
1128 let mut journal = turn_journal::Journal::create(&d.path().join("s.journal.jsonl")).unwrap();
1129 execute_autonomous_milestone(
1130 &FakeChat(std::cell::RefCell::new(replies.into())),
1131 &mut journal,
1132 &mut Vec::new(),
1133 "active",
1134 7,
1135 &crate::hooks::HookRegistry::default_sovereign_registry(),
1136 dispatch,
1137 )
1138 .await
1139 }
1140 #[tokio::test]
1141 async fn round3_milestone_exhaustion_refuses_completion() {
1142 let reply = request(json!({"action":"list"}));
1143 let mut count = 0;
1144 let result = run(vec![reply; 15], |_, _| {
1145 count += 1;
1146 json!({"status":"ok"})
1147 })
1148 .await;
1149 assert!(result.is_err(), "exhaustion completed");
1150 assert_eq!(count, 15);
1151 }
1152 #[tokio::test]
1153 async fn round3_milestone_empty_and_final_text_refuse_completion() {
1154 for reply in ["", "I think the milestone is done."] {
1155 assert!(run(vec![reply.into()], |_, _| panic!("no dispatch"))
1156 .await
1157 .is_err());
1158 }
1159 }
1160 #[tokio::test]
1161 async fn round3_milestone_denied_request_refuses_completion() {
1162 for refusal in [
1163 json!({"error":"SECURITY DENIAL: policy refused"}),
1164 json!({"status":"error","error":"write goals failed"}),
1165 ] {
1166 let result = run(
1167 vec![request(
1168 json!({"action":"milestone_done","id":"active","milestone_id":7}),
1169 )],
1170 |_, _| refusal.clone(),
1171 )
1172 .await;
1173 assert!(
1174 result.is_err(),
1175 "denied/failed completion request succeeded"
1176 );
1177 }
1178 }
1179 #[tokio::test]
1180 async fn round3_milestone_invalid_request_refuses_completion() {
1181 for args in [
1182 json!({"action":"milestone_done","id":"other","milestone_id":7}),
1183 json!({"action":"milestone_done","id":"active","milestone_id":8}),
1184 json!({"action":"milestone_done","id":"active"}),
1185 json!({"action":"done","id":"active"}),
1186 ] {
1187 let mut dispatched = false;
1188 assert!(run(vec![request(args)], |_, _| {
1189 dispatched = true;
1190 json!({"status":"ok"})
1191 })
1192 .await
1193 .is_err());
1194 assert!(!dispatched, "invalid completion request reached its effect");
1195 }
1196 }
1197 #[tokio::test]
1198 async fn round3_milestone_valid_request_completes() {
1199 let mut count = 0;
1200 run(
1201 vec![request(
1202 json!({"action":"milestone_done","id":"active","milestone_id":7}),
1203 )],
1204 |_, _| {
1205 count += 1;
1206 json!({"status":"ok"})
1207 },
1208 )
1209 .await
1210 .unwrap();
1211 assert_eq!(count, 1);
1212 }
1213}
1214
1215/// Prints the outcome of a compaction pass. Skips are reported too, so a
1216/// refusal (detached tool result, store failure) is never silent.
1217/// sc#664: prints the compaction report and, when the history changed, records
1218/// the new history in the session journal at once. The journal line is written
1219/// whole or not at all, so a resumed session loads either the old history or
1220/// the compacted one, never both the recap and the messages it replaced.
1221///
1222/// `Err(CompactionUnrecorded)` means the compacted transcript is only in
1223/// memory. The caller ends the session: the journal already holds the
1224/// pre-compaction history, and that is what resume loads. A marker cannot
1225/// stand in for the snapshot, because the write that failed is the one that
1226/// would have stored the compacted transcript.
1227fn record_compaction(
1228 report: &crate::compaction::CompactionReport,
1229 messages: &[Value],
1230 journal: &mut turn_journal::Journal,
1231) -> Result<(), turn_journal::TurnStop> {
1232 report_compaction(report);
1233 if report.applied {
1234 journal
1235 .snapshot(messages)
1236 .map_err(|e| turn_journal::TurnStop::CompactionUnrecorded(e.to_string()))?;
1237 }
1238 Ok(())
1239}
1240
1241fn report_compaction(report: &crate::compaction::CompactionReport) {
1242 use crate::compaction::SkipReason;
1243 if let Some(stats) = &report.stats {
1244 println!(
1245 "{}",
1246 format!(
1247 " ⚡ ContextCompactor: {} -> {} tokens ({}), {} messages recapped, {} tool bytes pruned, {} oversized, record {}",
1248 stats.initial_tokens,
1249 stats.compacted_tokens,
1250 stats.token_source,
1251 stats.pruned_messages_count,
1252 stats.pruned_tool_bytes,
1253 stats.oversized_results,
1254 stats.recovery_pointer
1255 )
1256 .cyan()
1257 .dimmed()
1258 );
1259 if stats.still_over_budget {
1260 println!(
1261 "{}",
1262 " ⚡ ContextCompactor: still over the hard token maximum after compaction (everything left is protected: recent turns or an approval wait)"
1263 .yellow()
1264 .dimmed()
1265 );
1266 }
1267 return;
1268 }
1269 match &report.skipped {
1270 None | Some(SkipReason::NotNeeded) | Some(SkipReason::TooShort) => {}
1271 Some(reason) => println!(
1272 "{}",
1273 format!(
1274 " ⚡ ContextCompactor: skipped ({:?}); history left unchanged",
1275 reason
1276 )
1277 .yellow()
1278 .dimmed()
1279 ),
1280 }
1281}
1282
1283/// sc#667: record the agent's file writes so `/rollback` can undo them
1284/// without touching the operator's own edits. A store that cannot open is
1285/// reported; the session still runs, with writes refused only if a later
1286/// snapshot fails.
1287fn start_checkpoints(home: &std::path::Path, session_id: &str) {
1288 if let Err(err) = crate::checkpoint::start_session(home, session_id) {
1289 eprintln!(
1290 "{}",
1291 format!("Checkpoints off for this session: {}", err).yellow()
1292 );
1293 }
1294}
1295
1296#[cfg(test)]
1297mod compaction_journal_tests {
1298 use super::*;
1299 use crate::compaction::{CompactionStore, ContextCompactor};
1300
1301 fn user(t: &str) -> Value {
1302 json!({"role": "user", "content": t})
1303 }
1304
1305 /// sc#664 acceptance: a compaction is on disk before anything else
1306 /// happens, so a process killed right after it resumes with the compacted
1307 /// history, once: one recap, not the recap plus the messages it replaced.
1308 #[test]
1309 fn resume_after_a_compaction_does_not_double_load() {
1310 let d = tempfile::tempdir().unwrap();
1311 let path = d.path().join("s.journal.jsonl");
1312 let mut journal = turn_journal::Journal::create(&path).unwrap();
1313 let compactor = ContextCompactor::new(2000, 1000, 500)
1314 .with_store(CompactionStore::new(d.path().join("compaction")));
1315 let mut messages = Vec::new();
1316 let opening = [
1317 json!({"role": "system", "content": "sys"}),
1318 user("grounding"),
1319 ];
1320 for m in opening {
1321 journal.push(&mut messages, m).unwrap();
1322 }
1323 for k in 0..4 {
1324 journal
1325 .push(&mut messages, user(&format!("ask {k}")))
1326 .unwrap();
1327 journal
1328 .push(
1329 &mut messages,
1330 json!({"role": "assistant", "content": "<tool_call>\n{\"name\": \"view_file\", \"arguments\": {}}\n</tool_call>"}),
1331 )
1332 .unwrap();
1333 let big = format!(
1334 "<tool_response name=\"view_file\">\n{}\n</tool_response>",
1335 "Z".repeat(4000)
1336 );
1337 journal.push(&mut messages, user(&big)).unwrap();
1338 journal
1339 .push(
1340 &mut messages,
1341 json!({"role": "assistant", "content": format!("answer {k}")}),
1342 )
1343 .unwrap();
1344 }
1345 let before = messages.len();
1346 let report = compactor.compact_if_needed(&mut messages);
1347 assert!(report.applied, "{report:?}");
1348 assert!(messages.len() < before);
1349 record_compaction(&report, &messages, &mut journal).unwrap();
1350 // Killed here: nothing else is written.
1351 drop(journal);
1352
1353 let (_j, rep) = turn_journal::Journal::resume(&path).unwrap();
1354 assert_eq!(rep.messages, messages);
1355 let recaps = rep
1356 .messages
1357 .iter()
1358 .filter(|m| {
1359 m["content"]
1360 .as_str()
1361 .is_some_and(|c| c.starts_with("<context_compaction_recap"))
1362 })
1363 .count();
1364 assert_eq!(recaps, 1);
1365 for k in 0..4 {
1366 assert!(
1367 rep.messages.contains(&user(&format!("ask {k}"))),
1368 "ask {k} lost"
1369 );
1370 }
1371 }
1372
1373 /// The snapshot after compaction is the compacted transcript. If it does
1374 /// not land, the turn does not take another step, and resume still has the
1375 /// history from before the compaction.
1376 #[test]
1377 fn a_failed_compaction_snapshot_stops_before_another_step() {
1378 let d = tempfile::tempdir().unwrap();
1379 let path = d.path().join("s.journal.jsonl");
1380 let mut journal = turn_journal::Journal::create(&path).unwrap();
1381 let compactor = ContextCompactor::new(2000, 1000, 500)
1382 .with_store(CompactionStore::new(d.path().join("compaction")));
1383 let mut messages = Vec::new();
1384 for m in [
1385 json!({"role": "system", "content": "sys"}),
1386 user("grounding"),
1387 ] {
1388 journal.push(&mut messages, m).unwrap();
1389 }
1390 for k in 0..4 {
1391 journal
1392 .push(&mut messages, user(&format!("ask {k}")))
1393 .unwrap();
1394 journal
1395 .push(
1396 &mut messages,
1397 json!({"role": "assistant", "content": "<tool_call>\n{\"name\": \"view_file\", \"arguments\": {}}\n</tool_call>"}),
1398 )
1399 .unwrap();
1400 let big = format!(
1401 "<tool_response name=\"view_file\">\n{}\n</tool_response>",
1402 "Z".repeat(4000)
1403 );
1404 journal.push(&mut messages, user(&big)).unwrap();
1405 journal
1406 .push(
1407 &mut messages,
1408 json!({"role": "assistant", "content": format!("answer {k}")}),
1409 )
1410 .unwrap();
1411 }
1412 let durable = messages.clone();
1413 let report = compactor.compact_if_needed(&mut messages);
1414 assert!(report.applied, "{report:?}");
1415 assert_ne!(messages, durable);
1416 journal.accept_only_n_writes_for_test(0);
1417
1418 let mut stepped = false;
1419 match record_compaction(&report, &messages, &mut journal) {
1420 Ok(()) => stepped = true,
1421 Err(stop) => {
1422 assert!(matches!(
1423 stop,
1424 turn_journal::TurnStop::CompactionUnrecorded(_)
1425 ));
1426 assert!(stop.describe().contains("compaction-unrecorded"));
1427 journal.stop(&stop);
1428 }
1429 }
1430 assert!(
1431 !stepped,
1432 "the turn continued after the compaction snapshot failed"
1433 );
1434 drop(journal);
1435
1436 let (_j, rep) = turn_journal::Journal::resume(&path).unwrap();
1437 assert_eq!(
1438 rep.messages, durable,
1439 "resume loads the history from before this compaction"
1440 );
1441 assert!(
1442 !rep.messages.iter().any(|m| {
1443 m["content"]
1444 .as_str()
1445 .is_some_and(|c| c.starts_with("<context_compaction_recap"))
1446 }),
1447 "the unrecorded recap must not be in the journal"
1448 );
1449 }
1450
1451 #[test]
1452 fn a_skipped_compaction_does_not_stop_the_turn() {
1453 let d = tempfile::tempdir().unwrap();
1454 let path = d.path().join("s.journal.jsonl");
1455 let mut journal = turn_journal::Journal::create(&path).unwrap();
1456 journal.accept_only_n_writes_for_test(0);
1457 let report = crate::compaction::CompactionReport {
1458 applied: false,
1459 skipped: Some(crate::compaction::SkipReason::NotNeeded),
1460 stats: None,
1461 };
1462 assert!(record_compaction(&report, &[], &mut journal).is_ok());
1463 }
1464
1465 /// Answers every chat request with one streamed assistant reply and
1466 /// counts the requests.
1467 fn mock_model(reply: &'static str) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
1468 use std::io::{BufRead, BufReader, Read, Write};
1469 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1470 let url = format!(
1471 "http://{}/v1/chat/completions",
1472 listener.local_addr().unwrap()
1473 );
1474 let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1475 let seen = calls.clone();
1476 std::thread::spawn(move || {
1477 for stream in listener.incoming() {
1478 let Ok(mut stream) = stream else { return };
1479 let mut reader = BufReader::new(stream.try_clone().unwrap());
1480 let mut len = 0usize;
1481 loop {
1482 let mut line = String::new();
1483 if reader.read_line(&mut line).unwrap_or(0) == 0 {
1484 break;
1485 }
1486 if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
1487 len = v.trim().parse().unwrap_or(0);
1488 }
1489 if line == "\r\n" {
1490 break;
1491 }
1492 }
1493 let mut body = vec![0u8; len];
1494 let _ = reader.read_exact(&mut body);
1495 seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1496 let chunk = json!({"choices": [{"delta": {"content": reply}}]});
1497 let sse = format!("data: {chunk}\n\ndata: [DONE]\n\n");
1498 let _ = write!(
1499 stream,
1500 "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1501 sse.len(),
1502 sse
1503 );
1504 }
1505 });
1506 (url, calls)
1507 }
1508
1509 /// #832 item 3, end to end through `run_model_steps`: the model asks for
1510 /// a tool, compaction applies, and its snapshot cannot be written. No
1511 /// tool runs, no second model call is made, the loop returns the stop,
1512 /// and resume loads the history from before the compaction.
1513 #[tokio::test]
1514 async fn compaction_unrecorded_ends_the_session_before_any_tool_or_model_call() {
1515 let d = tempfile::tempdir().unwrap();
1516 let path = d.path().join("s.journal.jsonl");
1517 let mut journal = turn_journal::Journal::create(&path).unwrap();
1518 let compactor = ContextCompactor::new(2000, 1000, 500)
1519 .with_store(CompactionStore::new(d.path().join("compaction")));
1520 let mut messages = Vec::new();
1521 for m in [
1522 json!({"role": "system", "content": "sys"}),
1523 user("grounding"),
1524 ] {
1525 journal.push(&mut messages, m).unwrap();
1526 }
1527 for k in 0..4 {
1528 journal
1529 .push(&mut messages, user(&format!("ask {k}")))
1530 .unwrap();
1531 journal
1532 .push(&mut messages, json!({"role": "assistant", "content": format!("answer {k}: {}", "Z".repeat(4000))}))
1533 .unwrap();
1534 }
1535 journal.push(&mut messages, user("list the files")).unwrap();
1536 let reply =
1537 "<tool_call>\n{\"name\": \"list_dir\", \"arguments\": {\"path\": \".\"}}\n</tool_call>";
1538 let (url, calls) = mock_model(reply);
1539 let client = ChatClient::new(Some(url), Some("mock".into()));
1540 let hooks = crate::hooks::HookRegistry::new();
1541 let batch = tool_batch::BatchConfig::new(32_000, None);
1542 // The assistant reply reaches disk; the compaction snapshot does not.
1543 journal.accept_only_n_writes_for_test(1);
1544
1545 let stop = run_model_steps(
1546 &client,
1547 &mut messages,
1548 &mut journal,
1549 Some(&compactor),
1550 &hooks,
1551 false,
1552 &batch,
1553 )
1554 .await;
1555 assert!(
1556 matches!(stop, Some(turn_journal::TurnStop::CompactionUnrecorded(_))),
1557 "{stop:?}"
1558 );
1559 assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
1560 drop(journal);
1561
1562 let (_j, rep) = turn_journal::Journal::resume(&path).unwrap();
1563 assert!(rep.in_doubt.is_empty(), "a tool request was recorded");
1564 assert_eq!(rep.messages.last().unwrap()["content"], reply);
1565 assert!(!rep.messages.iter().any(|m| {
1566 m["content"]
1567 .as_str()
1568 .is_some_and(|c| c.starts_with("<context_compaction_recap"))
1569 }));
1570 assert!(!rep.messages.iter().any(|m| {
1571 m["content"]
1572 .as_str()
1573 .is_some_and(|c| c.starts_with("<tool_response"))
1574 }));
1575 }
1576}
1577
1578#[cfg(test)]
1579mod autonomous_journal_tests {
1580 use super::*;
1581
1582 fn reply_with(name: &str, args: serde_json::Value) -> String {
1583 format!(
1584 "<tool_call>\n{{\"name\": \"{name}\", \"arguments\": {args}}}\n</tool_call>",
1585 args = args
1586 )
1587 }
1588
1589 /// The one allowed journal write records the assistant reply. The tool
1590 /// request is the write that fails, and dispatch does not run.
1591 #[test]
1592 fn journal_write_failure_stops_an_autonomous_turn_before_dispatch() {
1593 let d = tempfile::tempdir().unwrap();
1594 let path = d.path().join("s.journal.jsonl");
1595 let mut journal = turn_journal::Journal::create(&path).unwrap();
1596 let mut messages = Vec::new();
1597 journal
1598 .push(
1599 &mut messages,
1600 json!({"role": "user", "content": "do the milestone"}),
1601 )
1602 .unwrap();
1603 journal.accept_only_n_writes_for_test(1);
1604 let assistant = reply_with("run_command", json!({"command": "rm x"}));
1605 let mut ran = false;
1606 let result =
1607 apply_autonomous_reply(&mut journal, &mut messages, &assistant, "g", 1, |_, _| {
1608 ran = true;
1609 json!({})
1610 });
1611 assert!(
1612 matches!(result, Err(turn_journal::TurnStop::PersistFailed(_))),
1613 "{result:?}"
1614 );
1615 assert!(!ran, "dispatch ran after the journal write failed");
1616 assert!(
1617 !messages.iter().any(|m| m["content"]
1618 .as_str()
1619 .unwrap_or("")
1620 .contains("<tool_response")),
1621 "a tool result was added after the write failed"
1622 );
1623 drop(journal);
1624 let rep = turn_journal::replay(&std::fs::read_to_string(&path).unwrap()).unwrap();
1625 assert!(rep.in_doubt.is_empty(), "the tool request was not recorded");
1626 assert_eq!(rep.messages.len(), 2, "user message and assistant reply");
1627 assert!(rep.messages[1]["content"]
1628 .as_str()
1629 .unwrap()
1630 .contains("run_command"));
1631 }
1632
1633 #[test]
1634 fn an_autonomous_tool_request_is_on_disk_before_it_runs() {
1635 let d = tempfile::tempdir().unwrap();
1636 let path = d.path().join("s.journal.jsonl");
1637 let mut journal = turn_journal::Journal::create(&path).unwrap();
1638 let mut messages = Vec::new();
1639 journal
1640 .push(
1641 &mut messages,
1642 json!({"role": "user", "content": "milestone"}),
1643 )
1644 .unwrap();
1645 let assistant = reply_with(
1646 "goal",
1647 json!({"action": "milestone_done", "id": "g", "milestone_id": 1}),
1648 );
1649 let path_for_dispatch = path.clone();
1650 let step = apply_autonomous_reply(
1651 &mut journal,
1652 &mut messages,
1653 &assistant,
1654 "g",
1655 1,
1656 |name, args| {
1657 let rep =
1658 turn_journal::replay(&std::fs::read_to_string(&path_for_dispatch).unwrap())
1659 .unwrap();
1660 assert_eq!(
1661 rep.in_doubt.len(),
1662 1,
1663 "the request must be durable before dispatch"
1664 );
1665 assert_eq!(rep.in_doubt[0].name, name);
1666 assert_eq!(rep.in_doubt[0].effect, turn_journal::Effect::Effectful);
1667 assert_eq!(args["action"], "milestone_done");
1668 json!({"status": "ok"})
1669 },
1670 )
1671 .unwrap();
1672 assert!(matches!(step, AutonomousStep::Completed), "{step:?}");
1673 assert!(messages.iter().any(|m| {
1674 m["content"]
1675 .as_str()
1676 .is_some_and(|c| c.contains("<tool_response name=\"goal\">"))
1677 }));
1678 drop(journal);
1679 let rep = turn_journal::replay(&std::fs::read_to_string(&path).unwrap()).unwrap();
1680 assert!(rep.in_doubt.is_empty());
1681 }
1682}
1683
1684#[cfg(test)]
1685mod tool_batch_runtime_tests {
1686 use super::*;
1687
1688 /// sc#666: the real tools, run side by side from plain threads inside the
1689 /// real multi-threaded runtime. `dispatch_tool` reaches the runtime
1690 /// (`block_in_place`, `Handle::current`) for its hooks; the batch runner
1691 /// must hand each thread the runtime handle or this panics.
1692 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1693 async fn real_reads_run_side_by_side_inside_the_runtime() {
1694 let d = tempfile::Builder::new()
1695 .prefix("aien-666-")
1696 .tempdir_in("/tmp")
1697 .unwrap();
1698 let a = d.path().join("a.txt");
1699 let b = d.path().join("b.txt");
1700 std::fs::write(&a, "alpha\n").unwrap();
1701 std::fs::write(&b, "beta\n").unwrap();
1702 let mut journal = turn_journal::Journal::create(&d.path().join("s.journal.jsonl")).unwrap();
1703 let mut messages = Vec::new();
1704 let batch = tool_batch::BatchConfig::new(24_000, Some(d.path().join("spill")));
1705 let calls = vec![
1706 (
1707 "view_file".to_string(),
1708 json!({"path": a.display().to_string()}),
1709 ),
1710 (
1711 "view_file".to_string(),
1712 json!({"path": b.display().to_string()}),
1713 ),
1714 ];
1715 let report = run_tools(&mut journal, &mut messages, calls, &batch).unwrap();
1716 assert_eq!((report.segments, report.ran_together), (1, 2));
1717 assert_eq!(messages.len(), 2);
1718 let first = messages[0]["content"].as_str().unwrap();
1719 let second = messages[1]["content"].as_str().unwrap();
1720 assert!(
1721 first.contains("alpha") && !first.contains("CONFINEMENT"),
1722 "{first}"
1723 );
1724 assert!(second.contains("beta"), "{second}");
1725 }
1726}