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": {
40                            "type": "string",
41                            "enum": ["s", "m", "l"],
42                            "description": "How much work the change is. s: one file, or a handful of lines across two, covered by an existing test or one obvious one. m: several files in one area, or a new function others call, or one that needs its own tests written. l: a new module, a change to an interface other code depends on, a format that has to migrate, or anything you cannot verify by running something that already exists. This decides the order the run works in, cheapest first, and the larger of the two reviewers' answers is used."
43                        },
44                        "depends_on": {
45                            "type": "array",
46                            "items": {"type": "integer"},
47                            "description": "Issue numbers from this same list that should land first. Empty if none."
48                        },
49                        "risk": {
50                            "type": "string",
51                            "enum": ["low", "med", "high"],
52                            "description": "The blast radius if the change is wrong, and how easily it is undone. low: contained in one place and a revert puts everything back. med: other code calls into it, or it changes behaviour somebody may rely on, but the failure is visible. high: it touches data that persists, a security or permission boundary, or a path whose failure is silent. The larger of the two reviewers' answers is used."
53                        }
54                    },
55                    "required": ["issue", "worth_doing", "tracker", "reason", "complexity", "depends_on", "risk"]
56                }
57            }
58        },
59        "required": ["issues"]
60    })
61}
62
63pub fn review() -> Value {
64    json!({
65        "type": "object",
66        "additionalProperties": false,
67        "properties": {
68            "verdict": {
69                "type": "string",
70                "enum": ["approve", "changes_requested"],
71                "description": "Your overall call. The findings and next_action are what act, so this has to agree with them: approve means you raised nothing blocking. A disagreement between the two is reported and the findings decide."
72            },
73            "next_action": {"type": "string", "enum": ["merge", "fix_myself", "hand_back"]},
74            "summary": {
75                "type": "string",
76                "description": "One sentence, at most 200 characters. No preamble, no restating the diff."
77            },
78            "findings": {
79                "type": "array",
80                "items": {
81                    "type": "object",
82                    "additionalProperties": false,
83                    "properties": {
84                        "severity": {
85                            "type": "string",
86                            "enum": ["blocking", "non-blocking", "nit"],
87                            "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."
88                        },
89                        "title": {
90                            "type": "string",
91                            "description": "Under 80 characters. State the defect, not the fix."
92                        },
93                        "detail": {
94                            "type": "string",
95                            "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."
96                        },
97                        "file": {
98                            "type": "string",
99                            "description": "Path, with a line number if you have one. Empty string if the finding is general."
100                        },
101                        "problem": {
102                            "type": ["string", "null"],
103                            "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."
104                        },
105                        "reproduction": {
106                            "type": ["string", "null"],
107                            "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."
108                        },
109                        "impact": {
110                            "type": ["string", "null"],
111                            "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."
112                        },
113                        "expected": {
114                            "type": ["string", "null"],
115                            "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."
116                        },
117                        "in_scope": {
118                            "type": "boolean",
119                            "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."
120                        }
121                    },
122                    "required": [
123                        "severity",
124                        "title",
125                        "detail",
126                        "file",
127                        "in_scope",
128                        "problem",
129                        "reproduction",
130                        "impact",
131                        "expected"
132                    ]
133                }
134            }
135        },
136        "required": ["verdict", "next_action", "summary", "findings"]
137    })
138}
139
140/// What the implementor reports back, and the pull request body it becomes.
141///
142/// The body used to be one scraped `SUMMARY:` line under a `Closes #N`, which
143/// told a reviewer opening the diff cold nothing: not what was wrong, not what
144/// the change does about it, not how to check it. Asking for those separately
145/// is what puts them there, and composing the body from the fields rather than
146/// from the model's prose is what keeps it short enough to read.
147pub fn implementation() -> Value {
148    json!({
149        "type": "object",
150        "additionalProperties": false,
151        "properties": {
152            "not_worth_doing": {
153                "type": "boolean",
154                "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 changes when this is true."
155            },
156            "reason": {
157                "type": "string",
158                "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."
159            },
160            "summary": {
161                "type": "string",
162                "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."
163            },
164            "problem": {
165                "type": "string",
166                "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."
167            },
168            "changes": {
169                "type": "array",
170                "items": {"type": "string"},
171                "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."
172            },
173            "testing": {
174                "type": "array",
175                "items": {"type": "string"},
176                "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."
177            },
178            "notes": {
179                "type": ["string", "null"],
180                "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."
181            }
182        },
183        "required": ["not_worth_doing", "reason", "summary", "problem", "changes", "testing", "notes"]
184    })
185}
186
187pub fn response() -> Value {
188    json!({
189        "type": "object",
190        "additionalProperties": false,
191        "properties": {
192            "summary": {
193                "type": "string",
194                "description": "One sentence, at most 200 characters."
195            },
196            "dispositions": {
197                "type": "array",
198                "items": {
199                    "type": "object",
200                    "additionalProperties": false,
201                    "properties": {
202                        "title": {
203                            "type": "string",
204                            "description": "Copy the reviewer's finding title exactly, so the two can be matched up."
205                        },
206                        "file": {
207                            "type": "string",
208                            "description": "Copy the reviewer's file for this finding exactly. Empty string if it had none."
209                        },
210                        "action": {
211                            "type": "string",
212                            "enum": ["fixed", "refuted", "filed_issue"],
213                            "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."
214                        },
215                        "reasoning": {
216                            "type": "string",
217                            "description": "One or two sentences. For a refutation this is the whole argument, so make it the reason and not an apology."
218                        },
219                        "new_issue_title": {
220                            "type": ["string", "null"],
221                            "description": "Only for filed_issue, null otherwise."
222                        },
223                        "new_issue_body": {
224                            "type": ["string", "null"],
225                            "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."
226                        }
227                    },
228                    "required": ["title", "file", "action", "reasoning", "new_issue_title", "new_issue_body"]
229                }
230            }
231        },
232        "required": ["summary", "dispositions"]
233    })
234}
235
236/// One reviewer judging the other reviewer's findings.
237///
238/// Used only in review only mode, where nobody is going to fix anything and the
239/// product is the finding list itself. Asking each model to read the code and
240/// rule on the other's claims is what separates a defect worth a maintainer's
241/// attention from one model's pattern match.
242pub fn adjudication() -> Value {
243    json!({
244        "type": "object",
245        "additionalProperties": false,
246        "properties": {
247            "verdicts": {
248                "type": "array",
249                "items": {
250                    "type": "object",
251                    "additionalProperties": false,
252                    "properties": {
253                        "title": {
254                            "type": "string",
255                            "description": "Copy the finding's title exactly, so it can be matched up."
256                        },
257                        "file": {
258                            "type": "string",
259                            "description": "Copy the finding's file exactly. Empty string if it had none."
260                        },
261                        "agrees": {
262                            "type": "boolean",
263                            "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."
264                        },
265                        "severity": {
266                            "type": "string",
267                            "enum": ["blocking", "non-blocking", "nit"],
268                            "description": "Your own view of how badly it matters, even where you agree the defect is real."
269                        },
270                        "reasoning": {
271                            "type": "string",
272                            "description": "One or two sentences. If you disagree, this is the whole argument, so give the reason rather than an opinion."
273                        }
274                    },
275                    "required": ["title", "file", "agrees", "severity", "reasoning"]
276                }
277            }
278        },
279        "required": ["verdicts"]
280    })
281}
282
283/// One agent ruling on recorded follow-ups, before any becomes an issue.
284///
285/// Deliberately not the triage schema. Triage asks whether an issue is worth a
286/// pull request; this asks whether a note written weeks ago is still true of the
287/// code, which is a different question with a different expensive mistake:
288/// dropping something real, rather than scheduling something small.
289pub fn screen() -> Value {
290    json!({
291        "type": "object",
292        "additionalProperties": false,
293        "properties": {
294            "entries": {
295                "type": "array",
296                "items": {
297                    "type": "object",
298                    "additionalProperties": false,
299                    "properties": {
300                        "entry": {
301                            "type": "integer",
302                            "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."
303                        },
304                        "verdict": {
305                            "type": "string",
306                            "enum": ["still_relevant", "already_fixed", "not_worth_it", "duplicate"],
307                            "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."
308                        },
309                        "title": {
310                            "type": "string",
311                            "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."
312                        },
313                        "reason": {
314                            "type": "string",
315                            "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."
316                        },
317                        "duplicate_of_issue": {
318                            "type": ["integer", "null"],
319                            "description": "Only when the verdict is duplicate and an open issue already covers it. The issue number, null otherwise."
320                        },
321                        "duplicate_of_entry": {
322                            "type": ["integer", "null"],
323                            "description": "Only when the verdict is duplicate and another entry in this same list covers it. That entry's number from the list above, null otherwise. Kept apart from duplicate_of_issue because an entry is not an issue: it may itself be dropped, and then this one is kept rather than lost."
324                        }
325                    },
326                    "required": ["entry", "verdict", "title", "reason", "duplicate_of_issue", "duplicate_of_entry"]
327                }
328            }
329        },
330        "required": ["entries"]
331    })
332}
333
334/// One agent ruling on a whole queue at once: is this worth splitting.
335///
336/// One call rather than N, for the reason `screen` is one call: a repository
337/// aware pass is the dominant cost, and "is this too big to work in one piece"
338/// is partly a judgement across the queue rather than about each item alone.
339pub fn split_screen() -> Value {
340    json!({
341        "type": "object",
342        "additionalProperties": false,
343        "properties": {
344            "items": {
345                "type": "array",
346                "items": {
347                    "type": "object",
348                    "additionalProperties": false,
349                    "properties": {
350                        "item": {
351                            "type": "integer",
352                            "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."
353                        },
354                        "split": {
355                            "type": "boolean",
356                            "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."
357                        },
358                        "reason": {
359                            "type": "string",
360                            "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."
361                        }
362                    },
363                    "required": ["item", "split", "reason"]
364                }
365            }
366        },
367        "required": ["items"]
368    })
369}
370
371/// One agent decomposing one issue or one pull request.
372///
373/// The descriptions carry the two rules the command rests on: a part that
374/// cannot stand on its own is not a part, and the whole value of splitting is
375/// that each piece can be reviewed and merged by itself.
376pub fn split_proposal() -> Value {
377    json!({
378        "type": "object",
379        "additionalProperties": false,
380        "properties": {
381            "should_split": {
382                "type": "boolean",
383                "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."
384            },
385            "reason": {
386                "type": "string",
387                "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."
388            },
389            "stacked": {
390                "type": "boolean",
391                "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."
392            },
393            "parts": {
394                "type": "array",
395                "items": {
396                    "type": "object",
397                    "additionalProperties": false,
398                    "properties": {
399                        "title": {
400                            "type": "string",
401                            "description": "Under 80 characters. States the piece of work, not the fact that it was split out."
402                        },
403                        "body": {
404                            "type": "string",
405                            "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."
406                        },
407                        "files": {
408                            "type": ["array", "null"],
409                            "items": {"type": "string"},
410                            "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."
411                        }
412                    },
413                    "required": ["title", "body", "files"]
414                }
415            }
416        },
417        "required": ["should_split", "reason", "stacked", "parts"]
418    })
419}
420
421/// The second agent ruling on the first one's decomposition.
422///
423/// Not a second proposal. Two decompositions of one thing cannot be reconciled
424/// mechanically, so this agent rules on the one in front of it: accept, reject,
425/// or accept with named parts struck.
426pub fn split_check() -> Value {
427    json!({
428        "type": "object",
429        "additionalProperties": false,
430        "properties": {
431            "accept": {
432                "type": "boolean",
433                "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."
434            },
435            "stacked": {
436                "type": "boolean",
437                "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."
438            },
439            "strike": {
440                "type": "array",
441                "items": {"type": "integer"},
442                "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."
443            },
444            "reasoning": {
445                "type": "string",
446                "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."
447            }
448        },
449        "required": ["accept", "stacked", "strike", "reasoning"]
450    })
451}
452
453/// One agent judging the comments other people left on a pull request.
454///
455/// The descriptions carry the asymmetry the whole command rests on, because
456/// they travel with the request rather than sitting a thousand tokens back in
457/// the prompt: getting a decline wrong costs a person one read of a thread that
458/// stays open for them, and getting an implement wrong costs them a commit they
459/// did not ask for on a branch they own.
460pub fn checkin() -> Value {
461    json!({
462        "type": "object",
463        "additionalProperties": false,
464        "properties": {
465            "verdicts": {
466                "type": "array",
467                "items": {
468                    "type": "object",
469                    "additionalProperties": false,
470                    "properties": {
471                        "ref_id": {
472                            "type": "string",
473                            "description": "The handle printed beside the comment, copied across exactly, so your answer can be matched back to it."
474                        },
475                        "ask": {
476                            "type": "string",
477                            "enum": ["implement", "defer", "decline", "answer", "nothing"],
478                            "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."
479                        },
480                        "request": {
481                            "type": "string",
482                            "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."
483                        },
484                        "reasoning": {
485                            "type": "string",
486                            "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."
487                        },
488                        "unambiguous": {
489                            "type": "boolean",
490                            "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."
491                        },
492                        "new_issue_title": {
493                            "type": ["string", "null"],
494                            "description": "Only when ask is defer, null otherwise. States the defect, not the fix."
495                        },
496                        "new_issue_body": {
497                            "type": ["string", "null"],
498                            "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."
499                        }
500                    },
501                    "required": ["ref_id", "ask", "request", "reasoning", "unambiguous", "new_issue_title", "new_issue_body"]
502                }
503            }
504        },
505        "required": ["verdicts"]
506    })
507}
508
509/// The second agent ruling on the first one's calls.
510pub fn checkin_check() -> Value {
511    json!({
512        "type": "object",
513        "additionalProperties": false,
514        "properties": {
515            "checks": {
516                "type": "array",
517                "items": {
518                    "type": "object",
519                    "additionalProperties": false,
520                    "properties": {
521                        "ref_id": {
522                            "type": "string",
523                            "description": "The handle printed beside the comment, copied across exactly."
524                        },
525                        "agrees": {
526                            "type": "boolean",
527                            "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."
528                        },
529                        "ask": {
530                            "type": "string",
531                            "enum": ["implement", "defer", "decline", "answer", "nothing"],
532                            "description": "What you would do instead. Read only when agrees is false."
533                        },
534                        "unambiguous": {
535                            "type": "boolean",
536                            "description": "False if the comment could be read more than one way, whatever the other agent said about it."
537                        },
538                        "reasoning": {
539                            "type": "string",
540                            "description": "One or two sentences saying what you checked and what it showed. Required when you disagree, and useful when you agree."
541                        }
542                    },
543                    "required": ["ref_id", "agrees", "ask", "unambiguous", "reasoning"]
544                }
545            }
546        },
547        "required": ["checks"]
548    })
549}
550
551/// What the fix pass reports back about each change it was asked to make.
552pub fn checkin_fix() -> Value {
553    json!({
554        "type": "object",
555        "additionalProperties": false,
556        "properties": {
557            "done": {
558                "type": "array",
559                "items": {
560                    "type": "object",
561                    "additionalProperties": false,
562                    "properties": {
563                        "ref_id": {
564                            "type": "string",
565                            "description": "The handle printed beside the comment, copied across exactly."
566                        },
567                        "changed": {
568                            "type": "boolean",
569                            "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."
570                        },
571                        "summary": {
572                            "type": "string",
573                            "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."
574                        },
575                        "files": {
576                            "type": "array",
577                            "items": {"type": "string"},
578                            "description": "Repository relative paths this comment's change touched, empty when nothing was changed. Checked against the diff: a comment whose files are not in it is answered in words rather than reported as fixed."
579                        }
580                    },
581                    "required": ["ref_id", "changed", "summary", "files"]
582                }
583            }
584        },
585        "required": ["done"]
586    })
587}
588
589/// A reviewer's report on fixing its own findings.
590///
591/// Same shape as a response, minus the parts that only make sense from the
592/// author's side: a reviewer fixing its own point cannot refute it, and filing
593/// it as somebody else's issue is a decision for the round rather than for this
594/// call.
595pub fn own_fix() -> Value {
596    json!({
597        "type": "object",
598        "additionalProperties": false,
599        "properties": {
600            "summary": {
601                "type": "string",
602                "description": "One sentence naming what changed, at most 200 characters. This becomes the commit subject, so write it as one."
603            },
604            "fixes": {
605                "type": "array",
606                "items": {
607                    "type": "object",
608                    "additionalProperties": false,
609                    "properties": {
610                        "title": {
611                            "type": "string",
612                            "description": "Copy your own finding title exactly, so the two can be matched up."
613                        },
614                        "file": {
615                            "type": "string",
616                            "description": "Copy the file from that finding exactly. Empty string if it had none."
617                        },
618                        "fixed": {
619                            "type": "boolean",
620                            "description": "True only if this point is answered by a change in the working tree. False if you left it, whatever the reason."
621                        },
622                        "reason": {
623                            "type": "string",
624                            "description": "For a fix, what you changed and how it answers the point. For one you left, why, in a sentence the author will read: it stays open and goes to them."
625                        }
626                    },
627                    "required": ["title", "file", "fixed", "reason"]
628                }
629            }
630        },
631        "required": ["summary", "fixes"]
632    })
633}
634
635pub fn all() -> Vec<(&'static str, Value)> {
636    vec![
637        ("triage", triage()),
638        ("implementation", implementation()),
639        ("review", review()),
640        ("response", response()),
641        ("own_fix", own_fix()),
642        ("screen", screen()),
643        ("checkin", checkin()),
644        ("checkin_check", checkin_check()),
645        ("checkin_fix", checkin_fix()),
646        ("split_screen", split_screen()),
647        ("split_proposal", split_proposal()),
648        ("split_check", split_check()),
649    ]
650}
651
652#[cfg(test)]
653mod tests {
654    use super::*;
655
656    /// Yield every object schema, however deeply nested.
657    fn objects(node: &Value, path: String, out: &mut Vec<(String, Value)>) {
658        if let Some(map) = node.as_object() {
659            if map.get("type").and_then(Value::as_str) == Some("object")
660                && map.contains_key("properties")
661            {
662                out.push((path.clone(), node.clone()));
663                if let Some(props) = map.get("properties").and_then(Value::as_object) {
664                    for (key, child) in props {
665                        objects(child, format!("{path}.{key}"), out);
666                    }
667                }
668            }
669            if let Some(items) = map.get("items") {
670                objects(items, format!("{path}[]"), out);
671            }
672        }
673    }
674
675    fn walk(name: &str, schema: &Value) -> Vec<(String, Value)> {
676        let mut out = Vec::new();
677        objects(schema, name.to_string(), &mut out);
678        out
679    }
680
681    /// Strict structured output rejects any property that is not also in
682    /// `required`. The Python original violated this in the response schema
683    /// from the start and nothing caught it, because the response schema is
684    /// only reached when a review is handed back with blocking findings, and
685    /// almost every run approved in round one.
686    #[test]
687    fn every_property_is_required() {
688        for (name, schema) in all() {
689            for (path, node) in walk(name, &schema) {
690                let props: Vec<&String> = node["properties"].as_object().unwrap().keys().collect();
691                let required: Vec<String> = node["required"]
692                    .as_array()
693                    .unwrap_or(&vec![])
694                    .iter()
695                    .filter_map(|v| v.as_str().map(str::to_string))
696                    .collect();
697                for prop in &props {
698                    assert!(
699                        required.contains(prop),
700                        "{path}: {prop} is in properties but not in required. \
701                         Make optional fields nullable instead."
702                    );
703                }
704                assert_eq!(props.len(), required.len(), "{path}: required has extras");
705            }
706        }
707    }
708
709    /// The guard that was missing. A schema field can be added to the struct
710    /// and forgotten in the schema, and every test still passes: the tests
711    /// build the struct in Rust, so they never notice the model was never
712    /// asked. That shipped once, as four bug-report fields the agents were
713    /// never told about, which quietly did nothing.
714    #[test]
715    fn the_review_schema_asks_for_every_field_a_finding_holds() {
716        use crate::model::Finding;
717
718        let asked: Vec<String> = review()["properties"]["findings"]["items"]["properties"]
719            .as_object()
720            .expect("finding properties")
721            .keys()
722            .cloned()
723            .collect();
724
725        // Round-tripping a fully populated Finding names every field serde
726        // knows about, without repeating the list here to drift out of date.
727        let populated = Finding {
728            problem: Some("p".into()),
729            reproduction: Some("r".into()),
730            impact: Some("i".into()),
731            expected: Some("e".into()),
732            ..Finding::default()
733        };
734        let held: Vec<String> = serde_json::to_value(&populated)
735            .expect("serialisable")
736            .as_object()
737            .expect("object")
738            .keys()
739            .cloned()
740            .collect();
741
742        for field in &held {
743            assert!(
744                asked.contains(field),
745                "a Finding holds `{field}` and the schema never asks for it, so the model will \
746                 not fill it and the code reading it will always see nothing"
747            );
748        }
749    }
750
751    /// The same guard for the check-in exchange. A field added to the struct
752    /// and forgotten in the schema is one the model is never asked for, so the
753    /// code reading it always sees nothing: an `unambiguous` that is never
754    /// filled would default false and answer every comment in words.
755    #[test]
756    fn the_checkin_schema_asks_for_every_field_a_verdict_holds() {
757        use crate::model::{Ask, CommentVerdict};
758
759        let asked: Vec<String> = checkin()["properties"]["verdicts"]["items"]["properties"]
760            .as_object()
761            .expect("verdict properties")
762            .keys()
763            .cloned()
764            .collect();
765
766        let populated = CommentVerdict {
767            ref_id: "c1".into(),
768            ask: Ask::Decline,
769            request: "r".into(),
770            reasoning: "w".into(),
771            unambiguous: true,
772            new_issue_title: Some("t".into()),
773            new_issue_body: Some("b".into()),
774        };
775        let held: Vec<String> = serde_json::to_value(&populated)
776            .expect("serialisable")
777            .as_object()
778            .expect("object")
779            .keys()
780            .cloned()
781            .collect();
782
783        for field in &held {
784            assert!(
785                asked.contains(field),
786                "a CommentVerdict holds `{field}` and the schema never asks for it, so the model \
787                 will not fill it and the code reading it will always see nothing"
788            );
789        }
790    }
791
792    /// The same guard for the split exchange. A part field added to the struct
793    /// and forgotten here is one the model is never asked for, so a slice would
794    /// arrive with no files and carry nothing.
795    #[test]
796    fn the_split_schemas_ask_for_every_field_they_hold() {
797        use crate::model::{SplitCheck, SplitPart, SplitProposal};
798
799        let cases: Vec<(&str, Value, serde_json::Value)> = vec![
800            (
801                "SplitProposal",
802                split_proposal()["properties"].clone(),
803                serde_json::to_value(SplitProposal::default()).expect("serialisable"),
804            ),
805            (
806                "SplitPart",
807                split_proposal()["properties"]["parts"]["items"]["properties"].clone(),
808                serde_json::to_value(SplitPart::default()).expect("serialisable"),
809            ),
810            (
811                "SplitCheck",
812                split_check()["properties"].clone(),
813                serde_json::to_value(SplitCheck::default()).expect("serialisable"),
814            ),
815        ];
816        for (what, asked, held) in cases {
817            let asked: Vec<String> = asked
818                .as_object()
819                .expect("properties")
820                .keys()
821                .cloned()
822                .collect();
823            for field in held.as_object().expect("object").keys() {
824                assert!(
825                    asked.contains(field),
826                    "a {what} holds `{field}` and the schema never asks for it, so the code \
827                     reading it will always see nothing"
828                );
829            }
830        }
831    }
832
833    /// A slice with no files carries nothing, so the one field that decides
834    /// what a part is has to be spelled as nullable rather than left out.
835    #[test]
836    fn a_split_part_may_carry_no_files_without_omitting_the_field() {
837        let types = split_proposal()["properties"]["parts"]["items"]["properties"]["files"]["type"]
838            .to_string();
839        assert!(types.contains("null"), "files must accept null: {types}");
840    }
841
842    /// Every value the schema offers has to be one the parser accepts, or an
843    /// answer that matched the schema exactly is thrown away.
844    #[test]
845    fn the_checkin_ask_enum_matches_the_parser() {
846        use crate::model::Ask;
847
848        for schema in [
849            checkin()["properties"]["verdicts"]["items"]["properties"]["ask"].clone(),
850            checkin_check()["properties"]["checks"]["items"]["properties"]["ask"].clone(),
851        ] {
852            for value in schema["enum"].as_array().expect("an enum") {
853                let text = value.as_str().expect("a string");
854                assert!(
855                    Ask::parse_lenient(text).is_some(),
856                    "the schema offers `{text}` and the parser refuses it"
857                );
858            }
859        }
860    }
861
862    /// The same guard for the implementation exchange, where a forgotten field
863    /// means a pull request body with an empty section in it and nobody the
864    /// wiser.
865    #[test]
866    fn the_implementation_schema_asks_for_every_field_it_holds() {
867        use crate::model::Implementation;
868
869        let asked: Vec<String> = implementation()["properties"]
870            .as_object()
871            .expect("properties")
872            .keys()
873            .cloned()
874            .collect();
875
876        let populated = Implementation {
877            notes: Some("n".into()),
878            ..Implementation::default()
879        };
880        let held: Vec<String> = serde_json::to_value(&populated)
881            .expect("serialisable")
882            .as_object()
883            .expect("object")
884            .keys()
885            .cloned()
886            .collect();
887
888        for field in &held {
889            assert!(
890                asked.contains(field),
891                "an Implementation holds `{field}` and the schema never asks for it, so the \
892                 pull request body will always be missing that part"
893            );
894        }
895    }
896
897    /// Same guard for the other direction of the same exchange.
898    #[test]
899    fn the_response_schema_asks_for_every_field_a_disposition_holds() {
900        use crate::model::{Action, Disposition};
901
902        let asked: Vec<String> = response()["properties"]["dispositions"]["items"]["properties"]
903            .as_object()
904            .expect("disposition properties")
905            .keys()
906            .cloned()
907            .collect();
908
909        let populated = Disposition {
910            title: "t".into(),
911            file: "f".into(),
912            action: Action::Fixed,
913            reasoning: "r".into(),
914            new_issue_title: Some("t".into()),
915            new_issue_body: Some("b".into()),
916        };
917        let held: Vec<String> = serde_json::to_value(&populated)
918            .expect("serialisable")
919            .as_object()
920            .expect("object")
921            .keys()
922            .cloned()
923            .collect();
924
925        for field in &held {
926            assert!(
927                asked.contains(field),
928                "a Disposition holds `{field}`, unasked for"
929            );
930        }
931    }
932
933    #[test]
934    fn objects_forbid_additional_properties() {
935        for (name, schema) in all() {
936            for (path, node) in walk(name, &schema) {
937                assert_eq!(
938                    Some(false),
939                    node["additionalProperties"].as_bool(),
940                    "{path} allows additional properties"
941                );
942            }
943        }
944    }
945
946    #[test]
947    fn optional_fields_are_spelled_as_nullable() {
948        let item = &response()["properties"]["dispositions"]["items"];
949        for field in ["new_issue_title", "new_issue_body"] {
950            let types = item["properties"][field]["type"].to_string();
951            assert!(types.contains("null"), "{field} must accept null: {types}");
952        }
953    }
954
955    /// The re-litigation guard hashes a refutation by title *and* file. If the
956    /// disposition cannot carry the file, the key it records can never match
957    /// the key the next round's finding hashes to, and the guard is dead code.
958    #[test]
959    fn a_disposition_carries_the_file_so_the_ledger_key_can_match() {
960        let props = response()["properties"]["dispositions"]["items"]["properties"].clone();
961        assert!(
962            props.get("file").is_some(),
963            "dispositions must carry a file"
964        );
965    }
966
967    #[test]
968    fn severity_and_verdict_enums_match_the_parser() {
969        use crate::model::{Severity, Verdict};
970        let sev =
971            review()["properties"]["findings"]["items"]["properties"]["severity"]["enum"].clone();
972        for value in sev.as_array().unwrap() {
973            assert!(
974                Severity::parse_lenient(value.as_str().unwrap()).is_some(),
975                "schema offers {value} but the parser rejects it"
976            );
977        }
978        let verdicts = review()["properties"]["verdict"]["enum"].clone();
979        for value in verdicts.as_array().unwrap() {
980            assert!(Verdict::parse_lenient(value.as_str().unwrap()).is_some());
981        }
982    }
983
984    #[test]
985    fn triage_enums_match_the_parser() {
986        use crate::model::{Complexity, Risk};
987        let item = &triage()["properties"]["issues"]["items"]["properties"];
988        for value in item["complexity"]["enum"].as_array().unwrap() {
989            assert!(Complexity::parse_lenient(value.as_str().unwrap()).is_some());
990        }
991        for value in item["risk"]["enum"].as_array().unwrap() {
992            assert!(Risk::parse_lenient(value.as_str().unwrap()).is_some());
993        }
994    }
995
996    #[test]
997    fn response_action_enum_matches_the_parser() {
998        use crate::model::Action;
999        let actions = response()["properties"]["dispositions"]["items"]["properties"]["action"]
1000            ["enum"]
1001            .clone();
1002        for value in actions.as_array().unwrap() {
1003            assert!(Action::parse_lenient(value.as_str().unwrap()).is_some());
1004        }
1005    }
1006}