speccoder-runtime 0.5.2

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
//! The inbox: every decision waiting for a person, across features,
//! the most urgent first, each with the actions that decide it.

// Test code: panicking on unexpected input is the failure report.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use std::fs;
use std::path::Path;
use std::process::Command;

use speccoder_core::actions::Runnable;
use speccoder_core::{CommandData, InboxReport};

fn git(dir: &Path, args: &[&str]) {
    let out = Command::new("git")
        .args(["-c", "maintenance.auto=false", "-c", "gc.auto=0"])
        .args([
            "-c",
            "user.name=t",
            "-c",
            "user.email=t@t",
            "-c",
            "commit.gpgsign=false",
        ])
        .args(args)
        .current_dir(dir)
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "git {args:?}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

fn write(r: &Path, path: &str, text: &str) {
    let p = r.join(path);
    fs::create_dir_all(p.parent().unwrap()).unwrap();
    fs::write(p, text).unwrap();
}

const SPEC: &str = "# Spec\n\n## Requirements\n\n- **FR-001**: Users MUST log in.\n";

/// A Spec Kit project with two features, each one task citing FR-001 and
/// ticked by a verdict commit on its `speccoder/` branch.
fn repo() -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    let r = dir.path();
    write(r, ".specify/memory/constitution.md", "# Constitution\n");
    write(r, ".specify/init-options.json", "{}\n");
    for f in ["001-login", "002-logout"] {
        write(r, &format!("specs/{f}/spec.md"), SPEC);
        write(r, &format!("specs/{f}/plan.md"), "# Plan\n");
        write(
            r,
            &format!("specs/{f}/tasks.md"),
            "# Tasks\n\n## Phase 1: Core\n\n- [x] T001 Implement login per FR-001\n",
        );
    }
    git(r, &["init", "-q", "-b", "main"]);
    git(r, &["add", "-A"]);
    git(r, &["commit", "-q", "-m", "init"]);
    // The person approved both specs and committed the review.
    for f in ["001-login", "002-logout"] {
        let res = speccoder_runtime::review::decide(
            r,
            Some(f),
            &[],
            "approve",
            None,
            speccoder_core::actions::Via::Terminal,
        );
        assert_eq!(
            res.status(),
            speccoder_core::CommandStatus::Ok,
            "{}",
            res.message()
        );
    }
    git(r, &["add", "-A"]);
    git(r, &["commit", "-q", "-m", "review"]);
    for f in ["001-login", "002-logout"] {
        git(r, &["checkout", "-q", "-b", &format!("speccoder/{f}")]);
        git(
            r,
            &[
                "commit",
                "-q",
                "--allow-empty",
                "-m",
                &format!(
                    "speccoder: T001 x\n\nx\n\nSpec-Task: {f}/T001\nVerdict: verified\nRun: r1\n"
                ),
            ],
        );
        git(r, &["checkout", "-q", "main"]);
    }
    dir
}

fn inbox(r: &Path) -> (InboxReport, String) {
    let res = speccoder_runtime::inbox::inbox(r, None);
    let Some(CommandData::Inbox(i)) = res.data() else {
        panic!("{}", res.message())
    };
    ((**i).clone(), res.message().to_owned())
}

#[test]
fn finished_features_wait_to_be_handed_off() {
    let r = repo();
    let (i, message) = inbox(r.path());
    assert_eq!(i.features, 2);
    let kinds: Vec<(&str, &str)> = i
        .items
        .iter()
        .map(|x| (x.kind.as_str(), x.feature.as_str()))
        .collect();
    assert_eq!(
        kinds,
        [("handoff", "001-login"), ("handoff", "002-logout")],
        "{message}"
    );
    let a = &i.items[0].actions[0];
    assert_eq!(a.run, Some(Runnable::PullRequest));
    assert!(
        a.confirm.is_some(),
        "it leaves the machine: confirmed first"
    );
    // Two features: each command says which.
    assert_eq!(a.command, "speccoder pr --yes --feature 001-login");
    assert!(
        message.starts_with("2 decisions waiting in 2 features"),
        "{message}"
    );
}

#[test]
fn a_changed_spec_comes_before_a_handoff_and_replaces_it() {
    let r = repo();
    write(
        r.path(),
        "specs/002-logout/spec.md",
        &SPEC.replace("log in", "log in with a passkey"),
    );
    git(r.path(), &["commit", "-q", "-am", "spec"]);
    let (i, _) = inbox(r.path());
    let kinds: Vec<(&str, &str)> = i
        .items
        .iter()
        .map(|x| (x.kind.as_str(), x.feature.as_str()))
        .collect();
    // A stale feature is not handed off: its evidence is for the old wording;
    // the reworded requirement waits for the person's review again.
    assert_eq!(
        kinds,
        [
            ("stale", "002-logout"),
            ("review", "002-logout"),
            ("handoff", "001-login")
        ]
    );
    let stale = &i.items[0];
    assert!(stale.detail.contains("T001 (FR-001)"), "{}", stale.detail);
    assert_eq!(stale.actions[0].run, Some(Runnable::Converge));
    assert_eq!(
        stale.actions[0].command,
        "speccoder run --converge --feature 002-logout"
    );
}

#[test]
fn uncommitted_plans_wait_to_be_committed() {
    let r = repo();
    write(r.path(), "specs/001-login/plan.md", "# Plan\n\nRust.\n");
    let (i, _) = inbox(r.path());
    let commit = i
        .items
        .iter()
        .find(|x| x.kind == "commit")
        .expect("commit item");
    assert_eq!(commit.feature, "001-login");
    assert!(matches!(
        &commit.actions[0].run,
        Some(Runnable::Commit { paths }) if paths.iter().any(|p| p.ends_with("plan.md"))
    ));
    // Commit before hand-off: a run reads committed files only.
    let at = |k: &str| i.items.iter().position(|x| x.kind == k).unwrap();
    assert!(at("commit") < at("handoff"));
}

#[test]
fn nothing_waiting_says_so() {
    let dir = tempfile::tempdir().unwrap();
    let r = dir.path();
    write(r, ".specify/memory/constitution.md", "# Constitution\n");
    write(r, ".specify/init-options.json", "{}\n");
    write(r, "specs/001-login/spec.md", SPEC);
    write(
        r,
        "specs/001-login/tasks.md",
        "# Tasks\n\n## Phase 1: Core\n\n- [ ] T001 Implement login per FR-001\n",
    );
    git(r, &["init", "-q", "-b", "main"]);
    git(r, &["add", "-A"]);
    git(r, &["commit", "-q", "-m", "init"]);
    let (i, _) = inbox(r);
    assert_eq!(i.items.len(), 1, "the unreviewed spec: {:?}", i.items);
    assert_eq!(i.items[0].kind, "review");
    let res = speccoder_runtime::review::decide(
        r,
        None,
        &[],
        "approve",
        None,
        speccoder_core::actions::Via::Terminal,
    );
    assert_eq!(
        res.status(),
        speccoder_core::CommandStatus::Ok,
        "{}",
        res.message()
    );
    git(r, &["add", "-A"]);
    git(r, &["commit", "-q", "-m", "review"]);
    let (i, message) = inbox(r);
    assert!(i.items.is_empty(), "{:?}", i.items);
    assert!(message.starts_with("nothing waits for you"), "{message}");
}

/// `repo()` with T002 and T003 open in 001-login, on its branch (where the
/// report reads the task list).
fn with_open_task() -> tempfile::TempDir {
    let r = repo();
    git(r.path(), &["checkout", "-q", "speccoder/001-login"]);
    write(
        r.path(),
        "specs/001-login/tasks.md",
        "# Tasks\n\n## Phase 1: Core\n\n- [x] T001 Implement login per FR-001\n- [ ] T002 Lock out after five failures\n- [ ] T003 Remember the device\n",
    );
    git(r.path(), &["commit", "-q", "-am", "tasks"]);
    git(r.path(), &["checkout", "-q", "main"]);
    r
}

#[test]
fn a_held_ruling_and_a_suspected_shortcut_are_their_own_decisions() {
    let r = with_open_task();
    let state = tempfile::tempdir().unwrap();
    let tmp = tempfile::tempdir().unwrap();
    // T003: the gaming monitor stopped it.
    speccoder_runtime::attempts::save(
        r.path(),
        tmp.path(),
        "001-login",
        "T003",
        &speccoder_runtime::attempts::Record {
            run: Some("r2"),
            outcome: "suspected_gaming",
            reason: "the test was rewritten to assert nothing",
            pending: None,
            usage: None,
        },
    )
    .unwrap();
    // T002: verified, held — its tests reject an alternative the spec allows.
    let plane = speccoder_runtime::worktree::project_state_dir(state.path(), r.path());
    let permitted = speccoder_core::strength::Permitted {
        id: "permitted-1".to_owned(),
        scenario: "US1.2".to_owned(),
        rationale: "lock out after five or more".to_owned(),
        digest: "sha256:0".to_owned(),
        outcome: speccoder_core::strength::PermittedOutcome::Rejected,
        failing: None,
        patch: None,
    };
    speccoder_runtime::strength::hold(
        &speccoder_runtime::strength::dir(&plane, "001-login", "T002"),
        &[&permitted],
    )
    .unwrap();
    let res = speccoder_runtime::inbox::inbox_with(r.path(), Some("001-login"), Some(state.path()));
    let Some(CommandData::Inbox(i)) = res.data() else {
        panic!("{}", res.message())
    };
    let kinds: Vec<(&str, Option<&str>)> = i
        .items
        .iter()
        .map(|x| (x.kind.as_str(), x.task.as_deref()))
        .collect();
    // `--feature`: 002-logout's hand-off is not listed; ruling before gaming.
    assert_eq!(
        kinds,
        [("ruling", Some("T002")), ("gaming", Some("T003"))],
        "{}",
        res.message()
    );
    assert_eq!(i.features, 1);
    let ruling = &i.items[0];
    assert!(ruling.detail.contains("five or more"), "{}", ruling.detail);
    assert_eq!(
        ruling.actions[0].run,
        Some(Runnable::Rule {
            task: "T002".to_owned()
        })
    );
    assert!(ruling.actions[0].input.is_some(), "a ruling needs a reason");
    let gaming = &i.items[1];
    assert!(
        gaming.detail.contains("assert nothing"),
        "{}",
        gaming.detail
    );
    // One feature: commands carry no --feature.
    assert_eq!(
        gaming.actions[0].command,
        "speccoder task nudge T003 --note \"…\""
    );
}

#[test]
fn an_unknown_feature_is_refused_not_ignored() {
    let r = repo();
    let res = speccoder_runtime::inbox::inbox(r.path(), Some("009-nope"));
    assert_ne!(
        res.status(),
        speccoder_core::CommandStatus::Ok,
        "{}",
        res.message()
    );
}

#[test]
fn a_change_request_waits_to_be_revised() {
    let r = repo();
    let res = speccoder_runtime::review::decide(
        r.path(),
        Some("001-login"),
        &["FR-001".to_owned()],
        "request",
        Some("name the login methods"),
        speccoder_core::actions::Via::Terminal,
    );
    assert_eq!(
        res.status(),
        speccoder_core::CommandStatus::Ok,
        "{}",
        res.message()
    );
    let (i, _) = inbox(r.path());
    let revise = i
        .items
        .iter()
        .find(|x| x.kind == "revise")
        .expect("revise item");
    assert_eq!(revise.feature, "001-login");
    assert!(
        revise.detail.contains("FR-001: name the login methods"),
        "{}",
        revise.detail
    );
    // No revising skill installed here: editing by hand is what is offered.
    assert_eq!(revise.actions.len(), 1);
    assert_eq!(
        revise.actions[0].command,
        "speccoder review --feature 001-login"
    );
    // Revise ranks before the hand-off of the other feature.
    let at = |k: &str| i.items.iter().position(|x| x.kind == k).unwrap();
    assert!(at("revise") < at("handoff"));
}

#[test]
fn an_open_question_comes_before_the_review_it_blocks() {
    let r = repo();
    write(
        r.path(),
        "specs/001-login/spec.md",
        "# Spec\n\n## Requirements\n\n- **FR-001**: Users MUST log in [NEEDS CLARIFICATION: with what?].\n",
    );
    let (i, _) = inbox(r.path());
    let q = i
        .items
        .iter()
        .position(|x| x.kind == "question")
        .expect("question item");
    assert_eq!(i.items[q].feature, "001-login");
    assert!(
        i.items[q].detail.contains("Q1: with what?"),
        "{}",
        i.items[q].detail
    );
    let review = i
        .items
        .iter()
        .position(|x| x.kind == "review")
        .expect("review item");
    assert!(
        q < review,
        "{:?}",
        i.items.iter().map(|x| &x.kind).collect::<Vec<_>>()
    );
}