codeswarm-adapters 0.10.8

Reusable ACP and native coding-agent adapters for CodeSwarm
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
//! Pure workflow semantics for pair collaboration and completion evidence.
//!
//! This module has no filesystem or provider I/O. Role helpers classify
//! implementer/reviewer handoffs, and [`CompletionSummary`] accumulates a
//! result summary strictly from observed [`AgentEvent`] data. Agent prose is
//! labelled as a claim, never as evidence, and missing evidence is labelled
//! unknown.

use serde::{Deserialize, Serialize};

use crate::{AgentEvent, RosterSlot, ToolStatus, ToolUpdate};

/// A role inside the two-agent pair review loop. Roster, solo, and manual
/// strategies never assign these roles.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PairRole {
    /// The agent producing the change that the pair reviewer will inspect.
    Implementer,
    /// The agent inspecting an implementer's handoff for concrete defects.
    Reviewer,
}

impl PairRole {
    pub fn label(self) -> &'static str {
        match self {
            PairRole::Implementer => "Implementer",
            PairRole::Reviewer => "Reviewer",
        }
    }
}

/// Classify a non-direct pair-strategy dispatch.
///
/// Roles are anchored to the first responder of the current human task, so
/// returning to that slot after review means implementation work again.
pub fn pair_role(implementer_slot: Option<RosterSlot>, slot: RosterSlot) -> Option<PairRole> {
    match implementer_slot {
        None => Some(PairRole::Implementer),
        Some(implementer) if implementer == slot => Some(PairRole::Implementer),
        Some(_) => Some(PairRole::Reviewer),
    }
}

/// Explain the pair handoff for one dispatched turn.
///
/// `peer` optionally names the counterpart agent. The reviewer fragment asks
/// for concrete defects or a concise approval; the implementer fragment makes
/// the upcoming review explicit. Neither fragment mentions the stop token, so
/// stop eligibility stays governed by the existing prompt footer.
pub fn role_fragment(role: PairRole, peer: Option<&str>) -> String {
    match role {
        PairRole::Implementer => match peer {
            Some(peer) => format!(
                "Pair role: you are the implementer. Produce the concrete change for the \
                 shared task; your reviewer {peer} will review the result next, so describe \
                 exactly what you changed."
            ),
            None => "Pair role: you are the implementer. Produce the concrete change for the \
                 shared task; your pair reviewer will review the result next, so describe \
                 exactly what you changed."
                .to_owned(),
        },
        PairRole::Reviewer => match peer {
            Some(peer) => format!(
                "Pair role: you are the reviewer. {peer} handed off their work for review. \
                 Reply with concrete defects to fix, or a concise approval if none remain."
            ),
            None => "Pair role: you are the reviewer. The implementer handed off their work for \
                 review. Reply with concrete defects to fix, or a concise approval if none \
                 remain."
                .to_owned(),
        },
    }
}

/// One deduplicated tool outcome, keyed by the adapter's stable tool id.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ToolOutcome {
    pub id: String,
    pub title: String,
    pub status: ToolStatus,
    pub detail: Option<String>,
    pub slot: RosterSlot,
}

impl ToolOutcome {
    /// Evidence label for the final observed status. A pending or running
    /// tool has no final outcome, so its evidence is unknown; a completed
    /// status proves only that the tool call finished, never that a test
    /// suite or any claimed result succeeded.
    pub fn evidence_label(&self) -> &'static str {
        match self.status {
            ToolStatus::Completed => "completed",
            ToolStatus::Failed => "failed",
            ToolStatus::Running => "unknown (still running)",
            ToolStatus::Pending => "unknown (still pending)",
        }
    }
}

/// Accumulated, evidence-bound completion state for one human task.
///
/// The root CLI resets this per human task, feeds live [`AgentEvent`]s as
/// they arrive, attaches caller-supplied working-tree paths, and renders the
/// `/summary` text. [`AgentEvent::History`] replays are display-only and are
/// never counted as live turns; use [`CompletionSummary::from_events`] to
/// rebuild from archived events deliberately.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct CompletionSummary {
    task: Option<String>,
    response: Option<String>,
    response_slot: Option<RosterSlot>,
    pending_response: String,
    pending_slot: Option<RosterSlot>,
    tools: Vec<ToolOutcome>,
    changed_paths: Vec<String>,
    changed_paths_observed: bool,
    turns_observed: usize,
}

impl CompletionSummary {
    pub fn new() -> Self {
        Self::default()
    }

    /// Start a fresh task. Clears all observed state and records the task
    /// text shown at the top of every render.
    pub fn begin_task(&mut self, task: impl Into<String>) {
        *self = Self {
            task: Some(task.into()),
            ..Self::default()
        };
    }

    /// Clear all observed state without changing the task text.
    pub fn reset(&mut self) {
        let task = self.task.take();
        *self = Self::default();
        self.task = task;
    }

    /// Observe one live normalized event. Display-only history replay events
    /// ([`AgentEvent::History`]) are ignored so restored conversations never
    /// count as live turns or fabricate outcomes.
    pub fn observe(&mut self, event: &AgentEvent) {
        match event {
            AgentEvent::History { .. } | AgentEvent::BatchComplete { .. } => {}
            AgentEvent::TurnStarted { .. } => {
                self.commit_pending();
                self.turns_observed += 1;
            }
            AgentEvent::Text { slot, text } => {
                self.pending_response.push_str(text);
                self.pending_slot = Some(*slot);
            }
            AgentEvent::Tool { slot, update } => self.record_tool(*slot, update),
            AgentEvent::TurnComplete { .. }
            | AgentEvent::Failed { .. }
            | AgentEvent::UsageLimitReached { .. } => self.commit_pending(),
            _ => {}
        }
    }

    /// Deliberately rebuild a summary from stored or replayed events, such as
    /// an archived journal. Unlike live observation this is an explicit
    /// intent to summarize past activity; [`AgentEvent::History`] wrappers
    /// are still display-only and stay excluded.
    pub fn from_events<'a>(events: impl IntoIterator<Item = &'a AgentEvent>) -> Self {
        let mut summary = Self::new();
        for event in events {
            summary.observe(event);
        }
        summary
    }

    /// Attach caller-supplied changed working-tree paths, such as `git
    /// status` output. The summary never inspects the filesystem itself.
    /// Paths are trimmed, deduplicated preserving first-seen order, and
    /// replace any previously attached set.
    pub fn set_changed_paths(&mut self, paths: impl IntoIterator<Item = impl Into<String>>) {
        let mut seen = Vec::new();
        for path in paths {
            let path = path.into().trim().to_owned();
            if !path.is_empty() && !seen.contains(&path) {
                seen.push(path);
            }
        }
        self.changed_paths = seen;
        self.changed_paths_observed = true;
    }

    pub fn task(&self) -> Option<&str> {
        self.task.as_deref()
    }

    /// The final response text of the most recent turn with text. This is
    /// agent-reported prose, never evidence of execution.
    pub fn last_response(&self) -> Option<&str> {
        self.response.as_deref()
    }

    pub fn last_response_slot(&self) -> Option<RosterSlot> {
        self.response_slot
    }

    pub fn tool_outcomes(&self) -> &[ToolOutcome] {
        &self.tools
    }

    pub fn changed_paths(&self) -> &[String] {
        &self.changed_paths
    }

    pub fn observed_turns(&self) -> usize {
        self.turns_observed
    }

    fn commit_pending(&mut self) {
        if !self.pending_response.trim().is_empty() {
            self.response = Some(std::mem::take(&mut self.pending_response));
            self.response_slot = self.pending_slot.take();
        } else {
            self.pending_response.clear();
            self.pending_slot = None;
        }
    }

    fn record_tool(&mut self, slot: RosterSlot, update: &ToolUpdate) {
        if let Some(existing) = self
            .tools
            .iter_mut()
            .find(|outcome| outcome.slot == slot && outcome.id == update.id)
        {
            existing.title = update.title.clone();
            existing.status = update.status;
            existing.detail = update.detail.clone();
            existing.slot = slot;
        } else {
            self.tools.push(ToolOutcome {
                id: update.id.clone(),
                title: update.title.clone(),
                status: update.status,
                detail: update.detail.clone(),
                slot,
            });
        }
    }

    /// Render the summary as GitHub-flavored Markdown.
    pub fn render_markdown(&self) -> String {
        self.render(true)
    }

    /// Render the summary as plain text.
    pub fn render_text(&self) -> String {
        self.render(false)
    }

    fn render(&self, markdown: bool) -> String {
        let mut out = String::new();
        if markdown {
            out.push_str("## Completion summary\n\n");
        } else {
            out.push_str("Completion summary\n\n");
        }
        match &self.task {
            Some(task) => {
                if markdown {
                    out.push_str(&format!("**Task:** {task}\n"));
                } else {
                    out.push_str(&format!("Task: {task}\n"));
                }
            }
            None => {
                if markdown {
                    out.push_str("_Task: unknown (no task recorded)._\n");
                } else {
                    out.push_str("Task: unknown (no task recorded).\n");
                }
            }
        }
        out.push('\n');
        match &self.response {
            Some(response) => {
                if markdown {
                    out.push_str("**Last response** (agent-reported, not evidence):\n");
                } else {
                    out.push_str("Last response (agent-reported, not evidence):\n");
                }
                out.push_str(response.trim_end());
                out.push_str("\n\n");
            }
            None => {
                if markdown {
                    out.push_str("_Last response: unknown (no live response observed)._\n\n");
                } else {
                    out.push_str("Last response: unknown (no live response observed).\n\n");
                }
            }
        }
        if markdown {
            out.push_str("**Tool outcomes:**\n");
        } else {
            out.push_str("Tool outcomes:\n");
        }
        if self.tools.is_empty() {
            if markdown {
                out.push_str("_None recorded; execution evidence is unknown._\n");
            } else {
                out.push_str("None recorded; execution evidence is unknown.\n");
            }
        } else {
            for outcome in &self.tools {
                out.push_str(&format!(
                    "- {} (`{}`, slot {}): {}",
                    outcome.title,
                    outcome.id,
                    outcome.slot,
                    outcome.evidence_label()
                ));
                if let Some(detail) = &outcome.detail {
                    for line in detail.lines() {
                        if markdown {
                            out.push_str(&format!("\n  > {line}"));
                        } else {
                            out.push_str(&format!("\n    {line}"));
                        }
                    }
                }
                out.push('\n');
            }
        }
        out.push('\n');
        if markdown {
            out.push_str("**Changed working-tree paths** (caller-provided):\n");
        } else {
            out.push_str("Changed working-tree paths (caller-provided):\n");
        }
        if self.changed_paths.is_empty() && self.changed_paths_observed {
            out.push_str("None (working tree was clean when checked).\n");
        } else if self.changed_paths.is_empty() {
            if markdown {
                out.push_str("_Unknown (not provided)._\n");
            } else {
                out.push_str("Unknown (not provided).\n");
            }
        } else {
            for path in &self.changed_paths {
                out.push_str(&format!("- {path}\n"));
            }
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::{CompletionSummary, PairRole, ToolOutcome, pair_role, role_fragment};
    use crate::{AgentEvent, ToolStatus, ToolUpdate};

    fn tool(id: &str, status: ToolStatus) -> AgentEvent {
        AgentEvent::Tool {
            slot: 1,
            update: ToolUpdate {
                id: id.into(),
                title: format!("tool {id}"),
                status,
                detail: None,
            },
        }
    }

    #[test]
    fn pair_roles_classify_fresh_handoffs_and_repeat_dispatches() {
        assert_eq!(pair_role(None, 0), Some(PairRole::Implementer));
        assert_eq!(pair_role(None, 3), Some(PairRole::Implementer));
        assert_eq!(pair_role(Some(0), 1), Some(PairRole::Reviewer));
        assert_eq!(pair_role(Some(1), 0), Some(PairRole::Reviewer));
        assert_eq!(pair_role(Some(0), 0), Some(PairRole::Implementer));
    }

    #[test]
    fn role_fragments_explain_handoffs_and_request_defects_or_approval() {
        let implementer = role_fragment(PairRole::Implementer, None);
        assert!(implementer.contains("you are the implementer"));
        assert!(implementer.contains("pair reviewer will review the result next"));
        assert!(!implementer.contains(crate::relay::STOP_TOKEN));

        let reviewer = role_fragment(PairRole::Reviewer, Some("Claude"));
        assert!(reviewer.contains("you are the reviewer"));
        assert!(reviewer.contains("Claude handed off"));
        assert!(reviewer.contains("concrete defects"));
        assert!(reviewer.contains("concise approval"));
        assert!(!reviewer.contains(crate::relay::STOP_TOKEN));

        let unnamed = role_fragment(PairRole::Reviewer, None);
        assert!(unnamed.contains("The implementer handed off"));
    }

    #[test]
    fn summary_accumulates_only_the_latest_turn_response() {
        let mut summary = CompletionSummary::new();
        summary.begin_task("fix the build");
        for event in [
            AgentEvent::TurnStarted { slot: 0 },
            AgentEvent::Text {
                slot: 0,
                text: "first ".into(),
            },
            AgentEvent::Text {
                slot: 0,
                text: "response".into(),
            },
            AgentEvent::TurnComplete { slot: 0 },
            AgentEvent::TurnStarted { slot: 1 },
            AgentEvent::Text {
                slot: 1,
                text: "final response".into(),
            },
            AgentEvent::TurnComplete { slot: 1 },
        ] {
            summary.observe(&event);
        }
        assert_eq!(summary.task(), Some("fix the build"));
        assert_eq!(summary.last_response(), Some("final response"));
        assert_eq!(summary.last_response_slot(), Some(1));
        assert_eq!(summary.observed_turns(), 2);

        // A turn that produces no text keeps the previous response.
        summary.observe(&AgentEvent::TurnStarted { slot: 0 });
        summary.observe(&AgentEvent::TurnComplete { slot: 0 });
        assert_eq!(summary.last_response(), Some("final response"));
    }

    #[test]
    fn summary_deduplicates_tool_updates_by_id() {
        let mut summary = CompletionSummary::new();
        summary.observe(&tool("t1", ToolStatus::Running));
        summary.observe(&AgentEvent::Tool {
            slot: 1,
            update: ToolUpdate {
                id: "t1".into(),
                title: "cargo test".into(),
                status: ToolStatus::Completed,
                detail: Some("exit 0".into()),
            },
        });
        summary.observe(&tool("t2", ToolStatus::Failed));
        assert_eq!(
            summary.tool_outcomes(),
            [
                ToolOutcome {
                    id: "t1".into(),
                    title: "cargo test".into(),
                    status: ToolStatus::Completed,
                    detail: Some("exit 0".into()),
                    slot: 1,
                },
                ToolOutcome {
                    id: "t2".into(),
                    title: "tool t2".into(),
                    status: ToolStatus::Failed,
                    detail: None,
                    slot: 1,
                },
            ]
        );
        let text = summary.render_text();
        assert!(text.contains("cargo test (`t1`, slot 1): completed"));
        assert!(text.contains("tool t2 (`t2`, slot 1): failed"));
    }

    #[test]
    fn tool_ids_are_scoped_to_agents_and_explicit_empty_evidence_clears() {
        let mut summary = CompletionSummary::new();
        for slot in [0, 1] {
            summary.observe(&AgentEvent::Tool {
                slot,
                update: ToolUpdate {
                    id: "same".into(),
                    title: "Read".into(),
                    status: ToolStatus::Completed,
                    detail: Some("output".into()),
                },
            });
        }
        assert_eq!(summary.tool_outcomes().len(), 2);
        summary.observe(&AgentEvent::Tool {
            slot: 0,
            update: ToolUpdate {
                id: "same".into(),
                title: "Read".into(),
                status: ToolStatus::Completed,
                detail: None,
            },
        });
        assert_eq!(summary.tool_outcomes()[0].detail, None);
        assert_eq!(summary.tool_outcomes()[1].detail.as_deref(), Some("output"));
        summary.set_changed_paths(Vec::<String>::new());
        assert!(summary.render_text().contains("working tree was clean"));
    }

    #[test]
    fn unresolved_tools_report_unknown_evidence() {
        let mut summary = CompletionSummary::new();
        summary.observe(&tool("t1", ToolStatus::Pending));
        summary.observe(&tool("t2", ToolStatus::Running));
        let text = summary.render_text();
        assert!(text.contains("(`t1`, slot 1): unknown (still pending)"));
        assert!(text.contains("(`t2`, slot 1): unknown (still running)"));
        assert!(!text.to_lowercase().contains("completed"));
    }

    #[test]
    fn history_events_never_count_as_live_turns_or_outcomes() {
        let mut summary = CompletionSummary::new();
        summary.begin_task("task");
        summary.observe(&AgentEvent::History {
            slot: 0,
            content: crate::HistoryContent::Text("replayed".into()),
        });
        summary.observe(&AgentEvent::History {
            slot: 0,
            content: crate::HistoryContent::Tool(ToolUpdate {
                id: "h1".into(),
                title: "replayed tool".into(),
                status: ToolStatus::Completed,
                detail: None,
            }),
        });
        assert_eq!(summary.last_response(), None);
        assert!(summary.tool_outcomes().is_empty());
        assert_eq!(summary.observed_turns(), 0);
        let text = summary.render_text();
        assert!(text.contains("unknown (no live response observed)"));
        assert!(text.contains("None recorded; execution evidence is unknown."));
    }

    #[test]
    fn from_events_rebuilds_archived_activity_deliberately() {
        let events = vec![
            AgentEvent::TurnStarted { slot: 0 },
            AgentEvent::Text {
                slot: 0,
                text: "archived answer".into(),
            },
            AgentEvent::Tool {
                slot: 0,
                update: ToolUpdate {
                    id: "a1".into(),
                    title: "edit".into(),
                    status: ToolStatus::Completed,
                    detail: None,
                },
            },
            AgentEvent::TurnComplete { slot: 0 },
            // Display-only replay content stays excluded even here.
            AgentEvent::History {
                slot: 0,
                content: crate::HistoryContent::Text("replay".into()),
            },
        ];
        let summary = CompletionSummary::from_events(&events);
        assert_eq!(summary.last_response(), Some("archived answer"));
        assert_eq!(summary.tool_outcomes().len(), 1);
        assert_eq!(summary.observed_turns(), 1);
    }

    #[test]
    fn changed_paths_are_trimmed_deduplicated_and_rendered() {
        let mut summary = CompletionSummary::new();
        summary.set_changed_paths([" src/lib.rs ", "", "src/lib.rs", "docs/plan.md"]);
        assert_eq!(
            summary.changed_paths(),
            ["src/lib.rs".to_string(), "docs/plan.md".to_string()]
        );
        let markdown = summary.render_markdown();
        assert_eq!(markdown.matches("- src/lib.rs").count(), 1);
        assert!(markdown.contains("- docs/plan.md"));

        summary.set_changed_paths(Vec::<String>::new());
        assert!(summary.changed_paths().is_empty());
        assert!(
            summary
                .render_text()
                .contains("None (working tree was clean when checked).")
        );
        assert!(
            summary
                .render_markdown()
                .contains("None (working tree was clean when checked).")
        );
    }

    #[test]
    fn agent_prose_is_never_promoted_to_execution_evidence() {
        let mut summary = CompletionSummary::new();
        summary.observe(&AgentEvent::TurnStarted { slot: 0 });
        summary.observe(&AgentEvent::Text {
            slot: 0,
            text: "All tests passed and the build is clean.".into(),
        });
        summary.observe(&AgentEvent::TurnComplete { slot: 0 });
        for render in [summary.render_text(), summary.render_markdown()] {
            assert!(render.contains("agent-reported, not evidence"));
            assert!(render.contains("All tests passed"));
            assert!(!render.to_lowercase().contains("verified"));
            assert!(render.contains("None recorded; execution evidence is unknown."));
        }
    }

    #[test]
    fn renders_cover_task_absent_and_reset_semantics() {
        let mut summary = CompletionSummary::new();
        assert!(summary.render_text().contains("Task: unknown"));
        summary.begin_task("first");
        summary.observe(&AgentEvent::Text {
            slot: 0,
            text: "progress".into(),
        });
        summary.reset();
        assert_eq!(summary.task(), Some("first"));
        assert_eq!(summary.last_response(), None);
        assert_eq!(summary.observed_turns(), 0);
        assert!(summary.tool_outcomes().is_empty());
        summary.begin_task("second");
        assert_eq!(summary.task(), Some("second"));
        assert_eq!(summary.last_response(), None);
    }
}