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
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
//! A person's approvals and rejections.
//!
//! When an attempt stops for approval, its pending call is saved with the
//! attempt. `speccoder task approve` turns that call's class — the path
//! of a write, the exact argv of a command — into an approval for the task;
//! `speccoder task reject` into a denial with a reason the model is told. The
//! next attempt carries the task's decisions in its journaled input, so
//! strict replay needs nothing else. Standing approvals for commands are
//! `[commands] allow` in `speccoder.toml`.

use std::collections::BTreeMap;
use std::path::Path;

use serde::{Deserialize, Serialize};
use speccoder_core::{
    ApprovalsReport, CommandData, CommandResult, CommandStatus, DecidedCall, PendingCall,
};

use crate::tools::policy::{Grant, Rejection};

/// The decisions file in a project's state directory.
pub const FILE: &str = "approvals.json";

/// One task's decisions.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskDecisions {
    /// Approved classes.
    #[serde(default)]
    pub approved: Vec<Grant>,
    /// Rejected classes with reasons.
    #[serde(default)]
    pub rejected: Vec<Rejection>,
    /// A person's notes for the task's next attempts (`speccoder task nudge`).
    #[serde(default)]
    pub nudges: Vec<String>,
    /// Every decision, in order, with who made it.
    #[serde(default)]
    pub decided: Vec<Decided>,
}

/// Who decided, through what, and how speccoder knows the name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Who {
    /// The person (see [`who`]).
    pub name: String,
    /// `terminal`, `editor <name>` or `cli`.
    pub via: String,
    /// `asserted` (typed at a local terminal or the CLI) or `connected`
    /// (reported by a client over its connection). speccoder authenticates
    /// nobody, so never `authenticated`.
    #[serde(default = "asserted")]
    pub basis: String,
}

fn asserted() -> String {
    "asserted".to_owned()
}

impl Who {
    /// The local person, deciding through `via`: over an editor's
    /// connection the name is the connection's (`connected`), otherwise
    /// the person's own (`asserted`).
    #[must_use]
    pub fn local(via: &str) -> Self {
        Self::local_in(Path::new("."), via)
    }

    /// [`Who::local`], named as git names the person in `dir` (the project).
    #[must_use]
    pub fn local_in(dir: &Path, via: &str) -> Self {
        Self {
            name: who_in(dir),
            via: via.to_owned(),
            basis: if via.starts_with("editor") {
                "connected"
            } else {
                "asserted"
            }
            .to_owned(),
        }
    }

    /// One line: `hupe (terminal)`.
    #[must_use]
    pub fn describe(&self) -> String {
        format!("{} ({})", self.name, self.via)
    }

    /// agentplane's operator: the name and its basis.
    #[must_use]
    pub fn operator(&self) -> Option<agentplane::core::Operator> {
        agentplane::core::Operator::from_parts(&self.name, &self.basis).ok()
    }

    /// The operator as reports show it.
    #[must_use]
    pub fn view(&self) -> speccoder_core::OperatorView {
        speccoder_core::OperatorView {
            actor: self.name.clone(),
            basis: self.basis.clone(),
        }
    }
}

/// The local person's name, the same for every decision and attestation:
/// git's `user.name` (what their commits say), else the operating-system
/// user, else `unknown` — never a guess.
#[must_use]
pub fn who() -> String {
    who_in(Path::new("."))
}

/// [`who`], reading git's configuration as it applies in `dir`.
#[must_use]
pub fn who_in(dir: &Path) -> String {
    crate::git::Git::at(dir)
        .line(&["config", "user.name"])
        .ok()
        .filter(|n| !n.trim().is_empty())
        .or_else(|| {
            ["USER", "USERNAME", "LOGNAME"]
                .iter()
                .find_map(|k| std::env::var(k).ok().filter(|v| !v.trim().is_empty()))
        })
        .unwrap_or_else(|| "unknown".to_owned())
}

/// One decision, as it was made.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Decided {
    /// `approve` or `reject`.
    pub verb: String,
    /// The call class.
    pub grant: Grant,
    /// A rejection's reason.
    #[serde(default)]
    pub reason: Option<String>,
    /// How far an approval reaches: `once`, `task` or `run` (a rejection
    /// holds for the task).
    #[serde(default = "task_scope")]
    pub scope: String,
    /// An approval's note to the model.
    #[serde(default)]
    pub note: Option<String>,
    /// Who decided.
    pub by: Who,
    /// Seconds since the epoch.
    pub at: u64,
}

fn task_scope() -> String {
    "task".to_owned()
}

fn now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs())
}

/// All decisions, by `feature/task`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Decisions {
    /// By `feature/task`.
    #[serde(default)]
    pub tasks: BTreeMap<String, TaskDecisions>,
}

impl Decisions {
    /// Reads the decisions in `dir`; none when there is no file yet.
    pub fn load(dir: &Path) -> Result<Self, String> {
        match std::fs::read_to_string(dir.join(FILE)) {
            Ok(text) => serde_json::from_str(&text)
                .map_err(|e| format!("{}: {e}", dir.join(FILE).display())),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(e) => Err(format!("{}: {e}", dir.join(FILE).display())),
        }
    }

    /// Writes the decisions to `dir` (temporary file, then rename).
    pub fn save(&self, dir: &Path) -> Result<(), String> {
        std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
        let text = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
        let tmp = dir.join(format!("{FILE}.tmp"));
        std::fs::write(&tmp, text).map_err(|e| format!("{}: {e}", tmp.display()))?;
        std::fs::rename(&tmp, dir.join(FILE)).map_err(|e| format!("{}: {e}", dir.display()))
    }

    /// The decisions for `feature/task`.
    #[must_use]
    pub fn for_task(&self, feature: &str, task: &str) -> TaskDecisions {
        self.tasks
            .get(&format!("{feature}/{task}"))
            .cloned()
            .unwrap_or_default()
    }

    /// Records an approval; a rejection of the same class is withdrawn.
    pub fn approve(&mut self, feature: &str, task: &str, grant: Grant, by: &Who) {
        let d = self.tasks.entry(format!("{feature}/{task}")).or_default();
        d.rejected.retain(|r| r.grant != grant);
        if !d.approved.contains(&grant) {
            d.approved.push(grant.clone());
        }
        d.decided.push(Decided {
            verb: "approve".to_owned(),
            grant,
            reason: None,
            scope: task_scope(),
            note: None,
            by: by.clone(),
            at: now(),
        });
    }

    /// Records a decision that changes nothing for the task (an inline
    /// approval or rejection of one call): the history only.
    pub fn note(&mut self, feature: &str, task: &str, decided: Decided) {
        self.tasks
            .entry(format!("{feature}/{task}"))
            .or_default()
            .decided
            .push(decided);
    }

    /// Records a rejection; an approval of the same class is withdrawn.
    pub fn reject(&mut self, feature: &str, task: &str, grant: Grant, reason: &str, by: &Who) {
        let d = self.tasks.entry(format!("{feature}/{task}")).or_default();
        d.approved.retain(|g| *g != grant);
        d.rejected.retain(|r| r.grant != grant);
        d.rejected.push(Rejection {
            grant: grant.clone(),
            reason: reason.to_owned(),
        });
        d.decided.push(Decided {
            verb: "reject".to_owned(),
            grant,
            reason: Some(reason.to_owned()),
            scope: task_scope(),
            note: None,
            by: by.clone(),
            at: now(),
        });
    }

    /// Whether `grant` was decided for `feature/task` either way.
    #[must_use]
    pub fn decided(&self, feature: &str, task: &str, grant: &Grant) -> bool {
        let d = self.for_task(feature, task);
        d.approved.contains(grant) || d.rejected.iter().any(|r| &r.grant == grant)
    }
}

// ── Inline approvals ────────────────────────────────────────────────

pub mod present;
pub mod tasks;

pub use present::{PresentContext, Presentation, present};

/// A call that needs a person: the identity of the journaled question, so
/// only what the journal already holds goes in (the presentation — the diff,
/// the sandbox line — is built live from it).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Request {
    /// `feature/task`.
    pub task: String,
    /// The task's title.
    #[serde(default)]
    pub task_title: String,
    /// The model turn (1-based).
    #[serde(default)]
    pub turn: u32,
    /// The tool.
    pub tool: String,
    /// Its arguments as the model sent them.
    pub arguments: serde_json::Value,
    /// `write`, `edit`, `run`, `network` or `mcp`.
    #[serde(default)]
    pub kind: String,
    /// Why it needs approval.
    pub reason: String,
    /// What a "for this task" answer would cover.
    pub covers: String,
    /// `high` (runs arbitrary code or uses the network), `medium` (changes
    /// dependencies, frozen tests or repository state; any MCP tool) or `low`.
    pub risk: String,
    /// What the model said in that turn: one line, at most 200 characters,
    /// control characters escaped — a claim, not a fact.
    #[serde(default)]
    pub claim: Option<String>,
    /// The choices offered, in order: of `once`, `task`, `run`, `reject`, `stop`.
    #[serde(default)]
    pub options: Vec<String>,
}

/// How far an approval reaches.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Scope {
    /// This call.
    Once,
    /// The call's class for the rest of the task.
    Task,
    /// The call's class in every task of this run.
    Run,
}

impl Scope {
    /// Its name.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Once => "once",
            Self::Task => "task",
            Self::Run => "run",
        }
    }
}

/// What a person decided.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Decision {
    /// Run the call.
    Approve,
    /// Refuse it; the model is told why.
    Reject,
    /// End the task here; the call waits for `speccoder task approve`.
    Stop,
}

/// A person's answer ("later" is no answer: nothing is journaled until one exists).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Answer {
    /// Approve, reject or stop.
    pub decision: Decision,
    /// How far an approval reaches.
    pub scope: Scope,
    /// An approval's note to the model.
    #[serde(default)]
    pub note: Option<String>,
    /// A rejection's reason — the model is told.
    #[serde(default)]
    pub reason: Option<String>,
    /// Who answered; journaled with the answer.
    #[serde(default)]
    pub by: Option<Who>,
}

impl Answer {
    /// An approval with `scope` and an optional note to the model.
    #[must_use]
    pub fn approve(scope: Scope, note: Option<String>, by: Option<Who>) -> Self {
        Self {
            decision: Decision::Approve,
            scope,
            note: note.filter(|n| !n.trim().is_empty()),
            reason: None,
            by,
        }
    }

    /// A rejection; the model is told `reason`.
    #[must_use]
    pub fn reject(reason: impl Into<String>, by: Option<Who>) -> Self {
        Self {
            decision: Decision::Reject,
            scope: Scope::Once,
            note: None,
            reason: Some(reason.into()),
            by,
        }
    }

    /// Stop the task; the call waits.
    #[must_use]
    pub fn stop(by: Option<Who>) -> Self {
        Self {
            decision: Decision::Stop,
            scope: Scope::Once,
            note: None,
            reason: None,
            by,
        }
    }
}

/// Asks a person, synchronously, while an attempt waits (a terminal prompt
/// in the CLI, a permission request in an editor). The answer is journaled;
/// replay never asks again.
pub trait Approver: Send + Sync + std::fmt::Debug {
    /// The person's answer to the presented call.
    fn ask(&self, p: &Presentation) -> Answer;

    /// The person's free-text answer to a question a hosted skill asks
    ///; `None` when nobody can answer.
    fn answer(&self, question: &str) -> Option<String> {
        let _ = question;
        None
    }

    /// Through what the person answers: `terminal`, or `editor <name>`.
    fn via(&self) -> String {
        "terminal".to_owned()
    }
}

/// The kind of call, from the call alone (it is part of the journaled
/// question, so it never depends on the worktree): `write` (`write_file`),
/// `edit` (`edit_file`), `run`, `network` (a command asking for the network)
/// or `mcp`. Whether a write replaces a file is the presentation's to say.
#[must_use]
pub fn kind_of(tool: &str, arguments: &serde_json::Value) -> &'static str {
    match tool {
        "write_file" => "write",
        "edit_file" => "edit",
        "run_command" if arguments["network"] == true => "network",
        "run_command" => "run",
        t if t.starts_with(crate::mcp::PREFIX) => "mcp",
        _ => "edit",
    }
}

/// The choices offered: "for this run" never for high risk; neither "task"
/// nor "run" when the class is not shown in full.
#[must_use]
pub fn options(risk: &str, subject_complete: bool) -> Vec<String> {
    let mut o = vec!["once"];
    if subject_complete {
        o.push("task");
        if risk != "high" {
            o.push("run");
        }
    }
    o.extend(["reject", "stop"]);
    o.into_iter().map(str::to_owned).collect()
}

/// A model's text, one line, at most 200 characters, control characters
/// escaped: what it claimed in the turn that asked.
#[must_use]
pub fn claim(text: &str) -> Option<String> {
    let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
    let line = present::escape(&line);
    if line.is_empty() {
        return None;
    }
    Some(if line.chars().count() > 200 {
        format!("{}…", line.chars().take(199).collect::<String>())
    } else {
        line
    })
}

/// The risk tier of a call that needs approval, from the policy's reason.
#[must_use]
pub fn risk(tool: &str, reason: &str) -> &'static str {
    let r = reason.to_lowercase();
    if tool == "run_command" && (r.contains("arbitrary") || r.contains("network")) {
        "high"
    } else if tool.starts_with(crate::mcp::PREFIX)
        || r.contains("manifest")
        || r.contains("frozen")
        || r.contains("repository state")
        || r.contains("recursive")
    {
        "medium"
    } else {
        "low"
    }
}

// ── `speccoder report --approvals` / `approve` / `reject` ────────────────────────────

/// The feature, its repository root and its state directory.
fn locate(
    command: &str,
    path: &Path,
    feature: Option<&str>,
    state: &Path,
) -> Result<(String, std::path::PathBuf, std::path::PathBuf), Box<CommandResult>> {
    let inspected = crate::inspect(path, feature);
    let Some(CommandData::Inspect(snapshot)) = inspected.data() else {
        return Err(Box::new(CommandResult::carried(command, &inspected)));
    };
    let Some(f) = snapshot.feature.as_ref() else {
        return Err(Box::new(CommandResult::new(
            command,
            CommandStatus::SelectionNeeded,
            inspected.message(),
        )));
    };
    let root = std::path::PathBuf::from(&snapshot.root);
    Ok((
        f.feature.name.clone(),
        crate::worktree::project_state_dir(state, &root),
        root,
    ))
}

/// Open tasks' latest attempts that stopped for approval and are undecided.
fn pending(
    root: &Path,
    feature: &str,
    open: &[String],
    decisions: &Decisions,
) -> Vec<(PendingCall, Grant)> {
    let mut seen = std::collections::BTreeSet::new();
    let mut out = Vec::new();
    for saved in crate::attempts::list(root, feature) {
        if !open.contains(&saved.task) || !seen.insert(saved.task.clone()) {
            continue; // newest first: only each open task's latest attempt
        }
        let Some(p) = saved.pending.filter(|_| saved.outcome == "needs_approval") else {
            continue;
        };
        let tool = p["tool"].as_str().unwrap_or_default().to_owned();
        let Some(grant) = Grant::of(&tool, &p["arguments"]) else {
            continue;
        };
        if decisions.decided(feature, &saved.task, &grant) {
            continue;
        }
        let presentation = view(root, feature, &saved.task, &saved.reference, &tool, &p);
        out.push((
            PendingCall {
                task: saved.task.clone(),
                covers: grant.describe(),
                tool,
                arguments: p["arguments"].clone(),
                reason: p["reason"].as_str().unwrap_or_default().to_owned(),
                reference: saved.reference.clone(),
                presentation: Some(presentation),
                source: "attempt".to_owned(),
                kind: "approval".to_owned(),
                ..PendingCall::default()
            },
            grant,
        ));
    }
    out
}

/// The saved call as the inline prompt would have shown it: the file as the
/// saved attempt left it, the project's sandbox, the model's claim.
fn view(
    root: &Path,
    feature: &str,
    task: &str,
    reference: &str,
    tool: &str,
    pending: &serde_json::Value,
) -> speccoder_core::ApprovalView {
    let arguments = pending["arguments"].clone();
    let reason = pending["reason"].as_str().unwrap_or_default().to_owned();
    let grant = Grant::of(tool, &arguments);
    let risk = risk(tool, &reason);
    let request = Request {
        task: format!("{feature}/{task}"),
        task_title: String::new(),
        turn: pending["turn"]
            .as_u64()
            .and_then(|t| u32::try_from(t).ok())
            .unwrap_or(0),
        tool: tool.to_owned(),
        kind: kind_of(tool, &arguments).to_owned(),
        covers: grant.as_ref().map(|g| g.describe()).unwrap_or_default(),
        risk: risk.to_owned(),
        claim: pending["claim"].as_str().map(str::to_owned),
        options: options(risk, grant.is_some()),
        arguments,
        reason,
    };
    let path = request.arguments["path"].as_str().unwrap_or_default();
    let file_text = (!path.is_empty())
        .then(|| {
            crate::git::Git::at(root)
                .run(&["show", &format!("{reference}:./{path}")])
                .ok()
                .map(|b| String::from_utf8_lossy(&b).into_owned())
        })
        .flatten();
    presented(root, &request, task, file_text)
}

/// `request` as the inline prompt shows it, with the project's sandbox
/// and `file_text` (the file as the call would find it) for a write.
fn presented(
    root: &Path,
    request: &Request,
    task: &str,
    file_text: Option<String>,
) -> speccoder_core::ApprovalView {
    let config = crate::verify::find_config(root)
        .and_then(|d| std::fs::read_to_string(d.join(crate::verify::config::FILE)).ok())
        .unwrap_or_default();
    let sandbox = crate::sandbox::parse(&config).ok();
    let p = present(
        request,
        &PresentContext {
            root: None,
            sandbox: sandbox
                .as_ref()
                .filter(|c| c.mode != crate::sandbox::Mode::Off)
                .map(|_| {
                    if cfg!(target_os = "macos") {
                        "Seatbelt".to_owned()
                    } else {
                        "Landlock+seccomp".to_owned()
                    }
                }),
            network: match sandbox.map(|c| c.network) {
                Some(crate::sandbox::Network::Loopback) => "loopback",
                Some(crate::sandbox::Network::On) => "unrestricted",
                _ => "none",
            }
            .to_owned(),
            file_text,
        },
    );
    speccoder_core::ApprovalView {
        kind: request.kind.clone(),
        title: p.title,
        subject: p.subject,
        body_lines: p.body,
        sandbox: p.sandbox,
        claim: request.claim.clone(),
        risk: request.risk.clone(),
        scope: format!("for the rest of {task}: {}", p.scope),
    }
}

fn decided(feature: &str, decisions: &Decisions) -> Vec<DecidedCall> {
    let prefix = format!("{feature}/");
    let mut out = Vec::new();
    for (key, d) in &decisions.tasks {
        let Some(task) = key.strip_prefix(&prefix) else {
            continue;
        };
        let last = |g: &Grant| d.decided.iter().rev().find(|x| x.grant == *g);
        out.extend(d.approved.iter().map(|g| DecidedCall {
            task: task.to_owned(),
            decision: "approved".to_owned(),
            covers: g.describe(),
            reason: None,
            by: last(g).map(|x| x.by.describe()),
            scope: Some("task".to_owned()),
            note: last(g).and_then(|x| x.note.clone()),
            operator: last(g).map(|x| x.by.view()),
            via: last(g).map(|x| x.by.via.clone()),
            ..DecidedCall::default()
        }));
        out.extend(d.rejected.iter().map(|r| DecidedCall {
            task: task.to_owned(),
            decision: "rejected".to_owned(),
            covers: r.grant.describe(),
            reason: Some(r.reason.clone()),
            by: last(&r.grant).map(|x| x.by.describe()),
            scope: Some("task".to_owned()),
            note: None,
            operator: last(&r.grant).map(|x| x.by.view()),
            via: last(&r.grant).map(|x| x.by.via.clone()),
            ..DecidedCall::default()
        }));
        // "For this run" decisions live in the history only.
        out.extend(
            d.decided
                .iter()
                .filter(|x| x.verb == "approve" && x.scope == "run")
                .map(|x| DecidedCall {
                    task: task.to_owned(),
                    decision: "approved".to_owned(),
                    covers: x.grant.describe(),
                    reason: None,
                    by: Some(x.by.describe()),
                    scope: Some("run".to_owned()),
                    note: x.note.clone(),
                    operator: Some(x.by.view()),
                    via: Some(x.by.via.clone()),
                    ..DecidedCall::default()
                }),
        );
    }
    out
}

/// Calls of `feature` waiting for a person on a human task, oldest
/// first: the attempt is suspended and resumes once they are decided.
fn waiting_tasks(
    root: &Path,
    dir: &Path,
    feature: &str,
) -> Vec<(PendingCall, agentplane::core::Task)> {
    let Ok(rt) = crate::tokio_runtime() else {
        return Vec::new();
    };
    let Ok(plane) = crate::substrate::Plane::open_for_decisions(dir) else {
        return Vec::new();
    };
    // A call past its deadline is denied as expired before it is listed.
    let _ = rt.block_on(plane.expire_due(agentplane::core::Timestamp::now_utc()));
    let open = rt.block_on(plane.open_tasks()).unwrap_or_default();
    let prefix = format!("{feature}/");
    open.into_iter()
        .filter(|t| t.kind == tasks::APPROVAL)
        .filter_map(|t| {
            let request = tasks::request_of(&t.justification.proposed_action)?;
            let task = request.task.strip_prefix(&prefix)?.to_owned();
            let view = presented(root, &request, &task, None);
            Some((
                PendingCall {
                    task,
                    covers: request.covers.clone(),
                    tool: request.tool.clone(),
                    arguments: request.arguments.clone(),
                    reason: request.reason.clone(),
                    reference: String::new(),
                    presentation: Some(view),
                    call: t.id.to_hex(),
                    source: "task".to_owned(),
                    kind: tasks::APPROVAL.to_owned(),
                    question: None,
                    waiting_since: Some(t.created_at.unix_timestamp().max(0).unsigned_abs()),
                    deadline: t.due_at.map(|d| d.unix_timestamp().max(0).unsigned_abs()),
                },
                t,
            ))
        })
        .collect()
}

/// Denies, as expired, every call in the journal at `dir` whose deadline
/// passed at `now` (nobody's decision); their attempts read the refusal
/// when they next resume.
pub fn expire_due(dir: &Path, now: agentplane::core::Timestamp) -> Result<(), String> {
    let rt = crate::tokio_runtime()?;
    let plane = crate::substrate::Plane::open_for_decisions(dir).map_err(|e| e.0)?;
    rt.block_on(plane.expire_due(now)).map_err(|e| e.0)
}

/// Another task of `feature` whose attempt waits for a person, with what
/// it waits on: its attempt holds the feature's worktree until it is
/// decided and resumed.
#[must_use]
pub fn waiting_elsewhere(
    root: &Path,
    dir: &Path,
    feature: &str,
    task: &str,
) -> Option<(String, String)> {
    waiting_tasks(root, dir, feature)
        .into_iter()
        .map(|(c, _)| c)
        .find(|c| c.task != task && c.source == "task")
        .map(|c| (c.task, c.covers))
}

/// Withdraws every call of `feature` waiting on a person: their attempts
/// were set aside (`--return`, changed intent), so nothing resumes them.
pub fn withdraw_waiting(
    root: &Path,
    dir: &Path,
    feature: &str,
    reason: &str,
) -> Result<usize, String> {
    let rows = waiting_tasks(root, dir, feature);
    if rows.is_empty() {
        return Ok(0);
    }
    let rt = crate::tokio_runtime()?;
    let plane = crate::substrate::Plane::open_for_decisions(dir).map_err(|e| e.0)?;
    let by = Who::local_in(root, "cli")
        .operator()
        .ok_or_else(|| "no name to record the withdrawal under".to_owned())?;
    for (_, task) in &rows {
        rt.block_on(plane.withdraw(task, &by, reason))
            .map_err(|e| e.0)?;
    }
    Ok(rows.len())
}

/// Records `answer` on the waiting call `task` through a plane without the
/// attempt's skill: the run continues when it next resumes.
fn decide_waiting(
    dir: &Path,
    task: &agentplane::core::Task,
    answer: &Answer,
    by: &Who,
) -> Result<(), String> {
    let rt = crate::tokio_runtime()?;
    let plane = crate::substrate::Plane::open_for_decisions(dir).map_err(|e| e.0)?;
    let decision = tasks::decision_for(answer, by, None)
        .ok_or_else(|| format!("`{}` is not a name a decision can carry", by.name))?;
    rt.block_on(plane.decide(task.id, &decision))
        .map(|_| ())
        .map_err(|e| e.0)
}

/// What to do with a pending call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verb<'a> {
    /// Only list.
    List,
    /// Approve the task's pending call.
    Approve(&'a str),
    /// Approve it with a note the next attempt is told.
    ApproveNoted(&'a str, &'a str),
    /// Reject the task's pending call, with a reason.
    Reject(&'a str, &'a str),
    /// Decide waiting calls as `speccoder task approve|reject` options say.
    Decide(Choice<'a>),
}

/// Which waiting calls to decide, and how (`approve`/`reject` options).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Choice<'a> {
    /// The task's calls (`--task`); all of the feature's with `--all` alone.
    pub task: Option<&'a str>,
    /// One call by its id or a prefix of it (`--call`).
    pub call: Option<&'a str>,
    /// Every matching call (`--all`), each decided and recorded on its own.
    pub all: bool,
    /// Approve, or reject.
    pub approve: bool,
    /// How far an approval reaches (`--scope`, default `task`).
    pub scope: Scope,
    /// An approval's note to the model.
    pub note: Option<&'a str>,
    /// A rejection's reason, which the model is told.
    pub reason: Option<&'a str>,
}

impl<'a> Choice<'a> {
    /// Approve the task's waiting call (for the task), with an optional note.
    #[must_use]
    pub fn approve(task: &'a str, note: Option<&'a str>) -> Self {
        Self {
            task: Some(task),
            call: None,
            all: false,
            approve: true,
            scope: Scope::Task,
            note,
            reason: None,
        }
    }

    /// Reject the task's waiting call; the model is told `reason`.
    #[must_use]
    pub fn reject(task: &'a str, reason: &'a str) -> Self {
        Self {
            task: Some(task),
            call: None,
            all: false,
            approve: false,
            scope: Scope::Task,
            note: None,
            reason: Some(reason),
        }
    }
}

/// `approvals`, `approve --task` and `reject --task --reason` against `state`.
pub fn decide_with(
    path: &Path,
    feature: Option<&str>,
    verb: Verb<'_>,
    state: &Path,
) -> CommandResult {
    let command = match verb {
        Verb::List => "approvals",
        Verb::Approve(_) | Verb::ApproveNoted(..) => "approve",
        Verb::Reject(..) => "reject",
        Verb::Decide(c) if c.approve => "approve",
        Verb::Decide(_) => "reject",
    };
    let (feature, dir, root) = match locate(command, path, feature, state) {
        Ok(x) => x,
        Err(r) => return *r,
    };
    let mut decisions = match Decisions::load(&dir) {
        Ok(d) => d,
        Err(e) => return CommandResult::new(command, CommandStatus::ConfigError, &e),
    };
    // Open tasks, from the speccoder branch when there is one.
    let status = crate::status::report(&root, Some(&feature));
    let open: Vec<String> = match status.data() {
        Some(CommandData::Report(r)) => r
            .tasks
            .iter()
            .filter(|t| matches!(t.state.as_str(), "ready" | "blocked"))
            .map(|t| t.id.clone())
            .collect(),
        _ => Vec::new(),
    };
    let tasks_waiting = waiting_tasks(&root, &dir, &feature);
    let waiting = pending(&root, &feature, &open, &decisions);

    // A call waiting on a task is decided there: who, how known, bound to
    // what was shown. Its attempt continues on the next run.
    let choice = match verb {
        Verb::List => None,
        Verb::Approve(t) => Some(Choice::approve(t, None)),
        Verb::ApproveNoted(t, n) => Some(Choice::approve(t, Some(n))),
        Verb::Reject(t, r) => Some(Choice::reject(t, r)),
        Verb::Decide(c) => Some(c),
    };
    if let Some(c) = choice {
        let matching: Vec<&(PendingCall, agentplane::core::Task)> = tasks_waiting
            .iter()
            .filter(|(p, _)| c.task.is_none_or(|t| p.task == t))
            .filter(|(p, _)| {
                c.call
                    .is_none_or(|id| !id.is_empty() && p.call.starts_with(id))
            })
            .collect();
        if matching.len() > 1 && !c.all {
            let list: Vec<String> = matching
                .iter()
                .map(|(p, _)| {
                    format!(
                        "{} ({}, {})",
                        &p.call[..12.min(p.call.len())],
                        p.task,
                        p.covers
                    )
                })
                .collect();
            return CommandResult::new(
                command,
                CommandStatus::UsageError,
                &format!(
                    "{} calls are waiting; name one with --call, or decide them all with --all: {}",
                    matching.len(),
                    list.join(", ")
                ),
            );
        }
        if !matching.is_empty() {
            let by = Who::local_in(&root, "cli");
            let mut lines = Vec::new();
            for (call, row) in &matching {
                let answer = if c.approve {
                    Answer::approve(c.scope, c.note.map(str::to_owned), Some(by.clone()))
                } else {
                    Answer::reject(c.reason.unwrap_or("no reason given"), Some(by.clone()))
                };
                if let Err(e) = decide_waiting(&dir, row, &answer, &by) {
                    return CommandResult::new(command, CommandStatus::Error, &e);
                }
                lines.push(if c.approve {
                    format!(
                        "approved: {} for {} ({}) — by {} ({})",
                        call.covers,
                        call.task,
                        c.scope.name(),
                        by.name,
                        by.basis
                    )
                } else {
                    format!(
                        "rejected: {} for {} — by {} ({}); the model will be told: {}",
                        call.covers,
                        call.task,
                        by.name,
                        by.basis,
                        c.reason.unwrap_or("no reason given")
                    )
                });
            }
            let report = ApprovalsReport {
                decided: decided(&feature, &decisions),
                pending: waiting_tasks(&root, &dir, &feature)
                    .into_iter()
                    .map(|(c, _)| c)
                    .chain(
                        pending(&root, &feature, &open, &decisions)
                            .into_iter()
                            .map(|(c, _)| c),
                    )
                    .collect(),
                feature,
            };
            return CommandResult::new(
                command,
                CommandStatus::Ok,
                &format!(
                    "{}; `speccoder run` continues each attempt where it stopped",
                    lines.join("\n")
                ),
            )
            .with_data(CommandData::Approvals(Box::new(report)));
        }
        if c.all || c.call.is_some() || c.task.is_none() {
            return CommandResult::new(
                command,
                CommandStatus::NotFound,
                "no call matching that awaits a decision (see `speccoder report --approvals`)",
            );
        }
    }
    // In a parallel lane, a stopped attempt is saved with its call:
    // deciding it records a grant the task's next attempt starts with.
    let verb = match verb {
        Verb::Decide(c) => match (c.task, c.approve, c.note) {
            (Some(t), true, Some(n)) => Verb::ApproveNoted(t, n),
            (Some(t), true, None) => Verb::Approve(t),
            (Some(t), false, _) => Verb::Reject(t, c.reason.unwrap_or("no reason given")),
            (None, ..) => Verb::List,
        },
        v => v,
    };

    let message = match verb {
        // Mapped onto the verbs above before this point.
        Verb::List | Verb::Decide(_) => {
            let n = waiting.len() + tasks_waiting.len();
            if n == 0 {
                "nothing awaits a decision".to_owned()
            } else {
                format!("{n} call(s) await a decision")
            }
        }
        Verb::Approve(task) | Verb::ApproveNoted(task, _) | Verb::Reject(task, _) => {
            let Some((call, grant)) = waiting.iter().find(|(c, _)| c.task == task) else {
                return CommandResult::new(
                    command,
                    CommandStatus::NotFound,
                    &format!(
                        "{task} has no call awaiting a decision (see `speccoder report --approvals`)"
                    ),
                );
            };
            let what = match verb {
                Verb::Reject(_, reason) => {
                    decisions.reject(
                        &feature,
                        task,
                        grant.clone(),
                        reason,
                        &Who::local_in(&root, "cli"),
                    );
                    format!(
                        "rejected: {} for {task} — the model will be told: {reason}",
                        call.covers
                    )
                }
                _ => {
                    decisions.approve(&feature, task, grant.clone(), &Who::local_in(&root, "cli"));
                    if let Verb::ApproveNoted(_, note) = verb
                        && !note.trim().is_empty()
                    {
                        let t = decisions
                            .tasks
                            .entry(format!("{feature}/{task}"))
                            .or_default();
                        if let Some(last) = t.decided.last_mut() {
                            last.note = Some(note.trim().to_owned());
                        }
                        // The next attempt is told, beside the approval.
                        t.nudges.push(format!(
                            "A person approved {}: {}",
                            call.covers,
                            note.trim()
                        ));
                    }
                    format!("approved: {} for {task}", call.covers)
                }
            };
            if let Err(e) = decisions.save(&dir) {
                return CommandResult::new(command, CommandStatus::Error, &e);
            }
            format!("{what}; run the task again to continue (speccoder run --task {task})")
        }
    };
    let report = ApprovalsReport {
        decided: decided(&feature, &decisions),
        pending: tasks_waiting
            .into_iter()
            .map(|(c, _)| c)
            .chain(
                pending(&root, &feature, &open, &decisions)
                    .into_iter()
                    .map(|(c, _)| c),
            )
            .collect(),
        feature,
    };
    CommandResult::new(command, CommandStatus::Ok, &message)
        .with_data(CommandData::Approvals(Box::new(report)))
}

/// [`decide_with`] in the default state directory.
#[must_use]
pub fn decide(path: &Path, feature: Option<&str>, verb: Verb<'_>) -> CommandResult {
    match crate::worktree::state_dir() {
        Some(state) => decide_with(path, feature, verb, &state),
        None => CommandResult::new(
            "approvals",
            CommandStatus::ConfigError,
            "no state directory (set SPECCODER_STATE_DIR or HOME)",
        )
        .with_code("NO-STATE-DIR"),
    }
}

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

    #[test]
    fn decisions_round_trip_and_replace_each_other() {
        let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
        let g = Grant::Write {
            path: "Cargo.toml".to_owned(),
        };
        let mut d = Decisions::load(dir.path()).unwrap_or_else(|e| panic!("{e}"));
        let by = Who::local("cli");
        d.reject("f", "T1", g.clone(), "no new dependencies", &by);
        d.approve("f", "T1", g.clone(), &by);
        assert_eq!(d.tasks["f/T1"].decided.len(), 2);
        assert_eq!(d.tasks["f/T1"].decided[1].by, by);
        d.save(dir.path()).unwrap_or_else(|e| panic!("{e}"));
        let back = Decisions::load(dir.path()).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(back.for_task("f", "T1").approved, std::slice::from_ref(&g));
        assert!(back.for_task("f", "T1").rejected.is_empty());
        assert!(back.decided("f", "T1", &g) && !back.decided("f", "T2", &g));
    }
}