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, changes that would make the codebase worse, and tracking issues. Set tracker as well for the last of those."
30                        },
31                        "tracker": {
32                            "type": "boolean",
33                            "description": "True when the issue exists to hold context for work that is filed elsewhere: an umbrella, an epic, a meta issue whose parts are their own issues. Judge it by what the issue is, not by whether you agree with it. Nothing is opened for a tracker, but it is not finished either: its parts are still open, and the shared context and rejected alternatives it records are why somebody wrote it. False for an ordinary issue, whatever you decided about it."
34                        },
35                        "reason": {
36                            "type": "string",
37                            "description": "One sentence. This is posted verbatim on the issue when both agents decline it, and the issue may well stay open afterwards, so write it for the person who opened it rather than as a verdict."
38                        },
39                        "complexity": {"type": "string", "enum": ["s", "m", "l"]},
40                        "depends_on": {
41                            "type": "array",
42                            "items": {"type": "integer"},
43                            "description": "Issue numbers from this same list that should land first. Empty if none."
44                        },
45                        "risk": {"type": "string", "enum": ["low", "med", "high"]}
46                    },
47                    "required": ["issue", "worth_doing", "tracker", "reason", "complexity", "depends_on", "risk"]
48                }
49            }
50        },
51        "required": ["issues"]
52    })
53}
54
55pub fn review() -> Value {
56    json!({
57        "type": "object",
58        "additionalProperties": false,
59        "properties": {
60            "verdict": {"type": "string", "enum": ["approve", "changes_requested"]},
61            "next_action": {"type": "string", "enum": ["merge", "fix_myself", "hand_back"]},
62            "summary": {
63                "type": "string",
64                "description": "One sentence, at most 200 characters. No preamble, no restating the diff."
65            },
66            "findings": {
67                "type": "array",
68                "items": {
69                    "type": "object",
70                    "additionalProperties": false,
71                    "properties": {
72                        "severity": {
73                            "type": "string",
74                            "enum": ["blocking", "non-blocking", "nit"],
75                            "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."
76                        },
77                        "title": {
78                            "type": "string",
79                            "description": "Under 80 characters. State the defect, not the fix."
80                        },
81                        "detail": {
82                            "type": "string",
83                            "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."
84                        },
85                        "file": {
86                            "type": "string",
87                            "description": "Path, with a line number if you have one. Empty string if the finding is general."
88                        },
89                        "problem": {
90                            "type": ["string", "null"],
91                            "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."
92                        },
93                        "reproduction": {
94                            "type": ["string", "null"],
95                            "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."
96                        },
97                        "impact": {
98                            "type": ["string", "null"],
99                            "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."
100                        },
101                        "expected": {
102                            "type": ["string", "null"],
103                            "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."
104                        },
105                        "in_scope": {
106                            "type": "boolean",
107                            "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."
108                        }
109                    },
110                    "required": [
111                        "severity",
112                        "title",
113                        "detail",
114                        "file",
115                        "in_scope",
116                        "problem",
117                        "reproduction",
118                        "impact",
119                        "expected"
120                    ]
121                }
122            }
123        },
124        "required": ["verdict", "next_action", "summary", "findings"]
125    })
126}
127
128/// What the implementor reports back, and the pull request body it becomes.
129///
130/// The body used to be one scraped `SUMMARY:` line under a `Closes #N`, which
131/// told a reviewer opening the diff cold nothing: not what was wrong, not what
132/// the change does about it, not how to check it. Asking for those separately
133/// is what puts them there, and composing the body from the fields rather than
134/// from the model's prose is what keeps it short enough to read.
135pub fn implementation() -> Value {
136    json!({
137        "type": "object",
138        "additionalProperties": false,
139        "properties": {
140            "not_worth_doing": {
141                "type": "boolean",
142                "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."
143            },
144            "reason": {
145                "type": "string",
146                "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."
147            },
148            "summary": {
149                "type": "string",
150                "description": "One plain sentence saying what changed, at most 200 characters. It leads the pull request body, and it carries one fact: what this does now that it did not before. Not the signatures, not the null handling, not the edge cases, all of which belong in changes. If it needs a comma to join two ideas, or reads like a changelog line, it is carrying too much."
151            },
152            "problem": {
153                "type": "string",
154                "description": "Two to four short sentences on what was actually wrong and what it cost, as you understand it now that you have read the code. One fact each: a sentence naming three functions and their signatures is one the reviewer has to decipher, and splitting it costs a few words and saves them that. 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."
155            },
156            "changes": {
157                "type": "array",
158                "items": {"type": "string"},
159                "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. This is where a signature or a null case belongs, one per line, rather than crowded into the summary. Not a list of touched files: the diff already has that. Empty when the summary covers it, which for a small change it does."
160            },
161            "testing": {
162                "type": "array",
163                "items": {"type": "string"},
164                "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."
165            },
166            "notes": {
167                "type": ["string", "null"],
168                "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."
169            }
170        },
171        "required": ["not_worth_doing", "reason", "summary", "problem", "changes", "testing", "notes"]
172    })
173}
174
175pub fn response() -> Value {
176    json!({
177        "type": "object",
178        "additionalProperties": false,
179        "properties": {
180            "summary": {
181                "type": "string",
182                "description": "One sentence, at most 200 characters."
183            },
184            "dispositions": {
185                "type": "array",
186                "items": {
187                    "type": "object",
188                    "additionalProperties": false,
189                    "properties": {
190                        "title": {
191                            "type": "string",
192                            "description": "Copy the reviewer's finding title exactly, so the two can be matched up."
193                        },
194                        "file": {
195                            "type": "string",
196                            "description": "Copy the reviewer's file for this finding exactly. Empty string if it had none."
197                        },
198                        "action": {
199                            "type": "string",
200                            "enum": ["fixed", "refuted", "filed_issue"],
201                            "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."
202                        },
203                        "reasoning": {
204                            "type": "string",
205                            "description": "One or two sentences. For a refutation this is the whole argument, so make it the reason and not an apology."
206                        },
207                        "new_issue_title": {
208                            "type": ["string", "null"],
209                            "description": "Only for filed_issue, null otherwise."
210                        },
211                        "new_issue_body": {
212                            "type": ["string", "null"],
213                            "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."
214                        }
215                    },
216                    "required": ["title", "file", "action", "reasoning", "new_issue_title", "new_issue_body"]
217                }
218            }
219        },
220        "required": ["summary", "dispositions"]
221    })
222}
223
224/// One reviewer judging the other reviewer's findings.
225///
226/// Used only in review only mode, where nobody is going to fix anything and the
227/// product is the finding list itself. Asking each model to read the code and
228/// rule on the other's claims is what separates a defect worth a maintainer's
229/// attention from one model's pattern match.
230pub fn adjudication() -> Value {
231    json!({
232        "type": "object",
233        "additionalProperties": false,
234        "properties": {
235            "verdicts": {
236                "type": "array",
237                "items": {
238                    "type": "object",
239                    "additionalProperties": false,
240                    "properties": {
241                        "title": {
242                            "type": "string",
243                            "description": "Copy the finding's title exactly, so it can be matched up."
244                        },
245                        "file": {
246                            "type": "string",
247                            "description": "Copy the finding's file exactly. Empty string if it had none."
248                        },
249                        "agrees": {
250                            "type": "boolean",
251                            "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."
252                        },
253                        "severity": {
254                            "type": "string",
255                            "enum": ["blocking", "non-blocking", "nit"],
256                            "description": "Your own view of how badly it matters, even where you agree the defect is real."
257                        },
258                        "reasoning": {
259                            "type": "string",
260                            "description": "One or two sentences. If you disagree, this is the whole argument, so give the reason rather than an opinion."
261                        }
262                    },
263                    "required": ["title", "file", "agrees", "severity", "reasoning"]
264                }
265            }
266        },
267        "required": ["verdicts"]
268    })
269}
270
271pub fn all() -> Vec<(&'static str, Value)> {
272    vec![
273        ("triage", triage()),
274        ("implementation", implementation()),
275        ("review", review()),
276        ("response", response()),
277    ]
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    /// Yield every object schema, however deeply nested.
285    fn objects(node: &Value, path: String, out: &mut Vec<(String, Value)>) {
286        if let Some(map) = node.as_object() {
287            if map.get("type").and_then(Value::as_str) == Some("object")
288                && map.contains_key("properties")
289            {
290                out.push((path.clone(), node.clone()));
291                if let Some(props) = map.get("properties").and_then(Value::as_object) {
292                    for (key, child) in props {
293                        objects(child, format!("{path}.{key}"), out);
294                    }
295                }
296            }
297            if let Some(items) = map.get("items") {
298                objects(items, format!("{path}[]"), out);
299            }
300        }
301    }
302
303    fn walk(name: &str, schema: &Value) -> Vec<(String, Value)> {
304        let mut out = Vec::new();
305        objects(schema, name.to_string(), &mut out);
306        out
307    }
308
309    /// Strict structured output rejects any property that is not also in
310    /// `required`. The Python original violated this in the response schema
311    /// from the start and nothing caught it, because the response schema is
312    /// only reached when a review is handed back with blocking findings, and
313    /// almost every run approved in round one.
314    #[test]
315    fn every_property_is_required() {
316        for (name, schema) in all() {
317            for (path, node) in walk(name, &schema) {
318                let props: Vec<&String> = node["properties"].as_object().unwrap().keys().collect();
319                let required: Vec<String> = node["required"]
320                    .as_array()
321                    .unwrap_or(&vec![])
322                    .iter()
323                    .filter_map(|v| v.as_str().map(str::to_string))
324                    .collect();
325                for prop in &props {
326                    assert!(
327                        required.contains(prop),
328                        "{path}: {prop} is in properties but not in required. \
329                         Make optional fields nullable instead."
330                    );
331                }
332                assert_eq!(props.len(), required.len(), "{path}: required has extras");
333            }
334        }
335    }
336
337    /// The guard that was missing. A schema field can be added to the struct
338    /// and forgotten in the schema, and every test still passes: the tests
339    /// build the struct in Rust, so they never notice the model was never
340    /// asked. That shipped once, as four bug-report fields the agents were
341    /// never told about, which quietly did nothing.
342    #[test]
343    fn the_review_schema_asks_for_every_field_a_finding_holds() {
344        use crate::model::Finding;
345
346        let asked: Vec<String> = review()["properties"]["findings"]["items"]["properties"]
347            .as_object()
348            .expect("finding properties")
349            .keys()
350            .cloned()
351            .collect();
352
353        // Round-tripping a fully populated Finding names every field serde
354        // knows about, without repeating the list here to drift out of date.
355        let populated = Finding {
356            problem: Some("p".into()),
357            reproduction: Some("r".into()),
358            impact: Some("i".into()),
359            expected: Some("e".into()),
360            ..Finding::default()
361        };
362        let held: Vec<String> = serde_json::to_value(&populated)
363            .expect("serialisable")
364            .as_object()
365            .expect("object")
366            .keys()
367            .cloned()
368            .collect();
369
370        for field in &held {
371            assert!(
372                asked.contains(field),
373                "a Finding holds `{field}` and the schema never asks for it, so the model will \
374                 not fill it and the code reading it will always see nothing"
375            );
376        }
377    }
378
379    /// The same guard for the implementation exchange, where a forgotten field
380    /// means a pull request body with an empty section in it and nobody the
381    /// wiser.
382    #[test]
383    fn the_implementation_schema_asks_for_every_field_it_holds() {
384        use crate::model::Implementation;
385
386        let asked: Vec<String> = implementation()["properties"]
387            .as_object()
388            .expect("properties")
389            .keys()
390            .cloned()
391            .collect();
392
393        let populated = Implementation {
394            notes: Some("n".into()),
395            ..Implementation::default()
396        };
397        let held: Vec<String> = serde_json::to_value(&populated)
398            .expect("serialisable")
399            .as_object()
400            .expect("object")
401            .keys()
402            .cloned()
403            .collect();
404
405        for field in &held {
406            assert!(
407                asked.contains(field),
408                "an Implementation holds `{field}` and the schema never asks for it, so the \
409                 pull request body will always be missing that part"
410            );
411        }
412    }
413
414    /// Same guard for the other direction of the same exchange.
415    #[test]
416    fn the_response_schema_asks_for_every_field_a_disposition_holds() {
417        use crate::model::{Action, Disposition};
418
419        let asked: Vec<String> = response()["properties"]["dispositions"]["items"]["properties"]
420            .as_object()
421            .expect("disposition properties")
422            .keys()
423            .cloned()
424            .collect();
425
426        let populated = Disposition {
427            title: "t".into(),
428            file: "f".into(),
429            action: Action::Fixed,
430            reasoning: "r".into(),
431            new_issue_title: Some("t".into()),
432            new_issue_body: Some("b".into()),
433        };
434        let held: Vec<String> = serde_json::to_value(&populated)
435            .expect("serialisable")
436            .as_object()
437            .expect("object")
438            .keys()
439            .cloned()
440            .collect();
441
442        for field in &held {
443            assert!(
444                asked.contains(field),
445                "a Disposition holds `{field}`, unasked for"
446            );
447        }
448    }
449
450    #[test]
451    fn objects_forbid_additional_properties() {
452        for (name, schema) in all() {
453            for (path, node) in walk(name, &schema) {
454                assert_eq!(
455                    Some(false),
456                    node["additionalProperties"].as_bool(),
457                    "{path} allows additional properties"
458                );
459            }
460        }
461    }
462
463    #[test]
464    fn optional_fields_are_spelled_as_nullable() {
465        let item = &response()["properties"]["dispositions"]["items"];
466        for field in ["new_issue_title", "new_issue_body"] {
467            let types = item["properties"][field]["type"].to_string();
468            assert!(types.contains("null"), "{field} must accept null: {types}");
469        }
470    }
471
472    /// The re-litigation guard hashes a refutation by title *and* file. If the
473    /// disposition cannot carry the file, the key it records can never match
474    /// the key the next round's finding hashes to, and the guard is dead code.
475    #[test]
476    fn a_disposition_carries_the_file_so_the_ledger_key_can_match() {
477        let props = response()["properties"]["dispositions"]["items"]["properties"].clone();
478        assert!(
479            props.get("file").is_some(),
480            "dispositions must carry a file"
481        );
482    }
483
484    #[test]
485    fn severity_and_verdict_enums_match_the_parser() {
486        use crate::model::{Severity, Verdict};
487        let sev =
488            review()["properties"]["findings"]["items"]["properties"]["severity"]["enum"].clone();
489        for value in sev.as_array().unwrap() {
490            assert!(
491                Severity::parse_lenient(value.as_str().unwrap()).is_some(),
492                "schema offers {value} but the parser rejects it"
493            );
494        }
495        let verdicts = review()["properties"]["verdict"]["enum"].clone();
496        for value in verdicts.as_array().unwrap() {
497            assert!(Verdict::parse_lenient(value.as_str().unwrap()).is_some());
498        }
499    }
500
501    #[test]
502    fn triage_enums_match_the_parser() {
503        use crate::model::{Complexity, Risk};
504        let item = &triage()["properties"]["issues"]["items"]["properties"];
505        for value in item["complexity"]["enum"].as_array().unwrap() {
506            assert!(Complexity::parse_lenient(value.as_str().unwrap()).is_some());
507        }
508        for value in item["risk"]["enum"].as_array().unwrap() {
509            assert!(Risk::parse_lenient(value.as_str().unwrap()).is_some());
510        }
511    }
512
513    #[test]
514    fn response_action_enum_matches_the_parser() {
515        use crate::model::Action;
516        let actions = response()["properties"]["dispositions"]["items"]["properties"]["action"]
517            ["enum"]
518            .clone();
519        for value in actions.as_array().unwrap() {
520            assert!(Action::parse_lenient(value.as_str().unwrap()).is_some());
521        }
522    }
523}