Skip to main content

speccoder_runtime/pipeline/
commit.rs

1//! Commit messages, trailers and the records a finished attempt leaves.
2
3use std::path::Path;
4
5use crate::{approvals, git, tools};
6
7/// The monitor's findings in one line: `kind: evidence; …`.
8pub(crate) fn monitor_summary(monitor: Option<&serde_json::Value>) -> String {
9    monitor
10        .and_then(|m| m["findings"].as_array())
11        .map(|f| {
12            f.iter()
13                .map(|x| {
14                    format!(
15                        "{}: {}",
16                        x["kind"].as_str().unwrap_or("other"),
17                        x["evidence"]
18                            .as_str()
19                            .unwrap_or_default()
20                            .split_whitespace()
21                            .collect::<Vec<_>>()
22                            .join(" ")
23                    )
24                })
25                .collect::<Vec<_>>()
26                .join("; ")
27        })
28        .filter(|s| !s.is_empty())
29        .unwrap_or_else(|| "no details given".to_owned())
30}
31
32/// Inline "for this task" approvals become task decisions of this run, as
33/// if made with `speccoder task approve`, so a retry or a later attempt of
34/// the run is not asked again — and a later run is.
35///
36/// # Errors
37///
38/// The decisions file cannot be read or written: the attempt's decisions
39/// are not recorded (later attempts ask again), and the caller says so.
40pub(crate) fn record_inline_approvals(
41    dir: &Path,
42    feature: &str,
43    task: &str,
44    calls: &[serde_json::Value],
45    run_grants: &std::sync::Mutex<Vec<tools::policy::Object>>,
46    run: &str,
47) -> Result<(), String> {
48    // Every decision a person made in this attempt, with who made it and how
49    // far it reaches; calls an earlier decision allowed (`*-grant`) are not
50    // new decisions.
51    let decided: Vec<approvals::Decided> = calls
52        .iter()
53        .filter(|c| c["approved_by"] == "person" || c["rejected_by"] == "person")
54        .filter(|c| !c["scope"].as_str().is_some_and(|s| s.ends_with("-grant")))
55        .filter_map(|c| {
56            let object: tools::policy::Object = serde_json::from_value(c["object"].clone()).ok()?;
57            let by = serde_json::from_value::<approvals::Who>(c["approver"].clone())
58                .unwrap_or_else(|_| approvals::Who {
59                    name: "unknown".to_owned(),
60                    via: "inline".to_owned(),
61                    client: None,
62                    basis: "asserted".to_owned(),
63                });
64            let approved = c["approved_by"] == "person";
65            Some(approvals::Decided {
66                verb: if approved { "approve" } else { "reject" }.to_owned(),
67                object: Some(object),
68                run: Some(run.to_owned()),
69                reason: c["rejection"].as_str().map(str::to_owned),
70                scope: c["scope"].as_str().unwrap_or("once").to_owned(),
71                note: c["note"].as_str().map(str::to_owned),
72                by,
73                at: std::time::SystemTime::now()
74                    .duration_since(std::time::UNIX_EPOCH)
75                    .map_or(0, |d| d.as_secs()),
76            })
77        })
78        .collect();
79    if decided.is_empty() {
80        return Ok(());
81    }
82    let mut d = approvals::Decisions::load(dir)?;
83    for decision in decided {
84        match (decision.verb.as_str(), decision.scope.as_str()) {
85            // For the task: it joins the task's approvals, for later attempts.
86            ("approve", "task") => {
87                let Some(object) = decision.object.clone() else {
88                    continue;
89                };
90                d.approve(feature, task, object, Some(run), &decision.by);
91                if let Some(last) = d
92                    .tasks
93                    .get_mut(&format!("{feature}/{task}"))
94                    .and_then(|t| t.decided.last_mut())
95                {
96                    last.note.clone_from(&decision.note);
97                }
98            }
99            // For this run: every later task of the run; the history only.
100            ("approve", "run") => {
101                if let (Ok(mut g), Some(object)) = (run_grants.lock(), &decision.object)
102                    && !g.contains(object)
103                {
104                    g.push(object.clone());
105                }
106                d.note(feature, task, decision);
107            }
108            _ => d.note(feature, task, decision),
109        }
110    }
111    d.save(dir)
112}
113
114/// Every model call of a task's run: its attempts, and the judge-side
115/// calls that wrote and kept its tests (visible, held-out).
116pub(crate) fn all_usage(report: &speccoder_core::RunReport) -> Option<serde_json::Value> {
117    add_usage(
118        add_usage(
119            report.usage.as_ref(),
120            report.acceptance.as_ref().and_then(|a| a.get("usage")),
121        )
122        .as_ref(),
123        report
124            .acceptance
125            .as_ref()
126            .and_then(|a| a.get("held_out"))
127            .and_then(|h| h.get("usage")),
128    )
129}
130
131/// Sums two token usage objects key by key.
132pub(crate) fn add_usage(
133    a: Option<&serde_json::Value>,
134    b: Option<&serde_json::Value>,
135) -> Option<serde_json::Value> {
136    match (a, b) {
137        (None, b) => b.cloned(),
138        (a, None) => a.cloned(),
139        (Some(a), Some(b)) => {
140            let mut sum = serde_json::Map::new();
141            for key in [
142                "input_tokens",
143                "output_tokens",
144                "cache_read_tokens",
145                "cache_write_tokens",
146            ] {
147                let n = a[key].as_u64().unwrap_or(0) + b[key].as_u64().unwrap_or(0);
148                sum.insert(key.to_owned(), serde_json::json!(n));
149            }
150            Some(serde_json::Value::Object(sum))
151        }
152    }
153}
154
155/// Commits everything in the worktree on its branch with speccoder's
156/// identity, without hooks; returns the commit id. Never pushes.
157pub(crate) fn commit_attempt(worktree: &Path, message: &str) -> Result<String, String> {
158    commit_attempt_as(worktree, message, false)
159}
160
161/// Commits exactly `paths` (worktree-relative: added, changed or removed)
162/// with speccoder's identity — nothing else the worktree holds; returns the
163/// commit id. Never pushes.
164pub(crate) fn commit_paths(
165    worktree: &Path,
166    message: &str,
167    paths: &[String],
168    allow_empty: bool,
169) -> Result<String, String> {
170    let g = git::Git::at(worktree);
171    let base = [
172        "-c",
173        "user.name=speccoder",
174        "-c",
175        "user.email=speccoder@users.noreply.invalid",
176        "-c",
177        "commit.gpgsign=false",
178    ];
179    g.run(&["reset", "-q"]).map_err(|e| e.0)?;
180    if !paths.is_empty() {
181        let mut add = base.to_vec();
182        add.extend(["add", "-A", "--"]);
183        add.extend(paths.iter().map(String::as_str));
184        g.run(&add).map_err(|e| e.0)?;
185    }
186    let mut commit = base.to_vec();
187    commit.extend(["commit", "-q", "--no-verify", "-m", message]);
188    if allow_empty {
189        commit.push("--allow-empty");
190    }
191    g.run(&commit).map_err(|e| e.0)?;
192    g.line(&["rev-parse", "HEAD"]).map_err(|e| e.0)
193}
194
195/// [`commit_attempt`]; `allow_empty` records a verdict whose work touched no
196/// tracked file (in place, the tick lives in a git-ignored `tasks.md`).
197pub(crate) fn commit_attempt_as(
198    worktree: &Path,
199    message: &str,
200    allow_empty: bool,
201) -> Result<String, String> {
202    let g = git::Git::at(worktree);
203    let base = [
204        "-c",
205        "user.name=speccoder",
206        "-c",
207        "user.email=speccoder@users.noreply.invalid",
208        "-c",
209        "commit.gpgsign=false",
210    ];
211    // Never a file copied from the checkout ([worktree] include), whatever
212    // the ignore rules say; the index is checked again before the commit.
213    let excluded = crate::include::pathspecs(worktree);
214    let mut add = base.to_vec();
215    add.extend(["add", "-A", "--", ":/"]);
216    add.extend(excluded.iter().map(String::as_str));
217    g.run(&add).map_err(|e| e.0)?;
218    crate::include::check_staged(worktree)?;
219    let mut commit = base.to_vec();
220    commit.extend(["commit", "-q", "--no-verify", "-m", message]);
221    if allow_empty {
222        commit.push("--allow-empty");
223    }
224    g.run(&commit).map_err(|e| e.0)?;
225    g.line(&["rev-parse", "HEAD"]).map_err(|e| e.0)
226}
227
228/// `speccoder: T004 <title>` cut to 72 characters on a char boundary.
229pub(crate) fn commit_subject(task: &str, title: &str) -> String {
230    let full = format!("speccoder: {task} {title}");
231    if full.chars().count() <= 72 {
232        return full;
233    }
234    let cut: String = full.chars().take(71).collect();
235    format!("{}…", cut.trim_end())
236}
237
238/// What a tick's commit message is made of.
239pub(crate) struct TickFacts<'a> {
240    pub(crate) feature: &'a str,
241    pub(crate) task: &'a str,
242    pub(crate) title: &'a str,
243    pub(crate) report: &'a speccoder_core::RunReport,
244    /// The kind of red the acceptance tests showed, when they did.
245    pub(crate) red: Option<speccoder_core::verify::RedClass>,
246    pub(crate) checklists_overridden: bool,
247    /// More trailers (a bug task's `Bug:`, `Acceptance:`, `Fixes`).
248    pub(crate) extra: String,
249    /// The story's scenarios as worded now: what `Scenarios:` digests.
250    pub(crate) scenarios: &'a [speccoder_core::spec::ScenarioRef],
251}
252
253/// The scenarios a verified tick's acceptance tests cite, once each in the
254/// order cited, each as a digest of its id and wording: `Scenarios:
255/// US3-1@3f9a0c1d2e4b, …` (the id kept for a reader where it is one plain
256/// word; an OpenSpec scenario's name is not). The story's checkpoint no
257/// longer has to judge them while they are worded the same.
258pub(crate) fn scenarios_trailer(
259    acceptance: Option<&serde_json::Value>,
260    progress: Option<&speccoder_core::story::Progress>,
261    scenarios: &[speccoder_core::spec::ScenarioRef],
262) -> String {
263    let mut cited: Vec<&str> = Vec::new();
264    // A task of a story claims exactly what it turned green on the oracle.
265    if let Some(speccoder_core::story::Progress::Verified { turned }) = progress {
266        cited.extend(turned.iter().map(String::as_str));
267    }
268    for t in acceptance
269        .and_then(|a| a["tests"].as_array())
270        .into_iter()
271        .flatten()
272    {
273        for s in t["scenarios"].as_array().into_iter().flatten() {
274            if let Some(s) = s.as_str().filter(|s| !cited.contains(s)) {
275                cited.push(s);
276            }
277        }
278    }
279    let plain = |id: &str| {
280        !id.is_empty()
281            && id
282                .chars()
283                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
284    };
285    let marked: Vec<String> = cited
286        .iter()
287        .filter_map(|id| scenarios.iter().find(|s| s.id == *id))
288        .map(|s| {
289            let d = scenario_digest(&s.id, &s.text);
290            if plain(&s.id) {
291                format!("{}@{d}", s.id)
292            } else {
293                d
294            }
295        })
296        .collect();
297    if marked.is_empty() {
298        String::new()
299    } else {
300        format!("Scenarios: {}\n", marked.join(", "))
301    }
302}
303
304/// A scenario, digested: 12 hex of SHA-256 over its id, a NUL and its
305/// wording with runs of whitespace as one space.
306pub(crate) fn scenario_digest(id: &str, text: &str) -> String {
307    let words = text.split_whitespace().collect::<Vec<_>>().join(" ");
308    crate::integrity::sha256_hex(format!("{id}\0{words}").as_bytes())[..12].to_owned()
309}
310
311/// The commit message of a ticked task: subject, title, and the trailers
312/// `report` reads back (`Spec-Task`, `Verdict`, `Regression-Only`, `Red`, `Scenarios`, `Flaky`,
313/// `Scope-Outside`, `Checklists`, `Held-Out`, `Acceptance-Strength`,
314/// `Ruling`, `Run`, `Usage`, `Mutation`).
315pub(crate) fn tick_message(f: &TickFacts<'_>) -> String {
316    let report = f.report;
317    let verdict_word = report
318        .verdict
319        .as_ref()
320        .map(super::outcome::verdict_word)
321        .unwrap_or_default();
322    let usage = all_usage(report);
323    let mut evidence = match (&report.regression, verdict_word.as_str()) {
324        (Some(r), "regression_only") => format!(
325            "{}: {}\n",
326            speccoder_core::regression::TRAILER,
327            speccoder_core::regression::trailer(&r.reason)
328        ),
329        _ => String::new(),
330    };
331    evidence.push_str(
332        &f.red
333            .map(|c| format!("Red: {}\n", super::acceptance::class_word(c)))
334            .unwrap_or_default(),
335    );
336    evidence.push_str(&held_out_trailer(report.acceptance.as_ref()));
337    if verdict_word == "verified" {
338        evidence.push_str(&scenarios_trailer(
339            report.acceptance.as_ref(),
340            report.progress.as_ref(),
341            f.scenarios,
342        ));
343    }
344    evidence.push_str(&flaky_trailer(report.verification.as_ref()));
345    evidence.push_str(&scope_trailer(report.scope.as_ref()));
346    if let Some(strength) = &report.strength {
347        evidence.push_str(&speccoder_core::strength::trailers(strength));
348    }
349    if f.checklists_overridden {
350        evidence.push_str("Checklists: overridden\n");
351    }
352    // An external agent made the attempt: its preset from the configuration
353    // (`acp` for one of the person's own), never the name it gave itself.
354    if let Some(a) = &report.agent {
355        let preset: String = a
356            .preset
357            .chars()
358            .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
359            .collect();
360        evidence.push_str(&format!("Executor: {preset}\n"));
361    }
362    // Commands the sandbox confined ran without asking: how many, on the tick.
363    let contained = report
364        .tool_calls
365        .iter()
366        .filter(|c| c["contained"] == true)
367        .count();
368    if contained > 0 {
369        evidence.push_str(&format!("Contained: {contained}\n"));
370    }
371    evidence.push_str(&f.extra);
372    format!(
373        "{}\n\n{}\n\nSpec-Task: {}/{}\nVerdict: {verdict_word}\n{evidence}Run: {}\n{}{}",
374        commit_subject(f.task, f.title),
375        f.title,
376        f.feature,
377        f.task,
378        report.run_id,
379        crate::attempts::usage_trailer(usage.as_ref()),
380        report
381            .mutation
382            .as_ref()
383            .and_then(crate::mutation::trailer)
384            .unwrap_or_default()
385    )
386}
387
388/// `Held-Out: passed=<k>/<k> manifest=sha256:<hex>`, `absent=<reason>` or
389/// `off`; nothing for a task without acceptance tests.
390fn held_out_trailer(acceptance: Option<&serde_json::Value>) -> String {
391    let Some(h) = acceptance.and_then(|a| a.get("held_out")) else {
392        return String::new();
393    };
394    match h["state"].as_str() {
395        Some("on") => {
396            let kept = h["kept"].as_u64().unwrap_or(0);
397            format!(
398                "Held-Out: passed={kept}/{kept} manifest={}\n",
399                h["manifest"].as_str().unwrap_or_default()
400            )
401        }
402        Some("off") => "Held-Out: off\n".to_owned(),
403        Some("absent") => format!(
404            "Held-Out: absent={}\n",
405            h["reason"].as_str().unwrap_or("none_generated")
406        ),
407        _ => String::new(),
408    }
409}
410
411/// `Flaky: <checks>` for checks that passed only when run again.
412fn flaky_trailer(verification: Option<&speccoder_core::verify::VerifyReport>) -> String {
413    let names: Vec<&str> = verification
414        .into_iter()
415        .flat_map(|v| &v.checks)
416        .filter(|c| c.flaky)
417        .map(|c| c.name.as_str())
418        .collect();
419    if names.is_empty() {
420        String::new()
421    } else {
422        format!("Flaky: {}\n", names.join(", "))
423    }
424}
425
426/// `Scope-Outside: <paths>` (the first ten, then a count).
427fn scope_trailer(scope: Option<&speccoder_core::scope::ScopeFinding>) -> String {
428    let Some(outside) = scope.map(|s| &s.outside).filter(|o| !o.is_empty()) else {
429        return String::new();
430    };
431    let mut shown: Vec<&str> = outside.iter().take(10).map(String::as_str).collect();
432    let more = outside.len().saturating_sub(10);
433    let more = format!("… (+{more})");
434    if outside.len() > 10 {
435        shown.push(&more);
436    }
437    format!("Scope-Outside: {}\n", shown.join(", "))
438}
439
440/// Leftovers of an interrupted run (or edits by hand) saved under an attempt
441/// ref and set aside, so a run starts from the branch tip; the ref.
442pub(crate) fn set_aside_leftovers(
443    wt_root: &Path,
444    tmp: &Path,
445    feature: &str,
446    task: &str,
447) -> Result<String, String> {
448    crate::attempts::save(
449        wt_root,
450        tmp,
451        feature,
452        task,
453        &crate::attempts::Record {
454            run: None,
455            outcome: crate::controls::SET_ASIDE,
456            reason: "the worktree had uncommitted changes when a run started (an interrupted run, or edits by hand); saved and set aside — `speccoder task restore` keeps them, `task drop` discards them",
457            pending: None,
458            usage: None,
459            story_open: &[],
460            own_test: None,
461        },
462    )
463    .and_then(|saved| crate::attempts::restore_head(wt_root, tmp).map(|()| saved.reference))
464    .map_err(|e| e.0)
465}
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470
471    #[test]
472    fn an_agent_s_tick_names_its_executor_by_preset() {
473        let mut report = crate::pipeline::outcome::bare_report("f", "T001", "w", "completed");
474        let facts = |report: &speccoder_core::RunReport| {
475            tick_message(&TickFacts {
476                feature: "f",
477                task: "T001",
478                title: "Add it",
479                report,
480                red: None,
481                checklists_overridden: false,
482                extra: String::new(),
483                scenarios: &[],
484            })
485        };
486        assert_eq!(trailer(&facts(&report), "Executor"), None);
487        report.agent = Some(speccoder_core::AgentAttempt {
488            agent: "Copilot\nVerdict: verified".to_owned(),
489            preset: "copilot\nVerdict: forged".to_owned(),
490            mode: None,
491            decides_alone: false,
492            known: true,
493            unasked: 0,
494            tally: speccoder_core::PermissionTally::default(),
495            plan: Vec::new(),
496        });
497        let m = facts(&report);
498        assert_eq!(trailer(&m, "Executor"), Some("copilotVerdictforged"));
499        assert_eq!(m.matches("Verdict:").count(), 1, "{m}");
500    }
501
502    /// The value of trailer `key` in `message`, by exact key (`Acceptance:` is
503    /// not `Acceptance-Strength:`).
504    fn trailer<'m>(message: &'m str, key: &str) -> Option<&'m str> {
505        message.lines().find_map(|l| {
506            let (k, v) = l.split_once(':')?;
507            (k == key).then(|| v.trim())
508        })
509    }
510
511    #[test]
512    fn trailers_are_read_by_their_exact_key() {
513        let m = "speccoder: T001 fix\n\nSpec-Task: 007-bugfixes/T001\nVerdict: verified\nAcceptance-Strength: 1.00 near-miss=1/1\nAcceptance: bug_confirmation manifest=sha256:m approval=sha256:a wording=sha256:w by=Ada\nBug: fixed (standing_speckit) triad=sha256:t\nFixes: #42\n";
514        assert_eq!(
515            trailer(m, "Acceptance"),
516            Some("bug_confirmation manifest=sha256:m approval=sha256:a wording=sha256:w by=Ada")
517        );
518        assert_eq!(
519            trailer(m, "Acceptance-Strength"),
520            Some("1.00 near-miss=1/1")
521        );
522        assert_eq!(
523            trailer(m, "Bug"),
524            Some("fixed (standing_speckit) triad=sha256:t")
525        );
526        assert_eq!(trailer(m, "Spec-Task"), Some("007-bugfixes/T001"));
527        assert_eq!(trailer(m, "Fixes"), Some("#42"));
528        assert_eq!(trailer(m, "Acceptance-Str"), None);
529        // A set frozen at review has the same one form.
530        let review = "speccoder: T005 x\n\nAcceptance-Strength: 0.80 near-miss=0/1\nAcceptance: review manifest=sha256:m approval=sha256:a wording=sha256:w by=Ada Lovelace\n";
531        assert_eq!(
532            trailer(review, "Acceptance"),
533            Some("review manifest=sha256:m approval=sha256:a wording=sha256:w by=Ada Lovelace")
534        );
535        assert_eq!(
536            trailer(review, "Acceptance-Strength"),
537            Some("0.80 near-miss=0/1")
538        );
539    }
540}