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
15/// A single actionable issue, drafted against the repository.
16pub fn code_issue() -> Value {
17    json!({
18        "type": "object",
19        "additionalProperties": false,
20        "properties": {
21            "title": {"type": "string", "description": "A concise, specific issue title."},
22            "body": {"type": "string", "description": "A detailed Markdown issue with context, requested behavior, scope, acceptance criteria, and a test plan. Distinguish verified facts from assumptions."}
23        },
24        "required": ["title", "body"]
25    })
26}
27
28pub fn triage() -> Value {
29    json!({
30        "type": "object",
31        "additionalProperties": false,
32        "properties": {
33            "issues": {
34                "type": "array",
35                "items": {
36                    "type": "object",
37                    "additionalProperties": false,
38                    "properties": {
39                        "issue": {"type": "integer", "description": "The issue number."},
40                        "worth_doing": {
41                            "type": "boolean",
42                            "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."
43                        },
44                        "tracker": {
45                            "type": "boolean",
46                            "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."
47                        },
48                        "reason": {
49                            "type": "string",
50                            "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."
51                        },
52                        "complexity": {
53                            "type": "string",
54                            "enum": ["s", "m", "l"],
55                            "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."
56                        },
57                        "depends_on": {
58                            "type": "array",
59                            "items": {"type": "integer"},
60                            "description": "Issue numbers from this same list that should land first. Empty if none."
61                        },
62                        "risk": {
63                            "type": "string",
64                            "enum": ["low", "med", "high"],
65                            "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."
66                        }
67                    },
68                    "required": ["issue", "worth_doing", "tracker", "reason", "complexity", "depends_on", "risk"]
69                }
70            }
71        },
72        "required": ["issues"]
73    })
74}
75
76pub fn review() -> Value {
77    json!({
78        "type": "object",
79        "additionalProperties": false,
80        "properties": {
81            "verdict": {
82                "type": "string",
83                "enum": ["approve", "changes_requested"],
84                "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."
85            },
86            "next_action": {"type": "string", "enum": ["merge", "fix_myself", "hand_back"]},
87            "summary": {
88                "type": "string",
89                "description": "One sentence, at most 200 characters. No preamble, no restating the diff."
90            },
91            "findings": {
92                "type": "array",
93                "items": {
94                    "type": "object",
95                    "additionalProperties": false,
96                    "properties": {
97                        "severity": {
98                            "type": "string",
99                            "enum": ["blocking", "non-blocking", "nit"],
100                            "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."
101                        },
102                        "title": {
103                            "type": "string",
104                            "description": "Under 80 characters. State the defect, not the fix."
105                        },
106                        "detail": {
107                            "type": "string",
108                            "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."
109                        },
110                        "file": {
111                            "type": "string",
112                            "description": "Path from the repository root, then :line or :first-last for the line in the branch's version of the file when you have one, as src/net.rs:88. Empty string if the finding is general."
113                        },
114                        "problem": {
115                            "type": ["string", "null"],
116                            "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."
117                        },
118                        "reproduction": {
119                            "type": ["string", "null"],
120                            "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."
121                        },
122                        "impact": {
123                            "type": ["string", "null"],
124                            "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."
125                        },
126                        "expected": {
127                            "type": ["string", "null"],
128                            "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."
129                        },
130                        "in_scope": {
131                            "type": "boolean",
132                            "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."
133                        }
134                    },
135                    "required": [
136                        "severity",
137                        "title",
138                        "detail",
139                        "file",
140                        "in_scope",
141                        "problem",
142                        "reproduction",
143                        "impact",
144                        "expected"
145                    ]
146                }
147            }
148        },
149        "required": ["verdict", "next_action", "summary", "findings"]
150    })
151}
152
153/// What the implementor reports back, and the pull request body it becomes.
154///
155/// The body used to be one scraped `SUMMARY:` line under a `Closes #N`, which
156/// told a reviewer opening the diff cold nothing: not what was wrong, not what
157/// the change does about it, not how to check it. Asking for those separately
158/// is what puts them there, and composing the body from the fields rather than
159/// from the model's prose is what keeps it short enough to read.
160pub fn implementation() -> Value {
161    json!({
162        "type": "object",
163        "additionalProperties": false,
164        "properties": {
165            "not_worth_doing": {
166                "type": "boolean",
167                "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."
168            },
169            "reason": {
170                "type": "string",
171                "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."
172            },
173            "summary": {
174                "type": "string",
175                "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."
176            },
177            "problem": {
178                "type": "string",
179                "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."
180            },
181            "changes": {
182                "type": "array",
183                "items": {"type": "string"},
184                "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."
185            },
186            "testing": {
187                "type": "array",
188                "items": {"type": "string"},
189                "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."
190            },
191            "notes": {
192                "type": ["string", "null"],
193                "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."
194            }
195        },
196        "required": ["not_worth_doing", "reason", "summary", "problem", "changes", "testing", "notes"]
197    })
198}
199
200pub fn response() -> Value {
201    json!({
202        "type": "object",
203        "additionalProperties": false,
204        "properties": {
205            "summary": {
206                "type": "string",
207                "description": "One sentence, at most 200 characters."
208            },
209            "dispositions": {
210                "type": "array",
211                "items": {
212                    "type": "object",
213                    "additionalProperties": false,
214                    "properties": {
215                        "title": {
216                            "type": "string",
217                            "description": "Copy the reviewer's finding title exactly, so the two can be matched up."
218                        },
219                        "file": {
220                            "type": "string",
221                            "description": "Copy the reviewer's file for this finding exactly. Empty string if it had none."
222                        },
223                        "action": {
224                            "type": "string",
225                            "enum": ["fixed", "refuted", "filed_issue"],
226                            "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."
227                        },
228                        "reasoning": {
229                            "type": "string",
230                            "description": "One or two sentences. For a refutation this is the whole argument, so make it the reason and not an apology."
231                        },
232                        "new_issue_title": {
233                            "type": ["string", "null"],
234                            "description": "Only for filed_issue, null otherwise."
235                        },
236                        "new_issue_body": {
237                            "type": ["string", "null"],
238                            "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."
239                        }
240                    },
241                    "required": ["title", "file", "action", "reasoning", "new_issue_title", "new_issue_body"]
242                }
243            }
244        },
245        "required": ["summary", "dispositions"]
246    })
247}
248
249/// Who is answering for the acceptance criteria: the author, whose word is a
250/// claim, or a reviewer, whose word is what ticks a box.
251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252pub enum CriteriaVoice {
253    Author,
254    Reviewer,
255}
256
257/// `schema` with a status asked for on each numbered acceptance criterion.
258///
259/// Added only when the issue has criteria, so an issue without any is asked
260/// exactly what it was asked before.
261pub fn with_criteria(mut schema: Value, voice: CriteriaVoice) -> Value {
262    let (statuses, description) = match voice {
263        CriteriaVoice::Author => (
264            json!(["done", "not_done", "needs_person"]),
265            "One entry per numbered acceptance criterion. done: the change does it. not_done: it does not. needs_person: the repository cannot show it, such as a run on a device. This is your account for the pull request body, and the reviewer rules on each one.",
266        ),
267        CriteriaVoice::Reviewer => (
268            json!(["met", "not_met", "needs_person"]),
269            "One entry per numbered acceptance criterion. met: you checked the branch does it. not_met: it does not, or you could not confirm it. needs_person: the repository cannot show it, such as a run on a device. A criterion ruled met is ticked on the issue when spar merges.",
270        ),
271    };
272    let property = json!({
273        "type": "array",
274        "description": description,
275        "items": {
276            "type": "object",
277            "additionalProperties": false,
278            "properties": {
279                "number": {"type": "integer", "description": "The criterion's number as listed."},
280                "status": {"type": "string", "enum": statuses},
281                "reason": {
282                    "type": "string",
283                    "description": "One line: what you did or checked, or what is missing."
284                }
285            },
286            "required": ["number", "status", "reason"]
287        }
288    });
289    schema["properties"]["criteria"] = property;
290    if let Some(required) = schema["required"].as_array_mut() {
291        required.push(json!("criteria"));
292    }
293    schema
294}
295
296/// One reviewer judging the other reviewer's findings.
297///
298/// Used only in review only mode, where nobody is going to fix anything and the
299/// product is the finding list itself. Asking each model to read the code and
300/// rule on the other's claims is what separates a defect worth a maintainer's
301/// attention from one model's pattern match.
302pub fn adjudication() -> Value {
303    json!({
304        "type": "object",
305        "additionalProperties": false,
306        "properties": {
307            "verdicts": {
308                "type": "array",
309                "items": {
310                    "type": "object",
311                    "additionalProperties": false,
312                    "properties": {
313                        "title": {
314                            "type": "string",
315                            "description": "Copy the finding's title exactly, so it can be matched up."
316                        },
317                        "file": {
318                            "type": "string",
319                            "description": "Copy the finding's file exactly. Empty string if it had none."
320                        },
321                        "agrees": {
322                            "type": "boolean",
323                            "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."
324                        },
325                        "severity": {
326                            "type": "string",
327                            "enum": ["blocking", "non-blocking", "nit"],
328                            "description": "Your own view of how badly it matters, even where you agree the defect is real."
329                        },
330                        "reasoning": {
331                            "type": "string",
332                            "description": "One or two sentences. If you disagree, this is the whole argument, so give the reason rather than an opinion."
333                        }
334                    },
335                    "required": ["title", "file", "agrees", "severity", "reasoning"]
336                }
337            }
338        },
339        "required": ["verdicts"]
340    })
341}
342
343/// Both agents, after a reviewed pull request moved: a ruling per earlier
344/// finding, matched back by the number the prompt gave it, and ordinary
345/// findings for anything new in the delta. The finding item is `review()`'s,
346/// so there is one definition of a finding.
347pub fn recheck() -> Value {
348    let mut findings = review()["properties"]["findings"].clone();
349    findings["description"] = json!(
350        "Only what is new since the last review. An earlier point belongs in its ruling, not here."
351    );
352    json!({
353        "type": "object",
354        "additionalProperties": false,
355        "properties": {
356            "summary": {
357                "type": "string",
358                "description": "One sentence, at most 200 characters, on what changed since the last review and whether it holds up."
359            },
360            "rulings": {
361                "type": "array",
362                "items": {
363                    "type": "object",
364                    "additionalProperties": false,
365                    "properties": {
366                        "index": {
367                            "type": "integer",
368                            "description": "The number the earlier finding was given in the list. Copy it exactly, so the ruling can be matched back to the point it is about."
369                        },
370                        "outcome": {
371                            "type": "string",
372                            "enum": ["fixed", "rebutted", "open"],
373                            "description": "fixed: the code now answers the point. rebutted: the code did not change for it, and a quoted response shows the point was wrong or does not apply here. open: neither. Say open when you are unsure: an open point costs one more look, a wrongly closed one ships."
374                        },
375                        "reasoning": {
376                            "type": "string",
377                            "description": "One or two sentences. For fixed, the file and line that answers it and what you did to confirm that. For rebutted, which response and why it holds against the code. For open, what is still missing. This is posted for the author, so write it to them."
378                        }
379                    },
380                    "required": ["index", "outcome", "reasoning"]
381                }
382            },
383            "findings": findings
384        },
385        "required": ["summary", "rulings", "findings"]
386    })
387}
388
389/// One agent ruling on recorded follow-ups, before any becomes an issue.
390///
391/// Deliberately not the triage schema. Triage asks whether an issue is worth a
392/// pull request; this asks whether a note written weeks ago is still true of the
393/// code, which is a different question with a different expensive mistake:
394/// dropping something real, rather than scheduling something small.
395pub fn screen() -> Value {
396    json!({
397        "type": "object",
398        "additionalProperties": false,
399        "properties": {
400            "entries": {
401                "type": "array",
402                "items": {
403                    "type": "object",
404                    "additionalProperties": false,
405                    "properties": {
406                        "entry": {
407                            "type": "integer",
408                            "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."
409                        },
410                        "verdict": {
411                            "type": "string",
412                            "enum": ["still_relevant", "already_fixed", "not_worth_it", "duplicate"],
413                            "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."
414                        },
415                        "title": {
416                            "type": "string",
417                            "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."
418                        },
419                        "reason": {
420                            "type": "string",
421                            "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."
422                        },
423                        "duplicate_of_issue": {
424                            "type": ["integer", "null"],
425                            "description": "Only when the verdict is duplicate and an open issue already covers it. The issue number, null otherwise."
426                        },
427                        "duplicate_of_entry": {
428                            "type": ["integer", "null"],
429                            "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."
430                        }
431                    },
432                    "required": ["entry", "verdict", "title", "reason", "duplicate_of_issue", "duplicate_of_entry"]
433                }
434            }
435        },
436        "required": ["entries"]
437    })
438}
439
440/// One agent ruling on a whole queue at once: is this worth splitting.
441///
442/// One call rather than N, for the reason `screen` is one call: a repository
443/// aware pass is the dominant cost, and "is this too big to work in one piece"
444/// is partly a judgement across the queue rather than about each item alone.
445pub fn split_screen() -> Value {
446    json!({
447        "type": "object",
448        "additionalProperties": false,
449        "properties": {
450            "items": {
451                "type": "array",
452                "items": {
453                    "type": "object",
454                    "additionalProperties": false,
455                    "properties": {
456                        "item": {
457                            "type": "integer",
458                            "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."
459                        },
460                        "split": {
461                            "type": "boolean",
462                            "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."
463                        },
464                        "reason": {
465                            "type": "string",
466                            "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."
467                        }
468                    },
469                    "required": ["item", "split", "reason"]
470                }
471            }
472        },
473        "required": ["items"]
474    })
475}
476
477/// One agent decomposing one issue or one pull request.
478///
479/// The descriptions carry the two rules the command rests on: a part that
480/// cannot stand on its own is not a part, and the whole value of splitting is
481/// that each piece can be reviewed and merged by itself.
482pub fn split_proposal() -> Value {
483    json!({
484        "type": "object",
485        "additionalProperties": false,
486        "properties": {
487            "should_split": {
488                "type": "boolean",
489                "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."
490            },
491            "reason": {
492                "type": "string",
493                "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."
494            },
495            "stacked": {
496                "type": "boolean",
497                "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."
498            },
499            "parts": {
500                "type": "array",
501                "items": {
502                    "type": "object",
503                    "additionalProperties": false,
504                    "properties": {
505                        "title": {
506                            "type": "string",
507                            "description": "Under 80 characters. States the piece of work, not the fact that it was split out."
508                        },
509                        "body": {
510                            "type": "string",
511                            "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."
512                        },
513                        "files": {
514                            "type": ["array", "null"],
515                            "items": {"type": "string"},
516                            "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."
517                        }
518                    },
519                    "required": ["title", "body", "files"]
520                }
521            }
522        },
523        "required": ["should_split", "reason", "stacked", "parts"]
524    })
525}
526
527/// The second agent ruling on the first one's decomposition.
528///
529/// Not a second proposal. Two decompositions of one thing cannot be reconciled
530/// mechanically, so this agent rules on the one in front of it: accept, reject,
531/// or accept with named parts struck.
532pub fn split_check() -> Value {
533    json!({
534        "type": "object",
535        "additionalProperties": false,
536        "properties": {
537            "accept": {
538                "type": "boolean",
539                "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."
540            },
541            "stacked": {
542                "type": "boolean",
543                "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."
544            },
545            "strike": {
546                "type": "array",
547                "items": {"type": "integer"},
548                "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."
549            },
550            "reasoning": {
551                "type": "string",
552                "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."
553            }
554        },
555        "required": ["accept", "stacked", "strike", "reasoning"]
556    })
557}
558
559/// One agent judging the comments other people left on a pull request.
560///
561/// The descriptions carry the asymmetry the whole command rests on, because
562/// they travel with the request rather than sitting a thousand tokens back in
563/// the prompt: getting a decline wrong costs a person one read of a thread that
564/// stays open for them, and getting an implement wrong costs them a commit they
565/// did not ask for on a branch they own.
566pub fn checkin() -> Value {
567    json!({
568        "type": "object",
569        "additionalProperties": false,
570        "properties": {
571            "verdicts": {
572                "type": "array",
573                "items": {
574                    "type": "object",
575                    "additionalProperties": false,
576                    "properties": {
577                        "ref_id": {
578                            "type": "string",
579                            "description": "The handle printed beside the comment, copied across exactly, so your answer can be matched back to it."
580                        },
581                        "ask": {
582                            "type": "string",
583                            "enum": ["implement", "defer", "decline", "answer", "nothing"],
584                            "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 somebody asked, which gets a reply. nothing: nothing is being asked for, such as praise, an approval, a review that found nothing to change, or a bot reporting a build; nothing is said in reply."
585                        },
586                        "request": {
587                            "type": "string",
588                            "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."
589                        },
590                        "reasoning": {
591                            "type": "string",
592                            "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."
593                        },
594                        "unambiguous": {
595                            "type": "boolean",
596                            "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."
597                        },
598                        "new_issue_title": {
599                            "type": ["string", "null"],
600                            "description": "Only when ask is defer, null otherwise. States the defect, not the fix."
601                        },
602                        "new_issue_body": {
603                            "type": ["string", "null"],
604                            "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."
605                        }
606                    },
607                    "required": ["ref_id", "ask", "request", "reasoning", "unambiguous", "new_issue_title", "new_issue_body"]
608                }
609            }
610        },
611        "required": ["verdicts"]
612    })
613}
614
615/// The second agent ruling on the first one's calls.
616pub fn checkin_check() -> Value {
617    json!({
618        "type": "object",
619        "additionalProperties": false,
620        "properties": {
621            "checks": {
622                "type": "array",
623                "items": {
624                    "type": "object",
625                    "additionalProperties": false,
626                    "properties": {
627                        "ref_id": {
628                            "type": "string",
629                            "description": "The handle printed beside the comment, copied across exactly."
630                        },
631                        "agrees": {
632                            "type": "boolean",
633                            "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."
634                        },
635                        "ask": {
636                            "type": "string",
637                            "enum": ["implement", "defer", "decline", "answer", "nothing"],
638                            "description": "What you would do instead. Read only when agrees is false."
639                        },
640                        "unambiguous": {
641                            "type": "boolean",
642                            "description": "False if the comment could be read more than one way, whatever the other agent said about it."
643                        },
644                        "reasoning": {
645                            "type": "string",
646                            "description": "One or two sentences saying what you checked and what it showed. Required when you disagree, and useful when you agree."
647                        }
648                    },
649                    "required": ["ref_id", "agrees", "ask", "unambiguous", "reasoning"]
650                }
651            }
652        },
653        "required": ["checks"]
654    })
655}
656
657/// What the fix pass reports back about each change it was asked to make.
658pub fn checkin_fix() -> Value {
659    json!({
660        "type": "object",
661        "additionalProperties": false,
662        "properties": {
663            "done": {
664                "type": "array",
665                "items": {
666                    "type": "object",
667                    "additionalProperties": false,
668                    "properties": {
669                        "ref_id": {
670                            "type": "string",
671                            "description": "The handle printed beside the comment, copied across exactly."
672                        },
673                        "changed": {
674                            "type": "boolean",
675                            "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."
676                        },
677                        "summary": {
678                            "type": "string",
679                            "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."
680                        },
681                        "files": {
682                            "type": "array",
683                            "items": {"type": "string"},
684                            "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."
685                        }
686                    },
687                    "required": ["ref_id", "changed", "summary", "files"]
688                }
689            }
690        },
691        "required": ["done"]
692    })
693}
694
695/// One agent drafting answers to what an issue asks of the viewer.
696///
697/// The line the whole command rests on travels with the request: a question
698/// of fact is spar's to answer, and anything that commits the viewer is never
699/// answered in their name.
700pub fn answer() -> Value {
701    json!({
702        "type": "object",
703        "additionalProperties": false,
704        "properties": {
705            "questions": {
706                "type": "array",
707                "items": {
708                    "type": "object",
709                    "additionalProperties": false,
710                    "properties": {
711                        "ref_id": {
712                            "type": "string",
713                            "description": "The handle printed beside the mention the question is in, copied across exactly."
714                        },
715                        "question": {
716                            "type": "string",
717                            "description": "The question as it was put to the viewer, quoted from the issue where it reads on its own, and restated as briefly as possible where it does not."
718                        },
719                        "kind": {
720                            "type": "string",
721                            "enum": ["answer", "yours"],
722                            "description": "answer: a question of fact or of how something works that the code, the issue, or what it links settles, and that you checked. yours: anything that asks the viewer to decide, agree, commit, own, schedule, approve, review, or give a view or a preference, and anything you could not check. Posted answers speak as the viewer, so a wrong answer is worse than none: when in doubt, yours."
723                        },
724                        "answer": {
725                            "type": "string",
726                            "description": "For answer, the reply as it would be posted under the viewer's name: direct, specific, citing what it rests on, and no longer than the question needs. For yours, what you found that would help the viewer answer it themselves, which is never posted."
727                        },
728                        "evidence": {
729                            "type": "string",
730                            "description": "What the answer rests on: repository paths with line numbers, commits, or links you read. Empty only for yours when there was nothing to check."
731                        },
732                        "reasoning": {
733                            "type": "string",
734                            "description": "One sentence saying why this kind. For yours, what makes it the viewer's to answer."
735                        }
736                    },
737                    "required": ["ref_id", "question", "kind", "answer", "evidence", "reasoning"]
738                }
739            }
740        },
741        "required": ["questions"]
742    })
743}
744
745/// The second agent ruling on the drafted answers.
746pub fn answer_check() -> Value {
747    json!({
748        "type": "object",
749        "additionalProperties": false,
750        "properties": {
751            "checks": {
752                "type": "array",
753                "items": {
754                    "type": "object",
755                    "additionalProperties": false,
756                    "properties": {
757                        "id": {
758                            "type": "string",
759                            "description": "The handle printed beside the question, q1 and so on, copied across exactly."
760                        },
761                        "agrees": {
762                            "type": "boolean",
763                            "description": "True only if you checked the drafted answer yourself and it is right, complete, and fit to post under the viewer's name. Do not agree to be agreeable: anything you agree to is posted as the viewer's own words."
764                        },
765                        "kind": {
766                            "type": "string",
767                            "enum": ["answer", "yours"],
768                            "description": "Who you say should answer it, on the same terms as the draft: yours for anything that asks the viewer to decide, commit, or give a view, and for anything you could not check."
769                        },
770                        "reasoning": {
771                            "type": "string",
772                            "description": "One or two sentences saying what you checked and what it showed. Required when you disagree."
773                        }
774                    },
775                    "required": ["id", "agrees", "kind", "reasoning"]
776                }
777            },
778            "missed": {
779                "type": "array",
780                "items": {"type": "string"},
781                "description": "Questions the mentions put to the viewer that the draft left out, one per entry, quoted. Empty when it left none out. Never a question put to somebody else."
782            }
783        },
784        "required": ["checks", "missed"]
785    })
786}
787
788/// A reviewer's report on fixing its own findings.
789///
790/// Same shape as a response, minus the parts that only make sense from the
791/// author's side: a reviewer fixing its own point cannot refute it, and filing
792/// it as somebody else's issue is a decision for the round rather than for this
793/// call.
794pub fn own_fix() -> Value {
795    json!({
796        "type": "object",
797        "additionalProperties": false,
798        "properties": {
799            "summary": {
800                "type": "string",
801                "description": "One sentence naming what changed, at most 200 characters. This becomes the commit subject, so write it as one."
802            },
803            "fixes": {
804                "type": "array",
805                "items": {
806                    "type": "object",
807                    "additionalProperties": false,
808                    "properties": {
809                        "title": {
810                            "type": "string",
811                            "description": "Copy your own finding title exactly, so the two can be matched up."
812                        },
813                        "file": {
814                            "type": "string",
815                            "description": "Copy the file from that finding exactly. Empty string if it had none."
816                        },
817                        "fixed": {
818                            "type": "boolean",
819                            "description": "True only if this point is answered by a change in the working tree. False if you left it, whatever the reason."
820                        },
821                        "reason": {
822                            "type": "string",
823                            "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."
824                        }
825                    },
826                    "required": ["title", "file", "fixed", "reason"]
827                }
828            }
829        },
830        "required": ["summary", "fixes"]
831    })
832}
833
834/// One idea's shape, shared by the diverge answer and a cross round's build.
835///
836/// `combines` is required and described at length because it is the whole
837/// method: an idea that cannot name the existing pieces it pairs is a wish.
838fn idea() -> Value {
839    json!({
840        "type": "object",
841        "additionalProperties": false,
842        "properties": {
843            "title": {
844                "type": "string",
845                "description": "One line naming the idea by what it does, not by its ingredients. It becomes a heading, and may become an issue title."
846            },
847            "combines": {
848                "type": "array",
849                "items": {"type": "string"},
850                "description": "The existing techniques, primitives, results, tools, or patterns this idea pairs, one per entry, each named specifically enough to look up. At least two. This is the whole method: the pieces exist already and the pairing is what is new."
851            },
852            "how_it_works": {
853                "type": "string",
854                "description": "The mechanism, concretely enough that somebody could start on it. A paragraph, not a pitch."
855            },
856            "why_new": {
857                "type": "string",
858                "description": "The nearest thing that already exists, named, and what this does that it does not. If you cannot name a nearest thing, look harder before claiming there is none."
859            },
860            "enables": {
861                "type": "string",
862                "description": "What becomes possible that was not, in one or two sentences."
863            },
864            "risks": {
865                "type": "string",
866                "description": "What would make it fail, honestly. The reader decides whether to try it on this."
867            },
868            "first_experiment": {
869                "type": "string",
870                "description": "The cheapest thing that would show whether it works: a prototype, a calculation, a query, a conversation with somebody who would know."
871            }
872        },
873        "required": ["title", "combines", "how_it_works", "why_new", "enables", "risks", "first_experiment"]
874    })
875}
876
877pub fn brainstorm_ideas() -> Value {
878    json!({
879        "type": "object",
880        "additionalProperties": false,
881        "properties": {
882            "ideas": {
883                "type": "array",
884                "items": idea(),
885                "description": "The ideas, best first. Each pairs existing pieces in a way that has not been done."
886            }
887        },
888        "required": ["ideas"]
889    })
890}
891
892/// A cross round: one agent ruling on ideas the other proposed.
893///
894/// Matched back by number rather than title, for the reason the screen schema
895/// carries an entry number: a model rewrites titles.
896pub fn brainstorm_cross() -> Value {
897    let mut build = idea();
898    build["type"] = json!(["object", "null"]);
899    build["description"] = json!("The revised idea in full when the verdict is build, naming everything it combines including the new piece. Null for any other verdict.");
900    json!({
901        "type": "object",
902        "additionalProperties": false,
903        "properties": {
904            "verdicts": {
905                "type": "array",
906                "items": {
907                    "type": "object",
908                    "additionalProperties": false,
909                    "properties": {
910                        "idea": {
911                            "type": "integer",
912                            "description": "The number the idea was given in the list above. Copy it exactly, so the ruling can be matched back to the idea it is about."
913                        },
914                        "verdict": {
915                            "type": "string",
916                            "enum": ["build", "challenge", "keep"],
917                            "description": "build: you can see a further piece that completes it or makes it stronger, and you have written the revised idea in build. challenge: it already exists and you can name where, or it cannot work and you can say why. keep: real and new as far as you can tell, nothing to add."
918                        },
919                        "reason": {
920                            "type": "string",
921                            "description": "For challenge, the thing that already exists or the reason it cannot work, specifically: the proposer answers this with specifics. For build, what the new piece adds. For keep, one sentence or empty."
922                        },
923                        "build": build
924                    },
925                    "required": ["idea", "verdict", "reason", "build"]
926                }
927            }
928        },
929        "required": ["verdicts"]
930    })
931}
932
933/// The last round: defend or withdraw what was challenged, and rank the rest.
934pub fn brainstorm_converge() -> Value {
935    json!({
936        "type": "object",
937        "additionalProperties": false,
938        "properties": {
939            "defences": {
940                "type": "array",
941                "items": {
942                    "type": "object",
943                    "additionalProperties": false,
944                    "properties": {
945                        "idea": {
946                            "type": "integer",
947                            "description": "The number of an idea you proposed that was challenged. One entry per challenged idea of yours, and none for anything else."
948                        },
949                        "stands": {
950                            "type": "boolean",
951                            "description": "True only if you can give the specific evidence that settles the objection in reply. False withdraws the idea, which is the right answer when the objection is correct."
952                        },
953                        "reply": {
954                            "type": "string",
955                            "description": "The evidence when it stands: the prior art that does not actually do this, the mechanism the objection missed, the number that makes it work. One sentence when it does not."
956                        }
957                    },
958                    "required": ["idea", "stands", "reply"]
959                }
960            },
961            "ranking": {
962                "type": "array",
963                "items": {"type": "integer"},
964                "description": "Every idea number that is not withdrawn, best first, including your own and the ones you challenged. Novelty and feasibility together: an idea nobody has done that could be tried this month beats a moonshot, and a moonshot beats a small improvement on something that exists."
965            }
966        },
967        "required": ["defences", "ranking"]
968    })
969}
970
971pub fn all() -> Vec<(&'static str, Value)> {
972    vec![
973        ("code_issue", code_issue()),
974        ("triage", triage()),
975        ("implementation", implementation()),
976        ("review", review()),
977        (
978            "implementation_with_criteria",
979            with_criteria(implementation(), CriteriaVoice::Author),
980        ),
981        (
982            "review_with_criteria",
983            with_criteria(review(), CriteriaVoice::Reviewer),
984        ),
985        ("recheck", recheck()),
986        ("response", response()),
987        ("own_fix", own_fix()),
988        ("screen", screen()),
989        ("checkin", checkin()),
990        ("checkin_check", checkin_check()),
991        ("checkin_fix", checkin_fix()),
992        ("answer", answer()),
993        ("answer_check", answer_check()),
994        ("split_screen", split_screen()),
995        ("split_proposal", split_proposal()),
996        ("split_check", split_check()),
997        ("brainstorm_ideas", brainstorm_ideas()),
998        ("brainstorm_cross", brainstorm_cross()),
999        ("brainstorm_converge", brainstorm_converge()),
1000    ]
1001}
1002
1003#[cfg(test)]
1004mod tests {
1005    use super::*;
1006
1007    /// Yield every object schema, however deeply nested.
1008    fn objects(node: &Value, path: String, out: &mut Vec<(String, Value)>) {
1009        if let Some(map) = node.as_object() {
1010            if map.get("type").and_then(Value::as_str) == Some("object")
1011                && map.contains_key("properties")
1012            {
1013                out.push((path.clone(), node.clone()));
1014                if let Some(props) = map.get("properties").and_then(Value::as_object) {
1015                    for (key, child) in props {
1016                        objects(child, format!("{path}.{key}"), out);
1017                    }
1018                }
1019            }
1020            if let Some(items) = map.get("items") {
1021                objects(items, format!("{path}[]"), out);
1022            }
1023        }
1024    }
1025
1026    fn walk(name: &str, schema: &Value) -> Vec<(String, Value)> {
1027        let mut out = Vec::new();
1028        objects(schema, name.to_string(), &mut out);
1029        out
1030    }
1031
1032    /// Strict structured output rejects any property that is not also in
1033    /// `required`. The Python original violated this in the response schema
1034    /// from the start and nothing caught it, because the response schema is
1035    /// only reached when a review is handed back with blocking findings, and
1036    /// almost every run approved in round one.
1037    #[test]
1038    fn every_property_is_required() {
1039        for (name, schema) in all() {
1040            for (path, node) in walk(name, &schema) {
1041                let props: Vec<&String> = node["properties"].as_object().unwrap().keys().collect();
1042                let required: Vec<String> = node["required"]
1043                    .as_array()
1044                    .unwrap_or(&vec![])
1045                    .iter()
1046                    .filter_map(|v| v.as_str().map(str::to_string))
1047                    .collect();
1048                for prop in &props {
1049                    assert!(
1050                        required.contains(prop),
1051                        "{path}: {prop} is in properties but not in required. \
1052                         Make optional fields nullable instead."
1053                    );
1054                }
1055                assert_eq!(props.len(), required.len(), "{path}: required has extras");
1056            }
1057        }
1058    }
1059
1060    /// Asked only when there are criteria, and then of both voices in the
1061    /// spelling each one's statuses parse back from.
1062    #[test]
1063    fn criteria_are_asked_only_when_added_and_parse_back() {
1064        use crate::model::{Implementation, Mark, Review};
1065        assert!(implementation()["properties"].get("criteria").is_none());
1066        assert!(review()["properties"].get("criteria").is_none());
1067        for (voice, met) in [
1068            (CriteriaVoice::Author, "done"),
1069            (CriteriaVoice::Reviewer, "met"),
1070        ] {
1071            let schema = with_criteria(review(), voice);
1072            let statuses =
1073                &schema["properties"]["criteria"]["items"]["properties"]["status"]["enum"];
1074            for status in statuses.as_array().unwrap() {
1075                assert!(Mark::parse_lenient(status.as_str().unwrap()).is_some());
1076            }
1077            assert_eq!(Some(Mark::Met), Mark::parse_lenient(met));
1078        }
1079        let work: Implementation = serde_json::from_value(json!({
1080            "criteria": [{"number": 1, "status": "needs_person", "reason": "a device"}]
1081        }))
1082        .unwrap();
1083        assert_eq!(Mark::NeedsPerson, work.criteria[0].status);
1084        let review: Review = serde_json::from_value(json!({
1085            "verdict": "approve", "next_action": "merge", "summary": "", "findings": [],
1086            "criteria": [{"number": 2, "status": "not_met", "reason": "no test"}]
1087        }))
1088        .unwrap();
1089        assert_eq!(Mark::NotMet, review.criteria[0].status);
1090    }
1091
1092    /// The guard that was missing. A schema field can be added to the struct
1093    /// and forgotten in the schema, and every test still passes: the tests
1094    /// build the struct in Rust, so they never notice the model was never
1095    /// asked. That shipped once, as four bug-report fields the agents were
1096    /// never told about, which quietly did nothing.
1097    #[test]
1098    fn the_review_schema_asks_for_every_field_a_finding_holds() {
1099        use crate::model::Finding;
1100
1101        let asked: Vec<String> = review()["properties"]["findings"]["items"]["properties"]
1102            .as_object()
1103            .expect("finding properties")
1104            .keys()
1105            .cloned()
1106            .collect();
1107
1108        // Round-tripping a fully populated Finding names every field serde
1109        // knows about, without repeating the list here to drift out of date.
1110        let populated = Finding {
1111            problem: Some("p".into()),
1112            reproduction: Some("r".into()),
1113            impact: Some("i".into()),
1114            expected: Some("e".into()),
1115            ..Finding::default()
1116        };
1117        let held: Vec<String> = serde_json::to_value(&populated)
1118            .expect("serialisable")
1119            .as_object()
1120            .expect("object")
1121            .keys()
1122            .cloned()
1123            .collect();
1124
1125        for field in &held {
1126            assert!(
1127                asked.contains(field),
1128                "a Finding holds `{field}` and the schema never asks for it, so the model will \
1129                 not fill it and the code reading it will always see nothing"
1130            );
1131        }
1132    }
1133
1134    /// The same guard for the second look: its findings are `review()`'s
1135    /// items, and its rulings have to ask for every field a ruling holds.
1136    #[test]
1137    fn the_recheck_schema_asks_for_every_field_a_finding_and_a_ruling_hold() {
1138        use crate::model::{RecheckRuling, Ruling};
1139
1140        assert_eq!(
1141            review()["properties"]["findings"]["items"],
1142            recheck()["properties"]["findings"]["items"],
1143            "a second look's findings are first look findings"
1144        );
1145
1146        let asked: Vec<String> = recheck()["properties"]["rulings"]["items"]["properties"]
1147            .as_object()
1148            .expect("ruling properties")
1149            .keys()
1150            .cloned()
1151            .collect();
1152        let held: Vec<String> = serde_json::to_value(RecheckRuling {
1153            index: 1,
1154            outcome: Ruling::Open,
1155            reasoning: "r".into(),
1156        })
1157        .expect("serialisable")
1158        .as_object()
1159        .expect("object")
1160        .keys()
1161        .cloned()
1162        .collect();
1163        for field in &held {
1164            assert!(
1165                asked.contains(field),
1166                "a ruling holds `{field}`, unasked for"
1167            );
1168        }
1169    }
1170
1171    /// Every outcome the schema offers is one the parser reads back.
1172    #[test]
1173    fn the_recheck_outcome_enum_matches_the_parser() {
1174        use crate::model::Ruling;
1175
1176        let offered = recheck()["properties"]["rulings"]["items"]["properties"]["outcome"]["enum"]
1177            .as_array()
1178            .expect("an enum")
1179            .clone();
1180        assert_eq!(3, offered.len());
1181        for value in offered {
1182            let word = value.as_str().expect("a word");
1183            assert!(
1184                Ruling::parse_lenient(word).is_some(),
1185                "{word} is offered and cannot be read back"
1186            );
1187        }
1188    }
1189
1190    /// The same guard for the check-in exchange. A field added to the struct
1191    /// and forgotten in the schema is one the model is never asked for, so the
1192    /// code reading it always sees nothing: an `unambiguous` that is never
1193    /// filled would default false and answer every comment in words.
1194    #[test]
1195    fn the_checkin_schema_asks_for_every_field_a_verdict_holds() {
1196        use crate::model::{Ask, CommentVerdict};
1197
1198        let asked: Vec<String> = checkin()["properties"]["verdicts"]["items"]["properties"]
1199            .as_object()
1200            .expect("verdict properties")
1201            .keys()
1202            .cloned()
1203            .collect();
1204
1205        let populated = CommentVerdict {
1206            ref_id: "c1".into(),
1207            ask: Ask::Decline,
1208            request: "r".into(),
1209            reasoning: "w".into(),
1210            unambiguous: true,
1211            new_issue_title: Some("t".into()),
1212            new_issue_body: Some("b".into()),
1213        };
1214        let held: Vec<String> = serde_json::to_value(&populated)
1215            .expect("serialisable")
1216            .as_object()
1217            .expect("object")
1218            .keys()
1219            .cloned()
1220            .collect();
1221
1222        for field in &held {
1223            assert!(
1224                asked.contains(field),
1225                "a CommentVerdict holds `{field}` and the schema never asks for it, so the model \
1226                 will not fill it and the code reading it will always see nothing"
1227            );
1228        }
1229    }
1230
1231    /// The same guard for the split exchange. A part field added to the struct
1232    /// and forgotten here is one the model is never asked for, so a slice would
1233    /// arrive with no files and carry nothing.
1234    #[test]
1235    fn the_split_schemas_ask_for_every_field_they_hold() {
1236        use crate::model::{SplitCheck, SplitPart, SplitProposal};
1237
1238        let cases: Vec<(&str, Value, serde_json::Value)> = vec![
1239            (
1240                "SplitProposal",
1241                split_proposal()["properties"].clone(),
1242                serde_json::to_value(SplitProposal::default()).expect("serialisable"),
1243            ),
1244            (
1245                "SplitPart",
1246                split_proposal()["properties"]["parts"]["items"]["properties"].clone(),
1247                serde_json::to_value(SplitPart::default()).expect("serialisable"),
1248            ),
1249            (
1250                "SplitCheck",
1251                split_check()["properties"].clone(),
1252                serde_json::to_value(SplitCheck::default()).expect("serialisable"),
1253            ),
1254        ];
1255        for (what, asked, held) in cases {
1256            let asked: Vec<String> = asked
1257                .as_object()
1258                .expect("properties")
1259                .keys()
1260                .cloned()
1261                .collect();
1262            for field in held.as_object().expect("object").keys() {
1263                assert!(
1264                    asked.contains(field),
1265                    "a {what} holds `{field}` and the schema never asks for it, so the code \
1266                     reading it will always see nothing"
1267                );
1268            }
1269        }
1270    }
1271
1272    /// A slice with no files carries nothing, so the one field that decides
1273    /// what a part is has to be spelled as nullable rather than left out.
1274    #[test]
1275    fn a_split_part_may_carry_no_files_without_omitting_the_field() {
1276        let types = split_proposal()["properties"]["parts"]["items"]["properties"]["files"]["type"]
1277            .to_string();
1278        assert!(types.contains("null"), "files must accept null: {types}");
1279    }
1280
1281    /// Every value the schema offers has to be one the parser accepts, or an
1282    /// answer that matched the schema exactly is thrown away.
1283    #[test]
1284    fn the_checkin_ask_enum_matches_the_parser() {
1285        use crate::model::Ask;
1286
1287        for schema in [
1288            checkin()["properties"]["verdicts"]["items"]["properties"]["ask"].clone(),
1289            checkin_check()["properties"]["checks"]["items"]["properties"]["ask"].clone(),
1290        ] {
1291            for value in schema["enum"].as_array().expect("an enum") {
1292                let text = value.as_str().expect("a string");
1293                assert!(
1294                    Ask::parse_lenient(text).is_some(),
1295                    "the schema offers `{text}` and the parser refuses it"
1296                );
1297            }
1298        }
1299    }
1300
1301    /// The same guard for the implementation exchange, where a forgotten field
1302    /// means a pull request body with an empty section in it and nobody the
1303    /// wiser.
1304    #[test]
1305    fn the_implementation_schema_asks_for_every_field_it_holds() {
1306        use crate::model::Implementation;
1307
1308        let asked: Vec<String> = implementation()["properties"]
1309            .as_object()
1310            .expect("properties")
1311            .keys()
1312            .cloned()
1313            .collect();
1314
1315        let populated = Implementation {
1316            notes: Some("n".into()),
1317            ..Implementation::default()
1318        };
1319        let held: Vec<String> = serde_json::to_value(&populated)
1320            .expect("serialisable")
1321            .as_object()
1322            .expect("object")
1323            .keys()
1324            .cloned()
1325            .collect();
1326
1327        for field in &held {
1328            assert!(
1329                asked.contains(field),
1330                "an Implementation holds `{field}` and the schema never asks for it, so the \
1331                 pull request body will always be missing that part"
1332            );
1333        }
1334    }
1335
1336    /// Same guard for the other direction of the same exchange.
1337    #[test]
1338    fn the_response_schema_asks_for_every_field_a_disposition_holds() {
1339        use crate::model::{Action, Disposition};
1340
1341        let asked: Vec<String> = response()["properties"]["dispositions"]["items"]["properties"]
1342            .as_object()
1343            .expect("disposition properties")
1344            .keys()
1345            .cloned()
1346            .collect();
1347
1348        let populated = Disposition {
1349            title: "t".into(),
1350            file: "f".into(),
1351            action: Action::Fixed,
1352            reasoning: "r".into(),
1353            new_issue_title: Some("t".into()),
1354            new_issue_body: Some("b".into()),
1355        };
1356        let held: Vec<String> = serde_json::to_value(&populated)
1357            .expect("serialisable")
1358            .as_object()
1359            .expect("object")
1360            .keys()
1361            .cloned()
1362            .collect();
1363
1364        for field in &held {
1365            assert!(
1366                asked.contains(field),
1367                "a Disposition holds `{field}`, unasked for"
1368            );
1369        }
1370    }
1371
1372    #[test]
1373    fn objects_forbid_additional_properties() {
1374        for (name, schema) in all() {
1375            for (path, node) in walk(name, &schema) {
1376                assert_eq!(
1377                    Some(false),
1378                    node["additionalProperties"].as_bool(),
1379                    "{path} allows additional properties"
1380                );
1381            }
1382        }
1383    }
1384
1385    #[test]
1386    fn optional_fields_are_spelled_as_nullable() {
1387        let item = &response()["properties"]["dispositions"]["items"];
1388        for field in ["new_issue_title", "new_issue_body"] {
1389            let types = item["properties"][field]["type"].to_string();
1390            assert!(types.contains("null"), "{field} must accept null: {types}");
1391        }
1392    }
1393
1394    /// The re-litigation guard hashes a refutation by title *and* file. If the
1395    /// disposition cannot carry the file, the key it records can never match
1396    /// the key the next round's finding hashes to, and the guard is dead code.
1397    #[test]
1398    fn a_disposition_carries_the_file_so_the_ledger_key_can_match() {
1399        let props = response()["properties"]["dispositions"]["items"]["properties"].clone();
1400        assert!(
1401            props.get("file").is_some(),
1402            "dispositions must carry a file"
1403        );
1404    }
1405
1406    #[test]
1407    fn severity_and_verdict_enums_match_the_parser() {
1408        use crate::model::{Severity, Verdict};
1409        let sev =
1410            review()["properties"]["findings"]["items"]["properties"]["severity"]["enum"].clone();
1411        for value in sev.as_array().unwrap() {
1412            assert!(
1413                Severity::parse_lenient(value.as_str().unwrap()).is_some(),
1414                "schema offers {value} but the parser rejects it"
1415            );
1416        }
1417        let verdicts = review()["properties"]["verdict"]["enum"].clone();
1418        for value in verdicts.as_array().unwrap() {
1419            assert!(Verdict::parse_lenient(value.as_str().unwrap()).is_some());
1420        }
1421    }
1422
1423    #[test]
1424    fn triage_enums_match_the_parser() {
1425        use crate::model::{Complexity, Risk};
1426        let item = &triage()["properties"]["issues"]["items"]["properties"];
1427        for value in item["complexity"]["enum"].as_array().unwrap() {
1428            assert!(Complexity::parse_lenient(value.as_str().unwrap()).is_some());
1429        }
1430        for value in item["risk"]["enum"].as_array().unwrap() {
1431            assert!(Risk::parse_lenient(value.as_str().unwrap()).is_some());
1432        }
1433    }
1434
1435    #[test]
1436    fn response_action_enum_matches_the_parser() {
1437        use crate::model::Action;
1438        let actions = response()["properties"]["dispositions"]["items"]["properties"]["action"]
1439            ["enum"]
1440            .clone();
1441        for value in actions.as_array().unwrap() {
1442            assert!(Action::parse_lenient(value.as_str().unwrap()).is_some());
1443        }
1444    }
1445}