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