1use 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
17const FS: char = '\u{1f}';
19const RS: char = '\u{1e}';
20
21#[derive(Debug, Clone)]
23struct Evidence {
24 commit: String,
25 verdict: String,
26 run: String,
27 reason: String,
28 task_line: String,
30 intent: String,
32 strength: String,
34}
35
36fn read_log(log: &str, feature: &str) -> (BTreeMap<String, Evidence>, Vec<ConvergenceRound>) {
40 let mut evidence: BTreeMap<String, Evidence> = BTreeMap::new();
41 let mut rounds = Vec::new();
42 for record in log.split(RS) {
43 let fields: Vec<&str> = record.trim_start_matches('\n').split(FS).collect();
44 let [
45 commit,
46 subject,
47 task,
48 verdict,
49 run,
50 reason,
51 task_line,
52 intent,
53 strength,
54 body,
55 ] = fields[..]
56 else {
57 continue;
58 };
59 if let Some(task) = task.trim().strip_prefix(&format!("{feature}/")) {
60 evidence.entry(task.to_owned()).or_insert(Evidence {
61 commit: commit.to_owned(),
62 verdict: verdict.trim().to_owned(),
63 run: run.trim().to_owned(),
64 reason: reason.trim().to_owned(),
65 task_line: task_line.trim().to_owned(),
66 intent: intent.trim().trim_start_matches("sha256:").to_owned(),
67 strength: strength.trim().to_owned(),
68 });
69 } else if let Some(n) = subject
70 .strip_prefix("speccoder: converge round ")
71 .and_then(|r| r.split(' ').next())
72 .and_then(|n| n.parse::<u32>().ok())
73 {
74 rounds.push(ConvergenceRound {
75 round: n,
76 commit: commit.to_owned(),
77 tasks: body
78 .lines()
79 .filter(|l| {
80 l.strip_prefix('T')
81 .is_some_and(|r| r.starts_with(|c: char| c.is_ascii_digit()))
82 })
83 .map(str::to_owned)
84 .collect(),
85 });
86 }
87 }
88 rounds.reverse();
89 (evidence, rounds)
90}
91
92fn statuses(
96 parsed: &ParsedTasks,
97 evidence: &BTreeMap<String, Evidence>,
98 lines: &BTreeMap<String, String>,
99 saved: &[crate::attempts::Saved],
100 skipped: &BTreeMap<String, String>,
101) -> Vec<TaskStatus> {
102 let (schedule, _) = speccoder_core::graph::schedule(parsed);
103 parsed
104 .tasks
105 .iter()
106 .map(|t| {
107 let scheduled = schedule.tasks.iter().find(|s| s.id == t.id);
108 let found = evidence.get(&t.id).filter(|e| {
109 e.task_line.is_empty() || lines.get(&t.id).is_none_or(|h| *h == e.task_line)
110 });
111 let untick = found.filter(|e| !t.done && !e.task_line.is_empty() && !lines.is_empty());
113 let state = if untick.is_some() {
114 "evidence_without_tick".to_owned()
115 } else if t.done {
116 match found.map(|e| e.verdict.as_str()) {
117 Some(v @ ("verified" | "regression_only" | "attested")) => v.to_owned(),
118 _ => "ticked_without_evidence".to_owned(),
119 }
120 } else if skipped.contains_key(&t.id) {
121 "skipped".to_owned()
122 } else if scheduled.is_some_and(|s| s.state == TaskState::Ready) {
123 "ready".to_owned()
124 } else {
125 "blocked".to_owned()
126 };
127 TaskStatus {
128 id: t.id.clone(),
129 title: t.title.clone(),
130 phase: t.phase.clone().unwrap_or_default(),
131 blocked_by: if t.done {
132 Vec::new()
133 } else {
134 scheduled.map(|s| s.blocked_by.clone()).unwrap_or_default()
135 },
136 commit: found
137 .filter(|_| t.done || untick.is_some())
138 .map(|e| e.commit.clone()),
139 attestation: None,
140 strength: found
141 .filter(|e| t.done && !e.strength.is_empty())
142 .map(|e| e.strength.clone()),
143 drift: None,
144 run_id: found
145 .filter(|e| t.done && !e.run.is_empty())
146 .map(|e| e.run.clone()),
147 last_attempt: saved.iter().find(|a| !t.done && a.task == t.id).map(|a| {
149 speccoder_core::LastAttempt {
150 outcome: a.outcome.clone(),
151 reason: a.reason.clone(),
152 run_id: a.run_id.clone(),
153 reference: a.reference.clone(),
154 }
155 }),
156 note: if t.done {
157 found.map(|e| e.reason.clone()).filter(|r| !r.is_empty())
158 } else {
159 skipped.get(&t.id).cloned()
160 },
161 state,
162 }
163 })
164 .collect()
165}
166
167fn totals(tasks: &[TaskStatus]) -> StatusTotals {
168 let n = |s: &str| tasks.iter().filter(|t| t.state == s).count();
169 StatusTotals {
170 verified: n("verified"),
171 regression_only: n("regression_only"),
172 ticked_without_evidence: n("ticked_without_evidence"),
173 evidence_without_tick: n("evidence_without_tick"),
174 without_attestation: tasks
175 .iter()
176 .filter(|t| t.attestation.as_deref() == Some("missing"))
177 .count(),
178 attested: n("attested"),
179 skipped: n("skipped"),
180 ready: n("ready"),
181 blocked: n("blocked"),
182 stale: tasks
183 .iter()
184 .filter(|t| t.drift.as_ref().is_some_and(speccoder_core::Drift::stale))
185 .count(),
186 }
187}
188
189#[must_use]
191pub fn report(path: &Path, feature: Option<&str>) -> CommandResult {
192 let inspected = crate::inspect(path, feature);
193 let Some(CommandData::Inspect(snapshot)) = inspected.data() else {
194 return CommandResult::carried("report", &inspected);
195 };
196 let format = crate::format::of(snapshot);
197 let Some(f) = snapshot.feature.as_ref() else {
198 if snapshot.features.is_empty()
200 && !snapshot
201 .diagnostics
202 .iter()
203 .any(|d| d.code == "select.not-found")
204 {
205 let unit = format.messages().unit;
206 let create = (format.planning().creates.first())
207 .or((format.planning().toward_tasks)(false).first())
208 .map_or_else(
209 || "speccoder spec".to_owned(),
210 |s| format!("speccoder spec {s} \"…\""),
211 );
212 return CommandResult::new(
213 "report",
214 CommandStatus::Ok,
215 &format!("no {unit}s yet — `{create}` writes the first one"),
216 )
217 .with_next(vec![speccoder_core::next::NextStep {
218 command: create,
219 why: format!("describe the {unit}; its spec is written for you to review"),
220 }]);
221 }
222 let unit = format.messages().unit;
225 let names: Vec<&str> = snapshot.features.iter().map(|f| f.name.as_str()).collect();
226 if let Some(d) = snapshot
227 .diagnostics
228 .iter()
229 .find(|d| d.code == "select.not-found")
230 {
231 return CommandResult::new(
232 "report",
233 CommandStatus::SelectionNeeded,
234 &match &d.hint {
235 Some(h) => format!("{}; {h}", d.message),
236 None => d.message.clone(),
237 },
238 )
239 .with_code(if feature.is_some() {
241 "FEATURE-UNKNOWN"
242 } else {
243 "FEATURE-GONE"
244 });
245 }
246 return CommandResult::new(
247 "report",
248 CommandStatus::SelectionNeeded,
249 &format!(
250 "{} {unit}s and none is current ({})",
251 names.len(),
252 names.join(", ")
253 ),
254 );
255 };
256 let artifacts: Vec<String> = [
257 ("spec", f.artifacts.spec),
258 ("plan", f.artifacts.plan),
259 ("tasks", f.artifacts.tasks),
260 ]
261 .into_iter()
262 .filter(|(_, on)| *on)
263 .map(|(n, _)| n.to_owned())
264 .collect();
265 let uncommitted = crate::hosting::uncommitted(path, feature);
266 let Some(checkout_tasks) = f.tasks.as_ref() else {
269 let planning: Vec<String> = (format.planning().toward_tasks)(f.artifacts.plan)
270 .iter()
271 .map(|s| (*s).to_owned())
272 .collect();
273 return CommandResult::new(
274 "report",
275 CommandStatus::Ok,
276 &format!(
277 "{} is being planned: {} written, no {} yet",
278 f.feature.name,
279 if artifacts.is_empty() {
280 "nothing".to_owned()
281 } else {
282 artifacts.join(" and ")
283 },
284 format.messages().tasks_file
285 ),
286 )
287 .with_data(CommandData::Report(Box::new(StatusReport {
288 review: crate::review::totals_of(
289 Path::new(&snapshot.root),
290 format,
291 &f.feature.name,
292 &f.feature.dir,
293 ),
294 issues: issues_of(path, Some(&f.feature.name)),
295 feature: f.feature.name.clone(),
296 branch: None,
297 source: "checkout".to_owned(),
298 selected_by: crate::current::reason_text(snapshot.selection.reason, format),
299 journey: journey_of(&artifacts, &uncommitted, 0, 0),
300 artifacts,
301 planning,
302 uncommitted,
303 unmerged_commits: 0,
304 tasks: Vec::new(),
305 convergence: Vec::new(),
306 trace: Vec::new(),
307 totals: speccoder_core::StatusTotals::default(),
308 })));
309 };
310 let name = f.feature.name.clone();
311 let branch = format!("speccoder/{name}");
312 let root = Path::new(&snapshot.root);
313 let git = Git::at(root);
314 let has_branch = git
315 .succeeds(&[
316 "rev-parse",
317 "--verify",
318 "-q",
319 &format!("refs/heads/{branch}"),
320 ])
321 .unwrap_or(false);
322
323 let mut prefix = String::new();
324 let (parsed, source, log, unmerged) = if has_branch {
325 let top = git.toplevel().ok().flatten();
327 let canonical = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
328 let rel = top
329 .as_deref()
330 .and_then(|t| {
331 canonical(root)
332 .strip_prefix(canonical(t))
333 .ok()
334 .map(Path::to_path_buf)
335 })
336 .unwrap_or_default();
337 prefix = rel.to_string_lossy().replace('\\', "/");
338 if !prefix.is_empty() {
339 prefix.push('/');
340 }
341 let repo_path = rel
342 .join(&checkout_tasks.path)
343 .to_string_lossy()
344 .replace('\\', "/");
345 let text = git
346 .run(&["show", &format!("{branch}:{repo_path}")])
347 .map(|b| String::from_utf8_lossy(&b).into_owned());
348 let local = text.is_err()
351 && !git
352 .succeeds(&["ls-files", "--error-unmatch", "--", &repo_path])
353 .unwrap_or(false);
354 let parsed = match text {
355 Ok(text) => format.parse_tasks(&checkout_tasks.path, &text).0,
356 Err(_) if local => checkout_tasks.clone(),
357 Err(_) => {
358 return CommandResult::new(
359 "report",
360 CommandStatus::GitPrecondition,
361 &format!("{branch} has no {repo_path}"),
362 );
363 }
364 };
365 let format = format!(
366 "--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}%b{RS}"
367 );
368 let log = git
369 .run(&["log", &format, &branch])
370 .map(|b| String::from_utf8_lossy(&b).into_owned())
371 .unwrap_or_default();
372 let unmerged = git
373 .line(&["rev-list", "--count", &format!("HEAD..{branch}")])
374 .ok()
375 .and_then(|n| n.trim().parse().ok())
376 .unwrap_or(0);
377 (
378 parsed,
379 if local { "checkout" } else { "branch" },
380 log,
381 unmerged,
382 )
383 } else {
384 (checkout_tasks.clone(), "checkout", String::new(), 0)
385 };
386 let local_ticks = has_branch && source == "checkout";
387 let lines = if local_ticks {
388 open_lines(&root.join(&checkout_tasks.path), &parsed)
389 } else {
390 BTreeMap::new()
391 };
392 let (evidence, convergence) = read_log(&log, &name);
393 let saved = crate::attempts::list(root, &name);
394 let skipped = crate::controls::skipped(root, &name);
395 let mut tasks = statuses(&parsed, &evidence, &lines, &saved, &skipped);
396 for t in tasks.iter_mut() {
398 if let Some(commit) = t.commit.as_deref() {
399 t.attestation = Some(crate::attest::note_state(root, commit));
400 }
401 }
402 if !crate::drift::mark(root, format, &f.feature.dir, &prefix, &mut tasks) && local_ticks {
403 let now = crate::in_place::intent_digest(
406 root,
407 &crate::tools::policy::Policy::new(&[], &[]).rules(format.rules()),
408 format.messages().tasks_file,
409 );
410 for t in &mut tasks {
411 let judged = evidence.get(&t.id).map(|e| e.intent.as_str());
412 if t.commit.is_some() && judged.is_some_and(|i| !i.is_empty() && i != now) {
413 t.drift = Some(speccoder_core::Drift {
414 requirements: Vec::new(),
415 files: Vec::new(),
416 });
417 }
418 }
419 }
420 let trace = trace(&format.requirement_ids(root, &f.feature.dir), &tasks);
421 let totals = totals(&tasks);
422 let finished = totals.verified
423 + totals.regression_only
424 + totals.attested
425 + totals.ticked_without_evidence
426 + totals.skipped;
427 let done =
428 totals.verified + totals.regression_only + totals.attested + totals.ticked_without_evidence;
429 let parts: Vec<String> = [
432 (totals.verified, "verified"),
433 (totals.regression_only, "regression only"),
434 (totals.attested, "attested"),
435 (totals.ticked_without_evidence, "without evidence"),
436 ]
437 .iter()
438 .filter(|(n, _)| *n > 0)
439 .map(|(n, w)| format!("{n} {w}"))
440 .collect();
441 let open: Vec<String> = [
442 (totals.ready, "ready"),
443 (totals.blocked, "blocked"),
444 (totals.skipped, "skipped"),
445 ]
446 .iter()
447 .filter(|(n, _)| *n > 0)
448 .map(|(n, w)| format!("{n} {w}"))
449 .collect();
450 let mut message = format!("{done}/{} done", tasks.len());
451 if !parts.is_empty() {
452 message.push_str(&format!(": {}", parts.join(", ")));
453 }
454 if !open.is_empty() {
455 message.push_str(&format!(
456 "{}{}",
457 if parts.is_empty() { ": " } else { "; " },
458 open.join(", ")
459 ));
460 }
461 if !convergence.is_empty() {
462 message.push_str(&format!("; {} convergence round(s)", convergence.len()));
463 }
464 let uncited = trace.iter().filter(|r| r.task.is_none()).count();
465 if uncited > 0 {
466 message.push_str(&format!("; {uncited} requirement(s) no task cites"));
467 }
468 if totals.without_attestation > 0 {
469 message.push_str(&format!(
470 "; {} tick(s) without an attestation",
471 totals.without_attestation
472 ));
473 }
474 if totals.evidence_without_tick > 0 {
475 message.push_str(&format!(
476 "; {} committed without their local tick (the next `run --in-place` ticks them)",
477 totals.evidence_without_tick
478 ));
479 }
480 if totals.stale > 0 {
481 message.push_str(&format!(
482 "; {} tick(s) proven against an earlier wording of their requirements",
483 totals.stale
484 ));
485 }
486 let drifted = tasks.iter().filter(|t| t.drift.is_some()).count() - totals.stale;
487 if drifted > 0 {
488 message.push_str(&format!(
489 "; the spec changed since {drifted}{} tick(s), not in what they cite",
490 if totals.stale > 0 { " other" } else { "" }
491 ));
492 }
493 if local_ticks {
494 message.push_str(&format!(
495 "; ticks are local to this checkout ({} is not in git)",
496 format.messages().tasks_file
497 ));
498 }
499 if has_branch {
500 if unmerged > 0 {
501 message.push_str(&format!("; {unmerged} commit(s) on {branch} not merged"));
502 }
503 } else {
504 message.push_str("; speccoder has not worked on this feature yet");
505 }
506 CommandResult::new("report", CommandStatus::Ok, &message).with_data(CommandData::Report(
507 Box::new(StatusReport {
508 review: crate::review::totals_of(root, format, &name, &f.feature.dir),
509 issues: issues_of(root, Some(&name)),
510 feature: name,
511 branch: has_branch.then_some(branch),
512 source: source.to_owned(),
513 selected_by: crate::current::reason_text(snapshot.selection.reason, format),
514 journey: journey_of(&artifacts, &uncommitted, tasks.len(), finished),
515 artifacts,
516 planning: Vec::new(),
517 uncommitted,
518 unmerged_commits: unmerged,
519 tasks,
520 convergence,
521 trace,
522 totals,
523 }),
524 ))
525}
526
527#[must_use]
529pub fn show(path: &Path, feature: Option<&str>, task: &str) -> CommandResult {
530 let full = report(path, feature);
531 let Some(CommandData::Report(r)) = full.data() else {
532 return CommandResult::carried("task show", &full);
533 };
534 let Some(t) = r.tasks.iter().find(|t| t.id == task) else {
535 return CommandResult::new(
536 "task show",
537 CommandStatus::NotFound,
538 &format!("{} has no task {task}", r.feature),
539 )
540 .with_code("NOT-FOUND")
541 .with_fix(vec![format!("speccoder report --feature {}", r.feature)]);
542 };
543 let mut one = (**r).clone();
544 one.tasks = vec![t.clone()];
545 one.trace.retain(|row| row.task.as_deref() == Some(task));
546 one.convergence.clear();
547 one.totals = totals(&one.tasks);
548 let message = format!("{task}: {}", t.state.replace('_', " "));
549 CommandResult::ok("task show", &message).with_data(CommandData::Report(Box::new(one)))
550}
551
552fn trace(requirements: &[(String, String)], tasks: &[TaskStatus]) -> Vec<TraceRow> {
555 requirements
556 .iter()
557 .flat_map(|(id, _)| {
558 let rows: Vec<TraceRow> = tasks
559 .iter()
560 .filter(|t| crate::attest::cites(&t.title, id))
561 .map(|t| TraceRow {
562 requirement: id.clone(),
563 scenario: None,
564 test: None,
565 task: Some(t.id.clone()),
566 verdict: Some(t.state.clone()),
567 changed: t
568 .drift
569 .as_ref()
570 .is_some_and(|d| d.requirements.iter().any(|r| r.id == *id)),
571 })
572 .collect();
573 if rows.is_empty() {
574 vec![TraceRow {
575 requirement: id.clone(),
576 scenario: None,
577 test: None,
578 task: None,
579 verdict: None,
580 changed: false,
581 }]
582 } else {
583 rows
584 }
585 })
586 .collect()
587}
588
589fn open_lines(file: &Path, parsed: &ParsedTasks) -> BTreeMap<String, String> {
592 let text = std::fs::read_to_string(file).unwrap_or_default();
593 let lines: Vec<&str> = text.lines().collect();
594 parsed
595 .tasks
596 .iter()
597 .filter_map(|t| {
598 let line = lines.get(usize::try_from(t.line).ok()?.checked_sub(1)?)?;
599 let open = crate::in_place::untick(line.as_bytes());
600 Some((t.id.clone(), crate::integrity::sha256_hex(&open)))
601 })
602 .collect()
603}
604
605fn journey_of(
606 artifacts: &[String],
607 uncommitted: &[String],
608 total: usize,
609 finished: usize,
610) -> Vec<speccoder_core::actions::JourneyStep> {
611 let has = |a: &str| artifacts.iter().any(|x| x == a);
612 speccoder_core::actions::journey(speccoder_core::actions::JourneyFacts {
613 spec: has("spec"),
614 plan: has("plan"),
615 tasks: has("tasks"),
616 uncommitted: !uncommitted.is_empty(),
617 total,
618 finished,
619 })
620}
621
622fn issues_of(root: &Path, feature: Option<&str>) -> Vec<String> {
624 let mut out: Vec<String> = Vec::new();
625 for (_, _, text) in crate::documents::sources(root, feature) {
626 for url in crate::github::issue_urls(&text) {
627 if !out.contains(&url) {
628 out.push(url);
629 }
630 }
631 }
632 out
633}
634
635#[cfg(test)]
636mod tests {
637 use super::*;
638
639 #[test]
640 fn a_requirement_no_task_cites_is_a_row_of_its_own() {
641 let task = |id: &str, title: &str, state: &str| TaskStatus {
642 id: id.to_owned(),
643 title: title.to_owned(),
644 phase: "Phase 3".to_owned(),
645 state: state.to_owned(),
646 drift: None,
647 blocked_by: Vec::new(),
648 commit: None,
649 run_id: None,
650 last_attempt: None,
651 note: None,
652 attestation: None,
653 strength: None,
654 };
655 let ids = |v: &[&str]| {
656 v.iter()
657 .map(|i| ((*i).to_owned(), String::new()))
658 .collect::<Vec<_>>()
659 };
660 let tasks = [
661 task("T001", "Parse the config (FR-001, FR-002)", "verified"),
662 task("T002", "Render it per FR-002", "ready"),
663 task("T003", "Unrelated FR-0010 work", "ready"),
664 ];
665 let rows = trace(&ids(&["FR-001", "FR-002", "FR-003"]), &tasks);
666 let shown: Vec<_> = rows
667 .iter()
668 .map(|r| {
669 (
670 r.requirement.as_str(),
671 r.task.as_deref(),
672 r.verdict.as_deref(),
673 )
674 })
675 .collect();
676 assert_eq!(
677 shown,
678 [
679 ("FR-001", Some("T001"), Some("verified")),
680 ("FR-002", Some("T001"), Some("verified")),
681 ("FR-002", Some("T002"), Some("ready")),
682 ("FR-003", None, None),
683 ]
684 );
685 }
686
687 #[test]
688 fn trailers_and_rounds_are_read_newest_first() {
689 let rec = |c: &str, s: &str, t: &str, v: &str, r: &str, b: &str| {
690 format!("{c}{FS}{s}{FS}{t}\n{FS}{v}\n{FS}{r}\n{FS}{FS}{FS}{FS}{FS}{b}{RS}\n")
691 };
692 let log = [
693 rec(
694 "c4",
695 "speccoder: T003 again",
696 "f/T003",
697 "verified",
698 "run_b",
699 "",
700 ),
701 rec(
702 "c3",
703 "speccoder: converge round 1 (1 task)",
704 "",
705 "",
706 "",
707 "T003 Fix it per FR-1 (missing)\n\nSpec-Feature: f\nRun: run_c\n",
708 ),
709 rec(
710 "c2",
711 "speccoder: T003 first",
712 "f/T003",
713 "regression_only",
714 "run_a",
715 "",
716 ),
717 rec("c1", "init", "", "", "", ""),
718 rec("c0", "other feature", "g/T001", "verified", "x", ""),
719 ]
720 .concat();
721 let (ev, rounds) = read_log(&log, "f");
722 assert_eq!(ev.len(), 1);
723 assert_eq!(
724 (ev["T003"].commit.as_str(), ev["T003"].verdict.as_str()),
725 ("c4", "verified")
726 );
727 assert_eq!(rounds.len(), 1);
728 assert_eq!(rounds[0].tasks, ["T003 Fix it per FR-1 (missing)"]);
729 }
730}