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: this should not merge as is, real defects only. non-blocking: real, and smaller than holding the merge for. A minor defect belongs here as much as an improvement does. 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, say your piece in the finding and label it non-blocking."
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
271/// One agent ruling on recorded follow-ups, before any becomes an issue.
272///
273/// Deliberately not the triage schema. Triage asks whether an issue is worth a
274/// pull request; this asks whether a note written weeks ago is still true of the
275/// code, which is a different question with a different expensive mistake:
276/// dropping something real, rather than scheduling something small.
277pub fn screen() -> Value {
278    json!({
279        "type": "object",
280        "additionalProperties": false,
281        "properties": {
282            "entries": {
283                "type": "array",
284                "items": {
285                    "type": "object",
286                    "additionalProperties": false,
287                    "properties": {
288                        "entry": {
289                            "type": "integer",
290                            "description": "The number this entry was given in the list above. Copy it exactly, so the verdict can be matched back to the entry it is about."
291                        },
292                        "verdict": {
293                            "type": "string",
294                            "enum": ["still_relevant", "already_fixed", "not_worth_it", "duplicate"],
295                            "description": "still_relevant files it as an issue. The other three take it out of the queue and file nothing, so say still_relevant when you are unsure: what survives is triaged by both agents afterwards and can be declined there, while what is dropped here is dropped."
296                        },
297                        "title": {
298                            "type": "string",
299                            "description": "The entry's title, which becomes the issue title. Copy it across unchanged unless it is wrong or says nothing, in which case write one that states the defect."
300                        },
301                        "reason": {
302                            "type": "string",
303                            "description": "One sentence. For already_fixed, name the function or the change that fixed it, so somebody can check you. For anything but still_relevant this is the only record of why the entry was dropped, so give the reason rather than the verdict again."
304                        },
305                        "duplicate_of": {
306                            "type": ["integer", "null"],
307                            "description": "Only when the verdict is duplicate, null otherwise. An open issue number, or the number of an earlier entry in this same list."
308                        }
309                    },
310                    "required": ["entry", "verdict", "title", "reason", "duplicate_of"]
311                }
312            }
313        },
314        "required": ["entries"]
315    })
316}
317
318/// One agent ruling on a whole queue at once: is this worth splitting.
319///
320/// One call rather than N, for the reason `screen` is one call: a repository
321/// aware pass is the dominant cost, and "is this too big to work in one piece"
322/// is partly a judgement across the queue rather than about each item alone.
323pub fn split_screen() -> Value {
324    json!({
325        "type": "object",
326        "additionalProperties": false,
327        "properties": {
328            "items": {
329                "type": "array",
330                "items": {
331                    "type": "object",
332                    "additionalProperties": false,
333                    "properties": {
334                        "item": {
335                            "type": "integer",
336                            "description": "The issue or pull request number from the list above, copied exactly, so the verdict can be matched back to what it is about."
337                        },
338                        "split": {
339                            "type": "boolean",
340                            "description": "True only for something that is plainly several separate pieces of work and would be reviewed better as several. Say false when you are unsure: no is the common answer, and a split proposed on a whim is a proposal somebody now has to read. Size alone is not the test, since a forty file rename is one piece of work and a three file mess can be three."
341                        },
342                        "reason": {
343                            "type": "string",
344                            "description": "One sentence. For true, name the pieces you can see, so somebody can check you before two more agent calls are spent on it."
345                        }
346                    },
347                    "required": ["item", "split", "reason"]
348                }
349            }
350        },
351        "required": ["items"]
352    })
353}
354
355/// One agent decomposing one issue or one pull request.
356///
357/// The descriptions carry the two rules the command rests on: a part that
358/// cannot stand on its own is not a part, and the whole value of splitting is
359/// that each piece can be reviewed and merged by itself.
360pub fn split_proposal() -> Value {
361    json!({
362        "type": "object",
363        "additionalProperties": false,
364        "properties": {
365            "should_split": {
366                "type": "boolean",
367                "description": "False when this is one piece of work, however large. A rename across forty files is one change; three unrelated fixes in one file are three. False is a fine answer and costs one person one read of something that stays as it was."
368            },
369            "reason": {
370                "type": "string",
371                "description": "One or two sentences on why it should or should not be split. For false this is the whole argument, so give the reason rather than the verdict again."
372            },
373            "stacked": {
374                "type": "boolean",
375                "description": "True only when the parts are genuinely sequential, so each needs its predecessor to make sense. Stacked parts are created in order, each branched off the one before. False means each part stands on the base branch and can be reviewed and merged in any order, which is what makes the review loop cheaper, so prefer it wherever the change allows."
376            },
377            "parts": {
378                "type": "array",
379                "items": {
380                    "type": "object",
381                    "additionalProperties": false,
382                    "properties": {
383                        "title": {
384                            "type": "string",
385                            "description": "Under 80 characters. States the piece of work, not the fact that it was split out."
386                        },
387                        "body": {
388                            "type": "string",
389                            "description": "For an issue, the body of the issue this part becomes, written for somebody picking it up cold with no sight of the parent: what is wrong, how to see it, what it should do instead. For a pull request slice, what this slice is and why it stands on its own. Either way, no preamble and no restating the title."
390                        },
391                        "files": {
392                            "type": ["array", "null"],
393                            "items": {"type": "string"},
394                            "description": "Only when splitting a pull request, null when splitting an issue. The paths from the change that this slice carries, copied exactly from the list you were given. Every path belongs to at most one part, and a part whose files cannot build and pass on their own is not a part: fold it into another or leave it out."
395                        }
396                    },
397                    "required": ["title", "body", "files"]
398                }
399            }
400        },
401        "required": ["should_split", "reason", "stacked", "parts"]
402    })
403}
404
405/// The second agent ruling on the first one's decomposition.
406///
407/// Not a second proposal. Two decompositions of one thing cannot be reconciled
408/// mechanically, so this agent rules on the one in front of it: accept, reject,
409/// or accept with named parts struck.
410pub fn split_check() -> Value {
411    json!({
412        "type": "object",
413        "additionalProperties": false,
414        "properties": {
415            "accept": {
416                "type": "boolean",
417                "description": "True only if you read the code and this decomposition is right. Do not defer to the other agent and do not agree to be agreeable. Getting a rejection wrong costs one person one read of something that stays as it was; getting an acceptance wrong costs them issues to close, a checklist to strip out of somebody's body, and branches and pull requests to delete."
418            },
419            "stacked": {
420                "type": "boolean",
421                "description": "Your own view of whether the parts are sequential, whatever the other agent said. True means each part is branched off the one before it."
422            },
423            "strike": {
424                "type": "array",
425                "items": {"type": "integer"},
426                "description": "The numbers of any parts, from 1, that should not be split out: a part that cannot stand on its own, one that is really the same work as another, one that is too small to be worth its own review. Empty to accept the parts as proposed. Striking so many that fewer than two remain means nothing is split, which is the right answer when that is what you think."
427            },
428            "reasoning": {
429                "type": "string",
430                "description": "One or two sentences saying what you checked and what it showed. Required when you reject or strike anything, and useful when you accept."
431            }
432        },
433        "required": ["accept", "stacked", "strike", "reasoning"]
434    })
435}
436
437/// One agent judging the comments other people left on a pull request.
438///
439/// The descriptions carry the asymmetry the whole command rests on, because
440/// they travel with the request rather than sitting a thousand tokens back in
441/// the prompt: getting a decline wrong costs a person one read of a thread that
442/// stays open for them, and getting an implement wrong costs them a commit they
443/// did not ask for on a branch they own.
444pub fn checkin() -> Value {
445    json!({
446        "type": "object",
447        "additionalProperties": false,
448        "properties": {
449            "verdicts": {
450                "type": "array",
451                "items": {
452                    "type": "object",
453                    "additionalProperties": false,
454                    "properties": {
455                        "ref_id": {
456                            "type": "string",
457                            "description": "The handle printed beside the comment, copied across exactly, so your answer can be matched back to it."
458                        },
459                        "ask": {
460                            "type": "string",
461                            "enum": ["implement", "defer", "decline", "answer", "nothing"],
462                            "description": "implement: the change is right and belongs on this branch. defer: the change is right and is really its own piece of work, so supply new_issue_title and new_issue_body. decline: the change should not be made. answer: a question rather than a request. nothing: nothing is being asked for."
463                        },
464                        "request": {
465                            "type": "string",
466                            "description": "What is being asked for, in one sentence, in your own words. This is how the harness checks the comment was understood before acting on it, so restate the request rather than the comment."
467                        },
468                        "reasoning": {
469                            "type": "string",
470                            "description": "One or two sentences. For decline this is the whole argument and it is posted in the thread, so give the reason and write it for the person who raised the point, not for this harness."
471                        },
472                        "unambiguous": {
473                            "type": "boolean",
474                            "description": "False if the comment could be read more than one way, or if you are guessing at what it wants. False costs a reply asking what was meant; a wrong true costs somebody a commit on their branch that they did not ask for."
475                        },
476                        "new_issue_title": {
477                            "type": ["string", "null"],
478                            "description": "Only when ask is defer, null otherwise. States the defect, not the fix."
479                        },
480                        "new_issue_body": {
481                            "type": ["string", "null"],
482                            "description": "Only when ask is defer, null otherwise. Written for somebody picking it up cold months later, not for whoever is reading this thread today."
483                        }
484                    },
485                    "required": ["ref_id", "ask", "request", "reasoning", "unambiguous", "new_issue_title", "new_issue_body"]
486                }
487            }
488        },
489        "required": ["verdicts"]
490    })
491}
492
493/// The second agent ruling on the first one's calls.
494pub fn checkin_check() -> Value {
495    json!({
496        "type": "object",
497        "additionalProperties": false,
498        "properties": {
499            "checks": {
500                "type": "array",
501                "items": {
502                    "type": "object",
503                    "additionalProperties": false,
504                    "properties": {
505                        "ref_id": {
506                            "type": "string",
507                            "description": "The handle printed beside the comment, copied across exactly."
508                        },
509                        "agrees": {
510                            "type": "boolean",
511                            "description": "True only if you went to the code and confirmed the call. Do not defer to the other agent and do not agree to be agreeable: a decision you cannot confirm is one that is about to put a commit on somebody's branch in their name."
512                        },
513                        "ask": {
514                            "type": "string",
515                            "enum": ["implement", "defer", "decline", "answer", "nothing"],
516                            "description": "What you would do instead. Read only when agrees is false."
517                        },
518                        "unambiguous": {
519                            "type": "boolean",
520                            "description": "False if the comment could be read more than one way, whatever the other agent said about it."
521                        },
522                        "reasoning": {
523                            "type": "string",
524                            "description": "One or two sentences saying what you checked and what it showed. Required when you disagree, and useful when you agree."
525                        }
526                    },
527                    "required": ["ref_id", "agrees", "ask", "unambiguous", "reasoning"]
528                }
529            }
530        },
531        "required": ["checks"]
532    })
533}
534
535/// What the fix pass reports back about each change it was asked to make.
536pub fn checkin_fix() -> Value {
537    json!({
538        "type": "object",
539        "additionalProperties": false,
540        "properties": {
541            "done": {
542                "type": "array",
543                "items": {
544                    "type": "object",
545                    "additionalProperties": false,
546                    "properties": {
547                        "ref_id": {
548                            "type": "string",
549                            "description": "The handle printed beside the comment, copied across exactly."
550                        },
551                        "changed": {
552                            "type": "boolean",
553                            "description": "False if the change turned out to be wrong once you were in the code. You are not obliged to make a change you now believe is a mistake, and saying so is a better answer than making it."
554                        },
555                        "summary": {
556                            "type": "string",
557                            "description": "One sentence naming what changed, or why it was left alone. This is posted in the thread the comment sits in, so write it for the person who asked rather than for this harness."
558                        }
559                    },
560                    "required": ["ref_id", "changed", "summary"]
561                }
562            }
563        },
564        "required": ["done"]
565    })
566}
567
568pub fn all() -> Vec<(&'static str, Value)> {
569    vec![
570        ("triage", triage()),
571        ("implementation", implementation()),
572        ("review", review()),
573        ("response", response()),
574        ("screen", screen()),
575        ("checkin", checkin()),
576        ("checkin_check", checkin_check()),
577        ("checkin_fix", checkin_fix()),
578        ("split_screen", split_screen()),
579        ("split_proposal", split_proposal()),
580        ("split_check", split_check()),
581    ]
582}
583
584#[cfg(test)]
585mod tests {
586    use super::*;
587
588    /// Yield every object schema, however deeply nested.
589    fn objects(node: &Value, path: String, out: &mut Vec<(String, Value)>) {
590        if let Some(map) = node.as_object() {
591            if map.get("type").and_then(Value::as_str) == Some("object")
592                && map.contains_key("properties")
593            {
594                out.push((path.clone(), node.clone()));
595                if let Some(props) = map.get("properties").and_then(Value::as_object) {
596                    for (key, child) in props {
597                        objects(child, format!("{path}.{key}"), out);
598                    }
599                }
600            }
601            if let Some(items) = map.get("items") {
602                objects(items, format!("{path}[]"), out);
603            }
604        }
605    }
606
607    fn walk(name: &str, schema: &Value) -> Vec<(String, Value)> {
608        let mut out = Vec::new();
609        objects(schema, name.to_string(), &mut out);
610        out
611    }
612
613    /// Strict structured output rejects any property that is not also in
614    /// `required`. The Python original violated this in the response schema
615    /// from the start and nothing caught it, because the response schema is
616    /// only reached when a review is handed back with blocking findings, and
617    /// almost every run approved in round one.
618    #[test]
619    fn every_property_is_required() {
620        for (name, schema) in all() {
621            for (path, node) in walk(name, &schema) {
622                let props: Vec<&String> = node["properties"].as_object().unwrap().keys().collect();
623                let required: Vec<String> = node["required"]
624                    .as_array()
625                    .unwrap_or(&vec![])
626                    .iter()
627                    .filter_map(|v| v.as_str().map(str::to_string))
628                    .collect();
629                for prop in &props {
630                    assert!(
631                        required.contains(prop),
632                        "{path}: {prop} is in properties but not in required. \
633                         Make optional fields nullable instead."
634                    );
635                }
636                assert_eq!(props.len(), required.len(), "{path}: required has extras");
637            }
638        }
639    }
640
641    /// The guard that was missing. A schema field can be added to the struct
642    /// and forgotten in the schema, and every test still passes: the tests
643    /// build the struct in Rust, so they never notice the model was never
644    /// asked. That shipped once, as four bug-report fields the agents were
645    /// never told about, which quietly did nothing.
646    #[test]
647    fn the_review_schema_asks_for_every_field_a_finding_holds() {
648        use crate::model::Finding;
649
650        let asked: Vec<String> = review()["properties"]["findings"]["items"]["properties"]
651            .as_object()
652            .expect("finding properties")
653            .keys()
654            .cloned()
655            .collect();
656
657        // Round-tripping a fully populated Finding names every field serde
658        // knows about, without repeating the list here to drift out of date.
659        let populated = Finding {
660            problem: Some("p".into()),
661            reproduction: Some("r".into()),
662            impact: Some("i".into()),
663            expected: Some("e".into()),
664            ..Finding::default()
665        };
666        let held: Vec<String> = serde_json::to_value(&populated)
667            .expect("serialisable")
668            .as_object()
669            .expect("object")
670            .keys()
671            .cloned()
672            .collect();
673
674        for field in &held {
675            assert!(
676                asked.contains(field),
677                "a Finding holds `{field}` and the schema never asks for it, so the model will \
678                 not fill it and the code reading it will always see nothing"
679            );
680        }
681    }
682
683    /// The same guard for the check-in exchange. A field added to the struct
684    /// and forgotten in the schema is one the model is never asked for, so the
685    /// code reading it always sees nothing: an `unambiguous` that is never
686    /// filled would default false and answer every comment in words.
687    #[test]
688    fn the_checkin_schema_asks_for_every_field_a_verdict_holds() {
689        use crate::model::{Ask, CommentVerdict};
690
691        let asked: Vec<String> = checkin()["properties"]["verdicts"]["items"]["properties"]
692            .as_object()
693            .expect("verdict properties")
694            .keys()
695            .cloned()
696            .collect();
697
698        let populated = CommentVerdict {
699            ref_id: "c1".into(),
700            ask: Ask::Decline,
701            request: "r".into(),
702            reasoning: "w".into(),
703            unambiguous: true,
704            new_issue_title: Some("t".into()),
705            new_issue_body: Some("b".into()),
706        };
707        let held: Vec<String> = serde_json::to_value(&populated)
708            .expect("serialisable")
709            .as_object()
710            .expect("object")
711            .keys()
712            .cloned()
713            .collect();
714
715        for field in &held {
716            assert!(
717                asked.contains(field),
718                "a CommentVerdict holds `{field}` and the schema never asks for it, so the model \
719                 will not fill it and the code reading it will always see nothing"
720            );
721        }
722    }
723
724    /// The same guard for the split exchange. A part field added to the struct
725    /// and forgotten here is one the model is never asked for, so a slice would
726    /// arrive with no files and carry nothing.
727    #[test]
728    fn the_split_schemas_ask_for_every_field_they_hold() {
729        use crate::model::{SplitCheck, SplitPart, SplitProposal};
730
731        let cases: Vec<(&str, Value, serde_json::Value)> = vec![
732            (
733                "SplitProposal",
734                split_proposal()["properties"].clone(),
735                serde_json::to_value(SplitProposal::default()).expect("serialisable"),
736            ),
737            (
738                "SplitPart",
739                split_proposal()["properties"]["parts"]["items"]["properties"].clone(),
740                serde_json::to_value(SplitPart::default()).expect("serialisable"),
741            ),
742            (
743                "SplitCheck",
744                split_check()["properties"].clone(),
745                serde_json::to_value(SplitCheck::default()).expect("serialisable"),
746            ),
747        ];
748        for (what, asked, held) in cases {
749            let asked: Vec<String> = asked
750                .as_object()
751                .expect("properties")
752                .keys()
753                .cloned()
754                .collect();
755            for field in held.as_object().expect("object").keys() {
756                assert!(
757                    asked.contains(field),
758                    "a {what} holds `{field}` and the schema never asks for it, so the code \
759                     reading it will always see nothing"
760                );
761            }
762        }
763    }
764
765    /// A slice with no files carries nothing, so the one field that decides
766    /// what a part is has to be spelled as nullable rather than left out.
767    #[test]
768    fn a_split_part_may_carry_no_files_without_omitting_the_field() {
769        let types = split_proposal()["properties"]["parts"]["items"]["properties"]["files"]["type"]
770            .to_string();
771        assert!(types.contains("null"), "files must accept null: {types}");
772    }
773
774    /// Every value the schema offers has to be one the parser accepts, or an
775    /// answer that matched the schema exactly is thrown away.
776    #[test]
777    fn the_checkin_ask_enum_matches_the_parser() {
778        use crate::model::Ask;
779
780        for schema in [
781            checkin()["properties"]["verdicts"]["items"]["properties"]["ask"].clone(),
782            checkin_check()["properties"]["checks"]["items"]["properties"]["ask"].clone(),
783        ] {
784            for value in schema["enum"].as_array().expect("an enum") {
785                let text = value.as_str().expect("a string");
786                assert!(
787                    Ask::parse_lenient(text).is_some(),
788                    "the schema offers `{text}` and the parser refuses it"
789                );
790            }
791        }
792    }
793
794    /// The same guard for the implementation exchange, where a forgotten field
795    /// means a pull request body with an empty section in it and nobody the
796    /// wiser.
797    #[test]
798    fn the_implementation_schema_asks_for_every_field_it_holds() {
799        use crate::model::Implementation;
800
801        let asked: Vec<String> = implementation()["properties"]
802            .as_object()
803            .expect("properties")
804            .keys()
805            .cloned()
806            .collect();
807
808        let populated = Implementation {
809            notes: Some("n".into()),
810            ..Implementation::default()
811        };
812        let held: Vec<String> = serde_json::to_value(&populated)
813            .expect("serialisable")
814            .as_object()
815            .expect("object")
816            .keys()
817            .cloned()
818            .collect();
819
820        for field in &held {
821            assert!(
822                asked.contains(field),
823                "an Implementation holds `{field}` and the schema never asks for it, so the \
824                 pull request body will always be missing that part"
825            );
826        }
827    }
828
829    /// Same guard for the other direction of the same exchange.
830    #[test]
831    fn the_response_schema_asks_for_every_field_a_disposition_holds() {
832        use crate::model::{Action, Disposition};
833
834        let asked: Vec<String> = response()["properties"]["dispositions"]["items"]["properties"]
835            .as_object()
836            .expect("disposition properties")
837            .keys()
838            .cloned()
839            .collect();
840
841        let populated = Disposition {
842            title: "t".into(),
843            file: "f".into(),
844            action: Action::Fixed,
845            reasoning: "r".into(),
846            new_issue_title: Some("t".into()),
847            new_issue_body: Some("b".into()),
848        };
849        let held: Vec<String> = serde_json::to_value(&populated)
850            .expect("serialisable")
851            .as_object()
852            .expect("object")
853            .keys()
854            .cloned()
855            .collect();
856
857        for field in &held {
858            assert!(
859                asked.contains(field),
860                "a Disposition holds `{field}`, unasked for"
861            );
862        }
863    }
864
865    #[test]
866    fn objects_forbid_additional_properties() {
867        for (name, schema) in all() {
868            for (path, node) in walk(name, &schema) {
869                assert_eq!(
870                    Some(false),
871                    node["additionalProperties"].as_bool(),
872                    "{path} allows additional properties"
873                );
874            }
875        }
876    }
877
878    #[test]
879    fn optional_fields_are_spelled_as_nullable() {
880        let item = &response()["properties"]["dispositions"]["items"];
881        for field in ["new_issue_title", "new_issue_body"] {
882            let types = item["properties"][field]["type"].to_string();
883            assert!(types.contains("null"), "{field} must accept null: {types}");
884        }
885    }
886
887    /// The re-litigation guard hashes a refutation by title *and* file. If the
888    /// disposition cannot carry the file, the key it records can never match
889    /// the key the next round's finding hashes to, and the guard is dead code.
890    #[test]
891    fn a_disposition_carries_the_file_so_the_ledger_key_can_match() {
892        let props = response()["properties"]["dispositions"]["items"]["properties"].clone();
893        assert!(
894            props.get("file").is_some(),
895            "dispositions must carry a file"
896        );
897    }
898
899    #[test]
900    fn severity_and_verdict_enums_match_the_parser() {
901        use crate::model::{Severity, Verdict};
902        let sev =
903            review()["properties"]["findings"]["items"]["properties"]["severity"]["enum"].clone();
904        for value in sev.as_array().unwrap() {
905            assert!(
906                Severity::parse_lenient(value.as_str().unwrap()).is_some(),
907                "schema offers {value} but the parser rejects it"
908            );
909        }
910        let verdicts = review()["properties"]["verdict"]["enum"].clone();
911        for value in verdicts.as_array().unwrap() {
912            assert!(Verdict::parse_lenient(value.as_str().unwrap()).is_some());
913        }
914    }
915
916    #[test]
917    fn triage_enums_match_the_parser() {
918        use crate::model::{Complexity, Risk};
919        let item = &triage()["properties"]["issues"]["items"]["properties"];
920        for value in item["complexity"]["enum"].as_array().unwrap() {
921            assert!(Complexity::parse_lenient(value.as_str().unwrap()).is_some());
922        }
923        for value in item["risk"]["enum"].as_array().unwrap() {
924            assert!(Risk::parse_lenient(value.as_str().unwrap()).is_some());
925        }
926    }
927
928    #[test]
929    fn response_action_enum_matches_the_parser() {
930        use crate::model::Action;
931        let actions = response()["properties"]["dispositions"]["items"]["properties"]["action"]
932            ["enum"]
933            .clone();
934        for value in actions.as_array().unwrap() {
935            assert!(Action::parse_lenient(value.as_str().unwrap()).is_some());
936        }
937    }
938}