trusty_code/ipc/mod.rs
1//! NDJSON IPC protocol for PM <-> sub-agent communication.
2//!
3//! Why: Provides a minimal, newline-delimited JSON protocol so the PM and
4//! sub-agent subprocesses can exchange structured messages over stdin/stdout
5//! without framing ambiguity.
6//! What: Defines the `IpcMessage` enum (Task / Result / Error), the
7//! `HistoryMessage` wire type for conversation history, and helpers to
8//! serialize to/from single-line JSON.
9//! Test: Round-trip each variant through `serialize_message` + `parse_message`
10//! and assert equality (see unit tests below).
11
12use std::path::PathBuf;
13
14use anyhow::{Context, Result};
15use serde::{Deserialize, Serialize};
16
17use crate::perf::TokenUsage;
18
19/// Simple `{role, content}` serializable form used over IPC.
20///
21/// Why: The LLM-client typed message format (e.g. `ChatCompletionRequestMessage`
22/// from async-openai) has a complex shape that does not round-trip cleanly
23/// through JSON IPC. A tiny `HistoryMessage` is trivially serde-friendly and
24/// sufficient to rebuild the typed messages on the sub-agent side. This type
25/// lives in the `ipc` module because it IS an IPC wire type — it only ever
26/// exists to cross the PM→sub-agent boundary.
27/// What: Pair of `role` ("user"|"assistant"|"system") and `content` strings.
28/// Test: See `ipc::tests` round-trips.
29#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
30pub struct HistoryMessage {
31 pub role: String,
32 pub content: String,
33}
34
35impl HistoryMessage {
36 /// Construct a `HistoryMessage` with role=`"user"`.
37 ///
38 /// Why: Callers serialize a dialog turn over IPC without touching the
39 /// role string directly, avoiding typos.
40 /// What: Plain struct literal with `role="user"`.
41 /// Test: Indirectly via IPC round-trip tests.
42 pub fn user(content: impl Into<String>) -> Self {
43 Self {
44 role: "user".to_string(),
45 content: content.into(),
46 }
47 }
48
49 /// Construct a `HistoryMessage` with role=`"assistant"`.
50 ///
51 /// Why: Symmetric with `user` — keeps IPC construction declarative.
52 /// What: Plain struct literal with `role="assistant"`.
53 /// Test: Indirectly via IPC round-trip tests.
54 pub fn assistant(content: impl Into<String>) -> Self {
55 Self {
56 role: "assistant".to_string(),
57 content: content.into(),
58 }
59 }
60}
61
62/// A single IPC message exchanged between the PM and a sub-agent.
63///
64/// Why: Discriminated union keeps message handling type-safe while serializing
65/// to a compact single-line JSON form suitable for NDJSON framing.
66/// What: Three variants — Task (PM -> sub), Result (sub -> PM success),
67/// Error (sub -> PM failure). All carry a correlation `id`.
68/// Test: Serialize each variant, assert the `"type"` tag matches; parse back
69/// and assert structural equality.
70#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
71#[serde(tag = "type", rename_all = "snake_case")]
72pub enum IpcMessage {
73 /// PM -> sub-agent: new task to execute.
74 ///
75 /// `history`, when present, carries prior user/assistant turns that the
76 /// sub-agent should prepend to its chat request. `session_reset`, when
77 /// true, instructs the sub-agent to behave as if no history exists; its
78 /// primary use is flushing stale state mid-run without round-tripping
79 /// through the PM. Both fields are optional and omitted from the wire when
80 /// absent so existing tools and older agents keep working unchanged.
81 Task {
82 id: String,
83 task: String,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 history: Option<Vec<HistoryMessage>>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 session_reset: Option<bool>,
88 },
89 /// Sub-agent -> PM: successful result.
90 ///
91 /// `content` is the full agent output. `summary` is an optional concise
92 /// summary (~200-500 words) that downstream workflow phases substitute via
93 /// `{{phase_name}}` templates — keeping prompt sizes bounded. Missing =
94 /// no summary extracted.
95 Result {
96 id: String,
97 content: String,
98 #[serde(default, skip_serializing_if = "Option::is_none")]
99 summary: Option<String>,
100 /// Aggregated LLM token usage for this task.
101 ///
102 /// Why: Sub-agents own the LLM round-trips; PM/WorkflowEngine needs
103 /// the counts to produce per-phase performance records. Optional for
104 /// backward compat with tool-only (non-LLM) results.
105 /// What: `TokenUsage` with Anthropic cache fields; serializes under
106 /// the `"usage"` key and is omitted when absent.
107 /// Test: `ipc::tests::result_with_usage_roundtrip`.
108 #[serde(default, skip_serializing_if = "Option::is_none")]
109 usage: Option<TokenUsage>,
110 status: String,
111 },
112 /// Sub-agent -> PM: execution failure.
113 Error {
114 id: String,
115 error: String,
116 status: String,
117 },
118}
119
120impl IpcMessage {
121 /// Convenience constructor for a Task message with a fresh UUIDv4 id.
122 ///
123 /// Why: Callers should not have to generate UUIDs manually.
124 /// What: Wraps `uuid::Uuid::new_v4()` and builds a minimal Task variant.
125 /// Test: `ipc::tests::task_roundtrip`.
126 pub fn new_task(task: impl Into<String>) -> Self {
127 IpcMessage::Task {
128 id: uuid::Uuid::new_v4().to_string(),
129 task: task.into(),
130 history: None,
131 session_reset: None,
132 }
133 }
134
135 /// Convenience constructor for a Task carrying prior session history.
136 ///
137 /// Why: Persistent-session agents need their caller to forward the
138 /// accumulated user/assistant turns so the sub-agent can rebuild context
139 /// in a fresh process.
140 /// What: Same as `new_task` but sets `history` when non-empty.
141 /// Test: `ipc::tests::task_with_history_roundtrip`.
142 #[allow(dead_code)]
143 pub fn new_task_with_history(task: impl Into<String>, history: Vec<HistoryMessage>) -> Self {
144 IpcMessage::Task {
145 id: uuid::Uuid::new_v4().to_string(),
146 task: task.into(),
147 history: if history.is_empty() {
148 None
149 } else {
150 Some(history)
151 },
152 session_reset: None,
153 }
154 }
155
156 /// Convenience constructor for a success Result message (no summary).
157 ///
158 /// Why: Most test helpers only need content + status.
159 /// What: Returns a `Result` variant with `summary=None` and `usage=None`.
160 /// Test: `ipc::tests::result_roundtrip`.
161 #[allow(dead_code)]
162 pub fn new_result(id: impl Into<String>, content: impl Into<String>) -> Self {
163 IpcMessage::Result {
164 id: id.into(),
165 content: content.into(),
166 summary: None,
167 usage: None,
168 status: "success".into(),
169 }
170 }
171
172 /// Convenience constructor for a success Result message with a summary.
173 ///
174 /// Why: Sub-agents producing output for downstream phases should emit a
175 /// concise summary so prompt context doesn't balloon.
176 /// What: Returns a `Result` variant with both `content` and `summary` set.
177 /// Test: `ipc::tests::result_with_summary_roundtrip`.
178 #[allow(dead_code)]
179 pub fn new_result_with_summary(
180 id: impl Into<String>,
181 content: impl Into<String>,
182 summary: Option<String>,
183 ) -> Self {
184 IpcMessage::Result {
185 id: id.into(),
186 content: content.into(),
187 summary,
188 usage: None,
189 status: "success".into(),
190 }
191 }
192
193 /// Constructor for a success `Result` message with optional summary and
194 /// aggregated token usage.
195 ///
196 /// Why: Sub-agents aggregate per-turn `TokenUsage` across the whole task
197 /// and bubble it up via IPC so `WorkflowEngine` can build the per-phase
198 /// performance record.
199 /// What: Returns a `Result` variant populating all three optional fields.
200 /// Test: `ipc::tests::result_with_usage_roundtrip`.
201 pub fn new_result_full(
202 id: impl Into<String>,
203 content: impl Into<String>,
204 summary: Option<String>,
205 usage: Option<TokenUsage>,
206 ) -> Self {
207 IpcMessage::Result {
208 id: id.into(),
209 content: content.into(),
210 summary,
211 usage,
212 status: "success".into(),
213 }
214 }
215
216 /// Convenience constructor for an Error message.
217 ///
218 /// Why: Keeps error construction consistent at call sites.
219 /// What: Returns an `Error` variant with `status="error"`.
220 /// Test: `ipc::tests::error_roundtrip`.
221 pub fn new_error(id: impl Into<String>, error: impl Into<String>) -> Self {
222 IpcMessage::Error {
223 id: id.into(),
224 error: error.into(),
225 status: "error".into(),
226 }
227 }
228}
229
230/// Serialize an IpcMessage to a single NDJSON line (trailing `\n`).
231///
232/// Why: Callers write one message per line to the IPC pipe; centralizing the
233/// newline here prevents framing bugs at call sites.
234/// What: Returns `"{...json...}\n"`.
235/// Test: Assert output ends with `\n` and contains no embedded newlines in
236/// the JSON prefix.
237pub fn serialize_message(msg: &IpcMessage) -> Result<String> {
238 let mut s = serde_json::to_string(msg).context("failed to serialize IpcMessage")?;
239 s.push('\n');
240 Ok(s)
241}
242
243/// Parse a single NDJSON line into an IpcMessage.
244///
245/// Why: Callers read one line at a time from the IPC pipe; this helper
246/// strips any trailing newline and decodes the JSON object.
247/// What: Returns `Ok(IpcMessage)` or an error with context.
248/// Test: Feed known-good JSON for each variant and assert equality; feed
249/// malformed JSON and assert `Err`.
250pub fn parse_message(line: &str) -> Result<IpcMessage> {
251 let trimmed = line.trim_end_matches(['\n', '\r']);
252 serde_json::from_str::<IpcMessage>(trimmed)
253 .with_context(|| format!("failed to parse IpcMessage from line: {trimmed}"))
254}
255
256/// Extract a summary from an agent's content output.
257///
258/// Why: Downstream workflow phases need a concise summary (~200-500 words)
259/// rather than 30k chars of raw code. Agents are instructed to append a
260/// `## Summary` section; this helper extracts it so the engine can forward
261/// only the summary into subsequent phase templates.
262/// What: Looks for a case-insensitive `## Summary` heading at the end of the
263/// content. If found, returns everything AFTER that header (trimmed). If not
264/// found, returns the first 500 chars of content as a fallback.
265/// Test: See `extract_summary_finds_trailing_section` and
266/// `extract_summary_fallback_uses_prefix`.
267pub fn extract_summary(content: &str) -> String {
268 let lower = content.to_ascii_lowercase();
269 // Find the LAST `## summary` heading (case-insensitive) so agents that
270 // reference the word "summary" inline don't trigger a false match.
271 let mut best: Option<usize> = None;
272 let needle = "## summary";
273 let mut start = 0usize;
274 while let Some(pos) = lower[start..].find(needle) {
275 let abs = start + pos;
276 // Must be at start of line (preceded by newline or be at offset 0).
277 let at_line_start = abs == 0 || lower.as_bytes()[abs - 1] == b'\n';
278 if at_line_start {
279 best = Some(abs);
280 }
281 start = abs + needle.len();
282 }
283
284 if let Some(h) = best {
285 // Advance past the rest of the header line.
286 let after_header = &content[h..];
287 if let Some(nl) = after_header.find('\n') {
288 return after_header[nl + 1..].trim().to_string();
289 }
290 // Header with no newline after it — nothing to return.
291 return String::new();
292 }
293
294 // Fallback: first 500 chars.
295 let trimmed = content.trim();
296 if trimmed.chars().count() <= 500 {
297 return trimmed.to_string();
298 }
299 let prefix: String = trimmed.chars().take(500).collect();
300 prefix
301}
302
303/// Parse `## File: <path>` / `### \`<path>\`` sections from LLM output into
304/// a list of `(relative_path, body)` pairs, without touching the filesystem.
305///
306/// Why: The workflow engine must be able to materialize code-phase output to
307/// disk BETWEEN phases so the QA phase can run tests against it. Keeping the
308/// parse step pure makes it testable and reusable.
309/// What: Scans line-by-line for `## File: <path>`, `### File: <path>`, or
310/// `## \`path\`` / `### \`path\`` markdown headers, then captures the next
311/// fenced code block as the file body. Empty / unterminated blocks are
312/// skipped. Returns `Vec<(PathBuf, String)>` in the order they appear.
313/// Test: `extract_files_from_content_parses_multiple_files` asserts two
314/// files are returned from a document with two `## File:` sections.
315pub fn extract_files_from_content(content: &str) -> Vec<(PathBuf, String)> {
316 let lines: Vec<&str> = content.lines().collect();
317 let mut out: Vec<(PathBuf, String)> = Vec::new();
318 let mut i = 0;
319
320 while i < lines.len() {
321 let line = lines[i];
322 let trimmed = line.trim_start();
323
324 let rel_path: Option<String> = if let Some(rest) = trimmed.strip_prefix("## File:") {
325 Some(rest.trim().trim_matches('`').to_string())
326 } else if let Some(rest) = trimmed.strip_prefix("### File:") {
327 Some(rest.trim().trim_matches('`').to_string())
328 } else if let Some(rest) = trimmed.strip_prefix("### ") {
329 let s = rest.trim();
330 if s.starts_with('`') && s.ends_with('`') && s.len() >= 2 {
331 Some(s.trim_matches('`').to_string())
332 } else {
333 None
334 }
335 } else if let Some(rest) = trimmed.strip_prefix("## ") {
336 let s = rest.trim();
337 if s.starts_with('`') && s.ends_with('`') && s.len() >= 2 {
338 Some(s.trim_matches('`').to_string())
339 } else {
340 None
341 }
342 } else {
343 None
344 };
345
346 let Some(rel) = rel_path else {
347 i += 1;
348 continue;
349 };
350
351 if rel.is_empty() {
352 i += 1;
353 continue;
354 }
355
356 let mut j = i + 1;
357 while j < lines.len() && !lines[j].trim_start().starts_with("```") {
358 j += 1;
359 }
360 if j >= lines.len() {
361 break;
362 }
363
364 let body_start = j + 1;
365 let mut k = body_start;
366 while k < lines.len() && !lines[k].trim_start().starts_with("```") {
367 k += 1;
368 }
369
370 let body = if k > body_start {
371 lines[body_start..k].join("\n")
372 } else {
373 String::new()
374 };
375 let mut final_body = body;
376 if !final_body.ends_with('\n') {
377 final_body.push('\n');
378 }
379
380 out.push((PathBuf::from(rel), final_body));
381 i = k + 1;
382 }
383
384 out
385}
386
387#[cfg(test)]
388mod tests;