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 trace = trace(&format.requirement_ids(root, &f.feature.dir), &tasks);
495    let totals = totals(&tasks);
496    let finished = totals.verified
497        + totals.regression_only
498        + totals.attested
499        + totals.ticked_without_evidence
500        + totals.skipped;
501    let done =
502        totals.verified + totals.regression_only + totals.attested + totals.ticked_without_evidence;
503    // Only what there is: a first report says "0/11 done: 3 ready, 8
504    // blocked", not four kinds of evidence nothing has yet.
505    let parts: Vec<String> = [
506        (totals.verified, "verified"),
507        (totals.regression_only, "regression only"),
508        (totals.attested, "attested"),
509        (totals.ticked_without_evidence, "without evidence"),
510    ]
511    .iter()
512    .filter(|(n, _)| *n > 0)
513    .map(|(n, w)| format!("{n} {w}"))
514    .collect();
515    let open: Vec<String> = [
516        (totals.ready, "ready"),
517        (totals.blocked, "blocked"),
518        (totals.skipped, "skipped"),
519    ]
520    .iter()
521    .filter(|(n, _)| *n > 0)
522    .map(|(n, w)| format!("{n} {w}"))
523    .collect();
524    // A task list without a task: nothing is done, the tasks are to write.
525    let mut message = if tasks.is_empty() {
526        format!(
527            "no tasks yet: {} lists none; {}",
528            format.messages().tasks_file,
529            format.messages().make_tasks
530        )
531    } else {
532        format!("{done}/{} done", tasks.len())
533    };
534    let planning: Vec<String> = if tasks.is_empty() {
535        (format.planning().toward_tasks)(f.artifacts.plan)
536            .iter()
537            .map(|s| (*s).to_owned())
538            .collect()
539    } else {
540        Vec::new()
541    };
542    if !parts.is_empty() {
543        message.push_str(&format!(": {}", parts.join(", ")));
544    }
545    if !open.is_empty() {
546        message.push_str(&format!(
547            "{}{}",
548            if parts.is_empty() { ": " } else { "; " },
549            open.join(", ")
550        ));
551    }
552    if !convergence.is_empty() {
553        message.push_str(&format!("; {} convergence round(s)", convergence.len()));
554    }
555    let uncited = trace.iter().filter(|r| r.task.is_none()).count();
556    if uncited > 0 {
557        message.push_str(&format!("; {uncited} requirement(s) no task cites"));
558    }
559    if totals.without_attestation > 0 {
560        message.push_str(&format!(
561            "; {} tick(s) without an attestation",
562            totals.without_attestation
563        ));
564    }
565    if totals.evidence_without_tick > 0 {
566        message.push_str(&format!(
567            "; {} committed without their local tick (the next `run --in-place` ticks them)",
568            totals.evidence_without_tick
569        ));
570    }
571    if totals.stale > 0 {
572        message.push_str(&format!(
573            "; {} tick(s) proven against an earlier wording of their requirements",
574            totals.stale
575        ));
576    }
577    let drifted = tasks.iter().filter(|t| t.drift.is_some()).count() - totals.stale;
578    if drifted > 0 {
579        message.push_str(&format!(
580            "; the spec changed since {drifted}{} tick(s), not in what they cite",
581            if totals.stale > 0 { " other" } else { "" }
582        ));
583    }
584    if local_ticks {
585        message.push_str(&format!(
586            "; ticks are local to this checkout ({} is not in git)",
587            format.messages().tasks_file
588        ));
589    }
590    if has_branch {
591        if unmerged > 0 {
592            message.push_str(&format!("; {unmerged} commit(s) on {branch} not merged"));
593        }
594    } else {
595        message.push_str("; speccoder has not worked on this feature yet");
596    }
597    // A bug task's outcome, from what speccoder keeps of the bug.
598    if let Some(state) = crate::worktree::state_dir() {
599        let plane = crate::worktree::project_state_dir(&state, root);
600        for t in &mut tasks {
601            t.bug = crate::bug::state::load(&plane, &name, &t.id)
602                .map(|b| b.outcome.as_str().to_owned());
603        }
604    }
605    CommandResult::new("report", CommandStatus::Ok, &message).with_data(CommandData::Report(
606        Box::new(StatusReport {
607            review: crate::review::totals_of(root, format, &name, &f.feature.dir),
608            issues: issues_of(root, Some(&name)),
609            feature: name,
610            branch: has_branch.then_some(branch),
611            source: source.to_owned(),
612            selected_by: crate::current::reason_text(snapshot.selection.reason, format),
613            journey: journey_of(&artifacts, &uncommitted, tasks.len(), finished),
614            artifacts,
615            planning,
616            uncommitted,
617            unmerged_commits: unmerged,
618            tasks,
619            convergence,
620            trace,
621            totals,
622        }),
623    ))
624}
625
626/// `speccoder task show TASK`: the report narrowed to one task.
627#[must_use]
628pub fn show(path: &Path, feature: Option<&str>, task: &str) -> CommandResult {
629    let full = report(path, feature);
630    let Some(CommandData::Report(r)) = full.data() else {
631        return CommandResult::carried("task show", &full);
632    };
633    let Some(t) = r.tasks.iter().find(|t| t.id == task) else {
634        return CommandResult::new(
635            "task show",
636            CommandStatus::NotFound,
637            &format!("{} has no task {task}", r.feature),
638        )
639        .with_code("NOT-FOUND")
640        .with_fix(vec![format!("speccoder report --feature {}", r.feature)]);
641    };
642    let mut one = (**r).clone();
643    one.tasks = vec![t.clone()];
644    one.trace.retain(|row| row.task.as_deref() == Some(task));
645    one.convergence.clear();
646    one.totals = totals(&one.tasks);
647    let message = format!("{task}: {}", t.state.replace('_', " "));
648    CommandResult::ok("task show", &message).with_data(CommandData::Report(Box::new(one)))
649}
650
651/// One row per requirement and task citing it (by its identifier as a word
652/// in the title); a requirement no task cites is a row of its own.
653fn trace(requirements: &[(String, String)], tasks: &[TaskStatus]) -> Vec<TraceRow> {
654    requirements
655        .iter()
656        .flat_map(|(id, _)| {
657            let rows: Vec<TraceRow> = tasks
658                .iter()
659                .filter(|t| crate::attest::cites(&t.title, id))
660                .map(|t| TraceRow {
661                    requirement: id.clone(),
662                    scenario: None,
663                    test: None,
664                    task: Some(t.id.clone()),
665                    verdict: Some(t.state.clone()),
666                    changed: t
667                        .drift
668                        .as_ref()
669                        .is_some_and(|d| d.requirements.iter().any(|r| r.id == *id)),
670                })
671                .collect();
672            if rows.is_empty() {
673                vec![TraceRow {
674                    requirement: id.clone(),
675                    scenario: None,
676                    test: None,
677                    task: None,
678                    verdict: None,
679                    changed: false,
680                }]
681            } else {
682                rows
683            }
684        })
685        .collect()
686}
687
688/// Each task's line with its box read as open, hashed: what an in-place
689/// commit's `Task-Line` names.
690fn open_lines(file: &Path, parsed: &ParsedTasks) -> BTreeMap<String, String> {
691    let text = std::fs::read_to_string(file).unwrap_or_default();
692    let lines: Vec<&str> = text.lines().collect();
693    parsed
694        .tasks
695        .iter()
696        .filter_map(|t| {
697            let line = lines.get(usize::try_from(t.line).ok()?.checked_sub(1)?)?;
698            let open = crate::in_place::untick(line.as_bytes());
699            Some((t.id.clone(), crate::integrity::sha256_hex(&open)))
700        })
701        .collect()
702}
703
704fn journey_of(
705    artifacts: &[String],
706    uncommitted: &[String],
707    total: usize,
708    finished: usize,
709) -> Vec<speccoder_core::actions::JourneyStep> {
710    let has = |a: &str| artifacts.iter().any(|x| x == a);
711    speccoder_core::actions::journey(speccoder_core::actions::JourneyFacts {
712        spec: has("spec"),
713        plan: has("plan"),
714        tasks: has("tasks"),
715        uncommitted: !uncommitted.is_empty(),
716        total,
717        finished,
718    })
719}
720
721/// The GitHub issue addresses the feature's documents name.
722fn issues_of(root: &Path, feature: Option<&str>) -> Vec<String> {
723    let mut out: Vec<String> = Vec::new();
724    for (_, _, text) in crate::documents::sources(root, feature) {
725        for url in crate::github::issue_urls(&text) {
726            if !out.contains(&url) {
727                out.push(url);
728            }
729        }
730    }
731    out
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737
738    #[test]
739    fn a_requirement_no_task_cites_is_a_row_of_its_own() {
740        let task = |id: &str, title: &str, state: &str| TaskStatus {
741            lane: speccoder_core::lane::Lane::default(),
742            id: id.to_owned(),
743            title: title.to_owned(),
744            phase: "Phase 3".to_owned(),
745            state: state.to_owned(),
746            drift: None,
747            blocked_by: Vec::new(),
748            commit: None,
749            run_id: None,
750            last_attempt: None,
751            set_aside: None,
752            bug: None,
753            regression: None,
754            note: None,
755            attestation: None,
756            strength: None,
757        };
758        let ids = |v: &[&str]| {
759            v.iter()
760                .map(|i| ((*i).to_owned(), String::new()))
761                .collect::<Vec<_>>()
762        };
763        let tasks = [
764            task("T001", "Parse the config (FR-001, FR-002)", "verified"),
765            task("T002", "Render it per FR-002", "ready"),
766            task("T003", "Unrelated FR-0010 work", "ready"),
767        ];
768        let rows = trace(&ids(&["FR-001", "FR-002", "FR-003"]), &tasks);
769        let shown: Vec<_> = rows
770            .iter()
771            .map(|r| {
772                (
773                    r.requirement.as_str(),
774                    r.task.as_deref(),
775                    r.verdict.as_deref(),
776                )
777            })
778            .collect();
779        assert_eq!(
780            shown,
781            [
782                ("FR-001", Some("T001"), Some("verified")),
783                ("FR-002", Some("T001"), Some("verified")),
784                ("FR-002", Some("T002"), Some("ready")),
785                ("FR-003", None, None),
786            ]
787        );
788    }
789
790    #[test]
791    fn trailers_and_rounds_are_read_newest_first() {
792        let rec = |c: &str, s: &str, t: &str, v: &str, r: &str, b: &str| {
793            format!("{c}{FS}{s}{FS}{t}\n{FS}{v}\n{FS}{r}\n{FS}{FS}{FS}{FS}{FS}{FS}{b}{RS}\n")
794        };
795        let log = [
796            rec(
797                "c4",
798                "speccoder: T003 again",
799                "f/T003",
800                "verified",
801                "run_b",
802                "",
803            ),
804            rec(
805                "c3",
806                "speccoder: converge round 1 (1 task)",
807                "",
808                "",
809                "",
810                "T003 Fix it per FR-1 (missing)\n\nSpec-Feature: f\nRun: run_c\n",
811            ),
812            rec(
813                "c2",
814                "speccoder: T003 first",
815                "f/T003",
816                "regression_only",
817                "run_a",
818                "",
819            ),
820            rec("c1", "init", "", "", "", ""),
821            rec("c0", "other feature", "g/T001", "verified", "x", ""),
822        ]
823        .concat();
824        let (ev, rounds) = read_log(&log, "f");
825        assert_eq!(ev.len(), 1);
826        assert_eq!(
827            (ev["T003"].commit.as_str(), ev["T003"].verdict.as_str()),
828            ("c4", "verified")
829        );
830        assert_eq!(rounds.len(), 1);
831        assert_eq!(rounds[0].tasks, ["T003 Fix it per FR-1 (missing)"]);
832    }
833}