speccoder_runtime/substrate/
propose.rs1use crate::format::{Adapter, Wording};
5use agentplane::prelude::*;
6use serde_json::{Value, json};
7
8use super::model_config::{CacheTtl, PromptStyle};
9
10pub const CAPABILITY: &str = "speccoder.task.propose";
12
13pub fn policy(w: &Wording) -> String {
16 format!(
17 "You are the planning step of speccoder, a coding agent that executes \
18{product} tasks. Propose how to implement exactly one task. You cannot run tools in this \
19step and nothing you write is executed: a deterministic engine decides what happens, and \
20verification evidence — not your claims — decides when a task is done. Stay inside the task's \
21scope; name the files you expect to touch and the checks that would show the task works; say \
22what is unclear or risky instead of guessing. Answer only in the requested structure.",
23 product = w.product
24 )
25}
26
27#[must_use]
29pub fn schema() -> Value {
30 let strings = json!({ "type": "array", "items": { "type": "string" } });
31 json!({
32 "type": "object",
33 "properties": {
34 "summary": { "type": "string" },
35 "steps": strings,
36 "files": strings,
37 "checks": strings,
38 "risks": strings,
39 },
40 "required": ["summary", "steps", "files", "checks", "risks"],
41 "additionalProperties": false,
42 })
43}
44
45fn breakpoint(ttl: CacheTtl) -> Value {
46 match ttl {
47 CacheTtl::FiveMinutes => json!({ "type": "ephemeral" }),
48 CacheTtl::OneHour => json!({ "type": "ephemeral", "ttl": "1h" }),
49 }
50}
51
52#[must_use]
59pub fn layout(
60 bundle: &Value,
61 ttl: CacheTtl,
62 style: PromptStyle,
63 policy: &str,
64 format: &dyn Adapter,
65) -> Value {
66 let text = |key: &str| bundle[key].as_str().unwrap_or_default().to_owned();
67 let task = &bundle["task"];
68 let mut task_text = format!(
69 "# Task {}\n\n{}\n\nPhase: {}\n",
70 task["id"].as_str().unwrap_or_default(),
71 task["title"].as_str().unwrap_or_default(),
72 task["phase"].as_str().unwrap_or_default(),
73 );
74 for (key, label) in [("subsection", "Subsection"), ("story", "Story")] {
75 if let Some(v) = task[key].as_str().filter(|v| !v.is_empty()) {
76 task_text.push_str(&format!("{label}: {v}\n"));
77 }
78 }
79 if task["parallel"].as_bool() == Some(true) {
80 task_text.push_str("Marked [P]: may run in parallel with other [P] tasks.\n");
81 }
82 if let Some(deps) = bundle["dependencies"].as_array().filter(|d| !d.is_empty()) {
83 task_text.push_str("\nDepends on:\n");
84 for d in deps {
85 let mark = if d["done"].as_bool() == Some(true) {
86 "x"
87 } else {
88 " "
89 };
90 task_text.push_str(&format!(
91 "- [{mark}] {} {}\n",
92 d["id"].as_str().unwrap_or_default(),
93 d["title"].as_str().unwrap_or_default()
94 ));
95 }
96 }
97
98 let w = format.wording();
99 let constitution = format!("# {}\n\n{}", w.constitution, or_none(&text("constitution")));
100 let plan = format!(
101 "# {} ({})\n\n{}",
102 w.plan,
103 text("feature"),
104 or_none(&text("plan"))
105 );
106 let story = text("story");
107 let heading = if format.is_convergence(task["phase"].as_str().unwrap_or_default()) {
108 "# Specification (this task closes a gap found against it)".to_owned()
109 } else {
110 format!("# {}", format.wording().story)
111 };
112 let story = (!story.is_empty()).then(|| format!("{heading}\n\n{story}"));
113
114 if style == PromptStyle::OpenAi {
115 let mut parts = vec![plan];
116 parts.extend(story);
117 parts.push(task_text);
118 let content: Vec<Value> = parts
119 .into_iter()
120 .map(|t| json!({ "type": "input_text", "text": t }))
121 .collect();
122 return json!({
123 "system": format!("{policy}\n\n{constitution}"),
124 "input": [ { "role": "user", "content": content } ],
125 });
126 }
127
128 let mut user = vec![json!({
129 "type": "text",
130 "text": plan,
131 "cache_control": breakpoint(ttl),
132 })];
133 if let Some(story) = story {
134 user.push(json!({ "type": "text", "text": story }));
135 }
136 user.push(json!({ "type": "text", "text": task_text }));
137
138 let mut out = json!({
139 "system": [
140 { "type": "text", "text": policy },
141 { "type": "text", "text": constitution, "cache_control": breakpoint(ttl) },
142 ],
143 "messages": [ { "role": "user", "content": user } ],
144 });
145 if style == PromptStyle::Chat {
146 super::model_config::strip_cache_control(&mut out);
147 }
148 out
149}
150
151fn or_none(s: &str) -> &str {
152 if s.trim().is_empty() { "(none)" } else { s }
153}
154
155#[derive(Debug)]
157pub struct Propose {
158 pub cache_ttl: CacheTtl,
160 pub style: PromptStyle,
162 pub format: &'static dyn Adapter,
164}
165
166#[async_trait]
167impl Skill for Propose {
168 fn descriptor(&self) -> SkillDescriptor {
169 SkillDescriptor::new("speccoder.task.propose").provides(CAPABILITY)
170 }
171
172 async fn invoke(
173 &self,
174 cx: &mut StepCtx<'_>,
175 input: Tainted<Value>,
176 ) -> Result<Outcome, SkillError> {
177 let (ttl, style) = (self.cache_ttl, self.style);
178 let policy = policy(self.format.wording());
179 let prompt = input.map(|bundle| {
180 let mut p = layout(&bundle, ttl, style, &policy, self.format);
181 if let PromptStyle::Parts { caches } = style {
182 super::model_config::to_parts(&mut p, caches);
183 }
184 p
185 });
186 let completion = cx
187 .complete_with(&prompt, |call| call.expecting(schema()))
188 .await?;
189 Ok(Outcome::done(completion.map(|c| {
190 json!({
191 "proposal": c.structured,
192 "text": c.text,
193 "usage": serde_json::to_value(c.usage).unwrap_or(Value::Null),
194 })
195 })))
196 }
197}