speccoder-runtime 0.6.1

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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Read-side and single-shot services: `inspect`, `worktree`, `propose`,
//! `replay` and `eval`.

use std::path::Path;

use speccoder_core::snapshot::{ProjectSnapshot, Severity};
use speccoder_core::{CommandData, CommandResult, CommandStatus};

use crate::pipeline::*;
use crate::{context, git, substrate};

/// `speccoder inspect`: report what speccoder sees in the project
/// containing `path`. Read-only.
#[must_use]
pub fn inspect(path: &Path, feature: Option<&str>) -> CommandResult {
    match crate::format::open(path, feature) {
        Ok(opened) => {
            let snapshot = opened.snapshot;
            let status = status_of(&snapshot);
            let message = summary(&snapshot, opened.adapter.messages());
            CommandResult::new("inspect", status, &message)
                .with_data(CommandData::Inspect(Box::new(snapshot)))
        }
        Err(r) => CommandResult::new("inspect", r.status, &r.message),
    }
}

/// Exit precedence: selection failure > error diagnostics > ok.
pub(crate) fn status_of(s: &ProjectSnapshot) -> CommandStatus {
    let selection_failed = s.feature.is_none()
        && s.diagnostics
            .iter()
            .any(|d| d.severity == Severity::Error && d.code.starts_with("select."));
    if selection_failed {
        CommandStatus::SelectionNeeded
    } else if s.has_errors() {
        CommandStatus::DiagnosticsError
    } else {
        CommandStatus::Ok
    }
}

pub(crate) fn summary(s: &ProjectSnapshot, m: &crate::format::Messages) -> String {
    let features = match s.features.len() {
        1 => "1 feature".to_owned(),
        n => format!("{n} features"),
    };
    let selected = match &s.feature {
        Some(f) => match &f.tasks {
            Some(t) => format!(
                "{} selected: {} tasks, {} done, {} open",
                f.feature.name, t.totals.total, t.totals.done, t.totals.open
            ),
            None => format!("{} selected: no {}", f.feature.name, m.tasks_file),
        },
        None => "none selected".to_owned(),
    };
    let errors = s
        .diagnostics
        .iter()
        .filter(|d| d.severity == Severity::Error)
        .count();
    let warnings = s
        .diagnostics
        .iter()
        .filter(|d| d.severity == Severity::Warning)
        .count();
    format!("{features}, {selected}; {errors} errors, {warnings} warnings")
}

/// `speccoder worktree`: create or reuse the git worktree speccoder works in
/// for the selected feature of the project containing `path`.
#[must_use]
pub fn worktree(path: &Path, feature: Option<&str>) -> CommandResult {
    match crate::worktree::state_dir() {
        Some(state) => worktree_with(path, feature, &state),
        None => CommandResult::new(
            "worktree",
            CommandStatus::GitPrecondition,
            "no state directory (set SPECCODER_STATE_DIR or HOME)",
        ),
    }
}

/// [`worktree()`] with an explicit state directory.
pub fn worktree_with(path: &Path, feature: Option<&str>, state: &Path) -> CommandResult {
    let inspected = inspect(path, feature);
    let snapshot = match inspected.data() {
        Some(CommandData::Inspect(s)) => s.clone(),
        _ => return CommandResult::carried("worktree", &inspected),
    };
    let Some(f) = &snapshot.feature else {
        return CommandResult::new(
            "worktree",
            CommandStatus::SelectionNeeded,
            inspected.message(),
        );
    };
    worktree_of(&snapshot, &f.feature.name, &f.feature.dir, state)
}

/// The worktree of the unit `name` whose files are under `unit_dir`
/// (project-relative): a feature, or a home the format's tasks do not list
/// (a bug in the format's own bug structure).
pub fn worktree_of(
    snapshot: &speccoder_core::snapshot::ProjectSnapshot,
    name: &str,
    unit_dir: &str,
    state: &Path,
) -> CommandResult {
    use speccoder_core::{RefusedPath, WorktreeReport};
    let format = crate::format::of(snapshot);
    let name = name.to_owned();
    let mut report = WorktreeReport {
        feature: name.clone(),
        path: None,
        project_dir: None,
        branch: None,
        base: None,
        created: false,
        refused_paths: Vec::new(),
    };
    let refuse = |report: WorktreeReport, code: &str, message: &str, hint: &str| {
        let mut fix = vec![format!("→ {hint}")];
        if let Some(e) = speccoder_core::codes::lookup(code) {
            fix.extend(speccoder_core::codes::fixes(e, "run", None, Some(&name)));
        }
        CommandResult::new("worktree", CommandStatus::GitPrecondition, message)
            .with_code(code)
            .with_fix(fix)
            .with_data(CommandData::Worktree(report))
    };

    let project = Path::new(&snapshot.root);
    let repo_root = match git::Git::at(project).toplevel() {
        Ok(Some(root)) => std::fs::canonicalize(&root).unwrap_or(root),
        Ok(None) => {
            return refuse(
                report,
                "NO-REPOSITORY",
                format.messages().not_in_git,
                "run `git init` and commit the project",
            );
        }
        Err(e) => return refuse(report, "GIT", &e.0, "install git"),
    };
    // The project root may be a subdirectory of the repository (monorepo).
    let rel = project.strip_prefix(&repo_root).unwrap_or(Path::new(""));
    let join = |p: &str| {
        let joined = rel.join(p);
        let s = joined.to_string_lossy().replace('\\', "/");
        if s.is_empty() { ".".to_owned() } else { s }
    };
    let precondition = format.commit_precondition(project, &join, unit_dir);

    match crate::worktree::ensure_worktree(&repo_root, state, &name, precondition) {
        Ok(wt) => {
            report.project_dir = Some(wt.path.join(rel).display().to_string());
            report.path = Some(wt.path.display().to_string());
            report.branch = Some(wt.branch);
            report.base = Some(wt.base);
            report.created = wt.created;
            let message = if report.created {
                "worktree created"
            } else {
                "worktree reused"
            };
            CommandResult::new("worktree", CommandStatus::Ok, message)
                .with_data(CommandData::Worktree(report))
        }
        Err(r) => {
            report.refused_paths = r
                .paths
                .into_iter()
                .map(|(path, reason)| RefusedPath { path, reason })
                .collect();
            refuse(report, r.code, &r.message, &r.hint)
        }
    }
}

/// `speccoder propose`: the provider comes from `[model]`, its key from
/// `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` (never from files).
#[must_use]
pub fn propose(path: &Path, feature: Option<&str>, task: &str) -> CommandResult {
    let Some(state) = crate::worktree::state_dir() else {
        return CommandResult::new(
            "propose",
            CommandStatus::ConfigError,
            "no state directory (set SPECCODER_STATE_DIR or HOME)",
        )
        .with_code("NO-STATE-DIR");
    };
    // Validate everything that needs no key first: a wrong task or a missing
    // [model] is reported before a missing credential.
    match setup(path, feature, &state, "propose") {
        Err(r) => return *r,
        Ok(s) => {
            if let Err(e) = s.format.bundle(&s.snapshot, task) {
                let msg = match e {
                    context::BundleError::NotFound(id) => {
                        format!("no task {id} in the selected feature")
                    }
                    context::BundleError::NoTasks => {
                        format!(
                            "the selected feature has no {}",
                            s.format.messages().tasks_file
                        )
                    }
                    context::BundleError::NoFeature => {
                        "no feature selected; pass --feature".to_owned()
                    }
                };
                return CommandResult::new("propose", CommandStatus::NotFound, &msg);
            }
        }
    }
    let model = match setup(path, feature, &state, "propose") {
        Ok(s) => s.model,
        Err(r) => return *r,
    };
    let (driver, key) = match substrate::model_config::open_driver(&model) {
        Ok((d, k)) => (Ok::<_, String>(d), k.unwrap_or_default()),
        Err(e) => return substrate::model_config::refused("propose", &e),
    };
    let provider = match driver {
        Ok(p) => p,
        Err(e) => {
            return CommandResult::new(
                "propose",
                CommandStatus::ConfigError,
                &redact(&e, Some(&key)),
            );
        }
    };
    propose_with(path, feature, task, &state, provider, Some(&key))
}

/// [`propose`] with an explicit state directory and model driver; `secret`
/// is redacted from anything reported.
pub fn propose_with(
    path: &Path,
    feature: Option<&str>,
    task: &str,
    state: &Path,
    provider: std::sync::Arc<dyn agentplane::model::ModelProvider>,
    secret: Option<&str>,
) -> CommandResult {
    use speccoder_core::ProposeReport;

    let s = match setup(path, feature, state, "propose") {
        Ok(s) => s,
        Err(r) => return *r,
    };
    let bundle = match s.format.bundle(&s.snapshot, task) {
        Ok(b) => b,
        Err(context::BundleError::NotFound(id)) => {
            return CommandResult::new(
                "propose",
                CommandStatus::NotFound,
                &format!("no task {id} in the selected feature"),
            );
        }
        Err(context::BundleError::NoTasks) => {
            return CommandResult::new(
                "propose",
                CommandStatus::NotFound,
                &format!(
                    "the selected feature has no {}",
                    s.format.messages().tasks_file
                ),
            );
        }
        Err(context::BundleError::NoFeature) => {
            return CommandResult::new(
                "propose",
                CommandStatus::SelectionNeeded,
                "no feature selected; pass --feature",
            );
        }
    };
    let feature_name = bundle.feature.clone();
    let input = match serde_json::to_value(&bundle) {
        Ok(v) => v,
        Err(e) => return CommandResult::new("propose", CommandStatus::Error, &e.to_string()),
    };
    let fail =
        |m: String| CommandResult::new("propose", CommandStatus::RunFailed, &redact(&m, secret));

    let rt = match tokio_runtime() {
        Ok(rt) => rt,
        Err(e) => return fail(e),
    };
    let outcome = rt.block_on(async {
        let plane = substrate::Plane::open_with(
            &s.plane_dir,
            &s.model,
            provider,
            None,
            substrate::Hooks {
                format: Some(s.format),
                ..substrate::Hooks::default()
            },
        )?;
        // The person's committed spec, plan and task: trusted.
        plane
            .propose(
                &feature_name,
                task,
                agentplane::core::Tainted::trusted(input),
            )
            .await
    });
    let outcome = match outcome {
        Ok(o) => o,
        Err(e) => return fail(e.0),
    };
    let output = outcome.output.as_ref().map(|o| o.peek().clone());
    let report = ProposeReport {
        run_id: outcome.run_id.to_string(),
        feature: feature_name,
        task: task.to_owned(),
        run_status: outcome.status.as_str().to_owned(),
        proposal: output
            .as_ref()
            .and_then(|o| o.get("proposal").cloned())
            .filter(|p| !p.is_null()),
        usage: output.as_ref().and_then(|o| o.get("usage").cloned()),
    };
    let (status, message) = match (&outcome.status, &report.proposal) {
        (agentplane::prelude::RunStatus::Succeeded, Some(_)) => (
            CommandStatus::Ok,
            format!("proposal recorded in run {}", report.run_id),
        ),
        (agentplane::prelude::RunStatus::Succeeded, None) => (
            CommandStatus::RunFailed,
            format!(
                "run {} succeeded but the model's answer is not a proposal",
                report.run_id
            ),
        ),
        (other, _) => (
            CommandStatus::RunFailed,
            redact(
                &format!("run {} ended {}: {other:?}", report.run_id, other.as_str()),
                secret,
            ),
        ),
    };
    CommandResult::new("propose", status, &message)
        .with_data(CommandData::Propose(Box::new(report)))
}

/// `speccoder replay`: strict replay of a recorded run; calls no model.
#[must_use]
pub fn replay(path: &Path, run: &str) -> CommandResult {
    let Some(state) = crate::worktree::state_dir() else {
        return CommandResult::new(
            "replay",
            CommandStatus::ConfigError,
            "no state directory (set SPECCODER_STATE_DIR or HOME)",
        )
        .with_code("NO-STATE-DIR");
    };
    replay_with(path, run, &state)
}

/// [`replay`] with an explicit state directory.
pub fn replay_with(path: &Path, run: &str, state: &Path) -> CommandResult {
    use speccoder_core::ReplayReport;

    let s = match setup(path, None, state, "replay") {
        Ok(s) => s,
        Err(r) => return *r,
    };
    let rt = match tokio_runtime() {
        Ok(rt) => rt,
        Err(e) => return CommandResult::new("replay", CommandStatus::RunFailed, &e),
    };
    let report = |result: &str, detail: String| ReplayReport {
        run_id: run.to_owned(),
        result: result.to_owned(),
        detail,
    };
    let result = rt.block_on(substrate::replay_strict(
        &s.plane_dir,
        &s.model,
        run,
        s.format,
    ));
    match result {
        Ok(Some(v)) => {
            let (result, status, message) = replay_verdict(&v.finding);
            CommandResult::new("replay", status, &message)
                .with_data(CommandData::Replay(report(result, message.clone())))
        }
        Ok(None) => CommandResult::new(
            "replay",
            CommandStatus::NotFound,
            &format!("no run {run} in this project's journal"),
        )
        .with_data(CommandData::Replay(report("not_found", String::new()))),
        // agentplane names every divergence in the verdict's finding; an
        // error is a missing run, a journal that does not verify, or the store.
        Err(e) => CommandResult::new("replay", CommandStatus::RunFailed, &e.0)
            .with_data(CommandData::Replay(report("error", e.0.clone()))),
    }
}

/// `speccoder eval`: the suite's `[model]` decides the provider; its key
/// comes from the environment.
#[must_use]
pub fn eval(
    dir: &Path,
    only: Option<&str>,
    keep: Option<&Path>,
    repeat: usize,
    executor: Option<&str>,
) -> CommandResult {
    let suite = match crate::eval::suite_config(dir) {
        Ok(s) => s,
        Err(e) => return substrate::model_config::refused("eval", &e),
    };
    let model = match substrate::model_config::parse(&suite) {
        Ok(Some(m)) => m,
        Ok(None) => {
            return CommandResult::new(
                "eval",
                CommandStatus::ConfigError,
                "eval.toml has no [model]",
            );
        }
        Err(e) => {
            return CommandResult::new(
                "eval",
                CommandStatus::ConfigError,
                &format!("eval.toml: {e}"),
            );
        }
    };
    let (driver, key) = match substrate::model_config::open_driver(&model) {
        Ok((d, k)) => (Ok::<_, String>(d), k.unwrap_or_default()),
        Err(e) => return CommandResult::new("eval", CommandStatus::ConfigError, &e),
    };
    match driver {
        Ok(p) => crate::eval::run_suite_as(dir, only, &p, Some(&key), keep, repeat, executor),
        Err(e) => CommandResult::new("eval", CommandStatus::ConfigError, &redact(&e, Some(&key))),
    }
}

/// What a replay's finding means for the person: a faithful
/// replay of any ending is reproduced; a different effect or ending is a
/// divergence; a run this build cannot re-derive is neither.
pub(crate) fn replay_verdict(
    finding: &agentplane::runtime::Finding,
) -> (&'static str, CommandStatus, String) {
    use agentplane::runtime::Finding;
    match finding {
        Finding::Verified { outcome } => (
            "reproduced",
            CommandStatus::Ok,
            format!(
                "reproduced: every recorded effect again, and the recorded ending ({outcome}); no model was called"
            ),
        ),
        Finding::Diverged(d) => (
            "diverged",
            CommandStatus::ReplayDiverged,
            format!("diverged: {d:?}"),
        ),
        Finding::OutcomeDiffers { recorded, replayed } => (
            "diverged",
            CommandStatus::ReplayDiverged,
            format!(
                "diverged: every effect matched, but the run ended {replayed} instead of {recorded}"
            ),
        ),
        Finding::CannotReplay(why) => (
            "not_replayable",
            CommandStatus::NotReplayable,
            format!("this build cannot re-derive the run: {why:?}"),
        ),
        other => (
            "not_replayable",
            CommandStatus::NotReplayable,
            format!("{other:?}"),
        ),
    }
}

#[cfg(test)]
mod replay_tests {
    use super::*;
    use agentplane::runtime::{CannotReplay, Finding};

    #[test]
    fn findings_become_reproduced_diverged_or_not_replayable() {
        let (r, s, _) = replay_verdict(&Finding::Verified {
            outcome: "failed".to_owned(),
        });
        assert_eq!((r, s), ("reproduced", CommandStatus::Ok));
        let (r, s, m) = replay_verdict(&Finding::OutcomeDiffers {
            recorded: "succeeded".to_owned(),
            replayed: "failed".to_owned(),
        });
        assert_eq!((r, s), ("diverged", CommandStatus::ReplayDiverged));
        assert!(m.contains("instead of succeeded"));
        let (r, s, _) = replay_verdict(&Finding::CannotReplay(CannotReplay::NotConcluded));
        assert_eq!((r, s), ("not_replayable", CommandStatus::NotReplayable));
        assert_eq!(s.exit_code().code(), 25);
    }
}