1use crate::child_turn;
4use crate::session_runner::AgentSession;
5use crate::subagents::{AgentStatus, ForkTurns};
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::sync::{Arc, Mutex, Weak};
8use std::time::{Duration, Instant};
9use tokio::sync::{Notify, Semaphore, watch};
10use tokio_util::sync::CancellationToken;
11
12pub type JobId = u64;
13
14const MAX_ACTIVE_JOBS: usize = 4;
15const MAX_RETAINED_JOBS: usize = 20;
16pub const MAX_ITERATIONS: u32 = 100;
17
18pub fn format_interval(interval: Duration) -> String {
19 let mut nanos = interval.as_nanos();
20 let units = [
21 (86_400_000_000_000_u128, "d"),
22 (3_600_000_000_000, "h"),
23 (60_000_000_000, "m"),
24 (1_000_000_000, "s"),
25 (1_000_000, "ms"),
26 (1_000, "us"),
27 (1, "ns"),
28 ];
29 let mut output = String::new();
30 for (size, suffix) in units {
31 let count = nanos / size;
32 if count > 0 {
33 output.push_str(&format!("{count}{suffix}"));
34 nanos %= size;
35 }
36 }
37 if output.is_empty() {
38 output.push_str("0s");
39 }
40 output
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum JobKind {
45 Loop,
46 Autoresearch,
47}
48
49impl JobKind {
50 pub fn label(self) -> &'static str {
51 match self {
52 Self::Loop => "loop",
53 Self::Autoresearch => "autoresearch",
54 }
55 }
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum JobStatus {
60 Queued,
61 Running,
62 Paused,
63 Completed,
64 Failed,
65 Stopped,
66}
67
68impl JobStatus {
69 pub fn label(self) -> &'static str {
70 match self {
71 Self::Queued => "queued",
72 Self::Running => "running",
73 Self::Paused => "paused",
74 Self::Completed => "completed",
75 Self::Failed => "failed",
76 Self::Stopped => "stopped",
77 }
78 }
79
80 pub fn is_finished(self) -> bool {
81 matches!(self, Self::Completed | Self::Failed | Self::Stopped)
82 }
83}
84
85#[derive(Debug, Clone)]
86pub struct JobSnapshot {
87 pub id: JobId,
88 pub kind: JobKind,
89 pub goal: String,
90 pub status: JobStatus,
91 pub iteration: u32,
92 pub limit: Option<u32>,
93 pub interval: Option<Duration>,
94 pub tokens: u64,
95 pub elapsed: Duration,
96 pub session_id: String,
97 pub latest_result: Option<String>,
98 pub error: Option<String>,
99}
100
101#[derive(Debug, Clone)]
102pub struct JobSummary {
103 pub id: JobId,
104 pub kind: JobKind,
105 pub goal: String,
106 pub status: JobStatus,
107 pub iteration: u32,
108 pub limit: Option<u32>,
109 pub interval: Option<Duration>,
110 pub tokens: u64,
111 pub elapsed: Duration,
112}
113
114struct JobState {
115 status: JobStatus,
116 iteration: u32,
117 tokens: u64,
118 latest_result: Option<String>,
119 error: Option<String>,
120}
121
122pub struct JobRecord {
123 id: JobId,
124 kind: JobKind,
125 goal: String,
126 limit: Option<u32>,
127 interval: Option<Duration>,
128 session_id: String,
129 child: Arc<AgentSession>,
130 started: Instant,
131 state: Mutex<JobState>,
132 cancel: CancellationToken,
133 wake: Notify,
134 version: watch::Sender<u64>,
135 parent: Weak<AgentSession>,
136}
137
138impl JobRecord {
139 pub fn snapshot(&self) -> JobSnapshot {
140 let state = self.state.lock().unwrap();
141 JobSnapshot {
142 id: self.id,
143 kind: self.kind,
144 goal: self.goal.clone(),
145 status: state.status,
146 iteration: state.iteration,
147 limit: self.limit,
148 interval: self.interval,
149 tokens: state.tokens,
150 elapsed: self.started.elapsed(),
151 session_id: self.session_id.clone(),
152 latest_result: state.latest_result.clone(),
153 error: state.error.clone(),
154 }
155 }
156
157 fn summary(&self) -> JobSummary {
158 let state = self.state.lock().unwrap();
159 JobSummary {
160 id: self.id,
161 kind: self.kind,
162 goal: self.goal.clone(),
163 status: state.status,
164 iteration: state.iteration,
165 limit: self.limit,
166 interval: self.interval,
167 tokens: state.tokens,
168 elapsed: self.started.elapsed(),
169 }
170 }
171
172 pub fn subscribe(&self) -> watch::Receiver<u64> {
173 self.version.subscribe()
174 }
175
176 pub fn pause(&self) {
177 let mut state = self.state.lock().unwrap();
178 if matches!(state.status, JobStatus::Running | JobStatus::Queued) {
179 state.status = JobStatus::Paused;
180 drop(state);
181 self.signal();
182 }
183 }
184
185 pub fn resume(&self) {
186 let mut state = self.state.lock().unwrap();
187 if state.status == JobStatus::Paused {
188 state.status = JobStatus::Running;
189 drop(state);
190 self.wake.notify_waiters();
191 self.signal();
192 }
193 }
194
195 pub fn is_paused(&self) -> bool {
196 self.state.lock().unwrap().status == JobStatus::Paused
197 }
198
199 pub fn stop(&self) {
200 if self.state.lock().unwrap().status.is_finished() {
201 return;
202 }
203 self.cancel.cancel();
204 self.child.abort();
205 self.wake.notify_waiters();
206 }
207
208 fn signal(&self) {
209 self.version
210 .send_modify(|version| *version = version.wrapping_add(1));
211 if let Some(parent) = self.parent.upgrade() {
212 parent.emit_iterative(self.id, *self.version.borrow());
213 }
214 }
215
216 fn mark_running(&self) {
218 let mut state = self.state.lock().unwrap();
219 if state.status == JobStatus::Queued {
220 state.status = JobStatus::Running;
221 drop(state);
222 self.signal();
223 }
224 }
225
226 fn finish(&self, status: JobStatus) {
228 self.state.lock().unwrap().status = status;
229 self.signal();
230 }
231
232 async fn wait_until_ready(&self) -> bool {
233 loop {
234 let resumed = self.wake.notified();
237 if self.cancel.is_cancelled() {
238 return false;
239 }
240 if !self.is_paused() {
241 return true;
242 }
243 tokio::select! {
244 _ = self.cancel.cancelled() => return false,
245 _ = resumed => {}
246 }
247 }
248 }
249}
250
251pub struct IterativeRuntime {
252 parent: Weak<AgentSession>,
253 jobs: Mutex<Vec<Arc<JobRecord>>>,
254 next_id: AtomicU64,
255 permits: Arc<Semaphore>,
256}
257
258impl IterativeRuntime {
259 pub(crate) fn new(parent: Weak<AgentSession>) -> Arc<Self> {
260 Arc::new(Self {
261 parent,
262 jobs: Mutex::new(Vec::new()),
263 next_id: AtomicU64::new(1),
264 permits: Arc::new(Semaphore::new(MAX_ACTIVE_JOBS)),
265 })
266 }
267
268 pub fn start(
269 self: &Arc<Self>,
270 kind: JobKind,
271 goal: impl Into<String>,
272 limit: Option<u32>,
273 interval: Option<Duration>,
274 ) -> anyhow::Result<Arc<JobRecord>> {
275 let goal = goal.into();
276 if goal.trim().is_empty() {
277 anyhow::bail!("the job goal cannot be empty");
278 }
279 let parent = self
280 .parent
281 .upgrade()
282 .ok_or_else(|| anyhow::anyhow!("the parent session has closed"))?;
283 let id = self.next_id.fetch_add(1, Ordering::SeqCst);
284 if limit.is_some() && interval.is_some() {
285 anyhow::bail!("an interval and --iterations cannot be used together");
286 }
287 if kind == JobKind::Autoresearch && interval.is_some() {
288 anyhow::bail!("autoresearch does not support an interval");
289 }
290 if interval.is_some_and(|interval| interval.is_zero()) {
291 anyhow::bail!("the interval must be greater than zero");
292 }
293 let limit = limit.map(|limit| limit.clamp(1, MAX_ITERATIONS));
294 let task_name = format!("{}_{}", kind.label(), id);
295 let child = parent.create_subagent_session(
296 &task_name,
297 &format!("/root/{task_name}"),
298 ForkTurns::All,
299 None,
300 None,
301 )?;
302 let session_id = child.manager.lock().unwrap().session_id().to_string();
303 let (version, _) = watch::channel(0);
304 let record = Arc::new(JobRecord {
305 id,
306 kind,
307 goal,
308 limit,
309 interval,
310 session_id,
311 child,
312 started: Instant::now(),
313 state: Mutex::new(JobState {
314 status: JobStatus::Queued,
315 iteration: 0,
316 tokens: 0,
317 latest_result: None,
318 error: None,
319 }),
320 cancel: CancellationToken::new(),
321 wake: Notify::new(),
322 version,
323 parent: self.parent.clone(),
324 });
325
326 let mut jobs = self
327 .jobs
328 .lock()
329 .map_err(|_| anyhow::anyhow!("the job list is unavailable"))?;
330 jobs.push(record.clone());
331 while jobs.len() > MAX_RETAINED_JOBS {
332 let Some(position) = jobs
333 .iter()
334 .position(|job| job.state.lock().unwrap().status.is_finished())
335 else {
336 break;
337 };
338 jobs.remove(position);
339 }
340 drop(jobs);
341
342 let runtime = self.clone();
343 let running = record.clone();
344 tokio::spawn(async move { runtime.run(running).await });
345 record.signal();
346 Ok(record)
347 }
348
349 async fn run(self: Arc<Self>, job: Arc<JobRecord>) {
350 let permit = tokio::select! {
351 _ = job.cancel.cancelled() => None,
352 permit = self.permits.clone().acquire_owned() => permit.ok(),
353 };
354 let Some(_permit) = permit else {
355 job.finish(JobStatus::Stopped);
356 return;
357 };
358 if !job.wait_until_ready().await {
359 job.finish(JobStatus::Stopped);
360 return;
361 }
362 job.mark_running();
363
364 let mut iteration = 1_u32;
365 loop {
366 if !job.wait_until_ready().await {
367 job.finish(JobStatus::Stopped);
368 return;
369 }
370 job.state.lock().unwrap().iteration = iteration;
371 job.signal();
372
373 let outcome = child_turn::run_child_turn(
374 &job.parent,
375 &job.child,
376 iteration_prompt(job.kind, &job.goal, iteration, job.limit),
377 Some(job.cancel.clone()),
378 None,
379 )
380 .await;
381 {
382 let mut state = job.state.lock().unwrap();
383 state.tokens = state.tokens.saturating_add(outcome.usage.total_tokens);
384 state.latest_result = outcome.result.clone();
385 state.error = outcome.error.clone();
386 }
387 job.signal();
388
389 if job.cancel.is_cancelled() || outcome.status == AgentStatus::Interrupted {
390 job.finish(JobStatus::Stopped);
391 return;
392 }
393 if outcome.status == AgentStatus::Failed {
394 job.finish(JobStatus::Failed);
395 return;
396 }
397 if outcome
398 .result
399 .as_deref()
400 .is_some_and(contains_completion_marker)
401 {
402 job.finish(JobStatus::Completed);
403 return;
404 }
405 if job.limit == Some(iteration) {
406 job.finish(JobStatus::Completed);
407 return;
408 }
409 if let Some(interval) = job.interval {
410 tokio::select! {
411 _ = job.cancel.cancelled() => {
412 job.finish(JobStatus::Stopped);
413 return;
414 }
415 _ = tokio::time::sleep(interval) => {}
416 }
417 }
418 iteration = iteration.saturating_add(1);
419 }
420 }
421
422 pub fn get(&self, id: JobId) -> Option<Arc<JobRecord>> {
423 self.jobs
424 .lock()
425 .ok()?
426 .iter()
427 .find(|job| job.id == id)
428 .cloned()
429 }
430
431 pub fn summaries(&self) -> Vec<JobSummary> {
432 self.jobs
433 .lock()
434 .map(|jobs| jobs.iter().map(|job| job.summary()).collect())
435 .unwrap_or_default()
436 }
437
438 pub fn has_queued_or_running(&self) -> bool {
439 self.jobs.lock().is_ok_and(|jobs| {
440 jobs.iter().any(|job| {
441 matches!(
442 job.state.lock().unwrap().status,
443 JobStatus::Queued | JobStatus::Running
444 )
445 })
446 })
447 }
448
449 pub fn active_count(&self) -> usize {
450 self.jobs
451 .lock()
452 .map(|jobs| {
453 jobs.iter()
454 .filter(|job| !job.state.lock().unwrap().status.is_finished())
455 .count()
456 })
457 .unwrap_or(0)
458 }
459
460 pub fn latest(&self) -> Option<Arc<JobRecord>> {
461 self.jobs.lock().ok()?.last().cloned()
462 }
463
464 pub(crate) fn stop_all(&self) {
465 if let Ok(jobs) = self.jobs.lock() {
466 for job in jobs.iter() {
467 job.stop();
468 }
469 }
470 }
471}
472
473fn contains_completion_marker(result: &str) -> bool {
474 result.to_ascii_lowercase().contains("[goal-complete]")
475}
476
477fn iteration_prompt(kind: JobKind, goal: &str, iteration: u32, limit: Option<u32>) -> String {
478 let position = limit.map_or_else(
479 || format!("iteration {iteration}"),
480 |limit| format!("iteration {iteration} of {limit}"),
481 );
482 let common = format!(
483 "You are in {position} for this goal:\n\n{goal}\n\nWork directly in the shared repository. Make one useful, verified unit of progress. Do not ask for permission. End the answer with exactly [goal-complete] if the goal is fully achieved and verified. Otherwise end with exactly [continue]."
484 );
485 match kind {
486 JobKind::Loop => common,
487 JobKind::Autoresearch => format!(
488 "Autoresearch job. On the first iteration, establish a repeatable baseline and success metric. On each iteration, test one small idea, run the same verification, keep an improvement, and revert a regression. Protect existing behavior with focused tests. Record the measured result and the decision in the answer.\n\n{common}"
489 ),
490 }
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496 use kiss_ai::{AssistantEvent, AssistantMessage, ContentBlock, EventStream, StopReason};
497 use std::sync::atomic::AtomicUsize;
498
499 #[test]
500 fn unlimited_prompts_do_not_claim_a_limit() {
501 let prompt = iteration_prompt(JobKind::Loop, "fix tests", 2, None);
502 assert!(prompt.contains("iteration 2 for this goal"));
503 assert!(!prompt.contains("iteration 2 of"));
504 }
505
506 #[test]
507 fn interval_format_uses_compound_units() {
508 assert_eq!(
509 format_interval(Duration::from_secs(2 * 86_400 + 4 * 3_600)),
510 "2d4h"
511 );
512 assert_eq!(format_interval(Duration::from_millis(1_500)), "1s500ms");
513 }
514
515 #[test]
516 fn prompts_define_progress_and_completion() {
517 let loop_prompt = iteration_prompt(JobKind::Loop, "fix tests", 2, Some(10));
518 assert!(loop_prompt.contains("iteration 2 of 10"));
519 assert!(loop_prompt.contains("[goal-complete]"));
520 assert!(loop_prompt.contains("[continue]"));
521
522 let research = iteration_prompt(JobKind::Autoresearch, "make it faster", 1, None);
523 assert!(research.contains("baseline"));
524 assert!(research.contains("success metric"));
525 assert!(research.contains("revert a regression"));
526 }
527
528 #[test]
529 fn completion_marker_is_case_insensitive() {
530 assert!(contains_completion_marker("done\n[GOAL-COMPLETE]"));
531 assert!(!contains_completion_marker("keep going\n[continue]"));
532 }
533
534 fn parent_session() -> Arc<AgentSession> {
535 let registry = kiss_ai::Registry::from_builtin();
536 let model = registry.all().first().unwrap().clone();
537 AgentSession::new(
538 crate::SessionManager::in_memory(std::path::Path::new("/test")),
539 Vec::new(),
540 registry,
541 crate::Settings::default(),
542 "test".into(),
543 model,
544 kiss_ai::ThinkingLevel::Off,
545 None,
546 Arc::new(|_| {}),
547 )
548 }
549
550 #[tokio::test]
551 async fn a_pause_that_arrives_before_the_job_starts_is_kept() {
552 let parent = parent_session();
553 let job = parent
554 .iterative_jobs()
555 .unwrap()
556 .start(JobKind::Loop, "finish it", None, None)
557 .unwrap();
558 job.pause();
559 job.mark_running();
560 assert!(job.is_paused());
561 job.stop();
562 }
563
564 #[tokio::test]
565 async fn a_paused_waiter_resumes_and_a_stopped_job_refuses_work() {
566 let parent = parent_session();
567 let job = parent
568 .iterative_jobs()
569 .unwrap()
570 .start(JobKind::Loop, "finish it", None, None)
571 .unwrap();
572 job.pause();
573 let ready = job.wait_until_ready();
574 tokio::pin!(ready);
575 assert!(futures::poll!(&mut ready).is_pending());
576 job.resume();
577 assert!(
578 tokio::time::timeout(Duration::from_secs(1), ready)
579 .await
580 .unwrap()
581 );
582 job.stop();
583 assert!(!job.wait_until_ready().await);
584 }
585
586 #[tokio::test]
587 async fn one_job_reuses_its_forked_session_and_stops_early() {
588 let parent = parent_session();
589 parent
590 .manager
591 .lock()
592 .unwrap()
593 .append_message(kiss_agent::AgentMessage::user("parent context"))
594 .unwrap();
595 let calls = Arc::new(AtomicUsize::new(0));
596 parent.set_stream_fn(Some(Arc::new({
597 let calls = calls.clone();
598 move |_, _, _| {
599 let call = calls.fetch_add(1, Ordering::SeqCst);
600 let text = if call == 0 {
601 "first change\n[continue]"
602 } else {
603 "verified\n[goal-complete]"
604 };
605 let mut message = AssistantMessage::empty("fake", "fake", "fake");
606 message.content.push(ContentBlock::text(text));
607 message.stop_reason = StopReason::Stop;
608 let (sink, stream) = EventStream::channel();
609 sink.send(AssistantEvent::Start {
610 partial: message.clone(),
611 });
612 sink.done(message);
613 stream
614 }
615 })));
616
617 let runtime = parent.iterative_jobs().unwrap();
618 let job = runtime
619 .start(JobKind::Loop, "finish it", None, None)
620 .unwrap();
621 let mut updates = job.subscribe();
622 tokio::time::timeout(Duration::from_secs(2), async {
623 while !job.snapshot().status.is_finished() {
624 updates.changed().await.unwrap();
625 }
626 })
627 .await
628 .unwrap();
629
630 let snapshot = job.snapshot();
631 assert_eq!(snapshot.status, JobStatus::Completed);
632 assert_eq!(snapshot.iteration, 2);
633 assert_eq!(snapshot.limit, None);
634 assert_eq!(calls.load(Ordering::SeqCst), 2);
635 let messages = job
636 .child
637 .manager
638 .lock()
639 .unwrap()
640 .build_session_context()
641 .messages;
642 assert!(matches!(
643 messages.first(),
644 Some(kiss_agent::AgentMessage::User(user)) if user.content.as_text() == "parent context"
645 ));
646 assert_eq!(
647 messages
648 .iter()
649 .filter(|message| matches!(message, kiss_agent::AgentMessage::Assistant(_)))
650 .count(),
651 2
652 );
653 assert!(!snapshot.session_id.is_empty());
654 }
655}