speccoder-runtime 0.1.0

Application services of speccoder: the only crate that executes anything.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! `speccoder pr`: hands a feature's work to review as a **draft**
//! pull request whose body is the evidence behind every tick.
//!
//! The one place speccoder talks to a git remote, and only when a person
//! runs it and confirms (or passes `--yes`); without that it is a dry run
//! that prints the body and the commands. It never merges, never marks the
//! pull request ready, and pushes only `speccoder/<feature>` and the
//! attestation notes (`refs/notes/speccoder`, never forced).

use std::fmt::Write as _;
use std::path::Path;

use speccoder_core::{CommandData, CommandResult, CommandStatus, PrReport, StatusReport};

use crate::git::Git;

/// How to hand off.
#[derive(Debug, Clone)]
pub struct PrOptions<'a> {
    /// The git remote (`origin`).
    pub remote: &'a str,
    /// The target branch; default: the branch the checkout is on.
    pub base: Option<&'a str>,
    /// Push and open (`false`: a dry run).
    pub open: bool,
    /// Hand off although the branch's full-tier checks failed (said in the body).
    pub force: bool,
    /// How GitHub is reached ([`crate::github::Ctx::from_env`]).
    pub github: &'a crate::github::Ctx,
}

/// Commit trailers on the branch: (task, `Mutation:` value, `Usage:` value).
fn trailers(repo: &Git, base: &str, branch: &str) -> Vec<(String, String, String)> {
    const FS: char = '\u{1f}';
    const RS: char = '\u{1e}';
    let format = format!(
        "--format=%(trailers:key=Spec-Task,valueonly){FS}%(trailers:key=Mutation,valueonly){FS}%(trailers:key=Usage,valueonly){RS}"
    );
    let log = repo
        .run(&["log", &format, &format!("{base}..{branch}")])
        .map(|b| String::from_utf8_lossy(&b).into_owned())
        .unwrap_or_default();
    log.split(RS)
        .filter_map(|r| {
            let f: Vec<&str> = r.trim_start_matches('\n').split(FS).collect();
            let [task, mutation, usage] = f[..] else {
                return None;
            };
            let task = task.trim().rsplit('/').next()?.to_owned();
            (!task.is_empty()).then(|| (task, mutation.trim().to_owned(), usage.trim().to_owned()))
        })
        .collect()
}

/// A note's state for the table: `ssh SHA256:…` (signer and key; who the
/// key belongs to is `attest verify`'s answer), `unsigned` or `missing`.
fn attestation(state: &str) -> String {
    match state.strip_prefix("signed ") {
        Some(signer) => format!("`{signer}`"),
        None => state.to_owned(),
    }
}

/// How a reviewer checks the attestations themselves, when there are any.
/// `sigstore` is the identity and issuer the project says sign: printed
/// for the reviewer to confirm, never trusted on the project's word.
#[must_use]
pub fn verify_section(
    status: &StatusReport,
    remote: &str,
    sigstore: Option<(&str, &str)>,
) -> Option<String> {
    let attested = status
        .tasks
        .iter()
        .filter(|t| t.attestation.as_deref().is_some_and(|a| a != "missing"))
        .count();
    let trust = sigstore.map_or_else(
        || "--allowed-signers <file>".to_owned(),
        |(identity, issuer)| {
            format!("--certificate-identity {identity} --certificate-oidc-issuer {issuer}")
        },
    );
    (attested > 0).then(|| {
        format!(
            "\n**Attestations.** {attested} tick(s) carry in-toto statements (DSSE, SLSA VSA) in the git note `{REF}` on their commit. To check them yourself:\n\n```sh\ngit fetch {remote} {REF}:{REF}\nspeccoder attest verify --feature {} {trust}\n```\n",
            status.feature,
            REF = crate::attest::notes::REF,
        )
    })
}

/// The pull request body: totals, a table of every task's evidence, what
/// is open, mutation results and tokens, and what `verified` does not mean.
#[must_use]
pub fn body(status: &StatusReport, trailers: &[(String, String, String)]) -> String {
    let t = &status.totals;
    let ticked = t.verified + t.regression_only + t.attested + t.ticked_without_evidence;
    let mut out = String::new();
    let _ = writeln!(
        out,
        "`{}`, implemented by speccoder. **{ticked} of {} tasks ticked**: {} verified (spec-derived acceptance tests went from red to green), {} regression only (the checks stayed green), {} attested by a person, {} ticked without evidence; {} skipped, {} open.\n",
        status.feature,
        status.tasks.len(),
        t.verified,
        t.regression_only,
        t.attested,
        t.ticked_without_evidence,
        t.skipped,
        t.ready + t.blocked
    );
    let _ = writeln!(
        out,
        "| Task | Evidence | Mutation | Attestation | Commit |\n|---|---|---|---|---|"
    );
    for task in &status.tasks {
        let mutation = trailers
            .iter()
            .find(|(id, m, _)| *id == task.id && !m.is_empty())
            .map(|(_, m, _)| m.replace(' ', ", "))
            .unwrap_or_default();
        let mut evidence = task.state.replace('_', " ");
        if let Some(n) = &task.note {
            let _ = write!(evidence, " — {n}");
        }
        if let Some(a) = &task.last_attempt {
            let _ = write!(
                evidence,
                " (last attempt: {}, `{}`)",
                a.outcome.replace('_', " "),
                a.reference
            );
        }
        let title: String = task.title.chars().take(70).collect();
        let _ = writeln!(
            out,
            "| {} {} | {} | {} | {} | {} |",
            task.id,
            title.replace('|', "\\|"),
            evidence.replace('|', "\\|"),
            mutation,
            task.attestation
                .as_deref()
                .map(attestation)
                .unwrap_or_default(),
            task.commit
                .as_deref()
                .map(|c| &c[..c.len().min(9)])
                .unwrap_or("")
        );
    }
    let (mut input, mut output) = (0u64, 0u64);
    for (_, _, usage) in trailers {
        if let Some(u) = crate::attempts::parse_usage(usage) {
            input += u["input_tokens"].as_u64().unwrap_or(0);
            output += u["output_tokens"].as_u64().unwrap_or(0);
        }
    }
    if input + output > 0 {
        let _ = writeln!(
            out,
            "\nTokens: {input} in, {output} out (`speccoder report --cost` has the breakdown)."
        );
    }
    if !status.convergence.is_empty() {
        let _ = writeln!(
            out,
            "\nConvergence appended {} round(s) of tasks after assessing the feature against its spec.",
            status.convergence.len()
        );
    }
    let _ = writeln!(
        out,
        "\n> `verified` means the spec-derived acceptance tests went from red to green and no check regressed. It does not mean the change is correct, complete or safe: review this like any contribution. Opened as a draft by `speccoder pr`; speccoder never merges."
    );
    out
}

/// `speccoder pr`.
#[must_use]
pub fn pr(path: &Path, feature: Option<&str>, options: &PrOptions<'_>) -> CommandResult {
    let refuse = |status: CommandStatus, m: &str| CommandResult::new("pr", status, m);
    let status = crate::status::report(path, feature);
    let Some(CommandData::Report(report)) = status.data() else {
        return refuse(status.status(), status.message());
    };
    let Some(branch) = report.branch.clone() else {
        return refuse(
            CommandStatus::GitPrecondition,
            "speccoder has not worked on this feature yet (no speccoder branch)",
        )
        .with_code("NOTHING-TO-HAND-OFF");
    };
    let repo_root = match Git::at(path).toplevel() {
        Ok(Some(r)) => r,
        _ => {
            return refuse(CommandStatus::GitPrecondition, "not a git repository")
                .with_code("NO-REPOSITORY");
        }
    };
    let repo = Git::at(&repo_root);
    let base = match options.base {
        Some(b) => b.to_owned(),
        None => match repo.line(&["rev-parse", "--abbrev-ref", "HEAD"]) {
            Ok(b) if b != "HEAD" => b,
            _ => {
                return refuse(
                    CommandStatus::GitPrecondition,
                    "the checkout is not on a branch; pass --base",
                );
            }
        },
    };
    if base == branch {
        return refuse(
            CommandStatus::GitPrecondition,
            "the base is the speccoder branch itself",
        );
    }
    let ahead = repo
        .line(&["rev-list", "--count", &format!("{base}..{branch}")])
        .ok()
        .and_then(|n| n.parse::<usize>().ok())
        .unwrap_or(0);
    if ahead == 0 {
        return refuse(
            CommandStatus::GitPrecondition,
            &format!("{branch} has nothing that {base} does not have"),
        )
        .with_code("NOTHING-TO-HAND-OFF");
    }
    if !repo
        .succeeds(&["remote", "get-url", options.remote])
        .unwrap_or(false)
    {
        return refuse(
            CommandStatus::GitPrecondition,
            &format!("no git remote `{}`", options.remote),
        )
        .with_code("NO-REMOTE");
    }
    let t = &report.totals;
    let title = format!(
        "{}: {} verified, {} regression only, {} open (speccoder)",
        report.feature,
        t.verified,
        t.regression_only,
        t.ready + t.blocked
    );
    // A branch whose full-tier checks failed is not handed off unless forced.
    let full =
        crate::pipeline::full::read(&repo_root, &report.feature, &branch).filter(|t| !t.passed);
    if let Some(t) = full.as_ref().filter(|_| !options.force) {
        return refuse(
            CommandStatus::VerificationFailed,
            &format!(
                "the full-tier checks failed on {branch}: {}; fix them, or pass --force",
                t.failed.join(", ")
            ),
        );
    }
    let mut body = body(report, &trailers(&repo, &base, &branch));
    if let Some(t) = &full {
        body.push_str(&format!(
            "\n> **Full-tier checks failed** on this branch: {}. Handed off with `--force`.\n",
            t.failed.join(", ")
        ));
    }
    let attest = crate::verify::find_config(path)
        .and_then(|d| std::fs::read_to_string(d.join(crate::verify::config::FILE)).ok())
        .and_then(|c| crate::substrate::run_config::parse(&c).ok())
        .map(|c| c.attest);
    let sigstore = attest
        .as_ref()
        .filter(|a| a.signer == crate::substrate::run_config::Signer::Sigstore)
        .and_then(|a| {
            a.sigstore_identity
                .as_deref()
                .zip(a.sigstore_issuer.as_deref())
        });
    // The issues the spec names: merged, the pull request closes them.
    if !report.issues.is_empty() {
        body.push('\n');
        for url in &report.issues {
            body.push_str(&format!("Closes {url}\n"));
        }
    }
    if let Some(section) = verify_section(report, options.remote, sigstore) {
        body.push_str(&section);
    }
    let refspec = format!("{branch}:refs/heads/{branch}");
    let notes = crate::attest::notes::REF;
    let push_notes = repo
        .succeeds(&["rev-parse", "--verify", "-q", notes])
        .unwrap_or(false);
    let mut commands = vec![format!("git push {} {refspec}", options.remote)];
    if push_notes {
        commands.push(format!("git push {} {notes}", options.remote));
    }
    // The repository the remote names on GitHub: where the draft opens.
    let github = crate::github::repo(&repo_root, Some(options.remote));
    commands.push(match &github {
        Ok(r) => format!(
            "open (or update) a draft pull request on {}: {branch} → {base} (GitHub API, as you)",
            r.slug()
        ),
        Err(e) => format!("no pull request can be opened: {e}"),
    });
    let mut out = PrReport {
        feature: report.feature.clone(),
        branch: branch.clone(),
        base: base.clone(),
        remote: options.remote.to_owned(),
        title: title.clone(),
        body: body.clone(),
        commands,
        opened: false,
        url: None,
    };
    if !options.open {
        return CommandResult::new(
            "pr",
            CommandStatus::Ok,
            "dry run: nothing was pushed (confirm, or pass --yes, to push and open the draft)",
        )
        .with_data(CommandData::Pr(Box::new(out)));
    }
    // Nothing leaves the machine unless the pull request can be opened:
    // a GitHub repository the remote names, and someone signed in there.
    let github = match github {
        Ok(r) => r,
        Err(e) => {
            return crate::github::refused("pr", &format!("{e}; nothing was pushed"))
                .with_data(CommandData::Pr(Box::new(out)));
        }
    };
    if options.github.token(&github.host).is_none() {
        return crate::github::refused(
            "pr",
            &format!(
                "not signed in to {}: `speccoder auth login` (or set GH_TOKEN); nothing was pushed",
                github.host
            ),
        )
        .with_data(CommandData::Pr(Box::new(out)));
    }
    if let Err(e) = repo.run(&["push", "--quiet", options.remote, &refspec]) {
        return CommandResult::new(
            "pr",
            CommandStatus::GitPrecondition,
            &format!("push failed: {}", e.0),
        )
        .with_data(CommandData::Pr(Box::new(out)));
    }
    // The notes are pushed as they are: a remote that has diverged is told
    // how to merge, never overwritten; the pull request opens regardless.
    let notes_warning = push_notes
        .then(|| repo.run(&["push", "--quiet", options.remote, &format!("{notes}:{notes}")]).err())
        .flatten()
        .map(|e| {
            format!(
                "; the attestation notes were not pushed ({}): `git fetch {r} {notes}:refs/notes/speccoder-remote && git notes --ref=speccoder merge refs/notes/speccoder-remote`, then `git push {r} {notes}`",
                e.0.lines().last().unwrap_or_default().trim(),
                r = options.remote,
            )
        })
        .unwrap_or_default();
    let failed = |e: &str, out: PrReport| {
        let r = crate::github::refused("pr", e);
        let status = r.status();
        r.reworded(status, &format!("pushed {branch}, but {e}"))
            .with_data(CommandData::Pr(Box::new(out)))
    };
    // A pull request for this branch already: the push updated its code;
    // its title and description are brought up to date with the evidence.
    // A second one is never opened.
    // The pull request in the repository this remote names (not `origin`'s).
    match crate::github::pr_in(options.github, &github, &branch) {
        Ok(Some(existing)) if existing.state == "OPEN" => {
            out.opened = true;
            out.url = Some(existing.url.clone());
            if let Err(e) =
                crate::github::update(options.github, &github, existing.number, &title, &body)
            {
                return failed(&e, out);
            }
            return CommandResult::new(
                "pr",
                CommandStatus::Ok,
                &format!(
                    "pushed {branch}: updated pull request #{} and its evidence ({}){notes_warning}",
                    existing.number, existing.url
                ),
            )
            .with_data(CommandData::Pr(Box::new(out)));
        }
        Ok(_) => {}
        Err(e) => return failed(&e, out),
    }
    match crate::github::open_draft(options.github, &github, &base, &branch, &title, &body) {
        Ok((number, url)) => {
            out.opened = true;
            out.url = Some(url.clone());
            CommandResult::new(
                "pr",
                CommandStatus::Ok,
                &format!("draft pull request #{number} opened: {url}{notes_warning}"),
            )
            .with_data(CommandData::Pr(Box::new(out)))
        }
        Err(e) => failed(&e, out),
    }
}