trusty-code 0.8.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! [`StdioRpcClient`]: a JSON-RPC 2.0 client speaking NDJSON over a spawned
//! `tcode serve --stdio` child's stdio pipes (#2060).
//!
//! Why: the CLI needs to drive the daemon's `session.*`/`task.*` methods
//! without reimplementing any of their logic. Spawning an ephemeral child
//! per invocation (rather than discovering/reusing a long-lived daemon) is
//! the simplest robust M1 approach the ticket calls for — no discovery file,
//! no port, no lifecycle management beyond this one process's lifetime.
//! What: [`StdioRpcClient::spawn`] launches the child; [`StdioRpcClient::call`]
//! sends a request and blocks (bounded by [`DEFAULT_CALL_TIMEOUT`]) for its
//! matching response, buffering any interleaved `session.event` notification
//! lines rather than dropping them; [`StdioRpcClient::next_notification`]
//! drains that buffer (or reads fresh lines, bounded by a caller-supplied
//! wait) for the streaming subcommands (`attach`, `run-task`).
//! [`classify_notification`]/[`build_request`] are pure helpers, unit tested
//! here without spawning a real process; the full spawn+wire round trip is
//! covered by `tests/cli_e2e.rs` against the real `tcode` binary.
//! Test: `cli_client::stdio::tests::*`.

use std::collections::VecDeque;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;

use serde_json::Value;
use tokio::io::{AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, ChildStdout};
use tokio::time::timeout;
use trusty_common::stdio_mcp_client::capped_line::{CappedLine, read_capped_line};
use trusty_common::stdio_mcp_client::{MAX_LINE_BYTES, is_response_to, log_field};
use trusty_mcp::Request;

use crate::events::SessionEventEnvelope;

/// How long [`StdioRpcClient::call`] waits for a matching response before
/// giving up.
///
/// Why: every method this client calls (`session.*`, `task.run`) is a fast,
/// synchronous handler by design — `task.run` in particular reserves its
/// execution slot and returns immediately rather than blocking on the LLM
/// run (see `task::protocol::task_run`'s docs) — so a real hang here means a
/// genuine daemon-side regression, not a slow-but-legitimate call. Generous
/// enough for a debug build under load, tight enough to fail fast.
pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(15);

/// Errors a CLI subcommand handler surfaces to the user (mapped onto a
/// nonzero exit code by the caller — this type carries no exit-code opinion
/// itself).
#[derive(Debug, thiserror::Error)]
pub enum RpcClientError {
    /// The child process could not be spawned at all (binary missing, not
    /// executable, etc.).
    #[error("failed to spawn `{0}`: {1}")]
    Spawn(String, #[source] std::io::Error),
    /// The child's stdout closed (process exited) before a full response
    /// arrived.
    #[error("daemon connection closed unexpectedly")]
    ConnectionClosed,
    /// A read/write against the child's stdio pipes failed.
    #[error("failed to read from daemon: {0}")]
    Io(#[source] std::io::Error),
    /// A line on the wire was not valid JSON, or lacked fields a response
    /// must have.
    #[error("malformed response from daemon: {0}")]
    MalformedResponse(String),
    /// The daemon's JSON-RPC error envelope for this call (verbatim: code +
    /// message + optional `data`).
    #[error("daemon returned an error ({code}): {message}")]
    Rpc {
        code: i32,
        message: String,
        data: Option<Value>,
    },
    /// No matching response arrived within [`DEFAULT_CALL_TIMEOUT`].
    #[error("timed out waiting for the daemon to respond")]
    Timeout,
    /// #10360: a stdout line passed [`MAX_LINE_BYTES`]. The line is dropped,
    /// never truncated; the next read resumes after its terminating newline.
    #[error("daemon sent a line over the {0}-byte cap; line discarded")]
    LineTooLong(usize),
}

/// The child-supplied `method` of `frame`, bounded for a log line.
///
/// Why: #10360 — the method string comes from the child; logged whole, one
/// frame can flood the log.
/// What: trusty-common's `log_field` cut (64 chars plus an `…(+N)` marker).
/// Test: `logged_method_truncates_long_method`.
fn logged_method(frame: &Value) -> String {
    log_field(frame.get("method").and_then(Value::as_str).unwrap_or(""))
}

/// Build the outgoing JSON-RPC 2.0 request envelope for one call.
///
/// Why: split out so `next_id` bookkeeping and wire-envelope construction
/// are each independently, purely testable — no process I/O involved.
/// What: `jsonrpc: "2.0"`, `id` as a JSON number, `method`/`params` verbatim.
/// Test: `tests::build_request_uses_2_0_and_given_id`.
fn build_request(id: i64, method: &str, params: Value) -> Request {
    Request {
        jsonrpc: Some("2.0".to_string()),
        id: Some(serde_json::json!(id)),
        method: method.to_string(),
        params: Some(params),
    }
}

/// Classify one already-JSON-parsed wire line as a `session.event`
/// notification, if it is one.
///
/// Why: the daemon interleaves request/response traffic with
/// server-initiated `session.event` notifications on the SAME connection
/// (see `session::registry`'s attach-forwarding docs); every line this
/// client reads must be checked against both shapes.
/// What: `Some(envelope)` when `value.method == "session.event"` and
/// `value.params` deserialises as a [`SessionEventEnvelope`]; `None`
/// otherwise (including a shape that claims to be a notification but fails
/// to parse — degrade silently rather than error, matching `Event`'s own
/// "unknown variants are ignored" forward-compatibility stance).
/// Test: `tests::classify_notification_recognises_session_event`,
/// `tests::classify_notification_ignores_other_shapes`.
fn classify_notification(value: &Value) -> Option<SessionEventEnvelope> {
    if value.get("method").and_then(|m| m.as_str()) != Some("session.event") {
        return None;
    }
    serde_json::from_value(value.get("params")?.clone()).ok()
}

/// A JSON-RPC 2.0 client over a spawned `tcode serve --stdio` child.
///
/// Why: see module docs.
/// What: owns the child + its stdin/stdout handles and a monotonic request
/// id counter; buffers notification lines encountered while a `call` is
/// awaiting its own response so nothing observed on the wire is ever
/// silently dropped.
/// Test: `tests::*` for the pure helpers; `tests/cli_e2e.rs` for the real
/// spawn + wire round trip.
pub struct StdioRpcClient {
    child: Child,
    stdin: ChildStdin,
    stdout: BufReader<ChildStdout>,
    /// #10360: bytes of a line not yet ended by `\n`, kept across a
    /// cancelled read. A new spawn starts empty, so no state outlives a child.
    line_buf: Vec<u8>,
    /// #10360: set after an oversize line; bytes up to the next `\n` drop.
    discard_line: bool,
    next_id: i64,
    pending_notifications: VecDeque<SessionEventEnvelope>,
}

impl StdioRpcClient {
    /// Spawn `<tcode_exe> serve --project <project> --stdio` and return a
    /// client wired to its stdio pipes.
    ///
    /// Why: `tcode_exe` is normally `std::env::current_exe()` — the CLI
    /// re-spawns ITSELF in daemon mode, per the ticket's "in-process spawn"
    /// requirement; passing it explicitly (rather than hardcoding
    /// `current_exe()` inside this function) keeps this module testable
    /// with an arbitrary binary path and avoids a hidden `std::env` read
    /// inside library code.
    /// What: `kill_on_drop(true)` so a CLI process that exits early (panic,
    /// early return) never leaks the child; the child's stderr is
    /// inherited so daemon-side log lines are visible to the operator
    /// without corrupting the stdout NDJSON framing this client reads.
    /// Test: `tests/cli_e2e.rs` (spawns the real binary).
    pub fn spawn(tcode_exe: &Path, project: &Path) -> Result<Self, RpcClientError> {
        let mut child = tokio::process::Command::new(tcode_exe)
            .arg("serve")
            .arg("--project")
            .arg(project)
            .arg("--stdio")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| RpcClientError::Spawn(tcode_exe.display().to_string(), e))?;
        let stdin = child.stdin.take().ok_or(RpcClientError::ConnectionClosed)?;
        let stdout = child
            .stdout
            .take()
            .ok_or(RpcClientError::ConnectionClosed)?;
        Ok(Self {
            child,
            stdin,
            stdout: BufReader::new(stdout),
            line_buf: Vec::new(),
            discard_line: false,
            next_id: 1,
            pending_notifications: VecDeque::new(),
        })
    }

    /// Call `method` with `params`, waiting for its matching response.
    ///
    /// Why: the request/response half of the protocol every non-streaming
    /// subcommand (`session.list`/`status`/`cancel`/`get_transcript`,
    /// `task.run`'s initial call) uses.
    /// What: writes one NDJSON request line, then reads lines until a true
    /// response (no `method`, has `result` or `error`, #10360) carries the
    /// SAME `id` — a server request with that id is skipped and logged; any `session.event` notification observed
    /// along the way is buffered (not dropped) for a later
    /// [`Self::next_notification`] call. A JSON-RPC error envelope becomes
    /// `Err(RpcClientError::Rpc)`; the whole call is bounded by
    /// [`DEFAULT_CALL_TIMEOUT`].
    /// Test: `tests::call_skips_server_request_with_matching_id`; end-to-end
    /// by `tests/cli_e2e.rs`.
    pub async fn call(&mut self, method: &str, params: Value) -> Result<Value, RpcClientError> {
        timeout(DEFAULT_CALL_TIMEOUT, self.call_inner(method, params))
            .await
            .map_err(|_| RpcClientError::Timeout)?
    }

    async fn call_inner(&mut self, method: &str, params: Value) -> Result<Value, RpcClientError> {
        let id = self.next_id;
        self.next_id += 1;
        let id_value = Value::from(id);
        let req = build_request(id, method, params);
        let mut line = serde_json::to_string(&req)
            .map_err(|e| RpcClientError::MalformedResponse(e.to_string()))?;
        line.push('\n');
        self.stdin
            .write_all(line.as_bytes())
            .await
            .map_err(RpcClientError::Io)?;
        self.stdin.flush().await.map_err(RpcClientError::Io)?;

        loop {
            let raw = self.read_raw_line().await?;
            let value: Value = serde_json::from_str(&raw)
                .map_err(|e| RpcClientError::MalformedResponse(format!("{e}: {raw}")))?;

            // #10360: only a true response (no `method`, has `result` or
            // `error`) to this id is the call's answer.
            if is_response_to(&value, &id_value) {
                if let Some(err) = value.get("error").filter(|e| !e.is_null()) {
                    return Err(RpcClientError::Rpc {
                        code: err.get("code").and_then(Value::as_i64).unwrap_or(0) as i32,
                        message: err
                            .get("message")
                            .and_then(|m| m.as_str())
                            .unwrap_or_default()
                            .to_string(),
                        data: err.get("data").cloned(),
                    });
                }
                return Ok(value.get("result").cloned().unwrap_or(Value::Null));
            }

            if let Some(envelope) = classify_notification(&value) {
                self.pending_notifications.push_back(envelope);
            } else if value.get("id") == Some(&id_value) {
                // #10360: a server request colliding with our id is an
                // anomaly, so warn; log id and method only, never the payload.
                let method = logged_method(&value);
                tracing::warn!(id, %method, "StdioRpcClient: skipping non-response frame with the awaited id");
            } else {
                // A response to an id we no longer care about; this client
                // only ever has one call in flight at a time.
                tracing::debug!(id, "StdioRpcClient: skipping non-matching frame");
            }
        }
    }

    /// Return the next observed `session.event` notification, waiting up to
    /// `wait` for a fresh one if none is already buffered.
    ///
    /// Why: the streaming subcommands (`attach`, `run-task`) poll this in a
    /// loop, printing each envelope as it arrives, until a terminal event or
    /// the user interrupts.
    /// What: drains [`Self::pending_notifications`] first (events observed
    /// while a previous `call` was still awaiting its own response); only
    /// reads fresh lines from the child when the buffer is empty.
    /// `Ok(None)` means "nothing arrived within `wait`" — NOT connection
    /// loss (that is `Err(ConnectionClosed)`) — callers should keep polling.
    /// Test: covered end-to-end by `tests/cli_e2e.rs`.
    pub async fn next_notification(
        &mut self,
        wait: Duration,
    ) -> Result<Option<SessionEventEnvelope>, RpcClientError> {
        if let Some(envelope) = self.pending_notifications.pop_front() {
            return Ok(Some(envelope));
        }
        match timeout(wait, self.read_raw_line()).await {
            Ok(Ok(raw)) => {
                let value: Value = serde_json::from_str(&raw)
                    .map_err(|e| RpcClientError::MalformedResponse(format!("{e}: {raw}")))?;
                Ok(classify_notification(&value))
            }
            Ok(Err(e)) => Err(e),
            Err(_) => Ok(None),
        }
    }

    /// Read one stdout line of at most [`MAX_LINE_BYTES`], newline stripped.
    ///
    /// Why: #10360 — `Lines::next_line` is not cancel-safe under the call
    /// timeout and buffers a line of any size.
    /// What: delegates to trusty-common's [`read_capped_line`]; an oversize
    /// line is `Err(LineTooLong)` and its tail is skipped on the next call.
    /// Test: `oversize_line_errors_with_line_too_long`,
    /// `oversize_line_errors_then_next_call_resyncs`.
    async fn read_raw_line(&mut self) -> Result<String, RpcClientError> {
        let read = read_capped_line(
            &mut self.stdout,
            &mut self.line_buf,
            &mut self.discard_line,
            MAX_LINE_BYTES,
        )
        .await
        .map_err(RpcClientError::Io)?;
        match read {
            CappedLine::Line(bytes) => {
                let line = String::from_utf8(bytes)
                    .map_err(|e| RpcClientError::MalformedResponse(e.to_string()))?;
                Ok(line.trim_end_matches(['\n', '\r']).to_string())
            }
            CappedLine::TooLong => Err(RpcClientError::LineTooLong(MAX_LINE_BYTES)),
            CappedLine::Eof => Err(RpcClientError::ConnectionClosed),
        }
    }

    /// Close stdin (EOF) and wait, bounded by `grace`, for the child to
    /// exit cleanly; force-kills it if it doesn't.
    ///
    /// Why: mirrors the daemon's own connection-safe-shutdown convention
    /// (issue #534) from the client side — the CLI should give its spawned
    /// child a real chance to drain before the process ends.
    /// What: dropping `stdin` signals EOF (the same trigger
    /// `serve::run_stdio` reacts to); force-kill is best-effort, matching
    /// every other bounded-shutdown path in this crate.
    /// Test: covered end-to-end by `tests/cli_e2e.rs`.
    pub async fn shutdown(mut self, grace: Duration) -> Result<(), RpcClientError> {
        drop(self.stdin);
        match timeout(grace, self.child.wait()).await {
            Ok(Ok(_status)) => Ok(()),
            Ok(Err(e)) => Err(RpcClientError::Io(e)),
            Err(_) => {
                let _ = self.child.start_kill();
                Ok(())
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// `build_request` must stamp `jsonrpc: "2.0"` and the exact given id.
    #[test]
    fn build_request_uses_2_0_and_given_id() {
        let req = build_request(7, "session.list", json!({}));
        assert_eq!(req.jsonrpc.as_deref(), Some("2.0"));
        assert_eq!(req.id, Some(json!(7)));
        assert_eq!(req.method, "session.list");
    }

    /// A well-formed `session.event` notification must parse into its
    /// envelope.
    #[test]
    fn classify_notification_recognises_session_event() {
        let line = json!({
            "method": "session.event",
            "params": {
                "session_id": "s-1",
                "seq": 1,
                "at": "2024-01-01T00:00:00Z",
                "kind": "session_started",
                "event": {"type": "session_started", "session_id": "s-1", "project": "p"},
            }
        });
        let envelope = classify_notification(&line).expect("must classify as a notification");
        assert_eq!(envelope.session_id, "s-1");
        assert_eq!(envelope.kind, "session_started");
    }

    /// A JSON-RPC response (has an `id`, no `method`) must NOT be classified
    /// as a notification.
    #[test]
    fn classify_notification_ignores_other_shapes() {
        let response = json!({"jsonrpc": "2.0", "id": 1, "result": {}});
        assert!(classify_notification(&response).is_none());

        let other_method = json!({"method": "ping", "params": {}});
        assert!(classify_notification(&other_method).is_none());

        let malformed_params = json!({"method": "session.event", "params": {"not": "an envelope"}});
        assert!(classify_notification(&malformed_params).is_none());
    }

    /// Why: #10360 — `call` accepted any frame whose id matched, so a server
    /// request carrying the awaited id became the call's result.
    /// What: a stand-in daemon script answers request 1 with a `roots/list`
    /// request (id 1), an `error` frame that also has `method`, then the real
    /// response; `call` must return the real result.
    /// Test: This test.
    #[tokio::test]
    #[cfg(unix)]
    async fn call_skips_server_request_with_matching_id() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().expect("tempdir");
        let exe = dir.path().join("fake-tcode");
        let script = "#!/bin/sh\nread -r l\n\
printf '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"roots/list\"}\\n'\n\
printf '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"x\",\"error\":{\"code\":-1,\"message\":\"m\"}}\\n'\n\
printf '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"answer\":\"real\"}}\\n'\n\
sleep 5\n";
        std::fs::write(&exe, script).expect("write script");
        std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).expect("chmod");
        let mut client = StdioRpcClient::spawn(&exe, dir.path()).expect("spawn");
        let result = client
            .call("session.list", json!({}))
            .await
            .expect("the real response");
        assert_eq!(result, json!({ "answer": "real" }));
    }

    /// #10360: the warn log keeps a bounded prefix of a child-supplied method.
    #[test]
    fn logged_method_truncates_long_method() {
        let frame = json!({"id": 1, "method": "m".repeat(10_000)});
        let shown = logged_method(&frame);
        assert_eq!(shown, format!("{}…(+9936)", "m".repeat(64)));
        assert_eq!(
            logged_method(&json!({"method": "roots/list"})),
            "roots/list"
        );
    }

    /// Spawn a fake `tcode` running `body` after `#!/bin/sh`.
    #[cfg(unix)]
    fn fake_child(body: &str) -> (tempfile::TempDir, StdioRpcClient) {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().expect("tempdir");
        let exe = dir.path().join("fake-tcode");
        std::fs::write(&exe, format!("#!/bin/sh\n{body}")).expect("write script");
        std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).expect("chmod");
        let client = StdioRpcClient::spawn(&exe, dir.path()).expect("spawn");
        (dir, client)
    }

    /// Shell that prints one newline-terminated line one byte over the cap.
    #[cfg(unix)]
    fn oversize_line_sh() -> String {
        format!(
            "head -c {} /dev/zero | tr '\\000' x; printf '\\n'\n",
            MAX_LINE_BYTES + 1
        )
    }

    /// #10360: a line over the cap fails the call with `LineTooLong`.
    #[tokio::test]
    #[cfg(unix)]
    async fn oversize_line_errors_with_line_too_long() {
        let (_dir, mut client) = fake_child(&format!("read -r l\n{}sleep 5\n", oversize_line_sh()));
        let err = client
            .call("session.list", json!({}))
            .await
            .expect_err("oversize");
        assert!(
            matches!(err, RpcClientError::LineTooLong(MAX_LINE_BYTES)),
            "got {err:?}"
        );
    }

    /// #10360: after an oversize line, the next call skips its tail and the
    /// stale id-1 reply, and returns its own response.
    #[tokio::test]
    #[cfg(unix)]
    async fn oversize_line_errors_then_next_call_resyncs() {
        let body = format!(
            "read -r l\n{}printf '{{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":1}}\\n'\n\
read -r l\nprintf '{{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{{\"ok\":true}}}}\\n'\nsleep 5\n",
            oversize_line_sh()
        );
        let (_dir, mut client) = fake_child(&body);
        let first = client.call("session.list", json!({})).await;
        assert!(
            matches!(first, Err(RpcClientError::LineTooLong(_))),
            "got {first:?}"
        );
        let second = client
            .call("session.list", json!({}))
            .await
            .expect("resynced");
        assert_eq!(second, json!({ "ok": true }));
    }
}