Skip to main content

speccoder_runtime/
service.rs

1//! The web host's one way into the runtime: every entry point it uses,
2//! re-exported or delegated without changing a result. A write the host
3//! serves goes through [`actions::perform`], like every interface's; a
4//! later feature adds read views here as delegates, never a second write
5//! path. The layering test holds the host to this module.
6
7use std::path::Path;
8
9pub use crate::RunOptions;
10
11/// The action list and the one dispatcher.
12pub mod actions {
13    pub use crate::actions::{Dispatch, Interface, Offer, available, list, offered, perform};
14}
15
16/// The person's own commands, run for them (a fix speccoder printed), and
17/// a terminal at the project.
18pub mod person {
19    pub use crate::person::{Stream, TIMEOUT, open_terminal, run, sandboxed, shown, speccoder};
20}
21
22/// What went wrong, as a block to copy; the setup as a bug report.
23pub mod copy {
24    pub use crate::copy::block;
25    pub use crate::doctor::bug_report;
26}
27
28/// Calls waiting for a person, and who answers them.
29pub mod approvals {
30    pub use crate::approvals::{Answer, Approver, Presentation, Who, list};
31}
32
33/// A run's progress, as it happens and as another process left it.
34pub mod progress {
35    pub use crate::progress::{Event, Progress, read_live};
36}
37
38/// Read views.
39pub mod status {
40    pub use crate::status::report;
41}
42
43/// Shape: a person's words made into a requirement, judged by code; the
44/// writing check. Writes nothing.
45pub mod shape {
46    pub use crate::shape::{FIELDS, findings, judge, shape};
47}
48
49/// Ask: a read-only conversation; a turn writes only the Ask plane's
50/// journal and the conversation's thread.
51pub mod ask {
52    pub use crate::ask::chips::{ChipRef, resolve as chip};
53    pub use crate::ask::proposal::revalidate as proposal;
54    pub use crate::ask::{Request, changed_since, conversations, new_id, stop, thread, turn};
55}
56
57/// Explore: an idea's sessions, read; writes are actions.
58pub mod explore {
59    pub use crate::explore::{list, session};
60}
61
62/// The next steps a result names.
63pub mod next {
64    pub use crate::next::attach;
65}
66
67/// The person's review of the spec.
68pub mod review {
69    /// The comment tray and the last revision turn.
70    pub use crate::comments::list as comments;
71    pub use crate::review::{readiness, report};
72}
73
74/// Planning a new feature: the rung a description suggests, the
75/// requirements it is close to (read-only, no model).
76pub mod planning {
77    pub use crate::planning_chain::{similar_command, similar_to, suggest};
78}
79
80/// A new project: its plan (read-only), the idea offered once.
81pub mod new_project {
82    pub use crate::new_project::{Creation, creation, first_feature, plan, undo_offer};
83    pub use speccoder_core::new_project::{NewChoices, Stack, slug};
84}
85
86/// What a host outside a project shows.
87pub mod welcome {
88    pub use crate::welcome::{
89        Recent, RecentView, default_parent, folders, forget, is_project, remember, tilde, views,
90    };
91}
92
93/// The bundled sample.
94pub mod sample {
95    pub use crate::sample::{available, copy, home, missing_tool};
96}
97
98/// Needs You.
99pub mod inbox {
100    pub use crate::inbox::inbox;
101}
102
103/// A bug as speccoder keeps it (read-only; a bug's actions are kinds).
104pub mod bug {
105    pub use crate::bug::show;
106}
107
108/// A task's evidence.
109pub mod evidence {
110    pub use crate::evidence::{account_of, banner, rows, statements};
111}
112
113/// A task's evidence tour (`evidence_tour`), read as recorded.
114pub mod tour {
115    use std::path::Path;
116
117    use speccoder_core::{CommandData, CommandResult, CommandStatus};
118
119    /// The tour of `task` of `feature` (default: the selected feature) at
120    /// `HEAD`: [`crate::tour::command`] without trust, so it shows what the
121    /// statements and the commit say.
122    #[must_use]
123    pub fn of_task(root: &Path, feature: Option<&str>, task: &str) -> CommandResult {
124        let selected = || match crate::inspect(root, None).data() {
125            Some(CommandData::Inspect(snap)) => {
126                snap.feature.as_ref().map(|f| f.feature.name.clone())
127            }
128            _ => None,
129        };
130        let Some(feature) = feature.map(str::to_owned).or_else(selected) else {
131            return CommandResult::new(
132                "tour",
133                CommandStatus::SelectionNeeded,
134                "no feature selected",
135            );
136        };
137        crate::tour::command(
138            root,
139            &feature,
140            task,
141            &crate::attest::branch::Options::default(),
142            "tour",
143        )
144    }
145}
146
147/// The feature's documents.
148pub mod documents {
149    pub use crate::documents::{of_feature, render};
150}
151
152/// The machine and the project, checked.
153pub mod doctor {
154    pub use crate::doctor::{agents, run};
155}
156
157/// `speccoder.toml`.
158pub mod settings {
159    /// What a prefix entry would newly allow (`config coverage`).
160    pub use crate::approvals::coverage::show as coverage;
161    pub use crate::settings::{apply, commit, show};
162}
163
164/// Tokens and money.
165pub mod controls {
166    pub use crate::controls::{SkillCost, cost, skill_cost};
167}
168
169/// The code view: the branch's change, its files.
170pub mod code {
171    pub use crate::code::{changes, file, tree, worktree_file, worktree_view};
172}
173
174/// Setting up a project.
175pub mod init {
176    pub use crate::init::{commit_written, finish, prepare, preview, root_of};
177}
178
179/// The features.
180pub mod current {
181    pub use crate::current::list;
182}
183
184/// The pull request, previewed.
185pub mod handoff {
186    pub use crate::handoff::{PrOptions, pr};
187}
188
189/// Where speccoder keeps its state.
190pub mod worktree {
191    pub use crate::worktree::state_dir;
192}
193
194/// GitHub: sign-in, issues, the branch's pull request.
195pub mod github {
196    pub use crate::github::{
197        Ctx, RepoEntry, description, issue, issues, login_with_token, pr_for, reach, refused, repo,
198        repositories, started, status, valid_slug,
199    };
200
201    /// Signing in on a device.
202    pub mod auth {
203        pub use crate::github::auth::{Pending, client_id, start, wait};
204    }
205
206    /// GitHub's addresses.
207    pub mod http {
208        pub use crate::github::http::oauth;
209    }
210}
211
212/// How the project's format words things, for the page's header.
213#[derive(Debug, Clone, Copy)]
214pub struct FormatWords {
215    /// The format (`Spec Kit`).
216    pub name: &'static str,
217    /// What it calls a unit of work (`feature`, `change`).
218    pub unit: &'static str,
219}
220
221/// The words of the format of the project at `root`.
222#[must_use]
223pub fn format_words(root: &Path) -> FormatWords {
224    let format = crate::format::at(root);
225    FormatWords {
226        name: format.wording().name,
227        unit: format.messages().unit,
228    }
229}
230
231/// The format's planning chain, by installed skill name, for the New
232/// Feature sheet: what creates a unit, what leads to the task list, what
233/// checks it and what revises a written spec.
234#[derive(Debug, Clone, serde::Serialize)]
235pub struct PlanningWords {
236    /// The creating skill (`speckit-specify`).
237    pub creates: Option<String>,
238    /// The skills toward the task list after it (`speckit-plan`, `speckit-tasks`).
239    pub toward: Vec<String>,
240    /// The checking skill (`speckit-analyze`).
241    pub checks: Option<String>,
242    /// The revising skill (`speckit-clarify`).
243    pub revises: Option<String>,
244}
245
246/// [`PlanningWords`] of the project at `root`.
247#[must_use]
248pub fn planning_words(root: &Path) -> PlanningWords {
249    let p = crate::format::at(root).planning();
250    let full = |s: &str| format!("{}{s}", p.prefix);
251    let creates = p.creates.first().map(|c| full(c));
252    PlanningWords {
253        toward: (p.toward_tasks)(false)
254            .iter()
255            .map(|s| full(s))
256            .filter(|s| Some(s) != creates.as_ref())
257            .collect(),
258        creates,
259        checks: p.checks.map(full),
260        revises: p.revises.map(full),
261    }
262}
263
264/// The installed name of the format's skill that creates a unit, if it has one.
265#[must_use]
266pub fn create_skill(root: &Path) -> Option<String> {
267    let planning = crate::format::at(root).planning();
268    planning
269        .creates
270        .first()
271        .map(|c| format!("{}{c}", planning.prefix))
272}
273
274/// One commit's patch, if `commit` names a commit (a blob or a tree id
275/// from elsewhere in the repository is never shown); empty otherwise.
276#[must_use]
277pub fn commit_patch(root: &Path, commit: &str) -> String {
278    commit_patch_of(root, commit)
279}
280
281/// Whether `id` is reached from `HEAD`, a branch or a saved attempt.
282fn reachable(git: &crate::git::Git, id: &str) -> bool {
283    if git
284        .succeeds(&["merge-base", "--is-ancestor", id, "HEAD"])
285        .unwrap_or(false)
286    {
287        return true;
288    }
289    git.line(&[
290        "for-each-ref",
291        "--count=1",
292        "--format=%(refname)",
293        "--contains",
294        id,
295        "refs/heads",
296        "refs/speccoder/attempts",
297    ])
298    .is_ok_and(|l| !l.trim().is_empty())
299}
300
301fn commit_patch_of(root: &Path, commit: &str) -> String {
302    let git = crate::git::Git::at(root);
303    // `^{commit}` peels or fails.
304    let Ok(id) = git.line(&[
305        "rev-parse",
306        "--verify",
307        "-q",
308        &format!("{commit}^{{commit}}"),
309    ]) else {
310        return String::new();
311    };
312    // Only what a branch, `HEAD` or a saved attempt reaches: a commit the
313    // page could only name by its id (a sealed or unreachable object) shows
314    // nothing.
315    if !reachable(&git, &id) {
316        return String::new();
317    }
318    git.run(&["show", "--no-color", "--patch", "--format=%h %s%n%n%b", &id])
319        .map(|b| String::from_utf8_lossy(&b).into_owned())
320        .unwrap_or_default()
321}