trusty-code 0.5.1

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! Process/protocol plumbing shared by `tests/session_e2e.rs`, (#2056)
//! `tests/task_e2e.rs`, (#2060) `tests/cli_e2e.rs`, and (#2062)
//! `tests/m1_cutline_e2e.rs`.
//!
//! Why: driving the REAL `tcode` binary over its real stdio/HTTP surface
//! needs a bit of scaffolding (spawn, NDJSON line I/O with timeouts, parse
//! helpers for responses vs. server-initiated notifications, SSE body
//! reading) that has nothing to do with the session-lifecycle assertions
//! themselves. Keeping it in `tests/support/mod.rs` (not a top-level
//! `tests/*.rs` file, so cargo does not treat it as its own test binary)
//! keeps every `*_e2e.rs` file readable as a pure black-box script.
//! What: [`StdioSession`] (spawn + NDJSON request/response/notification
//! I/O over real pipes — [`StdioSession::spawn_with_mock_llm`] additionally
//! roots the daemon at a given project dir and sets `TCODE_MOCK_LLM=echo`
//! for #2056's offline task-execution coverage), [`HttpDaemon`]/
//! [`spawn_http_daemon`]/[`spawn_http_daemon_with_env`] (#2062: the general
//! form taking a project root + extra env vars, e.g. the SAME mock-LLM
//! determinism over HTTP that STDIO already had) (spawn + discover the
//! bound HTTP address from stderr), [`find_response`]/[`find_session_event`]
//! (classify a raw NDJSON line), [`open_sse`]/[`read_sse_until`] (read one
//! never-terminating SSE connection in stages), [`parse_sse_frames`] (split
//! an SSE body into its JSON `data:` frames), and
//! [`assert_envelopes_contiguous`] (#2055: the shared seq/field-presence
//! check both the STDIO and HTTP/SSE e2e scenarios run against the SAME
//! `SessionEventEnvelope` shape).
//!
//! `#![allow(dead_code)]`: each `tests/*.rs` file compiles `mod support;` as
//! its OWN independent crate (cargo's per-integration-test-binary model), so
//! any helper one file doesn't use (e.g. `task_e2e.rs` never touches the
//! HTTP/SSE helpers `session_e2e.rs` needs) is flagged dead in THAT binary —
//! a false positive from splitting one shared file across two consumers,
//! not a real unused-code issue.
#![allow(dead_code)]

/// A stand-in trusty-memory daemon on a temp Unix socket (#6286).
pub mod uds_mock;

// Only `recall_content_e2e` needs these, and every other `tests/*.rs` binary
// compiles this file too — the same false positive `#![allow(dead_code)]`
// above exists for.
#[allow(unused_imports)]
pub use uds_mock::{MockMemoryDaemon, spawn as spawn_mock_memory_daemon};

use std::process::Stdio;
use std::time::Duration;

use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
use tokio::process::{Child, ChildStdin, ChildStdout};
use tokio::time::timeout;

/// Per-read/response timeout used throughout — generous enough for a debug
/// build under CI load, tight enough that a genuine protocol bug fails the
/// test in seconds rather than hanging the suite.
const WIRE_TIMEOUT: Duration = Duration::from_secs(5);

/// The ONLY way an integration test may name the `tcode` binary — a
/// `Command` for the freshly-built executable with ambient-daemon isolation
/// already installed (#3036, #3195).
///
/// Why: `trusty_common::search_index` refuses daemon writes when
/// `running_under_test_harness()` holds (#4255), but that reads the RUNNING
/// process's own path. `env!("CARGO_BIN_EXE_tcode")` is
/// `target/<profile>/tcode` — outside `deps/` — so a spawned child is
/// indistinguishable from a user's real invocation and warms its
/// `--project` into whatever trusty-search daemon it discovers. On a
/// developer machine that is the OPERATOR's live daemon, which registers the
/// test's `$TMPDIR/.tmpXXXXXX` fixture and writes `.gitignore` plus
/// `.trusty-search/{index.redb,hnsw.usearch,…}` back INSIDE the sandbox.
/// Those files land at an unpredictable moment — the warm-up is a detached
/// thread and the daemon walks the tree asynchronously — so they corrupt
/// whichever `run_task` before/after diff assertion happens to be open,
/// which is why a different test failed each run and why `--test-threads=1`
/// looked green. `spawn_inner`/`spawn_http_daemon_with_env` already set this
/// on the two children they own; the 28 call sites across 24 test functions
/// that built their own `Command` did not, and that residue is #3036/#3195.
/// What: `std::process::Command` for the binary, with
/// `TRUSTY_TEST_HARNESS=1` set so the child reports itself as a test process
/// and every `search_index` write is refused at the source. Pinning `HOME`
/// is NOT a substitute: macOS resolves the data dir through `NSFileManager`,
/// which ignores `$HOME`.
/// Test: `no_test_spawns_the_tcode_binary_unguarded` (in the lib suite)
/// fails if any test file names the binary directly instead of calling this.
pub fn tcode_command() -> std::process::Command {
    let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_tcode"));
    cmd.env(trusty_common::test_harness::FORCE_ENV, "1");
    cmd
}

/// Provision a throwaway project with `.claude/agents/{pm,python-engineer}.md`.
///
/// Why: shared by `tests/task_e2e.rs` (drives the daemon directly) and
/// (#2060) `tests/cli_e2e.rs` (drives the `tcode` CLI, which spawns its own
/// nested daemon) — both need the SAME minimal two-agent fixture for
/// `TCODE_MOCK_LLM=echo`'s scripted PM -> engineer delegation to resolve.
/// `.md` (not `.toml`) since #2897 Slice D retired the TOML agent loader —
/// `agents::discover_agents` only globs `*.md`.
pub fn project_with_agents() -> tempfile::TempDir {
    let tmp = tempfile::tempdir().expect("project tempdir");
    let agents = tmp.path().join(".claude").join("agents");
    std::fs::create_dir_all(&agents).expect("mkdir agents");
    std::fs::write(
        agents.join("pm.md"),
        "---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nYou are the PM. Delegate work to python-engineer.\n",
    )
    .expect("write pm.md");
    std::fs::write(
        agents.join("python-engineer.md"),
        "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\nYou are a Python engineer.\n",
    )
    .expect("write python-engineer.md");
    tmp
}

/// A fake `$HOME` containing `~/.claude/agents/{pm,python-engineer}.md`.
///
/// Why: a PROJECTLESS daemon has no project root to resolve `.claude/agents`
/// from, so `ProjectBinding::agents_dir` falls back to the USER-level
/// `~/.claude/agents`. Pointing the child's `$HOME` at a fixture lets the
/// projectless e2e resolve real agent configs hermetically — and exercises that
/// user-level fallback itself, rather than depending on whatever happens to be
/// in the developer's real home directory.
/// What: same two agent configs `project_with_agents` writes (`.md`, #2897
/// Slice D), rooted at `<tmp>/.claude/agents` and intended to be passed as
/// the child's `HOME`.
/// Test: used by `task_e2e::projectless_task_runs_end_to_end`.
pub fn home_with_user_level_agents() -> tempfile::TempDir {
    let tmp = tempfile::tempdir().expect("home tempdir");
    let agents = tmp.path().join(".claude").join("agents");
    std::fs::create_dir_all(&agents).expect("mkdir user-level agents");
    std::fs::write(
        agents.join("pm.md"),
        "---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nYou are the PM. Delegate work to python-engineer.\n",
    )
    .expect("write pm.md");
    std::fs::write(
        agents.join("python-engineer.md"),
        "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\nYou are a Python engineer.\n",
    )
    .expect("write python-engineer.md");
    tmp
}

/// A running `tcode serve --stdio` subprocess with line-buffered stdin/stdout.
///
/// Why: the STDIO half of the API-driven e2e coverage — every call in
/// `session_lifecycle_over_stdio` goes through this, writing/reading actual
/// NDJSON bytes over the child's real pipes.
pub struct StdioSession {
    child: Child,
    stdin: ChildStdin,
    lines: Lines<BufReader<ChildStdout>>,
}

impl StdioSession {
    /// Spawn the real `tcode` binary in `--stdio` mode.
    ///
    /// Why: `env!("CARGO_BIN_EXE_tcode")` resolves to the freshly-built
    /// binary for this exact test run — no separate install step needed.
    /// What: `--project .` (any existing directory works; `session.*` does
    /// not require a `.claude/` root), stdin/stdout piped, stderr discarded
    /// (logs aren't asserted on here), `kill_on_drop` so a panicking test
    /// still reaps the child instead of leaking a process.
    pub fn spawn() -> Self {
        Self::spawn_inner(Some(std::path::Path::new(".")), None, None, &[], &[])
    }

    /// Spawn `tcode serve --stdio` rooted at `project`, with
    /// `TCODE_MOCK_LLM=echo` set in the child's environment so `task.run`
    /// drives #2056's deterministic offline `EchoLlmClient` instead of
    /// requiring a live `OPENROUTER_API_KEY` — the mandatory offline
    /// black-box path for `tests/task_e2e.rs`.
    pub fn spawn_with_mock_llm(project: &std::path::Path) -> Self {
        Self::spawn_inner(
            Some(project),
            Some(trusty_code::task::mock_llm::MOCK_LLM_ECHO),
            None,
            &[],
            &[],
        )
    }

    /// Spawn `tcode serve --stdio` rooted at `project`, with `TCODE_MOCK_LLM`
    /// set to `mock_llm_value` (DOC-39 AC-13).
    ///
    /// Why: [`Self::spawn_with_mock_llm`] hardcodes
    /// `trusty_code::task::mock_llm::MOCK_LLM_ECHO`'s fixed single-delegation
    /// script, which cannot exercise a fan-out to two SAME-named delegated
    /// agents — the acceptance proof `tests/agent_id_e2e.rs` needs. This is
    /// the general form that lets a caller select any registered mock-LLM
    /// variant (e.g. `trusty_code::task::mock_llm::MOCK_LLM_ECHO_FANOUT`)
    /// while keeping `spawn_with_mock_llm` itself unchanged for every other
    /// e2e file.
    /// Test: `agent_id_e2e::fanned_out_same_named_delegations_get_distinct_agent_ids_over_the_wire`.
    pub fn spawn_with_mock_llm_variant(project: &std::path::Path, mock_llm_value: &str) -> Self {
        Self::spawn_inner(Some(project), Some(mock_llm_value), None, &[], &[])
    }

    /// Like [`Self::spawn_with_mock_llm_variant`], additionally setting
    /// `envs` in the child's environment (DOC-39 Slice C).
    ///
    /// Why: `tests/recall_content_e2e.rs` needs to point the daemon's
    /// `recall_session` tool at a MOCK trusty-memory backend (via
    /// `TRUSTY_MEMORY_SOCKET`,
    /// `trusty_common::memory_rpc::TRUSTY_MEMORY_SOCKET_ENV`)
    /// rather than a real daemon — no prior e2e scenario in this crate needed
    /// to override an env var beyond the mock-LLM selector, so this is the
    /// general form that adds that capability without touching any other
    /// `spawn_*` caller.
    /// What: identical to `spawn_with_mock_llm_variant`, plus every
    /// `(key, value)` pair in `envs` set on the child.
    /// Test: `recall_content_e2e::held_back_recall_result_carries_its_text_and_run_id_over_the_wire`.
    pub fn spawn_with_mock_llm_variant_and_env(
        project: &std::path::Path,
        mock_llm_value: &str,
        envs: &[(&str, &str)],
    ) -> Self {
        Self::spawn_inner(Some(project), Some(mock_llm_value), None, envs, &[])
    }

    /// Like [`Self::spawn_with_mock_llm_variant`] but also sets `extra_envs`
    /// in the child's environment (DOC-39 Slice B).
    ///
    /// Why: `tests/search_hits_e2e.rs` needs the spawned `tcode` daemon to
    /// resolve `trusty-search` (the binary `tools::trusty_search` spawns) to
    /// a FAKE MCP server script instead of a real trusty-search install —
    /// the only seam for that is prepending a fixture directory to the
    /// child's `PATH`. No other e2e scenario needs extra env vars, so this
    /// stays a separate opt-in form rather than growing every existing call
    /// site's arity.
    /// Test: `search_hits_e2e::search_code_hit_paths_and_scores_reach_the_search_performed_event`.
    pub fn spawn_with_mock_llm_variant_and_envs(
        project: &std::path::Path,
        mock_llm_value: &str,
        extra_envs: &[(&str, &str)],
    ) -> Self {
        Self::spawn_inner(Some(project), Some(mock_llm_value), None, &[], extra_envs)
    }

    /// Spawn `tcode serve --stdio` with NO `--project` — a PROJECTLESS daemon.
    ///
    /// Why: this is the state screen 7a renders and the one that was previously
    /// impossible to even start: `--project` was a required `PathBuf`. That the
    /// daemon accepts this invocation at all is half of what the projectless
    /// e2e proves.
    /// What: omits `--project` entirely and points the child's `HOME` at
    /// `home` so the user-level `~/.claude/agents` fallback resolves the
    /// fixture's agent configs hermetically. `TCODE_MOCK_LLM=echo` as usual.
    /// Test: `task_e2e::projectless_task_runs_end_to_end`.
    pub fn spawn_projectless_with_mock_llm(home: &std::path::Path) -> Self {
        Self::spawn_inner(
            None,
            Some(trusty_code::task::mock_llm::MOCK_LLM_ECHO),
            Some(home),
            &[],
            &[],
        )
    }

    fn spawn_inner(
        project: Option<&std::path::Path>,
        mock_llm_value: Option<&str>,
        home: Option<&std::path::Path>,
        envs: &[(&str, &str)],
        extra_envs: &[(&str, &str)],
    ) -> Self {
        let mut cmd = tokio::process::Command::new(env!("CARGO_BIN_EXE_tcode"));
        cmd.arg("serve");
        // #4255: the child is `target/<profile>/tcode`, not a `deps/` test
        // binary, so it cannot detect the harness from its own path — and
        // `tcode serve` warms its working project into whatever trusty-search
        // daemon it discovers. Without this the e2e suite registered one
        // `$TMPDIR/.tmpXXXXXX` fixture root per target in the operator's live
        // registry. Setting `HOME` is not enough: on macOS `data_local_dir()`
        // goes through NSFileManager, which ignores `$HOME`.
        cmd.env(trusty_common::test_harness::FORCE_ENV, "1");
        for (key, value) in extra_envs {
            cmd.env(key, value);
        }
        if let Some(project) = project {
            cmd.arg("--project").arg(project);
        }
        cmd.arg("--stdio");
        if let Some(home) = home {
            cmd.env("HOME", home);
        }
        if let Some(value) = mock_llm_value {
            cmd.env(trusty_code::task::mock_llm::MOCK_LLM_ENV, value);
        }
        for (key, value) in envs {
            cmd.env(key, value);
        }
        let mut child = cmd
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .expect("spawn `tcode serve --stdio`");
        let stdin = child.stdin.take().expect("child stdin");
        let stdout = child.stdout.take().expect("child stdout");
        let lines = BufReader::new(stdout).lines();
        Self {
            child,
            stdin,
            lines,
        }
    }

    /// Write one JSON-RPC 2.0 request line; does not read a response.
    ///
    /// Why: `session.send`'s response and its streamed notification can
    /// arrive in either order on the wire (see `session_e2e.rs`), so that
    /// call site needs to write first and read separately via
    /// `read_lines`, rather than going through [`Self::call`].
    pub async fn write_request(&mut self, id: i64, method: &str, params: Value) {
        let req = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
        let mut line = serde_json::to_string(&req).expect("serialise request");
        line.push('\n');
        self.stdin
            .write_all(line.as_bytes())
            .await
            .expect("write request line");
        self.stdin.flush().await.expect("flush stdin");
    }

    /// Write a request, then read lines (skipping any interleaved
    /// notifications) until the matching response arrives.
    ///
    /// Why: the common case — one request, one response, no observable
    /// side-stream traffic to correlate.
    /// What: panics after [`WIRE_TIMEOUT`] if no matching response shows up.
    pub async fn call(&mut self, id: i64, method: &str, params: Value) -> Value {
        self.write_request(id, method, params).await;
        timeout(WIRE_TIMEOUT, async {
            loop {
                let line = self.next_line().await;
                if let Some(resp) = find_response(&line, id) {
                    return resp;
                }
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for a response to id={id} ({method})"))
    }

    /// Read raw NDJSON lines until `max_lines` have been collected or
    /// [`WIRE_TIMEOUT`] elapses, whichever comes first.
    ///
    /// Why: `session.send`'s test needs to observe BOTH its response and a
    /// streamed notification, which may arrive in either order — reading a
    /// bounded batch and classifying each line afterward (via
    /// [`find_response`]/[`find_session_event`]) is simpler and more robust
    /// than trying to predict the interleaving.
    pub async fn read_lines(&mut self, max_lines: usize) -> Vec<String> {
        let mut collected = Vec::new();
        let _ = timeout(WIRE_TIMEOUT, async {
            while collected.len() < max_lines {
                collected.push(self.next_line().await);
            }
        })
        .await;
        collected
    }

    /// Read exactly one NDJSON line, panicking on EOF or an I/O error.
    async fn next_line(&mut self) -> String {
        self.lines
            .next_line()
            .await
            .expect("read stdout line")
            .expect("tcode serve --stdio closed stdout unexpectedly")
    }

    /// Close stdin (EOF) and assert the daemon exits cleanly.
    ///
    /// Why: proves the STDIO transport's documented EOF-triggers-shutdown
    /// behaviour end-to-end, not just via the offline `transport::tests`.
    pub async fn shutdown_via_eof_and_assert_clean_exit(mut self) {
        drop(self.stdin);
        let status = timeout(WIRE_TIMEOUT, self.child.wait())
            .await
            .expect("timed out waiting for the daemon to exit after stdin EOF")
            .expect("wait() failed");
        assert!(
            status.success(),
            "daemon must exit 0 on stdin EOF, got {status:?}"
        );
    }
}

/// A running `tcode serve --http` subprocess plus its discovered base URL and
/// the credential every request to it must carry.
pub struct HttpDaemon {
    child: Child,
    pub base_url: String,
    /// #5439: the daemon's local-client credential, read from the `0600` file
    /// `run_http` wrote into [`Self::data_dir`] before binding. Every route but
    /// `/health` requires it.
    pub token: String,
    /// The daemon's own isolated data directory. Held so it outlives the
    /// daemon; dropping it removes the tree.
    pub data_dir: tempfile::TempDir,
}

/// Spawn `tcode serve --http --port 0` and discover its ephemeral bound
/// address from stderr.
///
/// Why: `--port 0` avoids test-suite port collisions; the daemon logs the
/// real bound `host:port` to stderr (never stdout) on startup, which this
/// helper parses.
/// What: thin wrapper over [`spawn_http_daemon_with_env`] rooted at `.`
/// with no extra env vars — the shape every pre-#2062 caller
/// (`tests/session_e2e.rs`) needs.
pub async fn spawn_http_daemon() -> HttpDaemon {
    spawn_http_daemon_with_env(std::path::Path::new("."), &[]).await
}

/// Spawn `tcode serve --http --port 0` rooted at `project`, with `envs` set
/// in the child's environment, discovering its ephemeral bound address from
/// stderr.
///
/// Why: (#2062) the M1 milestone suite's HTTP scenario needs the SAME
/// `TCODE_MOCK_LLM=echo` offline determinism the STDIO scenario gets from
/// `StdioSession::spawn_with_mock_llm` — `spawn_http_daemon`'s original
/// zero-argument form couldn't express that, so this is the general form
/// both now share.
/// What: `--project` argument path and `env(...)`-set every `(key, value)`
/// pair in `envs`; otherwise identical to `spawn_http_daemon`'s original
/// stderr address-discovery + drain-for-life behaviour.
pub async fn spawn_http_daemon_with_env(
    project: &std::path::Path,
    envs: &[(&str, &str)],
) -> HttpDaemon {
    let mut cmd = tokio::process::Command::new(env!("CARGO_BIN_EXE_tcode"));
    cmd.arg("serve")
        .arg("--project")
        .arg(project)
        .args(["--http", "--port", "0"]);
    // #4255: same reason as `spawn_inner` — the spawned `tcode` cannot detect
    // the test harness from its own path, and would warm `project` (a
    // `tempfile` fixture) into the operator's live trusty-search registry.
    cmd.env(trusty_common::test_harness::FORCE_ENV, "1");
    // #5439: give every spawned daemon its OWN data directory. Without this
    // they all mint into the operator's real `~/…/trusty-code/auth_token`, so
    // a test run rewrites a live daemon's credential and two concurrent test
    // daemons race each other for it. The isolated tree is also where this
    // helper reads the token from below, which is what makes the read
    // deterministic rather than a lookup in whatever the parent process
    // happens to see.
    let data_dir = tempfile::tempdir().expect("daemon data dir");
    cmd.env(
        trusty_common::data_dir::DATA_DIR_OVERRIDE_ENV,
        data_dir.path(),
    );
    // A caller's own env wins — `cli_e2e` sets its own override for tests that
    // assert on the discovery file's location.
    for (key, value) in envs {
        cmd.env(key, value);
    }
    let mut child = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .kill_on_drop(true)
        .spawn()
        .expect("spawn `tcode serve --http`");

    let stderr = child.stderr.take().expect("child stderr");
    let mut lines = BufReader::new(stderr).lines();

    let base_url = timeout(WIRE_TIMEOUT, async {
        loop {
            let line = lines
                .next_line()
                .await
                .expect("read stderr")
                .expect("tcode serve --http closed stderr before reporting its address");
            if let Some(addr) = line.split("listening on http://").nth(1) {
                return format!("http://{}", addr.trim());
            }
        }
    })
    .await
    .expect("timed out waiting for the daemon to report its bound address");

    // Keep draining stderr for the rest of the daemon's life so the pipe
    // never fills and blocks it; log content isn't asserted on beyond the
    // startup line already consumed above.
    tokio::spawn(async move { while let Ok(Some(_)) = lines.next_line().await {} });

    // #5439: the daemon established this before it printed the line above, so
    // by now the file exists — in the isolated tree, not the operator's. Read
    // through the same entry point a real client uses, so a test can never
    // authenticate by a path production does not have.
    let token_path = data_dir
        .path()
        .join(trusty_code::serve::http::TOKEN_APP_NAME)
        .join(trusty_common::daemon_token::TOKEN_FILENAME);
    let token = trusty_common::daemon_token::read_token_at(&token_path).unwrap_or_else(|| {
        panic!(
            "`tcode serve --http` must write its credential to {} before it binds",
            token_path.display()
        )
    });

    HttpDaemon {
        child,
        base_url,
        token,
        data_dir,
    }
}

impl HttpDaemon {
    /// A `reqwest::Client` that carries this daemon's credential on every
    /// request.
    ///
    /// Why (#5439): every route but `/health` requires the credential, so a
    /// bare `reqwest::Client::new()` now gets `401` and the test reports a
    /// decode failure rather than the behaviour it meant to assert. Attaching
    /// it as a DEFAULT header means an added request site cannot forget it.
    pub fn client(&self) -> reqwest::Client {
        let mut auth = reqwest::header::HeaderValue::from_str(&format!("Bearer {}", self.token))
            .expect("credential is header-safe");
        auth.set_sensitive(true);
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(reqwest::header::AUTHORIZATION, auth);
        reqwest::Client::builder()
            .default_headers(headers)
            .build()
            .expect("build credentialed test client")
    }

    /// Send SIGTERM and assert the daemon exits cleanly (issue #534
    /// connection-safe daemon-restart convention, exercised here against
    /// the real process rather than only `trusty_common::shutdown_signal`'s
    /// offline unit tests).
    pub async fn shutdown_via_sigterm_and_assert_clean_exit(mut self) {
        let pid = self.child.id().expect("child has a pid") as i32;
        // Safety: `kill(2)` with a valid pid and the standard termination
        // signal; no memory is touched, only a signal is delivered.
        unsafe {
            libc::kill(pid, libc::SIGTERM);
        }
        let status = timeout(WIRE_TIMEOUT, self.child.wait())
            .await
            .expect("timed out waiting for the daemon to exit after SIGTERM")
            .expect("wait() failed");
        assert!(
            status.success(),
            "daemon must exit 0 after graceful SIGTERM shutdown, got {status:?}"
        );
    }
}

/// Parse `line` as JSON and return it if it's a response whose `id` matches.
///
/// Why: `session.send`'s response and a streamed notification can arrive
/// interleaved with each other (and, in principle, with earlier
/// still-in-flight lines); this is the "is this line the response I'm
/// waiting for" classifier.
pub fn find_response(line: &str, id: i64) -> Option<Value> {
    let v: Value = serde_json::from_str(line).ok()?;
    if v.get("id").and_then(|i| i.as_i64()) == Some(id) {
        Some(v)
    } else {
        None
    }
}

/// Parse `line` as JSON and return its `params` if it's a `session.event`
/// notification for `session_id`.
///
/// Why: the classifier for the OTHER half of an interleaved
/// response/notification pair — a server-initiated notification has no
/// `id`, a `method` field, and this crate's wire shape nests the actual
/// `crate::events::Event` under `params.event`.
pub fn find_session_event(line: &str, session_id: &str) -> Option<Value> {
    let v: Value = serde_json::from_str(line).ok()?;
    if v.get("method").and_then(|m| m.as_str()) == Some("session.event")
        && v["params"]["session_id"].as_str() == Some(session_id)
    {
        Some(v["params"].clone())
    } else {
        None
    }
}

/// Drive `task.run` -> `session.attach` -> read-until-`session_done` over an
/// already-spawned [`StdioSession`], returning the session id once the run
/// has reached a terminal state.
///
/// Why: (#2058) both `tests/task_e2e.rs`'s live-tool-event assertions and its
/// `session.get_transcript` assertions need "run a task to completion" as a
/// precondition — `get_transcript` in particular must not be called before
/// `task::executor::run_and_record` has stored the outcome via
/// `SessionRegistry::set_run_outcome`, or the transcript would still be
/// empty. Factored out so both call sites share the exact same
/// read-until-terminal logic rather than copy-pasting the polling loop.
/// What: calls `task.run` (id 1) and `session.attach` (id 2) — these two ids
/// are reserved by this helper, so callers must start their OWN subsequent
/// request ids at 3 — then reads NDJSON lines, classifying each as a
/// `session.event` for this session, until `session_done` is observed (or
/// panics after 20 read rounds, mirroring the bounded wait every other e2e
/// polling loop in this crate uses). Returns the session id.
pub async fn run_task_to_completion(daemon: &mut StdioSession, task_description: &str) -> String {
    let run_resp = daemon
        .call(1, "task.run", json!({"task_description": task_description}))
        .await;
    assert!(run_resp["error"].is_null(), "task.run failed: {run_resp}");
    let session_id = run_resp["result"]["session_id"]
        .as_str()
        .expect("task.run must return a session_id")
        .to_string();

    let attach_resp = daemon
        .call(2, "session.attach", json!({"session_id": session_id}))
        .await;
    assert!(
        attach_resp["error"].is_null(),
        "attach failed: {attach_resp}"
    );
    let mut kinds: Vec<String> = attach_resp["result"]["events"]
        .as_array()
        .expect("attach must return a replay events array")
        .iter()
        .map(|e| {
            e["kind"]
                .as_str()
                .expect("kind must be a string")
                .to_string()
        })
        .collect();

    let mut iterations = 0;
    while !kinds.iter().any(|k| k == "session_done") {
        iterations += 1;
        assert!(
            iterations < 20,
            "gave up waiting for session_done after {iterations} read rounds; kinds so far: {kinds:?}"
        );
        let lines = daemon.read_lines(20).await;
        assert!(
            !lines.is_empty(),
            "timed out waiting for more events; kinds so far: {kinds:?}"
        );
        for line in &lines {
            if let Some(envelope) = find_session_event(line, &session_id) {
                kinds.push(
                    envelope["kind"]
                        .as_str()
                        .expect("kind must be a string")
                        .to_string(),
                );
            }
        }
    }

    session_id
}

/// Open `url` as a Server-Sent Events GET, asserting a successful status.
///
/// Why: the #2055 replay->live continuity check needs to read ONE SSE
/// connection in two stages (first the replay burst, then a live event
/// published while still connected) — unlike [`http_get_prefix`], which
/// opens a fresh connection per call and only proves replay content, not
/// continuity within a single stream.
/// What: returns the live `reqwest::Response`; pair with
/// [`read_sse_until`] to pull further chunks from the SAME connection.
pub async fn open_sse(client: &reqwest::Client, url: &str) -> reqwest::Response {
    let resp = client.get(url).send().await.expect("GET request");
    assert!(
        resp.status().is_success(),
        "GET {url} returned {}",
        resp.status()
    );
    resp
}

/// Read more chunks from `resp` into `buffer` until it contains
/// `until_substr` or `total_timeout` elapses.
///
/// Why: paired with [`open_sse`] so a test can read a SINGLE SSE connection
/// in stages (replay, then a later live event) instead of opening a fresh
/// GET per stage — which is what actually proves replay -> live continuity
/// on one stream, per the #2055 requirement.
/// What: appends to `buffer` in place (so a second call continues from
/// where the first left off) via `Response::chunk()` — no `Stream`/`Bytes`
/// naming needed at the call site.
pub async fn read_sse_until(
    resp: &mut reqwest::Response,
    buffer: &mut Vec<u8>,
    until_substr: &str,
    total_timeout: Duration,
) {
    if String::from_utf8_lossy(buffer).contains(until_substr) {
        return;
    }
    let read = timeout(total_timeout, async {
        while !String::from_utf8_lossy(buffer).contains(until_substr) {
            match resp.chunk().await {
                Ok(Some(chunk)) => buffer.extend_from_slice(&chunk),
                _ => break,
            }
        }
    })
    .await;
    assert!(
        read.is_ok(),
        "timed out waiting for {until_substr:?} in the SSE stream"
    );
}

/// Parse an SSE body (one or more `data: {...}` lines, possibly interleaved
/// with blank lines or `:`-comment keep-alives) into the JSON objects it
/// carries.
///
/// Why: the #2055 envelope assertions need to inspect individual event
/// objects (`seq`, `kind`, `session_id`, ...), not just substring-match the
/// raw SSE text the way [`http_get_prefix`]'s callers otherwise would.
/// What: for each line starting with `data:`, strips the prefix and parses
/// the remainder as JSON; lines that aren't `data:` or don't parse are
/// skipped (SSE comment lines, a partially-read trailing frame at the
/// prefix's read boundary).
pub fn parse_sse_frames(text: &str) -> Vec<Value> {
    text.lines()
        .filter_map(|line| line.strip_prefix("data:"))
        .filter_map(|rest| serde_json::from_str::<Value>(rest.trim()).ok())
        .collect()
}

/// Assert that `envelopes` (in receipt order) each carry every
/// `SessionEventEnvelope` field and form ONE gap-free, strictly increasing
/// `seq` sequence; returns `(first_seq, last_seq)`.
///
/// Why: the #2055 correctness property this whole e2e suite exists to
/// prove — factored out so the STDIO and HTTP/SSE scenarios run the exact
/// same check against their respective wire representations of the same
/// envelope shape.
/// What: panics with the offending envelope on the first missing field or
/// any `seq` that isn't exactly `previous + 1`. Panics on empty input too —
/// every call site here always has at least the replay burst to check.
pub fn assert_envelopes_contiguous(envelopes: &[Value]) -> (u64, u64) {
    assert!(
        !envelopes.is_empty(),
        "expected at least one envelope to check"
    );
    let mut previous: Option<u64> = None;
    for envelope in envelopes {
        for field in ["session_id", "seq", "at", "kind", "event"] {
            assert!(
                envelope.get(field).is_some(),
                "envelope missing required field {field:?}: {envelope}"
            );
        }
        let seq = envelope["seq"].as_u64().expect("seq must be a u64");
        if let Some(prev) = previous {
            assert_eq!(
                seq,
                prev + 1,
                "seq must increase by exactly 1 with no gaps or duplicates: {envelope}"
            );
        }
        previous = Some(seq);
    }
    let first = envelopes[0]["seq"].as_u64().unwrap();
    let last = envelopes[envelopes.len() - 1]["seq"].as_u64().unwrap();
    (first, last)
}