Skip to main content

speccoder_runtime/
controls.rs

1//! A person's controls over single tasks: `accept`, `skip`,
2//! `nudge` — and `cost`, what the work used.
3//!
4//! What a person decides is recorded where speccoder's other durable facts
5//! are: an acceptance is a commit on `speccoder/<feature>` (`Verdict:
6//! attested` — a person's word, never shown as evidence); a skip is a ref
7//! under `refs/speccoder/skipped/`; a nudge is a task note in the state
8//! directory that rides in the attempt's journaled input.
9
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12
13use speccoder_core::{
14    CommandData, CommandResult, CommandStatus, ControlReport, CostReport, TaskCost, Usage,
15};
16
17use crate::git::Git;
18
19pub use crate::attest::notes::SKIPPED;
20
21const FS: char = '\u{1f}';
22const RS: char = '\u{1e}';
23
24/// One line: trailers and subjects never span lines.
25pub(crate) fn one_line(text: &str) -> String {
26    text.split_whitespace().collect::<Vec<_>>().join(" ")
27}
28
29/// The person, named as every approval names them: `<name> (asserted)`.
30pub(crate) fn person(root: &Path) -> String {
31    format!("{} (asserted)", crate::approvals::who_in(root))
32}
33
34/// A person's decision on a task as an attestation: one
35/// `task-verification`, verdict `attested` or `skipped`, no summary. A
36/// line for the message; empty when `[attest]` is off.
37pub(crate) fn attest_decision(
38    repo: &Path,
39    project: &Path,
40    task: &speccoder_core::snapshot::Task,
41    unit: (&str, &str),
42    record: (&str, &str),
43    decider: (&str, &str),
44) -> String {
45    let config = crate::verify::find_config(project)
46        .and_then(|d| std::fs::read_to_string(d.join(crate::verify::config::FILE)).ok())
47        .unwrap_or_default();
48    let Ok(run_config) = crate::substrate::run_config::parse(&config) else {
49        return String::new();
50    };
51    if !run_config.attest.enabled {
52        return String::new();
53    }
54    let adapter = crate::format::at(project);
55    let format = format!("{:?}", adapter.kind()).to_lowercase();
56    let requirements = adapter.requirement_ids(project, unit.1);
57    let tick = crate::attest::Tick {
58        repo,
59        config: &config,
60        attest: &run_config.attest,
61        format: &format,
62        feature: unit.0,
63        feature_dir: unit.1,
64        task: &task.id,
65        title: &task.title,
66        line_hash: &task.line_hash,
67        section: task.story.as_deref(),
68        section_text: "",
69        requirements: &requirements,
70        commit: record.0,
71        verdict: record.1,
72        sandbox: serde_json::Value::Null,
73        executor: serde_json::Value::Null,
74        model: serde_json::Value::Null,
75        bug: None,
76    };
77    let a = crate::attest::record_decision(&tick, decider.0, decider.1);
78    match (a["state"].as_str(), a["reason"].as_str()) {
79        (Some("signed"), _) => format!(
80            "; attested: signed ({})",
81            a["signer"].as_str().unwrap_or("?")
82        ),
83        (Some(state), Some(why)) => format!("; attestation {state}: {why}"),
84        (Some(state), None) => format!("; attestation {state}"),
85        _ => String::new(),
86    }
87}
88
89fn done(command: &str, report: ControlReport, message: &str) -> CommandResult {
90    CommandResult::new(command, CommandStatus::Ok, message)
91        .with_data(CommandData::Control(Box::new(report)))
92}
93
94/// The outcome a run's set-aside changes are saved with.
95pub const SET_ASIDE: &str = "set_aside";
96
97/// The files `commit` changes against its parent, repository-relative.
98#[must_use]
99pub fn changed_files(root: &Path, commit: &str) -> Vec<String> {
100    Git::at(root)
101        .run(&["diff", "--name-only", &format!("{commit}^"), commit])
102        .map(|o| {
103            String::from_utf8_lossy(&o)
104                .lines()
105                .map(str::to_owned)
106                .collect()
107        })
108        .unwrap_or_default()
109}
110
111/// Whether a saved attempt holds changes a run set aside (0.1.0 saved
112/// them as `interrupted`, with this reason).
113#[must_use]
114pub fn is_set_aside(a: &crate::attempts::Saved) -> bool {
115    a.outcome == SET_ASIDE
116        || (a.outcome == "interrupted"
117            && a.reason
118                .starts_with("the worktree had uncommitted changes when a run started"))
119}
120
121/// The newest changes set aside before `task`'s run.
122fn set_aside_of(root: &Path, feature: &str, task: &str) -> Option<crate::attempts::Saved> {
123    crate::attempts::list(root, feature)
124        .into_iter()
125        .find(|a| a.task == task && is_set_aside(a))
126}
127
128/// `speccoder task restore TASK`: the changes set aside before the task's
129/// run, committed onto `speccoder/<feature>` as the person's own — merged
130/// three ways when the branch moved since, refused when they conflict.
131#[must_use]
132pub fn restore(path: &Path, feature: Option<&str>, task: &str) -> CommandResult {
133    let (feature, root) = match locate("restore", path, feature) {
134        Ok(x) => x,
135        Err(r) => return *r,
136    };
137    let refuse = |status, m: String| CommandResult::new("restore", status, &m);
138    let Some(saved) = set_aside_of(&root, &feature, task) else {
139        return refuse(
140            CommandStatus::NotFound,
141            format!("nothing was set aside before {task}'s run"),
142        );
143    };
144    let git = Git::at(&root);
145    let branch = format!("refs/heads/speccoder/{feature}");
146    let (Ok(tip), Ok(parent)) = (
147        git.line(&["rev-parse", "--verify", &branch]),
148        git.line(&["rev-parse", &format!("{}^", saved.commit)]),
149    ) else {
150        return refuse(
151            CommandStatus::NotFound,
152            format!("speccoder/{feature} or the saved changes are gone"),
153        );
154    };
155    let tree = if tip == parent {
156        git.line(&["rev-parse", &format!("{}^{{tree}}", saved.commit)])
157    } else {
158        git.line(&[
159            "merge-tree",
160            "--write-tree",
161            &format!("--merge-base={parent}"),
162            &tip,
163            &saved.commit,
164        ])
165    };
166    let Ok(tree) = tree else {
167        return refuse(
168            CommandStatus::NeedsHuman,
169            format!(
170                "the set-aside changes no longer apply cleanly to speccoder/{feature}; nothing was changed — see them with `git show {}`",
171                saved.reference
172            ),
173        );
174    };
175    let files = changed_files(&root, &saved.commit);
176    let message = format!(
177        "keep the changes set aside before {task}\n\n{}\n\nKept-From: {}",
178        files.join("\n"),
179        saved.reference
180    );
181    let kept = match git.line(&[
182        "-c",
183        "commit.gpgsign=false",
184        "commit-tree",
185        tree.lines().next().unwrap_or_default(),
186        "-p",
187        &tip,
188        "-m",
189        &message,
190    ]) {
191        Ok(kept) => kept,
192        // git says why (no identity configured, most often).
193        Err(e) => {
194            return refuse(
195                CommandStatus::Error,
196                format!("the commit could not be made: {e}"),
197            );
198        }
199    };
200    // The worktree follows its branch: clean, it fast-forwards; with
201    // changes, nothing moves.
202    let moved = match crate::worktree::worktree_for(&git, &format!("speccoder/{feature}")) {
203        Ok(Some(wt)) => {
204            // Untracked build output does not stand in the way; edits to
205            // tracked files do, and are named.
206            let dirty: Vec<String> = Git::at(&wt)
207                .run(&["status", "--porcelain=v1", "--untracked-files=no"])
208                .map(|o| {
209                    String::from_utf8_lossy(&o)
210                        .lines()
211                        .map(|l| l.get(3..).unwrap_or(l).to_owned())
212                        .collect()
213                })
214                .unwrap_or_default();
215            if !dirty.is_empty() {
216                return refuse(
217                    CommandStatus::NeedsHuman,
218                    format!(
219                        "the worktree {} has uncommitted changes to {}; nothing was changed",
220                        wt.display(),
221                        dirty.iter().take(5).cloned().collect::<Vec<_>>().join(", ")
222                            + if dirty.len() > 5 { ", …" } else { "" }
223                    ),
224                );
225            }
226            // An untracked copy identical to what is kept (a lockfile the
227            // checks wrote again) gives way; a different one stops the merge.
228            let wt_git = Git::at(&wt);
229            for f in &files {
230                let p = wt.join(f);
231                let same = p.is_file()
232                    && wt_git
233                        .line(&["ls-files", "--error-unmatch", "--", f])
234                        .is_err()
235                    && wt_git.line(&["hash-object", "--", f]).ok()
236                        == git.line(&["rev-parse", &format!("{kept}:{f}")]).ok();
237                if same {
238                    let _ = std::fs::remove_file(&p);
239                }
240            }
241            wt_git.run(&["merge", "--ff-only", "-q", &kept]).map(|_| ())
242        }
243        _ => git.run(&["update-ref", &branch, &kept, &tip]).map(|_| ()),
244    };
245    if let Err(e) = moved {
246        return refuse(
247            CommandStatus::Error,
248            format!("speccoder/{feature} could not move: {e}"),
249        );
250    }
251    let _ = git.run(&["update-ref", "-d", &saved.reference]);
252    done(
253        "restore",
254        ControlReport {
255            feature: feature.clone(),
256            task: task.to_owned(),
257            action: "restored".to_owned(),
258            text: Some(kept.chars().take(12).collect()),
259            record: Some(saved.reference.clone()),
260        },
261        &format!(
262            "kept the changes set aside before {task} ({} file(s)) as {} on speccoder/{feature}",
263            files.len(),
264            kept.chars().take(7).collect::<String>()
265        ),
266    )
267}
268
269/// `speccoder task drop TASK`: every change set aside before the task's
270/// runs, discarded.
271#[must_use]
272pub fn drop_set_aside(path: &Path, feature: Option<&str>, task: &str) -> CommandResult {
273    let (feature, root) = match locate("drop", path, feature) {
274        Ok(x) => x,
275        Err(r) => return *r,
276    };
277    let saved: Vec<crate::attempts::Saved> = crate::attempts::list(&root, &feature)
278        .into_iter()
279        .filter(|a| a.task == task && is_set_aside(a))
280        .collect();
281    if saved.is_empty() {
282        return CommandResult::new(
283            "drop",
284            CommandStatus::NotFound,
285            &format!("nothing was set aside before {task}'s run"),
286        );
287    }
288    let git = Git::at(&root);
289    for a in &saved {
290        if let Err(e) = git.run(&["update-ref", "-d", &a.reference]) {
291            return CommandResult::new("drop", CommandStatus::Error, &e.to_string());
292        }
293    }
294    let n = saved.len();
295    done(
296        "drop",
297        ControlReport {
298            feature,
299            task: task.to_owned(),
300            action: "dropped".to_owned(),
301            text: Some(n.to_string()),
302            record: saved.first().map(|a| a.reference.clone()),
303        },
304        &if n == 1 {
305            format!("discarded the changes set aside before {task}")
306        } else {
307            format!("discarded the {n} sets of changes set aside before {task}")
308        },
309    )
310}
311
312/// The unit of the bug `slug` in the format's own bug structure, and the
313/// project root: the bug must be there (its directory), and a `feature`
314/// given must name that unit.
315fn bug_unit_of(
316    path: &Path,
317    feature: Option<&str>,
318    slug: &str,
319) -> Result<(String, PathBuf), Box<CommandResult>> {
320    let not_found = |m: String| Box::new(CommandResult::new("skip", CommandStatus::NotFound, &m));
321    if !speccoder_core::bug::valid_slug(slug) {
322        return Err(Box::new(
323            CommandResult::new(
324                "skip",
325                CommandStatus::UsageError,
326                &format!("`{slug}` is not a bug slug"),
327            )
328            .with_code("USAGE"),
329        ));
330    }
331    let opened = crate::format::open(path, None)
332        .map_err(|r| Box::new(CommandResult::new("skip", r.status, &r.message)))?;
333    let root = PathBuf::from(&opened.snapshot.root);
334    let format = crate::format::at(&root);
335    let home = format
336        .bug_unit(&root)
337        .ok()
338        .filter(|h| h.kind.native())
339        .ok_or_else(|| {
340            not_found(format!(
341                "bug:{slug} names a bug of the format's own bug structure, which this project does not have"
342            ))
343        })?;
344    let (dir, unit) = format
345        .bug_dir(&home, slug)
346        .filter(|(dir, _)| root.join(dir).is_dir())
347        .ok_or_else(|| not_found(format!("no bug {slug} in {}", home.location)))?;
348    if let Some(f) = feature
349        && f != unit
350        && f != dir
351    {
352        return Err(not_found(format!(
353            "bug:{slug} is a task of {unit}, not of {f}"
354        )));
355    }
356    Ok((unit, root))
357}
358
359/// The selected feature and the project root of the user's checkout.
360fn locate(
361    command: &str,
362    path: &Path,
363    feature: Option<&str>,
364) -> Result<(String, PathBuf), Box<CommandResult>> {
365    let inspected = crate::inspect(path, feature);
366    let Some(CommandData::Inspect(snapshot)) = inspected.data() else {
367        return Err(Box::new(CommandResult::carried(command, &inspected)));
368    };
369    let Some(f) = snapshot.feature.as_ref() else {
370        return Err(Box::new(CommandResult::new(
371            command,
372            CommandStatus::SelectionNeeded,
373            inspected.message(),
374        )));
375    };
376    Ok((f.feature.name.clone(), PathBuf::from(&snapshot.root)))
377}
378
379/// The feature's open tasks as `report` sees them (branch first).
380fn open_tasks(root: &Path, feature: &str) -> Vec<String> {
381    match crate::status::report(root, Some(feature)).data() {
382        Some(CommandData::Report(r)) => r
383            .tasks
384            .iter()
385            .filter(|t| matches!(t.state.as_str(), "ready" | "blocked" | "skipped"))
386            .map(|t| t.id.clone())
387            .collect(),
388        _ => Vec::new(),
389    }
390}
391
392// ── accept ─────────────────────────────────────────────────────────────────
393
394/// `speccoder task accept T --reason R`: a person attests the task is
395/// done. speccoder ticks it and commits `Verdict: attested`.
396pub fn accept_with(
397    path: &Path,
398    feature: Option<&str>,
399    task: &str,
400    reason: &str,
401    state: &Path,
402) -> CommandResult {
403    accept_in(path, feature, task, reason, state, false)
404}
405
406/// [`accept_with`], in the person's checkout when `in_place` (`accept
407/// --in-place`): committed with the in-place trailers, then ticked.
408pub fn accept_in(
409    path: &Path,
410    feature: Option<&str>,
411    task: &str,
412    reason: &str,
413    state: &Path,
414    in_place: bool,
415) -> CommandResult {
416    let options = crate::RunOptions {
417        in_place,
418        ..crate::RunOptions::default()
419    };
420    crate::pipeline::in_session("accept", path, feature, state, &options, |o| {
421        accept_task(path, feature, task, reason, state, o)
422    })
423}
424
425fn accept_task(
426    path: &Path,
427    feature: Option<&str>,
428    task: &str,
429    reason: &str,
430    state: &Path,
431    options: &crate::RunOptions,
432) -> CommandResult {
433    let refuse = |status, m: String| CommandResult::new("accept", status, &m);
434    let wt = crate::pipeline::workspace(path, feature, state, options);
435    let Some(CommandData::Worktree(w)) = wt.data() else {
436        return CommandResult::carried("accept", &wt);
437    };
438    if wt.status() != CommandStatus::Ok {
439        return CommandResult::carried("accept", &wt);
440    }
441    let (Some(wt_path), Some(project_dir)) = (w.path.clone(), w.project_dir.clone()) else {
442        return refuse(CommandStatus::Error, "worktree without a path".to_owned());
443    };
444    let wt_root = PathBuf::from(&wt_path);
445    if options.session.is_none() && crate::worktree::require_clean(&wt_root).is_err() {
446        return refuse(
447            CommandStatus::GitPrecondition,
448            format!(
449                "the worktree {wt_path} has uncommitted changes; the next `speccoder run` sets them aside, or commit them yourself"
450            ),
451        )
452        .with_code("WORKTREE-DIRTY");
453    }
454    let project = PathBuf::from(&project_dir);
455    let format = crate::format::at(&project);
456    let Some(snap) = format.inspect(&project, Some(&w.feature)) else {
457        return refuse(
458            CommandStatus::NotAProject,
459            format.messages().no_project_in_worktree.to_owned(),
460        );
461    };
462    let Some(tasks) = snap.feature.as_ref().and_then(|f| f.tasks.as_ref()) else {
463        return refuse(
464            CommandStatus::NotFound,
465            format!("{} has no {}", w.feature, format.messages().tasks_file),
466        );
467    };
468    let Some(t) = tasks.tasks.iter().find(|t| t.id == task) else {
469        return refuse(
470            CommandStatus::NotFound,
471            format!("no task {task} in {}", w.feature),
472        );
473    };
474    if t.done {
475        return refuse(
476            CommandStatus::TaskNotReady,
477            format!("{task} is already done"),
478        )
479        .with_code("TASK-DONE");
480    }
481    let reason = one_line(reason);
482    let by = person(&project);
483    let message = format!(
484        "speccoder: {task} accepted by {by}\n\n{}\n\n{reason}\n\nSpec-Task: {}/{task}\nVerdict: attested\nAccepted-By: {by}\nReason: {reason}\n",
485        t.title, w.feature
486    );
487    let file = project.join(&tasks.path);
488    let committed = match &options.session {
489        None => format.tick(&file, task, &t.line_hash).and_then(|()| {
490            crate::commit_attempt(&wt_root, &message).map_err(|e| format!("commit failed: {e}"))
491        }),
492        // In place: the checkout and the intent as the session found them.
493        Some(session) => {
494            let policy = crate::tools::policy::Policy::new(&[], &[]).rules(format.rules());
495            let Ok(mut s) = session.lock() else {
496                return refuse(
497                    CommandStatus::Error,
498                    "the in-place session is unavailable".to_owned(),
499                );
500            };
501            if let Err(e) = s.check(&policy) {
502                return e.result("accept");
503            }
504            let digest =
505                crate::in_place::intent_digest(&project, &policy, format.messages().tasks_file);
506            let done = s.commit_and_tick(
507                &plane_dir_of(state, &project),
508                &file,
509                &t.line_hash,
510                &message,
511                &digest,
512                || format.tick(&file, task, &t.line_hash),
513            );
514            match (done.commit, done.ticked) {
515                (Some(c), true) => Ok(c),
516                _ => Err(done.problems.join("; ")),
517            }
518        }
519    };
520    match committed {
521        Ok(commit) => {
522            let attested = attest_decision(
523                &wt_root,
524                &project,
525                t,
526                (
527                    &w.feature,
528                    &snap
529                        .feature
530                        .as_ref()
531                        .map(|f| f.feature.dir.clone())
532                        .unwrap_or_default(),
533                ),
534                (&commit, "attested"),
535                (&by, &reason),
536            );
537            done(
538                "accept",
539                ControlReport {
540                    feature: w.feature.clone(),
541                    task: task.to_owned(),
542                    action: "accepted".to_owned(),
543                    text: Some(reason),
544                    record: Some(commit),
545                },
546                &format!(
547                    "{task} ticked as attested by {by} (not verified); `report` shows it as such{attested}"
548                ),
549            )
550        }
551        Err(e) => refuse(CommandStatus::Error, e),
552    }
553}
554
555/// The state directory of the project at `project`.
556fn plane_dir_of(state: &Path, project: &Path) -> PathBuf {
557    crate::worktree::project_state_dir(state, project)
558}
559
560// ── skip ───────────────────────────────────────────────────────────────────
561
562/// A task id as a ref name component: `bug:<slug>` (a trailer-only task
563/// of the format's own bug structure) has a `:`, which git refuses in a ref.
564fn ref_task(task: &str) -> String {
565    task.replace('%', "%25").replace(':', "%3A")
566}
567
568/// [`ref_task`] read back.
569fn task_of_ref(name: &str) -> String {
570    name.replace("%3A", ":").replace("%25", "%")
571}
572
573/// Skipped tasks of `feature` with their reasons.
574#[must_use]
575pub fn skipped(root: &Path, feature: &str) -> BTreeMap<String, String> {
576    let format = format!("--format=%(refname){FS}%(trailers:key=Reason,valueonly){RS}");
577    let prefix = format!("{SKIPPED}/{feature}/");
578    let out = Git::at(root)
579        .run(&["for-each-ref", &format, &prefix])
580        .map(|b| String::from_utf8_lossy(&b).into_owned())
581        .unwrap_or_default();
582    out.split(RS)
583        .filter_map(|r| {
584            let (name, reason) = r.trim_start_matches('\n').split_once(FS)?;
585            Some((
586                task_of_ref(name.strip_prefix(&prefix)?),
587                reason.trim().to_owned(),
588            ))
589        })
590        .collect()
591}
592
593/// `speccoder task skip T --reason R` (or `--undo`): the task is neither
594/// done nor attempted; the feature loop passes it by, and what depends on it
595/// stays blocked.
596pub fn skip(path: &Path, feature: Option<&str>, task: &str, reason: Option<&str>) -> CommandResult {
597    // A bug of the format's own bug structure (`bug:<slug>`): no feature
598    // lists it as a task — its unit is found from its slug.
599    let located = match task.strip_prefix("bug:") {
600        Some(slug) => bug_unit_of(path, feature, slug),
601        None => locate("skip", path, feature),
602    };
603    let (feature, root) = match located {
604        Ok(x) => x,
605        Err(r) => return *r,
606    };
607    let git = Git::at(&root);
608    let reference = format!("{SKIPPED}/{feature}/{}", ref_task(task));
609    let report = |action: &str, text: Option<String>| ControlReport {
610        feature: feature.clone(),
611        task: task.to_owned(),
612        action: action.to_owned(),
613        text,
614        record: Some(reference.clone()),
615    };
616    let Some(reason) = reason else {
617        let _ = git.run(&["update-ref", "-d", &reference]);
618        return done(
619            "skip",
620            report("unskipped", None),
621            &format!("{task} is no longer skipped"),
622        );
623    };
624    if !task.starts_with("bug:") && !open_tasks(&root, &feature).iter().any(|t| t == task) {
625        return CommandResult::new(
626            "skip",
627            CommandStatus::NotFound,
628            &format!("{task} is not an open task of {feature}"),
629        );
630    }
631    if task.starts_with("bug:")
632        && let Some(state) = crate::worktree::state_dir()
633        && let Some(b) = crate::bug::state::load(
634            &crate::worktree::project_state_dir(&state, &root),
635            &feature,
636            task,
637        )
638        && b.commit.is_some()
639    {
640        return CommandResult::new(
641            "skip",
642            CommandStatus::TaskNotReady,
643            &format!("{task} is done already: its commit is recorded"),
644        )
645        .with_code("TASK-DONE");
646    }
647    let reason = one_line(reason);
648    let by = person(&root);
649    let made = git
650        .line(&["rev-parse", "HEAD^{tree}"])
651        .and_then(|tree| {
652            git.line(&[
653                "-c",
654                "user.name=speccoder",
655                "-c",
656                "user.email=speccoder@users.noreply.invalid",
657                "-c",
658                "commit.gpgsign=false",
659                "commit-tree",
660                &tree,
661                "-m",
662                &format!("speccoder: skip {task}\n\n{reason}\n\nSpec-Task: {feature}/{task}\nSkipped-By: {by}\nReason: {reason}\n"),
663            ])
664        })
665        .and_then(|commit| git.run(&["update-ref", &reference, &commit]).map(|_| commit));
666    match made {
667        Ok(commit) => {
668            let snap = crate::format::at(&root).inspect(&root, Some(&feature));
669            let unit = snap.as_ref().and_then(|s| s.feature.as_ref());
670            let attested = unit
671                .and_then(|u| {
672                    u.tasks
673                        .as_ref()
674                        .and_then(|t| t.tasks.iter().find(|x| x.id == task))
675                        .map(|t| (u, t))
676                })
677                .map(|(u, t)| {
678                    attest_decision(
679                        &root,
680                        &root,
681                        t,
682                        (&feature, &u.feature.dir),
683                        (&commit, "skipped"),
684                        (&by, &reason),
685                    )
686                })
687                .unwrap_or_default();
688            done(
689                "skip",
690                report("skipped", Some(reason)),
691                &format!(
692                    "{task} skipped: runs pass it by, and tasks depending on it stay blocked (`skip --task {task} --undo` to take it back){attested}"
693                ),
694            )
695        }
696        Err(e) => CommandResult::new("skip", CommandStatus::GitPrecondition, &e.0),
697    }
698}
699
700// ── nudge ──────────────────────────────────────────────────────────────────
701
702/// `speccoder task rule <task> --tests-right --reason …`: a
703/// person rules that the tests of a held attempt are right — the flagged
704/// alternative is not what the spec allows. The ruling is bound to the
705/// alternative's digest; the next `run` of the task judges the held attempt
706/// again from the journal and ticks it with the ruling recorded.
707pub fn rule(
708    path: &Path,
709    feature: Option<&str>,
710    task: &str,
711    reason: &str,
712    variant: Option<&str>,
713    state: &Path,
714) -> CommandResult {
715    let (feature, root) = match locate("rule", path, feature) {
716        Ok(x) => x,
717        Err(r) => return *r,
718    };
719    if reason.trim().is_empty() {
720        return CommandResult::new("rule", CommandStatus::UsageError, "a ruling needs a reason");
721    }
722    let keep = crate::strength::dir(
723        &crate::worktree::project_state_dir(state, &root),
724        &feature,
725        task,
726    );
727    let Some(held) = crate::strength::held(&keep) else {
728        return CommandResult::new(
729            "rule",
730            CommandStatus::NotFound,
731            &format!("{task} has no attempt held for a ruling on its tests"),
732        )
733        .with_code("NOT-FOUND");
734    };
735    let chosen: Vec<_> = held
736        .findings
737        .iter()
738        .filter(|p| variant.is_none_or(|v| p.id == v))
739        .collect();
740    if chosen.is_empty() {
741        return CommandResult::new(
742            "rule",
743            CommandStatus::NotFound,
744            &format!(
745                "{task} has no finding `{}` (held: {})",
746                variant.unwrap_or_default(),
747                held.findings
748                    .iter()
749                    .map(|p| p.id.as_str())
750                    .collect::<Vec<_>>()
751                    .join(", ")
752            ),
753        )
754        .with_code("NOT-FOUND");
755    }
756    let by = crate::approvals::who_in(&root);
757    for p in &chosen {
758        let ruling = speccoder_core::strength::Ruling {
759            digest: p.digest.clone(),
760            scenario: p.scenario.clone(),
761            by: by.clone(),
762            reason: reason.trim().to_owned(),
763        };
764        if let Err(e) = crate::strength::add_ruling(&keep, ruling) {
765            return CommandResult::new("rule", CommandStatus::Error, &e.to_string());
766        }
767    }
768    done(
769        "rule",
770        ControlReport {
771            feature,
772            task: task.to_owned(),
773            action: "ruled_tests_right".to_owned(),
774            text: Some(reason.trim().to_owned()),
775            record: None,
776        },
777        &format!(
778            "ruled by {by}: {task}'s tests are right about {}; `speccoder run --task {task}` judges the held attempt again and ticks it",
779            chosen
780                .iter()
781                .map(|p| format!("{} ({})", p.id, p.scenario))
782                .collect::<Vec<_>>()
783                .join(", ")
784        ),
785    )
786}
787
788/// `speccoder task nudge T "note"` (or `--clear`): a person's note for the
789/// task's next attempts, journaled with them.
790pub fn nudge_with(
791    path: &Path,
792    feature: Option<&str>,
793    task: &str,
794    note: Option<&str>,
795    state: &Path,
796) -> CommandResult {
797    let (feature, root) = match locate("nudge", path, feature) {
798        Ok(x) => x,
799        Err(r) => return *r,
800    };
801    let dir = crate::worktree::project_state_dir(state, &root);
802    let mut decisions = match crate::approvals::Decisions::load(&dir) {
803        Ok(d) => d,
804        Err(e) => return CommandResult::new("nudge", CommandStatus::ConfigError, &e),
805    };
806    let entry = decisions
807        .tasks
808        .entry(format!("{feature}/{task}"))
809        .or_default();
810    let (action, message) = match note {
811        Some(n) => {
812            entry.nudges.push(n.trim().to_owned());
813            (
814                "nudged",
815                format!("{task}'s next attempts will read: {}", n.trim()),
816            )
817        }
818        None => {
819            entry.nudges.clear();
820            ("nudges_cleared", format!("{task} has no notes any more"))
821        }
822    };
823    if let Err(e) = decisions.save(&dir) {
824        return CommandResult::new("nudge", CommandStatus::Error, &e);
825    }
826    done(
827        "nudge",
828        ControlReport {
829            feature,
830            task: task.to_owned(),
831            action: action.to_owned(),
832            text: note.map(|n| n.trim().to_owned()),
833            record: None,
834        },
835        &message,
836    )
837}
838
839// ── cost ───────────────────────────────────────────────────────────────────
840
841fn add(total: &mut Usage, u: &serde_json::Value) {
842    let n = |k: &str| u[k].as_u64().unwrap_or(0);
843    total.input_tokens += n("input_tokens");
844    total.output_tokens += n("output_tokens");
845    total.cache_read_tokens += n("cache_read_tokens");
846    total.cache_write_tokens += n("cache_write_tokens");
847    if let Some(c) = u["cost_usd"].as_f64() {
848        total.usd = Some(total.usd.unwrap_or(0.0) + c);
849    }
850}
851
852/// Prices `u` from `[model]`, unless its cost was reported (an external
853/// agent's own figure, which the configured prices do not describe).
854fn price(u: &mut Usage, prices: Option<crate::substrate::model_config::Prices>) {
855    if let Some(p) = prices.filter(|_| u.usd.is_none()) {
856        u.usd = Some(p.usd(
857            u.input_tokens,
858            u.output_tokens,
859            u.cache_read_tokens,
860            u.cache_write_tokens,
861        ));
862    }
863}
864
865/// `speccoder report --cost`: tokens per task — every attempt recorded in git, the
866/// passing one and the saved ones — plus convergence, priced when `[model]`
867/// states prices.
868pub fn cost(path: &Path, feature: Option<&str>) -> CommandResult {
869    let (feature, root) = match locate("cost", path, feature) {
870        Ok(x) => x,
871        Err(r) => return *r,
872    };
873    let model = crate::verify::find_config(&root)
874        .and_then(|d| std::fs::read_to_string(d.join(crate::verify::config::FILE)).ok())
875        .and_then(|t| crate::substrate::model_config::parse(&t).ok().flatten());
876    let prices = model.as_ref().and_then(|m| m.prices);
877
878    let branch = format!("speccoder/{feature}");
879    let format = format!(
880        "--format=%s{FS}%(trailers:key=Spec-Task,valueonly){FS}%(trailers:key=Usage,valueonly){RS}"
881    );
882    let log = Git::at(&root)
883        .run(&["log", &format, &branch])
884        .map(|b| String::from_utf8_lossy(&b).into_owned())
885        .unwrap_or_default();
886    let mut per_task: BTreeMap<String, (usize, Usage)> = BTreeMap::new();
887    let mut convergence = Usage::default();
888    for record in log.split(RS) {
889        let f: Vec<&str> = record.trim_start_matches('\n').split(FS).collect();
890        let [subject, task, usage] = f[..] else {
891            continue;
892        };
893        let Some(u) = crate::attempts::parse_usage(usage.trim()) else {
894            continue;
895        };
896        if let Some(t) = task.trim().strip_prefix(&format!("{feature}/")) {
897            let e = per_task.entry(t.to_owned()).or_default();
898            e.0 += 1;
899            add(&mut e.1, &u);
900        } else if subject.starts_with("speccoder: converge round") {
901            add(&mut convergence, &u);
902        }
903    }
904    for saved in crate::attempts::list(&root, &feature) {
905        if let Some(u) = saved.usage.as_ref() {
906            let e = per_task.entry(saved.task.clone()).or_default();
907            e.0 += 1;
908            add(&mut e.1, u);
909        }
910    }
911
912    let mut total = Usage::default();
913    let mut tasks = Vec::new();
914    for (task, (attempts, mut usage)) in per_task {
915        total.input_tokens += usage.input_tokens;
916        total.output_tokens += usage.output_tokens;
917        total.cache_read_tokens += usage.cache_read_tokens;
918        total.cache_write_tokens += usage.cache_write_tokens;
919        price(&mut usage, prices);
920        tasks.push(TaskCost {
921            task,
922            attempts,
923            usage,
924        });
925    }
926    total.input_tokens += convergence.input_tokens;
927    total.output_tokens += convergence.output_tokens;
928    total.cache_read_tokens += convergence.cache_read_tokens;
929    total.cache_write_tokens += convergence.cache_write_tokens;
930    price(&mut convergence, prices);
931    let priced: Vec<f64> = tasks
932        .iter()
933        .map(|t| &t.usage)
934        .chain([&convergence])
935        .filter_map(|u| u.usd)
936        .collect();
937    total.usd = (!priced.is_empty()).then(|| priced.iter().sum());
938    let message = match total.usd {
939        Some(usd) => format!(
940            "{} tokens in, {} out ({} from the cache): ${usd:.4}",
941            total.input_tokens, total.output_tokens, total.cache_read_tokens
942        ),
943        None => format!(
944            "{} tokens in, {} out ({} from the cache); add price_input_per_mtok and price_output_per_mtok to [model] for money",
945            total.input_tokens, total.output_tokens, total.cache_read_tokens
946        ),
947    };
948    CommandResult::new("cost", CommandStatus::Ok, &message).with_data(CommandData::Cost(Box::new(
949        CostReport {
950            feature,
951            tasks,
952            convergence,
953            total,
954            priced_model: prices.and(model.map(|m| format!("{}/{}", m.provider, m.model))),
955        },
956    )))
957}
958
959#[cfg(test)]
960mod tests {
961    use super::*;
962
963    #[test]
964    fn cached_input_is_priced_at_the_cache_rate() {
965        let mut u = Usage {
966            input_tokens: 1_000_000,
967            output_tokens: 100_000,
968            cache_read_tokens: 600_000,
969            cache_write_tokens: 0,
970            usd: None,
971        };
972        price(
973            &mut u,
974            Some(crate::substrate::model_config::Prices {
975                input: 1.0,
976                output: 4.0,
977                cache_read: 0.1,
978                cache_write: 1.25,
979                cache_write_1h: 2.0,
980                one_hour: false,
981            }),
982        );
983        // 0.4M fresh × $1 + 0.6M cached × $0.1 + 0.1M out × $4
984        assert!(
985            (u.usd.unwrap_or_default() - 0.86).abs() < 1e-9,
986            "{:?}",
987            u.usd
988        );
989    }
990}