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/// Sums two token usage objects key by key.
115pub(crate) fn add_usage(
116    a: Option<&serde_json::Value>,
117    b: Option<&serde_json::Value>,
118) -> Option<serde_json::Value> {
119    match (a, b) {
120        (None, b) => b.cloned(),
121        (a, None) => a.cloned(),
122        (Some(a), Some(b)) => {
123            let mut sum = serde_json::Map::new();
124            for key in [
125                "input_tokens",
126                "output_tokens",
127                "cache_read_tokens",
128                "cache_write_tokens",
129            ] {
130                let n = a[key].as_u64().unwrap_or(0) + b[key].as_u64().unwrap_or(0);
131                sum.insert(key.to_owned(), serde_json::json!(n));
132            }
133            Some(serde_json::Value::Object(sum))
134        }
135    }
136}
137
138/// Commits everything in the worktree on its branch with speccoder's
139/// identity, without hooks; returns the commit id. Never pushes.
140pub(crate) fn commit_attempt(worktree: &Path, message: &str) -> Result<String, String> {
141    commit_attempt_as(worktree, message, false)
142}
143
144/// [`commit_attempt`]; `allow_empty` records a verdict whose work touched no
145/// tracked file (in place, the tick lives in a git-ignored `tasks.md`).
146pub(crate) fn commit_attempt_as(
147    worktree: &Path,
148    message: &str,
149    allow_empty: bool,
150) -> Result<String, String> {
151    let g = git::Git::at(worktree);
152    let base = [
153        "-c",
154        "user.name=speccoder",
155        "-c",
156        "user.email=speccoder@users.noreply.invalid",
157        "-c",
158        "commit.gpgsign=false",
159    ];
160    let mut add = base.to_vec();
161    add.extend(["add", "-A"]);
162    g.run(&add).map_err(|e| e.0)?;
163    let mut commit = base.to_vec();
164    commit.extend(["commit", "-q", "--no-verify", "-m", message]);
165    if allow_empty {
166        commit.push("--allow-empty");
167    }
168    g.run(&commit).map_err(|e| e.0)?;
169    g.line(&["rev-parse", "HEAD"]).map_err(|e| e.0)
170}
171
172/// `speccoder: T004 <title>` cut to 72 characters on a char boundary.
173pub(crate) fn commit_subject(task: &str, title: &str) -> String {
174    let full = format!("speccoder: {task} {title}");
175    if full.chars().count() <= 72 {
176        return full;
177    }
178    let cut: String = full.chars().take(71).collect();
179    format!("{}…", cut.trim_end())
180}
181
182/// What a tick's commit message is made of.
183pub(crate) struct TickFacts<'a> {
184    pub(crate) feature: &'a str,
185    pub(crate) task: &'a str,
186    pub(crate) title: &'a str,
187    pub(crate) report: &'a speccoder_core::RunReport,
188    /// The kind of red the acceptance tests showed, when they did.
189    pub(crate) red: Option<speccoder_core::verify::RedClass>,
190    pub(crate) checklists_overridden: bool,
191    /// More trailers (a bug task's `Bug:`, `Acceptance:`, `Fixes`).
192    pub(crate) extra: String,
193}
194
195/// The commit message of a ticked task: subject, title, and the trailers
196/// `report` reads back (`Spec-Task`, `Verdict`, `Regression-Only`, `Red`, `Flaky`,
197/// `Scope-Outside`, `Checklists`, `Held-Out`, `Acceptance-Strength`,
198/// `Ruling`, `Run`, `Usage`, `Mutation`).
199pub(crate) fn tick_message(f: &TickFacts<'_>) -> String {
200    let report = f.report;
201    let verdict_word = report
202        .verdict
203        .as_ref()
204        .map(super::outcome::verdict_word)
205        .unwrap_or_default();
206    // Attempts and the judge-side acceptance calls together.
207    let usage = add_usage(
208        add_usage(
209            report.usage.as_ref(),
210            report.acceptance.as_ref().and_then(|a| a.get("usage")),
211        )
212        .as_ref(),
213        report
214            .acceptance
215            .as_ref()
216            .and_then(|a| a.get("held_out"))
217            .and_then(|h| h.get("usage")),
218    );
219    let mut evidence = match (&report.regression, verdict_word.as_str()) {
220        (Some(r), "regression_only") => format!(
221            "{}: {}\n",
222            speccoder_core::regression::TRAILER,
223            speccoder_core::regression::trailer(&r.reason)
224        ),
225        _ => String::new(),
226    };
227    evidence.push_str(
228        &f.red
229            .map(|c| format!("Red: {}\n", super::acceptance::class_word(c)))
230            .unwrap_or_default(),
231    );
232    evidence.push_str(&held_out_trailer(report.acceptance.as_ref()));
233    if let Some(story) = report
234        .acceptance
235        .as_ref()
236        .and_then(|a| a["story_file"].as_str())
237    {
238        evidence.push_str(&format!("Story-File: {story}\n"));
239    }
240    evidence.push_str(&flaky_trailer(report.verification.as_ref()));
241    evidence.push_str(&scope_trailer(report.scope.as_ref()));
242    if let Some(strength) = &report.strength {
243        evidence.push_str(&speccoder_core::strength::trailers(strength));
244    }
245    if f.checklists_overridden {
246        evidence.push_str("Checklists: overridden\n");
247    }
248    evidence.push_str(&f.extra);
249    format!(
250        "{}\n\n{}\n\nSpec-Task: {}/{}\nVerdict: {verdict_word}\n{evidence}Run: {}\n{}{}",
251        commit_subject(f.task, f.title),
252        f.title,
253        f.feature,
254        f.task,
255        report.run_id,
256        crate::attempts::usage_trailer(usage.as_ref()),
257        report
258            .mutation
259            .as_ref()
260            .and_then(crate::mutation::trailer)
261            .unwrap_or_default()
262    )
263}
264
265/// The story files speccoder created on the feature's branch: the
266/// `Story-File:` trailers of its ticks.
267pub(crate) fn story_files(repo: &std::path::Path, feature: &str) -> Vec<String> {
268    let log = crate::git::Git::at(repo)
269        .run(&[
270            "log",
271            "--first-parent",
272            "--format=%(trailers:key=Spec-Task,valueonly)%x1f%(trailers:key=Story-File,valueonly)%x1e",
273            "HEAD",
274        ])
275        .map(|b| String::from_utf8_lossy(&b).into_owned())
276        .unwrap_or_default();
277    let mut out: Vec<String> = log
278        .split('\u{1e}')
279        .filter_map(|r| {
280            let (task, file) = r.trim().split_once('\u{1f}')?;
281            task.trim()
282                .starts_with(&format!("{feature}/"))
283                .then(|| file.trim().to_owned())
284        })
285        .filter(|f| !f.is_empty())
286        .collect();
287    out.sort();
288    out.dedup();
289    out
290}
291
292/// `Held-Out: passed=<k>/<k> manifest=sha256:<hex>`, `absent=<reason>` or
293/// `off`; nothing for a task without acceptance tests.
294fn held_out_trailer(acceptance: Option<&serde_json::Value>) -> String {
295    let Some(h) = acceptance.and_then(|a| a.get("held_out")) else {
296        return String::new();
297    };
298    match h["state"].as_str() {
299        Some("on") => {
300            let kept = h["kept"].as_u64().unwrap_or(0);
301            format!(
302                "Held-Out: passed={kept}/{kept} manifest={}\n",
303                h["manifest"].as_str().unwrap_or_default()
304            )
305        }
306        Some("off") => "Held-Out: off\n".to_owned(),
307        Some("absent") => format!(
308            "Held-Out: absent={}\n",
309            h["reason"].as_str().unwrap_or("none_generated")
310        ),
311        _ => String::new(),
312    }
313}
314
315/// `Flaky: <checks>` for checks that passed only when run again.
316fn flaky_trailer(verification: Option<&speccoder_core::verify::VerifyReport>) -> String {
317    let names: Vec<&str> = verification
318        .into_iter()
319        .flat_map(|v| &v.checks)
320        .filter(|c| c.flaky)
321        .map(|c| c.name.as_str())
322        .collect();
323    if names.is_empty() {
324        String::new()
325    } else {
326        format!("Flaky: {}\n", names.join(", "))
327    }
328}
329
330/// `Scope-Outside: <paths>` (the first ten, then a count).
331fn scope_trailer(scope: Option<&speccoder_core::scope::ScopeFinding>) -> String {
332    let Some(outside) = scope.map(|s| &s.outside).filter(|o| !o.is_empty()) else {
333        return String::new();
334    };
335    let mut shown: Vec<&str> = outside.iter().take(10).map(String::as_str).collect();
336    let more = outside.len().saturating_sub(10);
337    let more = format!("… (+{more})");
338    if outside.len() > 10 {
339        shown.push(&more);
340    }
341    format!("Scope-Outside: {}\n", shown.join(", "))
342}
343
344/// Leftovers of an interrupted run (or edits by hand) saved under an attempt
345/// ref and set aside, so a run starts from the branch tip; the ref.
346pub(crate) fn set_aside_leftovers(
347    wt_root: &Path,
348    tmp: &Path,
349    feature: &str,
350    task: &str,
351) -> Result<String, String> {
352    crate::attempts::save(
353        wt_root,
354        tmp,
355        feature,
356        task,
357        &crate::attempts::Record {
358            run: None,
359            outcome: crate::controls::SET_ASIDE,
360            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",
361            pending: None,
362            usage: None,
363        },
364    )
365    .and_then(|saved| crate::attempts::restore_head(wt_root, tmp).map(|()| saved.reference))
366    .map_err(|e| e.0)
367}
368
369#[cfg(test)]
370mod tests {
371    /// The value of trailer `key` in `message`, by exact key (`Acceptance:` is
372    /// not `Acceptance-Strength:`).
373    fn trailer<'m>(message: &'m str, key: &str) -> Option<&'m str> {
374        message.lines().find_map(|l| {
375            let (k, v) = l.split_once(':')?;
376            (k == key).then(|| v.trim())
377        })
378    }
379
380    #[test]
381    fn trailers_are_read_by_their_exact_key() {
382        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";
383        assert_eq!(
384            trailer(m, "Acceptance"),
385            Some("bug_confirmation manifest=sha256:m approval=sha256:a wording=sha256:w by=Ada")
386        );
387        assert_eq!(
388            trailer(m, "Acceptance-Strength"),
389            Some("1.00 near-miss=1/1")
390        );
391        assert_eq!(
392            trailer(m, "Bug"),
393            Some("fixed (standing_speckit) triad=sha256:t")
394        );
395        assert_eq!(trailer(m, "Spec-Task"), Some("007-bugfixes/T001"));
396        assert_eq!(trailer(m, "Fixes"), Some("#42"));
397        assert_eq!(trailer(m, "Acceptance-Str"), None);
398        // A set frozen at review has the same one form.
399        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";
400        assert_eq!(
401            trailer(review, "Acceptance"),
402            Some("review manifest=sha256:m approval=sha256:a wording=sha256:w by=Ada Lovelace")
403        );
404        assert_eq!(
405            trailer(review, "Acceptance-Strength"),
406            Some("0.80 near-miss=0/1")
407        );
408    }
409}