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
124pub fn response() -> Value {
125    json!({
126        "type": "object",
127        "additionalProperties": false,
128        "properties": {
129            "summary": {
130                "type": "string",
131                "description": "One sentence, at most 200 characters."
132            },
133            "dispositions": {
134                "type": "array",
135                "items": {
136                    "type": "object",
137                    "additionalProperties": false,
138                    "properties": {
139                        "title": {
140                            "type": "string",
141                            "description": "Copy the reviewer's finding title exactly, so the two can be matched up."
142                        },
143                        "file": {
144                            "type": "string",
145                            "description": "Copy the reviewer's file for this finding exactly. Empty string if it had none."
146                        },
147                        "action": {
148                            "type": "string",
149                            "enum": ["fixed", "refuted", "filed_issue"],
150                            "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."
151                        },
152                        "reasoning": {
153                            "type": "string",
154                            "description": "One or two sentences. For a refutation this is the whole argument, so make it the reason and not an apology."
155                        },
156                        "new_issue_title": {
157                            "type": ["string", "null"],
158                            "description": "Only for filed_issue, null otherwise."
159                        },
160                        "new_issue_body": {
161                            "type": ["string", "null"],
162                            "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."
163                        }
164                    },
165                    "required": ["title", "file", "action", "reasoning", "new_issue_title", "new_issue_body"]
166                }
167            }
168        },
169        "required": ["summary", "dispositions"]
170    })
171}
172
173/// One reviewer judging the other reviewer's findings.
174///
175/// Used only in review only mode, where nobody is going to fix anything and the
176/// product is the finding list itself. Asking each model to read the code and
177/// rule on the other's claims is what separates a defect worth a maintainer's
178/// attention from one model's pattern match.
179pub fn adjudication() -> Value {
180    json!({
181        "type": "object",
182        "additionalProperties": false,
183        "properties": {
184            "verdicts": {
185                "type": "array",
186                "items": {
187                    "type": "object",
188                    "additionalProperties": false,
189                    "properties": {
190                        "title": {
191                            "type": "string",
192                            "description": "Copy the finding's title exactly, so it can be matched up."
193                        },
194                        "file": {
195                            "type": "string",
196                            "description": "Copy the finding's file exactly. Empty string if it had none."
197                        },
198                        "agrees": {
199                            "type": "boolean",
200                            "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."
201                        },
202                        "severity": {
203                            "type": "string",
204                            "enum": ["blocking", "non-blocking", "nit"],
205                            "description": "Your own view of how badly it matters, even where you agree the defect is real."
206                        },
207                        "reasoning": {
208                            "type": "string",
209                            "description": "One or two sentences. If you disagree, this is the whole argument, so give the reason rather than an opinion."
210                        }
211                    },
212                    "required": ["title", "file", "agrees", "severity", "reasoning"]
213                }
214            }
215        },
216        "required": ["verdicts"]
217    })
218}
219
220pub fn all() -> Vec<(&'static str, Value)> {
221    vec![
222        ("triage", triage()),
223        ("review", review()),
224        ("response", response()),
225    ]
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    /// Yield every object schema, however deeply nested.
233    fn objects(node: &Value, path: String, out: &mut Vec<(String, Value)>) {
234        if let Some(map) = node.as_object() {
235            if map.get("type").and_then(Value::as_str) == Some("object")
236                && map.contains_key("properties")
237            {
238                out.push((path.clone(), node.clone()));
239                if let Some(props) = map.get("properties").and_then(Value::as_object) {
240                    for (key, child) in props {
241                        objects(child, format!("{path}.{key}"), out);
242                    }
243                }
244            }
245            if let Some(items) = map.get("items") {
246                objects(items, format!("{path}[]"), out);
247            }
248        }
249    }
250
251    fn walk(name: &str, schema: &Value) -> Vec<(String, Value)> {
252        let mut out = Vec::new();
253        objects(schema, name.to_string(), &mut out);
254        out
255    }
256
257    /// Strict structured output rejects any property that is not also in
258    /// `required`. The Python original violated this in the response schema
259    /// from the start and nothing caught it, because the response schema is
260    /// only reached when a review is handed back with blocking findings, and
261    /// almost every run approved in round one.
262    #[test]
263    fn every_property_is_required() {
264        for (name, schema) in all() {
265            for (path, node) in walk(name, &schema) {
266                let props: Vec<&String> = node["properties"].as_object().unwrap().keys().collect();
267                let required: Vec<String> = node["required"]
268                    .as_array()
269                    .unwrap_or(&vec![])
270                    .iter()
271                    .filter_map(|v| v.as_str().map(str::to_string))
272                    .collect();
273                for prop in &props {
274                    assert!(
275                        required.contains(prop),
276                        "{path}: {prop} is in properties but not in required. \
277                         Make optional fields nullable instead."
278                    );
279                }
280                assert_eq!(props.len(), required.len(), "{path}: required has extras");
281            }
282        }
283    }
284
285    /// The guard that was missing. A schema field can be added to the struct
286    /// and forgotten in the schema, and every test still passes: the tests
287    /// build the struct in Rust, so they never notice the model was never
288    /// asked. That shipped once, as four bug-report fields the agents were
289    /// never told about, which quietly did nothing.
290    #[test]
291    fn the_review_schema_asks_for_every_field_a_finding_holds() {
292        use crate::model::Finding;
293
294        let asked: Vec<String> = review()["properties"]["findings"]["items"]["properties"]
295            .as_object()
296            .expect("finding properties")
297            .keys()
298            .cloned()
299            .collect();
300
301        // Round-tripping a fully populated Finding names every field serde
302        // knows about, without repeating the list here to drift out of date.
303        let populated = Finding {
304            problem: Some("p".into()),
305            reproduction: Some("r".into()),
306            impact: Some("i".into()),
307            expected: Some("e".into()),
308            ..Finding::default()
309        };
310        let held: Vec<String> = serde_json::to_value(&populated)
311            .expect("serialisable")
312            .as_object()
313            .expect("object")
314            .keys()
315            .cloned()
316            .collect();
317
318        for field in &held {
319            assert!(
320                asked.contains(field),
321                "a Finding holds `{field}` and the schema never asks for it, so the model will \
322                 not fill it and the code reading it will always see nothing"
323            );
324        }
325    }
326
327    /// Same guard for the other direction of the same exchange.
328    #[test]
329    fn the_response_schema_asks_for_every_field_a_disposition_holds() {
330        use crate::model::{Action, Disposition};
331
332        let asked: Vec<String> = response()["properties"]["dispositions"]["items"]["properties"]
333            .as_object()
334            .expect("disposition properties")
335            .keys()
336            .cloned()
337            .collect();
338
339        let populated = Disposition {
340            title: "t".into(),
341            file: "f".into(),
342            action: Action::Fixed,
343            reasoning: "r".into(),
344            new_issue_title: Some("t".into()),
345            new_issue_body: Some("b".into()),
346        };
347        let held: Vec<String> = serde_json::to_value(&populated)
348            .expect("serialisable")
349            .as_object()
350            .expect("object")
351            .keys()
352            .cloned()
353            .collect();
354
355        for field in &held {
356            assert!(
357                asked.contains(field),
358                "a Disposition holds `{field}`, unasked for"
359            );
360        }
361    }
362
363    #[test]
364    fn objects_forbid_additional_properties() {
365        for (name, schema) in all() {
366            for (path, node) in walk(name, &schema) {
367                assert_eq!(
368                    Some(false),
369                    node["additionalProperties"].as_bool(),
370                    "{path} allows additional properties"
371                );
372            }
373        }
374    }
375
376    #[test]
377    fn optional_fields_are_spelled_as_nullable() {
378        let item = &response()["properties"]["dispositions"]["items"];
379        for field in ["new_issue_title", "new_issue_body"] {
380            let types = item["properties"][field]["type"].to_string();
381            assert!(types.contains("null"), "{field} must accept null: {types}");
382        }
383    }
384
385    /// The re-litigation guard hashes a refutation by title *and* file. If the
386    /// disposition cannot carry the file, the key it records can never match
387    /// the key the next round's finding hashes to, and the guard is dead code.
388    #[test]
389    fn a_disposition_carries_the_file_so_the_ledger_key_can_match() {
390        let props = response()["properties"]["dispositions"]["items"]["properties"].clone();
391        assert!(
392            props.get("file").is_some(),
393            "dispositions must carry a file"
394        );
395    }
396
397    #[test]
398    fn severity_and_verdict_enums_match_the_parser() {
399        use crate::model::{Severity, Verdict};
400        let sev =
401            review()["properties"]["findings"]["items"]["properties"]["severity"]["enum"].clone();
402        for value in sev.as_array().unwrap() {
403            assert!(
404                Severity::parse_lenient(value.as_str().unwrap()).is_some(),
405                "schema offers {value} but the parser rejects it"
406            );
407        }
408        let verdicts = review()["properties"]["verdict"]["enum"].clone();
409        for value in verdicts.as_array().unwrap() {
410            assert!(Verdict::parse_lenient(value.as_str().unwrap()).is_some());
411        }
412    }
413
414    #[test]
415    fn triage_enums_match_the_parser() {
416        use crate::model::{Complexity, Risk};
417        let item = &triage()["properties"]["issues"]["items"]["properties"];
418        for value in item["complexity"]["enum"].as_array().unwrap() {
419            assert!(Complexity::parse_lenient(value.as_str().unwrap()).is_some());
420        }
421        for value in item["risk"]["enum"].as_array().unwrap() {
422            assert!(Risk::parse_lenient(value.as_str().unwrap()).is_some());
423        }
424    }
425
426    #[test]
427    fn response_action_enum_matches_the_parser() {
428        use crate::model::Action;
429        let actions = response()["properties"]["dispositions"]["items"]["properties"]["action"]
430            ["enum"]
431            .clone();
432        for value in actions.as_array().unwrap() {
433            assert!(Action::parse_lenient(value.as_str().unwrap()).is_some());
434        }
435    }
436}