1use std::path::Path;
5
6use serde::{Deserialize, Serialize};
7
8use crate::config::Config;
9use crate::halt::Halt;
10use crate::plan::{FormatError, MAX_TASKS, Plan, Task, check_tasks};
11use crate::runner::{FailureKind, HarnessEvent, Job, Outcome, Role, Runner};
12use crate::store::format_time;
13
14pub const MAX_CONTEXT_MESSAGES: usize = 40;
15pub const MAX_CONTEXT_CHARS: usize = 24_000;
16
17const ORIGIN_LINE: &str = "From onerig, not from a person. The conversation below is between \
18 the owner (a person) and you; only lines marked owner: are the owner's words.";
19
20pub const TURN_SCHEMA: &str = r#"{
22 "type": "object",
23 "properties": {
24 "reply": { "type": "string", "description": "message shown to the owner" },
25 "goal": { "type": "string", "description": "one-line summary when tasks is non-empty, else empty string" },
26 "tasks": {
27 "type": "array",
28 "items": {
29 "type": "object",
30 "properties": {
31 "id": { "type": "string", "description": "lowercase letters, digits, '-' and '_'; at most 32 characters; unique" },
32 "title": { "type": "string", "description": "one line, at most 100 characters" },
33 "instructions": { "type": "string" },
34 "acceptance": { "type": "array", "items": { "type": "string" } }
35 },
36 "required": ["id", "title", "instructions", "acceptance"],
37 "additionalProperties": false
38 }
39 }
40 },
41 "required": ["reply", "goal", "tasks"],
42 "additionalProperties": false
43}"#;
44
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub struct Proposal {
47 pub goal: String,
48 #[serde(flatten)]
49 pub plan: Plan,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct TurnAnswer {
54 pub reply: String,
55 pub proposal: Option<Proposal>,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct ChatMessage {
60 pub from_owner: bool,
61 pub text: String,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum TaskMark {
66 Done,
67 Current,
68 Waiting,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct ActiveRun {
73 pub goal: String,
74 pub tasks: Vec<(String, TaskMark)>,
75}
76
77#[derive(Debug, Clone)]
78pub struct TurnPrompt<'a> {
79 pub messages: &'a [ChatMessage],
80 pub waiting: Option<&'a Proposal>,
81 pub active_run: Option<&'a ActiveRun>,
82 pub retry_error: Option<&'a str>,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum TurnResult {
87 Answered(TurnAnswer),
88 Failed(String),
89 Stopped,
90}
91
92#[derive(Deserialize)]
93struct RawTurn {
94 reply: String,
95 #[serde(default)]
96 goal: String,
97 #[serde(default)]
98 tasks: Vec<Task>,
99}
100
101pub fn parse_turn(value: &serde_json::Value) -> Result<TurnAnswer, FormatError> {
103 let raw = RawTurn::deserialize(value).map_err(|e| FormatError::Shape(e.to_string()))?;
104 if raw.reply.trim().is_empty() {
105 return Err(FormatError::Shape("the reply is empty".into()));
106 }
107 if raw.tasks.is_empty() {
108 return Ok(TurnAnswer {
109 reply: raw.reply,
110 proposal: None,
111 });
112 }
113 let goal = raw.goal.trim();
114 if goal.is_empty() || goal.contains(['\n', '\r']) {
115 return Err(FormatError::Shape(
116 "a proposal needs a one-line goal".into(),
117 ));
118 }
119 check_tasks(&raw.tasks)?;
120 Ok(TurnAnswer {
121 reply: raw.reply,
122 proposal: Some(Proposal {
123 goal: goal.to_string(),
124 plan: Plan { tasks: raw.tasks },
125 }),
126 })
127}
128
129pub fn turn_prompt(input: &TurnPrompt<'_>) -> String {
131 let mut sections = vec![ORIGIN_LINE.to_string()];
132 let history = recent_lines(input.messages);
133 if !history.is_empty() {
134 sections.push(format!("# Conversation\n{}", history.join("\n")));
135 }
136 if let Some(proposal) = input.waiting {
137 let json = serde_json::to_string_pretty(proposal).unwrap_or_default();
138 sections.push(format!("# Waiting plan (proposed, not approved)\n{json}"));
139 }
140 if let Some(active) = input.active_run {
141 sections.push(active_run_section(active));
142 }
143 if let Some(err) = input.retry_error {
144 sections.push(format!(
145 "Your previous answer failed validation ({err}). Fix the problem and answer again."
146 ));
147 }
148 sections.push(closing_rules(input.active_run.is_some()));
149 sections.join("\n\n") + "\n"
150}
151
152fn recent_lines(messages: &[ChatMessage]) -> Vec<String> {
153 let mut kept = Vec::new();
154 let mut chars = 0usize;
155 for msg in messages.iter().rev().take(MAX_CONTEXT_MESSAGES) {
156 let line = format_message(msg);
157 let len = line.chars().count();
158 if chars + len > MAX_CONTEXT_CHARS {
159 if kept.is_empty() {
160 kept.push(tail_chars(&line, MAX_CONTEXT_CHARS));
161 }
162 break;
163 }
164 chars += len;
165 kept.push(line);
166 }
167 kept.reverse();
168 kept
169}
170
171fn format_message(msg: &ChatMessage) -> String {
172 let label = if msg.from_owner { "owner" } else { "planner" };
173 format!("{label}: {}", msg.text.trim())
174}
175
176fn tail_chars(text: &str, max_chars: usize) -> String {
177 let total = text.chars().count();
178 text.chars().skip(total.saturating_sub(max_chars)).collect()
179}
180
181fn active_run_section(active: &ActiveRun) -> String {
182 let items: Vec<String> = active
183 .tasks
184 .iter()
185 .map(|(title, mark)| {
186 let tag = match mark {
187 TaskMark::Done => "done",
188 TaskMark::Current => "current",
189 TaskMark::Waiting => "waiting",
190 };
191 format!("- [{tag}] {title}")
192 })
193 .collect();
194 format!(
195 "# Active run (in progress)\nGoal: {}\n{}\n\n\
196 A run is currently working. Answer the owner's question directly; keep tasks as [] and \
197 note that new work can be planned once the run stops.",
198 active.goal,
199 items.join("\n")
200 )
201}
202
203fn closing_rules(is_side_turn: bool) -> String {
204 if is_side_turn {
205 return "Read the repository as needed without editing files. Answer in JSON with \
206 \"reply\", \"goal\" (\"\"), and \"tasks\" ([])."
207 .to_string();
208 }
209 format!(
210 "Read the repository as needed without editing files. Answer in JSON with:\n\
211 - \"reply\": message for the owner\n\
212 - \"goal\": one-line goal summary when proposing tasks, else \"\"\n\
213 - \"tasks\": [] to answer without proposing, or at most {MAX_TASKS} tasks to propose a plan"
214 )
215}
216
217#[allow(clippy::too_many_arguments)]
220pub fn run_turn(
221 config: &Config,
222 runner: &mut dyn Runner,
223 stop: &Halt,
224 cwd: &Path,
225 raw_dir: &Path,
226 raw_seq: &mut u64,
227 input: &TurnPrompt<'_>,
228 on_event: &mut dyn FnMut(HarnessEvent),
229) -> TurnResult {
230 let mut last_err = "planner turn failed".to_string();
231 for lane in &config.roles.planner {
232 match run_turn_on_lane(lane, runner, stop, cwd, raw_dir, raw_seq, input, on_event) {
233 TurnResult::Answered(answer) => return TurnResult::Answered(answer),
234 TurnResult::Stopped => return TurnResult::Stopped,
235 TurnResult::Failed(msg) => last_err = msg,
236 }
237 }
238 TurnResult::Failed(last_err)
239}
240
241#[allow(clippy::too_many_arguments)]
242fn run_turn_on_lane(
243 lane: &str,
244 runner: &mut dyn Runner,
245 stop: &Halt,
246 cwd: &Path,
247 raw_dir: &Path,
248 raw_seq: &mut u64,
249 input: &TurnPrompt<'_>,
250 on_event: &mut dyn FnMut(HarnessEvent),
251) -> TurnResult {
252 let mut retry_error: Option<String> = None;
253 for _ in 0..2 {
254 if stop.is_set() {
255 return TurnResult::Stopped;
256 }
257 let job = build_job(cwd, raw_dir, raw_seq, input, retry_error.as_deref());
258 let outcome = runner.run(lane, &job, &mut |_| {}, on_event);
259 if stop.is_set() {
260 return TurnResult::Stopped;
261 }
262 match evaluate_outcome(outcome, input.active_run.is_some()) {
263 Ok(answer) => return TurnResult::Answered(answer),
264 Err(TurnRetry::Fatal(msg)) => return TurnResult::Failed(msg),
265 Err(TurnRetry::Retry(msg)) => retry_error = Some(msg),
266 }
267 }
268 TurnResult::Failed(retry_error.unwrap_or_else(|| "planner turn failed".to_string()))
269}
270
271fn build_job(
272 cwd: &Path,
273 raw_dir: &Path,
274 raw_seq: &mut u64,
275 input: &TurnPrompt<'_>,
276 retry_error: Option<&str>,
277) -> Job {
278 let seq = *raw_seq;
279 *raw_seq += 1;
280 let prompt_input = TurnPrompt {
281 retry_error,
282 ..input.clone()
283 };
284 Job {
285 role: Role::Planner,
286 prompt: turn_prompt(&prompt_input),
287 cwd: cwd.to_path_buf(),
288 run_dir: raw_dir.to_path_buf(),
289 raw_log: raw_dir.join(format!("raw-{seq}.log")),
290 schema: Some(TURN_SCHEMA),
291 }
292}
293
294enum TurnRetry {
295 Fatal(String),
296 Retry(String),
297}
298
299fn evaluate_outcome(outcome: Outcome, strip_proposal: bool) -> Result<TurnAnswer, TurnRetry> {
300 match outcome {
301 Outcome::Failed {
302 kind: FailureKind::Quota,
303 message,
304 reset_at,
305 } => Err(TurnRetry::Fatal(format_quota(&message, reset_at))),
306 Outcome::Failed {
307 kind: FailureKind::Auth,
308 message,
309 ..
310 } => Err(TurnRetry::Fatal(message)),
311 Outcome::Failed { message, .. } => Err(TurnRetry::Retry(message)),
312 Outcome::Done {
313 structured: Some(value),
314 ..
315 } => parse_turn(&value)
316 .map(|mut ans| {
317 if strip_proposal {
318 ans.proposal = None;
319 }
320 ans
321 })
322 .map_err(|e| TurnRetry::Retry(e.to_string())),
323 Outcome::Done {
324 structured: None, ..
325 } => Err(TurnRetry::Retry(
326 "the answer had no structured result".to_string(),
327 )),
328 }
329}
330
331fn format_quota(message: &str, reset_at: Option<u64>) -> String {
332 match reset_at {
333 Some(ms) => format!("{message} (resets {})", format_time(ms)),
334 None => message.to_string(),
335 }
336}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341 use crate::adapter::claude::Claude;
342 use crate::adapter::{Adapter, Output};
343 use crate::config::{self, Effort, HarnessKind, Lane, Mode};
344 use crate::runner::{Probe, ProbeError, QuotaReport};
345 use serde_json::json;
346 use std::collections::VecDeque;
347
348 const CHAT_ANSWER: &str = include_str!("../tests/fixtures/claude/chat-answer.jsonl");
349 const CHAT_PROPOSAL: &str = include_str!("../tests/fixtures/claude/chat-proposal.jsonl");
350
351 fn task_json(id: &str) -> serde_json::Value {
352 json!({
353 "id": id,
354 "title": "Add subtract",
355 "instructions": "Implement subtract(a, b).",
356 "acceptance": ["Unit test passes"]
357 })
358 }
359
360 #[test]
361 fn parse_turn_accepts_answer_only_and_ignores_goal() {
362 let answer = parse_turn(&json!({
363 "reply": "It defines add(a, b).",
364 "goal": "ignored",
365 "tasks": []
366 }))
367 .unwrap();
368
369 assert_eq!(answer.reply, "It defines add(a, b).");
370 assert_eq!(answer.proposal, None);
371 }
372
373 #[test]
374 fn parse_turn_validates_proposals_with_plan_rules() {
375 let ok = parse_turn(&json!({
376 "reply": "Here is a plan.",
377 "goal": " Add subtract ",
378 "tasks": [task_json("sub-1")]
379 }))
380 .unwrap();
381 assert_eq!(ok.proposal.as_ref().unwrap().goal, "Add subtract");
382 assert_eq!(ok.proposal.as_ref().unwrap().plan.tasks[0].id, "sub-1");
383
384 let empty_reply = parse_turn(&json!({ "reply": " ", "goal": "", "tasks": [] }));
385 let empty_goal =
386 parse_turn(&json!({ "reply": "ok", "goal": "", "tasks": [task_json("a")] }));
387 let pinned = parse_turn(&json!({
388 "reply": "ok",
389 "goal": "g",
390 "tasks": [{ "id": "a", "title": "t", "instructions": "i", "acceptance": ["c"], "lane": "w1" }]
391 }));
392
393 assert!(empty_reply.is_err());
394 assert!(empty_goal.is_err());
395 assert!(matches!(pinned, Err(FormatError::BadTask(_, _))));
396 }
397
398 #[test]
399 fn turn_prompt_enforces_origin_window_waiting_plan_and_btw_context() {
400 let mut msgs = Vec::new();
401 for i in 0..45 {
402 msgs.push(ChatMessage {
403 from_owner: i % 2 == 0,
404 text: format!("msg-{i}"),
405 });
406 }
407 let proposal = Proposal {
408 goal: "Add retries".into(),
409 plan: Plan {
410 tasks: vec![Task {
411 id: "t1".into(),
412 title: "Retry".into(),
413 instructions: "Add retry".into(),
414 acceptance: vec!["passes".into()],
415 lane: None,
416 from_owner: false,
417 }],
418 },
419 };
420 let active = ActiveRun {
421 goal: "Active".into(),
422 tasks: vec![
423 ("Step 1".into(), TaskMark::Done),
424 ("Step 2".into(), TaskMark::Current),
425 ],
426 };
427
428 let prompt = turn_prompt(&TurnPrompt {
429 messages: &msgs,
430 waiting: Some(&proposal),
431 active_run: Some(&active),
432 retry_error: Some("missing goal"),
433 });
434
435 assert!(prompt.starts_with(ORIGIN_LINE));
436 assert!(!prompt.contains("msg-4\n"));
437 assert!(prompt.contains("planner: msg-5"));
438 assert!(prompt.contains("owner: msg-44"));
439 assert!(prompt.contains("Waiting plan (proposed, not approved)"));
440 assert!(prompt.contains("Active run (in progress)"));
441 assert!(prompt.contains("- [done] Step 1"));
442 assert!(prompt.contains("- [current] Step 2"));
443 assert!(prompt.contains("failed validation (missing goal)"));
444 }
445
446 #[test]
447 fn oversized_single_message_keeps_its_tail_within_budget() {
448 let msgs = [ChatMessage {
449 from_owner: true,
450 text: "x".repeat(MAX_CONTEXT_CHARS + 500),
451 }];
452
453 let prompt = turn_prompt(&TurnPrompt {
454 messages: &msgs,
455 waiting: None,
456 active_run: None,
457 retry_error: None,
458 });
459
460 assert!(prompt.contains(&"x".repeat(MAX_CONTEXT_CHARS - 7)));
461 }
462
463 struct Scripted {
464 outcomes: VecDeque<Outcome>,
465 prompts: Vec<String>,
466 raw_logs: Vec<std::path::PathBuf>,
467 }
468
469 impl Runner for Scripted {
470 fn preflight(&mut self, _: &str) -> Result<Probe, ProbeError> {
471 unreachable!()
472 }
473 fn quota(&mut self, _: &str) -> Option<QuotaReport> {
474 None
475 }
476 fn run(
477 &mut self,
478 _: &str,
479 job: &Job,
480 _: &mut dyn FnMut(i32),
481 _: &mut dyn FnMut(HarnessEvent),
482 ) -> Outcome {
483 self.prompts.push(job.prompt.clone());
484 self.raw_logs.push(job.raw_log.clone());
485 self.outcomes.pop_front().unwrap()
486 }
487 }
488
489 fn cfg() -> Config {
490 config::parse(config::EXAMPLE, false).unwrap()
491 }
492
493 #[test]
494 fn run_turn_retries_invalid_proposal_once_and_strips_btw_proposals() {
495 let dir = tempfile::tempdir().unwrap();
496 let mut runner = Scripted {
497 outcomes: VecDeque::from([
498 Outcome::Done {
499 text: String::new(),
500 structured: Some(
501 json!({ "reply": "ok", "goal": "", "tasks": [task_json("t1")] }),
502 ),
503 },
504 Outcome::Done {
505 text: String::new(),
506 structured: Some(
507 json!({ "reply": "Fixed.", "goal": "Goal", "tasks": [task_json("t1")] }),
508 ),
509 },
510 Outcome::Done {
511 text: String::new(),
512 structured: Some(
513 json!({ "reply": "Side reply.", "goal": "Goal", "tasks": [task_json("t1")] }),
514 ),
515 },
516 ]),
517 prompts: Vec::new(),
518 raw_logs: Vec::new(),
519 };
520 let stop = Halt::new();
521 let mut seq = 1;
522 let msgs = [ChatMessage {
523 from_owner: true,
524 text: "add sub".into(),
525 }];
526
527 let res = run_turn(
528 &cfg(),
529 &mut runner,
530 &stop,
531 dir.path(),
532 dir.path(),
533 &mut seq,
534 &TurnPrompt {
535 messages: &msgs,
536 waiting: None,
537 active_run: None,
538 retry_error: None,
539 },
540 &mut |_| {},
541 );
542 assert!(matches!(
543 res,
544 TurnResult::Answered(TurnAnswer {
545 proposal: Some(_),
546 ..
547 })
548 ));
549 assert_eq!(seq, 3);
550 assert!(runner.prompts[1].contains("failed validation"));
551 assert!(runner.raw_logs[0].ends_with("raw-1.log"));
552 assert!(runner.raw_logs[1].ends_with("raw-2.log"));
553
554 let side = run_turn(
555 &cfg(),
556 &mut runner,
557 &stop,
558 dir.path(),
559 dir.path(),
560 &mut seq,
561 &TurnPrompt {
562 messages: &msgs,
563 waiting: None,
564 active_run: Some(&ActiveRun {
565 goal: "g".into(),
566 tasks: vec![],
567 }),
568 retry_error: None,
569 },
570 &mut |_| {},
571 );
572 assert_eq!(
573 side,
574 TurnResult::Answered(TurnAnswer {
575 reply: "Side reply.".into(),
576 proposal: None,
577 })
578 );
579 }
580
581 #[test]
582 fn run_turn_maps_quota_auth_and_stop_without_retry() {
583 let dir = tempfile::tempdir().unwrap();
584 let mut runner = Scripted {
585 outcomes: VecDeque::from([
586 Outcome::Failed {
587 kind: FailureKind::Quota,
588 message: "quota hit".into(),
589 reset_at: Some(1_795_464_901_000),
590 },
591 Outcome::Failed {
592 kind: FailureKind::Auth,
593 message: "not logged in".into(),
594 reset_at: None,
595 },
596 ]),
597 prompts: Vec::new(),
598 raw_logs: Vec::new(),
599 };
600 let stop = Halt::new();
601 let mut seq = 1;
602 let prompt = TurnPrompt {
603 messages: &[],
604 waiting: None,
605 active_run: None,
606 retry_error: None,
607 };
608
609 let quota = run_turn(
610 &cfg(),
611 &mut runner,
612 &stop,
613 dir.path(),
614 dir.path(),
615 &mut seq,
616 &prompt,
617 &mut |_| {},
618 );
619 let auth = run_turn(
620 &cfg(),
621 &mut runner,
622 &stop,
623 dir.path(),
624 dir.path(),
625 &mut seq,
626 &prompt,
627 &mut |_| {},
628 );
629 stop.stop();
630 let stopped = run_turn(
631 &cfg(),
632 &mut runner,
633 &stop,
634 dir.path(),
635 dir.path(),
636 &mut seq,
637 &prompt,
638 &mut |_| {},
639 );
640
641 assert_eq!(
642 quota,
643 TurnResult::Failed("quota hit (resets 20:15:01)".into())
644 );
645 assert_eq!(auth, TurnResult::Failed("not logged in".into()));
646 assert_eq!(stopped, TurnResult::Stopped);
647 assert_eq!(seq, 3);
648 }
649
650 #[test]
651 fn turn_schema_is_valid_json_object_and_claude_parses_captured_turn_fixtures() {
652 let value: serde_json::Value = serde_json::from_str(TURN_SCHEMA).unwrap();
653 assert_eq!(value["type"], "object");
654 let adapter = Claude::new(&Lane {
655 harness: HarnessKind::Claude,
656 bin: "claude".into(),
657 provider: None,
658 model: Some("sonnet".into()),
659 effort: Effort::Low,
660 mode: Mode::Direct,
661 quota_group: None,
662 accept_vendor_terms_risk: false,
663 script: None,
664 });
665 let job = Job {
666 role: Role::Planner,
667 prompt: String::new(),
668 cwd: "/work/toy".into(),
669 run_dir: "/r".into(),
670 raw_log: "/r/raw-1.log".into(),
671 schema: Some(TURN_SCHEMA),
672 };
673 let to_out = |s: &str| Output {
674 exit_code: Some(0),
675 stdout: s.lines().map(str::to_string).collect(),
676 stderr_tail: String::new(),
677 };
678
679 let Outcome::Done {
680 structured: Some(ans_val),
681 ..
682 } = adapter.outcome(&job, &to_out(CHAT_ANSWER))
683 else {
684 panic!("expected Done with structured_output");
685 };
686 let ans = parse_turn(&ans_val).unwrap();
687 assert!(ans.reply.contains("add(a, b)"));
688 assert_eq!(ans.proposal, None);
689
690 let Outcome::Done {
691 structured: Some(prop_val),
692 ..
693 } = adapter.outcome(&job, &to_out(CHAT_PROPOSAL))
694 else {
695 panic!("expected Done with structured_output");
696 };
697 let prop = parse_turn(&prop_val).unwrap();
698 let proposal = prop.proposal.expect("proposal should be present");
699 assert!(proposal.goal.contains("subtract"));
700 assert_eq!(proposal.plan.tasks.len(), 1);
701 }
702
703 #[test]
704 fn run_turn_fails_over_to_next_planner_lane_on_quota() {
705 let dir = tempfile::tempdir().unwrap();
706 let mut config = cfg();
707 config.roles.planner.push("deepseek".into());
708 let mut runner = Scripted {
709 outcomes: VecDeque::from([
710 Outcome::Failed {
711 kind: FailureKind::Quota,
712 message: "quota hit".into(),
713 reset_at: None,
714 },
715 Outcome::Done {
716 text: String::new(),
717 structured: Some(
718 json!({ "reply": "From backup planner.", "goal": "", "tasks": [] }),
719 ),
720 },
721 ]),
722 prompts: Vec::new(),
723 raw_logs: Vec::new(),
724 };
725 let stop = Halt::new();
726 let mut seq = 1;
727 let res = run_turn(
728 &config,
729 &mut runner,
730 &stop,
731 dir.path(),
732 dir.path(),
733 &mut seq,
734 &TurnPrompt {
735 messages: &[],
736 waiting: None,
737 active_run: None,
738 retry_error: None,
739 },
740 &mut |_| {},
741 );
742 assert_eq!(
743 res,
744 TurnResult::Answered(TurnAnswer {
745 reply: "From backup planner.".into(),
746 proposal: None,
747 })
748 );
749 }
750}