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