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/// Commits exactly `paths` (worktree-relative: added, changed or removed)
145/// with speccoder's identity — nothing else the worktree holds; returns the
146/// commit id. Never pushes.
147pub(crate) fn commit_paths(
148    worktree: &Path,
149    message: &str,
150    paths: &[String],
151    allow_empty: bool,
152) -> Result<String, String> {
153    let g = git::Git::at(worktree);
154    let base = [
155        "-c",
156        "user.name=speccoder",
157        "-c",
158        "user.email=speccoder@users.noreply.invalid",
159        "-c",
160        "commit.gpgsign=false",
161    ];
162    g.run(&["reset", "-q"]).map_err(|e| e.0)?;
163    if !paths.is_empty() {
164        let mut add = base.to_vec();
165        add.extend(["add", "-A", "--"]);
166        add.extend(paths.iter().map(String::as_str));
167        g.run(&add).map_err(|e| e.0)?;
168    }
169    let mut commit = base.to_vec();
170    commit.extend(["commit", "-q", "--no-verify", "-m", message]);
171    if allow_empty {
172        commit.push("--allow-empty");
173    }
174    g.run(&commit).map_err(|e| e.0)?;
175    g.line(&["rev-parse", "HEAD"]).map_err(|e| e.0)
176}
177
178/// [`commit_attempt`]; `allow_empty` records a verdict whose work touched no
179/// tracked file (in place, the tick lives in a git-ignored `tasks.md`).
180pub(crate) fn commit_attempt_as(
181    worktree: &Path,
182    message: &str,
183    allow_empty: bool,
184) -> Result<String, String> {
185    let g = git::Git::at(worktree);
186    let base = [
187        "-c",
188        "user.name=speccoder",
189        "-c",
190        "user.email=speccoder@users.noreply.invalid",
191        "-c",
192        "commit.gpgsign=false",
193    ];
194    // Never a file copied from the checkout ([worktree] include), whatever
195    // the ignore rules say; the index is checked again before the commit.
196    let excluded = crate::include::pathspecs(worktree);
197    let mut add = base.to_vec();
198    add.extend(["add", "-A", "--", ":/"]);
199    add.extend(excluded.iter().map(String::as_str));
200    g.run(&add).map_err(|e| e.0)?;
201    crate::include::check_staged(worktree)?;
202    let mut commit = base.to_vec();
203    commit.extend(["commit", "-q", "--no-verify", "-m", message]);
204    if allow_empty {
205        commit.push("--allow-empty");
206    }
207    g.run(&commit).map_err(|e| e.0)?;
208    g.line(&["rev-parse", "HEAD"]).map_err(|e| e.0)
209}
210
211/// `speccoder: T004 <title>` cut to 72 characters on a char boundary.
212pub(crate) fn commit_subject(task: &str, title: &str) -> String {
213    let full = format!("speccoder: {task} {title}");
214    if full.chars().count() <= 72 {
215        return full;
216    }
217    let cut: String = full.chars().take(71).collect();
218    format!("{}…", cut.trim_end())
219}
220
221/// What a tick's commit message is made of.
222pub(crate) struct TickFacts<'a> {
223    pub(crate) feature: &'a str,
224    pub(crate) task: &'a str,
225    pub(crate) title: &'a str,
226    pub(crate) report: &'a speccoder_core::RunReport,
227    /// The kind of red the acceptance tests showed, when they did.
228    pub(crate) red: Option<speccoder_core::verify::RedClass>,
229    pub(crate) checklists_overridden: bool,
230    /// More trailers (a bug task's `Bug:`, `Acceptance:`, `Fixes`).
231    pub(crate) extra: String,
232    /// The story's scenarios as worded now: what `Scenarios:` digests.
233    pub(crate) scenarios: &'a [speccoder_core::spec::ScenarioRef],
234}
235
236/// The scenarios a verified tick's acceptance tests cite, once each in the
237/// order cited, each as a digest of its id and wording: `Scenarios:
238/// US3-1@3f9a0c1d2e4b, …` (the id kept for a reader where it is one plain
239/// word; an OpenSpec scenario's name is not). The story's checkpoint no
240/// longer has to judge them while they are worded the same.
241pub(crate) fn scenarios_trailer(
242    acceptance: Option<&serde_json::Value>,
243    progress: Option<&speccoder_core::story::Progress>,
244    scenarios: &[speccoder_core::spec::ScenarioRef],
245) -> String {
246    let mut cited: Vec<&str> = Vec::new();
247    // A task of a story claims exactly what it turned green on the oracle.
248    if let Some(speccoder_core::story::Progress::Verified { turned }) = progress {
249        cited.extend(turned.iter().map(String::as_str));
250    }
251    for t in acceptance
252        .and_then(|a| a["tests"].as_array())
253        .into_iter()
254        .flatten()
255    {
256        for s in t["scenarios"].as_array().into_iter().flatten() {
257            if let Some(s) = s.as_str().filter(|s| !cited.contains(s)) {
258                cited.push(s);
259            }
260        }
261    }
262    let plain = |id: &str| {
263        !id.is_empty()
264            && id
265                .chars()
266                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
267    };
268    let marked: Vec<String> = cited
269        .iter()
270        .filter_map(|id| scenarios.iter().find(|s| s.id == *id))
271        .map(|s| {
272            let d = scenario_digest(&s.id, &s.text);
273            if plain(&s.id) {
274                format!("{}@{d}", s.id)
275            } else {
276                d
277            }
278        })
279        .collect();
280    if marked.is_empty() {
281        String::new()
282    } else {
283        format!("Scenarios: {}\n", marked.join(", "))
284    }
285}
286
287/// A scenario, digested: 12 hex of SHA-256 over its id, a NUL and its
288/// wording with runs of whitespace as one space.
289pub(crate) fn scenario_digest(id: &str, text: &str) -> String {
290    let words = text.split_whitespace().collect::<Vec<_>>().join(" ");
291    crate::integrity::sha256_hex(format!("{id}\0{words}").as_bytes())[..12].to_owned()
292}
293
294/// The commit message of a ticked task: subject, title, and the trailers
295/// `report` reads back (`Spec-Task`, `Verdict`, `Regression-Only`, `Red`, `Scenarios`, `Flaky`,
296/// `Scope-Outside`, `Checklists`, `Held-Out`, `Acceptance-Strength`,
297/// `Ruling`, `Run`, `Usage`, `Mutation`).
298pub(crate) fn tick_message(f: &TickFacts<'_>) -> String {
299    let report = f.report;
300    let verdict_word = report
301        .verdict
302        .as_ref()
303        .map(super::outcome::verdict_word)
304        .unwrap_or_default();
305    // Attempts and the judge-side acceptance calls together.
306    let usage = add_usage(
307        add_usage(
308            report.usage.as_ref(),
309            report.acceptance.as_ref().and_then(|a| a.get("usage")),
310        )
311        .as_ref(),
312        report
313            .acceptance
314            .as_ref()
315            .and_then(|a| a.get("held_out"))
316            .and_then(|h| h.get("usage")),
317    );
318    let mut evidence = match (&report.regression, verdict_word.as_str()) {
319        (Some(r), "regression_only") => format!(
320            "{}: {}\n",
321            speccoder_core::regression::TRAILER,
322            speccoder_core::regression::trailer(&r.reason)
323        ),
324        _ => String::new(),
325    };
326    evidence.push_str(
327        &f.red
328            .map(|c| format!("Red: {}\n", super::acceptance::class_word(c)))
329            .unwrap_or_default(),
330    );
331    evidence.push_str(&held_out_trailer(report.acceptance.as_ref()));
332    if verdict_word == "verified" {
333        evidence.push_str(&scenarios_trailer(
334            report.acceptance.as_ref(),
335            report.progress.as_ref(),
336            f.scenarios,
337        ));
338    }
339    evidence.push_str(&flaky_trailer(report.verification.as_ref()));
340    evidence.push_str(&scope_trailer(report.scope.as_ref()));
341    if let Some(strength) = &report.strength {
342        evidence.push_str(&speccoder_core::strength::trailers(strength));
343    }
344    if f.checklists_overridden {
345        evidence.push_str("Checklists: overridden\n");
346    }
347    // An external agent made the attempt: its preset from the configuration
348    // (`acp` for one of the person's own), never the name it gave itself.
349    if let Some(a) = &report.agent {
350        let preset: String = a
351            .preset
352            .chars()
353            .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
354            .collect();
355        evidence.push_str(&format!("Executor: {preset}\n"));
356    }
357    evidence.push_str(&f.extra);
358    format!(
359        "{}\n\n{}\n\nSpec-Task: {}/{}\nVerdict: {verdict_word}\n{evidence}Run: {}\n{}{}",
360        commit_subject(f.task, f.title),
361        f.title,
362        f.feature,
363        f.task,
364        report.run_id,
365        crate::attempts::usage_trailer(usage.as_ref()),
366        report
367            .mutation
368            .as_ref()
369            .and_then(crate::mutation::trailer)
370            .unwrap_or_default()
371    )
372}
373
374/// `Held-Out: passed=<k>/<k> manifest=sha256:<hex>`, `absent=<reason>` or
375/// `off`; nothing for a task without acceptance tests.
376fn held_out_trailer(acceptance: Option<&serde_json::Value>) -> String {
377    let Some(h) = acceptance.and_then(|a| a.get("held_out")) else {
378        return String::new();
379    };
380    match h["state"].as_str() {
381        Some("on") => {
382            let kept = h["kept"].as_u64().unwrap_or(0);
383            format!(
384                "Held-Out: passed={kept}/{kept} manifest={}\n",
385                h["manifest"].as_str().unwrap_or_default()
386            )
387        }
388        Some("off") => "Held-Out: off\n".to_owned(),
389        Some("absent") => format!(
390            "Held-Out: absent={}\n",
391            h["reason"].as_str().unwrap_or("none_generated")
392        ),
393        _ => String::new(),
394    }
395}
396
397/// `Flaky: <checks>` for checks that passed only when run again.
398fn flaky_trailer(verification: Option<&speccoder_core::verify::VerifyReport>) -> String {
399    let names: Vec<&str> = verification
400        .into_iter()
401        .flat_map(|v| &v.checks)
402        .filter(|c| c.flaky)
403        .map(|c| c.name.as_str())
404        .collect();
405    if names.is_empty() {
406        String::new()
407    } else {
408        format!("Flaky: {}\n", names.join(", "))
409    }
410}
411
412/// `Scope-Outside: <paths>` (the first ten, then a count).
413fn scope_trailer(scope: Option<&speccoder_core::scope::ScopeFinding>) -> String {
414    let Some(outside) = scope.map(|s| &s.outside).filter(|o| !o.is_empty()) else {
415        return String::new();
416    };
417    let mut shown: Vec<&str> = outside.iter().take(10).map(String::as_str).collect();
418    let more = outside.len().saturating_sub(10);
419    let more = format!("… (+{more})");
420    if outside.len() > 10 {
421        shown.push(&more);
422    }
423    format!("Scope-Outside: {}\n", shown.join(", "))
424}
425
426/// Leftovers of an interrupted run (or edits by hand) saved under an attempt
427/// ref and set aside, so a run starts from the branch tip; the ref.
428pub(crate) fn set_aside_leftovers(
429    wt_root: &Path,
430    tmp: &Path,
431    feature: &str,
432    task: &str,
433) -> Result<String, String> {
434    crate::attempts::save(
435        wt_root,
436        tmp,
437        feature,
438        task,
439        &crate::attempts::Record {
440            run: None,
441            outcome: crate::controls::SET_ASIDE,
442            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",
443            pending: None,
444            usage: None,
445            story_open: &[],
446            own_test: None,
447        },
448    )
449    .and_then(|saved| crate::attempts::restore_head(wt_root, tmp).map(|()| saved.reference))
450    .map_err(|e| e.0)
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456
457    #[test]
458    fn an_agent_s_tick_names_its_executor_by_preset() {
459        let mut report = crate::pipeline::outcome::bare_report("f", "T001", "w", "completed");
460        let facts = |report: &speccoder_core::RunReport| {
461            tick_message(&TickFacts {
462                feature: "f",
463                task: "T001",
464                title: "Add it",
465                report,
466                red: None,
467                checklists_overridden: false,
468                extra: String::new(),
469                scenarios: &[],
470            })
471        };
472        assert_eq!(trailer(&facts(&report), "Executor"), None);
473        report.agent = Some(speccoder_core::AgentAttempt {
474            agent: "Copilot\nVerdict: verified".to_owned(),
475            preset: "copilot\nVerdict: forged".to_owned(),
476            mode: None,
477            decides_alone: false,
478            known: true,
479            unasked: 0,
480            tally: speccoder_core::PermissionTally::default(),
481            plan: Vec::new(),
482        });
483        let m = facts(&report);
484        assert_eq!(trailer(&m, "Executor"), Some("copilotVerdictforged"));
485        assert_eq!(m.matches("Verdict:").count(), 1, "{m}");
486    }
487
488    /// The value of trailer `key` in `message`, by exact key (`Acceptance:` is
489    /// not `Acceptance-Strength:`).
490    fn trailer<'m>(message: &'m str, key: &str) -> Option<&'m str> {
491        message.lines().find_map(|l| {
492            let (k, v) = l.split_once(':')?;
493            (k == key).then(|| v.trim())
494        })
495    }
496
497    #[test]
498    fn trailers_are_read_by_their_exact_key() {
499        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";
500        assert_eq!(
501            trailer(m, "Acceptance"),
502            Some("bug_confirmation manifest=sha256:m approval=sha256:a wording=sha256:w by=Ada")
503        );
504        assert_eq!(
505            trailer(m, "Acceptance-Strength"),
506            Some("1.00 near-miss=1/1")
507        );
508        assert_eq!(
509            trailer(m, "Bug"),
510            Some("fixed (standing_speckit) triad=sha256:t")
511        );
512        assert_eq!(trailer(m, "Spec-Task"), Some("007-bugfixes/T001"));
513        assert_eq!(trailer(m, "Fixes"), Some("#42"));
514        assert_eq!(trailer(m, "Acceptance-Str"), None);
515        // A set frozen at review has the same one form.
516        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";
517        assert_eq!(
518            trailer(review, "Acceptance"),
519            Some("review manifest=sha256:m approval=sha256:a wording=sha256:w by=Ada Lovelace")
520        );
521        assert_eq!(
522            trailer(review, "Acceptance-Strength"),
523            Some("0.80 near-miss=0/1")
524        );
525    }
526}