Skip to main content

speccoder_runtime/substrate/
converge.rs

1//! `speccoder.feature.converge`: assess a feature's code against its spec,
2//! plan and tasks, read-only.
3//!
4//! The model may only read; it returns structured findings. speccoder — not
5//! the model — turns actionable findings into a `## Phase N: Convergence`
6//! section, appended behind a prefix guard. `unrequested` findings go to a
7//! person and are never turned into tasks.
8
9use crate::format::Wording;
10use agentplane::prelude::*;
11use serde_json::{Value, json};
12
13use super::attempt::{LoopSpec, tool_loop};
14use super::model_config::{CacheTtl, PromptStyle};
15use crate::tools::policy::Policy;
16
17/// The capability the skill provides.
18pub const CAPABILITY: &str = "speccoder.feature.converge";
19
20/// The tools converge may use: reading only.
21pub const READ_ONLY: [&str; 5] = [
22    "read_file",
23    "list_files",
24    "search_code",
25    "git_status",
26    "git_diff",
27];
28
29/// What the assessor is told (after Spec Kit's converge command).
30pub fn policy(w: &Wording) -> String {
31    format!(
32        "You are the convergence step of speccoder. Assess the CURRENT code of a {product} \
33{unit} against its {documents} — the sole source of intent — with {rules} as \
34governing constraints. Ticked tasks are not evidence: read the code. You can only read \
35(read_file, list_files, search_code, git_status, git_diff); you change nothing. For \
36every {targets}, report a finding only where there is a gap, classified as `missing` (absent), \
37`partial` (exists but does not fully satisfy), `contradicts` (conflicts with stated \
38intent or {must}) or `unrequested` (code that exists although the {sources} \
39do not call for it). A requirement or rule the code does not meet is \
40ALWAYS missing, partial or contradicts — never unrequested. Severity: CRITICAL \
41({critical}), HIGH \
42(missing/partial on a core requirement), MEDIUM, LOW. For each finding give `task`: one \
43imperative sentence that a coding agent can complete (no task ID, no checkbox, no file \
44contents), `source_ref` (e.g. {refs}), and \
45`evidence` (the file or area you observed). Do not report what is already satisfied; do \
46not invent requirements. If nothing remains, return no findings. Finish with the \
47requested structured answer.",
48        product = w.product,
49        unit = w.unit,
50        documents = w.documents,
51        rules = w.assess.rules,
52        targets = w.assess.targets,
53        must = w.assess.must,
54        sources = w.assess.sources,
55        critical = w.assess.critical,
56        refs = w.assess.refs,
57    )
58}
59
60/// The answer's schema.
61#[must_use]
62pub fn schema() -> Value {
63    super::answers::schema::<super::answers::Assessment>()
64}
65
66/// The run input: the feature's artifacts and limits — everything the
67/// skill's decisions depend on, journaled.
68#[must_use]
69pub fn input(
70    feature: &str,
71    artifacts: [&str; 4], // constitution, spec, plan, tasks
72    files: &[String],
73    changed: &[String],
74    max_turns: u32,
75    max_tool_calls: u32,
76) -> Tainted<Value> {
77    let [constitution, spec, plan, tasks] = artifacts;
78    // The artifacts are the person's; the file list is the worktree's.
79    let mut fields = vec![
80        ("feature", Tainted::trusted(json!(feature))),
81        ("constitution", Tainted::trusted(json!(constitution))),
82        ("spec", Tainted::trusted(json!(spec))),
83        ("plan", Tainted::trusted(json!(plan))),
84        ("tasks", Tainted::trusted(json!(tasks))),
85        (
86            "files",
87            Tainted::with_label(
88                json!(files),
89                super::provenance::from(super::provenance::WORKTREE),
90            ),
91        ),
92        (
93            "settings",
94            Tainted::trusted(json!({ "max_turns": max_turns, "max_tool_calls": max_tool_calls })),
95        ),
96    ];
97    // Requirements reworded since the ticks that cite them: the
98    // spec's own lines, then and now. Absent when nothing changed, so an
99    // assessment without drift is the one it always was.
100    if !changed.is_empty() {
101        fields.push(("changed", Tainted::trusted(json!(changed))));
102    }
103    Tainted::object(fields)
104}
105
106fn prompt_raw(input: &Value, ttl: CacheTtl, style: PromptStyle, w: &Wording) -> Value {
107    let system_policy = policy(w);
108    let text = |key: &str| {
109        let t = input[key].as_str().unwrap_or_default();
110        if t.trim().is_empty() {
111            "(none)".to_owned()
112        } else {
113            t.to_owned()
114        }
115    };
116    let files = input["files"]
117        .as_array()
118        .map(|f| {
119            f.iter()
120                .filter_map(Value::as_str)
121                .collect::<Vec<_>>()
122                .join("\n")
123        })
124        .unwrap_or_default();
125    let feature = input["feature"].as_str().unwrap_or_default();
126    let mut parts = vec![
127        format!("# {} ({feature})\n\n{}", w.files[0], text("spec")),
128        format!("# {}\n\n{}", w.files[1], text("plan")),
129        format!("# {}\n\n{}", w.files[2], text("tasks")),
130        format!("# Project files\n\n{files}"),
131    ];
132    if let Some(changed) = input["changed"].as_array().filter(|c| !c.is_empty()) {
133        let lines: Vec<&str> = changed.iter().filter_map(Value::as_str).collect();
134        parts.push(format!(
135            "# Changed since their tasks were verified\n\nThese requirements were reworded, added or removed after the tasks citing them were ticked: the code was judged against the earlier wording. Assess each against the wording now; a gap is `partial` or `contradicts`.\n\n{}",
136            lines.join("\n")
137        ));
138    }
139    let system = format!(
140        "{system_policy}\n\n# {}\n\n{}",
141        w.constitution,
142        text("constitution")
143    );
144    match style {
145        PromptStyle::OpenAi => json!({
146            "system": system,
147            "input": [{ "role": "user", "content": parts.iter().map(|t| json!({ "type": "input_text", "text": t })).collect::<Vec<_>>() }],
148        }),
149        PromptStyle::Anthropic | PromptStyle::Chat | PromptStyle::Parts { .. } => {
150            let breakpoint = match ttl {
151                CacheTtl::FiveMinutes => json!({ "type": "ephemeral" }),
152                CacheTtl::OneHour => json!({ "type": "ephemeral", "ttl": "1h" }),
153            };
154            let content: Vec<Value> = parts
155                .iter()
156                .enumerate()
157                .map(|(i, t)| {
158                    if i == 1 {
159                        json!({ "type": "text", "text": t, "cache_control": breakpoint })
160                    } else {
161                        json!({ "type": "text", "text": t })
162                    }
163                })
164                .collect();
165            json!({
166                "system": system,
167                "messages": [{ "role": "user", "content": content }],
168            })
169        }
170    }
171}
172
173fn prompt(input: &Value, ttl: CacheTtl, style: PromptStyle, w: &Wording) -> Value {
174    let mut out = prompt_raw(input, ttl, style, w);
175    if style == PromptStyle::Chat {
176        super::model_config::strip_cache_control(&mut out);
177    }
178    if let PromptStyle::Parts { caches } = style {
179        super::model_config::to_parts(&mut out, caches);
180    }
181    out
182}
183
184/// The coded skill.
185#[derive(Debug)]
186pub struct Converge {
187    /// Prompt dialect.
188    pub style: PromptStyle,
189    /// Cache breakpoint lifetime.
190    pub cache_ttl: CacheTtl,
191    /// The project's spec format.
192    pub format: &'static dyn crate::format::Adapter,
193}
194
195#[async_trait]
196impl Skill for Converge {
197    fn descriptor(&self) -> SkillDescriptor {
198        SkillDescriptor::new("speccoder.feature.converge").provides(CAPABILITY)
199    }
200
201    async fn invoke(
202        &self,
203        cx: &mut StepCtx<'_>,
204        input: Tainted<Value>,
205    ) -> Result<Outcome, SkillError> {
206        let (ttl, style) = (self.cache_ttl, self.style);
207        let settings = input.peek()["settings"].clone();
208        let limit = |key: &str, default: u32| {
209            settings[key]
210                .as_u64()
211                .map_or(default, |n| u32::try_from(n).unwrap_or(u32::MAX))
212        };
213        let prompt = super::provenance::labelled_prompt(
214            prompt(input.peek(), ttl, style, self.format.wording()),
215            &super::provenance::from(super::provenance::WORKTREE),
216        );
217        let tools = crate::tools::declarations()
218            .into_iter()
219            .filter(|d| READ_ONLY.contains(&d.name.as_str()))
220            .collect();
221        tool_loop(
222            cx,
223            &prompt,
224            LoopSpec {
225                // The account is shown for attempts; these read as documents.
226                reasoning: false,
227                tools,
228                policy: Policy::new(&[], &[]).rules(self.format.rules()),
229                max_turns: limit("max_turns", 30).max(1),
230                max_tool_calls: limit("max_tool_calls", 100),
231                schema: Some(schema()),
232                max_tokens: None,
233                left: None,
234                reads: None,
235                halt: None,
236                ask: None,
237                run_approved: Vec::new(),
238                once: Vec::new(),
239                run: None,
240                asking: super::attempt::Asking::default(),
241                parts: Vec::new(),
242                mcp_digests: std::collections::BTreeMap::new(),
243                stop: super::attempt::StopGate::default(),
244                observer: None,
245                routes: Vec::new(),
246                root: None,
247                frozen_additions: false,
248                finish: |_| "completed",
249            },
250        )
251        .await
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    fn text(input: &Tainted<Value>) -> String {
260        use crate::format::Adapter as _;
261        let w = crate::format::speckit::SpecKit.wording();
262        prompt(
263            input.peek(),
264            CacheTtl::FiveMinutes,
265            PromptStyle::Anthropic,
266            w,
267        )
268        .to_string()
269    }
270
271    #[test]
272    fn changed_requirements_reach_the_assessment_only_when_there_are_some() {
273        let artifacts = ["c", "spec", "plan", "tasks"];
274        let none = input("001-x", artifacts, &[], &[], 10, 20);
275        assert!(none.peek().get("changed").is_none());
276        assert!(!text(&none).contains("Changed since their tasks were verified"));
277        let changed = vec!["- T004 FR-001: was \"password\"; now \"passkey\"".to_owned()];
278        let some = input("001-x", artifacts, &[], &changed, 10, 20);
279        let t = text(&some);
280        assert!(t.contains("Changed since their tasks were verified"), "{t}");
281        assert!(t.contains("T004 FR-001"), "{t}");
282    }
283}