speccoder-runtime 0.10.1

Application services of speccoder: the only crate that executes anything.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
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
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
//! Live progress: what a run is doing while it does it.
//!
//! Events are a side channel — not journaled, not evidence — so replay and
//! verdicts are untouched. [`Live`] keeps `live.json` in the project's state
//! directory up to date (read by `speccoder report --live` from another terminal),
//! prices token counts when `[model]` has prices, and forwards each event to
//! the CLI's printer.

use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use serde::{Deserialize, Serialize};
use speccoder_core::stage::{Stage, StageState};
use speccoder_core::{CommandData, CommandResult, CommandStatus};

use crate::substrate::model_config::Prices;

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

/// One task of a feature run's plan.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PlannedTask {
    /// Task ID.
    pub id: String,
    /// Title.
    pub title: String,
    /// `done`, `ready`, `blocked` or `skipped`.
    pub state: String,
}

/// One entry of an external agent's plan.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlanEntry {
    /// What it says it will do (its words, escaped, at most 200 characters).
    pub content: String,
    /// `pending`, `in_progress` or `completed`.
    pub status: String,
}

/// Tool calls `live.json` keeps for watchers (`speccoder tui`).
pub const RECENT: usize = 12;

/// Something a run did.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum Event {
    /// A feature run begins: its tasks, as the graph has them (editors show
    /// them as a plan).
    RunStarted {
        /// Feature directory name.
        feature: String,
        /// Every task, in document order.
        tasks: Vec<PlannedTask>,
    },
    /// A task attempt run begins.
    TaskStarted {
        /// Feature directory name.
        feature: String,
        /// Task ID.
        task: String,
        /// Task title.
        title: String,
    },
    /// A stage of the task's pipeline began, ended or does not apply.
    Stage {
        /// Task ID.
        task: String,
        /// Which stage.
        stage: Stage,
        /// Where it is.
        state: StageState,
        /// `1/2 · sample 2/3` for an attempt, a short commit id, a reason.
        detail: Option<String>,
        /// How long it took, once it ended.
        elapsed_ms: Option<u64>,
        /// The last lines of a failed check (at most five).
        tail: Vec<String>,
    },
    /// A run picks up an attempt a killed process left behind.
    Resumed {
        /// Task ID.
        task: String,
        /// The stage it was in, when known.
        stage: Option<Stage>,
        /// The last tool call, when known.
        last_call: Option<String>,
    },
    /// A call waits for a person: notify them.
    ApprovalRequested {
        /// Task ID.
        task: String,
        /// The model's call id.
        call: String,
        /// The tool.
        tool: String,
        /// What waits, e.g. `cargo add x` (no control characters, ≤ 60 chars).
        what: String,
        /// The class of the object a decision covers: `write`, `command`,
        /// `network` or `mcp` (empty: none, the call is decided once).
        class: String,
        /// The object's short form: the path, `argv#<12 hex>`,
        /// `<tool>@<12 hex>` — no argv beyond what `what` shows.
        object: String,
    },
    /// A person decided a call inline.
    ApprovalDecided {
        /// Task ID.
        task: String,
        /// The model's call id.
        call: String,
        /// `approve` or `reject`.
        decision: String,
        /// `once`, `task` or `run`, for an approval.
        scope: Option<String>,
        /// Who decided.
        by: String,
        /// How that is known: `asserted`, `connected` (or `expired`).
        how: String,
        /// The object's class, as for [`Event::ApprovalRequested`].
        class: String,
        /// The object's short form.
        object: String,
    },
    /// A tool call the model asked for, with the policy's decision.
    ToolCall {
        /// Task ID.
        task: String,
        /// Model turn (1-based) within the attempt.
        turn: u32,
        /// The tool.
        tool: String,
        /// Its target: a path, a command, a pattern.
        target: String,
        /// `allow`, `deny`, `approval`, `unknown`, `stop`.
        decision: String,
        /// Whether an allowed call succeeded.
        ok: Option<bool>,
        /// The last lines of a failed command (at most five).
        tail: Vec<String>,
        /// Allowed without asking because the sandbox confines it.
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        contained: bool,
    },
    /// Tokens so far in the current attempt.
    Usage {
        /// Task ID.
        task: String,
        /// Input tokens.
        input_tokens: u64,
        /// Output tokens.
        output_tokens: u64,
        /// Input tokens read from the cache.
        cache_read_tokens: u64,
        /// Input tokens written to the cache.
        cache_write_tokens: u64,
        /// USD, when priced.
        usd: Option<f64>,
    },
    /// The task run ended.
    TaskFinished {
        /// Task ID.
        task: String,
        /// `verified`, `regression_only`, `failed`, `blocked`, …
        outcome: String,
        /// The run's message.
        message: String,
        /// The attempt's agentplane run, when one ran.
        run: Option<String>,
        /// Input tokens, all attempts and the acceptance call.
        input_tokens: u64,
        /// Output tokens.
        output_tokens: u64,
        /// Input tokens read from the cache.
        cache_read_tokens: u64,
        /// Input tokens written to the cache.
        cache_write_tokens: u64,
        /// USD, when priced.
        usd: Option<f64>,
        /// A regression-only tick: why, worded.
        regression: Option<speccoder_core::regression::Regression>,
    },
    /// The attempt's changed test files were checked against what the run
    /// collected (`collection.checked`).
    CollectionChecked {
        /// Task ID.
        task: String,
        /// Each judged file: path, state, what decided it.
        files: Vec<CollectionFile>,
    },
    /// An external agent makes the attempt: its name, and what its
    /// permission mode is (`decides_alone`: calls it makes without asking
    /// never reach speccoder, so an empty Needs You proves nothing).
    AgentStarted {
        /// Task ID.
        task: String,
        /// The agent's name.
        agent: String,
        /// Its permission mode, in a sentence.
        mode: String,
        /// It is in a mode that decides some calls without asking.
        decides_alone: bool,
        /// A recording of its version says whether it asks (`false`: not
        /// known, and said so).
        known: bool,
    },
    /// An external agent changed something without asking (its own
    /// settings let it): the count so far.
    AgentUnasked {
        /// Task ID.
        task: String,
        /// Calls it reported making without a request of speccoder's.
        calls: u32,
    },
    /// An external agent's plan for its attempt, as it last sent it: its
    /// claim of what it will do, never evidence.
    AgentPlan {
        /// Task ID.
        task: String,
        /// The entries, in its order.
        entries: Vec<PlanEntry>,
    },
    /// What the model said in a turn, beside its tool calls: its
    /// account of what it is doing — a claim, never evidence. Control
    /// characters escaped; at most 2000 characters.
    Said {
        /// Task ID.
        task: String,
        /// Model turn (1-based) within the attempt.
        turn: u32,
        /// The words.
        text: String,
    },
    /// The model's summary of its reasoning in a turn, as the provider
    /// gave it (`[model] reasoning_summary`): its account of why — a claim,
    /// never evidence. Control characters escaped; at most 4000 characters.
    Reasoning {
        /// Task ID.
        task: String,
        /// Model turn (1-based) within the attempt.
        turn: u32,
        /// The summary.
        text: String,
    },
    /// Anything else worth a line (convergence rounds, notices).
    Notice {
        /// The line.
        text: String,
    },
    /// A bug's step (`bug.*` on the event stream).
    Bug {
        /// The task (`T003`, `bug:<slug>`).
        task: String,
        /// What happened.
        step: BugEvent,
    },
    /// The oracle at review (`oracle.*` on the event stream): stage names,
    /// counts and digests — never a test's content, never held-out material.
    Oracle {
        /// What happened.
        step: OracleEvent,
    },
    /// Plan through stopped (`planning.stopped`).
    PlanningStopped {
        /// The unit, once it exists.
        unit: Option<String>,
        /// `questions`, `review`, `failed`, `done`.
        kind: String,
        /// The skill a continuation runs next.
        next_skill: Option<String>,
    },
    /// A quick change or bug fix that grew is offered as a spec of its own
    /// (`ladder.offered`): the signals that hold, by id.
    LadderOffered {
        /// Its unit.
        unit: String,
        /// The task.
        task: String,
        /// `S1`…`S4`.
        signals: Vec<String>,
    },
    /// A unit was promoted from a quick change or bug fix (`unit.promoted`):
    /// ids and digests, never the words.
    UnitPromoted {
        /// The new unit.
        unit: String,
        /// Where it came from.
        from_unit: String,
        /// The requirement promoted.
        requirement: String,
        /// The task it came from.
        task: String,
        /// The requirement's words' digest.
        requirement_sha256: String,
        /// The digests of the conversations carried.
        conversation_sha256: Vec<String>,
        /// The signals that held.
        signals: Vec<String>,
        /// Who.
        by: String,
        /// Through what.
        via: String,
    },
    /// A new project's step, its creation or its undo (`scaffold.*`,
    /// `project.*`): step ids, argv, states, digests — never the idea,
    /// never the folder's path.
    Project {
        /// What happened.
        step: ProjectEvent,
    },
    /// An Ask turn read something (`ask.step`).
    AskStep {
        /// The conversation.
        conversation: String,
        /// The turn.
        turn: u32,
        /// The tool.
        tool: String,
        /// What it read, in one line.
        target: String,
        /// The read id the answer may cite, when it returned something.
        read: Option<String>,
        /// It failed or was refused.
        refused: bool,
    },
    /// An Ask turn's answer as it is written (`ask.text`).
    AskText {
        /// The conversation.
        conversation: String,
        /// The turn.
        turn: u32,
        /// The next words.
        delta: String,
    },
    /// Inside the Ask plane: a turn's raw end, which `ask::turn` turns
    /// into [`Event::AskDone`]; never forwarded.
    AskTurnEnded {
        /// `ask:<conversation>#<turn>`.
        tag: String,
        /// The loop's output.
        output: Box<serde_json::Value>,
    },
    /// An Ask turn ended (`ask.done`).
    AskDone {
        /// The turn as shown.
        report: Box<speccoder_core::ask::AskReport>,
    },
}

/// A new project's step, its creation or its undo.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum ProjectEvent {
    /// A step began (progress).
    ScaffoldStarted {
        /// The step (`git_init`, `scaffold.1`, …).
        step: String,
        /// Its command.
        argv: Vec<String>,
        /// `local` or `network`.
        access: String,
    },
    /// A step ended (progress).
    ScaffoldFinished {
        /// The step.
        step: String,
        /// `done`, `skipped`, `failed`.
        state: String,
        /// Its exit status, when it ran.
        exit: Option<i32>,
        /// How long it took.
        duration_ms: u64,
    },
    /// The project was created and committed (domain).
    Created {
        /// SHA-256 of the folder's canonical path.
        path_digest: String,
        /// `new_folder` or `existing_repository`.
        mode: String,
        /// The stack.
        stack: String,
        /// The spec format.
        format: String,
        /// speccoder's commit.
        commit: String,
        /// Through what.
        via: String,
    },
    /// The project speccoder created was undone (domain).
    Undone {
        /// SHA-256 of the folder's canonical path.
        path_digest: String,
        /// `trash` or `revert`.
        how: String,
        /// Through what.
        via: String,
    },
}

/// One judged file of [`Event::CollectionChecked`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct CollectionFile {
    /// Workspace-relative path.
    pub path: String,
    /// `collected`, `not_collected`, `unknown`.
    pub state: speccoder_core::collection::FileState,
    /// `static`, `junit`, `listing`; `null` when unknown.
    pub decided_by: Option<speccoder_core::collection::DecidedBy>,
}

/// A step of the oracle at review.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum OracleEvent {
    /// Writing tests went one stage further (progress).
    Stage {
        /// The requirement.
        requirement: String,
        /// `writing`, `comparing`, `checking_red`, `held_out`.
        stage: String,
        /// This stage's step.
        n: u32,
        /// Of.
        of: u32,
    },
    /// The approval froze a requirement's tests (domain).
    Frozen {
        /// The unit.
        unit: String,
        /// The requirement.
        requirement: String,
        /// The visible set's manifest digest.
        manifest_sha256: String,
        /// The approval's digest.
        approval_sha256: String,
        /// Visible tests frozen.
        visible_count: usize,
        /// Held-out tests sealed with them.
        held_out_count: usize,
        /// Who.
        by: String,
        /// Through what.
        via: String,
    },
    /// A frozen oracle lapsed with its requirement's wording (domain).
    Lapsed {
        /// The unit.
        unit: String,
        /// The requirement.
        requirement: String,
        /// The wording it was frozen on.
        frozen_wording_sha256: String,
        /// The wording now.
        current_wording_sha256: String,
    },
}

/// One statement's class in a reproduce try.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StatementClass {
    /// `E1`, `U1`.
    pub statement: String,
    /// The red class (`assertion`, `passed`, …).
    pub class: String,
}

/// A reproduction as the stream shows it: never its content.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ShownReproduction {
    /// Its statement.
    pub statement: String,
    /// Its file.
    pub file: String,
    /// Its test.
    pub test: String,
    /// Its content's digest.
    pub digest: String,
}

/// A special case as the stream shows it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ShownSpecialCase {
    /// The statement it targets.
    pub statement: String,
    /// Rejected by the combined set.
    pub rejected: bool,
}

/// A bug's step.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum BugEvent {
    /// The triad is recorded (domain).
    Recorded {
        /// The home's kind.
        home: String,
        /// The unit.
        unit: String,
        /// The requirement.
        requirement: String,
        /// The triad's digest.
        triad_digest: String,
        /// Through what.
        via: String,
    },
    /// One reproduce try ended.
    ReproduceTry {
        /// The try.
        n: u32,
        /// Of at most.
        of: u32,
        /// Per statement.
        per_statement: Vec<StatementClass>,
    },
    /// Every statement is reproduced.
    Reproduced {
        /// The reproductions.
        reproductions: Vec<ShownReproduction>,
    },
    /// The reproductions wait for the person.
    ConfirmWaiting {
        /// The digest to confirm.
        digest: String,
        /// The command.
        next: String,
    },
    /// The person confirmed them (domain).
    Confirmed {
        /// The digest.
        digest: String,
        /// Who.
        by: String,
        /// Through what.
        via: String,
        /// `shown` or `named_test`.
        basis: String,
    },
    /// The person rejected them (domain).
    ConfirmRejected {
        /// The digest.
        digest: String,
        /// Why.
        reason: String,
    },
    /// The pass-to-pass set was chosen.
    UnchangedSelected {
        /// `selected` or `none_selected`.
        state: String,
        /// Members.
        count: usize,
    },
    /// The revert and special cases were judged.
    Discrimination {
        /// `rejected`, `survived`, `unviable`.
        revert: String,
        /// The special cases.
        special_case: Vec<ShownSpecialCase>,
    },
    /// The bug's outcome (domain).
    Outcome {
        /// `awaiting_confirmation`, `cannot_reproduce`, …
        outcome: String,
        /// The fix's verdict.
        verdict: Option<String>,
        /// The stop's code.
        code: Option<String>,
        /// What to do next.
        next: Vec<String>,
    },
}

impl BugEvent {
    /// Its name on the event stream (registered in
    /// `speccoder_core::event::REGISTRY`).
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Recorded { .. } => "bug.recorded",
            Self::ReproduceTry { .. } => "bug.reproduce_try",
            Self::Reproduced { .. } => "bug.reproduced",
            Self::ConfirmWaiting { .. } => "bug.confirm_waiting",
            Self::Confirmed { .. } => "bug.confirmed",
            Self::ConfirmRejected { .. } => "bug.confirm_rejected",
            Self::UnchangedSelected { .. } => "bug.unchanged_selected",
            Self::Discrimination { .. } => "bug.discrimination",
            Self::Outcome { .. } => "bug.outcome",
        }
    }

    /// The line a plain progress printer shows.
    #[must_use]
    pub fn line(&self) -> String {
        match self {
            Self::Recorded {
                unit, requirement, ..
            } => format!("bug recorded as {requirement} in {unit}"),
            Self::ReproduceTry {
                n,
                of,
                per_statement,
            } => format!(
                "reproduce try {n}/{of}: {}",
                per_statement
                    .iter()
                    .map(|s| format!("{} {}", s.statement, s.class))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            Self::Reproduced { reproductions } => format!(
                "reproduced: {} test(s) fail on an assertion",
                reproductions
                    .iter()
                    .filter(|r| r.statement.starts_with('E'))
                    .count()
            ),
            Self::ConfirmWaiting { next, .. } => format!("the reproductions wait for you: {next}"),
            Self::Confirmed { by, basis, .. } => {
                format!("reproductions confirmed by {by} ({basis})")
            }
            Self::ConfirmRejected { reason, .. } => format!("reproductions rejected: {reason}"),
            Self::UnchangedSelected { state, count } => {
                format!("pass-to-pass: {count} test(s) ({state})")
            }
            Self::Discrimination {
                revert,
                special_case,
            } => format!(
                "revert {revert}; {} special case(s), {} rejected",
                special_case.len(),
                special_case.iter().filter(|s| s.rejected).count()
            ),
            Self::Outcome {
                outcome, verdict, ..
            } => match verdict {
                Some(v) => format!("bug {outcome}: {v}"),
                None => format!("bug {outcome}"),
            },
        }
    }
}

/// Receives events as they happen.
pub trait Progress: Send + Sync + std::fmt::Debug {
    /// One event.
    fn event(&self, event: &Event);
}

/// What `live.json` holds.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct LiveState {
    /// The speccoder process.
    pub pid: u32,
    /// Feature directory name.
    pub feature: String,
    /// Task ID.
    pub task: String,
    /// Task title.
    pub title: String,
    /// The current stage.
    #[serde(default)]
    pub stage: Option<Stage>,
    /// Its detail (`1/2`, a commit id).
    #[serde(default)]
    pub stage_detail: Option<String>,
    /// The last tool call, e.g. `edit_file src/lib.rs (allow)`.
    pub last_call: Option<String>,
    /// What the model last said, its first line (a claim).
    #[serde(default)]
    pub said: Option<String>,
    /// The last line of the model's latest reasoning summary (a claim).
    #[serde(default)]
    pub thinking: Option<String>,
    /// The latest tool calls, oldest first (at most [`RECENT`]).
    #[serde(default)]
    pub recent: Vec<String>,
    /// Commands the sandbox confined, run without asking, this attempt.
    #[serde(default)]
    pub contained: u32,
    /// Tokens of the current attempt.
    pub input_tokens: u64,
    /// Output tokens of the current attempt.
    pub output_tokens: u64,
    /// USD of the current attempt, when priced.
    pub usd: Option<f64>,
    /// Set when the task run ended: its outcome and message.
    pub finished: Option<String>,
    /// Unix seconds when the task run started.
    pub started_at: u64,
    /// Unix seconds of the last event.
    pub updated_at: u64,
    /// The external agent making the attempt, when one is.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent: Option<LiveAgent>,
}

/// An external agent's attempt as it goes: its plan, and what speccoder
/// decided of what it asked.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LiveAgent {
    /// Its name.
    pub name: String,
    /// Its permission mode, in a sentence.
    pub mode: String,
    /// It decides some calls without asking (its mode, or calls it was
    /// seen to make unasked).
    pub decides_alone: bool,
    /// A recording says whether it asks.
    #[serde(default)]
    pub known: bool,
    /// Calls it made without asking.
    #[serde(default)]
    pub unasked: u32,
    /// Its plan, as it last sent it.
    #[serde(default)]
    pub plan: Vec<PlanEntry>,
    /// Calls speccoder decided.
    pub asked: u32,
    /// Of them, allowed.
    pub allowed: u32,
    /// Of them, waited for a person.
    pub waited: u32,
    /// Of them, refused.
    pub refused: u32,
}

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

/// USD for token counts (input includes cache reads and writes).
#[must_use]
pub fn usd(
    prices: Option<Prices>,
    input: u64,
    output: u64,
    cache_read: u64,
    cache_write: u64,
) -> Option<f64> {
    prices.map(|p| p.usd(input, output, cache_read, cache_write))
}

/// Keeps `live.json`, prices usage, forwards to a printer.
#[derive(Debug)]
pub struct Live {
    file: PathBuf,
    prices: Option<Prices>,
    sink: Option<Arc<dyn Progress>>,
    state: Mutex<LiveState>,
}

impl Live {
    /// A live record in `dir` forwarding to `sink`.
    #[must_use]
    pub fn new(dir: &Path, prices: Option<Prices>, sink: Option<Arc<dyn Progress>>) -> Self {
        let _ = std::fs::create_dir_all(dir);
        Self {
            file: dir.join(FILE),
            prices,
            sink,
            state: Mutex::new(LiveState {
                pid: std::process::id(),
                ..LiveState::default()
            }),
        }
    }

    fn write(&self, state: &LiveState) {
        if let Ok(text) = serde_json::to_string_pretty(state) {
            let tmp = self.file.with_extension("json.tmp");
            if std::fs::write(&tmp, text).is_ok() {
                let _ = std::fs::rename(&tmp, &self.file);
            }
        }
    }
}

impl Progress for Live {
    fn event(&self, event: &Event) {
        let mut event = event.clone();
        // Price what can be priced.
        match &mut event {
            Event::Usage {
                input_tokens,
                output_tokens,
                cache_read_tokens,
                cache_write_tokens,
                usd: price,
                ..
            } => {
                *price = usd(
                    self.prices,
                    *input_tokens,
                    *output_tokens,
                    *cache_read_tokens,
                    *cache_write_tokens,
                )
            }
            Event::TaskFinished {
                input_tokens,
                output_tokens,
                cache_read_tokens,
                cache_write_tokens,
                usd: price,
                ..
            } => {
                *price = usd(
                    self.prices,
                    *input_tokens,
                    *output_tokens,
                    *cache_read_tokens,
                    *cache_write_tokens,
                )
            }
            _ => {}
        }
        if let Ok(mut s) = self.state.lock() {
            match &event {
                Event::TaskStarted {
                    feature,
                    task,
                    title,
                } => {
                    *s = LiveState {
                        pid: s.pid,
                        feature: feature.clone(),
                        task: task.clone(),
                        title: title.clone(),
                        started_at: now(),
                        ..LiveState::default()
                    };
                }
                Event::Stage {
                    stage,
                    state: StageState::Started,
                    detail,
                    ..
                } => {
                    s.stage = Some(*stage);
                    s.stage_detail.clone_from(detail);
                }
                Event::Said { text, .. } => {
                    s.said = text
                        .lines()
                        .find(|l| !l.trim().is_empty())
                        .map(|l| l.chars().take(160).collect());
                }
                // Its conclusion: where the summary ends up.
                Event::Reasoning { text, .. } => {
                    s.thinking = text
                        .lines()
                        .rev()
                        .find(|l| !l.trim().is_empty())
                        .map(|l| l.chars().take(160).collect());
                }
                Event::AgentStarted {
                    agent,
                    mode,
                    decides_alone,
                    known,
                    ..
                } => {
                    s.agent = Some(LiveAgent {
                        name: agent.clone(),
                        mode: mode.clone(),
                        decides_alone: *decides_alone,
                        known: *known,
                        ..LiveAgent::default()
                    });
                }
                Event::AgentUnasked { calls, .. } => {
                    if let Some(a) = s.agent.as_mut() {
                        a.unasked = *calls;
                        a.decides_alone = true;
                    }
                }
                Event::AgentPlan { entries, .. } => {
                    if let Some(a) = s.agent.as_mut() {
                        a.plan.clone_from(entries);
                    }
                }
                Event::ApprovalRequested { .. } => {
                    if let Some(a) = s.agent.as_mut() {
                        a.waited += 1;
                    }
                }
                Event::Stage { .. } | Event::Resumed { .. } | Event::ApprovalDecided { .. } => {}
                Event::ToolCall {
                    turn,
                    tool,
                    target,
                    decision,
                    contained,
                    ..
                } => {
                    let decision = if *contained {
                        s.contained += 1;
                        "contained"
                    } else {
                        decision.as_str()
                    };
                    if let Some(a) = s.agent.as_mut()
                        && decision != "reported"
                    {
                        a.asked += 1;
                        match decision {
                            "allow" => a.allowed += 1,
                            "deny" => a.refused += 1,
                            _ => {}
                        }
                    }
                    let call = format!("{tool} {target} ({decision})");
                    s.recent.push(format!("turn {turn}  {call}"));
                    if s.recent.len() > RECENT {
                        s.recent.remove(0);
                    }
                    s.last_call = Some(call);
                }
                Event::Usage {
                    input_tokens,
                    output_tokens,
                    usd,
                    ..
                } => {
                    s.input_tokens = *input_tokens;
                    s.output_tokens = *output_tokens;
                    s.usd = *usd;
                }
                Event::TaskFinished {
                    outcome, message, ..
                } => s.finished = Some(format!("{outcome}: {message}")),
                Event::Notice { .. }
                | Event::RunStarted { .. }
                | Event::Bug { .. }
                | Event::Oracle { .. }
                | Event::CollectionChecked { .. }
                | Event::PlanningStopped { .. }
                | Event::LadderOffered { .. }
                | Event::UnitPromoted { .. }
                | Event::Project { .. }
                | Event::AskStep { .. }
                | Event::AskText { .. }
                | Event::AskTurnEnded { .. }
                | Event::AskDone { .. } => {}
            }
            s.updated_at = now();
            self.write(&s);
        }
        if let Some(sink) = &self.sink {
            sink.event(&event);
        }
    }
}

/// The target of a tool call, for one line.
#[must_use]
pub fn target(tool: &str, args: &serde_json::Value) -> String {
    let text = match tool {
        "run_command" => args["argv"]
            .as_array()
            .map(|a| {
                a.iter()
                    .filter_map(|v| v.as_str())
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .unwrap_or_default(),
        "search_code" => args["pattern"].as_str().unwrap_or_default().to_owned(),
        "report_blocked" => format!(
            "{}: {}",
            args["kind"].as_str().unwrap_or("?"),
            args["evidence"].as_str().unwrap_or_default()
        ),
        // An MCP tool: its first string argument, whatever it is called.
        name if name.starts_with(crate::mcp::PREFIX) => args
            .as_object()
            .and_then(|o| o.values().find_map(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_default(),
        _ => args["path"].as_str().unwrap_or_default().to_owned(),
    };
    let one: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
    if one.chars().count() > 60 {
        format!("{}…", one.chars().take(59).collect::<String>())
    } else {
        one
    }
}

// ── `speccoder report --live` ──────────────────────────────────────────────────────

/// The project's `live.json` and whether its process is still alive.
#[must_use]
pub fn read_live(path: &Path, state: &Path) -> Option<(LiveState, bool)> {
    let root = match crate::inspect(path, None).data() {
        Some(CommandData::Inspect(s)) => PathBuf::from(&s.root),
        _ => return None,
    };
    let text = std::fs::read_to_string(crate::worktree::project_state_dir(state, &root).join(FILE))
        .ok()?;
    let live: LiveState = serde_json::from_str(&text).ok()?;
    let running = live.finished.is_none() && alive(live.pid);
    Some((live, running))
}

/// Whether process `pid` is alive.
pub fn alive(pid: u32) -> bool {
    i32::try_from(pid)
        .is_ok_and(|p| nix::sys::signal::kill(nix::unistd::Pid::from_raw(p), None).is_ok())
}

/// `speccoder report --live`: the project's current (or last) run, from
/// `live.json`, in the state directory `state`.
pub fn status_with(path: &Path, state: &Path) -> CommandResult {
    status_at(path, state, agentplane::core::Timestamp::now_utc())
}

/// [`status_with`] as it reads at `now`: a call whose deadline passed by
/// then is not listed as waiting.
#[doc(hidden)]
pub fn status_at(path: &Path, state: &Path, now: agentplane::core::Timestamp) -> CommandResult {
    // One inspection for both: what runs, and what waits.
    let inspected = crate::inspect(path, None);
    let root = match inspected.data() {
        Some(CommandData::Inspect(s)) => PathBuf::from(&s.root),
        _ => return CommandResult::carried("report", &inspected),
    };
    let plane_dir = crate::worktree::project_state_dir(state, &root);
    let res = status_inner(&plane_dir);
    let lines = waiting_lines(&plane_dir, now);
    if lines.is_empty() {
        return res;
    }
    let mut next = res.next().to_vec();
    next.insert(
        0,
        speccoder_core::next::NextStep {
            command: "speccoder report --approvals".to_owned(),
            why: "see the waiting calls, then approve or reject them".to_owned(),
        },
    );
    let message = format!("{}\n{}", res.message(), lines.join("\n"));
    let status = res.status();
    res.reworded(status, &message).with_next(next)
}

/// One line per call waiting for a person at `now`: what, since when,
/// until when. A call past its deadline waits no more — the next writer
/// denies it as expired — so it is not listed, as in every other listing.
fn waiting_lines(plane_dir: &Path, now: agentplane::core::Timestamp) -> Vec<String> {
    // Unreadable is said, never shown as nothing waiting. Read beside the
    // journal's writer (a run in another process); no journal, nothing
    // waits — and a read never creates one.
    let unknown = |why: String| vec![format!("waiting for a person: unknown — {why}")];
    let rt = match crate::tokio_runtime() {
        Ok(rt) => rt,
        Err(e) => return unknown(e),
    };
    let plane = match crate::substrate::Plane::open_for_reading(plane_dir) {
        Ok(Some(p)) => p,
        Ok(None) => return Vec::new(),
        Err(e) => return unknown(e.0),
    };
    let open = match rt.block_on(plane.open_tasks()) {
        Ok(open) => open,
        Err(e) => return unknown(e.0),
    };
    open.into_iter()
        .filter(|t| crate::approvals::still_waits(t.due_at, now))
        .filter_map(|t| {
            let request = crate::approvals::tasks::request_of(&t.justification.proposed_action)?;
            let since = (now - t.created_at).whole_minutes().max(0);
            let until = t
                .due_at
                .map(|d| {
                    format!(
                        ", denied as expired in {} h",
                        (d - now).whole_hours().max(0)
                    )
                })
                .unwrap_or_default();
            Some(format!(
                "waiting for a person: {} — {} (for {since} min{until})",
                request.task,
                request.covers()
            ))
        })
        .collect()
}

fn status_inner(plane_dir: &Path) -> CommandResult {
    let plane_dir = plane_dir.to_path_buf();
    // An in-place session: the mode, and for an interrupted one both ways out.
    if let Some(s) = crate::in_place::Session::load(&plane_dir) {
        let mode = s.mode_line();
        if !alive(s.pid) {
            let step = |command: &str, why: &str| speccoder_core::next::NextStep {
                command: command.to_owned(),
                why: why.to_owned(),
            };
            return CommandResult::new(
                "status",
                CommandStatus::Ok,
                &format!(
                    "interrupted in-place run of {} (pid {} is gone): the checkout is still on {}\n{mode}",
                    s.feature, s.pid, s.branch
                ),
            )
            .with_next(vec![
                step("speccoder run --in-place", "resume where it stopped"),
                step(
                    "speccoder run --in-place --return",
                    "save what it left and switch back without running",
                ),
            ]);
        }
        let res = status_live(&plane_dir);
        let message = format!("{}\n{mode}", res.message());
        let status = res.status();
        return res.reworded(status, &message);
    }
    status_live(&plane_dir)
}

/// `status` from `live.json`.
fn status_live(plane_dir: &Path) -> CommandResult {
    let file = plane_dir.join(FILE);
    let live: LiveState = match std::fs::read_to_string(&file)
        .ok()
        .and_then(|t| serde_json::from_str(&t).ok())
    {
        Some(l) => l,
        None => {
            return CommandResult::new(
                "status",
                CommandStatus::Ok,
                "no run has been recorded for this project yet",
            );
        }
    };
    let ago = now().saturating_sub(live.updated_at);
    let tokens = format!(
        "{} in · {} out{}",
        live.input_tokens,
        live.output_tokens,
        live.usd.map(|u| format!(" · ${u:.4}")).unwrap_or_default()
    );
    use speccoder_core::next::{Outcome, next};
    let outcome = match (&live.finished, alive(live.pid)) {
        (None, true) => Some(Outcome::Running),
        (None, false) => Some(Outcome::Interrupted {
            task: live.task.clone(),
        }),
        (Some(_), _) => None,
    };
    let message = match (&live.finished, alive(live.pid)) {
        (None, true) => format!(
            "running (pid {}): {} {} — {} for {}s; last: {}; {tokens}{}{}",
            live.pid,
            live.feature,
            live.task,
            stage_word(&live),
            now().saturating_sub(live.started_at),
            live.last_call.as_deref().unwrap_or("-"),
            live.thinking
                .as_deref()
                .map(|s| format!("\nthe model thinks (a claim): {s}"))
                .unwrap_or_default(),
            live.said
                .as_deref()
                .map(|s| format!("\nthe model says (a claim): “{s}”"))
                .unwrap_or_default(),
        ),
        (None, false) => format!(
            "interrupted: {} {} stopped during {} {ago}s ago (pid {} is gone); the next `speccoder run` resumes it from its journal",
            live.feature,
            live.task,
            stage_word(&live),
            live.pid
        ),
        (Some(outcome), _) => format!(
            "last run: {} {} — {outcome} ({ago}s ago); {tokens}",
            live.feature, live.task
        ),
    };
    CommandResult::new("status", CommandStatus::Ok, &message)
        .with_next(outcome.map(|o| next(&o, None)).unwrap_or_default())
}

/// `verify`, `attempt 1/2`, or `starting`.
#[must_use]
pub fn stage_word(live: &LiveState) -> String {
    match (live.stage, &live.stage_detail) {
        (Some(st), Some(d)) => format!("{} {d}", st.name()),
        (Some(st), None) => st.name().to_owned(),
        (None, _) => "starting".to_owned(),
    }
}

/// The last lines of command output worth showing: at most five non-empty
/// lines, each at most 200 characters, control characters removed.
#[must_use]
pub fn tail(text: &str) -> Vec<String> {
    let lines: Vec<String> = text
        .lines()
        .map(|l| {
            l.chars()
                .filter(|c| !c.is_control())
                .take(200)
                .collect::<String>()
        })
        .filter(|l| !l.trim().is_empty())
        .collect();
    lines[lines.len().saturating_sub(5)..].to_vec()
}

/// [`status_with`] in the default state directory.
#[must_use]
pub fn status(path: &Path) -> CommandResult {
    match crate::worktree::state_dir() {
        Some(state) => status_with(path, &state),
        None => CommandResult::new(
            "status",
            CommandStatus::ConfigError,
            "no state directory (set SPECCODER_STATE_DIR or HOME)",
        )
        .with_code("NO-STATE-DIR"),
    }
}