返回 CodeWhale
schema.rs
根目录 / crates / workflow-js / src / schema.rs
1 //! `responseSchema` decoding: parse the subagent's reply as JSON and validate
2 //! it against the caller-supplied schema, with bounded repair when it fails.
3 //!
4 //! A reply that is not valid JSON, or that fails the schema, throws on the
5 //! awaiting `task()` call. Before that terminal throw the VM tries a bounded
6 //! repair (#5583): one re-ask (by default; `schemaRepairAttempts` up to 3) of
7 //! the same route with the schema, the invalid reply, and the decode error,
8 //! so a child that wrapped its JSON in prose does not abort a whole run. A
9 //! failed repair stays a schema failure — never a null slot or a degraded
10 //! success — and both attempts are reported through the driver as receipts.
11
12 /// Upper bound on `schemaRepairAttempts`. Repair is a bounded recovery, not a
13 /// retry loop: more attempts than this is a prompt or model-route problem that
14 /// re-asking cannot fix.
15 pub const SCHEMA_REPAIR_MAX_ATTEMPTS: u32 = 3;
16
17 /// Preview of a raw reply carried in receipts and reports. The full raw text
18 /// goes to a durable artifact when it is larger (the host writes it; the VM
19 /// only carries the bytes it was given).
20 pub const SCHEMA_RAW_PREVIEW_CHARS: usize = 2_000;
21
22 /// Hard cap on raw reply text carried in-memory through events. Child replies
23 /// beyond this are pathological; the carried text is capped with an explicit
24 /// marker so the receipt never pretends to be the whole reply.
25 pub const SCHEMA_RAW_CARRY_CHARS: usize = 64 * 1_024;
26
27 /// Compile the caller's schema. Called before spawning so a malformed schema
28 /// fails fast instead of burning a subagent.
29 pub fn compile_schema(
30 label: &str,
31 schema: &serde_json::Value,
32 ) -> Result<jsonschema::Validator, String> {
33 jsonschema::validator_for(schema).map_err(|err| format!("{label}: invalid schema: {err}"))
34 }
35
36 /// Why a reply failed schema decoding.
37 ///
38 /// The distinction is receipt material (#5583): a parse failure means the
39 /// model wrapped or broke the JSON (a repair usually fixes it); a validation
40 /// failure means the JSON parsed but said the wrong thing (a schema or prompt
41 /// problem the operator needs to see named).
42 #[derive(Debug, Clone, PartialEq, Eq)]
43 pub enum ReplyDecodeError {
44 /// The reply was not parseable as JSON at all.
45 Parse(String),
46 /// The reply parsed but violated the caller's schema.
47 Validate(String),
48 }
49
50 impl ReplyDecodeError {
51 /// Stable machine kind for receipts: `json_parse` or `schema_validation`.
52 pub fn kind(&self) -> &'static str {
53 match self {
54 Self::Parse(_) => "json_parse",
55 Self::Validate(_) => "schema_validation",
56 }
57 }
58
59 /// The operator-facing message.
60 pub fn message(&self) -> &str {
61 match self {
62 Self::Parse(message) | Self::Validate(message) => message,
63 }
64 }
65 }
66
67 /// Parse `text` as JSON (tolerating a single Markdown code fence around the
68 /// payload) and validate it against `validator`.
69 pub fn decode_reply(
70 label: &str,
71 text: &str,
72 validator: &jsonschema::Validator,
73 ) -> Result<serde_json::Value, ReplyDecodeError> {
74 let candidate = strip_code_fence(text);
75 let parsed: serde_json::Value = serde_json::from_str(candidate).map_err(|err| {
76 ReplyDecodeError::Parse(format!("{label}: reply is not valid JSON: {err}"))
77 })?;
78 let errors = validator
79 .iter_errors(&parsed)
80 .map(|err| err.to_string())
81 .collect::<Vec<_>>();
82 if !errors.is_empty() {
83 let prefix = if label == "task(): responseSchema" {
84 "task(): reply failed responseSchema validation".to_string()
85 } else {
86 format!("{label}: reply failed schema validation")
87 };
88 return Err(ReplyDecodeError::Validate(format!(
89 "{prefix}: {}",
90 errors.join("; ")
91 )));
92 }
93 Ok(parsed)
94 }
95
96 /// The raw reply text carried alongside a decode failure, capped at
97 /// [`SCHEMA_RAW_CARRY_CHARS`] on a char boundary with an explicit marker.
98 /// Returns `(carried, was_truncated)`.
99 pub(crate) fn carried_raw(text: &str) -> (String, bool) {
100 if text.chars().count() <= SCHEMA_RAW_CARRY_CHARS {
101 return (text.to_string(), false);
102 }
103 let kept: String = text.chars().take(SCHEMA_RAW_CARRY_CHARS).collect();
104 let dropped = text.chars().count() - SCHEMA_RAW_CARRY_CHARS;
105 (
106 format!("{kept}\n…[raw reply truncated: {dropped} chars not carried]"),
107 true,
108 )
109 }
110
111 /// Build the repair prompt for the next attempt: the same task, the schema it
112 /// must satisfy, the reply that failed, and why. The repair child is a fresh
113 /// agent — it has no memory of the failed attempt, so everything it needs to
114 /// correct the reply travels in this prompt.
115 pub fn repair_prompt(
116 original_prompt: &str,
117 schema: &serde_json::Value,
118 failed_raw: &str,
119 error: &ReplyDecodeError,
120 ) -> String {
121 let schema_text = serde_json::to_string_pretty(schema).unwrap_or_else(|_| schema.to_string());
122 format!(
123 "Your previous reply for this task failed its responseSchema and is being repaired.\n\
124 Return ONLY the corrected JSON. No prose, no explanation, no Markdown code fence.\n\n\
125 ## Original task\n\n{original_prompt}\n\n\
126 ## responseSchema the reply must satisfy\n\n```json\n{schema_text}\n```\n\n\
127 ## Your previous reply (it failed)\n\n```\n{failed_raw}\n```\n\n\
128 ## Why it failed\n\n{}\n\n\
129 Resend the reply as corrected JSON only.",
130 error.message(),
131 )
132 }
133
134 /// If the whole reply is wrapped in one Markdown code fence (``` or ```json),
135 /// return the fenced body; otherwise return the trimmed reply unchanged.
136 fn strip_code_fence(text: &str) -> &str {
137 let trimmed = text.trim();
138 let Some(rest) = trimmed.strip_prefix("```") else {
139 return trimmed;
140 };
141 let Some(body) = rest.strip_suffix("```") else {
142 return trimmed;
143 };
144 // Drop an optional language tag on the opening fence line.
145 match body.split_once('\n') {
146 Some((first_line, tail)) if !first_line.trim().is_empty() => tail.trim(),
147 _ => body.trim(),
148 }
149 }
150
151 #[cfg(test)]
152 mod tests {
153 use super::*;
154 use serde_json::json;
155
156 fn validator() -> jsonschema::Validator {
157 compile_schema(
158 "task(): responseSchema",
159 &json!({
160 "type": "object",
161 "properties": { "refuted": { "type": "boolean" } },
162 "required": ["refuted"],
163 }),
164 )
165 .expect("schema compiles")
166 }
167
168 #[test]
169 fn decodes_plain_json() {
170 let value = decode_reply(
171 "task(): responseSchema",
172 r#"{"refuted": true}"#,
173 &validator(),
174 )
175 .unwrap();
176 assert_eq!(value, json!({"refuted": true}));
177 }
178
179 #[test]
180 fn decodes_fenced_json() {
181 let text = "```json\n{\"refuted\": false}\n```";
182 let value = decode_reply("task(): responseSchema", text, &validator()).unwrap();
183 assert_eq!(value, json!({"refuted": false}));
184 }
185
186 #[test]
187 fn rejects_non_json_with_the_parse_kind() {
188 let err = decode_reply(
189 "task(): responseSchema",
190 "definitely not json",
191 &validator(),
192 )
193 .unwrap_err();
194 assert_eq!(err.kind(), "json_parse");
195 assert!(
196 err.message().contains("not valid JSON"),
197 "{}",
198 err.message()
199 );
200 }
201
202 #[test]
203 fn rejects_schema_violation_with_the_validation_kind() {
204 let err = decode_reply(
205 "task(): responseSchema",
206 r#"{"refuted": "yes"}"#,
207 &validator(),
208 )
209 .unwrap_err();
210 assert_eq!(err.kind(), "schema_validation");
211 assert!(
212 err.message().contains("responseSchema validation"),
213 "{}",
214 err.message()
215 );
216 }
217
218 #[test]
219 fn rejects_invalid_schema_before_spawn() {
220 let err =
221 compile_schema("task(): responseSchema", &json!({"type": "not-a-type"})).unwrap_err();
222 assert!(err.contains("invalid schema"), "{err}");
223 }
224
225 #[test]
226 fn carried_raw_passes_short_text_through() {
227 let (carried, truncated) = carried_raw("short");
228 assert_eq!(carried, "short");
229 assert!(!truncated);
230 }
231
232 #[test]
233 fn carried_raw_caps_long_text_on_a_char_boundary() {
234 let text = "é".repeat(SCHEMA_RAW_CARRY_CHARS + 10);
235 let (carried, truncated) = carried_raw(&text);
236 assert!(truncated);
237 assert!(carried.ends_with("chars not carried]"));
238 // The cap is honored in chars: exactly SCHEMA_RAW_CARRY_CHARS kept,
239 // with the marker appended as its own line.
240 let kept = carried.lines().next().unwrap_or_default();
241 assert_eq!(kept.chars().count(), SCHEMA_RAW_CARRY_CHARS);
242 }
243
244 #[test]
245 fn repair_prompt_carries_task_schema_reply_and_reason() {
246 let error = ReplyDecodeError::Parse(
247 "task(): responseSchema was set but the reply is not valid JSON: expected value"
248 .to_string(),
249 );
250 let prompt = repair_prompt(
251 "Score the diff.",
252 &json!({"type": "object"}),
253 "Sure! Here it is: {...}",
254 &error,
255 );
256 assert!(prompt.contains("Score the diff."));
257 assert!(prompt.contains("\"type\": \"object\""));
258 assert!(prompt.contains("Sure! Here it is: {...}"));
259 assert!(prompt.contains("not valid JSON"));
260 assert!(prompt.contains("corrected JSON only"));
261 }
262 }
263
263 lines RUST