返回 CodeWhale
plan_schema.rs
根目录 / crates / engine / src / tools / workflow / plan_schema.rs
1 //! Replaces the bare `WorkflowTool.plan` object with a provider-facing schema
2 //! for the common structured Workflow launch path.
3
4 use serde_json::{Value, json};
5
6 /// Keep this shape aligned with `StructuredWorkflowPlan`, `StructuredPlanPhase`,
7 /// `StructuredPlanChild`, and `GateSpec`. The runtime's legacy aliases and IR
8 /// parser remain available; the advertised path needs no JavaScript authoring.
9 pub(super) fn structured_plan_schema() -> Value {
10 let child = json!({
11 "type": "object",
12 "properties": {
13 "id": {
14 "type": "string",
15 "description": "Stable child id. Defaults to label, then a generated phase-local id."
16 },
17 "label": {
18 "type": "string",
19 "description": "Short child label, also used as its id when id is absent."
20 },
21 "prompt": {
22 "type": "string",
23 "minLength": 1,
24 "description": "Concrete assignment and expected result for this child."
25 },
26 "type": {
27 "type": "string",
28 "enum": ["general", "explore", "planner", "reviewer", "implement", "test"],
29 "description": "Optional worker type. Prefer role/profile for Fleet steps; do not combine them with a conflicting type. Legacy type aliases remain accepted by the runtime."
30 },
31 "role": {
32 "type": "string",
33 "description": "Fleet role name. The Fleet supplies its route and authority."
34 },
35 "profile": {
36 "type": "string",
37 "description": "Worker profile name, resolved with the selected Fleet and caller policy."
38 },
39 "model": {
40 "type": "string",
41 "description": "Optional model selector from agent(action=roster)'s saved shortlist. Omit to use the selected role/profile route. Exact Fleets fix each member's model, so select the member instead of overriding it."
42 },
43 "mode": {
44 "type": "string",
45 "enum": ["read_only", "read_write"],
46 "description": "Requested child mode. Defaults to the plan risk; it cannot increase caller authority."
47 },
48 "file_scope": {
49 "type": "array",
50 "items": { "type": "string" },
51 "description": "Workspace-relative file scopes for this child. Use [] when no narrower scope is requested."
52 },
53 "cwd": {
54 "type": "string",
55 "description": "Optional repository-relative working directory for this child. Required in multi-repository workspaces so the child (and worktree isolation) resolves the right repository."
56 }
57 },
58 "required": ["prompt", "file_scope"],
59 "additionalProperties": false
60 });
61 let phase = json!({
62 "type": "object",
63 "properties": {
64 "id": {
65 "type": "string",
66 "description": "Stable phase id. Defaults to title, then a generated phase id."
67 },
68 "title": {
69 "type": "string",
70 "description": "Short phase title."
71 },
72 "parallel": {
73 "type": "boolean",
74 "description": "Run independent children concurrently. Defaults to true for multiple children; use false when they depend on each other."
75 },
76 "children": {
77 "type": "array",
78 "minItems": 1,
79 "items": child.clone(),
80 "description": "At least one child. Phases run in order and receive prior-phase results; missing required results skip dependent steps while independent work continues."
81 }
82 },
83 "required": ["children"],
84 "additionalProperties": false
85 });
86 let gate = json!({
87 "type": "object",
88 "properties": {
89 "id": { "type": "string" },
90 "role": {
91 "type": "string",
92 "description": "Role whose lifecycle triggers this gate."
93 },
94 "on": {
95 "type": "string",
96 "enum": ["role_complete"]
97 },
98 "gate": {
99 "type": "string",
100 "enum": ["verify", "review", "approve"]
101 },
102 "on_fail": {
103 "type": "string",
104 "enum": ["retry", "block", "escalate"]
105 },
106 "blocks_role": {
107 "type": "string",
108 "description": "Downstream role blocked until the gate passes."
109 },
110 "max_retries": {
111 "type": "integer",
112 "minimum": 0,
113 "maximum": u32::MAX,
114 "default": 1,
115 "description": "Maximum retries before escalation. Use 1 for the runtime default."
116 },
117 "artifact_kind": {
118 "type": "string",
119 "description": "Optional handoff artifact kind, such as findings or verify_report."
120 },
121 "require_explicit_verdict": {
122 "type": "boolean",
123 "default": false,
124 "description": "Require a standalone first-line PASS, APPROVE, BLOCK, or FAIL verdict. False preserves completion-based gate evaluation."
125 }
126 },
127 "required": ["id", "role", "on", "gate", "on_fail", "max_retries", "require_explicit_verdict"],
128 "additionalProperties": false
129 });
130
131 // Strict providers require every property and make optional properties
132 // nullable. Serde's default Vec/bool/u32 fields accept omission but reject
133 // null, so advertise their concrete empty/default values as required.
134 json!({
135 "type": "object",
136 "description": "Structured Workflow plan. Provide goal and either ordered phases or parallel top-level children; use [] for unused collections. No JavaScript is required. Role/profile steps use the selected Fleet. Advanced Workflow IR remains available through script/source_path.",
137 "properties": {
138 "goal": {
139 "type": "string",
140 "minLength": 1,
141 "description": "Non-empty goal for the complete workflow."
142 },
143 "risk": {
144 "type": "string",
145 "enum": ["read_only", "writes", "elevated"],
146 "description": "Plan risk and default child mode. Defaults to read_only; writes/elevated remain subject to approval and caller policy."
147 },
148 "phases": {
149 "type": "array",
150 "items": phase,
151 "description": "Ordered phases with prior-result handoff. Use [] for a flat children plan."
152 },
153 "children": {
154 "type": "array",
155 "items": child,
156 "description": "Independent children run in parallel when phases is empty. Use [] when phases are provided."
157 },
158 "gates": {
159 "type": "array",
160 "items": gate,
161 "description": "Role lifecycle gates. Use [] when no additional gates are needed."
162 }
163 },
164 "required": ["goal", "phases", "children", "gates"],
165 "additionalProperties": false
166 })
167 }
168
169 #[cfg(test)]
170 mod tests {
171 use super::structured_plan_schema;
172 use codewhale_models::schema_sanitize::{sanitize, sanitize_for_strict};
173 use serde_json::{Value, json};
174
175 fn property_names(schema: &Value) -> Vec<&str> {
176 let mut names = schema["properties"]
177 .as_object()
178 .expect("explicit object properties")
179 .keys()
180 .map(String::as_str)
181 .collect::<Vec<_>>();
182 names.sort_unstable();
183 names
184 }
185
186 fn assert_strict_objects(schema: &Value) {
187 if schema["type"] == "object" {
188 let names = property_names(schema);
189 assert!(
190 !names.is_empty(),
191 "a closed empty object cannot carry a plan"
192 );
193 assert_eq!(schema["additionalProperties"], false);
194 let required = schema["required"].as_array().expect("required properties");
195 assert_eq!(required.len(), names.len());
196 for name in names {
197 assert!(required.contains(&json!(name)), "missing required {name}");
198 }
199 }
200 match schema {
201 Value::Object(object) => {
202 for value in object.values() {
203 assert_strict_objects(value);
204 }
205 }
206 Value::Array(array) => {
207 for value in array {
208 assert_strict_objects(value);
209 }
210 }
211 _ => {}
212 }
213 }
214
215 #[test]
216 fn structured_plan_properties_survive_general_and_strict_sanitizers() {
217 let mut schema = structured_plan_schema();
218 let original = schema.clone();
219 sanitize(&mut schema);
220 assert_eq!(schema, original);
221 sanitize_for_strict(&mut schema);
222
223 assert_eq!(
224 property_names(&schema),
225 ["children", "gates", "goal", "phases", "risk"]
226 );
227 let phase = &schema["properties"]["phases"]["items"];
228 assert_eq!(
229 property_names(phase),
230 ["children", "id", "parallel", "title"]
231 );
232 let child = &phase["properties"]["children"]["items"];
233 assert_eq!(
234 property_names(child),
235 [
236 "cwd",
237 "file_scope",
238 "id",
239 "label",
240 "mode",
241 "model",
242 "profile",
243 "prompt",
244 "role",
245 "type"
246 ]
247 );
248 assert_eq!(child, &schema["properties"]["children"]["items"]);
249 assert_strict_objects(&schema);
250 }
251
252 #[test]
253 fn strict_plan_only_marks_actual_option_fields_nullable() {
254 let mut schema = structured_plan_schema();
255 sanitize_for_strict(&mut schema);
256 let phase = &schema["properties"]["phases"]["items"];
257 let child = &phase["properties"]["children"]["items"];
258 let gate = &schema["properties"]["gates"]["items"];
259
260 for (object, names) in [
261 (&schema, &["goal", "phases", "children", "gates"][..]),
262 (phase, &["children"][..]),
263 (child, &["prompt", "file_scope"][..]),
264 (
265 gate,
266 &[
267 "id",
268 "role",
269 "on",
270 "gate",
271 "on_fail",
272 "max_retries",
273 "require_explicit_verdict",
274 ][..],
275 ),
276 ] {
277 for name in names {
278 assert!(
279 object["properties"][name].get("nullable").is_none(),
280 "{name} rejects null at runtime"
281 );
282 }
283 }
284 for (object, names) in [
285 (&schema, &["risk"][..]),
286 (phase, &["id", "title", "parallel"][..]),
287 (
288 child,
289 &["id", "label", "type", "role", "profile", "model", "mode"][..],
290 ),
291 (gate, &["blocks_role", "artifact_kind"][..]),
292 ] {
293 for name in names {
294 assert_eq!(
295 object["properties"][name]["nullable"], true,
296 "{name} is an Option at runtime"
297 );
298 }
299 }
300 }
301
302 #[test]
303 fn strict_shaped_plan_with_null_options_lowers_without_javascript_authoring() {
304 let plan = json!({
305 "goal": "Inspect the release receipts",
306 "risk": null,
307 "phases": [{
308 "id": null,
309 "title": null,
310 "parallel": null,
311 "children": [{
312 "id": null,
313 "label": null,
314 "prompt": "Read the existing receipts and report missing evidence.",
315 "type": null,
316 "role": null,
317 "profile": null,
318 "model": null,
319 "mode": null,
320 "file_scope": []
321 }]
322 }],
323 "children": [],
324 "gates": [{
325 "id": "review",
326 "role": "reviewer",
327 "on": "role_complete",
328 "gate": "review",
329 "on_fail": "block",
330 "blocks_role": null,
331 "max_retries": 1,
332 "artifact_kind": null,
333 "require_explicit_verdict": false
334 }]
335 });
336 let spec = super::super::structured_plan_to_workflow_spec(&plan)
337 .expect("strict provider values match runtime types");
338 assert_eq!(spec.goal, "Inspect the release receipts");
339 assert_eq!(spec.nodes.len(), 1);
340 assert_eq!(spec.gates.len(), 1);
341 assert_eq!(spec.gates[0].max_retries, 1);
342 let source = super::super::workflow_source_from_plan(&plan)
343 .expect("ordinary plans lower without caller-authored JavaScript");
344 assert!(source.spec.is_some());
345 assert!(!source.source.is_empty());
346 }
347
348 #[test]
349 fn typed_gate_schema_matches_serialized_gate_spec() {
350 let gate: codewhale_workflow::GateSpec = serde_json::from_value(json!({
351 "id": "verify",
352 "role": "verifier",
353 "on": "role_complete",
354 "gate": "verify",
355 "on_fail": "retry",
356 "blocks_role": "builder",
357 "max_retries": 2,
358 "artifact_kind": "verify_report",
359 "require_explicit_verdict": true
360 }))
361 .expect("existing GateSpec fields");
362 let serialized = serde_json::to_value(gate).expect("serialize gate");
363 let schema = structured_plan_schema();
364 let fields = property_names(&schema["properties"]["gates"]["items"]);
365 let mut serialized_fields = serialized
366 .as_object()
367 .expect("gate object")
368 .keys()
369 .map(String::as_str)
370 .collect::<Vec<_>>();
371 serialized_fields.sort_unstable();
372 assert_eq!(fields, serialized_fields);
373 }
374
375 #[test]
376 fn schema_does_not_remove_legacy_runtime_child_aliases_or_defaults() {
377 let spec = super::super::structured_plan_to_workflow_spec(&json!({
378 "goal": "Inspect the workspace",
379 "risk": "safe",
380 "children": [{
381 "description": "Report the existing behavior.",
382 "agent_type": "explorer",
383 "mode": "readonly"
384 }]
385 }))
386 .expect("legacy aliases and omitted collections remain runtime-compatible");
387 assert_eq!(spec.nodes.len(), 1);
388 assert!(spec.gates.is_empty());
389 }
390 }
391
391 lines RUST