Skip to main content

speccoder_runtime/substrate/
propose.rs

1//! `speccoder.task.propose`: one governed model call that proposes how to do
2//! a task. The answer is recorded, never executed.
3
4use crate::format::{Adapter, Wording};
5use agentplane::prelude::*;
6use serde_json::{Value, json};
7
8use super::model_config::{CacheTtl, PromptStyle};
9
10/// The capability the skill provides.
11pub const CAPABILITY: &str = "speccoder.task.propose";
12
13/// What speccoder tells every model call first. Stable across tasks, so it
14/// sits inside the cached prefix.
15pub 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/// The proposal's JSON schema.
28#[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/// The prompt for a bundle (the run's input `{bundle, cache_ttl}`).
53///
54/// Order is stability order: policy and constitution (identical for the whole
55/// project), then the plan (identical for the feature), then the task. A
56/// breakpoint closes each stable part.
57#[must_use]
58pub fn layout(
59    bundle: &Value,
60    ttl: CacheTtl,
61    style: PromptStyle,
62    policy: &str,
63    format: &dyn Adapter,
64) -> Value {
65    let text = |key: &str| bundle[key].as_str().unwrap_or_default().to_owned();
66    let task = &bundle["task"];
67    let mut task_text = format!(
68        "# Task {}\n\n{}\n\nPhase: {}\n",
69        task["id"].as_str().unwrap_or_default(),
70        task["title"].as_str().unwrap_or_default(),
71        task["phase"].as_str().unwrap_or_default(),
72    );
73    for (key, label) in [("subsection", "Subsection"), ("story", "Story")] {
74        if let Some(v) = task[key].as_str().filter(|v| !v.is_empty()) {
75            task_text.push_str(&format!("{label}: {v}\n"));
76        }
77    }
78    if task["parallel"].as_bool() == Some(true) {
79        task_text.push_str("Marked [P]: may run in parallel with other [P] tasks.\n");
80    }
81    if let Some(deps) = bundle["dependencies"].as_array().filter(|d| !d.is_empty()) {
82        task_text.push_str("\nDepends on:\n");
83        for d in deps {
84            let mark = if d["done"].as_bool() == Some(true) {
85                "x"
86            } else {
87                " "
88            };
89            task_text.push_str(&format!(
90                "- [{mark}] {} {}\n",
91                d["id"].as_str().unwrap_or_default(),
92                d["title"].as_str().unwrap_or_default()
93            ));
94        }
95    }
96
97    let w = format.wording();
98    let constitution = format!("# {}\n\n{}", w.constitution, or_none(&text("constitution")));
99    let plan = format!(
100        "# {} ({})\n\n{}",
101        w.plan,
102        text("feature"),
103        or_none(&text("plan"))
104    );
105    let story = text("story");
106    let heading = if format.is_convergence(task["phase"].as_str().unwrap_or_default()) {
107        "# Specification (this task closes a gap found against it)".to_owned()
108    } else {
109        format!("# {}", format.wording().story)
110    };
111    let story = (!story.is_empty()).then(|| format!("{heading}\n\n{story}"));
112
113    if style == PromptStyle::OpenAi {
114        let mut parts = vec![plan];
115        parts.extend(story);
116        parts.push(task_text);
117        let content: Vec<Value> = parts
118            .into_iter()
119            .map(|t| json!({ "type": "input_text", "text": t }))
120            .collect();
121        return json!({
122            "system": format!("{policy}\n\n{constitution}"),
123            "input": [ { "role": "user", "content": content } ],
124        });
125    }
126
127    let mut user = vec![json!({
128        "type": "text",
129        "text": plan,
130        "cache_control": breakpoint(ttl),
131    })];
132    if let Some(story) = story {
133        user.push(json!({ "type": "text", "text": story }));
134    }
135    user.push(json!({ "type": "text", "text": task_text }));
136
137    let mut out = json!({
138        "system": [
139            { "type": "text", "text": policy },
140            { "type": "text", "text": constitution, "cache_control": breakpoint(ttl) },
141        ],
142        "messages": [ { "role": "user", "content": user } ],
143    });
144    if style == PromptStyle::Chat {
145        super::model_config::strip_cache_control(&mut out);
146    }
147    out
148}
149
150fn or_none(s: &str) -> &str {
151    if s.trim().is_empty() { "(none)" } else { s }
152}
153
154/// The coded skill.
155#[derive(Debug)]
156pub struct Propose {
157    /// Lifetime of the prompt's cache breakpoints.
158    pub cache_ttl: CacheTtl,
159    /// The provider's prompt dialect.
160    pub style: PromptStyle,
161    /// The project's spec format.
162    pub format: &'static dyn Adapter,
163}
164
165#[async_trait]
166impl Skill for Propose {
167    fn descriptor(&self) -> SkillDescriptor {
168        SkillDescriptor::new("speccoder.task.propose").provides(CAPABILITY)
169    }
170
171    async fn invoke(
172        &self,
173        cx: &mut StepCtx<'_>,
174        input: Tainted<Value>,
175    ) -> Result<Outcome, SkillError> {
176        let (ttl, style) = (self.cache_ttl, self.style);
177        let policy = policy(self.format.wording());
178        let prompt = input.map(|bundle| layout(&bundle, ttl, style, &policy, self.format));
179        let completion = cx
180            .complete_with(&prompt, |call| call.expecting(schema()))
181            .await?;
182        Ok(Outcome::done(completion.map(|c| {
183            json!({
184                "proposal": c.structured,
185                "text": c.text,
186                "usage": serde_json::to_value(c.usage).unwrap_or(Value::Null),
187            })
188        })))
189    }
190}