borg/harness/mod.rs
1//! The coding agents borg runs in ("harnesses"), each one module behind one trait.
2//!
3//! Every harness already speaks one canonical, Claude-shaped hook event and gets a Claude-shaped answer
4//! back (hook.rs `dispatch`): a TS adapter translates for omp and opencode, Claude Code's command hooks need
5//! none, and Codex's need only its patch tool turned into an edit (`Harness::normalise`).
6//! So the core differs per harness only in data: how `borg install` wires it ([`Wiring`], `target`),
7//! what reaches its model and when ([`Caps`]), where the turn's work and the drone's last message come
8//! from ([`Transcript`]), and the stop's time budget. The hook (hook.rs), install (install.rs) and
9//! every other module ask these, never the harness's name.
10//!
11//! Adding a harness: one module here, a line in [`ALL`], and an adapter where the harness has no command
12//! hooks (docs/harnesses.md has the checklist; the conformance suites prove the basics).
13
14use std::path::{Path, PathBuf};
15use std::time::Duration;
16
17use serde_json::Value;
18
19pub mod claude;
20pub mod codex;
21pub mod omp;
22pub mod opencode;
23pub mod sim;
24pub mod wiring;
25
26/// One coding agent borg can run in.
27pub trait Harness: Sync {
28 /// The CLI argument (`borg hook <name>`, `borg install <name>`), `BORG_HARNESS` and presence's `harness`.
29 fn name(&self) -> &'static str;
30 fn caps(&self) -> Caps;
31 /// What `borg install` writes.
32 fn wiring(&self) -> Wiring;
33 /// The config file `borg install` writes, under `home`; `var` reads the harness's own config-dir
34 /// variables (`--home` gives none, so nothing outside `home` is reached).
35 fn target(&self, home: &Path, var: &dyn Fn(&str) -> Option<PathBuf>) -> PathBuf;
36 /// What `borg doctor` asks of the harness's CLI.
37 fn probe(&self) -> Probe;
38 /// Left out of help, completions, `all`, status and doctor (the simulated harness).
39 fn hidden(&self) -> bool {
40 false
41 }
42 /// The native hook payload as the canonical event. Default: it is one already.
43 fn normalise(&self, raw: Value) -> Value {
44 raw
45 }
46 /// What `borg doctor` checks beyond the CLI's version line ([`Probe`]), e.g. that the harness trusts
47 /// borg's hooks; `target` is the config `borg install` writes. Default: nothing more.
48 fn checks(&self, _target: &Path) -> Vec<(Level, String)> {
49 Vec::new()
50 }
51 /// What `borg install` tells the engineer to do in the harness itself (e.g. trust the new hooks).
52 fn install_notes(&self) -> Vec<String> {
53 Vec::new()
54 }
55 /// The groups of sub-agents its sessions ran under `home` (review_fix.rs), oldest first: of
56 /// `session` only (as its end hook names it), else of every session, from runs that started at
57 /// or after `since` (epoch ms). Default: none.
58 fn sub_runs(&self, _home: &Path, _session: Option<&str>, _since: Option<i64>) -> Vec<Run> {
59 Vec::new()
60 }
61 /// What its adapter waits for each answer ([`Budgets`]); None where the harness runs borg's hooks
62 /// itself, under the `timeout` borg installs or its own default (Claude Code, Codex). Default: None.
63 fn budgets(&self) -> Option<Budgets> {
64 None
65 }
66}
67
68/// One sub-agent of a [`Run`], as its transcript shows it.
69#[derive(Debug, Clone, Default)]
70pub struct SubAgent {
71 /// Its own id (a Claude Code agent id, a Codex thread id); empty where the harness gives none.
72 pub id: String,
73 /// The id of the sub-agent that started it; empty when the session's own agent did.
74 pub parent: String,
75 /// What the run calls it (`review:rust`, `MappingReview`, a task's description).
76 pub label: String,
77 /// Its workflow phase (`Review`, `Fix`); empty where the harness has none.
78 pub phase: String,
79 /// Its agent type (`reviewer`, `task`, `explore`); empty where the harness has none.
80 pub kind: String,
81 /// Epoch ms.
82 pub started: i64,
83 pub cwd: String,
84 pub prompt: String,
85 /// Every tool input and text it produced.
86 pub work: String,
87 /// Its last text to whoever started it: its answer (where a harness has no structured output, the
88 /// only place findings can be).
89 pub final_text: String,
90 /// Its structured output; None where it gave text only.
91 pub output: Option<Value>,
92}
93
94impl SubAgent {
95 /// A tool call's input, part of its work.
96 pub fn called(&mut self, input: &Value) {
97 self.work.push_str(&format!("{input}\n"));
98 }
99
100 /// A text it said: part of its work, and its final text until it says another.
101 pub fn said(&mut self, t: &str) {
102 self.work.push_str(&format!("{t}\n"));
103 self.final_text = t.to_string();
104 }
105}
106
107/// The sub-agents one session ran together: a Claude Code workflow run or a session's Agent-tool
108/// sub-agents, an omp session's task agents, an opencode session's subagents, a Codex session's
109/// spawned agents.
110#[derive(Debug, Clone, Default)]
111pub struct Run {
112 pub id: String,
113 pub session: String,
114 /// The workflow's or the session's name; may be empty.
115 pub name: String,
116 pub started: i64,
117 /// Its agents are the ones a plain session started one by one (Claude Code's Agent tool, Codex's
118 /// spawns), not one orchestrated run: the session's own agent built, so no sub-agent is the
119 /// builder, and they finish in any order, so a finding is named by its agent.
120 pub loose: bool,
121 /// In start order.
122 pub agents: Vec<SubAgent>,
123}
124
125/// What a harness can do with borg's answers, and what it sends. Each flag gates one behaviour of the
126/// core; a flag changes only with an evaluation behind it (docs/harnesses.md).
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub struct Caps {
129 /// Context returned at a prompt reaches the model.
130 pub prompt_context: bool,
131 /// Context returned after a tool call reaches the model before its next step (live mode's asks).
132 pub tool_context: bool,
133 /// Early delivery: a prompt or touch naming a lesson's scope gets that scope's lessons at once (hook.rs `early`).
134 pub early_delivery: bool,
135 /// A queen question is asked with a dialog (AskUserQuestion), else inline (queen.rs `render_delivery`).
136 pub question_dialog: bool,
137 pub transcript: Transcript,
138 /// `post_tool_failure` carries the engineer's denials, which become episodes (hook.rs
139 /// `capture_rejection`); without it the event is ignored.
140 pub deny_capture: bool,
141 /// Events carry the harness's pid, so a gone process reads as ended (presence.rs `state`); without
142 /// it an event's `pid` is dropped (hook.rs `main`).
143 pub sends_pid: bool,
144 /// The stop's budget when the event names none (`BORG_STOP_BUDGET_MS`, which an adapter sets to its
145 /// [`Budgets::stop`]): the live wait, the stop's model call and the expert drone keep inside it
146 /// (expert_route.rs `stop_budget`). None: the expert drone keeps inside [`DEFAULT_STOP_BUDGET`], the
147 /// model call inside the model's own limit.
148 pub stop_budget: Option<Duration>,
149 /// The characters of context one hook answer may inject into the harness's model and have it
150 /// arrive whole, shared by everything delivered in that event (messages, lessons). Derived: the
151 /// harness's own limit where it has one (cited in its module), else [`CONTEXT_GUARD`].
152 pub context_chars: usize,
153 /// The variable the harness sets to its session's id in every command its model runs; None: the
154 /// harness gives its shell no id (opencode).
155 pub session_env: Option<&'static str>,
156 /// The variable the harness sets to its own pid in every command its model runs, for a harness
157 /// whose shell has no session id: its events carry that pid (`sends_pid`), so presence names the
158 /// session (opencode's `OPENCODE_PID`, set by its CLI).
159 pub pid_env: Option<&'static str>,
160 /// How an idle session of the harness can be woken with a message.
161 pub drone_wake: DroneWake,
162}
163
164impl Caps {
165 /// [`Caps::context_chars`], for callers that read it as a method.
166 #[must_use]
167 pub const fn context_chars(self) -> usize {
168 self.context_chars
169 }
170}
171
172/// Guard: the context one hook answer injects into a harness that sets no limit of its own (omp,
173/// opencode), so one event (a flood of messages, a long pool of lessons) cannot fill the model's
174/// context. Derived: the strictest limit a harness does set ([`claude::CONTEXT_CHARS`],
175/// [`codex::CONTEXT_CHARS`]), so every harness gets at most what any of them would take whole.
176pub const CONTEXT_GUARD: usize = if claude::CONTEXT_CHARS < codex::CONTEXT_CHARS { claude::CONTEXT_CHARS } else { codex::CONTEXT_CHARS };
177
178/// Guard: the seconds borg gives a stop where it sets the limit itself (Claude Code's and Codex's Stop
179/// hook `timeout`, opencode's adapter budget, which opencode does not limit): it bounds how long a stuck
180/// stop can hold the engineer's turn, and leaves room for the live wait (live.rs `stop_wait`), the
181/// model call (`BORG_PREDICT_TIMEOUT_S`, 45 s) and an expert drone. Changing it makes every Codex
182/// engineer trust borg's hooks again (codex.rs `TIMEOUTS`).
183pub const STOP_TIMEOUT_S: u64 = 90;
184
185/// Guard: the characters of a shell call's output an adapter sends borg (its end, where a test run's
186/// summary is, which is what borg reads it for: hook.rs `capture_test`), so a build log of megabytes
187/// is never piped through every hook.
188pub const OUTPUT_TAIL: usize = 4000;
189
190/// How long an adapter waits for borg's answer at each event before it fails open (borg is killed and
191/// the harness carries on as if it said nothing), for a harness whose hooks are an adapter's. borg's
192/// answer carries them to an adapter that asks ([`with_budgets`]), so this table is their one
193/// definition: the adapter's own copy is only its fallback until such an answer came (a test here keeps
194/// the two equal).
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub struct Budgets {
197 /// The engineer's prompt: how long it waits for borg's context.
198 pub prompt: Duration,
199 /// Before every tool call (only steering reads there: a stat when nobody steers).
200 pub pre_tool: Duration,
201 /// After a tool call: how long its result waits for borg's context.
202 pub post_tool: Duration,
203 /// The stop, the one hook that may call a model: also its [`Caps::stop_budget`].
204 pub stop: Duration,
205 /// The session's end.
206 pub end: Duration,
207}
208
209impl Budgets {
210 /// As the answer carries them: milliseconds, and the output tail ([`OUTPUT_TAIL`]) in characters.
211 #[must_use]
212 pub fn json(self) -> Value {
213 let ms = |d: Duration| u64::try_from(d.as_millis()).unwrap_or(u64::MAX);
214 serde_json::json!({
215 "prompt_ms": ms(self.prompt),
216 "pre_ms": ms(self.pre_tool),
217 "post_ms": ms(self.post_tool),
218 "stop_ms": ms(self.stop),
219 "end_ms": ms(self.end),
220 "tail_chars": OUTPUT_TAIL,
221 })
222 }
223}
224
225/// `out` with `"budgets"` ([`Budgets::json`]) when the event asked for them (`"budgets": true`, which an
226/// adapter sends until an answer carried them) and `h`'s hooks are an adapter's; anything else as it
227/// was. hook.rs `main` passes every answer it prints through this, so an adapter learns its budgets
228/// from its first answer.
229pub fn with_budgets(h: &dyn Harness, input: &Value, out: Option<Value>) -> Option<Value> {
230 let Some(b) = h.budgets().filter(|_| input.get("budgets") == Some(&Value::Bool(true))) else { return out };
231 let mut o = out.filter(Value::is_object).unwrap_or_else(|| serde_json::json!({}));
232 o["budgets"] = b.json();
233 Some(o)
234}
235
236/// The longest a stop hook of any harness may run: the largest stop budget borg keeps inside
237/// ([`Caps::stop_budget`], else [`DEFAULT_STOP_BUDGET`]) and the largest stop `timeout` it installs
238/// ([`Wiring::CommandHooks`]).
239pub fn longest_stop() -> Duration {
240 let stop_timeout = |h: &dyn Harness| match h.wiring() {
241 Wiring::CommandHooks { timeouts, .. } => timeouts.iter().filter(|(e, _)| *e == "stop").map(|(_, s)| Duration::from_secs(*s)).max(),
242 Wiring::AdapterFile { .. } => None,
243 };
244 ALL.iter().flat_map(|h| [Some(h.caps().stop_budget.unwrap_or(DEFAULT_STOP_BUDGET)), stop_timeout(*h)]).flatten().max().unwrap_or(DEFAULT_STOP_BUDGET)
245}
246
247/// How an idle session of a harness is woken with a message.
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub enum DroneWake {
250 /// Its stop asks the model to run a waiter in the background, whose end starts the next turn
251 /// (Claude Code).
252 Model,
253 /// Its adapter keeps a waiter for the session's life and wakes the session by the harness's own
254 /// path (omp `pi.sendMessage`, opencode `session.promptAsync`/`prompt`).
255 Plugin,
256 /// No hook can wake an idle session: its stop starts a waiter detached, which wakes the session
257 /// through the harness's CLI (codex `codex queue --thread`). Its hooks run as children of the harness
258 /// process, which sends no pid of its own.
259 Queue,
260}
261
262/// Where the turn's work and the drone's last message come from.
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub enum Transcript {
265 /// The event's `transcript_path` is a Claude Code JSONL transcript.
266 Claude,
267 /// None: the event's own `last_assistant_message`, and the tool calls the hook logs (`.turn`).
268 None,
269}
270
271/// How `borg install` wires a harness.
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum Wiring {
274 /// Command hooks merged into a JSON file: one hook group per native event (native name, canonical
275 /// event), each running `<borg> hook <name> <event>`; `timeouts` gives a canonical event's hook a
276 /// `timeout` in seconds (the others get the harness's own default). `retired`: the hooks an older
277 /// borg installed and this one does not, which install and uninstall remove. `through_links`: the
278 /// file is often a symlink into a dotfiles repo, written through.
279 CommandHooks {
280 events: &'static [(&'static str, &'static str)],
281 timeouts: &'static [(&'static str, u64)],
282 retired: &'static [(&'static str, &'static str)],
283 through_links: bool,
284 },
285 /// A compiled-in adapter copied whole; a symlink is replaced, never written through, and uninstall
286 /// removes only a file with exactly this content.
287 AdapterFile { source: &'static str },
288}
289
290impl Wiring {
291 /// The adapter `borg install` copies whole ("" for command hooks).
292 pub fn adapter(self) -> &'static str {
293 match self {
294 Wiring::AdapterFile { source } => source,
295 Wiring::CommandHooks { .. } => "",
296 }
297 }
298}
299
300/// What `borg doctor` asks: the CLI whose `--version` it prints, and the versions borg was verified on.
301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
302pub struct Probe {
303 pub cli: &'static str,
304 /// Appended to the version line, e.g. " (adapter tested with …)"; empty for none.
305 pub tested: &'static str,
306}
307
308/// How bad a `borg doctor` finding is.
309#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
310pub enum Level {
311 Ok,
312 Warn,
313 Fail,
314}
315
316/// Guard: the stop's budget assumed where a harness names none: 60 s, Claude Code's default command-hook
317/// timeout before it became 600 s (claude.rs), so a hook installed with no `timeout` on an older Claude
318/// Code is never cut off. A safe floor, not a measured limit: `borg install` gives the Stop hook
319/// [`STOP_TIMEOUT_S`].
320pub const DEFAULT_STOP_BUDGET: Duration = Duration::from_secs(60);
321
322/// Set (to anything) by the conformance suites: only then are the hidden harnesses found by name, so
323/// `borg install sim` and `borg hook sim …` are unknown to everyone else.
324pub const TEST_ENV: &str = "BORG_TEST_HARNESS";
325
326/// Every harness, in the order help, status and `all` list them. Adding one is a line here.
327pub static ALL: &[&dyn Harness] = &[&claude::Claude, &omp::Omp, &opencode::Opencode, &codex::Codex, &sim::Sim];
328
329/// The harness called `name`; a hidden one only under [`TEST_ENV`].
330pub fn by_name(name: &str) -> Option<&'static dyn Harness> {
331 let hidden_too = std::env::var_os(TEST_ENV).is_some();
332 ALL.iter().copied().find(|h| h.name() == name && (hidden_too || !h.hidden()))
333}
334
335/// The harnesses people see (help, completions, `all`, status, doctor).
336pub fn visible() -> impl Iterator<Item = &'static dyn Harness> {
337 ALL.iter().copied().filter(|h| !h.hidden())
338}
339
340/// `claude|omp|opencode|codex`: the visible names, for usage lines.
341pub fn names(sep: &str) -> String {
342 visible().map(|h| h.name()).collect::<Vec<_>>().join(sep)
343}
344
345/// The drone's harness in a process its hook started (`BORG_HARNESS`, `borg check`), else the first.
346pub fn current() -> &'static dyn Harness {
347 named_current().unwrap_or(ALL[0])
348}
349
350/// The drone's harness when its hook named it (`BORG_HARNESS`), else None.
351pub fn named_current() -> Option<&'static dyn Harness> {
352 std::env::var("BORG_HARNESS").ok().and_then(|n| by_name(&n))
353}
354
355/// The variables harnesses set to their session's id in every command their model runs and every hook
356/// they run (`Caps::session_env`), each with its harness, in [`ALL`]'s order: Claude Code's
357/// (`CLAUDE_CODE_SESSION_ID`) equals the hook input's `session_id` and follows `/clear`, but under
358/// `--continue` or `--resume` without an id it may be the startup id instead (its env-vars docs); omp's
359/// (`PI_SESSION_ID`) is its session manager's id, the one its extension sends; codex's
360/// (`CODEX_THREAD_ID`, 0.153.2, also inside its sandbox) is the thread id its hooks carry as
361/// `session_id` and `codex queue --thread` takes. opencode gives its shell no session id.
362pub fn session_vars() -> Vec<(&'static str, &'static str)> {
363 ALL.iter().filter_map(|h| h.caps().session_env.map(|v| (v, h.name()))).collect()
364}
365
366/// Every session id set in this process's environment (`session_vars`, trimmed, non-empty), each with
367/// its harness, in `session_vars`' order. More than one when a harness runs inside another's shell (omp
368/// in a Claude Code session): it inherits the outer one's variable too.
369pub fn env_sessions() -> Vec<(String, &'static str)> {
370 let var = |k: &str| std::env::var(k).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
371 session_vars().into_iter().filter_map(|(k, h)| var(k).map(|v| (v, h))).collect()
372}
373
374/// Every harness pid set in this process's environment (`Caps::pid_env`), each with its harness, in
375/// [`ALL`]'s order.
376pub fn env_pids() -> Vec<(u32, &'static str)> {
377 let pid = |k: &str| std::env::var(k).ok().and_then(|v| v.trim().parse::<u32>().ok());
378 ALL.iter().filter_map(|h| h.caps().pid_env.and_then(pid).map(|p| (p, h.name()))).collect()
379}
380
381/// The event's transcript, when the harness writes one and the event names it.
382pub fn transcript(caps: Caps, ev: &Value) -> Option<&str> {
383 match caps.transcript {
384 Transcript::Claude => ev.get("transcript_path").and_then(Value::as_str).filter(|t| !t.is_empty()),
385 Transcript::None => None,
386 }
387}
388
389/// Live mode: this turn's work so far, its last `cap` characters: from the transcript where the harness
390/// writes one ([`Transcript`]), else the turn's tool calls the hook logged in `turn_log`.
391pub fn work_so_far(caps: Caps, ev: &Value, turn_log: &Path, cap: usize) -> String {
392 if let Some(t) = transcript(caps, ev).filter(|t| std::fs::metadata(t).is_ok()) {
393 return claude::turn_so_far(t.as_ref(), cap);
394 }
395 let text = std::fs::read_to_string(turn_log).unwrap_or_default();
396 let n = text.chars().count();
397 text.chars().skip(n.saturating_sub(cap)).collect()
398}
399
400/// The drone's last message, whole: the event's `last_assistant_message`, else the transcript's last
401/// assistant text.
402pub fn last_message(caps: Caps, ev: &Value) -> String {
403 match given(ev) {
404 Some(t) => t.to_string(),
405 None => claude::last_assistant_full(transcript(caps, ev).unwrap_or_default().as_ref()),
406 }
407}
408
409/// The drone's plan, as the queen and the experts read it: [`last_message`], but a transcript's text
410/// only its last 2000 characters (`claude::last_assistant_text`).
411pub fn plan(caps: Caps, ev: &Value) -> String {
412 match given(ev) {
413 Some(t) => t.to_string(),
414 None => claude::last_assistant_text(transcript(caps, ev).unwrap_or_default().as_ref()),
415 }
416}
417
418/// The event's own non-blank `last_assistant_message`.
419fn given(ev: &Value) -> Option<&str> {
420 ev.get("last_assistant_message").and_then(Value::as_str).filter(|t| !t.trim().is_empty())
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426
427 /// Today's flags, pinned: changing one is a product decision with an evaluation behind it, never a
428 /// side effect of a refactor.
429 #[test]
430 fn caps_are_todays() {
431 let row = |n: &str| {
432 let c = by_name(n).unwrap().caps();
433 (c.prompt_context, c.tool_context, c.early_delivery, c.question_dialog, c.transcript, c.deny_capture, c.sends_pid)
434 };
435 assert_eq!(row("claude"), (true, true, true, true, Transcript::Claude, true, false));
436 for n in ["omp", "opencode"] {
437 assert_eq!(row(n), (true, true, false, false, Transcript::None, true, true), "{n}");
438 }
439 assert_eq!(row("codex"), (true, true, false, false, Transcript::None, false, false));
440 // None: the expert drone keeps inside Claude Code's 60 s, the model call its own limit; omp: its
441 // 30 s handler limit less the adapter's margin; opencode and codex: the stop timeout borg sets.
442 let budgets = [("claude", None), ("omp", Some(28)), ("opencode", Some(90)), ("codex", Some(90)), ("sim", None)];
443 let got: Vec<(&str, Option<u64>)> = ALL.iter().map(|h| (h.name(), h.caps().stop_budget.map(|d| d.as_secs()))).collect();
444 assert_eq!(got, budgets, "every harness's stop budget");
445 let Wiring::CommandHooks { timeouts, through_links, .. } = by_name("claude").unwrap().wiring() else { panic!("claude has command hooks") };
446 assert_eq!((timeouts, through_links), (&[("stop", 90)][..], true), "a timeout on the stop only");
447 // Claude Code's and Codex's own limit; omp and opencode set none: the guard, the strictest of those.
448 let chars: Vec<(&str, usize)> = ALL.iter().map(|h| (h.name(), h.caps().context_chars())).collect();
449 assert_eq!(chars, [("claude", 10_000), ("omp", 10_000), ("opencode", 10_000), ("codex", 10_000), ("sim", 10_000)]);
450 }
451
452 /// An adapter's stop budget is the one its budgets name, and only adapters have budgets.
453 #[test]
454 fn only_an_adapters_harness_has_budgets_and_its_stop_is_its_caps_budget() {
455 for h in ALL {
456 let adapter = matches!(h.wiring(), Wiring::AdapterFile { .. });
457 assert_eq!(h.budgets().is_some(), adapter, "{}", h.name());
458 if let Some(b) = h.budgets() {
459 assert_eq!(h.caps().stop_budget, Some(b.stop), "{}", h.name());
460 assert!(b.stop <= Duration::from_secs(STOP_TIMEOUT_S) && b.pre_tool <= b.prompt, "{}: {b:?}", h.name());
461 }
462 }
463 }
464
465 #[test]
466 fn budgets_join_an_answer_only_when_an_adapter_asked() {
467 let omp = by_name("omp").unwrap();
468 let asked = serde_json::json!({"session_id": "s", "budgets": true});
469 let b = omp.budgets().unwrap();
470 let want = serde_json::json!({"prompt_ms": 5000, "pre_ms": 2000, "post_ms": 5000, "stop_ms": 28_000, "end_ms": 1500, "tail_chars": 4000});
471 assert_eq!(b.json(), want);
472 assert_eq!(with_budgets(omp, &asked, None), Some(serde_json::json!({"budgets": want})), "an answer of its own when borg says nothing");
473 let block = serde_json::json!({"decision": "block", "reason": "r"});
474 let both = with_budgets(omp, &asked, Some(block.clone())).unwrap();
475 assert_eq!((&both["decision"], &both["reason"], &both["budgets"]), (&block["decision"], &block["reason"], &want), "added to the answer");
476 let plain = serde_json::json!({"session_id": "s"});
477 assert_eq!(with_budgets(omp, &plain, Some(block.clone())), Some(block.clone()), "not asked: as it was");
478 assert_eq!(with_budgets(omp, &plain, None), None);
479 assert_eq!(with_budgets(by_name("claude").unwrap(), &asked, None), None, "no adapter, no budgets");
480 }
481
482 /// The adapter's budgets before borg's first answer (its `FALLBACK`) are the ones that answer carries.
483 #[test]
484 fn each_adapters_fallback_budgets_are_its_harness_budgets() {
485 for h in ALL {
486 let Some(b) = h.budgets() else { continue };
487 let src = h.wiring().adapter();
488 let line = src.lines().find(|l| l.starts_with("const FALLBACK")).unwrap_or_else(|| panic!("{}: no `const FALLBACK` line", h.name()));
489 let body = line.split_once('{').and_then(|(_, r)| r.split_once('}')).map(|(b, _)| b).unwrap_or_default();
490 let pairs = body
491 .split(',')
492 .filter_map(|kv| kv.split_once(':'))
493 .map(|(k, v)| (k.trim().to_string(), serde_json::json!(v.trim().replace('_', "").parse::<u64>().unwrap())));
494 assert_eq!(Value::Object(pairs.collect()), b.json(), "{}'s adapter", h.name());
495 }
496 }
497
498 /// No budget an answer carries is dead: each adapter's code (comments aside) reads every one, as the
499 /// `within` of a call (`"end_ms"`) or off its budgets (`budgets.tail_chars`).
500 #[test]
501 fn each_adapter_reads_every_budget_borg_sends_it() {
502 let mut adapters = 0;
503 for h in ALL {
504 let Some(b) = h.budgets() else { continue };
505 adapters += 1;
506 let code: String = h.wiring().adapter().lines().filter(|l| !["//", "/*", "*"].iter().any(|c| l.trim_start().starts_with(c))).collect();
507 let sent = b.json();
508 let keys: Vec<&String> = sent.as_object().map(|o| o.keys().collect()).unwrap_or_default();
509 assert!(!keys.is_empty(), "{sent}");
510 for k in keys {
511 assert!(code.contains(&format!("\"{k}\"")) || code.contains(&format!("budgets.{k}")), "{}'s adapter never reads {k}", h.name());
512 }
513 }
514 assert_eq!(adapters, 2, "omp and opencode");
515 }
516
517 /// The stop mark of a listening session (listen.rs) outlives every stop: it is sized from this.
518 #[test]
519 fn the_longest_stop_is_the_largest_budget_or_installed_timeout() {
520 assert_eq!(longest_stop(), Duration::from_secs(STOP_TIMEOUT_S));
521 for h in ALL {
522 assert!(h.caps().stop_budget.unwrap_or(DEFAULT_STOP_BUDGET) <= longest_stop(), "{}", h.name());
523 }
524 }
525
526 #[test]
527 fn names_are_unique_and_found_and_sim_is_hidden() {
528 for h in visible() {
529 assert_eq!(by_name(h.name()).map(|x| x.name()), Some(h.name()));
530 }
531 assert_eq!(ALL.iter().filter(|h| ALL.iter().filter(|x| x.name() == h.name()).count() > 1).count(), 0);
532 assert_eq!(names("|"), "claude|omp|opencode|codex");
533 assert!(ALL.iter().any(|h| h.name() == "sim" && h.hidden()));
534 // Known by name only under TEST_ENV (conformance_cli.rs runs `borg` with and without it).
535 assert_eq!(by_name("sim").is_some(), std::env::var_os(TEST_ENV).is_some());
536 assert!(by_name("nope").is_none());
537 }
538
539 #[test]
540 fn the_transcript_is_read_only_where_the_harness_writes_one() {
541 let ev = serde_json::json!({"transcript_path": "/nonexistent/t.jsonl", "last_assistant_message": ""});
542 assert_eq!(transcript(by_name("claude").unwrap().caps(), &ev), Some("/nonexistent/t.jsonl"));
543 assert_eq!(transcript(by_name("omp").unwrap().caps(), &ev), None);
544 let msg = serde_json::json!({"last_assistant_message": "done"});
545 assert_eq!(last_message(by_name("opencode").unwrap().caps(), &msg), "done");
546 }
547
548 #[test]
549 fn a_plan_from_a_transcript_is_its_tail_and_a_given_message_is_whole() {
550 let dir = std::env::temp_dir().join(format!("borg-harness-plan-{}", std::process::id()));
551 std::fs::create_dir_all(&dir).unwrap();
552 let t = dir.join("t.jsonl");
553 let long = "x".repeat(2500);
554 let line = serde_json::json!({"type": "assistant", "message": {"content": [{"type": "text", "text": long}]}});
555 std::fs::write(&t, format!("{line}\n")).unwrap();
556 let caps = by_name("claude").unwrap().caps();
557 let ev = serde_json::json!({"transcript_path": t, "last_assistant_message": ""});
558 assert_eq!((last_message(caps, &ev).len(), plan(caps, &ev).len()), (2500, 2000));
559 let given = serde_json::json!({"transcript_path": t, "last_assistant_message": long});
560 assert_eq!(plan(caps, &given).len(), 2500, "the event's own message is the plan, whole");
561 let _ = std::fs::remove_dir_all(dir);
562 }
563}