Skip to main content

speccoder_runtime/
status.rs

1//! `speccoder report`: a feature's tasks and the evidence behind
2//! each tick, read from what is durable and reviewable — `tasks.md` at the
3//! tip of `speccoder/<feature>` and the trailers of its commits. Read-only:
4//! no model, no worktree, no state directory.
5
6use std::collections::BTreeMap;
7use std::path::Path;
8
9use speccoder_core::snapshot::{ParsedTasks, TaskState};
10use speccoder_core::{
11    CommandData, CommandResult, CommandStatus, ConvergenceRound, StatusReport, StatusTotals,
12    TaskStatus, TraceRow,
13};
14
15use crate::git::Git;
16
17/// Field and record separators for `git log` output.
18const FS: char = '\u{1f}';
19const RS: char = '\u{1e}';
20
21/// What a speccoder commit says about a task.
22#[derive(Debug, Clone)]
23struct Evidence {
24    commit: String,
25    verdict: String,
26    run: String,
27    reason: String,
28    /// The task's line, unticked, when the commit was made in place.
29    task_line: String,
30    /// The intent it was judged against, when made in place.
31    intent: String,
32    /// `Acceptance-Strength:`.
33    strength: String,
34    /// `Regression-Only:`.
35    regression: String,
36}
37
38/// Reads the trailers speccoder writes (`Spec-Task`, `Verdict`, `Run`) and
39/// its convergence commits from `log` (newest first): the latest commit per
40/// task wins; rounds come back oldest first.
41fn read_log(log: &str, feature: &str) -> (BTreeMap<String, Evidence>, Vec<ConvergenceRound>) {
42    let mut evidence: BTreeMap<String, Evidence> = BTreeMap::new();
43    let mut rounds = Vec::new();
44    for record in log.split(RS) {
45        let fields: Vec<&str> = record.trim_start_matches('\n').split(FS).collect();
46        let [
47            commit,
48            subject,
49            task,
50            verdict,
51            run,
52            reason,
53            task_line,
54            intent,
55            strength,
56            regression,
57            body,
58        ] = fields[..]
59        else {
60            continue;
61        };
62        if let Some(task) = task.trim().strip_prefix(&format!("{feature}/")) {
63            evidence.entry(task.to_owned()).or_insert(Evidence {
64                commit: commit.to_owned(),
65                verdict: verdict.trim().to_owned(),
66                run: run.trim().to_owned(),
67                reason: reason.trim().to_owned(),
68                task_line: task_line.trim().to_owned(),
69                intent: intent.trim().trim_start_matches("sha256:").to_owned(),
70                strength: strength.trim().to_owned(),
71                regression: regression.trim().to_owned(),
72            });
73        } else if let Some(n) = subject
74            .strip_prefix("speccoder: converge round ")
75            .and_then(|r| r.split(' ').next())
76            .and_then(|n| n.parse::<u32>().ok())
77        {
78            rounds.push(ConvergenceRound {
79                round: n,
80                commit: commit.to_owned(),
81                tasks: body
82                    .lines()
83                    .filter(|l| {
84                        l.strip_prefix('T')
85                            .is_some_and(|r| r.starts_with(|c: char| c.is_ascii_digit()))
86                    })
87                    .map(str::to_owned)
88                    .collect(),
89            });
90        }
91    }
92    rounds.reverse();
93    (evidence, rounds)
94}
95
96/// A regression-only tick's reason from its trailer; a tick without one
97/// (without a recorded reason) reads `unrecorded`, never a guess.
98#[must_use]
99pub fn regression_of(trailer: &str) -> speccoder_core::regression::Regression {
100    use speccoder_core::regression::{Regression, RegressionReason, parse_trailer};
101    Regression::of(parse_trailer(trailer.trim()).unwrap_or(RegressionReason::Unrecorded))
102}
103
104/// Each task's state: evidence for ticked tasks, the schedule for open ones.
105/// `lines` (the open-line hash per task, for local ticks) decides whether a
106/// commit naming a `Task-Line` still matches the task as written.
107fn statuses(
108    parsed: &ParsedTasks,
109    evidence: &BTreeMap<String, Evidence>,
110    lines: &BTreeMap<String, String>,
111    saved: &[crate::attempts::Saved],
112    skipped: &BTreeMap<String, String>,
113) -> Vec<TaskStatus> {
114    let (schedule, _) = speccoder_core::graph::schedule(parsed);
115    parsed
116        .tasks
117        .iter()
118        .map(|t| {
119            let scheduled = schedule.tasks.iter().find(|s| s.id == t.id);
120            let found = evidence.get(&t.id).filter(|e| {
121                e.task_line.is_empty() || lines.get(&t.id).is_none_or(|h| *h == e.task_line)
122            });
123            // In place: a commit for exactly this line, the tick not written.
124            let untick = found.filter(|e| !t.done && !e.task_line.is_empty() && !lines.is_empty());
125            let state = if untick.is_some() {
126                "evidence_without_tick".to_owned()
127            } else if t.done {
128                match found.map(|e| e.verdict.as_str()) {
129                    Some(v @ ("verified" | "regression_only" | "attested")) => v.to_owned(),
130                    _ => "ticked_without_evidence".to_owned(),
131                }
132            } else if skipped.contains_key(&t.id) {
133                "skipped".to_owned()
134            } else if scheduled.is_some_and(|s| s.state == TaskState::Ready) {
135                "ready".to_owned()
136            } else {
137                "blocked".to_owned()
138            };
139            TaskStatus {
140                lane: speccoder_core::lane::Lane::default(),
141                id: t.id.clone(),
142                title: t.title.clone(),
143                phase: t.phase.clone().unwrap_or_default(),
144                blocked_by: if t.done {
145                    Vec::new()
146                } else {
147                    scheduled.map(|s| s.blocked_by.clone()).unwrap_or_default()
148                },
149                commit: found
150                    .filter(|_| t.done || untick.is_some())
151                    .map(|e| e.commit.clone()),
152                attestation: None,
153                strength: found
154                    .filter(|e| t.done && !e.strength.is_empty())
155                    .map(|e| e.strength.clone()),
156                drift: None,
157                run_id: found
158                    .filter(|e| t.done && !e.run.is_empty())
159                    .map(|e| e.run.clone()),
160                // Newest first: the first saved attempt of an open task.
161                last_attempt: saved
162                    .iter()
163                    .find(|a| !t.done && a.task == t.id && !crate::controls::is_set_aside(a))
164                    .map(|a| speccoder_core::LastAttempt {
165                        outcome: a.outcome.clone(),
166                        reason: a.reason.clone(),
167                        run_id: a.run_id.clone(),
168                        reference: a.reference.clone(),
169                        story_open: a.story_open.clone(),
170                    }),
171                judged: None,
172                set_aside: None,
173                bug: None,
174                regression: found
175                    .filter(|e| t.done && e.verdict == "regression_only")
176                    .map(|e| regression_of(&e.regression)),
177                note: if t.done {
178                    found.map(|e| e.reason.clone()).filter(|r| !r.is_empty())
179                } else {
180                    skipped.get(&t.id).cloned()
181                },
182                state,
183            }
184        })
185        .collect()
186}
187
188fn totals(tasks: &[TaskStatus]) -> StatusTotals {
189    let n = |s: &str| tasks.iter().filter(|t| t.state == s).count();
190    StatusTotals {
191        verified: n("verified"),
192        regression_only: n("regression_only"),
193        ticked_without_evidence: n("ticked_without_evidence"),
194        evidence_without_tick: n("evidence_without_tick"),
195        without_attestation: tasks
196            .iter()
197            .filter(|t| t.attestation.as_deref() == Some("missing"))
198            .count(),
199        attested: n("attested"),
200        skipped: n("skipped"),
201        ready: n("ready"),
202        blocked: n("blocked"),
203        stale: tasks
204            .iter()
205            .filter(|t| t.drift.as_ref().is_some_and(speccoder_core::Drift::stale))
206            .count(),
207    }
208}
209
210/// The open tasks by lane, for *Before you run*: `None` when every one
211/// is code (nothing worth saying) or there is no task to run.
212#[must_use]
213pub fn lanes(path: &Path, feature: Option<&str>) -> Option<speccoder_core::lane::Lanes> {
214    let r = report(path, feature);
215    let Some(CommandData::Report(r)) = r.data() else {
216        return None;
217    };
218    let lanes = speccoder_core::lane::Lanes::of(
219        r.tasks
220            .iter()
221            .filter(|t| matches!(t.state.as_str(), "ready" | "blocked"))
222            .map(|t| (t.id.as_str(), t.lane)),
223    );
224    lanes.notable().then_some(lanes)
225}
226
227/// `speccoder report [--feature]`.
228#[must_use]
229pub fn report(path: &Path, feature: Option<&str>) -> CommandResult {
230    let inspected = crate::inspect(path, feature);
231    let Some(CommandData::Inspect(snapshot)) = inspected.data() else {
232        return CommandResult::carried("report", &inspected);
233    };
234    let format = crate::format::of(snapshot);
235    let Some(f) = snapshot.feature.as_ref() else {
236        // A project with nothing planned yet is a beginning, not an error.
237        if snapshot.features.is_empty()
238            && !snapshot
239                .diagnostics
240                .iter()
241                .any(|d| d.code == "select.not-found")
242        {
243            let unit = format.messages().unit;
244            let create = (format.planning().creates.first())
245                .or((format.planning().toward_tasks)(false).first())
246                .map_or_else(
247                    || "speccoder spec".to_owned(),
248                    |s| format!("speccoder spec {s} \"…\""),
249                );
250            return CommandResult::new(
251                "report",
252                CommandStatus::Ok,
253                &format!("no {unit}s yet — `{create}` writes the first one"),
254            )
255            .with_next(vec![speccoder_core::next::NextStep {
256                command: create,
257                why: format!("describe the {unit}; its spec is written for you to review"),
258            }]);
259        }
260        // Several and none current, or a pointer to one that is gone: say
261        // which exist; the code's fixes say how to pick.
262        let unit = format.messages().unit;
263        let names: Vec<&str> = snapshot.features.iter().map(|f| f.name.as_str()).collect();
264        if let Some(d) = snapshot
265            .diagnostics
266            .iter()
267            .find(|d| d.code == "select.not-found")
268        {
269            return CommandResult::new(
270                "report",
271                CommandStatus::SelectionNeeded,
272                &match &d.hint {
273                    Some(h) => format!("{}; {h}", d.message),
274                    None => d.message.clone(),
275                },
276            )
277            // Named here, or remembered by the format's pointer.
278            .with_code(if feature.is_some() {
279                "FEATURE-UNKNOWN"
280            } else {
281                "FEATURE-GONE"
282            });
283        }
284        return CommandResult::new(
285            "report",
286            CommandStatus::SelectionNeeded,
287            &format!(
288                "{} {unit}s and none is current ({})",
289                names.len(),
290                names.join(", ")
291            ),
292        );
293    };
294    let artifacts: Vec<String> = [
295        ("spec", f.artifacts.spec),
296        ("plan", f.artifacts.plan),
297        ("tasks", f.artifacts.tasks),
298    ]
299    .into_iter()
300    .filter(|(_, on)| *on)
301    .map(|(n, _)| n.to_owned())
302    .collect();
303    let uncommitted = crate::hosting::uncommitted(path, feature);
304    // No task list yet: the feature is being planned — a stage, not an
305    // error. The report says what exists and which planning skills are next.
306    let Some(checkout_tasks) = f.tasks.as_ref() else {
307        let planning: Vec<String> = (format.planning().toward_tasks)(f.artifacts.plan)
308            .iter()
309            .map(|s| (*s).to_owned())
310            .collect();
311        return CommandResult::new(
312            "report",
313            CommandStatus::Ok,
314            &format!(
315                "{} is being planned: {} written, no {} yet",
316                f.feature.name,
317                if artifacts.is_empty() {
318                    "nothing".to_owned()
319                } else {
320                    speccoder_core::words::listed(&artifacts)
321                },
322                format.messages().tasks_file
323            ),
324        )
325        .with_data(CommandData::Report(Box::new(StatusReport {
326            stories: Vec::new(),
327            review: crate::review::totals_of(
328                Path::new(&snapshot.root),
329                format,
330                &f.feature.name,
331                &f.feature.dir,
332            ),
333            issues: issues_of(path, Some(&f.feature.name)),
334            feature: f.feature.name.clone(),
335            branch: None,
336            source: "checkout".to_owned(),
337            selected_by: crate::current::reason_text(snapshot.selection.reason, format),
338            journey: journey_of(&artifacts, &uncommitted, 0, 0),
339            artifacts,
340            planning,
341            uncommitted,
342            unmerged_commits: 0,
343            tasks: Vec::new(),
344            convergence: Vec::new(),
345            trace: Vec::new(),
346            totals: speccoder_core::StatusTotals::default(),
347        })));
348    };
349    let name = f.feature.name.clone();
350    let branch = format!("speccoder/{name}");
351    let root = Path::new(&snapshot.root);
352    let git = Git::at(root);
353    let has_branch = git
354        .succeeds(&[
355            "rev-parse",
356            "--verify",
357            "-q",
358            &format!("refs/heads/{branch}"),
359        ])
360        .unwrap_or(false);
361
362    let mut prefix = String::new();
363    let (parsed, source, log, unmerged) = if has_branch {
364        // tasks.md as committed at the branch tip, by its repository path.
365        let top = git.toplevel().ok().flatten();
366        let canonical = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
367        let rel = top
368            .as_deref()
369            .and_then(|t| {
370                canonical(root)
371                    .strip_prefix(canonical(t))
372                    .ok()
373                    .map(Path::to_path_buf)
374            })
375            .unwrap_or_default();
376        prefix = rel.to_string_lossy().replace('\\', "/");
377        if !prefix.is_empty() {
378            prefix.push('/');
379        }
380        let repo_path = rel
381            .join(&checkout_tasks.path)
382            .to_string_lossy()
383            .replace('\\', "/");
384        let text = git
385            .run(&["show", &format!("{branch}:{repo_path}")])
386            .map(|b| String::from_utf8_lossy(&b).into_owned());
387        // In place, an ignored task list is never committed: its ticks are
388        // the checkout's, checked against the commits' `Task-Line`.
389        let local = text.is_err()
390            && !git
391                .succeeds(&["ls-files", "--error-unmatch", "--", &repo_path])
392                .unwrap_or(false);
393        let parsed = match text {
394            Ok(text) => format.parse_tasks(&checkout_tasks.path, &text).0,
395            Err(_) if local => checkout_tasks.clone(),
396            Err(_) => {
397                return CommandResult::new(
398                    "report",
399                    CommandStatus::GitPrecondition,
400                    &format!("{branch} has no {repo_path}"),
401                );
402            }
403        };
404        let format = format!(
405            "--format=%H{FS}%s{FS}%(trailers:key=Spec-Task,valueonly){FS}%(trailers:key=Verdict,valueonly){FS}%(trailers:key=Run,valueonly){FS}%(trailers:key=Reason,valueonly){FS}%(trailers:key=Task-Line,valueonly){FS}%(trailers:key=Intent-Digest,valueonly){FS}%(trailers:key=Acceptance-Strength,valueonly){FS}%(trailers:key=Regression-Only,valueonly){FS}%b{RS}"
406        );
407        let log = git
408            .run(&["log", &format, &branch])
409            .map(|b| String::from_utf8_lossy(&b).into_owned())
410            .unwrap_or_default();
411        let unmerged = git
412            .line(&["rev-list", "--count", &format!("HEAD..{branch}")])
413            .ok()
414            .and_then(|n| n.trim().parse().ok())
415            .unwrap_or(0);
416        (
417            parsed,
418            if local { "checkout" } else { "branch" },
419            log,
420            unmerged,
421        )
422    } else {
423        (checkout_tasks.clone(), "checkout", String::new(), 0)
424    };
425    let local_ticks = has_branch && source == "checkout";
426    let lines = if local_ticks {
427        open_lines(&root.join(&checkout_tasks.path), &parsed)
428    } else {
429        BTreeMap::new()
430    };
431    let (evidence, convergence) = read_log(&log, &name);
432    let saved = crate::attempts::list(root, &name);
433    let skipped = crate::controls::skipped(root, &name);
434    let mut tasks = statuses(&parsed, &evidence, &lines, &saved, &skipped);
435    // Who does each task: derived from its line, its unit and its stop.
436    for (t, p) in tasks.iter_mut().zip(&parsed.tasks) {
437        let open = !matches!(
438            t.state.as_str(),
439            "verified" | "regression_only" | "attested" | "ticked_without_evidence" | "skipped"
440        );
441        t.lane = speccoder_core::lane::classify(
442            &p.title,
443            open && p.yours,
444            open && t
445                .last_attempt
446                .as_ref()
447                .is_some_and(|a| a.outcome == "blocked"),
448            &f.feature.dir,
449            &format.rules().judged,
450        );
451        // A planning attempt that changed code made the task code.
452        if t.lane == speccoder_core::lane::Lane::Planning
453            && saved
454                .iter()
455                .any(|a| a.task == t.id && a.outcome == crate::pipeline::CHANGED_CODE)
456        {
457            t.lane = speccoder_core::lane::Lane::Code;
458        }
459    }
460    // Changes a run set aside, newest first: the person decides on them,
461    // whatever became of the task.
462    for a in saved.iter().filter(|a| crate::controls::is_set_aside(a)) {
463        if let Some(t) = tasks
464            .iter_mut()
465            .find(|t| t.id == a.task && t.set_aside.is_none())
466        {
467            t.set_aside = Some(speccoder_core::SetAside {
468                reference: a.reference.clone(),
469                files: crate::controls::changed_files(root, &a.commit),
470            });
471        }
472    }
473    // What each committed tick's note says (signatures are `attest verify`'s).
474    for t in tasks.iter_mut() {
475        if let Some(commit) = t.commit.as_deref() {
476            t.attestation = Some(crate::attest::note_state(root, commit));
477        }
478    }
479    if !crate::drift::mark(root, format, &f.feature.dir, &prefix, &mut tasks) && local_ticks {
480        // The intent is not in git (in place, ignored): the commits'
481        // `Intent-Digest` says whether it changed, not where.
482        let now = crate::in_place::intent_digest(
483            root,
484            &crate::tools::policy::Policy::new(&[], &[]).rules(format.rules()),
485            format.messages().tasks_file,
486        );
487        for t in &mut tasks {
488            let judged = evidence.get(&t.id).map(|e| e.intent.as_str());
489            if t.commit.is_some() && judged.is_some_and(|i| !i.is_empty() && i != now) {
490                t.drift = Some(speccoder_core::Drift {
491                    requirements: Vec::new(),
492                    files: Vec::new(),
493                });
494            }
495        }
496    }
497    let mut trace = trace(&format.requirement_ids(root, &f.feature.dir), &tasks);
498    trace.extend(inherited(root, &name));
499    let totals = totals(&tasks);
500    let finished = totals.verified
501        + totals.regression_only
502        + totals.attested
503        + totals.ticked_without_evidence
504        + totals.skipped;
505    let done =
506        totals.verified + totals.regression_only + totals.attested + totals.ticked_without_evidence;
507    // Only what there is: a first report says "0/11 done: 3 ready, 8
508    // blocked", not four kinds of evidence nothing has yet.
509    let parts: Vec<String> = [
510        (totals.verified, "verified"),
511        (totals.regression_only, "regression only"),
512        (totals.attested, "attested"),
513        (totals.ticked_without_evidence, "without evidence"),
514    ]
515    .iter()
516    .filter(|(n, _)| *n > 0)
517    .map(|(n, w)| format!("{n} {w}"))
518    .collect();
519    let open: Vec<String> = [
520        (totals.ready, "ready"),
521        (totals.blocked, "blocked"),
522        (totals.skipped, "skipped"),
523    ]
524    .iter()
525    .filter(|(n, _)| *n > 0)
526    .map(|(n, w)| format!("{n} {w}"))
527    .collect();
528    // A task list without a task: nothing is done, the tasks are to write.
529    let mut message = if tasks.is_empty() {
530        format!(
531            "no tasks yet: {} lists none; {}",
532            format.messages().tasks_file,
533            format.messages().make_tasks
534        )
535    } else {
536        format!("{done}/{} done", tasks.len())
537    };
538    let planning: Vec<String> = if tasks.is_empty() {
539        (format.planning().toward_tasks)(f.artifacts.plan)
540            .iter()
541            .map(|s| (*s).to_owned())
542            .collect()
543    } else {
544        Vec::new()
545    };
546    if !parts.is_empty() {
547        message.push_str(&format!(": {}", parts.join(", ")));
548    }
549    if !open.is_empty() {
550        message.push_str(&format!(
551            "{}{}",
552            if parts.is_empty() { ": " } else { "; " },
553            open.join(", ")
554        ));
555    }
556    if !convergence.is_empty() {
557        message.push_str(&format!("; {} convergence round(s)", convergence.len()));
558    }
559    let uncited = trace.iter().filter(|r| r.task.is_none()).count();
560    if uncited > 0 {
561        message.push_str(&format!("; {uncited} requirement(s) no task cites"));
562    }
563    if totals.without_attestation > 0 {
564        message.push_str(&format!(
565            "; {} tick(s) without an attestation",
566            totals.without_attestation
567        ));
568    }
569    if totals.evidence_without_tick > 0 {
570        message.push_str(&format!(
571            "; {} committed without their local tick (the next `run --in-place` ticks them)",
572            totals.evidence_without_tick
573        ));
574    }
575    if totals.stale > 0 {
576        message.push_str(&format!(
577            "; {} tick(s) proven against an earlier wording of their requirements",
578            totals.stale
579        ));
580    }
581    let drifted = tasks.iter().filter(|t| t.drift.is_some()).count() - totals.stale;
582    if drifted > 0 {
583        message.push_str(&format!(
584            "; the spec changed since {drifted}{} tick(s), not in what they cite",
585            if totals.stale > 0 { " other" } else { "" }
586        ));
587    }
588    if local_ticks {
589        message.push_str(&format!(
590            "; ticks are local to this checkout ({} is not in git)",
591            format.messages().tasks_file
592        ));
593    }
594    if has_branch {
595        if unmerged > 0 {
596            message.push_str(&format!("; {unmerged} commit(s) on {branch} not merged"));
597        }
598    } else {
599        message.push_str("; speccoder has not worked on this feature yet");
600    }
601    // A bug task's outcome, from what speccoder keeps of the bug.
602    if let Some(state) = crate::worktree::state_dir() {
603        let plane = crate::worktree::project_state_dir(&state, root);
604        for t in &mut tasks {
605            t.bug = crate::bug::state::load(&plane, &name, &t.id)
606                .map(|b| b.outcome.as_str().to_owned());
607        }
608    }
609    // What judges each open task, and each story's scenarios: from the
610    // ticks' `Scenarios:` on the unit's branch (first-parent, as a run reads them).
611    let (shares, stories) =
612        crate::pipeline::story::story_view(&crate::pipeline::story::StoryView {
613            format,
614            snapshot,
615            feature: &name,
616            unit_dir: &f.feature.dir,
617            tasks: &parsed,
618            repo: root,
619            rev: if has_branch { &branch } else { "HEAD" },
620        });
621    for t in &mut tasks {
622        let open = !matches!(
623            t.state.as_str(),
624            "verified" | "regression_only" | "attested" | "ticked_without_evidence" | "skipped"
625        );
626        if open {
627            t.judged = shares.get(&t.id).cloned();
628        }
629    }
630    CommandResult::new("report", CommandStatus::Ok, &message).with_data(CommandData::Report(
631        Box::new(StatusReport {
632            stories,
633            review: crate::review::totals_of(root, format, &name, &f.feature.dir),
634            issues: issues_of(root, Some(&name)),
635            feature: name,
636            branch: has_branch.then_some(branch),
637            source: source.to_owned(),
638            selected_by: crate::current::reason_text(snapshot.selection.reason, format),
639            journey: journey_of(&artifacts, &uncommitted, tasks.len(), finished),
640            artifacts,
641            planning,
642            uncommitted,
643            unmerged_commits: unmerged,
644            tasks,
645            convergence,
646            trace,
647            totals,
648        }),
649    ))
650}
651
652/// `speccoder task show TASK`: the report narrowed to one task.
653#[must_use]
654pub fn show(path: &Path, feature: Option<&str>, task: &str) -> CommandResult {
655    let full = report(path, feature);
656    let Some(CommandData::Report(r)) = full.data() else {
657        return CommandResult::carried("task show", &full);
658    };
659    let Some(t) = r.tasks.iter().find(|t| t.id == task) else {
660        return CommandResult::new(
661            "task show",
662            CommandStatus::NotFound,
663            &format!("{} has no task {task}", r.feature),
664        )
665        .with_code("NOT-FOUND")
666        .with_fix(vec![format!("speccoder report --feature {}", r.feature)]);
667    };
668    let mut one = (**r).clone();
669    one.tasks = vec![t.clone()];
670    one.trace.retain(|row| row.task.as_deref() == Some(task));
671    one.convergence.clear();
672    one.totals = totals(&one.tasks);
673    let message = format!("{task}: {}", t.state.replace('_', " "));
674    CommandResult::ok("task show", &message).with_data(CommandData::Report(Box::new(one)))
675}
676
677/// A promoted unit's rows from where it came from: the lower unit's ticks
678/// of the carried requirement, proven against its earlier wording.
679fn inherited(root: &Path, unit: &str) -> Vec<TraceRow> {
680    let Some(state) = crate::worktree::state_dir() else {
681        return Vec::new();
682    };
683    let plane = crate::worktree::project_state_dir(&state, root);
684    let Some((from_unit, requirement, task)) = crate::ladder::of(&plane, unit)
685        .into_iter()
686        .find_map(|o| match o {
687            speccoder_core::ladder::Origin::PromotedFrom {
688                from_unit,
689                requirement,
690                task,
691                ..
692            } => Some((from_unit, requirement, task)),
693            _ => None,
694        })
695    else {
696        return Vec::new();
697    };
698    let lower = report(root, Some(&from_unit));
699    let Some(CommandData::Report(r)) = lower.data() else {
700        return Vec::new();
701    };
702    r.tasks
703        .iter()
704        .filter(|t| t.id == task && t.commit.is_some())
705        .map(|t| TraceRow {
706            // The lower unit's requirement, never one of this unit's.
707            requirement: format!("{from_unit}/{requirement}"),
708            scenario: None,
709            test: None,
710            task: Some(format!("{from_unit}/{}", t.id)),
711            verdict: Some(t.state.clone()),
712            changed: true,
713            inherited: Some(speccoder_core::Inherited {
714                unit: from_unit.clone(),
715                requirement: requirement.clone(),
716                task: t.id.clone(),
717                commit: t.commit.clone(),
718            }),
719        })
720        .collect()
721}
722
723/// One row per requirement and task citing it (by its identifier as a word
724/// in the title); a requirement no task cites is a row of its own.
725fn trace(requirements: &[(String, String)], tasks: &[TaskStatus]) -> Vec<TraceRow> {
726    requirements
727        .iter()
728        .flat_map(|(id, _)| {
729            let rows: Vec<TraceRow> = tasks
730                .iter()
731                .filter(|t| crate::attest::cites(&t.title, id))
732                .map(|t| TraceRow {
733                    requirement: id.clone(),
734                    scenario: None,
735                    test: None,
736                    task: Some(t.id.clone()),
737                    verdict: Some(t.state.clone()),
738                    changed: t
739                        .drift
740                        .as_ref()
741                        .is_some_and(|d| d.requirements.iter().any(|r| r.id == *id)),
742                    inherited: None,
743                })
744                .collect();
745            if rows.is_empty() {
746                vec![TraceRow {
747                    requirement: id.clone(),
748                    scenario: None,
749                    test: None,
750                    task: None,
751                    verdict: None,
752                    changed: false,
753                    inherited: None,
754                }]
755            } else {
756                rows
757            }
758        })
759        .collect()
760}
761
762/// Each task's line with its box read as open, hashed: what an in-place
763/// commit's `Task-Line` names.
764fn open_lines(file: &Path, parsed: &ParsedTasks) -> BTreeMap<String, String> {
765    let text = std::fs::read_to_string(file).unwrap_or_default();
766    let lines: Vec<&str> = text.lines().collect();
767    parsed
768        .tasks
769        .iter()
770        .filter_map(|t| {
771            let line = lines.get(usize::try_from(t.line).ok()?.checked_sub(1)?)?;
772            let open = crate::in_place::untick(line.as_bytes());
773            Some((t.id.clone(), crate::integrity::sha256_hex(&open)))
774        })
775        .collect()
776}
777
778fn journey_of(
779    artifacts: &[String],
780    uncommitted: &[String],
781    total: usize,
782    finished: usize,
783) -> Vec<speccoder_core::actions::JourneyStep> {
784    let has = |a: &str| artifacts.iter().any(|x| x == a);
785    speccoder_core::actions::journey(speccoder_core::actions::JourneyFacts {
786        spec: has("spec"),
787        plan: has("plan"),
788        tasks: has("tasks"),
789        uncommitted: !uncommitted.is_empty(),
790        total,
791        finished,
792    })
793}
794
795/// The GitHub issue addresses the feature's documents name.
796fn issues_of(root: &Path, feature: Option<&str>) -> Vec<String> {
797    let mut out: Vec<String> = Vec::new();
798    for (_, _, text) in crate::documents::sources(root, feature) {
799        for url in crate::github::issue_urls(&text) {
800            if !out.contains(&url) {
801                out.push(url);
802            }
803        }
804    }
805    out
806}
807
808#[cfg(test)]
809mod tests {
810    use super::*;
811
812    #[test]
813    fn a_requirement_no_task_cites_is_a_row_of_its_own() {
814        let task = |id: &str, title: &str, state: &str| TaskStatus {
815            lane: speccoder_core::lane::Lane::default(),
816            id: id.to_owned(),
817            title: title.to_owned(),
818            phase: "Phase 3".to_owned(),
819            state: state.to_owned(),
820            drift: None,
821            blocked_by: Vec::new(),
822            commit: None,
823            run_id: None,
824            last_attempt: None,
825            judged: None,
826            set_aside: None,
827            bug: None,
828            regression: None,
829            note: None,
830            attestation: None,
831            strength: None,
832        };
833        let ids = |v: &[&str]| {
834            v.iter()
835                .map(|i| ((*i).to_owned(), String::new()))
836                .collect::<Vec<_>>()
837        };
838        let tasks = [
839            task("T001", "Parse the config (FR-001, FR-002)", "verified"),
840            task("T002", "Render it per FR-002", "ready"),
841            task("T003", "Unrelated FR-0010 work", "ready"),
842        ];
843        let rows = trace(&ids(&["FR-001", "FR-002", "FR-003"]), &tasks);
844        let shown: Vec<_> = rows
845            .iter()
846            .map(|r| {
847                (
848                    r.requirement.as_str(),
849                    r.task.as_deref(),
850                    r.verdict.as_deref(),
851                )
852            })
853            .collect();
854        assert_eq!(
855            shown,
856            [
857                ("FR-001", Some("T001"), Some("verified")),
858                ("FR-002", Some("T001"), Some("verified")),
859                ("FR-002", Some("T002"), Some("ready")),
860                ("FR-003", None, None),
861            ]
862        );
863    }
864
865    #[test]
866    fn trailers_and_rounds_are_read_newest_first() {
867        let rec = |c: &str, s: &str, t: &str, v: &str, r: &str, b: &str| {
868            format!("{c}{FS}{s}{FS}{t}\n{FS}{v}\n{FS}{r}\n{FS}{FS}{FS}{FS}{FS}{FS}{b}{RS}\n")
869        };
870        let log = [
871            rec(
872                "c4",
873                "speccoder: T003 again",
874                "f/T003",
875                "verified",
876                "run_b",
877                "",
878            ),
879            rec(
880                "c3",
881                "speccoder: converge round 1 (1 task)",
882                "",
883                "",
884                "",
885                "T003 Fix it per FR-1 (missing)\n\nSpec-Feature: f\nRun: run_c\n",
886            ),
887            rec(
888                "c2",
889                "speccoder: T003 first",
890                "f/T003",
891                "regression_only",
892                "run_a",
893                "",
894            ),
895            rec("c1", "init", "", "", "", ""),
896            rec("c0", "other feature", "g/T001", "verified", "x", ""),
897        ]
898        .concat();
899        let (ev, rounds) = read_log(&log, "f");
900        assert_eq!(ev.len(), 1);
901        assert_eq!(
902            (ev["T003"].commit.as_str(), ev["T003"].verdict.as_str()),
903            ("c4", "verified")
904        );
905        assert_eq!(rounds.len(), 1);
906        assert_eq!(rounds[0].tasks, ["T003 Fix it per FR-1 (missing)"]);
907    }
908}