Skip to main content

speccoder_core/
actions.rs

1//! What a person can do now: one list, computed by the runtime and
2//! rendered by every interface — the dashboard's `n`, `c` and `:` today, a
3//! desktop app or another workbench later. Every action is a CLI command
4//! too, so nothing an interface offers is out of reach of a script.
5
6use serde::{Deserialize, Serialize};
7
8/// How an interface runs an action itself.
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
10#[serde(tag = "kind", rename_all = "snake_case")]
11pub enum Runnable {
12    /// A planning skill (`speccoder spec <name> <arguments>`).
13    Skill {
14        /// The skill.
15        name: String,
16        /// Its arguments (the input, when one is asked for).
17        arguments: String,
18    },
19    /// `speccoder run`, the feature or one task.
20    Run {
21        /// One task, or the feature's ready tasks.
22        task: Option<String>,
23        /// This run's agent (`--agent`): an ACP preset or `native`; `None`
24        /// is the configured executor.
25        #[serde(default, skip_serializing_if = "Option::is_none")]
26        agent: Option<String>,
27    },
28    /// `speccoder run --converge`: the ready tasks, then the assessment of
29    /// the code against the spec as it is now, appending what remains.
30    Converge,
31    /// Commit exactly these planning files.
32    Commit {
33        /// Repository-relative paths.
34        paths: Vec<String>,
35    },
36    /// Approve the task's waiting call: the one that was shown, refused
37    /// when another waits now.
38    Approve {
39        /// The task.
40        task: String,
41        /// The call's id ([`crate::PendingCall::id`]).
42        call: String,
43        /// The digest of the call that was shown ([`crate::PendingCall::digest`]).
44        digest: String,
45    },
46    /// Reject it (the input is the reason), bound the same way.
47    Reject {
48        /// The task.
49        task: String,
50        /// The call's id ([`crate::PendingCall::id`]).
51        call: String,
52        /// The digest of the call that was shown ([`crate::PendingCall::digest`]).
53        digest: String,
54    },
55    /// Tick the task on the person's word (the input is the reason).
56    Accept {
57        /// The task.
58        task: String,
59    },
60    /// Skip the task (the input is the reason).
61    Skip {
62        /// The task.
63        task: String,
64    },
65    /// Leave a note for the task's next attempts (the input is the note).
66    Nudge {
67        /// The task.
68        task: String,
69    },
70    /// I did it: tick a step the person took on their word (`attested`;
71    /// the input, when given, is the reason).
72    Done {
73        /// The task.
74        task: String,
75    },
76    /// Hint & retry: a note for the task (the input), then a new attempt.
77    Hint {
78        /// The task.
79        task: String,
80    },
81    /// Rule that a held attempt's tests are right (the input is the reason).
82    Rule {
83        /// The task.
84        task: String,
85    },
86    /// Record the person's review of requirements (the input is the
87    /// comment; required to request changes).
88    Review {
89        /// The requirement identifiers; empty: every one not yet approved.
90        ids: Vec<String>,
91        /// `approve`, `request` (changes), `clear`; `answer` (ids: the
92        /// question) and `edit` / `edit-approve` (ids: the requirement) take
93        /// the input as the words.
94        verdict: String,
95    },
96    /// Tell a GitHub issue it is being specified as the current feature.
97    IssueComment {
98        /// The issue's number.
99        issue: u64,
100        /// Also assign it to the person.
101        assign: bool,
102    },
103    /// Record a quick change and, when `run`, run it.
104    QuickChange {
105        /// The change, in the person's words.
106        request: String,
107        /// When it is done: its acceptance scenarios.
108        checks: Vec<String>,
109        /// Run it once recorded.
110        run: bool,
111        /// The Ask conversation that suggested it, recorded as its origin.
112        #[serde(default, skip_serializing_if = "Option::is_none")]
113        asked: Option<String>,
114    },
115    /// Commit the changes set aside before the task's run onto the
116    /// feature's branch, as the person's own.
117    KeepSetAside {
118        /// The task.
119        task: String,
120    },
121    /// Discard them.
122    DropSetAside {
123        /// The task.
124        task: String,
125    },
126    /// Commit the setup a run stops on (an uncommitted lockfile, build
127    /// output not ignored) in the checkout.
128    FixSetup,
129    /// Pick the current feature.
130    Feature,
131    /// Push the feature's branch and open (or update) its draft pull request.
132    PullRequest,
133    /// Record a bug in the person's words (`speccoder bug`) and, when
134    /// `run`, reproduce it.
135    BugFix {
136        /// What happens (the symptom).
137        symptom: String,
138        /// What should happen instead (one or more).
139        expected: Vec<String>,
140        /// What must keep working (zero or more).
141        unchanged: Vec<String>,
142        /// The GitHub issue it comes from.
143        issue: Option<u64>,
144        /// The person's own reproduction tests, one per expected statement
145        /// (`PATH::NAME`).
146        tests: Vec<String>,
147        /// Someone else's fix to judge: a patch file or `pr:N`.
148        candidate: Option<String>,
149        /// Continue a bug the format's own bug step created.
150        slug: Option<String>,
151        /// Reproduce it once recorded.
152        run: bool,
153        /// The Ask conversation that suggested it, recorded as its origin.
154        #[serde(default, skip_serializing_if = "Option::is_none")]
155        asked: Option<String>,
156    },
157    /// Confirm (or, with `reject`, reject: the input is the reason) a
158    /// bug's reproductions, bound to the digest shown.
159    BugConfirm {
160        /// `<unit>/<task>`.
161        task: String,
162        /// The digest the person saw.
163        digest: String,
164        /// Reject instead.
165        reject: bool,
166    },
167    /// Keep an already-satisfied bug's reproductions as a regression test:
168    /// committed, the task attested (the input is the reason).
169    BugKeep {
170        /// `<unit>/<task>`.
171        task: String,
172    },
173    /// Continue a bug: reproduce again, or run its confirmed fix.
174    BugRun {
175        /// A bug of the format's own bug structure, by slug.
176        slug: Option<String>,
177        /// Or `<unit>/<task>`.
178        task: Option<String>,
179    },
180    /// Always Allow: approve the waiting command once and add exactly its
181    /// argv to `[commands] allow` (or `[sandbox] network_allow`).
182    AllowAlways {
183        /// The task.
184        task: String,
185        /// The waiting call's id.
186        call: String,
187    },
188    /// Add a prefix to a prefix list, as the confirmation of its coverage
189    /// preview (refused when the preview changed or is incomplete).
190    WidenPolicy {
191        /// Which list.
192        key: PolicyList,
193        /// The prefix (two elements or more).
194        prefix: Vec<String>,
195        /// The digest of the preview the person saw.
196        digest: String,
197    },
198    /// Decide the calls waiting in a run's batch together, each once.
199    DecideBatch {
200        /// The run.
201        run: String,
202        /// Approve or reject (the input is the reason).
203        verdict: BatchVerdict,
204        /// The listed calls decided (a non-empty subset).
205        calls: Vec<String>,
206        /// The digest of the list the person saw.
207        digest: String,
208        /// Start the run's asking budget again.
209        resume_asking: bool,
210    },
211    /// Write, reject, ask again for, edit or settle a requirement's tests
212    /// at review (the input: the reason, the comment or the content).
213    OracleTests {
214        /// The requirement (`US1`).
215        req: String,
216        /// What to do.
217        op: crate::oracle::OracleOp,
218        /// The test (reject, again, edit).
219        path: Option<String>,
220        /// The ambiguous scenario (reading).
221        scenario: Option<String>,
222        /// The reading meant (reading).
223        reading: Option<crate::oracle::Reading>,
224    },
225    /// Approve every approvable decision line, freeze the written tests and
226    /// start the feature's run, asking or on autopilot.
227    ApproveAndRun {
228        /// How the run asks.
229        mode: crate::oracle::RunMode,
230        /// The grant ids (object-bound grants) an autopilot run holds.
231        grants: Vec<String>,
232        /// The sheet's `sha256`: what the person saw approved and frozen.
233        /// Required from every interface but a terminal command.
234        #[serde(default, skip_serializing_if = "Option::is_none")]
235        sheet: Option<String>,
236    },
237    /// Add, delete or keep a review comment (the input: its words).
238    Comment {
239        /// What to do.
240        op: CommentOp,
241        /// What a new comment is about.
242        anchor: Option<crate::oracle::CommentAnchor>,
243        /// The draft (delete, keep).
244        id: Option<String>,
245    },
246    /// Send the comments as one revision turn.
247    CommentsSend {
248        /// The drafts the person saw (empty: every draft in the tray); a
249        /// draft sent already refuses the send.
250        ids: Vec<String>,
251    },
252    /// Undo the last revision turn: the documents back, byte for byte.
253    RevisionUndo {
254        /// The turn the person saw.
255        turn: Option<String>,
256    },
257    /// Code-view line comments as one nudge for the task's next attempt.
258    CodeNudge {
259        /// The task.
260        task: String,
261        /// The comments.
262        comments: Vec<crate::oracle::CodeComment>,
263    },
264    /// Write a story's acceptance tests at a Setup or Foundational task
265    /// (`revoke`: take the decision back) — a decision recorded in the
266    /// state directory, never an edit of the spec.
267    AcceptanceAt {
268        /// The feature.
269        feature: String,
270        /// The story (`US1`).
271        story: String,
272        /// The task.
273        task: String,
274        /// Take the decision back.
275        revoke: bool,
276    },
277    /// Rule that one scenario's oracle tests are wrong (the input is the
278    /// reason): the next run writes that scenario's tests again.
279    RuleScenario {
280        /// The task that met them.
281        task: String,
282        /// The scenario (`US3-2`).
283        scenario: String,
284    },
285    /// Install the bundled `speccoder` Spec Kit preset through Spec Kit's
286    /// own `specify preset add` (`update`: the installed one, replaced).
287    PresetAdd {
288        /// Replace an installed older version.
289        update: bool,
290    },
291    /// Plan a new feature through the format's own skills — the creating
292    /// skill, then toward the task list, then the check — stopping where a
293    /// person decides (`speccoder spec <skill> --through <t>`).
294    PlanThrough {
295        /// A new description, or the continuation after a stop.
296        from: PlanFrom,
297        /// How far.
298        through: Through,
299    },
300    /// Make `target` a project: the plan the person saw, bound to its digest
301    /// (`speccoder new`).
302    NewProject {
303        /// The folder, as the plan names it.
304        target: String,
305        /// What the person chose.
306        choices: crate::new_project::NewChoices,
307        /// The digest of the plan on screen.
308        plan_digest: String,
309    },
310    /// Undo the project speccoder created at the dispatch's root
311    /// (`speccoder new --undo`): to the Trash, or a revert of its commit.
312    UndoNewProject {
313        /// speccoder's commit, as recorded.
314        commit: String,
315    },
316    /// Clone a repository of the person's with their git (their credentials).
317    CloneRepository {
318        /// `owner/repo`.
319        repo: String,
320        /// The destination folder.
321        target: String,
322    },
323    /// Copy the bundled sample into the state directory and replay its
324    /// recorded run strictly (`speccoder sample`).
325    OpenSample {
326        /// Replace an existing copy.
327        fresh: bool,
328    },
329    /// Run the sample's own checks, offline, in its copy (the sample's
330    /// end card, *Run the checks yourself*).
331    SampleChecks,
332    /// Decline a promotion offer: it returns only when a signal that did
333    /// not hold now holds.
334    DeclinePromotion {
335        /// `<unit>/<task>`.
336        task: String,
337    },
338    /// Explore an idea read-only, ending in approaches to choose from; or
339    /// resume a session with more words.
340    Explore {
341        /// The idea (a new session) or the words added (a resumed one).
342        idea: String,
343        /// The skill to host instead of the format's own (`--skill`).
344        #[serde(default)]
345        skill: Option<String>,
346        /// The session to resume.
347        #[serde(default)]
348        resume: Option<String>,
349    },
350    /// The person's choice in a session: an approach, and the constraints
351    /// and open questions they keep or add. It composes the brief.
352    ExploreChoose {
353        /// The session (`ex-…`).
354        session: String,
355        /// 1-based, of the session's last approaches.
356        approach: usize,
357        /// The constraints, as kept and added.
358        #[serde(default)]
359        constraints: Vec<String>,
360        /// The open questions, as kept and added.
361        #[serde(default)]
362        questions: Vec<String>,
363        /// Chosen by a flag (`--choose N`), not in a prompt or the app.
364        #[serde(default)]
365        flag: bool,
366    },
367}
368
369/// How far plan through goes.
370#[derive(
371    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
372)]
373#[serde(rename_all = "snake_case")]
374pub enum Through {
375    /// The spec only.
376    Spec,
377    /// The spec and the plan.
378    Plan,
379    /// The spec, the plan and the tasks.
380    Tasks,
381    /// Then the format's check of the planning files.
382    Analyze,
383}
384
385impl Through {
386    /// Every value, in order.
387    pub const ALL: [Self; 4] = [Self::Spec, Self::Plan, Self::Tasks, Self::Analyze];
388
389    /// Its name (`tasks`).
390    #[must_use]
391    pub const fn as_str(self) -> &'static str {
392        match self {
393            Self::Spec => "spec",
394            Self::Plan => "plan",
395            Self::Tasks => "tasks",
396            Self::Analyze => "analyze",
397        }
398    }
399
400    /// The value named `s`.
401    #[must_use]
402    pub fn parse(s: &str) -> Option<Self> {
403        Self::ALL.into_iter().find(|t| t.as_str() == s)
404    }
405}
406
407/// Where a new feature's description comes from. Later rungs add theirs
408/// (an Explore brief, a promoted quick change) when they are built.
409#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
410#[serde(tag = "kind", rename_all = "snake_case")]
411pub enum FeatureSource {
412    /// The person's own words.
413    Description,
414    /// A GitHub issue's description, verbatim.
415    Issue {
416        /// Its number.
417        number: u64,
418    },
419    /// A quick change or bug that grew: its requirement verbatim, and the
420    /// Ask conversations the person chose to carry.
421    Promotion {
422        /// `<unit>/<task>`.
423        task: String,
424        /// Conversation ids (`c-…`).
425        #[serde(default)]
426        conversations: Vec<String>,
427    },
428    /// An Explore session's brief, verbatim.
429    Explore {
430        /// The session (`ex-…`).
431        session: String,
432        /// The brief's digest, checked before anything runs.
433        digest: String,
434    },
435}
436
437/// What plan through starts from.
438#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
439#[serde(tag = "kind", rename_all = "snake_case")]
440pub enum PlanFrom {
441    /// A new unit from a description.
442    Create {
443        /// What it should do, verbatim.
444        description: String,
445        /// Where the description comes from.
446        source: FeatureSource,
447    },
448    /// The next skill after a stop, derived from the unit's files.
449    Continue,
450}
451
452/// What a comment action does.
453#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
454#[serde(rename_all = "snake_case")]
455pub enum CommentOp {
456    /// A new draft.
457    Add,
458    /// Remove a draft.
459    Delete,
460    /// Keep an outdated draft.
461    Keep,
462}
463
464/// A prefix list in `speccoder.toml`.
465#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
466#[serde(rename_all = "snake_case")]
467pub enum PolicyList {
468    /// `[commands] allow_prefix`.
469    CommandsPrefix,
470    /// `[sandbox] network_allow_prefix`.
471    NetworkPrefix,
472}
473
474impl PolicyList {
475    /// Its name as serialized.
476    #[must_use]
477    pub const fn as_str(self) -> &'static str {
478        match self {
479            Self::CommandsPrefix => "commands_prefix",
480            Self::NetworkPrefix => "network_prefix",
481        }
482    }
483
484    /// The configuration key it is (`commands.allow_prefix`).
485    #[must_use]
486    pub const fn key(self) -> &'static str {
487        match self {
488            Self::CommandsPrefix => "commands.allow_prefix",
489            Self::NetworkPrefix => "sandbox.network_allow_prefix",
490        }
491    }
492
493    /// The list for a configuration key.
494    #[must_use]
495    pub fn of_key(key: &str) -> Option<Self> {
496        match key {
497            "commands.allow_prefix" | "commands_prefix" => Some(Self::CommandsPrefix),
498            "sandbox.network_allow_prefix" | "network_prefix" => Some(Self::NetworkPrefix),
499            _ => None,
500        }
501    }
502}
503
504/// A batch decision.
505#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
506#[serde(rename_all = "snake_case")]
507pub enum BatchVerdict {
508    /// Each listed call once.
509    Approve,
510    /// Each listed call, with one reason.
511    Reject,
512}
513
514/// What kind of action it is: one per [`Runnable`] kind (a run split by
515/// whether it names a task), plus [`ActionKind::Command`] for an action an
516/// interface does not run itself. Exhaustive at any one version; a new
517/// kind arrives with its `Runnable` variant (the *adding a kind* contract
518/// of `speccoder_runtime::actions::perform`).
519#[derive(
520    Debug,
521    Clone,
522    Copy,
523    PartialEq,
524    Eq,
525    Hash,
526    PartialOrd,
527    Ord,
528    Serialize,
529    Deserialize,
530    schemars::JsonSchema,
531)]
532#[serde(rename_all = "snake_case")]
533pub enum ActionKind {
534    /// [`Runnable::Skill`].
535    Skill,
536    /// [`Runnable::Run`] with a task.
537    RunTask,
538    /// [`Runnable::Run`] without one: the feature.
539    RunFeature,
540    /// [`Runnable::Converge`].
541    Converge,
542    /// [`Runnable::Commit`].
543    Commit,
544    /// [`Runnable::Approve`].
545    Approve,
546    /// [`Runnable::Reject`].
547    Reject,
548    /// [`Runnable::Accept`].
549    Accept,
550    /// [`Runnable::Skip`].
551    Skip,
552    /// [`Runnable::Nudge`].
553    Nudge,
554    /// [`Runnable::Done`].
555    Done,
556    /// [`Runnable::Hint`].
557    Hint,
558    /// [`Runnable::Rule`].
559    Rule,
560    /// [`Runnable::Review`].
561    Review,
562    /// [`Runnable::IssueComment`].
563    IssueComment,
564    /// [`Runnable::QuickChange`].
565    QuickChange,
566    /// [`Runnable::KeepSetAside`].
567    KeepSetAside,
568    /// [`Runnable::DropSetAside`].
569    DropSetAside,
570    /// [`Runnable::FixSetup`].
571    FixSetup,
572    /// [`Runnable::Feature`].
573    Feature,
574    /// [`Runnable::PullRequest`].
575    PullRequest,
576    /// [`Runnable::BugFix`].
577    BugFix,
578    /// [`Runnable::BugConfirm`].
579    BugConfirm,
580    /// [`Runnable::BugRun`].
581    BugRun,
582    /// [`Runnable::BugKeep`].
583    BugKeep,
584    /// [`Runnable::AllowAlways`].
585    AllowAlways,
586    /// [`Runnable::WidenPolicy`].
587    WidenPolicy,
588    /// [`Runnable::DecideBatch`].
589    DecideBatch,
590    /// [`Runnable::OracleTests`].
591    OracleTests,
592    /// [`Runnable::ApproveAndRun`].
593    ApproveAndRun,
594    /// [`Runnable::Comment`].
595    Comment,
596    /// [`Runnable::CommentsSend`].
597    CommentsSend,
598    /// [`Runnable::RevisionUndo`].
599    RevisionUndo,
600    /// [`Runnable::CodeNudge`].
601    CodeNudge,
602    /// [`Runnable::AcceptanceAt`].
603    AcceptanceAt,
604    /// [`Runnable::RuleScenario`].
605    RuleScenario,
606    /// [`Runnable::PresetAdd`].
607    PresetAdd,
608    /// [`Runnable::PlanThrough`].
609    PlanThrough,
610    /// [`Runnable::NewProject`].
611    NewProject,
612    /// [`Runnable::UndoNewProject`].
613    UndoNewProject,
614    /// [`Runnable::CloneRepository`].
615    CloneRepository,
616    /// [`Runnable::OpenSample`].
617    OpenSample,
618    /// [`Runnable::SampleChecks`].
619    SampleChecks,
620    /// [`Runnable::DeclinePromotion`].
621    DeclinePromotion,
622    /// [`Runnable::Explore`].
623    Explore,
624    /// [`Runnable::ExploreChoose`].
625    ExploreChoose,
626    /// No runnable: the person runs the command.
627    Command,
628}
629
630impl ActionKind {
631    /// Every kind, in declaration order (a test holds it to the enum).
632    pub const ALL: &'static [Self] = &[
633        Self::Skill,
634        Self::RunTask,
635        Self::RunFeature,
636        Self::Converge,
637        Self::Commit,
638        Self::Approve,
639        Self::Reject,
640        Self::Accept,
641        Self::Skip,
642        Self::Nudge,
643        Self::Done,
644        Self::Hint,
645        Self::Rule,
646        Self::Review,
647        Self::IssueComment,
648        Self::QuickChange,
649        Self::KeepSetAside,
650        Self::DropSetAside,
651        Self::FixSetup,
652        Self::Feature,
653        Self::PullRequest,
654        Self::BugFix,
655        Self::BugConfirm,
656        Self::BugRun,
657        Self::BugKeep,
658        Self::AllowAlways,
659        Self::WidenPolicy,
660        Self::DecideBatch,
661        Self::OracleTests,
662        Self::ApproveAndRun,
663        Self::Comment,
664        Self::CommentsSend,
665        Self::RevisionUndo,
666        Self::CodeNudge,
667        Self::AcceptanceAt,
668        Self::RuleScenario,
669        Self::PresetAdd,
670        Self::PlanThrough,
671        Self::NewProject,
672        Self::UndoNewProject,
673        Self::CloneRepository,
674        Self::OpenSample,
675        Self::SampleChecks,
676        Self::DeclinePromotion,
677        Self::Explore,
678        Self::ExploreChoose,
679        Self::Command,
680    ];
681
682    /// Its name as serialized (`run_task`).
683    #[must_use]
684    pub const fn as_str(self) -> &'static str {
685        match self {
686            Self::Skill => "skill",
687            Self::RunTask => "run_task",
688            Self::RunFeature => "run_feature",
689            Self::Converge => "converge",
690            Self::Commit => "commit",
691            Self::Approve => "approve",
692            Self::Reject => "reject",
693            Self::Accept => "accept",
694            Self::Skip => "skip",
695            Self::Nudge => "nudge",
696            Self::Done => "done",
697            Self::Hint => "hint",
698            Self::Rule => "rule",
699            Self::Review => "review",
700            Self::IssueComment => "issue_comment",
701            Self::QuickChange => "quick_change",
702            Self::KeepSetAside => "keep_set_aside",
703            Self::DropSetAside => "drop_set_aside",
704            Self::FixSetup => "fix_setup",
705            Self::Feature => "feature",
706            Self::PullRequest => "pull_request",
707            Self::BugFix => "bug_fix",
708            Self::BugConfirm => "bug_confirm",
709            Self::BugRun => "bug_run",
710            Self::BugKeep => "bug_keep",
711            Self::AllowAlways => "allow_always",
712            Self::WidenPolicy => "widen_policy",
713            Self::DecideBatch => "decide_batch",
714            Self::OracleTests => "oracle_tests",
715            Self::ApproveAndRun => "approve_and_run",
716            Self::Comment => "comment",
717            Self::CommentsSend => "comments_send",
718            Self::RevisionUndo => "revision_undo",
719            Self::CodeNudge => "code_nudge",
720            Self::AcceptanceAt => "acceptance_at",
721            Self::RuleScenario => "rule_scenario",
722            Self::PresetAdd => "preset_add",
723            Self::PlanThrough => "plan_through",
724            Self::NewProject => "new_project",
725            Self::UndoNewProject => "undo_new_project",
726            Self::CloneRepository => "clone_repository",
727            Self::OpenSample => "open_sample",
728            Self::SampleChecks => "sample_checks",
729            Self::DeclinePromotion => "decline_promotion",
730            Self::Explore => "explore",
731            Self::ExploreChoose => "explore_choose",
732            Self::Command => "command",
733        }
734    }
735
736    /// One runnable of this kind (`None` for [`ActionKind::Command`]): what
737    /// tests and documentation enumerate the kinds by.
738    #[must_use]
739    pub fn example(self) -> Option<Runnable> {
740        let task = || "T001".to_owned();
741        Some(match self {
742            Self::Skill => Runnable::Skill {
743                name: "plan".to_owned(),
744                arguments: String::new(),
745            },
746            Self::RunTask => Runnable::Run {
747                task: Some(task()),
748                agent: None,
749            },
750            Self::RunFeature => Runnable::Run {
751                task: None,
752                agent: None,
753            },
754            Self::Converge => Runnable::Converge,
755            Self::Commit => Runnable::Commit {
756                paths: vec!["plan.md".to_owned()],
757            },
758            Self::Approve => Runnable::Approve {
759                task: task(),
760                call: "0f3c".to_owned(),
761                digest: "d1".to_owned(),
762            },
763            Self::Reject => Runnable::Reject {
764                task: task(),
765                call: "0f3c".to_owned(),
766                digest: "d1".to_owned(),
767            },
768            Self::Accept => Runnable::Accept { task: task() },
769            Self::Skip => Runnable::Skip { task: task() },
770            Self::Nudge => Runnable::Nudge { task: task() },
771            Self::Done => Runnable::Done { task: task() },
772            Self::Hint => Runnable::Hint { task: task() },
773            Self::Rule => Runnable::Rule { task: task() },
774            Self::Review => Runnable::Review {
775                ids: vec!["FR-001".to_owned()],
776                verdict: "approve".to_owned(),
777            },
778            Self::IssueComment => Runnable::IssueComment {
779                issue: 42,
780                assign: false,
781            },
782            Self::QuickChange => Runnable::QuickChange {
783                request: "a change".to_owned(),
784                checks: Vec::new(),
785                run: false,
786                asked: None,
787            },
788            Self::KeepSetAside => Runnable::KeepSetAside { task: task() },
789            Self::DropSetAside => Runnable::DropSetAside { task: task() },
790            Self::FixSetup => Runnable::FixSetup,
791            Self::Feature => Runnable::Feature,
792            Self::PullRequest => Runnable::PullRequest,
793            Self::BugFix => Runnable::BugFix {
794                symptom: "saving an empty title crashes".to_owned(),
795                expected: vec!["an empty title is refused".to_owned()],
796                unchanged: Vec::new(),
797                issue: None,
798                tests: Vec::new(),
799                candidate: None,
800                slug: None,
801                run: false,
802                asked: None,
803            },
804            Self::BugConfirm => Runnable::BugConfirm {
805                task: "007-bugfixes/T001".to_owned(),
806                digest: "sha256:0".to_owned(),
807                reject: false,
808            },
809            Self::BugRun => Runnable::BugRun {
810                slug: None,
811                task: Some("007-bugfixes/T001".to_owned()),
812            },
813            Self::BugKeep => Runnable::BugKeep {
814                task: "007-bugfixes/T001".to_owned(),
815            },
816            Self::AllowAlways => Runnable::AllowAlways {
817                task: task(),
818                call: "0f3c".to_owned(),
819            },
820            Self::WidenPolicy => Runnable::WidenPolicy {
821                key: PolicyList::CommandsPrefix,
822                prefix: vec!["npm".to_owned(), "run".to_owned()],
823                digest: "d1".to_owned(),
824            },
825            Self::DecideBatch => Runnable::DecideBatch {
826                run: "run-1-0a0b0c0d".to_owned(),
827                verdict: BatchVerdict::Approve,
828                calls: vec!["0f3c".to_owned()],
829                digest: "d1".to_owned(),
830                resume_asking: false,
831            },
832            Self::OracleTests => Runnable::OracleTests {
833                req: "US1".to_owned(),
834                op: crate::oracle::OracleOp::Write,
835                path: None,
836                scenario: None,
837                reading: None,
838            },
839            Self::ApproveAndRun => Runnable::ApproveAndRun {
840                mode: crate::oracle::RunMode::Ask,
841                grants: Vec::new(),
842                sheet: None,
843            },
844            Self::Comment => Runnable::Comment {
845                op: CommentOp::Delete,
846                anchor: None,
847                id: Some("c1".to_owned()),
848            },
849            Self::CommentsSend => Runnable::CommentsSend { ids: Vec::new() },
850            Self::RevisionUndo => Runnable::RevisionUndo { turn: None },
851            Self::CodeNudge => Runnable::CodeNudge {
852                task: task(),
853                comments: vec![crate::oracle::CodeComment {
854                    path: "src/lib.rs".to_owned(),
855                    line: 1,
856                    quote: "pub fn ok() {}".to_owned(),
857                    text: "name it".to_owned(),
858                }],
859            },
860            Self::AcceptanceAt => Runnable::AcceptanceAt {
861                feature: "001-greet-function".to_owned(),
862                story: "US1".to_owned(),
863                task: "T003".to_owned(),
864                revoke: false,
865            },
866            Self::RuleScenario => Runnable::RuleScenario {
867                task: "T021".to_owned(),
868                scenario: "US3-2".to_owned(),
869            },
870            Self::PresetAdd => Runnable::PresetAdd { update: false },
871            Self::PlanThrough => Runnable::PlanThrough {
872                from: PlanFrom::Create {
873                    description: "Users can export a report as CSV".to_owned(),
874                    source: FeatureSource::Description,
875                },
876                through: Through::Tasks,
877            },
878            Self::NewProject => Runnable::NewProject {
879                target: "/tmp/md2csv".to_owned(),
880                choices: crate::new_project::NewChoices {
881                    idea: "a CLI that turns Markdown tables into CSV".to_owned(),
882                    ..crate::new_project::NewChoices::default()
883                },
884                plan_digest: "sha256:0".to_owned(),
885            },
886            Self::UndoNewProject => Runnable::UndoNewProject {
887                commit: "1a2b3c4".to_owned(),
888            },
889            Self::CloneRepository => Runnable::CloneRepository {
890                repo: "octo/hello".to_owned(),
891                target: "/tmp/hello".to_owned(),
892            },
893            Self::OpenSample => Runnable::OpenSample { fresh: false },
894            Self::SampleChecks => Runnable::SampleChecks,
895            Self::DeclinePromotion => Runnable::DeclinePromotion {
896                task: "004-quick-changes/T002".to_owned(),
897            },
898            Self::Explore => Runnable::Explore {
899                idea: "export reports as CSV".to_owned(),
900                skill: None,
901                resume: None,
902            },
903            Self::ExploreChoose => Runnable::ExploreChoose {
904                session: "ex-1a2b3c4d5e6f".to_owned(),
905                approach: 2,
906                constraints: vec!["no new dependency".to_owned()],
907                questions: Vec::new(),
908                flag: false,
909            },
910            Self::Command => return None,
911        })
912    }
913}
914
915impl Runnable {
916    /// One runnable of every kind ([`ActionKind::example`]).
917    #[must_use]
918    pub fn examples() -> Vec<Self> {
919        ActionKind::ALL.iter().filter_map(|k| k.example()).collect()
920    }
921
922    /// Its kind.
923    #[must_use]
924    pub const fn kind(&self) -> ActionKind {
925        match self {
926            Self::Skill { .. } => ActionKind::Skill,
927            Self::Run { task: Some(_), .. } => ActionKind::RunTask,
928            Self::Run { task: None, .. } => ActionKind::RunFeature,
929            Self::Converge => ActionKind::Converge,
930            Self::Commit { .. } => ActionKind::Commit,
931            Self::Approve { .. } => ActionKind::Approve,
932            Self::Reject { .. } => ActionKind::Reject,
933            Self::Accept { .. } => ActionKind::Accept,
934            Self::Skip { .. } => ActionKind::Skip,
935            Self::Nudge { .. } => ActionKind::Nudge,
936            Self::Done { .. } => ActionKind::Done,
937            Self::Hint { .. } => ActionKind::Hint,
938            Self::Rule { .. } => ActionKind::Rule,
939            Self::Review { .. } => ActionKind::Review,
940            Self::IssueComment { .. } => ActionKind::IssueComment,
941            Self::QuickChange { .. } => ActionKind::QuickChange,
942            Self::KeepSetAside { .. } => ActionKind::KeepSetAside,
943            Self::DropSetAside { .. } => ActionKind::DropSetAside,
944            Self::FixSetup => ActionKind::FixSetup,
945            Self::Feature => ActionKind::Feature,
946            Self::PullRequest => ActionKind::PullRequest,
947            Self::BugFix { .. } => ActionKind::BugFix,
948            Self::BugConfirm { .. } => ActionKind::BugConfirm,
949            Self::BugRun { .. } => ActionKind::BugRun,
950            Self::BugKeep { .. } => ActionKind::BugKeep,
951            Self::AllowAlways { .. } => ActionKind::AllowAlways,
952            Self::WidenPolicy { .. } => ActionKind::WidenPolicy,
953            Self::DecideBatch { .. } => ActionKind::DecideBatch,
954            Self::OracleTests { .. } => ActionKind::OracleTests,
955            Self::ApproveAndRun { .. } => ActionKind::ApproveAndRun,
956            Self::Comment { .. } => ActionKind::Comment,
957            Self::CommentsSend { .. } => ActionKind::CommentsSend,
958            Self::RevisionUndo { .. } => ActionKind::RevisionUndo,
959            Self::CodeNudge { .. } => ActionKind::CodeNudge,
960            Self::AcceptanceAt { .. } => ActionKind::AcceptanceAt,
961            Self::RuleScenario { .. } => ActionKind::RuleScenario,
962            Self::PresetAdd { .. } => ActionKind::PresetAdd,
963            Self::PlanThrough { .. } => ActionKind::PlanThrough,
964            Self::NewProject { .. } => ActionKind::NewProject,
965            Self::UndoNewProject { .. } => ActionKind::UndoNewProject,
966            Self::CloneRepository { .. } => ActionKind::CloneRepository,
967            Self::OpenSample { .. } => ActionKind::OpenSample,
968            Self::SampleChecks => ActionKind::SampleChecks,
969            Self::DeclinePromotion { .. } => ActionKind::DeclinePromotion,
970            Self::Explore { .. } => ActionKind::Explore,
971            Self::ExploreChoose { .. } => ActionKind::ExploreChoose,
972        }
973    }
974}
975
976/// What an action is, independent of its wording: its kind and what it
977/// is about (the task, the skill, the issue). An interface finds an action
978/// by this, never by its label.
979#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
980pub struct ActionId {
981    /// Its kind.
982    pub kind: ActionKind,
983    /// What it is about: a task's id, a skill's name, an issue's number,
984    /// a review's `verdict` (`verdict:first id`), a command's words.
985    pub subject: Option<String>,
986}
987
988/// The identity of the action that runs `run` (or, without one, stands
989/// for `command`): derived, so it cannot disagree with what runs.
990#[must_use]
991pub fn identity(run: Option<&Runnable>, command: &str) -> ActionId {
992    let Some(run) = run else {
993        // The command's words: `speccoder attest verify` → `attest verify`.
994        let words: Vec<&str> = command
995            .split_whitespace()
996            .skip_while(|w| *w == "speccoder")
997            .take_while(|w| {
998                w.chars().next().is_some_and(|c| c.is_ascii_lowercase())
999                    && w.chars()
1000                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
1001            })
1002            .collect();
1003        return ActionId {
1004            kind: ActionKind::Command,
1005            subject: (!words.is_empty()).then(|| words.join(" ")),
1006        };
1007    };
1008    let subject = match run {
1009        Runnable::Skill { name, .. } => Some(name.clone()),
1010        Runnable::Run { task, .. } => task.clone(),
1011        Runnable::Approve { task, .. }
1012        | Runnable::Reject { task, .. }
1013        | Runnable::Accept { task }
1014        | Runnable::Skip { task }
1015        | Runnable::Nudge { task }
1016        | Runnable::Done { task }
1017        | Runnable::Hint { task }
1018        | Runnable::Rule { task }
1019        | Runnable::KeepSetAside { task }
1020        | Runnable::DropSetAside { task }
1021        | Runnable::AllowAlways { task, .. }
1022        | Runnable::CodeNudge { task, .. }
1023        | Runnable::AcceptanceAt { task, .. }
1024        | Runnable::RuleScenario { task, .. }
1025        | Runnable::DeclinePromotion { task } => Some(task.clone()),
1026        Runnable::Explore { resume, .. } => resume.clone(),
1027        Runnable::ExploreChoose { session, .. } => Some(session.clone()),
1028        Runnable::OracleTests { req, .. } => Some(req.clone()),
1029        Runnable::ApproveAndRun { mode, .. } => Some(mode.as_str().to_owned()),
1030        Runnable::Comment { id, .. } => id.clone(),
1031        Runnable::RevisionUndo { turn } => turn.clone(),
1032        Runnable::WidenPolicy { key, .. } => Some(key.as_str().to_owned()),
1033        Runnable::DecideBatch { run, .. } => Some(run.clone()),
1034        Runnable::IssueComment { issue, .. } => Some(issue.to_string()),
1035        Runnable::BugConfirm { task, .. } | Runnable::BugKeep { task } => Some(task.clone()),
1036        Runnable::BugRun { slug, task } => task.clone().or_else(|| slug.clone()),
1037        Runnable::BugFix { slug, issue, .. } => {
1038            slug.clone().or_else(|| issue.map(|n| format!("#{n}")))
1039        }
1040        Runnable::Review { ids, verdict } => Some(match ids.first() {
1041            Some(id) => format!("{verdict}:{id}"),
1042            None => verdict.clone(),
1043        }),
1044        Runnable::PlanThrough { from, through } => Some(match from {
1045            PlanFrom::Create { .. } => format!("create:{}", through.as_str()),
1046            PlanFrom::Continue => format!("continue:{}", through.as_str()),
1047        }),
1048        Runnable::NewProject { target, .. } => Some(target.clone()),
1049        Runnable::UndoNewProject { commit } => Some(commit.clone()),
1050        Runnable::CloneRepository { repo, .. } => Some(repo.clone()),
1051        Runnable::Converge
1052        | Runnable::OpenSample { .. }
1053        | Runnable::SampleChecks
1054        | Runnable::Commit { .. }
1055        | Runnable::QuickChange { .. }
1056        | Runnable::FixSetup
1057        | Runnable::Feature
1058        | Runnable::PullRequest
1059        | Runnable::PresetAdd { .. }
1060        | Runnable::CommentsSend { .. } => None,
1061    };
1062    ActionId {
1063        kind: run.kind(),
1064        subject,
1065    }
1066}
1067
1068/// The part a planning skill plays in its format's planning, from the
1069/// format's adapter: what an interface finds "the create step" or "the
1070/// analysis step" by, without naming a format's skill.
1071#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
1072#[serde(rename_all = "snake_case")]
1073pub enum SkillRole {
1074    /// It creates a unit (Spec Kit's `specify`).
1075    Create,
1076    /// It leads toward the task list (`plan`, `tasks`).
1077    TowardTasks,
1078    /// It revises a written spec (`clarify`).
1079    Revise,
1080    /// It checks the planning files for consistency (`analyze`).
1081    Check,
1082    /// Anything else.
1083    Other,
1084}
1085
1086/// The interface a person acted through, as a write records it (`via`):
1087/// one vocabulary for every record. Records written before it named
1088/// `cli`, `tui` or `dashboard` (read as [`Via::Terminal`]) and
1089/// `editor <name>` (read as [`Via::Acp`], the name a separate client).
1090#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
1091#[serde(rename_all = "snake_case")]
1092pub enum Via {
1093    /// A terminal: the line CLI, its prompts, the dashboard.
1094    #[serde(alias = "cli", alias = "tui", alias = "dashboard")]
1095    Terminal,
1096    /// The web app, in a browser tab or the desktop window.
1097    Web,
1098    /// The desktop window, once it can tell itself from a tab.
1099    Window,
1100    /// An editor over the Agent Client Protocol.
1101    Acp,
1102    /// A phone.
1103    Phone,
1104    /// Continuous integration.
1105    Ci,
1106    /// A client over the Model Context Protocol.
1107    Mcp,
1108}
1109
1110impl Via {
1111    /// Its recorded value (`terminal`).
1112    #[must_use]
1113    pub const fn as_str(self) -> &'static str {
1114        match self {
1115            Self::Terminal => "terminal",
1116            Self::Web => "web",
1117            Self::Window => "window",
1118            Self::Acp => "acp",
1119            Self::Phone => "phone",
1120            Self::Ci => "ci",
1121            Self::Mcp => "mcp",
1122        }
1123    }
1124
1125    /// A recorded value, read back with the client it names (`editor Zed`
1126    /// → `acp`, `Zed`); `None` for a value no interface ever recorded.
1127    #[must_use]
1128    pub fn read(recorded: &str) -> Option<(Self, Option<String>)> {
1129        if let Some(client) = recorded.strip_prefix("editor ") {
1130            return Some((Self::Acp, Some(client.to_owned())));
1131        }
1132        let via = match recorded {
1133            "terminal" | "cli" | "tui" | "dashboard" => Self::Terminal,
1134            "web" => Self::Web,
1135            "window" => Self::Window,
1136            "acp" | "editor" => Self::Acp,
1137            "phone" => Self::Phone,
1138            "ci" => Self::Ci,
1139            "mcp" => Self::Mcp,
1140            _ => return None,
1141        };
1142        Some((via, None))
1143    }
1144}
1145
1146impl std::fmt::Display for Via {
1147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1148        f.write_str(self.as_str())
1149    }
1150}
1151
1152/// One thing a person can do now.
1153#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
1154pub struct Action {
1155    /// `next`, `plan`, `work`, `task`, `feature` or `review`.
1156    pub group: String,
1157    /// What it does, in a few words.
1158    pub label: String,
1159    /// Why, or what follows (shown beside it).
1160    pub why: String,
1161    /// The equivalent command; `"…"` marks the input.
1162    pub command: String,
1163    /// How an interface runs it; `None`: see `step`.
1164    pub run: Option<Runnable>,
1165    /// How an interface takes it when it does not run it (`run` is `None`):
1166    /// a view it opens, the person's own command, a line for their shell.
1167    pub step: Option<crate::step::How>,
1168    /// Why it cannot run now; `None`: it can.
1169    pub blocked: Option<String>,
1170    /// What to ask for before it runs (`Describe the feature`).
1171    pub input: Option<String>,
1172    /// It leaves the machine (a push, a pull request) or cannot be undone
1173    /// (a discard): what an interface says in a confirmation before it runs it.
1174    pub confirm: Option<String>,
1175    /// What it is, independent of its wording ([`identity`]).
1176    pub id: ActionId,
1177    /// A planning skill's part in its format's planning; `None` for
1178    /// everything else.
1179    pub role: Option<SkillRole>,
1180}
1181
1182impl Action {
1183    /// An action that stands for `command`, which the person runs.
1184    #[must_use]
1185    pub fn new(
1186        group: &str,
1187        label: impl Into<String>,
1188        why: impl Into<String>,
1189        command: impl Into<String>,
1190    ) -> Self {
1191        let command = command.into();
1192        Self {
1193            group: group.to_owned(),
1194            label: label.into(),
1195            why: why.into(),
1196            id: identity(None, &command),
1197            step: Some(crate::step::step_of(&command, crate::step::Context::default()).how),
1198            command,
1199            run: None,
1200            blocked: None,
1201            input: None,
1202            confirm: None,
1203            role: None,
1204        }
1205    }
1206
1207    /// Run by an interface as `run`; its identity follows.
1208    #[must_use]
1209    pub fn with_run(mut self, run: Runnable) -> Self {
1210        self.id = identity(Some(&run), &self.command);
1211        self.run = Some(run);
1212        self.step = None;
1213        self
1214    }
1215
1216    /// A planning skill playing `role`.
1217    #[must_use]
1218    pub const fn with_role(mut self, role: SkillRole) -> Self {
1219        self.role = Some(role);
1220        self
1221    }
1222
1223    /// It can be run from an interface, now.
1224    #[must_use]
1225    pub const fn runnable(&self) -> bool {
1226        self.run.is_some() && self.blocked.is_none()
1227    }
1228}
1229
1230/// The primary action: the first runnable one of the `next` group.
1231#[must_use]
1232pub fn primary(actions: &[Action]) -> Option<&Action> {
1233    actions.iter().find(|a| a.group == "next" && a.runnable())
1234}
1235
1236/// Where a step of the journey is.
1237#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
1238#[serde(rename_all = "snake_case")]
1239pub enum StepState {
1240    /// Done.
1241    Done,
1242    /// The one to take now.
1243    Now,
1244    /// Later.
1245    Todo,
1246    /// Passed without its file: a task list written without a spec or a
1247    /// plan. Not a step left to take.
1248    Skipped,
1249}
1250
1251/// One step of a feature's journey: `spec`, `plan`, `tasks`, `commit`,
1252/// `run`, `review`.
1253#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
1254pub struct JourneyStep {
1255    /// Its name.
1256    pub name: String,
1257    /// Where it is.
1258    pub state: StepState,
1259}
1260
1261/// Facts the journey is derived from.
1262#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1263pub struct JourneyFacts {
1264    /// `spec.md` exists.
1265    pub spec: bool,
1266    /// `plan.md` exists.
1267    pub plan: bool,
1268    /// The task list exists.
1269    pub tasks: bool,
1270    /// Planning files are not committed.
1271    pub uncommitted: bool,
1272    /// Tasks in the list.
1273    pub total: usize,
1274    /// Of them ticked or skipped.
1275    pub finished: usize,
1276}
1277
1278/// The journey from a spec to a reviewed branch, and where the feature is
1279/// on it: everything before the first open step is done (or skipped, when a
1280/// later planning file exists without it), that one is now.
1281#[must_use]
1282pub fn journey(f: JourneyFacts) -> Vec<JourneyStep> {
1283    let skipped = [!f.spec && (f.plan || f.tasks), !f.plan && f.tasks];
1284    let done = [
1285        ("spec", f.spec),
1286        ("plan", f.plan),
1287        // A task list without a task is not written yet.
1288        ("tasks", f.tasks && f.total > 0),
1289        ("commit", f.tasks && f.total > 0 && !f.uncommitted),
1290        ("run", f.total > 0 && f.finished == f.total),
1291        ("review", false),
1292    ];
1293    let passed = |i: usize| skipped.get(i).copied().unwrap_or(false);
1294    let now = done
1295        .iter()
1296        .enumerate()
1297        .position(|(i, (_, d))| !d && !passed(i))
1298        .unwrap_or(done.len());
1299    done.iter()
1300        .enumerate()
1301        .map(|(i, (name, d))| JourneyStep {
1302            name: (*name).to_owned(),
1303            state: if *d && i < now {
1304                StepState::Done
1305            } else if passed(i) && i < now {
1306                StepState::Skipped
1307            } else if i == now {
1308                StepState::Now
1309            } else {
1310                StepState::Todo
1311            },
1312        })
1313        .collect()
1314}
1315
1316#[cfg(test)]
1317mod tests {
1318    use super::*;
1319
1320    #[test]
1321    fn every_kind_is_listed_once_and_every_runnable_has_its_own() {
1322        // The schema lists every variant the compiler knows.
1323        let schema = serde_json::to_value(schemars::schema_for!(ActionKind))
1324            .unwrap_or_else(|e| panic!("{e}"));
1325        let mut named: Vec<String> = schema["oneOf"]
1326            .as_array()
1327            .into_iter()
1328            .flatten()
1329            .filter_map(|v| v["const"].as_str().map(str::to_owned))
1330            .collect();
1331        named.sort();
1332        let mut listed: Vec<String> = ActionKind::ALL
1333            .iter()
1334            .map(|k| k.as_str().to_owned())
1335            .collect();
1336        listed.sort();
1337        assert_eq!(named, listed, "ActionKind::ALL is not the enum");
1338        for k in ActionKind::ALL {
1339            assert_eq!(
1340                serde_json::to_value(k).unwrap_or_default(),
1341                k.as_str(),
1342                "{k:?}"
1343            );
1344            if let Some(run) = k.example() {
1345                assert_eq!(run.kind(), *k);
1346                assert_eq!(identity(Some(&run), "").kind, *k);
1347            }
1348        }
1349        assert_eq!(
1350            Runnable::examples().len(),
1351            ActionKind::ALL.len() - 1,
1352            "every kind but `command` has a runnable"
1353        );
1354    }
1355
1356    #[test]
1357    fn identity_is_what_runs_never_how_it_is_worded() {
1358        let a = Action::new(
1359            "task",
1360            "accept T004",
1361            "tick it",
1362            "speccoder task accept T004",
1363        )
1364        .with_run(Runnable::Accept {
1365            task: "T004".to_owned(),
1366        });
1367        let mut b = a.clone();
1368        b.label = "x tick it anyway".to_owned();
1369        b.why = "x".to_owned();
1370        assert_eq!(a.id, b.id);
1371        assert_eq!(
1372            a.id,
1373            ActionId {
1374                kind: ActionKind::Accept,
1375                subject: Some("T004".to_owned())
1376            }
1377        );
1378        let id = |c: &str| identity(None, c).subject;
1379        assert_eq!(
1380            id("speccoder attest verify").as_deref(),
1381            Some("attest verify")
1382        );
1383        assert_eq!(id("speccoder doctor").as_deref(), Some("doctor"));
1384        assert_eq!(id("speccoder pr --yes").as_deref(), Some("pr"));
1385        assert_eq!(
1386            id("speccoder spec specify \"…\"").as_deref(),
1387            Some("spec specify")
1388        );
1389        let review = |ids: &[&str], v: &str| {
1390            identity(
1391                Some(&Runnable::Review {
1392                    ids: ids.iter().map(|s| (*s).to_owned()).collect(),
1393                    verdict: v.to_owned(),
1394                }),
1395                "",
1396            )
1397            .subject
1398        };
1399        assert_eq!(review(&[], "approve").as_deref(), Some("approve"));
1400        assert_eq!(review(&["Q1"], "answer").as_deref(), Some("answer:Q1"));
1401    }
1402
1403    #[test]
1404    fn origins_read_back_from_every_value_ever_recorded() {
1405        for (old, via, client) in [
1406            ("cli", Via::Terminal, None),
1407            ("tui", Via::Terminal, None),
1408            ("dashboard", Via::Terminal, None),
1409            ("terminal", Via::Terminal, None),
1410            ("web", Via::Web, None),
1411            ("editor Zed", Via::Acp, Some("Zed")),
1412        ] {
1413            assert_eq!(
1414                Via::read(old),
1415                Some((via, client.map(str::to_owned))),
1416                "{old}"
1417            );
1418        }
1419        let parsed: Via = serde_json::from_str("\"dashboard\"").unwrap_or(Via::Web);
1420        assert_eq!(parsed, Via::Terminal);
1421        assert_eq!(Via::Acp.as_str(), "acp");
1422        assert_eq!(Via::read("nobody"), None);
1423    }
1424
1425    fn states(f: JourneyFacts) -> Vec<(String, StepState)> {
1426        journey(f).into_iter().map(|s| (s.name, s.state)).collect()
1427    }
1428
1429    #[test]
1430    fn the_journey_marks_what_is_done_and_what_is_now() {
1431        use StepState::{Done, Now, Todo};
1432        let names = ["spec", "plan", "tasks", "commit", "run", "review"].map(String::from);
1433        let at = |v: [StepState; 6]| names.iter().cloned().zip(v).collect::<Vec<_>>();
1434        assert_eq!(
1435            states(JourneyFacts::default()),
1436            at([Now, Todo, Todo, Todo, Todo, Todo])
1437        );
1438        let planned = JourneyFacts {
1439            spec: true,
1440            plan: true,
1441            ..JourneyFacts::default()
1442        };
1443        assert_eq!(states(planned), at([Done, Done, Now, Todo, Todo, Todo]));
1444        let written = JourneyFacts {
1445            tasks: true,
1446            uncommitted: true,
1447            total: 3,
1448            ..planned
1449        };
1450        assert_eq!(states(written), at([Done, Done, Done, Now, Todo, Todo]));
1451        let running = JourneyFacts {
1452            uncommitted: false,
1453            finished: 1,
1454            ..written
1455        };
1456        assert_eq!(states(running), at([Done, Done, Done, Done, Now, Todo]));
1457        let finished = JourneyFacts {
1458            finished: 3,
1459            ..running
1460        };
1461        assert_eq!(states(finished), at([Done, Done, Done, Done, Done, Now]));
1462        // A task list with no task: the tasks are still to write, never run.
1463        let empty = JourneyFacts {
1464            tasks: true,
1465            ..planned
1466        };
1467        assert_eq!(states(empty), at([Done, Done, Now, Todo, Todo, Todo]));
1468    }
1469
1470    #[test]
1471    fn a_task_list_without_a_spec_skips_to_the_run() {
1472        use StepState::{Now, Skipped, Todo};
1473        let names = ["spec", "plan", "tasks", "commit", "run", "review"].map(String::from);
1474        let at = |v: [StepState; 6]| names.iter().cloned().zip(v).collect::<Vec<_>>();
1475        let only_tasks = JourneyFacts {
1476            tasks: true,
1477            total: 4,
1478            finished: 1,
1479            ..JourneyFacts::default()
1480        };
1481        assert_eq!(
1482            states(only_tasks),
1483            at([
1484                Skipped,
1485                Skipped,
1486                StepState::Done,
1487                StepState::Done,
1488                Now,
1489                Todo
1490            ])
1491        );
1492        // A plan without a spec: the spec is skipped, the tasks are next.
1493        let planned = JourneyFacts {
1494            plan: true,
1495            ..JourneyFacts::default()
1496        };
1497        assert_eq!(
1498            states(planned),
1499            at([Skipped, StepState::Done, Now, Todo, Todo, Todo])
1500        );
1501    }
1502}