Skip to main content

devflow_core/agents/
claude.rs

1//! Claude Code agent adapter.
2//!
3//! Launches `claude -p` headless with a bidirectional `stream-json` transport:
4//! the initial user turn travels on the child's **stdin**, and its events come
5//! back on stdout one JSON object per line. Claude runs headless — no trust
6//! dialogs, no user prompts.
7
8use super::AgentAdapter;
9
10pub struct ClaudeAgent;
11
12impl AgentAdapter for ClaudeAgent {
13    fn name(&self) -> &'static str {
14        "Claude Code"
15    }
16
17    /// Build the headless `stream-json` launch (Phase 31, constraint 1).
18    ///
19    /// **The prompt is deliberately absent from the returned argv.** Under
20    /// `--input-format stream-json` the CLI takes its initial user turn from
21    /// stdin as a JSON document, not from a positional argument; the monitor
22    /// writes that turn via [`crate::monitor::user_turn_line`]. The `prompt`
23    /// parameter is kept in the signature because [`AgentAdapter`] is shared
24    /// with adapters that DO pass it positionally (Codex, OpenCode) — it is
25    /// unused here on purpose, not by oversight.
26    ///
27    /// Evidence: all three archived Phase 30 harnesses
28    /// (`.planning/phases/30-keep-the-session-alive-past-turn-end/`,
29    /// `30b`/`30c`/`30d`) launch with exactly this flag set and no positional
30    /// prompt, then write
31    /// `{"type":"user","message":{"role":"user","content":<prompt>}}` to the
32    /// child's stdin. `30c-monitor-env-harness.py`'s `DEFAULT_CLI_ARGV` is the
33    /// literal argv reproduced here.
34    ///
35    /// `--verbose` is load-bearing, not decoration: every archived trial that
36    /// produced a usable capture carried it, and dropping it is untested
37    /// territory. Do not "clean it up".
38    ///
39    /// The switch is unconditional and stage-blind — constraint 1 forbids
40    /// predicting at launch time which stages will background work. The
41    /// *sequencing* choice about which stages route here lives at the call
42    /// site (`claude_stream_launch_enabled` in `pipeline_launch.rs`); the
43    /// shape a not-yet-widened stage gets instead is
44    /// [`ClaudeAgent::exec_command_single_document`], which is a live path
45    /// rather than a deprecated one.
46    fn exec_command(
47        &self,
48        _phase: u32,
49        _prompt: &str,
50        _extra_writable_roots: &[std::path::PathBuf],
51    ) -> (&'static str, Vec<String>) {
52        (
53            "claude",
54            vec![
55                "-p".into(),
56                "--input-format".into(),
57                "stream-json".into(),
58                "--output-format".into(),
59                "stream-json".into(),
60                "--verbose".into(),
61                "--dangerously-skip-permissions".into(),
62            ],
63        )
64    }
65
66    fn completion_signal_detected(&self, _output: &str) -> bool {
67        // Claude exits cleanly when done; monitor detects exit via kill -0.
68        false
69    }
70}
71
72impl ClaudeAgent {
73    /// The pre-31 single-document launch: `-p <prompt>` positionally with
74    /// `--output-format json`.
75    ///
76    /// **This is a live path, not a deprecated leftover.** Two things select
77    /// it, and both are deliberate:
78    ///
79    /// - **D-09/D-10's sequencing gate.** The stream-json launch is rolled out
80    ///   one stage at a time, starting at `Stage::Code`. Every stage not yet
81    ///   widened launches through here. That is a sequencing choice about
82    ///   rollout order, which constraint 1 permits — it is emphatically not a
83    ///   prediction about which stages background work, which constraint 1
84    ///   forbids.
85    /// - **D-11's opt-out.** An explicit flag (off by default) can force this
86    ///   shape back on for recovery without cutting a release. Automatic
87    ///   fallback on parse failure is rejected: a silent downgrade is the same
88    ///   invisible-degradation class as the bug Phase 31 exists to fix.
89    ///
90    /// The argv is the pre-31 [`AgentAdapter::exec_command`] body verbatim, so
91    /// the shipped capture shape (`CaptureKind::SingleDocEnvelope`) and the
92    /// 30b isolation tests that guard it (D-12) keep holding bit-for-bit.
93    pub fn exec_command_single_document(prompt: &str) -> (&'static str, Vec<String>) {
94        (
95            "claude",
96            vec![
97                "-p".into(),
98                prompt.to_string(),
99                "--output-format".into(),
100                "json".into(),
101                "--dangerously-skip-permissions".into(),
102            ],
103        )
104    }
105
106    /// Build the resume relaunch command for a confirmed checkpoint
107    /// auto-decide (D-03/D-04, 28-03). NOT a trait method — `--resume` is a
108    /// Claude-CLI-specific, documented feature with no equivalent on
109    /// `AgentAdapter` (D-05: Claude-only, no Codex/OpenCode accommodation,
110    /// `AgentAdapter` itself is untouched).
111    ///
112    /// Argv order (RESEARCH.md § "Architecture Patterns / Pattern 4",
113    /// confirmed): the print flag, the instruction, the resume flag
114    /// immediately followed by the session id (so the id is parsed as the
115    /// flag's value, not a positional argument), the output-format flag with
116    /// its JSON value, and the permission-bypass flag.
117    ///
118    /// **Pitfall 1 (RESEARCH.md, T-28-02) — load-bearing, do not "clean up":**
119    /// a `claude --resume`d session restores NEITHER the permission mode NOR
120    /// the output format from the original launch. Both are re-passed here
121    /// explicitly even though they look redundant with `exec_command`'s
122    /// launch above. Omitting either reintroduces the exact headless hang
123    /// this phase exists to close: the resumed session halts on a
124    /// permission prompt with no operator present to answer it, and the
125    /// prompt is not guaranteed to even reach the captured stdout.
126    /// `resume_command_includes_permission_bypass` is the named regression
127    /// test guarding this specifically — do not delete it as "obviously
128    /// redundant" with the launch-contract tests above; it guards a DIFFERENT
129    /// command construction path. Note the resume argv keeps `--output-format
130    /// json` and a POSITIONAL instruction even though `exec_command` no longer
131    /// does: a resumed session is a single-document relaunch, not a
132    /// stream-json one.
133    pub fn exec_resume_command(session_id: &str, instruction: &str) -> (&'static str, Vec<String>) {
134        (
135            "claude",
136            vec![
137                "-p".into(),
138                instruction.to_string(),
139                "--resume".into(),
140                session_id.to_string(),
141                "--output-format".into(),
142                "json".into(),
143                "--dangerously-skip-permissions".into(),
144            ],
145        )
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    /// A stand-in for the stage prompt's one invariant substring. Every real
154    /// stage prompt carries the `DEVFLOW_RESULT` contract, so its presence in
155    /// an argument is what identifies that argument as the prompt.
156    const PROMPT: &str = "do the work, then emit DEVFLOW_RESULT: {...}";
157
158    /// Both directions, or neither works. Flipping only `--output-format`
159    /// leaves the CLI with no first turn (the prompt has left argv but nothing
160    /// is writing it to stdin) and it stalls headless — the failure RESEARCH
161    /// Pitfall 1 names, whose warning sign is an `init` event followed by the
162    /// agent asking what to do.
163    #[test]
164    fn exec_command_uses_stream_json_on_both_input_and_output() {
165        let (program, args) = ClaudeAgent.exec_command(7, PROMPT, &[]);
166        assert_eq!(program, "claude");
167        assert!(
168            args.windows(2)
169                .any(|w| w[0] == "--input-format" && w[1] == "stream-json"),
170            "the input format is what moves the initial turn onto stdin: {args:?}"
171        );
172        assert!(
173            args.windows(2)
174                .any(|w| w[0] == "--output-format" && w[1] == "stream-json"),
175            "the output format is what makes the capture a JSONL event stream: {args:?}"
176        );
177        assert!(
178            args.iter().any(|a| a == "--verbose"),
179            "every archived Phase 30 trial that produced a usable capture \
180             carried --verbose; dropping it is untested territory: {args:?}"
181        );
182        assert!(
183            args.iter().any(|a| a == "--dangerously-skip-permissions"),
184            "a headless launch with no operator present cannot answer a \
185             permission prompt: {args:?}"
186        );
187    }
188
189    /// The half of the change that is easy to miss. RESEARCH Pitfall 1: the
190    /// ROADMAP and CONTEXT both describe Phase 31 as "the argv flip", which
191    /// reads as flags-only — but leaving the prompt at `args[1]` under
192    /// `--input-format stream-json` is not documented to work, and was never
193    /// tested in Phase 30.
194    #[test]
195    fn exec_command_carries_no_positional_prompt() {
196        let (_program, args) = ClaudeAgent.exec_command(7, PROMPT, &[]);
197        assert!(
198            !args.iter().any(|arg| arg.contains("DEVFLOW_RESULT")),
199            "the prompt must not appear in argv at all — it travels as a JSON \
200             user turn on the child's stdin, written by the monitor: {args:?}"
201        );
202    }
203
204    /// The pre-31 shape must stay REACHABLE, not merely present. Two live
205    /// selectors depend on it: D-11's opt-out (recovery without a release) and
206    /// the D-09/D-10 sequencing gate (every stage the rollout has not reached
207    /// yet). If this builder silently drifted toward the stream-json shape,
208    /// both would land on a launch that is not pre-31 at all, and the D-12
209    /// isolation guarantee for the shipped single-document capture would go
210    /// with it.
211    #[test]
212    fn single_document_command_preserves_pre31_shape() {
213        let (program, args) = ClaudeAgent::exec_command_single_document(PROMPT);
214        assert_eq!(program, "claude");
215        assert!(
216            args.windows(2).any(|w| w[0] == "-p" && w[1] == PROMPT),
217            "the prompt must follow -p POSITIONALLY, as it did pre-31: {args:?}"
218        );
219        assert!(
220            args.windows(2)
221                .any(|w| w[0] == "--output-format" && w[1] == "json"),
222            "the single-document envelope is what makes this capture classify \
223             as SingleDocEnvelope and keep the raw-scan path: {args:?}"
224        );
225        assert!(
226            args.iter().any(|a| a == "--dangerously-skip-permissions"),
227            "the opt-out path is still headless: {args:?}"
228        );
229        assert!(
230            !args.iter().any(|a| a == "--input-format"),
231            "this builder must NOT drift toward the stream-json shape — that \
232             would leave D-11's opt-out with nothing to opt out to: {args:?}"
233        );
234    }
235
236    #[test]
237    fn resume_command_names_claude_program() {
238        let (program, _args) = ClaudeAgent::exec_resume_command("sess", "instr");
239        assert_eq!(program, "claude");
240    }
241
242    #[test]
243    fn resume_command_carries_print_flag_and_instruction() {
244        let (_program, args) = ClaudeAgent::exec_resume_command("sess", "do the thing");
245        assert!(args.iter().any(|a| a == "-p"));
246        assert!(args.iter().any(|a| a == "do the thing"));
247    }
248
249    #[test]
250    fn resume_command_resume_flag_immediately_precedes_session_id() {
251        let (_program, args) = ClaudeAgent::exec_resume_command("sess-abc", "instr");
252        let resume_idx = args
253            .iter()
254            .position(|a| a == "--resume")
255            .expect("--resume flag must be present");
256        assert_eq!(
257            args.get(resume_idx + 1).map(String::as_str),
258            Some("sess-abc"),
259            "the session id must immediately follow --resume so it is parsed \
260             as the flag's value, not a positional argument: {args:?}"
261        );
262    }
263
264    /// Pitfall 1 (RESEARCH.md, T-28-02): the single highest-consequence
265    /// regression this phase can ship is a resume relaunch that omits either
266    /// the permission-bypass flag or the JSON output-format flag — a resumed
267    /// Claude session restores neither, so omitting them reintroduces a
268    /// silent headless hang on a permission prompt nobody can answer.
269    #[test]
270    fn resume_command_includes_permission_bypass() {
271        let (program, args) = ClaudeAgent::exec_resume_command("sess-123", "do the thing");
272        assert_eq!(program, "claude");
273        assert!(
274            args.iter().any(|a| a == "--dangerously-skip-permissions"),
275            "a resumed Claude session restores neither the permission mode \
276             nor the output format (RESEARCH Pitfall 1) — omitting this flag \
277             reintroduces a silent headless hang with nobody able to answer \
278             the resulting permission prompt: {args:?}"
279        );
280        assert!(
281            args.windows(2)
282                .any(|w| w[0] == "--output-format" && w[1] == "json"),
283            "the JSON output-format flag must also be re-passed explicitly, \
284             for the same reason as the permission-bypass flag: {args:?}"
285        );
286    }
287}