moor 0.9.4

Build software with an AI agent inside a locked-down container
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
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
//! One conversational turn with the agent inside a project's sandbox.
//!
//! `moor shell` puts an operator in front of the agent but leaves the
//! whole exchange outside the audit chain (its single entry's redacted
//! argv is the literal string "shell"). `moor recipe` is chained but has
//! no conversational step at all — the recipe is written blind. This
//! module is the middle: a request/response turn that is chained before
//! the operator ever sees the answer, resumable across turns, and
//! tool-bounded by role. See docs/decisions/0008-agent-session-protocol.md.

use crate::{audit, manifest::Agent, manifest::Manifest, paths, proc};
use anyhow::{Context, Result};
use serde::Deserialize;
use serde_json::json;
use sha2::{Digest, Sha256};
use std::path::Path;

/// Where the MCP config lands in the image (images/base/Dockerfile).
const MCP_CONFIG: &str = "/etc/moor/mcp-config.json";

/// What a turn may do, as an actual tool-access boundary rather than a
/// prompt-worded request for restraint — the same distinction
/// `recipe::author_spec` already relies on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
    /// Think a change through against the real repository. Read-only.
    Brainstorm,
    /// Make the change and check it, through the MCP server's
    /// verification verbs. Deliberately no `Bash`: a shell would hand
    /// back `keel approve`, which is the one thing the MCP surface exists
    /// to keep out of the agent's world.
    Build,
}

impl Role {
    pub fn parse(s: &str) -> Result<Role> {
        match s {
            "brainstorm" => Ok(Role::Brainstorm),
            "build" => Ok(Role::Build),
            other => anyhow::bail!("unknown role '{other}': expected 'brainstorm' or 'build'"),
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Role::Brainstorm => "brainstorm",
            Role::Build => "build",
        }
    }

    /// The exact `--allowedTools` set for this role.
    ///
    /// On its own this grants *auto-approval*, not exclusivity — see
    /// `denied_tools`, and ADR-0008's correction. A tool absent from here
    /// is not thereby unavailable.
    pub fn tools(&self) -> &'static [&'static str] {
        match self {
            Role::Brainstorm => &["Read", "Glob", "Grep"],
            Role::Build => &[
                "Read",
                "Glob",
                "Grep",
                "Edit",
                "Write",
                "mcp__moor-keel__keel_gate",
                "mcp__moor-keel__keel_next",
            ],
        }
    }

    /// The `--disallowedTools` set — the part that is actually a boundary.
    ///
    /// Measured against a live sandbox, not assumed: with `--allowedTools
    /// Read Glob Grep` and nothing else, Claude Code ran `Bash` anyway and
    /// returned its output, `permission_denials: []`. `--allowedTools` is
    /// an auto-approval list; under `--print` there is nobody to ask about
    /// anything else, and every permission mode (`auto`, `manual`,
    /// `dontAsk`, `plan`) let it through. `--disallowedTools` denied it —
    /// the agent then reported having no shell tool at all.
    ///
    /// So this list is load-bearing, and it is a list, which is the kind of
    /// control ADR-0003 wanted to avoid. That is a property of Claude
    /// Code's permission model rather than a choice moor gets to make: the
    /// MCP server still keeps `keel approve` off the tool surface, but only
    /// this keeps it from being reachable through a shell. Over-denying is
    /// the safe direction — naming a tool that does not exist costs
    /// nothing, missing one that does costs the checkpoint.
    pub fn denied_tools(&self) -> Vec<&'static str> {
        let mut denied: Vec<&'static str> = SHELL_AND_SUBAGENT.to_vec();
        denied.extend_from_slice(NETWORK);
        if *self == Role::Brainstorm {
            denied.extend_from_slice(MUTATING);
        }
        denied
    }
}

/// Tools that reach a shell, spawn a subagent, or run a slash command —
/// any one of which hands back everything the tool list was supposed to
/// withhold. `Bash` is the decisive one: with it, the agent can run `keel
/// approve` directly and the MCP server's whole reason for existing is
/// moot. `Task` is here because a subagent's tool set is not this one's.
const SHELL_AND_SUBAGENT: &[&str] = &[
    "Bash",
    "BashOutput",
    "KillShell",
    "KillBash",
    "Task",
    "SlashCommand",
];

/// Tools that change the workspace.
const MUTATING: &[&str] = &["Write", "Edit", "MultiEdit", "NotebookEdit"];

/// Tools that fetch from the network. The egress proxy default-denies
/// anyway, but a turn has no business reaching past it.
const NETWORK: &[&str] = &["WebFetch", "WebSearch"];

/// `--disallowedTools` plus every route to a shell or a subagent, ready to
/// append to any `claude` argv. Shared with `commands::recipe`, whose
/// agent steps make the same assumption this corrects: that granting one
/// tool withholds the others. It does not.
pub fn deny_shell_argv() -> Vec<String> {
    let mut argv = vec!["--disallowedTools".to_string()];
    argv.extend(SHELL_AND_SUBAGENT.iter().map(|t| t.to_string()));
    argv
}

/// How an agent's output is shaped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputShape {
    /// A JSON envelope with `is_error`/`result`/`session_id` (claude).
    Json,
    /// The response on stdout, with no envelope (copilot, kiro).
    PlainText,
}

/// Everything that differs between the agents moor can hold a turn with.
/// One table, so the behaviours below are pure functions of it and no
/// agent-specific literal survives anywhere else.
#[derive(Debug, Clone)]
pub struct AgentProfile {
    /// The command and the flags that put it in non-interactive mode.
    pub argv_prefix: &'static [&'static str],
    /// The flag that *auto-approves* a tool set. Not a restriction — see
    /// `Role::denied_tools` and ADR-0008.
    pub allow_flag: Option<&'static str>,
    /// The flag that actually *denies* tools. `None` means this agent has
    /// no denial mechanism, so a restricted role cannot be run on it.
    pub deny_flag: Option<&'static str>,
    /// The flag that resumes a prior session, if the agent has one.
    pub resume_flag: Option<&'static str>,
    pub output: OutputShape,
    /// What to tell the operator when a turn fails for want of a
    /// credential.
    pub auth_hint: &'static str,
}

/// The profile for an agent. Verified against each CLI's own `--help`:
/// claude has `--allowedTools`/`--disallowedTools`; copilot has
/// `--allow-tool`/`--deny-tool`; kiro has only `--trust-tools` (trust
/// *these*), whose semantics are the auto-approval that ADR-0008 showed
/// does not restrain — so kiro's `deny_flag` is deliberately `None`.
pub fn profile(agent: Agent) -> AgentProfile {
    match agent {
        Agent::Claude => AgentProfile {
            argv_prefix: &["claude", "--print", "--output-format", "json"],
            allow_flag: Some("--allowedTools"),
            deny_flag: Some("--disallowedTools"),
            resume_flag: Some("--resume"),
            output: OutputShape::Json,
            auth_hint: "this sandbox has no Claude Code credential — store one with `moor secrets set <project> CLAUDE_CODE_OAUTH_TOKEN` (from `claude setup-token` on the host), then `moor up <project>`.",
        },
        Agent::Copilot => AgentProfile {
            argv_prefix: &["copilot", "-p"],
            allow_flag: Some("--allow-tool"),
            deny_flag: Some("--deny-tool"),
            resume_flag: Some("--resume"),
            output: OutputShape::PlainText,
            auth_hint: "this sandbox has no usable Copilot credential — run `copilot /login` on the host (device flow; a personal access token will not work), then `moor up <project>`.",
        },
        Agent::Kiro => AgentProfile {
            argv_prefix: &["kiro-cli", "chat", "--no-interactive"],
            allow_flag: Some("--trust-tools"),
            // No denial mechanism: `--trust-tools` is an auto-approval
            // list, not a restriction.
            deny_flag: None,
            resume_flag: None,
            output: OutputShape::PlainText,
            auth_hint: "this sandbox has no Kiro credential — run `kiro-cli login` on the host, then `moor up <project>`.",
        },
    }
}

/// The fields of `claude --print --output-format json` this depends on,
/// verified directly against the image's Claude Code 2.1.270 rather than
/// assumed. `subtype` is deliberately absent: a failed turn there returned
/// `"is_error": true` alongside `"subtype": "success"`, so reading
/// `subtype` as a success signal would record that turn as a success.
#[derive(Debug, Default, Deserialize)]
pub struct TurnResult {
    #[serde(default)]
    pub is_error: bool,
    #[serde(default)]
    pub result: String,
    #[serde(default)]
    pub session_id: Option<String>,
    #[serde(default)]
    pub num_turns: Option<u64>,
    #[serde(default)]
    pub permission_denials: Vec<serde_json::Value>,
}

/// Read a turn's result in the selected agent's own output shape. A
/// plain-text agent emits the response and nothing else, so its stdout
/// *is* the result — parsing it as JSON would fail a perfectly good turn.
pub fn parse_turn(agent: Agent, stdout: &str) -> Result<TurnResult> {
    match profile(agent).output {
        OutputShape::Json => serde_json::from_str(stdout.trim())
            .with_context(|| format!("parsing `--output-format json` output:\n{stdout}")),
        OutputShape::PlainText => Ok(TurnResult {
            is_error: false,
            result: stdout.trim().to_string(),
            ..Default::default()
        }),
    }
}

/// A turn failed if it says so, whatever the process exit status said.
pub fn turn_failed(t: &TurnResult, exit_ok: bool) -> bool {
    t.is_error || !exit_ok
}

/// A session id is only usable if it looks like the UUID Claude Code
/// actually returns — 8-4-4-4-12 lowercase hex. Anything else is either a
/// different shape of output or something that came from the wrong place,
/// and in both cases resuming from it is worse than starting fresh.
pub fn valid_session_id(id: &str) -> bool {
    let groups = [8usize, 4, 4, 4, 12];
    let parts: Vec<&str> = id.split('-').collect();
    parts.len() == groups.len()
        && parts
            .iter()
            .zip(groups)
            .all(|(p, n)| p.len() == n && p.chars().all(|c| c.is_ascii_hexdigit()))
}

/// The id to carry into the next turn — taken from the parsed
/// `session_id` field and nowhere else. Text the agent produced is never
/// consulted, so a response that prints a plausible UUID cannot redirect
/// the next turn at another session.
pub fn next_session_id(t: &TurnResult) -> Option<String> {
    t.session_id
        .as_deref()
        .filter(|id| valid_session_id(id))
        .map(str::to_string)
}

fn store_session_id(path: &Path, id: &str) -> Result<()> {
    if !valid_session_id(id) {
        anyhow::bail!("refusing to store malformed session id '{id}'");
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, id).with_context(|| format!("writing {}", path.display()))
}

fn read_session_id(path: &Path) -> Option<String> {
    let raw = std::fs::read_to_string(path).ok()?;
    let id = raw.trim();
    // Re-validated on the way out as well as in: a hand-edited file is
    // the same problem as a malformed response.
    valid_session_id(id).then(|| id.to_string())
}

fn sha256_hex(text: &str) -> String {
    let mut h = Sha256::new();
    h.update(text.as_bytes());
    hex::encode(h.finalize())
}

/// Append this turn's `agent-turn` entry to the project's existing chain.
/// Hashes of the prompt and response, never the text — the chain is
/// tamper-evidence over *what happened*, and it is exported by `moor
/// audit --export`, so putting conversation content in it would leak
/// through every bundle. The full text goes to the redacted transcript
/// instead (`write_transcript`).
fn append_turn_to(path: &Path, turn: &ChainedTurn) -> Result<audit::ChainEntry> {
    audit::append_chained(
        path,
        "agent-turn",
        json!({
            "project": turn.project,
            "agent": format!("{:?}", turn.agent).to_lowercase(),
            "role": turn.role.as_str(),
            "tools": turn.role.tools(),
            "session_id": turn.session_id,
            "prompt_sha256": sha256_hex(turn.prompt),
            "response_sha256": sha256_hex(turn.response),
            "result": if turn.failed { "error" } else { "ok" },
            "num_turns": turn.result.num_turns,
            // The count only: a denial record carries the argument the
            // agent was denied, which is content.
            "permission_denials": turn.result.permission_denials.len(),
        }),
    )
}

/// Everything one chain entry commits to, gathered in one place so the
/// prompt and the response can't drift apart from the hashes taken of
/// them.
struct ChainedTurn<'a> {
    project: &'a str,
    /// Which agent produced the turn, so the trail distinguishes them.
    agent: Agent,
    role: Role,
    session_id: Option<&'a str>,
    prompt: &'a str,
    response: &'a str,
    failed: bool,
    result: &'a TurnResult,
}

/// Append the turn's full text to the project's transcript, redacted with
/// the project's declared secret names the same way `log_exec` masks
/// argv. The agent can echo a secret it was given back at us; this is
/// what stops that landing in a file at rest.
fn write_transcript(
    path: &Path,
    role: Role,
    prompt: &str,
    response: &str,
    secret_names: &[String],
) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let line = json!({
        "ts": chrono::Utc::now().to_rfc3339(),
        "role": role.as_str(),
        "prompt": audit::redact(prompt, secret_names),
        "response": audit::redact(response, secret_names),
    });
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .with_context(|| format!("opening transcript {}", path.display()))?;
    writeln!(f, "{line}")?;
    Ok(())
}

/// Flags whose value is `<thing...>` in `claude --help` — variadic, and so
/// greedy that they swallow a bare positional that follows them. The
/// prompt must come before every one of these or `claude` never sees a
/// prompt at all. Found the hard way twice: `recipe::author_spec`
/// documents it for `--allowedTools`, and `--mcp-config <configs...>` then
/// did exactly the same thing to `moor ask` in live use, reporting the
/// prompt as a missing config file ("MCP config file not found:
/// /workspace/say ok").
/// Every agent's tool/config flags take `<thing...>`, so each must land
/// *after* the positional prompt. `build_turn_argv` guarantees that
/// structurally (prompt first, then all flags), and the test below asserts
/// it against this list for every agent.
pub const VARIADIC_FLAGS: &[&str] = &[
    "--allowedTools",
    "--disallowedTools",
    "--allow-tool",
    "--deny-tool",
    "--trust-tools",
    "--mcp-config",
];

/// The argv for one turn: single-value flags, then the prompt, then every
/// variadic flag. `--resume <session-id>` takes exactly one value (checked
/// against `claude --help`, and against a live container) so it sits with
/// the single-value flags ahead of the prompt.
pub fn build_turn_argv(
    agent: Agent,
    role: Role,
    prompt: &str,
    resume: Option<&str>,
) -> Vec<String> {
    let p = profile(agent);
    let mut argv: Vec<String> = p.argv_prefix.iter().map(|s| s.to_string()).collect();
    // Single-value flags first: these take exactly one value, so they are
    // safe ahead of the positional prompt.
    if let (Some(flag), Some(id)) = (p.resume_flag, resume) {
        argv.push(flag.to_string());
        argv.push(id.to_string());
    }
    // The prompt, and then every variadic flag — in that order, which is
    // the whole point. Routing them through one loop after the prompt is
    // pushed is what makes the ordering structural rather than a thing to
    // remember: a new variadic flag gets added to this table, and lands on
    // the correct side of the prompt by construction.
    argv.push(prompt.to_string());
    let mut variadic: Vec<(&str, Vec<String>)> = Vec::new();
    // The MCP server is how a turn reaches keel; only agents that take an
    // --mcp-config get it.
    if agent == Agent::Claude {
        variadic.push(("--mcp-config", vec![MCP_CONFIG.to_string()]));
    }
    if let Some(flag) = p.allow_flag {
        variadic.push((flag, role.tools().iter().map(|t| t.to_string()).collect()));
    }
    if let Some(flag) = p.deny_flag {
        variadic.push((
            flag,
            role.denied_tools().iter().map(|t| t.to_string()).collect(),
        ));
    }
    for (flag, values) in variadic {
        debug_assert!(
            VARIADIC_FLAGS.contains(&flag),
            "{flag} is appended after the prompt, so it must be listed in VARIADIC_FLAGS"
        );
        argv.push(flag.to_string());
        argv.extend(values);
    }
    argv
}

/// Translate an agent failure moor can recognise into the fix for *that*
/// agent. Every one of them reports a missing credential as some variant
/// of "not logged in", and every one has a different remedy — Claude's is
/// an injected token, Copilot's is a host device-flow login, Kiro's is
/// `kiro-cli login`. The interactive advice each CLI prints ("run
/// /login") is useless inside the sandbox, where there is no interactive
/// session and the fix is host-side.
pub fn failure_hint(agent: Agent, project: &str, text: &str) -> Option<String> {
    let looks_like_auth = text.contains("Not logged in")
        || text.contains("/login")
        || text.contains("not authenticated")
        || text.contains("Unauthorized");
    if !looks_like_auth {
        return None;
    }
    let hint = profile(agent).auth_hint.replace("<project>", project);
    Some(format!(
        "{hint}\n\nWhere each secret resolves from:\n\n    moor secrets status {project}"
    ))
}

/// Refuse a role whose restriction this agent cannot express. A role that
/// denies tools is only restricted if the agent has a denial flag; without
/// one the turn would run with everything available, which is the opposite
/// of what the role asked for.
pub fn refuse_unrestrainable_role(agent: Agent, role: Role) -> Result<()> {
    if role.denied_tools().is_empty() {
        return Ok(());
    }
    if profile(agent).deny_flag.is_some() {
        return Ok(());
    }
    anyhow::bail!(
        "the '{}' role withholds tools, but the {agent:?} agent has no way to deny them — \
         running it would give the turn every tool instead.\n\n\
         Use an agent that can deny tools (claude, copilot) for this role, \
         or run this step with `keel run --driver` instead.",
        role.as_str()
    )
}

/// Turn a turn that produced no parseable JSON into something an operator
/// can act on. `claude` writes its own refusals to stderr and nothing to
/// stdout, so without this the only symptom is a JSON parse error about
/// column 0 of an empty string.
fn unparseable_turn(
    project: &str,
    stdout: &str,
    stderr: &str,
    parse_err: anyhow::Error,
) -> anyhow::Error {
    let stderr = stderr.trim();
    if stderr.contains("MCP config file not found") && stderr.contains(MCP_CONFIG) {
        return anyhow::anyhow!(
            "this sandbox predates moor's MCP server — {MCP_CONFIG} is not in its image.\n\
             Rebuild the images and recreate the container:\n\n    \
             make images && moor up {project}\n\n\
             claude said:\n{stderr}"
        );
    }
    if stdout.trim().is_empty() {
        return anyhow::anyhow!(
            "`claude` produced no output and did not start a turn. It said:\n{}",
            if stderr.is_empty() {
                "(nothing on stderr either)"
            } else {
                stderr
            }
        );
    }
    if stderr.is_empty() {
        return parse_err;
    }
    parse_err.context(format!("claude also wrote to stderr:\n{stderr}"))
}

/// Write a recipe the agent drafted, but only once it parses under the
/// same parser `moor recipe` uses. The agent contributes text; the host
/// creates the file that drives its own next run — via a temp file beside
/// the destination, so a draft that doesn't parse leaves nothing behind.
pub fn emit_recipe(dest: &Path, text: &str) -> Result<()> {
    let body = strip_code_fence(text);
    let tmp = dest.with_extension("recipe-draft");
    if let Some(parent) = dest.parent() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent)?;
        }
    }
    std::fs::write(&tmp, &body).with_context(|| format!("writing {}", tmp.display()))?;
    let parsed = crate::commands::recipe::parse_recipe(&tmp);
    match parsed {
        Ok(_) => {
            std::fs::rename(&tmp, dest)
                .with_context(|| format!("moving draft into {}", dest.display()))?;
            Ok(())
        }
        Err(e) => {
            let _ = std::fs::remove_file(&tmp);
            Err(e).with_context(|| {
                format!(
                    "the agent's recipe draft does not parse — nothing was written to {}",
                    dest.display()
                )
            })
        }
    }
}

/// Agents wrap file content in a fenced block more often than not; the
/// fence is presentation, not part of the recipe.
fn strip_code_fence(text: &str) -> String {
    let trimmed = text.trim();
    let Some(rest) = trimmed.strip_prefix("```") else {
        return format!("{trimmed}\n");
    };
    let body = rest.split_once('\n').map(|(_lang, b)| b).unwrap_or("");
    let body = body.trim_end().strip_suffix("```").unwrap_or(body);
    format!("{}\n", body.trim_end())
}

/// What one completed turn amounts to, once it has been chained and
/// transcribed. Returned rather than printed so a caller that owns the
/// terminal (`moor studio`) can draw it itself — the point being that
/// there is one chaining implementation, not one per front end.
pub struct TurnOutcome {
    pub text: String,
    pub failed: bool,
    pub denials: usize,
    /// moor's own read of *why* a turn failed, when the agent's message
    /// names a cause moor can act on. Kept separate from `text` so the
    /// chain entry and the transcript record what the agent actually said,
    /// never moor's commentary on it.
    pub hint: Option<String>,
}

/// Issue one turn: resume from the host's stored session id, run the agent
/// in the sandbox, then chain and transcribe it. Writes nothing to the
/// operator's terminal, so "chained before shown" holds for every caller
/// by construction — there is no path to a response that skips this
/// function.
pub fn run_turn(project: &str, role: Role, prompt: &str, new_session: bool) -> Result<TurnOutcome> {
    let m = Manifest::load(&paths::manifest_path(project)?)?;
    // Reconciled against the image: a Copilot sandbox never runs the
    // `claude` CLI even if its manifest omits `agent:`. See Manifest::agent.
    let agent = m.agent();
    crate::secrets::resolve_into_env(project, &m.secrets);
    paths::ensure_project_dirs(project)?;

    let session_path = paths::session_path(project)?;
    let resume = if new_session {
        None
    } else {
        read_session_id(&session_path)
    };
    // A restricted role on an agent with no way to deny tools would run
    // unrestricted — ADR-0008 established that an allow-list alone does
    // not restrain. Refuse rather than silently widen the role.
    refuse_unrestrainable_role(agent, role)?;
    let argv = build_turn_argv(agent, role, prompt, resume.as_deref());

    let container = m.sandbox_container();
    let mut args: Vec<&str> = vec!["exec", &container];
    args.extend(argv.iter().map(String::as_str));
    let (status, out, err) = proc::run_capture_split("docker", &args)?;

    let turn = parse_turn(agent, &out).map_err(|e| unparseable_turn(project, &out, &err, e))?;
    let failed = turn_failed(&turn, status.success());
    let session_id = next_session_id(&turn);

    // Chained before the caller can show anything — AC-6 of
    // `agent-session-protocol`.
    append_turn_to(
        &paths::chain_log_path(project)?,
        &ChainedTurn {
            project,
            agent,
            role,
            session_id: session_id.as_deref(),
            prompt,
            response: &turn.result,
            failed,
            result: &turn,
        },
    )?;
    write_transcript(
        &paths::transcript_path(project)?,
        role,
        prompt,
        &turn.result,
        &m.secrets,
    )?;
    if let Some(id) = &session_id {
        store_session_id(&session_path, id)?;
    }

    let hint = failed
        .then(|| failure_hint(agent, project, &turn.result))
        .flatten();
    Ok(TurnOutcome {
        text: turn.result,
        failed,
        denials: turn.permission_denials.len(),
        hint,
    })
}

/// `moor ask`: one turn, printed for a human.
pub fn ask(
    project: &str,
    role: Role,
    prompt: &str,
    new_session: bool,
    emit: Option<&Path>,
) -> Result<()> {
    println!("==> [{}] turn in project {project}", role.as_str());
    let outcome = run_turn(project, role, prompt, new_session)?;

    println!("{}", outcome.text);
    if outcome.denials > 0 {
        println!(
            "==> {} tool call(s) were denied — the role's tool set is {:?}",
            outcome.denials,
            role.tools()
        );
    }
    if outcome.failed {
        if let Some(hint) = &outcome.hint {
            println!("\n==> {hint}");
        }
        anyhow::bail!("the agent reported an error for this turn (is_error)");
    }
    if let Some(dest) = emit {
        emit_recipe(dest, &outcome.text)?;
        println!("==> wrote {} — run it with `moor recipe`", dest.display());
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_path(label: &str, ext: &str) -> std::path::PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!("moor-session-test-{label}-{nanos}.{ext}"))
    }

    fn result_json(is_error: bool, subtype: &str, session_id: &str, text: &str) -> String {
        json!({
            "type": "result",
            "subtype": subtype,
            "is_error": is_error,
            "result": text,
            "session_id": session_id,
            "num_turns": 3,
            "permission_denials": [],
        })
        .to_string()
    }

    /// AC-3. Note what this asserts twice over: that the mutating tools are
    /// not *granted*, and that they are explicitly *denied*. Granting alone
    /// is not a boundary — measured live, Claude Code ran `Bash` under
    /// `--allowedTools Read Glob Grep` and returned its output. See
    /// `Role::denied_tools`.
    #[test]
    fn brainstorm_grants_no_write_tool() {
        let tools = Role::Brainstorm.tools();
        assert_eq!(tools, &["Read", "Glob", "Grep"]);
        let denied = Role::Brainstorm.denied_tools();
        for forbidden in [
            "Write",
            "Edit",
            "Bash",
            "NotebookEdit",
            "MultiEdit",
            "WebFetch",
        ] {
            assert!(
                !tools.contains(&forbidden),
                "brainstorm must not grant {forbidden}"
            );
            assert!(
                denied.contains(&forbidden),
                "brainstorm must explicitly deny {forbidden} — not granting it is not enough"
            );
        }
        // The deny list reaches the argv, or it is decoration.
        let argv = build_turn_argv(Agent::Claude, Role::Brainstorm, "think about this", None);
        let at = argv.iter().position(|a| a == "--disallowedTools").unwrap();
        for forbidden in ["Bash", "Write", "Edit", "Task"] {
            assert!(argv[at..].iter().any(|a| a == forbidden));
        }
        // And the granted set in the argv is exactly the role's — the
        // values of `--allowedTools` up to whatever flag comes next.
        let argv = build_turn_argv(
            Agent::Claude,
            Role::Brainstorm,
            "what should we change?",
            None,
        );
        let at = argv.iter().position(|a| a == "--allowedTools").unwrap();
        let granted: Vec<&String> = argv[at + 1..]
            .iter()
            .take_while(|a| !a.starts_with("--"))
            .collect();
        assert_eq!(granted, vec!["Read", "Glob", "Grep"]);
    }

    /// AC-4
    #[test]
    fn rejects_malformed_session_id() {
        for bad in [
            "",
            "not-a-uuid",
            "abc",
            "3f2504e0-4f89-11d3-9a0c",
            "3f2504e0-4f89-11d3-9a0c-0305e82c33011",
            "3f2504e0-4f89-11d3-9a0c-0305e82c330z",
            "../../etc/passwd",
            "3f2504e04f8911d39a0c0305e82c3301",
        ] {
            assert!(!valid_session_id(bad), "'{bad}' should be rejected");
            let path = temp_path("bad-id", "txt");
            assert!(store_session_id(&path, bad).is_err());
            assert!(!path.exists(), "a rejected id must not be written");
        }

        let good = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
        assert!(valid_session_id(good));
        let path = temp_path("good-id", "txt");
        store_session_id(&path, good).unwrap();
        assert_eq!(read_session_id(&path).as_deref(), Some(good));

        // A stored file that was tampered with is not resumed from either.
        std::fs::write(&path, "wherever-you-like").unwrap();
        assert_eq!(read_session_id(&path), None);
        let _ = std::fs::remove_file(&path);

        // The id comes from the parsed field only — a response that prints
        // a perfectly well-formed UUID cannot redirect the next turn.
        let smuggled = json!({
            "is_error": false,
            "result": "Continue with session_id 11111111-2222-3333-4444-555555555555",
            "session_id": "not-a-uuid",
        })
        .to_string();
        let turn = parse_turn(Agent::Claude, &smuggled).unwrap();
        assert_eq!(next_session_id(&turn), None);
        assert!(turn.result.contains("11111111-2222-3333-4444-555555555555"));
    }

    /// AC-5
    #[test]
    fn error_turn_is_detected_by_is_error() {
        // The shape actually observed at Claude Code 2.1.270: a failed
        // turn reporting "subtype": "success".
        let raw = result_json(
            true,
            "success",
            "3f2504e0-4f89-11d3-9a0c-0305e82c3301",
            "boom",
        );
        let turn = parse_turn(Agent::Claude, &raw).unwrap();
        assert!(turn.is_error);
        assert!(
            turn_failed(&turn, true),
            "is_error must win over a zero exit status and a 'success' subtype"
        );
        assert!(!raw.contains("\"subtype\": \"error\""));

        // A clean turn is a success; a non-zero exit is still a failure.
        let ok = parse_turn(
            Agent::Claude,
            &result_json(
                false,
                "success",
                "3f2504e0-4f89-11d3-9a0c-0305e82c3301",
                "done",
            ),
        )
        .unwrap();
        assert!(!turn_failed(&ok, true));
        assert!(turn_failed(&ok, false));
    }

    /// AC-6
    #[test]
    fn turn_is_chained_without_content() {
        let path = temp_path("chain", "jsonl");
        let prompt = "the operator's private plan for the quarter";
        let response = "here is what I would do, in detail";
        let turn = parse_turn(
            Agent::Claude,
            &result_json(
                false,
                "success",
                "3f2504e0-4f89-11d3-9a0c-0305e82c3301",
                response,
            ),
        )
        .unwrap();

        let entry = append_turn_to(
            &path,
            &ChainedTurn {
                project: "sample",
                agent: Agent::Claude,
                role: Role::Brainstorm,
                session_id: Some("3f2504e0-4f89-11d3-9a0c-0305e82c3301"),
                prompt,
                response,
                failed: false,
                result: &turn,
            },
        )
        .unwrap();

        assert_eq!(entry.kind, "agent-turn");
        assert_eq!(entry.data["role"], json!("brainstorm"));
        assert_eq!(entry.data["tools"], json!(["Read", "Glob", "Grep"]));
        assert_eq!(
            entry.data["session_id"],
            json!("3f2504e0-4f89-11d3-9a0c-0305e82c3301")
        );
        assert_eq!(entry.data["prompt_sha256"], json!(sha256_hex(prompt)));
        assert_eq!(entry.data["response_sha256"], json!(sha256_hex(response)));
        assert_eq!(entry.data["result"], json!("ok"));

        // No content anywhere in the file on disk, and the chain still verifies.
        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert!(!on_disk.contains(prompt));
        assert!(!on_disk.contains(response));
        assert!(!on_disk.contains("private plan"));
        assert!(matches!(
            audit::verify_chain(&path).unwrap(),
            audit::VerifyOutcome::Ok { entries: 1 }
        ));
        let _ = std::fs::remove_file(&path);
    }

    /// AC-7
    #[test]
    fn transcript_is_redacted() {
        std::env::set_var("MOOR_TEST_SESSION_SECRET", "ghp_livetoken1234567890");
        let path = temp_path("transcript", "jsonl");
        write_transcript(
            &path,
            Role::Build,
            "use the token ghp_livetoken1234567890 to push",
            "I ran it with ghp_livetoken1234567890 and it worked",
            &["MOOR_TEST_SESSION_SECRET".to_string()],
        )
        .unwrap();

        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert!(
            !on_disk.contains("ghp_livetoken1234567890"),
            "the secret survived into the transcript:\n{on_disk}"
        );
        assert!(on_disk.contains("***REDACTED:MOOR_TEST_SESSION_SECRET***"));
        // Redacted, not dropped — the surrounding text is still readable.
        assert!(on_disk.contains("to push"));
        assert!(on_disk.contains("\"role\":\"build\""));
        std::env::remove_var("MOOR_TEST_SESSION_SECRET");
        let _ = std::fs::remove_file(&path);
    }

    /// AC-8
    #[test]
    fn emitted_recipe_round_trips() {
        let dest = temp_path("emitted", "md");
        let drafted = "```markdown\n---\nslug: greet-function\nscope:\n  - \"src/**\"\n---\n\nI want a greet function.\n```";
        emit_recipe(&dest, drafted).unwrap();

        // Written by the host, and it parses under the parser `moor
        // recipe` itself uses — so the emitted file can actually be run.
        let written = std::fs::read_to_string(&dest).unwrap();
        assert!(written.starts_with("---\n"));
        assert!(!written.contains("```"));
        let recipe = crate::commands::recipe::parse_recipe(&dest).unwrap();
        assert_eq!(recipe.front.slug, "greet-function");
        assert_eq!(recipe.description, "I want a greet function.");
        let _ = std::fs::remove_file(&dest);

        // A draft that doesn't parse writes nothing at all — no half-file
        // for `moor recipe` to trip over later.
        let bad = temp_path("emitted-bad", "md");
        let err = emit_recipe(&bad, "Sure! Here's how I'd approach that...").unwrap_err();
        assert!(err.to_string().contains("does not parse"));
        assert!(!bad.exists());
        assert!(!bad.with_extension("recipe-draft").exists());
    }

    #[test]
    fn build_role_has_verification_tools_but_no_shell() {
        let tools = Role::Build.tools();
        assert!(tools.contains(&"mcp__moor-keel__keel_gate"));
        assert!(tools.contains(&"mcp__moor-keel__keel_next"));
        assert!(!tools.iter().any(|t| t.starts_with("Bash")));
        assert!(!tools.iter().any(|t| t.contains("approve")));
        // But `build` can still edit — that is the point of the role.
        assert!(tools.contains(&"Edit"));
        assert!(tools.contains(&"Write"));
    }

    /// The one that matters: with a shell, the agent runs `keel approve`
    /// itself and every human checkpoint in keel's pipeline is advisory.
    /// Verified live before this existed — the `build` role reached
    /// `keel approve --help` through Bash and quoted it back — so every
    /// role must deny every route to a shell or a subagent, in the argv.
    #[test]
    fn no_role_can_reach_a_shell_or_a_subagent() {
        for role in [Role::Brainstorm, Role::Build] {
            let denied = role.denied_tools();
            let argv = build_turn_argv(Agent::Claude, role, "do the thing", None);
            let at = argv
                .iter()
                .position(|a| a == "--disallowedTools")
                .unwrap_or_else(|| panic!("{role:?} passes no deny list at all"));
            let denied_in_argv = &argv[at + 1..];
            for escape in [
                "Bash",
                "BashOutput",
                "KillShell",
                "KillBash",
                "Task",
                "SlashCommand",
            ] {
                assert!(denied.contains(&escape), "{role:?} does not deny {escape}");
                assert!(
                    denied_in_argv.iter().any(|a| a == escape),
                    "{role:?}'s argv does not deny {escape}: {argv:?}"
                );
            }
            // Nothing is both granted and denied — that would be ambiguous
            // and its resolution is not moor's to guess.
            for granted in role.tools() {
                assert!(
                    !denied.contains(granted),
                    "{role:?} both grants and denies {granted}"
                );
            }
        }
    }

    /// Every variadic flag swallows a bare positional that follows it, so
    /// the prompt has to precede all of them. This is asserted against the
    /// whole `VARIADIC_FLAGS` list rather than one flag because the bug has
    /// now happened twice: first with `--allowedTools`, then — in live use,
    /// after this was believed fixed — with `--mcp-config <configs...>`,
    /// which reported the prompt as a missing config file and left `claude`
    /// writing nothing to stdout at all.
    #[test]
    fn the_prompt_precedes_every_variadic_flag() {
        let prompt = "can we add a CI pipeline with security scans";
        for role in [Role::Brainstorm, Role::Build] {
            for resume in [None, Some("3f2504e0-4f89-11d3-9a0c-0305e82c3301")] {
                let argv = build_turn_argv(Agent::Claude, role, prompt, resume);
                let at_prompt = argv
                    .iter()
                    .position(|a| a == prompt)
                    .expect("the prompt is in the argv at all");
                for flag in VARIADIC_FLAGS {
                    if let Some(at_flag) = argv.iter().position(|a| a == flag) {
                        assert!(
                            at_prompt < at_flag,
                            "{flag} precedes the prompt, so claude will eat it: {argv:?}"
                        );
                    }
                }
                // Nothing may trail the last variadic flag's values either.
                let last_variadic = VARIADIC_FLAGS
                    .iter()
                    .filter_map(|f| argv.iter().position(|a| a == f))
                    .max()
                    .expect("a turn always passes at least one variadic flag");
                assert!(at_prompt < last_variadic);
            }
        }
    }

    /// The MCP config path is a value of `--mcp-config`, and must be the
    /// argument immediately after it — not somewhere a variadic flag
    /// earlier in the line could have absorbed.
    #[test]
    fn mcp_config_is_the_value_of_its_own_flag() {
        let argv = build_turn_argv(Agent::Claude, Role::Build, "go", None);
        let at = argv.iter().position(|a| a == "--mcp-config").unwrap();
        assert_eq!(argv[at + 1], MCP_CONFIG);
    }

    /// A turn that produced nothing parseable must hand the operator
    /// `claude`'s own words, not a JSON parse error about column 0.
    #[test]
    fn an_empty_turn_reports_what_claude_actually_said() {
        let parse_err = parse_turn(Agent::Claude, "").unwrap_err();
        let stderr = "Error: Invalid MCP configuration:\nMCP config file not found: /etc/moor/mcp-config.json";
        let reported = format!("{:?}", unparseable_turn("personil", "", stderr, parse_err));
        // Names the cause and the exact command that fixes it.
        assert!(
            reported.contains("predates moor's MCP server"),
            "{reported}"
        );
        assert!(
            reported.contains("make images && moor up personil"),
            "{reported}"
        );

        // Any other silent failure still surfaces stderr verbatim.
        let parse_err = parse_turn(Agent::Claude, "").unwrap_err();
        let reported = format!(
            "{:?}",
            unparseable_turn("demo", "", "Error: Invalid API key", parse_err)
        );
        assert!(reported.contains("Invalid API key"), "{reported}");
        assert!(reported.contains("produced no output"), "{reported}");

        // Output that is present but not JSON keeps the parse error and
        // adds stderr rather than replacing it.
        let parse_err = parse_turn(Agent::Claude, "not json").unwrap_err();
        let reported = format!(
            "{:?}",
            unparseable_turn("demo", "not json", "a warning", parse_err)
        );
        assert!(reported.contains("not json"), "{reported}");
        assert!(reported.contains("a warning"), "{reported}");
    }

    #[test]
    fn resume_is_passed_through_when_there_is_a_stored_session() {
        let argv = build_turn_argv(
            Agent::Claude,
            Role::Build,
            "carry on",
            Some("3f2504e0-4f89-11d3-9a0c-0305e82c3301"),
        );
        let at = argv.iter().position(|a| a == "--resume").unwrap();
        assert_eq!(argv[at + 1], "3f2504e0-4f89-11d3-9a0c-0305e82c3301");
        // `--resume <session-id>` takes exactly one value (per `claude
        // --help`, and verified live), so it belongs ahead of the prompt.
        assert!(at < argv.iter().position(|a| a == "carry on").unwrap());
        assert!(argv.contains(&MCP_CONFIG.to_string()));
    }

    /// "Not logged in · Please run /login" is what Claude Code says when a
    /// sandbox has no credential — advice that cannot be followed from a
    /// non-interactive turn. moor has to answer the question the operator
    /// actually has: which command fixes this, for which project.
    #[test]
    fn a_missing_credential_points_at_the_host_side_fix() {
        let hint = failure_hint(
            Agent::Claude,
            "omniscient",
            "Not logged in · Please run /login",
        )
        .expect("a missing credential is recognised");
        assert!(hint.contains("CLAUDE_CODE_OAUTH_TOKEN"));
        assert!(hint.contains("moor up omniscient"));
        // Secrets are scoped per project, so the hint names this project.
        assert!(hint.contains("moor secrets status omniscient"));

        // An ordinary failure gets no invented advice.
        assert_eq!(
            failure_hint(Agent::Claude, "demo", "I could not find that file."),
            None
        );
        assert_eq!(failure_hint(Agent::Claude, "demo", ""), None);
    }

    #[test]
    fn unknown_role_is_rejected() {
        assert!(Role::parse("brainstorm").is_ok());
        assert!(Role::parse("build").is_ok());
        assert!(Role::parse("approve").is_err());
        assert!(Role::parse("").is_err());
    }
    // --- agent-session-abstraction (SPEC-0012) --------------------------

    #[test]
    fn agent_parses_kiro() {
        // AC-1
        assert_eq!("kiro".parse::<Agent>().unwrap(), Agent::Kiro);
        assert_eq!("KIRO".parse::<Agent>().unwrap(), Agent::Kiro);
        assert!("kiro-cli".parse::<Agent>().is_err());
    }

    #[test]
    fn turn_argv_is_per_agent() {
        // AC-2: each agent gets its own invocation, not Claude's.
        let claude = build_turn_argv(Agent::Claude, Role::Brainstorm, "hi", None);
        assert_eq!(claude[0], "claude");
        assert!(claude.contains(&"--print".to_string()));

        let copilot = build_turn_argv(Agent::Copilot, Role::Brainstorm, "hi", None);
        assert_eq!(copilot[0], "copilot");
        assert!(copilot.contains(&"-p".to_string()));
        assert!(!copilot.contains(&"--print".to_string()));

        let kiro = build_turn_argv(Agent::Kiro, Role::Brainstorm, "hi", None);
        assert_eq!(kiro[0], "kiro-cli");
        assert!(kiro.contains(&"chat".to_string()));

        // The prompt is present for all three, after the prefix.
        for argv in [&claude, &copilot, &kiro] {
            assert!(argv.contains(&"hi".to_string()), "{argv:?}");
        }
    }

    #[test]
    fn an_agent_less_copilot_manifest_runs_copilot_not_claude() {
        // The regression this guards: a Copilot sandbox whose manifest
        // omits `agent:` defaults the raw field to Claude, so turns went to
        // the `claude` CLI and died with "Not logged in". `run_turn` reads
        // the agent through `Manifest::agent()`, which reconciles against
        // the image — so the invocation built for such a manifest must be
        // the copilot CLI. Proven over the real argv builder, no mocking.
        let yaml = "name: sc\nimage: moor/copilot-python:latest\n";
        let m: crate::manifest::Manifest = yaml_serde::from_str(yaml).unwrap();
        assert_eq!(m.agent, Agent::Claude, "raw field is the serde default");

        let argv = build_turn_argv(m.agent(), Role::Brainstorm, "hi", None);
        assert_eq!(argv[0], "copilot", "reconciled agent must drive the CLI");
        assert_ne!(argv[0], "claude");

        // And the auth hint it would show on failure is Copilot's host-side
        // fix, not Claude's — so the operator is pointed at `copilot /login`.
        let hint = failure_hint(m.agent(), "sc", "Not logged in").unwrap();
        assert!(hint.contains("copilot /login"), "{hint}");
        assert!(!hint.contains("setup-token"), "{hint}");
    }

    #[test]
    fn restricted_role_refused_without_deny_support() {
        // AC-3: a role that withholds tools cannot run on an agent with no
        // denial mechanism — it would run unrestricted instead.
        assert!(!Role::Brainstorm.denied_tools().is_empty());
        let err = refuse_unrestrainable_role(Agent::Kiro, Role::Brainstorm)
            .expect_err("kiro has no deny flag, so a restricted role must be refused");
        let msg = format!("{err}");
        assert!(msg.contains("no way to deny"), "{msg}");
        // Agents that can deny are allowed through.
        assert!(refuse_unrestrainable_role(Agent::Claude, Role::Brainstorm).is_ok());
        assert!(refuse_unrestrainable_role(Agent::Copilot, Role::Build).is_ok());
    }

    #[test]
    fn deny_flag_is_per_agent() {
        // AC-4: the deny flag, where it exists, is that agent's own.
        let claude = build_turn_argv(Agent::Claude, Role::Brainstorm, "hi", None);
        assert!(claude.contains(&"--disallowedTools".to_string()));
        let copilot = build_turn_argv(Agent::Copilot, Role::Brainstorm, "hi", None);
        assert!(copilot.contains(&"--deny-tool".to_string()));
        assert!(!copilot.contains(&"--disallowedTools".to_string()));
        // Kiro has none, so none is emitted.
        let kiro = build_turn_argv(Agent::Kiro, Role::Brainstorm, "hi", None);
        assert!(!kiro.contains(&"--deny-tool".to_string()));
        assert!(!kiro.contains(&"--disallowedTools".to_string()));
        // Bash is denied for every agent that can deny at all.
        for argv in [&claude, &copilot] {
            assert!(argv.contains(&"Bash".to_string()), "{argv:?}");
        }
    }

    #[test]
    fn turn_output_parsed_per_agent() {
        // AC-5: a plain-text agent's stdout is the response, not a parse
        // error; Claude's JSON envelope still parses as before.
        let plain = parse_turn(Agent::Copilot, "READY\n").unwrap();
        assert_eq!(plain.result, "READY");
        assert!(!plain.is_error);
        let kiro = parse_turn(Agent::Kiro, "done").unwrap();
        assert_eq!(kiro.result, "done");
        let json = parse_turn(
            Agent::Claude,
            &result_json(
                false,
                "success",
                "3f2504e0-4f89-11d3-9a0c-0305e82c3301",
                "ok",
            ),
        )
        .unwrap();
        assert_eq!(json.result, "ok");
        // Plain text that happens to look like JSON is still just text.
        assert!(parse_turn(Agent::Copilot, "not json").is_ok());
        assert!(parse_turn(Agent::Claude, "not json").is_err());
    }

    #[test]
    fn resume_form_is_per_agent() {
        // AC-6: the resume flag is the agent's own, and an agent with no
        // resume form omits it entirely.
        let id = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";
        let claude = build_turn_argv(Agent::Claude, Role::Build, "go", Some(id));
        let at = claude.iter().position(|a| a == "--resume").unwrap();
        assert_eq!(claude[at + 1], id);
        let copilot = build_turn_argv(Agent::Copilot, Role::Build, "go", Some(id));
        assert!(copilot.contains(&"--resume".to_string()));
        // Kiro declares no resume form: nothing is passed, and the id is
        // not smuggled in some other position.
        let kiro = build_turn_argv(Agent::Kiro, Role::Build, "go", Some(id));
        assert!(!kiro.contains(&"--resume".to_string()));
        assert!(!kiro.contains(&id.to_string()), "{kiro:?}");
    }

    #[test]
    fn failure_hint_is_per_agent() {
        // AC-7: each agent's own remedy, not Claude's for all three.
        let auth = "not authenticated";
        let c = failure_hint(Agent::Claude, "p", auth).unwrap();
        assert!(c.contains("CLAUDE_CODE_OAUTH_TOKEN"), "{c}");
        let g = failure_hint(Agent::Copilot, "p", auth).unwrap();
        assert!(g.contains("copilot /login"), "{g}");
        assert!(!g.contains("CLAUDE_CODE_OAUTH_TOKEN"), "{g}");
        let k = failure_hint(Agent::Kiro, "p", auth).unwrap();
        assert!(k.contains("kiro-cli login"), "{k}");
        // A non-auth failure still gets no invented advice, for any agent.
        for a in [Agent::Claude, Agent::Copilot, Agent::Kiro] {
            assert_eq!(failure_hint(a, "p", "file not found"), None);
        }
    }

    #[test]
    fn turn_record_names_the_agent() {
        // AC-8: the chain entry says which agent produced the turn.
        let dir = std::env::temp_dir().join(format!(
            "moor-agent-chain-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("chain.jsonl");
        let result = TurnResult::default();
        append_turn_to(
            &path,
            &ChainedTurn {
                project: "sample",
                agent: Agent::Copilot,
                role: Role::Brainstorm,
                session_id: None,
                prompt: "p",
                response: "r",
                failed: false,
                result: &result,
            },
        )
        .unwrap();
        let written = std::fs::read_to_string(&path).unwrap();
        assert!(written.contains("\"agent\":\"copilot\""), "{written}");
        let _ = std::fs::remove_dir_all(&dir);
    }
}