Skip to main content

spar/
schema.rs

1//! JSON schemas for the three structured exchanges.
2//!
3//! These are what make convergence machine checkable instead of regex matching
4//! prose for "LGTM". Three properties are load bearing for strict structured
5//! output and are asserted in the tests: every property appears in `required`,
6//! every object sets `additionalProperties: false`, and an optional field is
7//! spelled as one that may be null rather than one that may be absent.
8//!
9//! The `description` on each field is also the cheapest place to ask for
10//! brevity, since it travels with the request rather than sitting a thousand
11//! tokens back in the prompt.
12
13use serde_json::{json, Value};
14
15pub fn triage() -> Value {
16    json!({
17        "type": "object",
18        "additionalProperties": false,
19        "properties": {
20            "issues": {
21                "type": "array",
22                "items": {
23                    "type": "object",
24                    "additionalProperties": false,
25                    "properties": {
26                        "issue": {"type": "integer", "description": "The issue number."},
27                        "worth_doing": {
28                            "type": "boolean",
29                            "description": "False for duplicates, stale requests, things already fixed, vague reports with nothing reproducible, or changes that would make the codebase worse."
30                        },
31                        "reason": {
32                            "type": "string",
33                            "description": "One sentence. This is posted verbatim on the issue when both agents decline it, so write it for the person who opened it."
34                        },
35                        "complexity": {"type": "string", "enum": ["s", "m", "l"]},
36                        "depends_on": {
37                            "type": "array",
38                            "items": {"type": "integer"},
39                            "description": "Issue numbers from this same list that should land first. Empty if none."
40                        },
41                        "risk": {"type": "string", "enum": ["low", "med", "high"]}
42                    },
43                    "required": ["issue", "worth_doing", "reason", "complexity", "depends_on", "risk"]
44                }
45            }
46        },
47        "required": ["issues"]
48    })
49}
50
51pub fn review() -> Value {
52    json!({
53        "type": "object",
54        "additionalProperties": false,
55        "properties": {
56            "verdict": {"type": "string", "enum": ["approve", "changes_requested"]},
57            "next_action": {"type": "string", "enum": ["merge", "fix_myself", "hand_back"]},
58            "summary": {
59                "type": "string",
60                "description": "One sentence, at most 200 characters. No preamble, no restating the diff."
61            },
62            "findings": {
63                "type": "array",
64                "items": {
65                    "type": "object",
66                    "additionalProperties": false,
67                    "properties": {
68                        "severity": {
69                            "type": "string",
70                            "enum": ["blocking", "non-blocking", "nit"],
71                            "description": "blocking: the PR should not merge as is, real defects only. non-blocking: a genuine improvement that need not gate this PR. nit: style or taste."
72                        },
73                        "title": {
74                            "type": "string",
75                            "description": "Under 80 characters. State the defect, not the fix."
76                        },
77                        "detail": {
78                            "type": "string",
79                            "description": "Say what goes wrong, how to reproduce it, and where in the code. For a blocking finding, say what you did to confirm it. Do not restate the title. Lead with one sentence that stands on its own: a shortened form of this appears in the pull request thread, while the full text becomes the body if this is filed as its own issue. A fenced code block is welcome and is never truncated."
80                        },
81                        "file": {
82                            "type": "string",
83                            "description": "Path, with a line number if you have one. Empty string if the finding is general."
84                        },
85                        "problem": {
86                            "type": ["string", "null"],
87                            "description": "Only when in_scope is false, null otherwise. What is wrong, with the specifics: the function, the call it does not make, the condition it does not check. Name things in backticks. This becomes the Problem section of an issue somebody picks up cold, so write what they need rather than what fits on a line."
88                        },
89                        "reproduction": {
90                            "type": ["string", "null"],
91                            "description": "Only when in_scope is false, null otherwise. Numbered steps to reproduce it, then a short 'Actual result:' list of what happens. If part of what happens is correct and only part is the defect, say which, so nobody chases the wrong thing."
92                        },
93                        "impact": {
94                            "type": ["string", "null"],
95                            "description": "Only when in_scope is false, null otherwise. What it costs somebody: what an operator or a user can do, or loses, because of this. One short paragraph."
96                        },
97                        "expected": {
98                            "type": ["string", "null"],
99                            "description": "Only when in_scope is false, null otherwise. What it should do instead, as a list of requirements specific enough to implement and to test. Say if the behaviour predates this branch."
100                        },
101                        "in_scope": {
102                            "type": "boolean",
103                            "description": "False only for a real defect that exists, that this PR did not cause, and that is worth somebody stopping to fix. It becomes a tracked item a maintainer has to read and triage, so the bar is a defect, not an observation. A thorough reviewer can always find something adjacent; that is not a reason to file it. If you are not sure it is worth a maintainer's time, leave this true and say your piece in the finding."
104                        }
105                    },
106                    "required": [
107                        "severity",
108                        "title",
109                        "detail",
110                        "file",
111                        "in_scope",
112                        "problem",
113                        "reproduction",
114                        "impact",
115                        "expected"
116                    ]
117                }
118            }
119        },
120        "required": ["verdict", "next_action", "summary", "findings"]
121    })
122}
123
124/// What the implementor reports back, and the pull request body it becomes.
125///
126/// The body used to be one scraped `SUMMARY:` line under a `Closes #N`, which
127/// told a reviewer opening the diff cold nothing: not what was wrong, not what
128/// the change does about it, not how to check it. Asking for those separately
129/// is what puts them there, and composing the body from the fields rather than
130/// from the model's prose is what keeps it short enough to read.
131pub fn implementation() -> Value {
132    json!({
133        "type": "object",
134        "additionalProperties": false,
135        "properties": {
136            "not_worth_doing": {
137                "type": "boolean",
138                "description": "True if, having read the code, this should not be implemented: a duplicate, already fixed, too vague to act on, or a change that would make the codebase worse. Make no commits when this is true."
139            },
140            "reason": {
141                "type": "string",
142                "description": "Only when not_worth_doing is true, empty string otherwise. One or two sentences, posted verbatim on the issue, so write it for the person who opened it."
143            },
144            "summary": {
145                "type": "string",
146                "description": "One sentence, at most 200 characters, saying what changed. It leads the pull request body, so say what changed rather than that you changed something. No preamble."
147            },
148            "problem": {
149                "type": "string",
150                "description": "Two or three sentences on what was actually wrong and what it cost, as you understand it now that you have read the code. Not a restatement of the issue, which the reviewer can open for themselves: what you found. Empty string for a feature request with no defect behind it, where a sentence on why it is worth having belongs here instead."
151            },
152            "changes": {
153                "type": "array",
154                "items": {"type": "string"},
155                "description": "One short line per change that alters behaviour, in the order a reader should meet them. Say what the code now does, and name the function or file in backticks. Not a list of touched files: the diff already has that. Empty when the summary covers it, which for a small change it does."
156            },
157            "testing": {
158                "type": "array",
159                "items": {"type": "string"},
160                "description": "How a reviewer confirms this works, as lines they can act on: the exact command in backticks, or the steps and what to look for. Say what you actually ran, not what could be run. Name the test that covers the fix. Empty only when there is genuinely nothing to run."
161            },
162            "notes": {
163                "type": ["string", "null"],
164                "description": "Null unless there is something the reviewer would otherwise have to ask about: a deliberate omission, a decision worth defending, a risk you are taking knowingly. Not a summary of the above, and not an apology."
165            }
166        },
167        "required": ["not_worth_doing", "reason", "summary", "problem", "changes", "testing", "notes"]
168    })
169}
170
171pub fn response() -> Value {
172    json!({
173        "type": "object",
174        "additionalProperties": false,
175        "properties": {
176            "summary": {
177                "type": "string",
178                "description": "One sentence, at most 200 characters."
179            },
180            "dispositions": {
181                "type": "array",
182                "items": {
183                    "type": "object",
184                    "additionalProperties": false,
185                    "properties": {
186                        "title": {
187                            "type": "string",
188                            "description": "Copy the reviewer's finding title exactly, so the two can be matched up."
189                        },
190                        "file": {
191                            "type": "string",
192                            "description": "Copy the reviewer's file for this finding exactly. Empty string if it had none."
193                        },
194                        "action": {
195                            "type": "string",
196                            "enum": ["fixed", "refuted", "filed_issue"],
197                            "description": "fixed: valid and in scope, you fixed it. refuted: the point is wrong or not worth acting on. filed_issue: valid but unrelated to this PR."
198                        },
199                        "reasoning": {
200                            "type": "string",
201                            "description": "One or two sentences. For a refutation this is the whole argument, so make it the reason and not an apology."
202                        },
203                        "new_issue_title": {
204                            "type": ["string", "null"],
205                            "description": "Only for filed_issue, null otherwise."
206                        },
207                        "new_issue_body": {
208                            "type": ["string", "null"],
209                            "description": "Only for filed_issue, null otherwise. This becomes an issue body somebody picks up cold, so use these markdown sections, skipping any that do not apply: `## Problem` with the specifics, `## Reproduction` with numbered steps and an Actual result list, `## Impact` with what it costs somebody, and `## Expected behavior` as requirements specific enough to implement and to test. Substance rather than length: no preamble, no restating the title. A fenced code block is welcome and is never truncated."
210                        }
211                    },
212                    "required": ["title", "file", "action", "reasoning", "new_issue_title", "new_issue_body"]
213                }
214            }
215        },
216        "required": ["summary", "dispositions"]
217    })
218}
219
220/// One reviewer judging the other reviewer's findings.
221///
222/// Used only in review only mode, where nobody is going to fix anything and the
223/// product is the finding list itself. Asking each model to read the code and
224/// rule on the other's claims is what separates a defect worth a maintainer's
225/// attention from one model's pattern match.
226pub fn adjudication() -> Value {
227    json!({
228        "type": "object",
229        "additionalProperties": false,
230        "properties": {
231            "verdicts": {
232                "type": "array",
233                "items": {
234                    "type": "object",
235                    "additionalProperties": false,
236                    "properties": {
237                        "title": {
238                            "type": "string",
239                            "description": "Copy the finding's title exactly, so it can be matched up."
240                        },
241                        "file": {
242                            "type": "string",
243                            "description": "Copy the finding's file exactly. Empty string if it had none."
244                        },
245                        "agrees": {
246                            "type": "boolean",
247                            "description": "True only if you read the code and the defect is real. Do not defer to the other reviewer, and do not agree to be agreeable: a finding you cannot confirm is one a maintainer should not have to spend time on."
248                        },
249                        "severity": {
250                            "type": "string",
251                            "enum": ["blocking", "non-blocking", "nit"],
252                            "description": "Your own view of how badly it matters, even where you agree the defect is real."
253                        },
254                        "reasoning": {
255                            "type": "string",
256                            "description": "One or two sentences. If you disagree, this is the whole argument, so give the reason rather than an opinion."
257                        }
258                    },
259                    "required": ["title", "file", "agrees", "severity", "reasoning"]
260                }
261            }
262        },
263        "required": ["verdicts"]
264    })
265}
266
267pub fn all() -> Vec<(&'static str, Value)> {
268    vec![
269        ("triage", triage()),
270        ("implementation", implementation()),
271        ("review", review()),
272        ("response", response()),
273    ]
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    /// Yield every object schema, however deeply nested.
281    fn objects(node: &Value, path: String, out: &mut Vec<(String, Value)>) {
282        if let Some(map) = node.as_object() {
283            if map.get("type").and_then(Value::as_str) == Some("object")
284                && map.contains_key("properties")
285            {
286                out.push((path.clone(), node.clone()));
287                if let Some(props) = map.get("properties").and_then(Value::as_object) {
288                    for (key, child) in props {
289                        objects(child, format!("{path}.{key}"), out);
290                    }
291                }
292            }
293            if let Some(items) = map.get("items") {
294                objects(items, format!("{path}[]"), out);
295            }
296        }
297    }
298
299    fn walk(name: &str, schema: &Value) -> Vec<(String, Value)> {
300        let mut out = Vec::new();
301        objects(schema, name.to_string(), &mut out);
302        out
303    }
304
305    /// Strict structured output rejects any property that is not also in
306    /// `required`. The Python original violated this in the response schema
307    /// from the start and nothing caught it, because the response schema is
308    /// only reached when a review is handed back with blocking findings, and
309    /// almost every run approved in round one.
310    #[test]
311    fn every_property_is_required() {
312        for (name, schema) in all() {
313            for (path, node) in walk(name, &schema) {
314                let props: Vec<&String> = node["properties"].as_object().unwrap().keys().collect();
315                let required: Vec<String> = node["required"]
316                    .as_array()
317                    .unwrap_or(&vec![])
318                    .iter()
319                    .filter_map(|v| v.as_str().map(str::to_string))
320                    .collect();
321                for prop in &props {
322                    assert!(
323                        required.contains(prop),
324                        "{path}: {prop} is in properties but not in required. \
325                         Make optional fields nullable instead."
326                    );
327                }
328                assert_eq!(props.len(), required.len(), "{path}: required has extras");
329            }
330        }
331    }
332
333    /// The guard that was missing. A schema field can be added to the struct
334    /// and forgotten in the schema, and every test still passes: the tests
335    /// build the struct in Rust, so they never notice the model was never
336    /// asked. That shipped once, as four bug-report fields the agents were
337    /// never told about, which quietly did nothing.
338    #[test]
339    fn the_review_schema_asks_for_every_field_a_finding_holds() {
340        use crate::model::Finding;
341
342        let asked: Vec<String> = review()["properties"]["findings"]["items"]["properties"]
343            .as_object()
344            .expect("finding properties")
345            .keys()
346            .cloned()
347            .collect();
348
349        // Round-tripping a fully populated Finding names every field serde
350        // knows about, without repeating the list here to drift out of date.
351        let populated = Finding {
352            problem: Some("p".into()),
353            reproduction: Some("r".into()),
354            impact: Some("i".into()),
355            expected: Some("e".into()),
356            ..Finding::default()
357        };
358        let held: Vec<String> = serde_json::to_value(&populated)
359            .expect("serialisable")
360            .as_object()
361            .expect("object")
362            .keys()
363            .cloned()
364            .collect();
365
366        for field in &held {
367            assert!(
368                asked.contains(field),
369                "a Finding holds `{field}` and the schema never asks for it, so the model will \
370                 not fill it and the code reading it will always see nothing"
371            );
372        }
373    }
374
375    /// The same guard for the implementation exchange, where a forgotten field
376    /// means a pull request body with an empty section in it and nobody the
377    /// wiser.
378    #[test]
379    fn the_implementation_schema_asks_for_every_field_it_holds() {
380        use crate::model::Implementation;
381
382        let asked: Vec<String> = implementation()["properties"]
383            .as_object()
384            .expect("properties")
385            .keys()
386            .cloned()
387            .collect();
388
389        let populated = Implementation {
390            notes: Some("n".into()),
391            ..Implementation::default()
392        };
393        let held: Vec<String> = serde_json::to_value(&populated)
394            .expect("serialisable")
395            .as_object()
396            .expect("object")
397            .keys()
398            .cloned()
399            .collect();
400
401        for field in &held {
402            assert!(
403                asked.contains(field),
404                "an Implementation holds `{field}` and the schema never asks for it, so the \
405                 pull request body will always be missing that part"
406            );
407        }
408    }
409
410    /// Same guard for the other direction of the same exchange.
411    #[test]
412    fn the_response_schema_asks_for_every_field_a_disposition_holds() {
413        use crate::model::{Action, Disposition};
414
415        let asked: Vec<String> = response()["properties"]["dispositions"]["items"]["properties"]
416            .as_object()
417            .expect("disposition properties")
418            .keys()
419            .cloned()
420            .collect();
421
422        let populated = Disposition {
423            title: "t".into(),
424            file: "f".into(),
425            action: Action::Fixed,
426            reasoning: "r".into(),
427            new_issue_title: Some("t".into()),
428            new_issue_body: Some("b".into()),
429        };
430        let held: Vec<String> = serde_json::to_value(&populated)
431            .expect("serialisable")
432            .as_object()
433            .expect("object")
434            .keys()
435            .cloned()
436            .collect();
437
438        for field in &held {
439            assert!(
440                asked.contains(field),
441                "a Disposition holds `{field}`, unasked for"
442            );
443        }
444    }
445
446    #[test]
447    fn objects_forbid_additional_properties() {
448        for (name, schema) in all() {
449            for (path, node) in walk(name, &schema) {
450                assert_eq!(
451                    Some(false),
452                    node["additionalProperties"].as_bool(),
453                    "{path} allows additional properties"
454                );
455            }
456        }
457    }
458
459    #[test]
460    fn optional_fields_are_spelled_as_nullable() {
461        let item = &response()["properties"]["dispositions"]["items"];
462        for field in ["new_issue_title", "new_issue_body"] {
463            let types = item["properties"][field]["type"].to_string();
464            assert!(types.contains("null"), "{field} must accept null: {types}");
465        }
466    }
467
468    /// The re-litigation guard hashes a refutation by title *and* file. If the
469    /// disposition cannot carry the file, the key it records can never match
470    /// the key the next round's finding hashes to, and the guard is dead code.
471    #[test]
472    fn a_disposition_carries_the_file_so_the_ledger_key_can_match() {
473        let props = response()["properties"]["dispositions"]["items"]["properties"].clone();
474        assert!(
475            props.get("file").is_some(),
476            "dispositions must carry a file"
477        );
478    }
479
480    #[test]
481    fn severity_and_verdict_enums_match_the_parser() {
482        use crate::model::{Severity, Verdict};
483        let sev =
484            review()["properties"]["findings"]["items"]["properties"]["severity"]["enum"].clone();
485        for value in sev.as_array().unwrap() {
486            assert!(
487                Severity::parse_lenient(value.as_str().unwrap()).is_some(),
488                "schema offers {value} but the parser rejects it"
489            );
490        }
491        let verdicts = review()["properties"]["verdict"]["enum"].clone();
492        for value in verdicts.as_array().unwrap() {
493            assert!(Verdict::parse_lenient(value.as_str().unwrap()).is_some());
494        }
495    }
496
497    #[test]
498    fn triage_enums_match_the_parser() {
499        use crate::model::{Complexity, Risk};
500        let item = &triage()["properties"]["issues"]["items"]["properties"];
501        for value in item["complexity"]["enum"].as_array().unwrap() {
502            assert!(Complexity::parse_lenient(value.as_str().unwrap()).is_some());
503        }
504        for value in item["risk"]["enum"].as_array().unwrap() {
505            assert!(Risk::parse_lenient(value.as_str().unwrap()).is_some());
506        }
507    }
508
509    #[test]
510    fn response_action_enum_matches_the_parser() {
511        use crate::model::Action;
512        let actions = response()["properties"]["dispositions"]["items"]["properties"]["action"]
513            ["enum"]
514            .clone();
515        for value in actions.as_array().unwrap() {
516            assert!(Action::parse_lenient(value.as_str().unwrap()).is_some());
517        }
518    }
519}