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
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
//! `speccoder inbox`: every decision that waits for a person,
//! across the project's features, the most urgent first. When agents write
//! the code, this is the person's work: approve or refuse a call, rule on
//! tests, look at a suspected shortcut, settle a changed spec, decide what
//! to do with a task that did not pass, commit a plan, hand off a branch.
//! Read-only; every item carries the actions that decide it.

use std::path::Path;

use speccoder_core::actions::{Action, Runnable};
use speccoder_core::{
    ApprovalsReport, CommandData, CommandResult, CommandStatus, InboxItem, InboxReport,
    StatusReport,
};

use crate::actions::action;

/// The kinds, most urgent first: what blocks a run, what questions the
/// evidence, what stops a task, what blocks a hand-off.
pub const KINDS: [&str; 10] = [
    "approval", "ruling", "gaming", "stale", "question", "review", "revise", "stuck", "commit",
    "handoff",
];

/// `speccoder inbox [--feature]`: the decisions waiting in every feature of
/// the project at `path`, or in `feature` only.
#[must_use]
pub fn inbox(path: &Path, feature: Option<&str>) -> CommandResult {
    inbox_with(path, feature, crate::worktree::state_dir().as_deref())
}

/// [`inbox`] with an explicit state directory (where waiting calls and
/// held attempts are kept).
#[must_use]
pub fn inbox_with(path: &Path, feature: Option<&str>, state: Option<&Path>) -> CommandResult {
    let listed = crate::current::list(path, None);
    let Some(CommandData::Features(f)) = listed.data() else {
        return CommandResult::carried("inbox", &listed);
    };
    // `--feature` takes a name or a number, as everywhere: the one it selects.
    let only = match feature {
        Some(_) => match crate::current::list(path, feature).data() {
            Some(CommandData::Features(one)) => one.current.clone(),
            _ => None,
        },
        None => None,
    };
    if feature.is_some() && only.is_none() {
        return CommandResult::carried("inbox", &crate::status::report(path, feature));
    }
    let names: Vec<String> = f
        .features
        .iter()
        .map(|e| e.name.clone())
        .filter(|n| only.as_ref().is_none_or(|o| o == n))
        .collect();
    let several = names.len() > 1;
    let mut items = Vec::new();
    for name in &names {
        items.extend(of_feature(path, name, state, several));
    }
    let rank = |k: &str| KINDS.iter().position(|x| *x == k).unwrap_or(KINDS.len());
    items.sort_by(|a, b| {
        rank(&a.kind)
            .cmp(&rank(&b.kind))
            .then(
                a.since
                    .unwrap_or(u64::MAX)
                    .cmp(&b.since.unwrap_or(u64::MAX)),
            )
            .then(a.feature.cmp(&b.feature))
            .then(a.task.cmp(&b.task))
    });
    let message = summary(&items, names.len());
    CommandResult::new("inbox", CommandStatus::Ok, &message).with_data(CommandData::Inbox(
        Box::new(InboxReport {
            items,
            features: names.len(),
        }),
    ))
}

/// `n` with the word for one or for many: `1 tick`, `2 ticks`.
fn count(n: usize, one: &str, many: &str) -> String {
    format!("{n} {}", if n == 1 { one } else { many })
}

/// `3 decisions waiting in 2 features: 1 approval, 2 stuck`.
fn summary(items: &[InboxItem], features: usize) -> String {
    if items.is_empty() {
        return format!(
            "nothing waits for you in {}: the agents can work",
            count(features, "feature", "features")
        );
    }
    let mut in_features: Vec<&str> = items.iter().map(|i| i.feature.as_str()).collect();
    in_features.sort_unstable();
    in_features.dedup();
    let parts: Vec<String> = KINDS
        .iter()
        .filter_map(|k| {
            let n = items.iter().filter(|i| i.kind == *k).count();
            (n > 0).then(|| format!("{n} {k}"))
        })
        .collect();
    format!(
        "{} waiting in {}: {}",
        count(items.len(), "decision", "decisions"),
        count(in_features.len(), "feature", "features"),
        parts.join(", ")
    )
}

/// One feature's items. `several`: commands name the feature.
fn of_feature(path: &Path, feature: &str, state: Option<&Path>, several: bool) -> Vec<InboxItem> {
    let report = crate::status::report(path, Some(feature));
    let Some(CommandData::Report(r)) = report.data() else {
        return Vec::new();
    };
    let approvals: Option<ApprovalsReport> =
        state.and_then(|s| {
            match crate::approvals::decide_with(
                path,
                Some(feature),
                crate::approvals::Verb::List,
                s,
            )
            .data()
            {
                Some(CommandData::Approvals(a)) => Some((**a).clone()),
                _ => None,
            }
        });
    let flag = |command: String| {
        if several {
            format!("{command} --feature {feature}")
        } else {
            command
        }
    };
    let item = |kind: &str, task: Option<&str>, title: String, detail: String, actions| InboxItem {
        kind: kind.to_owned(),
        feature: feature.to_owned(),
        task: task.map(str::to_owned),
        title,
        detail,
        since: None,
        actions,
    };
    let mut out = Vec::new();
    let waiting: Vec<&str> = approvals
        .iter()
        .flat_map(|a| &a.pending)
        .map(|p| p.task.as_str())
        .collect();

    // A run waits on these.
    for p in approvals.iter().flat_map(|a| &a.pending) {
        let question = p.kind == "question";
        let mut yes = action(
            "next",
            if question {
                format!("answer {}", p.task)
            } else {
                format!("approve {}", p.task)
            },
            if question {
                "the attempt resumes with your answer".to_owned()
            } else {
                format!("allow {} for the task", p.covers)
            },
            flag(format!("speccoder task approve {}", p.task)),
        );
        yes.run = Some(Runnable::Approve {
            task: p.task.clone(),
        });
        if question {
            yes.input = Some("Your answer".to_owned());
        }
        let mut no = action(
            "next",
            format!("reject {}", p.task),
            "the model is told your reason",
            flag(format!("speccoder task reject {} --reason \"…\"", p.task)),
        );
        no.run = Some(Runnable::Reject {
            task: p.task.clone(),
        });
        no.input = Some("Why (the model is told)".to_owned());
        let mut i = item(
            "approval",
            Some(&p.task),
            if question {
                format!("{} asks you", p.task)
            } else {
                format!("{} waits for your approval", p.task)
            },
            p.question
                .clone()
                .filter(|_| question)
                .unwrap_or_else(|| format!("{} — {}", p.covers, p.reason)),
            vec![yes, no],
        );
        i.since = p.waiting_since;
        out.push(i);
    }

    let root = Path::new(path);
    let project_state = state.and_then(|s| {
        crate::format::at(root)
            .detect(root)
            .map(|project| crate::worktree::project_state_dir(s, &project))
    });
    for t in &r.tasks {
        let done = matches!(
            t.state.as_str(),
            "verified" | "regression_only" | "attested" | "ticked_without_evidence" | "skipped"
        );
        if done || waiting.contains(&t.id.as_str()) {
            continue;
        }
        let held = project_state
            .as_deref()
            .and_then(|s| crate::strength::held(&crate::strength::dir(s, feature, &t.id)));
        if let Some(held) = held {
            let mut rule = action(
                "task",
                format!("rule on {}", t.id),
                "the tests are right: the flagged alternatives are not what the spec allows",
                flag(format!(
                    "speccoder task rule {} --tests-right --reason \"…\"",
                    t.id
                )),
            );
            rule.run = Some(Runnable::Rule { task: t.id.clone() });
            rule.input = Some("Why the tests are right".to_owned());
            let findings: Vec<String> = held
                .findings
                .iter()
                .map(|p| format!("{} ({})", p.scenario, p.rationale))
                .collect();
            out.push(item(
                "ruling",
                Some(&t.id),
                format!("{}'s tests reject an alternative the spec may allow", t.id),
                findings.join("; "),
                vec![rule, nudge(t, &flag), skip(t, &flag)],
            ));
            continue;
        }
        let Some(a) = &t.last_attempt else {
            continue;
        };
        if a.outcome == "suspected_gaming" {
            out.push(item(
                "gaming",
                Some(&t.id),
                format!("{}: the monitor suspects a shortcut", t.id),
                a.reason.clone(),
                vec![nudge(t, &flag), skip(t, &flag), accept(t, &flag)],
            ));
            continue;
        }
        let mut actions = Vec::new();
        if t.state == "ready" {
            let mut again = action(
                "work",
                format!("run {} again", t.id),
                "with what the last attempt left: its facts and your notes",
                flag(format!("speccoder run --task {}", t.id)),
            );
            again.run = Some(Runnable::Run {
                task: Some(t.id.clone()),
            });
            again.blocked = if !r.uncommitted.is_empty() {
                Some("commit the planning files first".to_owned())
            } else {
                // A waiting call's attempt holds the worktree.
                waiting.first().map(|w| {
                    format!("{w} waits for your decision and holds the worktree: decide it first")
                })
            };
            actions.push(again);
        }
        actions.extend([nudge(t, &flag), skip(t, &flag), accept(t, &flag)]);
        out.push(item(
            "stuck",
            Some(&t.id),
            format!("{}'s last attempt: {}", t.id, a.outcome.replace('_', " ")),
            a.reason.clone(),
            actions,
        ));
    }

    let stale: Vec<String> = r
        .tasks
        .iter()
        .filter_map(|t| {
            let d = t.drift.as_ref().filter(|d| d.stale())?;
            let ids: Vec<&str> = d.requirements.iter().map(|q| q.id.as_str()).collect();
            Some(format!("{} ({})", t.id, ids.join(", ")))
        })
        .collect();
    if !stale.is_empty() {
        let mut a = action(
            "next",
            "re-check against the spec",
            "convergence assesses the code against the spec as it is now",
            flag("speccoder run --converge".to_owned()),
        );
        a.run = Some(Runnable::Converge);
        out.push(item(
            "stale",
            None,
            format!(
                "the spec changed under {}",
                count(stale.len(), "tick", "ticks")
            ),
            format!("proven against an earlier wording: {}", stale.join(", ")),
            vec![a],
        ));
    }

    // The spec, reviewed requirement by requirement.
    if let Some(rv) = crate::review::summary(path, Some(feature)).as_ref() {
        let t = rv.totals;
        // The documents' open questions: answered before anything is built.
        if !rv.questions.is_empty() {
            let read = action(
                "plan",
                "answer the open questions",
                "your words replace each question where it stands",
                flag("speccoder review".to_owned()),
            );
            let mut actions = vec![read];
            if let Some(skill) = &rv.revise_with {
                let mut a = action(
                    "plan",
                    format!("clarify with {skill}"),
                    "the format's skill asks you the questions and writes the answers in",
                    flag(format!("speccoder spec {skill}")),
                );
                a.run = Some(Runnable::Skill {
                    name: skill.clone(),
                    arguments: String::new(),
                });
                actions.push(a);
            }
            out.push(item(
                "question",
                None,
                count(
                    rv.questions.len(),
                    "open question in the spec",
                    "open questions in the spec",
                ),
                rv.questions
                    .iter()
                    .take(3)
                    .map(|q| format!("{}: {}", q.id, q.text))
                    .collect::<Vec<_>>()
                    .join("; "),
                actions,
            ));
        }
        if t.open + t.lapsed > 0 {
            let pending: Vec<&str> = rv
                .requirements
                .iter()
                .filter(|i| i.state == "open" || i.state == "lapsed")
                .map(|i| i.id.as_str())
                .collect();
            let read = action(
                "plan",
                "read the requirements",
                "each one, as the result will be judged against it",
                flag("speccoder review".to_owned()),
            );
            let mut all = action(
                "plan",
                format!(
                    "approve {}",
                    count(pending.len(), "requirement", "requirements")
                ),
                "on their current wording, as you",
                flag("speccoder review approve".to_owned()),
            );
            all.run = Some(Runnable::Review {
                ids: Vec::new(),
                verdict: "approve".to_owned(),
            });
            out.push(item(
                "review",
                None,
                if pending.len() == 1 {
                    "1 requirement waits for your review".to_owned()
                } else {
                    format!("{} requirements wait for your review", pending.len())
                },
                if t.lapsed > 0 {
                    format!(
                        "{}; {} changed since you decided",
                        pending.join(", "),
                        t.lapsed
                    )
                } else {
                    pending.join(", ")
                },
                vec![read, all],
            ));
        }
        if t.changes_requested > 0 {
            let asked: Vec<String> = rv
                .requirements
                .iter()
                .filter(|i| i.state == "changes_requested")
                .map(|i| format!("{}: {}", i.id, i.comment.as_deref().unwrap_or_default()))
                .collect();
            let mut actions = Vec::new();
            if let Some(skill) = &rv.revise_with {
                let mut a = action(
                    "plan",
                    format!("revise the spec ({skill})"),
                    "the format's skill rewrites what you asked; you review the result",
                    flag(format!("speccoder spec {skill} \"…\"")),
                );
                a.run = Some(Runnable::Skill {
                    name: skill.clone(),
                    arguments: rv.revision.clone().unwrap_or_default(),
                });
                actions.push(a);
            }
            actions.push(action(
                "plan",
                "edit the spec yourself",
                "then approve the new wording",
                flag("speccoder review".to_owned()),
            ));
            out.push(item(
                "revise",
                None,
                format!(
                    "{} on the spec",
                    count(t.changes_requested, "change request", "change requests")
                ),
                asked.join("; "),
                actions,
            ));
        }
    }

    if !r.uncommitted.is_empty() {
        let mut a = action(
            "next",
            format!("commit the planning files ({})", r.uncommitted.len()),
            "a run reads committed files only",
            format!(
                "git add {0} && git commit -m \"spec: …\" -- {0}",
                r.uncommitted.join(" ")
            ),
        );
        a.run = Some(Runnable::Commit {
            paths: r.uncommitted.clone(),
        });
        out.push(item(
            "commit",
            None,
            "planning files not committed yet".to_owned(),
            format!("read them, then commit: {}", r.uncommitted.join(", ")),
            vec![a],
        ));
    }

    if handoff(r) && stale.is_empty() {
        let mut pr = action(
            "review",
            "open a draft pull request",
            "push the branch and its evidence; open (or update) the draft",
            flag("speccoder pr --yes".to_owned()),
        );
        pr.run = Some(Runnable::PullRequest);
        pr.confirm = Some(
            "Push the feature's speccoder branch and its attestation notes to `origin`, and open (or update) its draft pull request on GitHub, as you (your token).".to_owned(),
        );
        out.push(item(
            "handoff",
            None,
            format!("every task is done: review {} and hand it off", r.feature),
            format!(
                "{} on {} not merged",
                count(r.unmerged_commits, "commit", "commits"),
                r.branch.as_deref().unwrap_or_default()
            ),
            vec![pr],
        ));
    }
    out
}

/// Every task finished and the branch carries work not merged.
fn handoff(r: &StatusReport) -> bool {
    !r.tasks.is_empty()
        && r.totals.ready == 0
        && r.totals.blocked == 0
        && r.unmerged_commits > 0
        && r.branch.is_some()
}

fn with_input(
    t: &speccoder_core::TaskStatus,
    verb: &str,
    why: &str,
    prompt: &str,
    run: Runnable,
    flag: &dyn Fn(String) -> String,
) -> Action {
    let option = if verb == "nudge" {
        "--note"
    } else {
        "--reason"
    };
    let mut a = action(
        "task",
        format!("{verb} {}", t.id),
        why,
        flag(format!("speccoder task {verb} {} {option} \"…\"", t.id)),
    );
    a.run = Some(run);
    a.input = Some(prompt.to_owned());
    a
}

fn nudge(t: &speccoder_core::TaskStatus, flag: &dyn Fn(String) -> String) -> Action {
    with_input(
        t,
        "nudge",
        "a note its next attempts read",
        "The note",
        Runnable::Nudge { task: t.id.clone() },
        flag,
    )
}

fn skip(t: &speccoder_core::TaskStatus, flag: &dyn Fn(String) -> String) -> Action {
    with_input(
        t,
        "skip",
        "runs pass it by; what depends on it stays blocked",
        "Why it is skipped",
        Runnable::Skip { task: t.id.clone() },
        flag,
    )
}

fn accept(t: &speccoder_core::TaskStatus, flag: &dyn Fn(String) -> String) -> Action {
    with_input(
        t,
        "accept",
        "tick it on your word (attested, never shown as verified)",
        "Why it is done",
        Runnable::Accept { task: t.id.clone() },
        flag,
    )
}