Skip to main content

onerig_core/
plan.rs

1//! The plan a planner returns and the verdict a reviewer returns, with the
2//! checks that decide whether a harness's answer is usable.
3
4use std::collections::HashSet;
5
6use serde::{Deserialize, Serialize};
7
8pub const MAX_TASKS: usize = 20;
9const MAX_ID_CHARS: usize = 32;
10const MAX_TITLE_CHARS: usize = 100;
11
12/// JSON Schema text handed to a harness that supports structured output.
13/// It only shapes the answer; `parse_plan` is what decides.
14pub const PLAN_SCHEMA: &str = r#"{
15  "type": "object",
16  "properties": {
17    "tasks": {
18      "type": "array",
19      "items": {
20        "type": "object",
21        "properties": {
22          "id": { "type": "string", "description": "lowercase letters, digits, '-' and '_'; at most 32 characters; unique" },
23          "title": { "type": "string", "description": "one line, at most 100 characters" },
24          "instructions": { "type": "string" },
25          "acceptance": { "type": "array", "items": { "type": "string" } }
26        },
27        "required": ["id", "title", "instructions", "acceptance"]
28      }
29    }
30  },
31  "required": ["tasks"]
32}"#;
33
34/// JSON Schema text handed to a harness that supports structured output.
35/// It only shapes the answer; `parse_verdict` is what decides.
36pub const VERDICT_SCHEMA: &str = r#"{
37  "type": "object",
38  "properties": {
39    "verdict": { "type": "string", "enum": ["approve", "revise"] },
40    "summary": { "type": "string" },
41    "issues": {
42      "type": "array",
43      "items": {
44        "type": "object",
45        "properties": {
46          "file": { "type": "string" },
47          "note": { "type": "string" }
48        },
49        "required": ["file", "note"]
50      }
51    }
52  },
53  "required": ["verdict", "summary"]
54}"#;
55
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct Task {
58    pub id: String,
59    pub title: String,
60    pub instructions: String,
61    pub acceptance: Vec<String>,
62    /// Only this lane may work on the task; no fallback to another lane.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub lane: Option<String>,
65    /// The task's words were typed by the owner, not written by the planner.
66    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
67    pub from_owner: bool,
68}
69
70const OWNER_TASK_ID: &str = "owner-1";
71const OWNER_ACCEPTANCE: &str = "What the owner asked for is done.";
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74pub struct Plan {
75    pub tasks: Vec<Task>,
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "snake_case")]
80pub enum VerdictKind {
81    Approve,
82    Revise,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct Issue {
87    pub file: String,
88    pub note: String,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct Verdict {
93    pub verdict: VerdictKind,
94    pub summary: String,
95    #[serde(default)]
96    pub issues: Vec<Issue>,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
100pub enum FormatError {
101    #[error("the result does not have the expected shape: {0}")]
102    Shape(String),
103    #[error("a plan needs 1 to {MAX_TASKS} tasks, got {0}")]
104    TaskCount(usize),
105    #[error(
106        "task id {0:?} is not valid: use lowercase letters, digits, '-' and '_', at most {MAX_ID_CHARS} characters"
107    )]
108    BadId(String),
109    #[error("task id {0:?} is used twice")]
110    DuplicateId(String),
111    #[error("task {0:?}: {1}")]
112    BadTask(String, &'static str),
113    #[error("a revise verdict needs at least one issue")]
114    ReviseWithoutIssues,
115}
116
117/// Turn a planner's structured answer into a plan, or say why it is unusable.
118pub fn parse_plan(value: &serde_json::Value) -> Result<Plan, FormatError> {
119    let plan = Plan::deserialize(value).map_err(|e| FormatError::Shape(e.to_string()))?;
120    check_tasks(&plan.tasks)?;
121    Ok(plan)
122}
123
124/// Validates a non-empty list of planner-authored tasks (rejecting owner-only fields).
125pub(crate) fn check_tasks(tasks: &[Task]) -> Result<(), FormatError> {
126    if tasks.is_empty() || tasks.len() > MAX_TASKS {
127        return Err(FormatError::TaskCount(tasks.len()));
128    }
129    let mut seen = HashSet::new();
130    for task in tasks {
131        if task.lane.is_some() || task.from_owner {
132            return Err(FormatError::BadTask(
133                task.id.clone(),
134                "only the owner can pin a lane or speak as the owner",
135            ));
136        }
137        check_task(task)?;
138        if !seen.insert(task.id.as_str()) {
139            return Err(FormatError::DuplicateId(task.id.clone()));
140        }
141    }
142    Ok(())
143}
144
145/// A one-task plan from text the owner typed for one lane (`@lane text`).
146/// The title is the first non-blank line, cut to fit a commit subject.
147pub fn owner_plan(lane: &str, text: &str) -> Result<Plan, FormatError> {
148    let text = text.trim();
149    let Some(first) = text.lines().map(str::trim).find(|l| !l.is_empty()) else {
150        return Err(FormatError::TaskCount(0));
151    };
152    let task = Task {
153        id: OWNER_TASK_ID.to_string(),
154        title: first.chars().take(MAX_TITLE_CHARS).collect(),
155        instructions: text.to_string(),
156        acceptance: vec![OWNER_ACCEPTANCE.to_string()],
157        lane: Some(lane.to_string()),
158        from_owner: true,
159    };
160    check_task(&task)?;
161    Ok(Plan { tasks: vec![task] })
162}
163
164/// Turn a reviewer's structured answer into a verdict, or say why it is unusable.
165pub fn parse_verdict(value: &serde_json::Value) -> Result<Verdict, FormatError> {
166    let verdict = Verdict::deserialize(value).map_err(|e| FormatError::Shape(e.to_string()))?;
167    if verdict.verdict == VerdictKind::Revise && verdict.issues.is_empty() {
168        return Err(FormatError::ReviseWithoutIssues);
169    }
170    Ok(verdict)
171}
172
173fn check_task(task: &Task) -> Result<(), FormatError> {
174    if !is_valid_id(&task.id) {
175        return Err(FormatError::BadId(task.id.clone()));
176    }
177    let problem = if !is_valid_title(&task.title) {
178        "the title must be one non-empty line of at most 100 characters"
179    } else if task.instructions.trim().is_empty() {
180        "the instructions are empty"
181    } else if task.acceptance.is_empty() || task.acceptance.iter().any(|a| a.trim().is_empty()) {
182        "at least one acceptance item is needed and none may be empty"
183    } else {
184        return Ok(());
185    };
186    Err(FormatError::BadTask(task.id.clone(), problem))
187}
188
189/// The id ends up in file names and log lines, so it is kept to a safe alphabet.
190pub(crate) fn is_valid_id(id: &str) -> bool {
191    let is_first = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit();
192    let is_rest = |c: char| is_first(c) || c == '-' || c == '_';
193    id.len() <= MAX_ID_CHARS && id.starts_with(is_first) && id.chars().all(is_rest)
194}
195
196/// The title becomes a commit subject.
197fn is_valid_title(title: &str) -> bool {
198    !title.trim().is_empty()
199        && !title.contains(['\n', '\r'])
200        && title.chars().count() <= MAX_TITLE_CHARS
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use serde_json::{Value, json};
207
208    fn task(id: &str) -> Value {
209        json!({
210            "id": id,
211            "title": "Add retry to the HTTP client",
212            "instructions": "Wrap send() in a retry loop.",
213            "acceptance": ["Requests are retried three times on 5xx"]
214        })
215    }
216
217    fn plan_of(tasks: Vec<Value>) -> Value {
218        json!({ "tasks": tasks })
219    }
220
221    fn with(mut task: Value, key: &str, value: Value) -> Value {
222        task[key] = value;
223        task
224    }
225
226    #[test]
227    fn accepts_a_valid_plan() {
228        let plan = parse_plan(&plan_of(vec![task("retry-helper"), task("wire_in2")])).unwrap();
229
230        assert_eq!(plan.tasks.len(), 2);
231        assert_eq!(plan.tasks[0].id, "retry-helper");
232        assert_eq!(plan.tasks[1].acceptance.len(), 1);
233    }
234
235    #[test]
236    fn rejects_a_result_without_tasks() {
237        let error = parse_plan(&json!({ "plan": [] })).unwrap_err();
238
239        assert!(matches!(error, FormatError::Shape(_)));
240    }
241
242    #[test]
243    fn rejects_a_plan_with_no_tasks_or_too_many() {
244        let too_many = (0..=MAX_TASKS).map(|i| task(&format!("t{i}"))).collect();
245
246        assert_eq!(parse_plan(&plan_of(vec![])), Err(FormatError::TaskCount(0)));
247        assert_eq!(
248            parse_plan(&plan_of(too_many)),
249            Err(FormatError::TaskCount(MAX_TASKS + 1))
250        );
251    }
252
253    #[test]
254    fn accepts_the_largest_allowed_plan_and_id() {
255        let tasks = (0..MAX_TASKS).map(|i| task(&format!("t{i}"))).collect();
256        let longest_id = "a".repeat(32);
257
258        assert!(parse_plan(&plan_of(tasks)).is_ok());
259        assert!(parse_plan(&plan_of(vec![task(&longest_id)])).is_ok());
260    }
261
262    #[test]
263    fn rejects_ids_that_are_not_safe_in_file_names() {
264        for id in [
265            "",
266            "Retry",
267            "-lead",
268            "_lead",
269            "a b",
270            "a/b",
271            "é",
272            &"a".repeat(33),
273        ] {
274            assert_eq!(
275                parse_plan(&plan_of(vec![task(id)])),
276                Err(FormatError::BadId(id.to_string())),
277                "id {id:?}"
278            );
279        }
280    }
281
282    #[test]
283    fn rejects_an_id_used_twice() {
284        let error = parse_plan(&plan_of(vec![task("a"), task("b"), task("a")])).unwrap_err();
285
286        assert_eq!(error, FormatError::DuplicateId("a".into()));
287    }
288
289    #[test]
290    fn rejects_a_title_that_is_empty_long_or_multi_line() {
291        for title in [
292            "",
293            "   ",
294            "two\nlines",
295            "carriage\rreturn",
296            &"x".repeat(101),
297        ] {
298            let bad = with(task("a"), "title", json!(title));
299            assert!(
300                matches!(parse_plan(&plan_of(vec![bad])), Err(FormatError::BadTask(id, _)) if id == "a"),
301                "title {title:?}"
302            );
303        }
304        let longest = with(task("a"), "title", json!("ü".repeat(100)));
305        assert!(parse_plan(&plan_of(vec![longest])).is_ok());
306    }
307
308    #[test]
309    fn rejects_empty_instructions_and_missing_acceptance() {
310        let no_instructions = with(task("a"), "instructions", json!(" \n"));
311        let no_acceptance = with(task("a"), "acceptance", json!([]));
312        let blank_acceptance = with(task("a"), "acceptance", json!(["ok", " "]));
313
314        for bad in [no_instructions, no_acceptance, blank_acceptance] {
315            assert!(matches!(
316                parse_plan(&plan_of(vec![bad])),
317                Err(FormatError::BadTask(_, _))
318            ));
319        }
320    }
321
322    #[test]
323    fn accepts_an_approval_without_issues() {
324        let verdict = parse_verdict(&json!({ "verdict": "approve", "summary": "Good." })).unwrap();
325
326        assert_eq!(verdict.verdict, VerdictKind::Approve);
327        assert!(verdict.issues.is_empty());
328    }
329
330    #[test]
331    fn accepts_a_revise_with_issues() {
332        let verdict = parse_verdict(&json!({
333            "verdict": "revise",
334            "summary": "One problem.",
335            "issues": [{ "file": "src/http.rs", "note": "Retry also fires on 4xx." }]
336        }))
337        .unwrap();
338
339        assert_eq!(verdict.verdict, VerdictKind::Revise);
340        assert_eq!(verdict.issues[0].file, "src/http.rs");
341    }
342
343    #[test]
344    fn rejects_a_revise_without_issues() {
345        let error = parse_verdict(&json!({ "verdict": "revise", "summary": "Hm." })).unwrap_err();
346
347        assert_eq!(error, FormatError::ReviseWithoutIssues);
348    }
349
350    #[test]
351    fn rejects_an_unknown_verdict_word() {
352        let error = parse_verdict(&json!({ "verdict": "lgtm", "summary": "" })).unwrap_err();
353
354        assert!(matches!(error, FormatError::Shape(_)));
355    }
356
357    #[test]
358    fn schemas_are_json_objects() {
359        for schema in [PLAN_SCHEMA, VERDICT_SCHEMA] {
360            let value: Value = serde_json::from_str(schema).unwrap();
361            assert_eq!(value["type"], "object");
362        }
363    }
364
365    #[test]
366    fn a_planner_can_neither_pin_a_lane_nor_claim_the_owners_words() {
367        let pinned = with(task("a"), "lane", json!("w1"));
368        let claimed = with(task("b"), "from_owner", json!(true));
369
370        let pinned = parse_plan(&plan_of(vec![pinned])).unwrap_err();
371        let claimed = parse_plan(&plan_of(vec![claimed])).unwrap_err();
372
373        assert_eq!(
374            pinned,
375            FormatError::BadTask(
376                "a".into(),
377                "only the owner can pin a lane or speak as the owner"
378            )
379        );
380        assert!(matches!(claimed, FormatError::BadTask(id, _) if id == "b"));
381    }
382
383    #[test]
384    fn an_owner_task_is_pinned_to_its_lane_and_carries_the_owners_words() {
385        let plan = owner_plan("w2", "\n  Fix the typo in README  \nIt says helo.").unwrap();
386
387        assert_eq!(
388            plan.tasks,
389            [Task {
390                id: "owner-1".into(),
391                title: "Fix the typo in README".into(),
392                instructions: "Fix the typo in README  \nIt says helo.".into(),
393                acceptance: vec!["What the owner asked for is done.".into()],
394                lane: Some("w2".into()),
395                from_owner: true,
396            }]
397        );
398    }
399
400    #[test]
401    fn an_owner_title_is_the_first_line_cut_at_100_characters() {
402        let long = "é".repeat(150);
403
404        let plan = owner_plan("w1", &long).unwrap();
405
406        assert_eq!(plan.tasks[0].title, "é".repeat(100));
407        assert_eq!(owner_plan("w1", " \n\t "), Err(FormatError::TaskCount(0)));
408    }
409
410    #[test]
411    fn a_plan_without_owner_fields_keeps_the_version_1_shape() {
412        let plan = parse_plan(&plan_of(vec![task("a")])).unwrap();
413
414        let written = serde_json::to_value(&plan).unwrap();
415
416        assert_eq!(written, plan_of(vec![task("a")]));
417        assert_eq!(plan.tasks[0].lane, None);
418        assert!(!plan.tasks[0].from_owner);
419    }
420}