speccoder-runtime 0.8.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
//! Approvals as agentplane human tasks: every decision names who
//! made it and how that is known, binds to what was shown, waits durably,
//! and expires as nobody's decision.

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

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;

use agentplane::model::ModelProvider;
use agentplane::model::fake::FakeProvider;
use serde_json::{Value, json};
use speccoder_core::{CommandData, CommandResult, CommandStatus, RunReport};
use speccoder_runtime::approvals::{Answer, Approver, Scope, Verb, decide_with};

const CONFIG: &str = "[model]\nprovider = \"openai\"\nmodel = \"gpt-5.4-mini\"\n\n[checks.has-ok]\nargv = [\"grep\", \"-q\", \"fn ok\", \"src/lib.rs\"]\n\n[acceptance]\ngenerate = false\n";

fn git(dir: &Path, args: &[&str]) {
    let ok = Command::new("git")
        .args(["-c", "maintenance.auto=false", "-c", "gc.auto=0"])
        .args([
            "-c",
            "user.name=Dana Example",
            "-c",
            "user.email=d@example.com",
        ])
        .args([
            "-c",
            "commit.gpgsign=false",
            "-c",
            "init.defaultBranch=main",
        ])
        .args(["-c", "core.hooksPath=/dev/null"])
        .args(args)
        .current_dir(dir)
        .status()
        .unwrap()
        .success();
    assert!(ok, "git {args:?}");
}

fn repo(extra: &str) -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    let r = dir.path();
    let fixture =
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../speccoder-speckit/tests/fixtures/graph");
    assert!(
        Command::new("cp")
            .arg("-R")
            .arg(fixture.join("."))
            .arg(r)
            .status()
            .unwrap()
            .success()
    );
    fs::write(
        r.join("specs/001-graph/spec.md"),
        "# Spec\n\n### User Story 1 - Login\n\nUsers log in.\n",
    )
    .unwrap();
    fs::create_dir_all(r.join("src")).unwrap();
    fs::write(r.join("src/lib.rs"), "pub fn ok() {}\n").unwrap();
    fs::write(r.join("speccoder.toml"), format!("{CONFIG}{extra}")).unwrap();
    git(r, &["init", "-q"]);
    // Whoever decides here is named as git names them.
    git(r, &["config", "user.name", "Dana Example"]);
    git(r, &["add", "-A"]);
    git(r, &["commit", "-q", "-m", "init"]);
    dir
}

fn fake() -> (Arc<FakeProvider>, Arc<dyn ModelProvider>) {
    let f = FakeProvider::new();
    let d: Arc<dyn ModelProvider> = f.clone();
    (f, d)
}

fn done() -> Value {
    json!({ "summary": "done", "status": "done", "files_changed": ["package.json"], "checks_run": [], "notes": [] })
}

/// A dependency manifest: a write that needs a person.
fn write_manifest(f: &FakeProvider, id: &str) {
    f.will_call_tool(
        id,
        "write_file",
        json!({ "path": "package.json", "content": "{}\n" }),
    );
}

fn report(r: &CommandResult) -> &RunReport {
    match r.data() {
        Some(CommandData::Run(rep)) => rep,
        other => panic!("{} → {other:?}", r.message()),
    }
}

fn pending(r: &Path, state: &Path) -> Vec<speccoder_core::PendingCall> {
    match speccoder_runtime::approvals::list_with(r, None, state).data() {
        Some(CommandData::Approvals(a)) => a.pending.clone(),
        other => panic!("{other:?}"),
    }
}

/// The project's state directory, where its journal lives.
fn plane_dir(r: &Path, state: &Path) -> PathBuf {
    speccoder_runtime::worktree::project_state_dir(state, &fs::canonicalize(r).unwrap())
}

#[derive(Debug)]
struct Scripted(std::sync::Mutex<Vec<Answer>>);

impl Approver for Scripted {
    fn ask(&self, _: &speccoder_runtime::approvals::Presentation) -> Answer {
        self.0.lock().unwrap().remove(0)
    }
}

fn person(answers: Vec<Answer>) -> Arc<Scripted> {
    Arc::new(Scripted(std::sync::Mutex::new(answers)))
}

#[test]
fn inline_decisions_name_their_operator_and_replay_without_asking() {
    let r = repo("");
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    write_manifest(&f, "c1");
    f.will_call_tool(
        "c2",
        "run_command",
        json!({ "argv": ["curl", "https://example.com"] }),
    );
    f.will_structure(done());
    let res = speccoder_runtime::run_with_approver(
        r.path(),
        None,
        "T005",
        state.path(),
        d,
        None,
        person(vec![
            Answer::approve(Scope::Task, Some("small is fine".to_owned()), None),
            Answer::reject("no network", None),
        ]),
    );
    let rep = report(&res);
    let (write, curl) = (&rep.tool_calls[0], &rep.tool_calls[1]);
    // Who decided, and how that is known: git's name, typed at a terminal.
    assert_eq!(write["approved_by"], "person");
    assert_eq!(
        write["operator"],
        json!({ "actor": "Dana Example", "basis": "asserted" })
    );
    assert_eq!(write["scope"], "task");
    assert_eq!(write["note"], "small is fine");
    assert_eq!(curl["decision"], "deny");
    assert_eq!(curl["rejected_by"], "person");
    assert_eq!(curl["operator"]["actor"], "Dana Example");
    assert_eq!(
        (write["by"].as_str(), curl["by"].as_str()),
        (Some("person"), Some("person"))
    );
    // Strict replay reads both decisions back; nobody is asked.
    let replayed = speccoder_runtime::replay_with(r.path(), &rep.run_id, state.path());
    assert_eq!(
        replayed.status(),
        CommandStatus::Ok,
        "{}",
        replayed.message()
    );
}

#[test]
fn an_approval_of_something_other_than_what_was_shown_is_refused() {
    let r = repo("");
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    write_manifest(&f, "c1");
    let first = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    assert_eq!(
        first.status(),
        CommandStatus::NeedsHuman,
        "{}",
        first.message()
    );
    let waiting = pending(r.path(), state.path());
    assert_eq!(waiting.len(), 1);
    // `status` says what waits, and the way forward.
    let status = speccoder_runtime::progress::status_with(r.path(), state.path());
    assert!(
        status
            .message()
            .contains("waiting for a person: 001-graph/T005 — write `package.json`"),
        "{}",
        status.message()
    );
    assert_eq!(status.next()[0].command, "speccoder report --approvals");
    let id = agentplane::core::TaskId::parse(&waiting[0].call).unwrap();

    // A decision naming a different version of the call.
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();
    let store = Arc::new(
        agentplane::store::RedbStore::open(plane_dir(r.path(), state.path()).join("journal.redb"))
            .unwrap(),
    );
    let plane = agentplane::prelude::Runtime::builder_on(store)
        .try_build()
        .unwrap();
    let other = agentplane::core::Justification::new(
        agentplane::core::Tainted::trusted("something else".to_owned()),
        json!({ "tool": "write_file", "arguments": { "path": "package.json", "content": "evil" } }),
    );
    let refused = rt.block_on(plane.decide_task_at(
        id,
        &agentplane::core::Decision::approve(
            agentplane::core::Operator::asserted("mallory").unwrap(),
            "",
        ),
        &[],
        Some(other.digest()),
    ));
    assert!(refused.is_err(), "a stale approval was accepted");
    drop(plane);
    drop(rt);
    // The call still waits; nothing was written.
    assert_eq!(pending(r.path(), state.path()).len(), 1);
    assert!(!r.path().join("package.json").exists());
}

#[test]
fn a_waiting_call_past_its_deadline_is_denied_as_nobodys_decision() {
    let r = repo("\n[approvals]\nwait = \"1m\"\n");
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    write_manifest(&f, "c1");
    let first = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    assert_eq!(
        first.status(),
        CommandStatus::NeedsHuman,
        "{}",
        first.message()
    );
    let waiting = pending(r.path(), state.path());
    assert_eq!(waiting.len(), 1);
    let deadline = waiting[0].deadline.unwrap();
    let since = waiting[0].waiting_since.unwrap();
    assert!(
        (50..=120).contains(&(deadline - since)),
        "{since} → {deadline}"
    );

    // Two minutes later: the deadline has passed. Every listing — status
    // too — leaves the call out before anything denies it.
    let later = agentplane::core::Timestamp::now_utc() + std::time::Duration::from_secs(120);
    let now = speccoder_runtime::progress::status_with(r.path(), state.path());
    assert!(
        now.message().contains("denied as expired in"),
        "{}",
        now.message()
    );
    let then = speccoder_runtime::progress::status_at(r.path(), state.path(), later);
    assert!(
        !then.message().contains("denied as expired in"),
        "{}",
        then.message()
    );
    speccoder_runtime::approvals::expire_due(&plane_dir(r.path(), state.path()), later).unwrap();

    // The attempt continues with the call refused, and nobody is named.
    let (f2, d2) = fake();
    f2.will_structure(done());
    let res = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d2, None);
    let rep = report(&res);
    let call = &rep.tool_calls[0];
    assert_eq!(call["decision"], "deny", "{:?}", rep.tool_calls);
    assert_eq!(call["expired"], true);
    assert_eq!(call["by"], "expiry");
    assert!(call.get("operator").is_none_or(Value::is_null));
    assert!(
        call["reason"]
            .as_str()
            .unwrap()
            .contains("not approved before its deadline"),
        "{call}"
    );
    assert!(pending(r.path(), state.path()).is_empty());
}

#[test]
fn a_waiting_task_holds_the_worktree_until_it_is_decided() {
    let r = repo("");
    // Two tasks that could run now.
    fs::write(
        r.path().join("specs/001-graph/tasks.md"),
        "# Tasks\n\n## Phase 1: Setup\n\n- [ ] T005 [P] Add the manifest\n- [ ] T006 [P] Add another manifest\n",
    )
    .unwrap();
    git(r.path(), &["commit", "-qam", "two tasks"]);
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    write_manifest(&f, "c1");
    let first = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    assert_eq!(
        first.status(),
        CommandStatus::NeedsHuman,
        "{}",
        first.message()
    );

    // T005's attempt holds the worktree: T006 does not start beside it.
    let (_f, d) = fake();
    let other = speccoder_runtime::run_with(r.path(), None, "T006", state.path(), d, None);
    assert_eq!(
        other.status(),
        CommandStatus::NeedsHuman,
        "{}",
        other.message()
    );
    assert!(
        other.message().contains("T005 waits for a person"),
        "{}",
        other.message()
    );

    // `--all` decides every waiting call, each on its own record.
    let all = decide_with(
        r.path(),
        None,
        Verb::Decide(speccoder_runtime::approvals::Choice {
            task: None,
            call: None,
            all: true,
            approve: true,
            scope: Scope::Once,
            note: None,
            reason: None,
            digest: None,
        }),
        state.path(),
        speccoder_core::actions::Via::Terminal,
    );
    assert_eq!(all.status(), CommandStatus::Ok, "{}", all.message());
    assert_eq!(
        all.message().matches("approved:").count(),
        1,
        "{}",
        all.message()
    );
    // A call id that waits nowhere is not found.
    let none = decide_with(
        r.path(),
        None,
        Verb::Decide(speccoder_runtime::approvals::Choice {
            task: None,
            call: Some("ffff"),
            all: false,
            approve: true,
            scope: Scope::Once,
            note: None,
            reason: None,
            digest: None,
        }),
        state.path(),
        speccoder_core::actions::Via::Terminal,
    );
    assert_eq!(none.status(), CommandStatus::NotFound, "{}", none.message());

    // T005 resumes and finishes; then T006 runs.
    let (f, d) = fake();
    f.will_structure(done());
    let resumed = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    assert_eq!(resumed.status(), CommandStatus::Ok, "{}", resumed.message());
    assert_eq!(report(&resumed).tool_calls[0]["scope"], "once");
    assert_eq!(f.asked().len(), 1, "a finished call was repeated");
    let (f, d) = fake();
    f.will_structure(done());
    let next = speccoder_runtime::run_with(r.path(), None, "T006", state.path(), d, None);
    assert_eq!(next.status(), CommandStatus::Ok, "{}", next.message());
}

#[test]
fn calls_decided_without_a_person_name_the_rule() {
    let r = repo("\n[commands]\nallow = [[\"grep\", \"-q\", \"ok\", \"src/lib.rs\"]]\n");
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    f.will_call_tool("c1", "read_file", json!({ "path": "src/lib.rs" }));
    f.will_call_tool(
        "c2",
        "run_command",
        json!({ "argv": ["grep", "-q", "ok", "src/lib.rs"] }),
    );
    f.will_call_tool(
        "c3",
        "write_file",
        json!({ "path": ".specify/memory/constitution.md", "content": "x" }),
    );
    f.will_structure(done());
    let res = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    let calls = &report(&res).tool_calls;
    let rules: Vec<(&str, &str)> = calls
        .iter()
        .map(|c| {
            (
                c["by"].as_str().unwrap_or("-"),
                c["rule"].as_str().unwrap_or("-"),
            )
        })
        .collect();
    assert_eq!(rules[0], ("rule", "workspace read"), "{calls:?}");
    assert_eq!(
        rules[1],
        ("rule", "exact command `grep -q ok src/lib.rs`"),
        "{calls:?}"
    );
    assert_eq!(rules[2].0, "rule", "{calls:?}");
    // No call a rule decided is recorded as a person's.
    assert!(calls.iter().all(|c| c["by"] != "person"));
}

#[test]
fn a_resumed_attempt_that_fails_is_undone_to_where_the_task_started() {
    // Found by dogfooding: the undo went to the tree the resumed run found,
    // which already held the attempt's own writes.
    let r = repo("\n[checks.no-manifest]\nargv = [\"sh\", \"-c\", \"test ! -e package.json\"]\n");
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    write_manifest(&f, "c1");
    let first = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    assert_eq!(
        first.status(),
        CommandStatus::NeedsHuman,
        "{}",
        first.message()
    );
    let ok = decide_with(
        r.path(),
        None,
        Verb::Approve("T005"),
        state.path(),
        speccoder_core::actions::Via::Terminal,
    );
    assert_eq!(ok.status(), CommandStatus::Ok, "{}", ok.message());

    let (f, d) = fake();
    f.will_structure(done());
    let res = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    let rep = report(&res);
    assert!(
        !rep.ticked && rep.saved_attempt.is_some(),
        "{}",
        res.message()
    );
    let wt = Path::new(&rep.worktree);
    assert!(
        !wt.join("package.json").exists(),
        "the failed attempt's write is still there"
    );
    let status = Command::new("git")
        .args(["-c", "maintenance.auto=false", "-c", "gc.auto=0"])
        .args(["status", "--porcelain"])
        .current_dir(wt)
        .output()
        .unwrap();
    assert!(
        status.stdout.is_empty(),
        "{}",
        String::from_utf8_lossy(&status.stdout)
    );
}

#[test]
fn calls_waiting_in_a_journal_another_process_holds_are_unknown_never_none() {
    let r = repo("");
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    write_manifest(&f, "c1");
    let first = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    assert_eq!(
        first.status(),
        CommandStatus::NeedsHuman,
        "{}",
        first.message()
    );
    assert_eq!(pending(r.path(), state.path()).len(), 1);

    // A writer that holds the journal alone (as speccoder 0.2.0 did): it
    // cannot be read beside.
    let held =
        agentplane::store::RedbStore::open(plane_dir(r.path(), state.path()).join("journal.redb"))
            .unwrap();
    let listed = speccoder_runtime::approvals::list_with(r.path(), None, state.path());
    let Some(CommandData::Approvals(a)) = listed.data() else {
        panic!("{listed:?}");
    };
    assert!(a.pending.is_empty());
    assert!(
        a.unreadable.is_some(),
        "an unreadable journal was reported as nothing waiting"
    );
    assert!(listed.message().contains("unknown"), "{}", listed.message());
    let inbox = speccoder_runtime::inbox::inbox_with(r.path(), None, Some(state.path()));
    let Some(CommandData::Inbox(i)) = inbox.data() else {
        panic!("{inbox:?}");
    };
    assert_eq!(
        i.items.first().map(|i| i.kind.as_str()),
        Some("unknown"),
        "{:?}",
        i.items
    );
    // A decision cannot be made blind.
    let approve = decide_with(
        r.path(),
        None,
        Verb::Approve("T005"),
        state.path(),
        speccoder_core::actions::Via::Terminal,
    );
    assert_eq!(
        approve.status(),
        CommandStatus::Error,
        "{}",
        approve.message()
    );

    drop(held);
    assert_eq!(pending(r.path(), state.path()).len(), 1);
}

/// A decisions file that cannot be read (an earlier shape, a torn write)
/// leaves a lane's stopped calls unknown, never none: the listing and the
/// inbox say so, and nothing is decided against it.
#[test]
fn decisions_that_cannot_be_read_are_unknown_never_none() {
    let r = repo("");
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    write_manifest(&f, "c1");
    let first = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    assert_eq!(
        first.status(),
        CommandStatus::NeedsHuman,
        "{}",
        first.message()
    );
    std::fs::write(
        plane_dir(r.path(), state.path()).join(speccoder_runtime::approvals::FILE),
        "{\"tasks\": {\"001-graph/T005\": {\"grants\": [\"write\"]}}}",
    )
    .unwrap();
    let listed = speccoder_runtime::approvals::list_with(r.path(), None, state.path());
    let Some(CommandData::Approvals(a)) = listed.data() else {
        panic!("{listed:?}");
    };
    let why = a.unreadable.as_deref().unwrap_or_default();
    assert!(why.contains(speccoder_runtime::approvals::FILE), "{why}");
    let inbox = speccoder_runtime::inbox::inbox_with(r.path(), None, Some(state.path()));
    let Some(CommandData::Inbox(i)) = inbox.data() else {
        panic!("{inbox:?}");
    };
    assert!(i.items.iter().any(|i| i.kind == "unknown"), "{:?}", i.items);
    let approve = decide_with(
        r.path(),
        None,
        Verb::Approve("T005"),
        state.path(),
        speccoder_core::actions::Via::Terminal,
    );
    assert_eq!(
        approve.status(),
        CommandStatus::ConfigError,
        "{}",
        approve.message()
    );
}

// ── a journal another process writes ────────────────────────────────

const WRITER: &str = "SPECCODER_TEST_JOURNAL_WRITER";

/// Wait for a marker file the other process writes.
fn until(path: &Path) {
    for _ in 0..600 {
        if path.exists() {
            return;
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    panic!("{} never appeared", path.display());
}

/// The writer half of `a_run_in_another_process_leaves_the_journal_readable`,
/// run in a child process: opens the project's journal to write, as a run
/// or a decision does, and holds it until told.
#[test]
#[ignore = "the writer half of a_run_in_another_process_leaves_the_journal_readable, run in a child process"]
fn the_other_process_writer() {
    let Ok(dir) = std::env::var(WRITER).map(PathBuf::from) else {
        return;
    };
    let plane_dir = PathBuf::from(fs::read_to_string(dir.join("plane")).unwrap());
    let plane = speccoder_runtime::substrate::Plane::open_for_decisions(&plane_dir)
        .unwrap_or_else(|e| panic!("{}", e.0));
    fs::write(dir.join("ready"), "").unwrap();
    until(&dir.join("done"));
    drop(plane);
}

/// **Another process writes the journal; this one reads it.** The waiting
/// call is listed (not `unknown`) in the approvals, the inbox and status,
/// the run's account reads, all without waiting for the writer — and a
/// second writer (a decision, a run) is refused at once, the file untouched.
#[test]
fn a_run_in_another_process_leaves_the_journal_readable() {
    let r = repo("");
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    f.will_answer(agentplane::model::Completion {
        tool_calls: vec![agentplane::model::ToolCall {
            id: "c1".to_owned(),
            name: "write_file".to_owned(),
            arguments: json!({ "path": "package.json", "content": "{}\n" }),
        }],
        text: "I'll add the manifest.".to_owned(),
        stop_reason: Some("tool_use".to_owned()),
        ..agentplane::model::Completion::default()
    });
    let first = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    assert_eq!(
        first.status(),
        CommandStatus::NeedsHuman,
        "{}",
        first.message()
    );
    let run_id = report(&first).run_id.clone();
    let journal = plane_dir(r.path(), state.path());

    let markers = tempfile::tempdir().unwrap();
    fs::write(
        markers.path().join("plane"),
        journal.to_string_lossy().as_bytes(),
    )
    .unwrap();
    let mut child = Command::new(std::env::current_exe().unwrap())
        .args([
            "the_other_process_writer",
            "--exact",
            "--ignored",
            "--nocapture",
        ])
        .env(WRITER, markers.path())
        .spawn()
        .unwrap();
    until(&markers.path().join("ready"));
    let before = fs::read(journal.join(speccoder_runtime::substrate::JOURNAL)).unwrap();

    // A reader that waited for the writer would wait until it is told to
    // let go (after these checks, or 30 s): 10 s tells the two apart
    // however loaded the machine is.
    let timed = |what: &str, started: std::time::Instant| {
        assert!(
            started.elapsed() < std::time::Duration::from_secs(10),
            "{what} waited {:?} for the other process",
            started.elapsed()
        );
    };
    // The approvals list the waiting call itself.
    let started = std::time::Instant::now();
    let listed = speccoder_runtime::approvals::list_with(r.path(), None, state.path());
    timed("the listing", started);
    let Some(CommandData::Approvals(a)) = listed.data() else {
        panic!("{listed:?}");
    };
    assert_eq!(a.pending.len(), 1, "{}", listed.message());
    assert!(a.unreadable.is_none(), "{:?}", a.unreadable);
    // So does the inbox.
    let started = std::time::Instant::now();
    let inbox = speccoder_runtime::inbox::inbox_with(r.path(), None, Some(state.path()));
    timed("the inbox", started);
    let Some(CommandData::Inbox(i)) = inbox.data() else {
        panic!("{inbox:?}");
    };
    assert!(
        i.items.iter().all(|i| i.kind != "unknown") && !i.items.is_empty(),
        "{:?}",
        i.items
    );
    // So does status.
    let started = std::time::Instant::now();
    let status = speccoder_runtime::progress::status_with(r.path(), state.path());
    timed("status", started);
    assert!(
        status
            .message()
            .contains("waiting for a person: 001-graph/T005"),
        "{}",
        status.message()
    );
    assert!(
        !status.message().contains("unknown"),
        "{}",
        status.message()
    );
    // The model's account of the run.
    let started = std::time::Instant::now();
    let account = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(speccoder_runtime::substrate::account(&journal, &run_id))
        .unwrap_or_else(|e| panic!("{}", e.0));
    timed("the account", started);
    assert_eq!(
        account.first().and_then(|t| t.said.as_deref()),
        Some("I'll add the manifest."),
        "{account:?}"
    );

    // A second writer is refused at once: a decision…
    let started = std::time::Instant::now();
    let approve = decide_with(
        r.path(),
        None,
        Verb::Approve("T005"),
        state.path(),
        speccoder_core::actions::Via::Terminal,
    );
    assert!(started.elapsed() < std::time::Duration::from_millis(500));
    assert_ne!(approve.status(), CommandStatus::Ok, "{}", approve.message());
    assert!(
        approve.message().contains("another speccoder"),
        "{}",
        approve.message()
    );
    // …and a run.
    let (_, d2) = fake();
    let second = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d2, None);
    assert_ne!(second.status(), CommandStatus::Ok, "{}", second.message());
    assert!(
        second.message().contains("another speccoder"),
        "{}",
        second.message()
    );
    assert_eq!(
        fs::read(journal.join(speccoder_runtime::substrate::JOURNAL)).unwrap(),
        before,
        "a refused writer or a reader touched the journal"
    );

    fs::write(markers.path().join("done"), "").unwrap();
    assert!(child.wait().unwrap().success(), "the writer process failed");
    // Once it is gone, the call is decided as ever.
    assert_eq!(pending(r.path(), state.path()).len(), 1);
}

/// A waiting call shows what the model said when it asked: its
/// commentary, where the provider marks it apart from the answer.
#[test]
fn a_waiting_call_shows_the_model_s_commentary() {
    let r = repo("");
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    f.will_answer(agentplane::model::Completion {
        tool_calls: vec![agentplane::model::ToolCall {
            id: "c1".to_owned(),
            name: "write_file".to_owned(),
            arguments: json!({ "path": "package.json", "content": "{}\n" }),
        }],
        text: String::new(),
        stop_reason: None,
        commentary: Some("The manifest comes first.".to_owned()),
        ..agentplane::model::Completion::default()
    });
    let first = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    assert_eq!(
        first.status(),
        CommandStatus::NeedsHuman,
        "{}",
        first.message()
    );
    let waiting = pending(r.path(), state.path());
    assert_eq!(
        waiting[0]
            .presentation
            .as_ref()
            .and_then(|p| p.claim.as_deref()),
        Some("The manifest comes first."),
        "{waiting:?}"
    );
}

// ── a journal whose writer was killed ───────────────────────────────

const KILLED: &str = "SPECCODER_TEST_KILLED_WRITER";

/// The writer half of `a_killed_writer_blocks_neither_a_run_s_gate_nor_a_decision`,
/// run in a child process: opens the journal to write as a decision does,
/// commits a sweep, and waits to be killed without closing it.
#[test]
#[ignore = "the writer half of a_killed_writer_blocks_neither_a_run_s_gate_nor_a_decision, run in a child process"]
fn the_killed_writer() {
    let Ok(dir) = std::env::var(KILLED).map(PathBuf::from) else {
        return;
    };
    let plane_dir = PathBuf::from(fs::read_to_string(dir.join("plane")).unwrap());
    let plane = speccoder_runtime::substrate::Plane::open_for_decisions(&plane_dir)
        .unwrap_or_else(|e| panic!("{}", e.0));
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(plane.expire_due(agentplane::core::Timestamp::now_utc()))
        .unwrap_or_else(|e| panic!("{}", e.0));
    fs::write(dir.join("ready"), "").unwrap();
    loop {
        std::thread::sleep(std::time::Duration::from_secs(1));
    }
}

/// Opens the journal in a child process and kills it (SIGKILL) while it
/// writes: the journal is left needing the repair only a writer makes.
fn kill_a_writer(journal: &Path) {
    let markers = tempfile::tempdir().unwrap();
    fs::write(
        markers.path().join("plane"),
        journal.to_string_lossy().as_bytes(),
    )
    .unwrap();
    let mut child = Command::new(std::env::current_exe().unwrap())
        .args(["the_killed_writer", "--exact", "--ignored", "--nocapture"])
        .env(KILLED, markers.path())
        .spawn()
        .unwrap();
    until(&markers.path().join("ready"));
    child.kill().unwrap();
    assert!(!child.wait().unwrap().success());
    // A reader cannot open it now: the repair is a writer's.
    assert!(
        speccoder_runtime::substrate::open_reader(journal)
            .err()
            .is_some_and(|e| e.0.contains("ended without closing")),
        "the killed writer left the journal readable"
    );
}

/// **A run killed while it writes the journal** leaves it needing a
/// repair a reader cannot make. The listings say exactly that — never
/// that nothing waits; the next run's gate reads through its own writer,
/// which repairs, so the call that waits still holds the worktree; and a
/// person's decision goes through, never blocked by the killed run.
#[test]
fn a_killed_writer_blocks_neither_a_run_s_gate_nor_a_decision() {
    let r = repo("");
    fs::write(
        r.path().join("specs/001-graph/tasks.md"),
        "# Tasks\n\n## Phase 1: Setup\n\n- [ ] T005 [P] Add the manifest\n- [ ] T006 [P] Add another manifest\n",
    )
    .unwrap();
    git(r.path(), &["commit", "-qam", "two tasks"]);
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    write_manifest(&f, "c1");
    let first = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    assert_eq!(
        first.status(),
        CommandStatus::NeedsHuman,
        "{}",
        first.message()
    );
    let journal = plane_dir(r.path(), state.path());

    // Listings read only: they say why they cannot, precisely.
    kill_a_writer(&journal);
    let listed = speccoder_runtime::approvals::list_with(r.path(), None, state.path());
    let Some(CommandData::Approvals(a)) = listed.data() else {
        panic!("{listed:?}");
    };
    assert!(
        a.unreadable.as_deref().is_some_and(|u| u
            .contains("the last run ended without closing its journal")
            && u.contains("the next run or decision repairs it")),
        "{:?}",
        a.unreadable
    );
    let status = speccoder_runtime::progress::status_with(r.path(), state.path());
    assert!(
        status
            .message()
            .contains("waiting for a person: unknown — the last run ended without closing"),
        "{}",
        status.message()
    );

    // The gate of another task's run fails closed: T005 still holds the
    // worktree, and T006 does not start beside it.
    let (_f, d) = fake();
    let other = speccoder_runtime::run_with(r.path(), None, "T006", state.path(), d, None);
    assert_eq!(
        other.status(),
        CommandStatus::NeedsHuman,
        "{}",
        other.message()
    );
    assert!(
        other.message().contains("T005 waits for a person"),
        "{}",
        other.message()
    );

    // A decision repairs it too, and is recorded.
    kill_a_writer(&journal);
    let approve = decide_with(
        r.path(),
        None,
        Verb::Approve("T005"),
        state.path(),
        speccoder_core::actions::Via::Terminal,
    );
    assert_eq!(approve.status(), CommandStatus::Ok, "{}", approve.message());
    assert!(pending(r.path(), state.path()).is_empty());
}

// ── a decision speccoder 0.2.0 recorded ─────────────────────────────

/// Records an approval of the waiting call `call` in the journal at
/// `journal` as speccoder 0.2.0 (agentplane 0.53) did: the decision as a
/// worklist event with `approved: true`, the shape 0.54 replaced by a
/// verdict, and the task completed.
fn approve_as_0_2_0(journal: &Path, call: &str) {
    use agentplane::case::{EventStore as _, TaskStore as _};
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();
    let store = agentplane::store::RedbStore::open_shared(journal.join("journal.redb")).unwrap();
    let id = agentplane::core::TaskId::parse(call).unwrap();
    let row = rt.block_on(store.task(id)).unwrap().unwrap();
    let by = agentplane::core::Operator::from_parts("Dana Example", "asserted").unwrap();
    let mut decision = agentplane::core::Decision::approve(by.clone(), "");
    decision.reviewed = Some(row.justification.digest());
    let mut old = serde_json::to_value(&decision).unwrap();
    let fields = old.as_object_mut().unwrap();
    fields.remove("verdict");
    fields.insert("approved".to_owned(), json!(true));
    let event = agentplane::core::InboundEvent::new(
        "agentplane://worklist",
        format!("task-decision:{call}"),
        "agentplane.task.decided",
        old,
    )
    .correlate(agentplane::core::CorrelationKey::new("task", call))
    .minted_by(by);
    assert!(
        rt.block_on(store.buffer(&event, agentplane::core::Timestamp::now_utc()))
            .unwrap()
    );
    rt.block_on(store.set_state(id, agentplane::core::TaskState::Completed))
        .unwrap();
}

/// **A decision speccoder 0.2.0 recorded** does not read in this build
/// (agentplane 0.54 made a decision a verdict). The attempt that waited on
/// it is named as such, with the fix — and the fix works: the next run
/// starts the task afresh instead of failing on the same record again.
#[test]
fn a_decision_recorded_by_0_2_0_is_named_and_the_task_runs_again() {
    let r = repo("");
    let state = tempfile::tempdir().unwrap();
    let (f, d) = fake();
    write_manifest(&f, "c1");
    let first = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d, None);
    assert_eq!(
        first.status(),
        CommandStatus::NeedsHuman,
        "{}",
        first.message()
    );
    let waiting = pending(r.path(), state.path());
    approve_as_0_2_0(&plane_dir(r.path(), state.path()), &waiting[0].call);

    let (f2, d2) = fake();
    f2.will_structure(done());
    let second = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d2, None);
    assert_eq!(
        second.status(),
        CommandStatus::RunFailed,
        "{}",
        second.message()
    );
    assert!(
        second
            .message()
            .contains("a decision recorded by speccoder 0.2.0")
            && second.message().contains("run the task again"),
        "{}",
        second.message()
    );
    // Its replay names it too, never as a divergence.
    let replayed = speccoder_runtime::replay_with(r.path(), &report(&second).run_id, state.path());
    assert!(
        replayed.message().contains("recorded by speccoder 0.2.0"),
        "{}",
        replayed.message()
    );
    // The fix works: the next run starts the attempt afresh, and asks again.
    let (f3, d3) = fake();
    write_manifest(&f3, "c1");
    let third = speccoder_runtime::run_with(r.path(), None, "T005", state.path(), d3, None);
    assert_eq!(
        third.status(),
        CommandStatus::NeedsHuman,
        "{}",
        third.message()
    );
    assert_eq!(pending(r.path(), state.path()).len(), 1);
}