Skip to main content

onerig_core/
turn.rs

1//! Chat planner turn: answer schema, parser, prompt builder and retry loop
2//! (design sections 6.1, 6.6 and 7).
3
4use 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
20/// JSON Schema handed to the planner harness for one chat turn.
21pub 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
101/// Validates a planner turn's structured JSON output.
102pub 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
129/// Builds the planner turn prompt with recent conversation and optional state.
130pub 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/// Runs one chat planner turn (retried once on invalid structured output or non-quota error).
218#[allow(clippy::too_many_arguments)]
219pub fn run_turn(
220    config: &Config,
221    runner: &mut dyn Runner,
222    stop: &Halt,
223    cwd: &Path,
224    raw_dir: &Path,
225    raw_seq: &mut u64,
226    input: &TurnPrompt<'_>,
227    on_event: &mut dyn FnMut(HarnessEvent),
228) -> TurnResult {
229    let mut retry_error: Option<String> = None;
230    for _ in 0..2 {
231        if stop.is_set() {
232            return TurnResult::Stopped;
233        }
234        let job = build_job(cwd, raw_dir, raw_seq, input, retry_error.as_deref());
235        let outcome = runner.run(&config.roles.planner, &job, &mut |_| {}, on_event);
236        if stop.is_set() {
237            return TurnResult::Stopped;
238        }
239        match evaluate_outcome(outcome, input.active_run.is_some()) {
240            Ok(answer) => return TurnResult::Answered(answer),
241            Err(TurnRetry::Fatal(msg)) => return TurnResult::Failed(msg),
242            Err(TurnRetry::Retry(msg)) => retry_error = Some(msg),
243        }
244    }
245    TurnResult::Failed(retry_error.unwrap_or_else(|| "planner turn failed".to_string()))
246}
247
248fn build_job(
249    cwd: &Path,
250    raw_dir: &Path,
251    raw_seq: &mut u64,
252    input: &TurnPrompt<'_>,
253    retry_error: Option<&str>,
254) -> Job {
255    let seq = *raw_seq;
256    *raw_seq += 1;
257    let prompt_input = TurnPrompt {
258        retry_error,
259        ..input.clone()
260    };
261    Job {
262        role: Role::Planner,
263        prompt: turn_prompt(&prompt_input),
264        cwd: cwd.to_path_buf(),
265        run_dir: raw_dir.to_path_buf(),
266        raw_log: raw_dir.join(format!("raw-{seq}.log")),
267        schema: Some(TURN_SCHEMA),
268    }
269}
270
271enum TurnRetry {
272    Fatal(String),
273    Retry(String),
274}
275
276fn evaluate_outcome(outcome: Outcome, strip_proposal: bool) -> Result<TurnAnswer, TurnRetry> {
277    match outcome {
278        Outcome::Failed {
279            kind: FailureKind::Quota,
280            message,
281            reset_at,
282        } => Err(TurnRetry::Fatal(format_quota(&message, reset_at))),
283        Outcome::Failed {
284            kind: FailureKind::Auth,
285            message,
286            ..
287        } => Err(TurnRetry::Fatal(message)),
288        Outcome::Failed { message, .. } => Err(TurnRetry::Retry(message)),
289        Outcome::Done {
290            structured: Some(value),
291            ..
292        } => parse_turn(&value)
293            .map(|mut ans| {
294                if strip_proposal {
295                    ans.proposal = None;
296                }
297                ans
298            })
299            .map_err(|e| TurnRetry::Retry(e.to_string())),
300        Outcome::Done {
301            structured: None, ..
302        } => Err(TurnRetry::Retry(
303            "the answer had no structured result".to_string(),
304        )),
305    }
306}
307
308fn format_quota(message: &str, reset_at: Option<u64>) -> String {
309    match reset_at {
310        Some(ms) => format!("{message} (resets {})", format_time(ms)),
311        None => message.to_string(),
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use crate::adapter::claude::Claude;
319    use crate::adapter::{Adapter, Output};
320    use crate::config::{self, Effort, HarnessKind, Lane, Mode};
321    use crate::runner::{Probe, ProbeError, QuotaReport};
322    use serde_json::json;
323    use std::collections::VecDeque;
324
325    const CHAT_ANSWER: &str = include_str!("../tests/fixtures/claude/chat-answer.jsonl");
326    const CHAT_PROPOSAL: &str = include_str!("../tests/fixtures/claude/chat-proposal.jsonl");
327
328    fn task_json(id: &str) -> serde_json::Value {
329        json!({
330            "id": id,
331            "title": "Add subtract",
332            "instructions": "Implement subtract(a, b).",
333            "acceptance": ["Unit test passes"]
334        })
335    }
336
337    #[test]
338    fn parse_turn_accepts_answer_only_and_ignores_goal() {
339        let answer = parse_turn(&json!({
340            "reply": "It defines add(a, b).",
341            "goal": "ignored",
342            "tasks": []
343        }))
344        .unwrap();
345
346        assert_eq!(answer.reply, "It defines add(a, b).");
347        assert_eq!(answer.proposal, None);
348    }
349
350    #[test]
351    fn parse_turn_validates_proposals_with_plan_rules() {
352        let ok = parse_turn(&json!({
353            "reply": "Here is a plan.",
354            "goal": "  Add subtract  ",
355            "tasks": [task_json("sub-1")]
356        }))
357        .unwrap();
358        assert_eq!(ok.proposal.as_ref().unwrap().goal, "Add subtract");
359        assert_eq!(ok.proposal.as_ref().unwrap().plan.tasks[0].id, "sub-1");
360
361        let empty_reply = parse_turn(&json!({ "reply": " ", "goal": "", "tasks": [] }));
362        let empty_goal =
363            parse_turn(&json!({ "reply": "ok", "goal": "", "tasks": [task_json("a")] }));
364        let pinned = parse_turn(&json!({
365            "reply": "ok",
366            "goal": "g",
367            "tasks": [{ "id": "a", "title": "t", "instructions": "i", "acceptance": ["c"], "lane": "w1" }]
368        }));
369
370        assert!(empty_reply.is_err());
371        assert!(empty_goal.is_err());
372        assert!(matches!(pinned, Err(FormatError::BadTask(_, _))));
373    }
374
375    #[test]
376    fn turn_prompt_enforces_origin_window_waiting_plan_and_btw_context() {
377        let mut msgs = Vec::new();
378        for i in 0..45 {
379            msgs.push(ChatMessage {
380                from_owner: i % 2 == 0,
381                text: format!("msg-{i}"),
382            });
383        }
384        let proposal = Proposal {
385            goal: "Add retries".into(),
386            plan: Plan {
387                tasks: vec![Task {
388                    id: "t1".into(),
389                    title: "Retry".into(),
390                    instructions: "Add retry".into(),
391                    acceptance: vec!["passes".into()],
392                    lane: None,
393                    from_owner: false,
394                }],
395            },
396        };
397        let active = ActiveRun {
398            goal: "Active".into(),
399            tasks: vec![
400                ("Step 1".into(), TaskMark::Done),
401                ("Step 2".into(), TaskMark::Current),
402            ],
403        };
404
405        let prompt = turn_prompt(&TurnPrompt {
406            messages: &msgs,
407            waiting: Some(&proposal),
408            active_run: Some(&active),
409            retry_error: Some("missing goal"),
410        });
411
412        assert!(prompt.starts_with(ORIGIN_LINE));
413        assert!(!prompt.contains("msg-4\n"));
414        assert!(prompt.contains("planner: msg-5"));
415        assert!(prompt.contains("owner: msg-44"));
416        assert!(prompt.contains("Waiting plan (proposed, not approved)"));
417        assert!(prompt.contains("Active run (in progress)"));
418        assert!(prompt.contains("- [done] Step 1"));
419        assert!(prompt.contains("- [current] Step 2"));
420        assert!(prompt.contains("failed validation (missing goal)"));
421    }
422
423    #[test]
424    fn oversized_single_message_keeps_its_tail_within_budget() {
425        let msgs = [ChatMessage {
426            from_owner: true,
427            text: "x".repeat(MAX_CONTEXT_CHARS + 500),
428        }];
429
430        let prompt = turn_prompt(&TurnPrompt {
431            messages: &msgs,
432            waiting: None,
433            active_run: None,
434            retry_error: None,
435        });
436
437        assert!(prompt.contains(&"x".repeat(MAX_CONTEXT_CHARS - 7)));
438    }
439
440    struct Scripted {
441        outcomes: VecDeque<Outcome>,
442        prompts: Vec<String>,
443        raw_logs: Vec<std::path::PathBuf>,
444    }
445
446    impl Runner for Scripted {
447        fn preflight(&mut self, _: &str) -> Result<Probe, ProbeError> {
448            unreachable!()
449        }
450        fn quota(&mut self, _: &str) -> Option<QuotaReport> {
451            None
452        }
453        fn run(
454            &mut self,
455            _: &str,
456            job: &Job,
457            _: &mut dyn FnMut(i32),
458            _: &mut dyn FnMut(HarnessEvent),
459        ) -> Outcome {
460            self.prompts.push(job.prompt.clone());
461            self.raw_logs.push(job.raw_log.clone());
462            self.outcomes.pop_front().unwrap()
463        }
464    }
465
466    fn cfg() -> Config {
467        config::parse(config::EXAMPLE, false).unwrap()
468    }
469
470    #[test]
471    fn run_turn_retries_invalid_proposal_once_and_strips_btw_proposals() {
472        let dir = tempfile::tempdir().unwrap();
473        let mut runner = Scripted {
474            outcomes: VecDeque::from([
475                Outcome::Done {
476                    text: String::new(),
477                    structured: Some(
478                        json!({ "reply": "ok", "goal": "", "tasks": [task_json("t1")] }),
479                    ),
480                },
481                Outcome::Done {
482                    text: String::new(),
483                    structured: Some(
484                        json!({ "reply": "Fixed.", "goal": "Goal", "tasks": [task_json("t1")] }),
485                    ),
486                },
487                Outcome::Done {
488                    text: String::new(),
489                    structured: Some(
490                        json!({ "reply": "Side reply.", "goal": "Goal", "tasks": [task_json("t1")] }),
491                    ),
492                },
493            ]),
494            prompts: Vec::new(),
495            raw_logs: Vec::new(),
496        };
497        let stop = Halt::new();
498        let mut seq = 1;
499        let msgs = [ChatMessage {
500            from_owner: true,
501            text: "add sub".into(),
502        }];
503
504        let res = run_turn(
505            &cfg(),
506            &mut runner,
507            &stop,
508            dir.path(),
509            dir.path(),
510            &mut seq,
511            &TurnPrompt {
512                messages: &msgs,
513                waiting: None,
514                active_run: None,
515                retry_error: None,
516            },
517            &mut |_| {},
518        );
519        assert!(matches!(
520            res,
521            TurnResult::Answered(TurnAnswer {
522                proposal: Some(_),
523                ..
524            })
525        ));
526        assert_eq!(seq, 3);
527        assert!(runner.prompts[1].contains("failed validation"));
528        assert!(runner.raw_logs[0].ends_with("raw-1.log"));
529        assert!(runner.raw_logs[1].ends_with("raw-2.log"));
530
531        let side = run_turn(
532            &cfg(),
533            &mut runner,
534            &stop,
535            dir.path(),
536            dir.path(),
537            &mut seq,
538            &TurnPrompt {
539                messages: &msgs,
540                waiting: None,
541                active_run: Some(&ActiveRun {
542                    goal: "g".into(),
543                    tasks: vec![],
544                }),
545                retry_error: None,
546            },
547            &mut |_| {},
548        );
549        assert_eq!(
550            side,
551            TurnResult::Answered(TurnAnswer {
552                reply: "Side reply.".into(),
553                proposal: None,
554            })
555        );
556    }
557
558    #[test]
559    fn run_turn_maps_quota_auth_and_stop_without_retry() {
560        let dir = tempfile::tempdir().unwrap();
561        let mut runner = Scripted {
562            outcomes: VecDeque::from([
563                Outcome::Failed {
564                    kind: FailureKind::Quota,
565                    message: "quota hit".into(),
566                    reset_at: Some(1_795_464_901_000),
567                },
568                Outcome::Failed {
569                    kind: FailureKind::Auth,
570                    message: "not logged in".into(),
571                    reset_at: None,
572                },
573            ]),
574            prompts: Vec::new(),
575            raw_logs: Vec::new(),
576        };
577        let stop = Halt::new();
578        let mut seq = 1;
579        let prompt = TurnPrompt {
580            messages: &[],
581            waiting: None,
582            active_run: None,
583            retry_error: None,
584        };
585
586        let quota = run_turn(
587            &cfg(),
588            &mut runner,
589            &stop,
590            dir.path(),
591            dir.path(),
592            &mut seq,
593            &prompt,
594            &mut |_| {},
595        );
596        let auth = run_turn(
597            &cfg(),
598            &mut runner,
599            &stop,
600            dir.path(),
601            dir.path(),
602            &mut seq,
603            &prompt,
604            &mut |_| {},
605        );
606        stop.stop();
607        let stopped = run_turn(
608            &cfg(),
609            &mut runner,
610            &stop,
611            dir.path(),
612            dir.path(),
613            &mut seq,
614            &prompt,
615            &mut |_| {},
616        );
617
618        assert_eq!(
619            quota,
620            TurnResult::Failed("quota hit (resets 20:15:01)".into())
621        );
622        assert_eq!(auth, TurnResult::Failed("not logged in".into()));
623        assert_eq!(stopped, TurnResult::Stopped);
624        assert_eq!(seq, 3);
625    }
626
627    #[test]
628    fn turn_schema_is_valid_json_object_and_claude_parses_captured_turn_fixtures() {
629        let value: serde_json::Value = serde_json::from_str(TURN_SCHEMA).unwrap();
630        assert_eq!(value["type"], "object");
631        let adapter = Claude::new(&Lane {
632            harness: HarnessKind::Claude,
633            bin: "claude".into(),
634            provider: None,
635            model: Some("sonnet".into()),
636            effort: Effort::Low,
637            mode: Mode::Direct,
638            quota_group: None,
639            accept_vendor_terms_risk: false,
640            script: None,
641        });
642        let job = Job {
643            role: Role::Planner,
644            prompt: String::new(),
645            cwd: "/work/toy".into(),
646            run_dir: "/r".into(),
647            raw_log: "/r/raw-1.log".into(),
648            schema: Some(TURN_SCHEMA),
649        };
650        let to_out = |s: &str| Output {
651            exit_code: Some(0),
652            stdout: s.lines().map(str::to_string).collect(),
653            stderr_tail: String::new(),
654        };
655
656        let Outcome::Done {
657            structured: Some(ans_val),
658            ..
659        } = adapter.outcome(&job, &to_out(CHAT_ANSWER))
660        else {
661            panic!("expected Done with structured_output");
662        };
663        let ans = parse_turn(&ans_val).unwrap();
664        assert!(ans.reply.contains("add(a, b)"));
665        assert_eq!(ans.proposal, None);
666
667        let Outcome::Done {
668            structured: Some(prop_val),
669            ..
670        } = adapter.outcome(&job, &to_out(CHAT_PROPOSAL))
671        else {
672            panic!("expected Done with structured_output");
673        };
674        let prop = parse_turn(&prop_val).unwrap();
675        let proposal = prop.proposal.expect("proposal should be present");
676        assert!(proposal.goal.contains("subtract"));
677        assert_eq!(proposal.plan.tasks.len(), 1);
678    }
679}