speccoder-core 0.5.2

Pure domain of speccoder: project snapshots, the task graph, verdict rules and command results. No IO, no async.
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! What to do next after a stop or a finish: a closed set of
//! outcomes and, for each, the commands that continue — deterministic, never
//! model text. The human `Next:` block, the TUI footer and `data.next` are
//! all this list.

use serde::{Deserialize, Serialize};

/// One step a person can take. Serialised with how an interface takes it
/// ([`crate::step::How`], beside `command` and `why`).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct NextStep {
    /// A copy-pasteable command (`"…"` marks text the person writes).
    pub command: String,
    /// Why, in one short line.
    pub why: String,
}

// A next step as it is serialised: the schema of `NextStep`.
/// One step a person can take.
#[derive(Serialize, schemars::JsonSchema)]
#[schemars(rename = "NextStep")]
struct Shown<'a> {
    /// A copy-pasteable command (`"…"` marks text the person writes).
    command: &'a str,
    /// Why, in one short line.
    why: &'a str,
    /// How an interface takes it.
    #[serde(flatten)]
    how: crate::step::How,
}

impl Serialize for NextStep {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        Shown {
            command: &self.command,
            why: &self.why,
            how: crate::step::step_of(&self.command, crate::step::Context::default()).how,
        }
        .serialize(serializer)
    }
}

impl schemars::JsonSchema for NextStep {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "NextStep".into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        Shown::json_schema(generator)
    }
}

/// How a command ended, as far as what comes next is concerned.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// A task passed; `ready` tasks can run now.
    TaskPassed {
        /// The task.
        task: String,
        /// Tasks ready after it.
        ready: usize,
    },
    /// Every task of the feature is ticked.
    FeatureDone,
    /// A call waits for a person.
    NeedsApproval {
        /// The task.
        task: String,
    },
    /// The model stopped honestly: the task cannot be done as written.
    Blocked {
        /// The task.
        task: String,
    },
    /// Out of turns or calls.
    BudgetExhausted {
        /// The task.
        task: String,
    },
    /// The model's closing report says the task is not finished.
    Incomplete {
        /// The task.
        task: String,
    },
    /// The checks or the acceptance tests failed after the retries.
    VerificationFailed {
        /// The task.
        task: String,
    },
    /// The gaming monitor suspects a shortcut.
    SuspectedGaming {
        /// The task.
        task: String,
    },
    /// An acceptance test rejects an implementation the spec appears to
    /// allow; the attempt is held for a ruling.
    TestsOverStrict {
        /// The task.
        task: String,
    },
    /// The acceptance set stayed below `min_strength`.
    AcceptanceWeak {
        /// The task.
        task: String,
    },
    /// A convergence gap no failing test shows, or unfinished checklists.
    NotDemonstrated {
        /// The task.
        task: String,
    },
    /// The run itself failed (provider, store, …).
    RunFailed {
        /// The task, when one was running.
        task: Option<String>,
    },
    /// Killed while running; the next run resumes.
    Interrupted {
        /// The task.
        task: String,
    },
    /// A run is in progress.
    Running,
    /// No task can run.
    NothingReady,
    /// The feature is being planned: it has no task list yet; these
    /// planning skills come next.
    Planning {
        /// The skills, in order (`plan`, `tasks`).
        skills: Vec<String>,
    },
    /// `report` shown.
    ReportShown {
        /// Tasks ready to run.
        ready: usize,
        /// Calls waiting for a person.
        open_approvals: usize,
        /// Ticks proven against an earlier wording of what they cite.
        stale: usize,
    },
    /// `approvals` listed.
    ApprovalsListed {
        /// The first task with a call waiting.
        first: Option<String>,
    },
    /// A person's decision recorded (approve, reject, accept, skip, nudge).
    Decided,
    /// The feature's checklists have unchecked items; nothing ran.
    ChecklistsOpen,
    /// `speccoder.toml` or the environment is wrong.
    ConfigError,
    /// git refused (dirty tree, uncommitted artifacts, …).
    GitPrecondition,
    /// An OpenSpec archive waits for a person's yes.
    ArchiveAwaiting {
        /// The change.
        change: String,
    },
}

/// The steps that continue after `outcome`; `--feature F` is appended to
/// speccoder's own commands when given. Total, non-empty, deterministic.
#[must_use]
pub fn next(outcome: &Outcome, feature: Option<&str>) -> Vec<NextStep> {
    use Outcome as O;
    let steps: Vec<(String, &str)> = match outcome {
        O::NeedsApproval { task } => vec![
            (
                "speccoder report --approvals".to_owned(),
                "see the call waiting and why it stopped",
            ),
            (
                format!("speccoder task approve {task}"),
                "allow it; the attempt resumes on the next run",
            ),
            (
                format!("speccoder task reject {task} --reason \"…\""),
                "refuse it; the model is told your reason",
            ),
            ("speccoder run".to_owned(), "continue the feature"),
        ],
        O::Blocked { task } => vec![
            (
                format!("speccoder task done {task}"),
                "you did it: tick it on your word (attested)",
            ),
            (
                format!("speccoder task hint {task} \"…\""),
                "a hint, then a new attempt now",
            ),
            (
                format!("speccoder task skip {task} --reason \"…\""),
                "pass it by; its dependents stay blocked",
            ),
        ],
        O::Incomplete { task } => vec![
            (
                format!("speccoder task nudge {task} --note \"…\""),
                "say what is missing, for the next attempt",
            ),
            (format!("speccoder run --task {task}"), "try the task again"),
            (
                format!("speccoder task skip {task} --reason \"…\""),
                "pass it by; its dependents stay blocked",
            ),
        ],
        O::BudgetExhausted { task } => vec![
            (
                format!("speccoder task nudge {task} --note \"…\""),
                "narrow the next attempt",
            ),
            (format!("speccoder run --task {task}"), "try the task again"),
            (
                format!("speccoder task skip {task} --reason \"…\""),
                "pass it by; its dependents stay blocked",
            ),
        ],
        O::VerificationFailed { task } => vec![
            (
                "speccoder report".to_owned(),
                "see what failed and the saved attempt",
            ),
            (
                format!("speccoder task nudge {task} --note \"…\""),
                "tell the next attempt what to fix",
            ),
            (format!("speccoder run --task {task}"), "try the task again"),
        ],
        O::SuspectedGaming { task } => vec![
            (
                "speccoder report".to_owned(),
                "review the saved attempt and the findings",
            ),
            (format!("speccoder run --task {task}"), "try the task again"),
            (
                format!("speccoder task skip {task} --reason \"…\""),
                "pass it by; its dependents stay blocked",
            ),
        ],
        O::TestsOverStrict { task } => vec![
            (
                format!("speccoder task rule {task} --tests-right --reason \"…\""),
                "the tests are right: the spec does not allow that alternative; the next run ticks the held attempt",
            ),
            (
                format!("speccoder run --task {task} --fresh-acceptance"),
                "the tests are too strict: write them again and attempt anew",
            ),
            (
                format!("speccoder task accept {task} --reason \"…\""),
                "tick it on your word (attested, not verified)",
            ),
        ],
        O::AcceptanceWeak { task } => vec![
            (
                "speccoder report".to_owned(),
                "see which wrong implementations the tests let through",
            ),
            (
                format!("speccoder run --task {task}"),
                "try the task again with fresh acceptance tests",
            ),
            (
                format!("speccoder task accept {task} --reason \"…\""),
                "tick it on your word (attested, not verified)",
            ),
        ],
        O::NotDemonstrated { task } => vec![
            (
                "speccoder report".to_owned(),
                "see why nothing was demonstrated",
            ),
            (
                format!("speccoder task nudge {task} --note \"…\""),
                "tell the next attempt what is meant",
            ),
            (
                format!("speccoder task accept {task} --reason \"…\""),
                "tick it on your word (attested)",
            ),
        ],
        O::RunFailed { task } => {
            let mut v = vec![(
                "speccoder report --live".to_owned(),
                "see where the run stopped",
            )];
            v.push(match task {
                Some(t) => (format!("speccoder run --task {t}"), "try the task again"),
                None => ("speccoder run".to_owned(), "try again"),
            });
            v
        }
        O::Interrupted { .. } => vec![(
            "speccoder run".to_owned(),
            "resume; finished calls will not repeat",
        )],
        O::Running => vec![
            ("speccoder tui".to_owned(), "watch the run"),
            ("speccoder report --live".to_owned(), "where it is now"),
        ],
        O::TaskPassed { ready, .. } if *ready > 0 => vec![
            ("speccoder run".to_owned(), "continue with the ready tasks"),
            ("speccoder report".to_owned(), "every task and its evidence"),
        ],
        O::TaskPassed { .. } | O::FeatureDone => vec![
            ("speccoder report".to_owned(), "every task and its evidence"),
            (
                "speccoder pr".to_owned(),
                "hand the branch off as a draft pull request",
            ),
        ],
        O::NothingReady => vec![
            (
                "speccoder report".to_owned(),
                "see what blocks the open tasks",
            ),
            (
                "speccoder report --approvals".to_owned(),
                "calls waiting for a person",
            ),
        ],
        O::Planning { skills } => {
            let mut steps: Vec<(String, &str)> = skills
                .iter()
                .map(|s| {
                    let why = match s.as_str() {
                        "plan" => "write the plan from the spec",
                        "tasks" => "break the plan into tasks",
                        "clarify" => "settle what the spec leaves open",
                        _ => "the next planning step",
                    };
                    (format!("speccoder spec {s}"), why)
                })
                .collect();
            steps.push((
                "speccoder run".to_owned(),
                "after you review and commit what they write",
            ));
            steps
        }
        O::ReportShown { open_approvals, .. } if *open_approvals > 0 => vec![
            (
                "speccoder report --approvals".to_owned(),
                "calls waiting for a person",
            ),
            ("speccoder run".to_owned(), "continue the feature"),
        ],
        O::ReportShown { stale, .. } if *stale > 0 => vec![(
            "speccoder run --converge".to_owned(),
            "the spec changed: re-check the code against it as it is now",
        )],
        O::ReportShown { ready, .. } if *ready > 0 => {
            vec![("speccoder run".to_owned(), "continue with the ready tasks")]
        }
        O::ReportShown { .. } => vec![(
            "speccoder pr".to_owned(),
            "hand the branch off as a draft pull request",
        )],
        O::ApprovalsListed { first: Some(task) } => vec![
            (
                format!("speccoder task approve {task}"),
                "allow it; the attempt resumes on the next run",
            ),
            (
                format!("speccoder task reject {task} --reason \"…\""),
                "refuse it; the model is told your reason",
            ),
        ],
        O::ApprovalsListed { first: None } | O::Decided => {
            vec![("speccoder run".to_owned(), "continue the feature")]
        }
        O::ChecklistsOpen => vec![(
            "speccoder run --ignore-checklists".to_owned(),
            "run anyway; recorded on every commit",
        )],
        O::ConfigError => vec![
            (
                "speccoder init".to_owned(),
                "write or repair speccoder.toml",
            ),
            (
                "speccoder verify".to_owned(),
                "check the configured checks run",
            ),
        ],
        O::GitPrecondition => vec![
            ("git status".to_owned(), "see what is uncommitted"),
            ("speccoder run".to_owned(), "run again once it is committed"),
        ],
        O::ArchiveAwaiting { change } => vec![
            (
                format!("openspec show {change} --diff"),
                "see what archiving changes in the main specs",
            ),
            (
                format!("speccoder spec archive {change} --yes"),
                "archive it and commit the result",
            ),
        ],
    };
    steps
        .into_iter()
        .map(|(command, why)| NextStep {
            command: match feature {
                Some(f) if command.starts_with("speccoder ") => format!("{command} --feature {f}"),
                _ => command,
            },
            why: why.to_owned(),
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn commands(o: &Outcome) -> Vec<String> {
        next(o, None).into_iter().map(|s| s.command).collect()
    }

    #[test]
    fn every_outcome_has_its_steps() {
        let t = || "T004".to_owned();
        let table: Vec<(Outcome, Vec<&str>)> = vec![
            (
                Outcome::NeedsApproval { task: t() },
                vec![
                    "speccoder report --approvals",
                    "speccoder task approve T004",
                    "speccoder task reject T004 --reason \"…\"",
                    "speccoder run",
                ],
            ),
            (
                Outcome::Blocked { task: t() },
                vec![
                    "speccoder task done T004",
                    "speccoder task hint T004 \"…\"",
                    "speccoder task skip T004 --reason \"…\"",
                ],
            ),
            (
                Outcome::Incomplete { task: t() },
                vec![
                    "speccoder task nudge T004 --note \"…\"",
                    "speccoder run --task T004",
                    "speccoder task skip T004 --reason \"…\"",
                ],
            ),
            (
                Outcome::BudgetExhausted { task: t() },
                vec![
                    "speccoder task nudge T004 --note \"…\"",
                    "speccoder run --task T004",
                    "speccoder task skip T004 --reason \"…\"",
                ],
            ),
            (
                Outcome::VerificationFailed { task: t() },
                vec![
                    "speccoder report",
                    "speccoder task nudge T004 --note \"…\"",
                    "speccoder run --task T004",
                ],
            ),
            (
                Outcome::SuspectedGaming { task: t() },
                vec![
                    "speccoder report",
                    "speccoder run --task T004",
                    "speccoder task skip T004 --reason \"…\"",
                ],
            ),
            (
                Outcome::NotDemonstrated { task: t() },
                vec![
                    "speccoder report",
                    "speccoder task nudge T004 --note \"…\"",
                    "speccoder task accept T004 --reason \"…\"",
                ],
            ),
            (
                Outcome::RunFailed { task: Some(t()) },
                vec!["speccoder report --live", "speccoder run --task T004"],
            ),
            (
                Outcome::RunFailed { task: None },
                vec!["speccoder report --live", "speccoder run"],
            ),
            (Outcome::Interrupted { task: t() }, vec!["speccoder run"]),
            (
                Outcome::Running,
                vec!["speccoder tui", "speccoder report --live"],
            ),
            (
                Outcome::TaskPassed {
                    task: t(),
                    ready: 2,
                },
                vec!["speccoder run", "speccoder report"],
            ),
            (
                Outcome::TaskPassed {
                    task: t(),
                    ready: 0,
                },
                vec!["speccoder report", "speccoder pr"],
            ),
            (
                Outcome::FeatureDone,
                vec!["speccoder report", "speccoder pr"],
            ),
            (
                Outcome::NothingReady,
                vec!["speccoder report", "speccoder report --approvals"],
            ),
            (
                Outcome::ReportShown {
                    ready: 1,
                    open_approvals: 1,
                    stale: 1,
                },
                vec!["speccoder report --approvals", "speccoder run"],
            ),
            (
                Outcome::ReportShown {
                    ready: 1,
                    open_approvals: 0,
                    stale: 0,
                },
                vec!["speccoder run"],
            ),
            (
                Outcome::ReportShown {
                    ready: 0,
                    open_approvals: 0,
                    stale: 2,
                },
                vec!["speccoder run --converge"],
            ),
            (
                Outcome::ReportShown {
                    ready: 0,
                    open_approvals: 0,
                    stale: 0,
                },
                vec!["speccoder pr"],
            ),
            (
                Outcome::ApprovalsListed { first: Some(t()) },
                vec![
                    "speccoder task approve T004",
                    "speccoder task reject T004 --reason \"…\"",
                ],
            ),
            (
                Outcome::ApprovalsListed { first: None },
                vec!["speccoder run"],
            ),
            (Outcome::Decided, vec!["speccoder run"]),
            (
                Outcome::ChecklistsOpen,
                vec!["speccoder run --ignore-checklists"],
            ),
            (
                Outcome::ConfigError,
                vec!["speccoder init", "speccoder verify"],
            ),
            (
                Outcome::GitPrecondition,
                vec!["git status", "speccoder run"],
            ),
        ];
        for (outcome, expected) in &table {
            assert_eq!(commands(outcome), *expected, "{outcome:?}");
            let steps = next(outcome, None);
            assert!(!steps.is_empty());
            assert_eq!(steps, next(outcome, None), "deterministic");
            for s in &steps {
                assert!(s.why.chars().count() <= 60, "{}", s.why);
                assert!(
                    s.why.chars().next().is_some_and(char::is_lowercase),
                    "{}",
                    s.why
                );
            }
        }
    }

    #[test]
    fn the_feature_is_carried_to_speccoder_commands_only() {
        let steps = next(&Outcome::GitPrecondition, Some("001-x"));
        assert_eq!(steps[0].command, "git status");
        assert_eq!(steps[1].command, "speccoder run --feature 001-x");
    }
}