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
//! The `[roles] fixer` fallback chain, shared by every node that asks a fixer.
//!
//! Five nodes turn a fixer into a seat: the review loop's fix rounds (and the
//! operator-selected fix), the gate-fix round, `land`'s fix rounds, the
//! rebase conflict round and the graft round. Each of them runs a plain forward `for` over
//! [`attempts`] and moves to the next entry only when the call advances
//! ([`crate::agent::output_advances`], the same decision point the other
//! chained roles use); this module holds what they would otherwise each
//! write and drift on: the order, the seat of each entry, and what a
//! handover looks like in the record.
//!
//! **Sticky within a run, never persisted.** Once a fallback agent answered a
//! fixer node, later calls in the same run start from it, so its session
//! carries across rounds instead of the first agent being re-asked (and its
//! quota re-billed) every round. The memory is the run's own
//! [`RunState::handovers`]: the last handover on a [`FIX_NODES`] node whose
//! `to` is on the chain. The report and the behaviour therefore read one
//! record, and nothing is written to the config. A call runs from the start to
//! the end of the chain, forward only: entries before the start are not
//! asked again, so the chain's last failure ends the call as it always did.
//!
//! A fallback agent always gets a fresh [`SeatState`] ([`seat_for`]), never
//! the previous agent's seat renamed: its session id is minted from the agent
//! too, because the previous agent's uuid is already taken by the CLI.
use crate::agent::{AgentOutput, SeatState};
use crate::config::{AgentSpec, ResolvedRoles};
use crate::run::{Candidate, FailClass, Handover, RunState};
/// The nodes whose handovers [`attempts`] reads as "who fixes now". Every
/// consumer records its handovers under exactly one of these, so the two sides
/// cannot disagree: a name here that nobody records would send every round
/// back to the first agent and bill its quota again.
pub const FIX_NODES: [&str; 5] = ["fix", "gate-fix", "land", "rebase", "graft"];
/// The agents to ask, in order, each with the seat key it sits in.
///
/// With `[roles] fixer` unset: the winner's own implementer, whose
/// conversation continues now that the competition is over (one entry, as it
/// has always been). With a chain: the entries from the sticky agent to the
/// end, once each, never wrapping. The chain's *first* entry, when it is the
/// winner's own agent, sits in the winner's seat (`impl-<label>`), as a lone
/// fixer always has; every other entry - a fallback, even one that is the
/// winner's author - sits in the shared `fix` seat, which `seat_for` gives a
/// fresh session (the implementation conversation is never reused by a
/// handover).
pub fn attempts(
state: &RunState,
roles: &ResolvedRoles,
winner: &Candidate,
) -> Vec<(AgentSpec, String)> {
let own = || {
(
state
.config
.agent(&winner.agent)
.cloned()
.unwrap_or_else(|_| roles.implementers[winner.index].clone()),
format!("impl-{}", winner.label),
)
};
let Some(chain) = roles.fixer.as_deref().filter(|c| !c.is_empty()) else {
return vec![own()];
};
let start = sticky_start(chain, &state.handovers);
chain
.iter()
.enumerate()
.skip(start)
.map(|(i, f)| {
if i == 0 && f.id == winner.agent {
own()
} else {
(f.clone(), "fix".to_owned())
}
})
.collect()
}
/// [`attempts`] for the graft round: the same agents in the same order, but
/// every entry sits in the one `graft` seat - never the winner's `impl-<label>`
/// conversation, which remembers the implementation. A fresh seat per agent
/// ([`seat_for`] semantics) keeps what the winner's author knew out of a round
/// that is told about candidates by label only.
pub fn graft_attempts(
state: &RunState,
roles: &ResolvedRoles,
winner: &Candidate,
) -> Vec<(AgentSpec, String)> {
attempts(state, roles, winner)
.into_iter()
.map(|(spec, _)| (spec, "graft".to_owned()))
.collect()
}
/// Where in `chain` a call starts: the agent the last fixer-node handover
/// moved to, else the first.
fn sticky_start(chain: &[AgentSpec], handovers: &[Handover]) -> usize {
handovers
.iter()
.rev()
.filter(|h| FIX_NODES.contains(&h.node.as_str()))
.find_map(|h| chain.iter().position(|s| s.id == h.to))
.unwrap_or(0)
}
/// Fetch or create the seat `key` for `agent`. The same agent continues its
/// conversation; another agent takes a fresh seat whose session id is minted
/// from the agent as well, so `agent::has_session` is false and the full
/// context is sent again.
pub fn seat_for(state: &mut RunState, key: &str, agent: &str) -> SeatState {
if let Some(existing) = state.seats.get(key)
&& existing.agent == agent
{
return existing.clone();
}
let fresh = if state.seats.contains_key(key) {
crate::graph::handover_seat(key, agent, state.next_seat_seed())
} else {
SeatState::new(key, agent, state.seed)
};
state.seats.insert(key.to_owned(), fresh.clone());
fresh
}
/// How a call that did not satisfy the chain failed, and a short reason, for
/// the handover record (`land` / `rebase` call the CLI directly).
pub fn failure_of(out: &anyhow::Result<AgentOutput>) -> (FailClass, String) {
match out {
Err(e) => (
FailClass::Other("error".to_owned()),
format!("{e:#}")
.lines()
.next()
.unwrap_or("")
.chars()
.take(160)
.collect(),
),
Ok(o) if o.quota_exhausted() => (FailClass::Quota, "rate limited (quota)".to_owned()),
Ok(o) if o.timed_out => (FailClass::Timeout, "timed out".to_owned()),
Ok(o) => (
FailClass::Other("unusable".to_owned()),
format!(
"nothing usable ({})",
crate::notices::exit_status(o.exit_code)
),
),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::AgentKind;
use jiff::Timestamp;
use std::collections::BTreeMap;
fn spec(id: &str) -> AgentSpec {
AgentSpec {
id: id.to_owned(),
kind: AgentKind::Command,
model: None,
command: vec!["true".to_owned()],
extra_args: Vec::new(),
env: BTreeMap::new(),
prompt_delivery: None,
max_turn_secs: None,
}
}
fn handover(node: &str, to: &str) -> Handover {
Handover {
at: Timestamp::now(),
node: node.to_owned(),
seat: "fix".to_owned(),
from: "x".to_owned(),
to: to.to_owned(),
reason: String::new(),
}
}
#[test]
fn the_start_follows_the_last_fixer_handover_on_the_chain() {
let chain = [spec("a"), spec("b"), spec("c")];
assert_eq!(sticky_start(&chain, &[]), 0);
// A reviewer's handover is not a fixer's.
assert_eq!(sticky_start(&chain, &[handover("review", "c")]), 0);
// An agent off the chain is ignored.
assert_eq!(sticky_start(&chain, &[handover("fix", "z")]), 0);
assert_eq!(
sticky_start(&chain, &[handover("fix", "b"), handover("rebase", "c")]),
2
);
assert_eq!(
sticky_start(&chain, &[handover("fix", "c"), handover("land", "a")]),
0
);
// A graft handover is a fixer handover too.
assert_eq!(sticky_start(&chain, &[handover("graft", "b")]), 1);
}
}