-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patheval_run.rs
More file actions
2184 lines (2069 loc) · 94 KB
/
Copy patheval_run.rs
File metadata and controls
2184 lines (2069 loc) · 94 KB
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Runtime for the st2 spec (P2+): boot a spec's team, and (P3/P4) run its `eval` + judges. The
//! team-boot REUSES the existing reconcile/execute machinery. Compact `team` declarations map to
//! in-memory [`AgentSpec`]s; an explicit `canonical-agents` eval instead discovers the post-run
//! hermetic catalog. Either way one [`AgentSpec`] vector flows through reconcile, execution,
//! supervision, and teardown exactly as `st2 up <catalog>` does.
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use std::sync::atomic::{AtomicBool, Ordering};
use anyhow::{Context, Result};
use crate::eval_spec::{Check, Eval, Judge, JudgeKind, RunStep, Spec, SpecAgent, parse_spec};
use crate::expand::expand_catalog;
use crate::flapping::FlappingCap;
use crate::reconcile::reconcile;
use crate::run::{Runner, SystemRunner, UpReport, detect_host, execute};
use agent_spec::spec::{AgentSpec, JobType, Task, TaskKind, TaskLifecycle};
macro_rules! eval_log {
($($arg:tt)*) => {
if std::env::var_os("ST2_EVAL_JSON").is_some() { eprintln!($($arg)*); } else { std::println!($($arg)*); }
};
}
static EVAL_INTERRUPTED: AtomicBool = AtomicBool::new(false);
extern "C" fn on_eval_signal(_signal: libc::c_int) {
EVAL_INTERRUPTED.store(true, Ordering::SeqCst);
}
fn install_eval_signal_handlers() -> (libc::sighandler_t, libc::sighandler_t) {
EVAL_INTERRUPTED.store(false, Ordering::SeqCst);
// libc exposes sighandler_t as a numeric ABI token on some targets.
#[allow(clippy::fn_to_numeric_cast, function_casts_as_integer)]
unsafe {
(libc::signal(libc::SIGINT, on_eval_signal as libc::sighandler_t), libc::signal(libc::SIGTERM, on_eval_signal as libc::sighandler_t))
}
}
fn restore_eval_signal_handlers(previous: (libc::sighandler_t, libc::sighandler_t)) {
unsafe { libc::signal(libc::SIGINT, previous.0); libc::signal(libc::SIGTERM, previous.1); }
}
struct EvalSignalGuard((libc::sighandler_t, libc::sighandler_t));
impl Drop for EvalSignalGuard {
fn drop(&mut self) { restore_eval_signal_handlers(self.0); }
}
/// Map a parsed spec's agents into in-memory [`AgentSpec`]s rooted at `root` (which becomes `$CATALOG`
/// and the base for each agent's `workspace`/cwd). Each agent's own `command` is a `pty` task keyed by
/// the agent id; each `exec` block is an `exec` task keyed by its id. Env is already cascaded.
pub fn spec_to_agent_specs(agents: &[SpecAgent], host: &str, root: &Path) -> Vec<AgentSpec> {
// `spec.path.parent()` is the cwd/`$CATALOG` base in reconcile/execute → point it at `root`.
let path = root.join("spec.kdl");
agents
.iter()
.map(|a| {
let mut tasks = Vec::new();
let mut ptags = BTreeMap::new();
ptags.insert("role".to_string(), "agent".to_string());
tasks.push(Task {
kind: TaskKind::Pty,
derived: false,
name: "agent".to_string(),
id: Some(a.id.clone()), // explicit id → the session is exactly the agent id (mix.sup)
command: Some(a.command.clone()),
argv: None,
cwd: None, // → the agent's workspace (resolved relative to `root`)
tags: ptags,
env: a.env.clone(),
keep: false,
lifecycle: TaskLifecycle::Service,
});
for ex in &a.execs {
tasks.push(Task {
kind: TaskKind::Exec,
derived: ex.derived,
name: ex.id.clone(),
id: Some(ex.id.clone()),
command: Some(ex.command.clone()),
argv: None,
cwd: None,
tags: BTreeMap::new(),
env: ex.env.clone(),
keep: false,
lifecycle: TaskLifecycle::Service,
});
}
AgentSpec {
identity: a.id.clone(),
name: a.name.clone(),
description: a.description.clone(),
host: Some(host.to_string()),
role: None,
job_type: JobType::Service,
workspace: a.workspace.clone(),
supervisor: a.supervisor.clone(),
retired: false,
keep: false,
restart: None,
resources: Vec::new(),
tasks,
path: path.clone(),
}
})
.collect()
}
#[derive(Debug)]
struct CanonicalEvalTeam {
specs: Vec<AgentSpec>,
runtime_tasks: Vec<EvalRuntimeTask>,
routes: BTreeMap<String, CanonicalRoute>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct EvalRuntimeTask {
agent_id: String,
runtime_id: String,
is_pty: bool,
}
#[derive(Debug, Clone)]
struct CanonicalRoute {
inbox: PathBuf,
archive: PathBuf,
}
fn admitted_route<'a>(
routes: &'a BTreeMap<String, CanonicalRoute>,
id: &str,
) -> &'a CanonicalRoute {
routes
.get(id)
.unwrap_or_else(|| panic!("strict canonical admission did not freeze route for `{id}`"))
}
fn task_runtime_id(spec: &AgentSpec, task: &Task, host: &str) -> String {
task.id
.clone()
.unwrap_or_else(|| format!("{}.{}", spec.bus_id(host), task.name))
}
fn task_is_launchable(task: &Task) -> bool {
task.command.is_some() || task.argv.is_some()
}
/// Discover the sole declaration authority for a `canonical-agents` eval after its fixture and run
/// steps have populated the hermetic catalog. This deliberately consumes the shared Agent Spec
/// parser instead of projecting the compact eval grammar into a second, partial declaration.
fn load_canonical_eval_team(catalog: &Path, host: &str) -> Result<CanonicalEvalTeam> {
let validation = crate::validate::validate_for_host(catalog, host);
if !validation.issues.is_empty() {
let issues = validation
.issues
.iter()
.map(|issue| {
format!(
"{} {} {}: {}",
issue.severity.tag(),
issue.code,
issue.path,
issue.message
)
})
.collect::<Vec<_>>()
.join("; ");
anyhow::bail!("canonical eval Agent Specs failed strict validation: {issues}");
}
let found = crate::discover(catalog);
if !found.errors.is_empty() {
let errors = found
.errors
.iter()
.map(|error| format!("{}: {}", error.path.display(), error.message))
.collect::<Vec<_>>()
.join("; ");
anyhow::bail!("canonical eval Agent Spec discovery failed: {errors}");
}
if !found.warnings.is_empty() {
anyhow::bail!(
"canonical eval Agent Specs must discover without warnings: {}",
found.warnings.join("; ")
);
}
if crate::catalog::pty_root(catalog) != catalog.join("pty") {
anyhow::bail!(
"canonical-agents requires the hermetic PTY root `{}`",
catalog.join("pty").display()
);
}
let local_specs = found
.specs
.iter()
.filter(|spec| spec.resolved_host(host) == host)
.cloned()
.collect::<Vec<_>>();
if local_specs.is_empty() {
anyhow::bail!(
"canonical-agents found no local canonical Agent Specs for host `{host}` in {}",
catalog.display()
);
}
let mut bus_ids = HashSet::new();
let mut runtime_ids = BTreeMap::<String, String>::new();
let mut runtime_tasks = Vec::new();
let mut routes = BTreeMap::new();
for spec in &local_specs {
let bus_id = spec.bus_id(host);
if !bus_ids.insert(bus_id.clone()) {
anyhow::bail!("canonical-agents found duplicate Agent Spec bus identity `{bus_id}`");
}
if spec.retired {
anyhow::bail!("canonical-agents refuses retired Agent Spec `{bus_id}`");
}
if !spec.is_runnable() {
anyhow::bail!("canonical-agents Agent Spec `{bus_id}` is not runnable");
}
for task in &spec.tasks {
for root in ["CATALOG", "ST_ROOT", "PTY_ROOT", "ST2_EVAL_REQUESTER"] {
if task.env.contains_key(root) {
anyhow::bail!(
"canonical-agents Agent Spec `{bus_id}` must not override eval-owned `{root}`"
);
}
}
}
for task in &spec.tasks {
let runtime_id = task_runtime_id(spec, task, host);
if runtime_id.trim().is_empty() {
anyhow::bail!(
"canonical-agents Agent Spec `{bus_id}` task `{}` runtime task id must be nonempty",
task.name
);
}
if let Some(previous) = runtime_ids.insert(runtime_id.clone(), bus_id.clone()) {
anyhow::bail!(
"canonical-agents found duplicate runtime task id `{runtime_id}` in `{previous}` and `{bus_id}`"
);
}
if task_is_launchable(task) {
runtime_tasks.push(EvalRuntimeTask {
agent_id: bus_id.clone(),
runtime_id,
is_pty: task.kind == TaskKind::Pty,
});
}
}
let agent_dir = spec
.path
.parent()
.expect("canonical Agent Spec path has an agent directory");
let route = CanonicalRoute {
inbox: crate::message::inbox_dir(agent_dir),
archive: crate::message::archive_dir(agent_dir),
};
for spelling in [bus_id, spec.identity.clone()] {
match routes.entry(spelling.clone()) {
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(route.clone());
}
std::collections::btree_map::Entry::Occupied(_) => {
anyhow::bail!(
"canonical-agents found duplicate canonical route spelling `{spelling}`"
);
}
}
}
}
runtime_tasks.sort_by(|left, right| left.runtime_id.cmp(&right.runtime_id));
let materialized =
crate::materialize::materialize_catalog(catalog, &local_specs, host);
if !materialized.errors.is_empty() {
anyhow::bail!(
"canonical eval Agent Spec materialization failed: {}",
materialized.errors.join("; ")
);
}
if !materialized.warnings.is_empty() {
anyhow::bail!(
"canonical eval Agent Spec materialization warnings are fatal: {}",
materialized.warnings.join("; ")
);
}
Ok(CanonicalEvalTeam {
specs: local_specs,
runtime_tasks,
routes,
})
}
fn shell_single_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
/// Wrap supervised eval seats so their natural exit code survives PTY metadata sweeping. A killed
/// wrapper cannot write the marker, which deliberately remains distinguishable from a clean exit.
fn add_eval_exit_markers(specs: &mut [AgentSpec], catalog: &Path) {
let marker_dir = catalog.join(".eval-exits");
let _ = std::fs::create_dir_all(&marker_dir);
for spec in specs {
let Some(task) = spec.tasks.iter_mut().find(|task| task.kind == TaskKind::Pty) else {
continue;
};
let Some(command) = task.command.take() else {
continue;
};
let marker = marker_dir.join(format!("{}.status", spec.identity));
let script = concat!(
"marker=$1; command=$2; rm -f \"$marker\"; ",
"sh -c \"$command\"; code=$?; ",
"tmp=\"$marker.$$\"; printf '%s\\n' \"$code\" > \"$tmp\"; ",
"mv \"$tmp\" \"$marker\"; exit \"$code\""
);
task.command = Some(format!(
"sh -c {} st2-exit-marker {} {}",
shell_single_quote(script),
shell_single_quote(&marker.display().to_string()),
shell_single_quote(&command)
));
}
}
fn eval_exit_code(catalog: &Path, identity: &str) -> Option<i64> {
std::fs::read_to_string(
catalog
.join(".eval-exits")
.join(format!("{identity}.status")),
)
.ok()?
.trim()
.parse()
.ok()
}
/// Strip the LAUNCHER's agent-identity env so a spawned harness seat runs as a FRESH top-level agent,
/// not a nested child. When `st2 eval`/`st2 up` is itself launched from INSIDE a claude/codex session
/// (e.g. evals-claude running `st2 eval`), those session-identity vars (`CLAUDECODE`,
/// `CLAUDE_CODE_SESSION_ID`, `CLAUDE_PID`, …) leak into the seats and make a nested claude behave as a
/// child/one-shot — it exits after the boot turn instead of staying interactive (the seat-persistence
/// failure). A fresh top-level harness has none of these, so the child must not inherit them.
/// `ANTHROPIC_*` (API creds) is deliberately kept — only the per-session identity is stripped.
fn sanitize_agent_env() {
let should_strip = |k: &str| {
matches!(k, "CLAUDECODE" | "CLAUDE_PID" | "CLAUDE_EFFORT" | "AI_AGENT")
|| k.starts_with("CLAUDE_CODE_")
|| k.starts_with("CODEX_")
};
let victims: Vec<String> = std::env::vars_os()
.filter_map(|(k, _)| k.into_string().ok())
.filter(|k| should_strip(k))
.collect();
// SAFETY: called before spawning seats, single-threaded (same contract as the PTY_ROOT/PATH sets).
for k in victims {
unsafe { std::env::remove_var(&k) };
}
}
/// One boot pass: reconcile the in-memory specs against live sessions and spawn what's missing
/// (adopting anything already alive). `root` roots `$CATALOG`; sessions land in the effective PTY_ROOT.
pub fn boot_team(agent_specs: &[AgentSpec], host: &str, root: &Path) -> Result<UpReport> {
sanitize_agent_env(); // seats must boot as fresh top-level agents, not nested children of the launcher
// HERMETIC exec state: `<catalog>/exec`, NOT the shared per-host `exec_state_dir(host)`. The eval's
// PTY_ROOT is already hermetic, but exec-task state (the dings) lived in a per-HOST dir — so an
// eval's `list_sessions()` unioned OTHER concurrent evals' + the LIVE FLEET's exec tasks, and its
// supervise/teardown sweep could reap them (cross-eval corruption + fleet ding-flapping). Rooting it
// under the catalog makes every eval fully isolated — it can only ever see/reap its OWN sessions.
let runner = SystemRunner::new(root.to_path_buf(), root.join("exec"));
let sessions = runner.list_sessions().context("listing pty sessions")?;
let plan = reconcile(agent_specs, &sessions, host);
let mut report = UpReport::default();
let mut cap = FlappingCap::default();
execute(&plan, &runner, &mut cap, &mut report);
Ok(report)
}
/// Resolve a spec argument to `(spec-file, root-dir)`: a `*.kdl` FILE → that file (root = its dir); a
/// DIR with exactly one top-level `*.kdl` that parses as a spec → that file (root = the dir). Returns
/// `None` if it's not a spec (so `st2 up` falls back to catalog discovery).
pub fn resolve_spec_path(path: &Path) -> Option<PathBuf> {
if path.is_file() {
return (path.extension().is_some_and(|x| x == "kdl")).then(|| path.to_path_buf());
}
if path.is_dir() {
let kdls: Vec<PathBuf> = std::fs::read_dir(path)
.ok()?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|x| x == "kdl"))
.collect();
if let [one] = kdls.as_slice() {
// Confirm it parses as a spec (vs a stray .kdl in a catalog dir).
if std::fs::read_to_string(one).ok().and_then(|t| parse_spec(&t).ok()).is_some() {
return Some(one.clone());
}
}
}
None
}
/// Load + parse a spec file, returning `(Spec, root)` where `root` is the spec's folder (`$CATALOG`
/// and the base for `workspace`/cwd/`copy`/`content` resolution).
pub fn load_spec(spec_file: &Path) -> Result<(Spec, PathBuf)> {
let text = std::fs::read_to_string(spec_file)
.with_context(|| format!("reading spec {}", spec_file.display()))?;
let spec = parse_spec(&text)?;
let root = spec_file
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("."));
let root = root.canonicalize().unwrap_or(root);
Ok((spec, root))
}
/// Prepare the launcher's env before spawning harness seats: (1) strip the launcher's agent-identity
/// vars so each seat boots as a FRESH top-level agent, not a nested child (see [`sanitize_agent_env`]),
/// and (2) prepend THIS binary's dir to PATH so the seats' bare `st2 ding`/`st2 message` resolve to the
/// same st2 as the runner (not a stale ambient install). Called by `st2 up <spec>` (fleet) and mirrored
/// by `st2 eval`. Idempotent; single-threaded contract (before any seat spawns).
pub fn prepare_spawn_env() {
sanitize_agent_env();
if let Ok(exe) = std::env::current_exe()
&& let Some(dir) = exe.parent()
{
let path = std::env::var("PATH").unwrap_or_default();
unsafe { std::env::set_var("PATH", format!("{}:{path}", dir.display())) };
}
}
// ── P3: the `st2 eval` flow ───────────────────────────────────────────────────────────────────────
/// The outcome of an eval run: whether the team reached "done", plus every judge's result. The
/// verdict is all-must-pass over the judges. Compact-team `done` remains informational; a canonical
/// team adds its completion result as a gating judge while still grading the final state.
#[derive(Debug, Clone, serde::Serialize)]
pub struct EvalReport {
/// The team reached the done signal (a sup→requester confirmation post-dating a worker report).
pub done: bool,
/// Every judge, in declared order (no short-circuit — a full legible report).
pub judges: Vec<JudgeResult>,
/// The whole-eval timeout that bounded the wait.
pub timeout: Duration,
}
impl EvalReport {
/// PASS iff there is at least one judge and every judge passed (all-must-pass).
pub fn passed(&self) -> bool {
// A pass requires at least one GATING (non-signal) judge, and every gating judge passing.
// Signal judges run + show but never gate; an eval with only signal judges asserts nothing.
let mut gating = self.judges.iter().filter(|j| !j.signal).peekable();
gating.peek().is_some() && gating.all(|j| j.passed)
}
}
/// One judge's outcome.
#[derive(Debug, Clone, serde::Serialize)]
pub struct JudgeResult {
pub name: String,
pub passed: bool,
/// A short human-readable reason (what passed/failed) — for the legible report.
pub detail: String,
/// A SIGNAL result (from a `signal` judge): shown in the report but NOT counted toward the verdict.
pub signal: bool,
}
/// Recursively copy `src`'s CONTENTS into `dst`, renaming any directory named `_git` → `.git`. A
/// committed fixture ships its repo db as `_git` (a real `.git` would nest as a gitlink); this
/// reconstructs a working repo in the run catalog with the working tree left as readable files.
pub fn copy_tree(src: &Path, dst: &Path) -> Result<()> {
std::fs::create_dir_all(dst)?;
for entry in std::fs::read_dir(src).with_context(|| format!("reading {}", src.display()))? {
let entry = entry?;
let from = entry.path();
let name = entry.file_name();
let dst_name = if name == "_git" { std::ffi::OsString::from(".git") } else { name };
let to = dst.join(&dst_name);
if entry.file_type()?.is_dir() {
copy_tree(&from, &to)?;
} else {
std::fs::copy(&from, &to).with_context(|| format!("copy {} → {}", from.display(), to.display()))?;
}
}
Ok(())
}
/// The bus root — the spec's top-level `ST_ROOT` with `$CATALOG` expanded, else the native flat
/// catalog root. Task runners use that same flat root when no task-level `ST_ROOT` is authored.
fn bus_root(spec: &Spec, catalog: &Path) -> PathBuf {
match spec.env.get("ST_ROOT") {
Some(v) => PathBuf::from(expand_catalog(v, catalog)),
None => catalog.to_path_buf(),
}
}
/// The kickoff content — a file (relative to the spec folder) if it exists, else inline text.
fn resolve_content(content: &str, spec_dir: &Path) -> Result<String> {
let candidate = spec_dir.join(content);
if candidate.is_file() {
std::fs::read_to_string(&candidate).with_context(|| format!("reading kickoff content {}", candidate.display()))
} else {
Ok(content.to_string())
}
}
/// Whether a message `from:` header is `id` (tolerant of a `<prefix>.id` form, though the st2 spec
/// uses bare team-dotted ids).
fn from_is(from: Option<&str>, id: &str) -> bool {
from.is_some_and(|f| f == id || f.ends_with(&format!(".{id}")))
}
/// Wait for the DONE signal, message-driven (not grade-poll). Multi-agent teams require a
/// `sup → requester` confirmation whose timestamp follows a `worker → sup` report. A canonical
/// singleton instead requires a causally new requester-inbox entry at-or-after the exact kickoff
/// receipt. Compact singleton semantics remain unchanged. Bounded by `timeout`. Returns whether done
/// fired.
fn wait_done(
bus: &Path,
canonical_routes: Option<&BTreeMap<String, CanonicalRoute>>,
sup: &str,
requester: &str,
workers: &[String],
kickoff_ts: Option<u64>,
requester_before_kickoff: Option<&HashSet<String>>,
timeout: Duration,
on_tick: &mut dyn FnMut(),
) -> bool {
let (sup_inbox, sup_archive) = match canonical_routes {
Some(routes) => {
let route = admitted_route(routes, sup);
(route.inbox.clone(), route.archive.clone())
}
None => (
bus.join(sup).join("inbox"),
bus.join(sup).join("archive"),
),
};
// The requester is eval-owned, not an admitted Agent Spec, and deliberately keeps one explicit
// flat mailbox. Every canonical agent route above comes from the frozen admitted vector.
let req_inbox = bus.join(requester).join("inbox");
let deadline = Instant::now() + timeout;
loop {
if EVAL_INTERRUPTED.load(Ordering::SeqCst) {
return false;
}
// Earliest worker→sup report (a message from a worker agent). Scan inbox AND archive:
// DING-BUS mandates "archive a message the moment you act on it", so a well-behaved sup MOVES the
// report inbox→archive the instant it acts. Scanning inbox-only makes the done-signal a race
// against the sup's archiving — a fully-closed loop hangs to max-timeout because the report left
// the inbox. (The confirmation side reads the requester's inbox, which is safe — the requester is
// a passive eval-runner seed that never archives.)
let sup_msgs = crate::message::list_dir(&sup_inbox).unwrap_or_default();
let sup_archived = crate::message::list_dir(&sup_archive).unwrap_or_default();
if workers.is_empty()
&& let Some(kickoff_ts) = kickoff_ts
&& let Some(before) = requester_before_kickoff
{
let confirmed = crate::message::list_dir(&req_inbox)
.unwrap_or_default()
.iter()
.any(|m| {
!before.contains(&m.filename)
&& from_is(m.from.as_deref(), sup)
&& m.ts_ms >= kickoff_ts
});
if confirmed {
return true;
}
}
let report_ts = sup_msgs
.iter()
.chain(sup_archived.iter())
.filter(|m| workers.iter().any(|w| from_is(m.from.as_deref(), w)))
.map(|m| m.ts_ms)
.min();
if let Some(rt) = report_ts {
// A sup→requester confirmation at-or-after that report = the real done (not a bare ack).
let confirmed = crate::message::list_dir(&req_inbox)
.unwrap_or_default()
.iter()
.any(|m| from_is(m.from.as_deref(), sup) && m.ts_ms >= rt);
if confirmed {
return true;
}
}
if Instant::now() > deadline {
return false;
}
// A per-tick hook: under `supervise`, this respawns any dead team task FROM SPEC (full env) so
// a fault-injected restart/crash recovers mid-run. A no-op for boot-once (unsupervised).
on_tick();
std::thread::sleep(Duration::from_millis(300));
}
}
/// Fail-fast boot gate: a task whose command exits immediately (127 harness-not-on-PATH, or a crash at
/// startup) must fail the eval LOUDLY now, not leave it hanging until `max-timeout` waiting for a
/// confirmation that can never come. Poll briefly for all tasks to be live — a real task is up within
/// ~1s; a dead-at-boot one never is (tolerant of a slow start + a transient pty-list flicker).
fn boot_gate(task_ids: &[String], specs: &[AgentSpec], host: &str, catalog: &Path) -> Result<()> {
let runner = SystemRunner::new(catalog.to_path_buf(), catalog.join("exec"));
let want: Vec<&str> = task_ids.iter().map(String::as_str).collect();
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let sessions = runner.list_sessions().unwrap_or_default();
let alive: HashSet<&str> = sessions.iter().filter(|s| s.alive).map(|s| s.pty_id.as_str()).collect();
let dead: Vec<&str> = want.iter().copied().filter(|id| !alive.contains(id)).collect();
if dead.is_empty() {
return Ok(());
}
if Instant::now() > deadline {
teardown_team(specs, host, catalog, false); // boot failure → no runtime tasks yet
anyhow::bail!(
"task(s) {dead:?} exited at boot — the command didn't stay running (harness not on PATH, \
e.g. claude/codex not installed, or a crash at startup). Failing fast instead of hanging \
until the eval's max-timeout."
);
}
std::thread::sleep(Duration::from_millis(500));
}
}
fn require_canonical_boot(report: &UpReport, task_ids: &[String]) -> Result<()> {
let missing = task_ids
.iter()
.filter(|id| !report.launched.contains(id))
.cloned()
.collect::<Vec<_>>();
if report.skipped
|| !report.errors.is_empty()
|| !report.flapping.is_empty()
|| !report.held.is_empty()
|| !report.unrunnable.is_empty()
|| !missing.is_empty()
{
anyhow::bail!(
"canonical Agent Spec boot did not launch every admitted task: missing={missing:?}; \
skipped={}; held={:?}; unrunnable={:?}; flapping={:?}; errors={:?}",
report.skipped,
report.held,
report.unrunnable,
report.flapping,
report.errors
);
}
Ok(())
}
fn message_timestamp(filename: &str) -> Result<u64> {
filename
.split_once('-')
.and_then(|(timestamp, _)| timestamp.parse().ok())
.ok_or_else(|| anyhow::anyhow!("message receipt `{filename}` has no timestamp"))
}
/// Tear down the team (nomad-safe): mark the specs retired and reconcile → the runner kills the live
/// sessions (process-group kill). Best-effort — an eval always tears down, with no zombie tasks.
///
/// `reap_all` (set under `supervise`): after the declared teardown, ALSO reap every remaining session
/// in the eval's hermetic PTY_ROOT — runtime-spawned tasks that are NOT in the spec (e.g. a
/// team-standup specialist the CoS spun up mid-run). Declared teardown only reaps declared tasks, so
/// a runtime task would leak as an orphan; since the PTY_ROOT is hermetic to this eval, anything still
/// alive is ours to clean. Killing an already-dead declared session is a harmless no-op.
fn teardown_team_with_runner(
specs: &[AgentSpec],
host: &str,
runner: &dyn Runner,
reap_all: bool,
) {
let retired: Vec<AgentSpec> = specs
.iter()
.cloned()
.map(|mut s| {
s.retired = true;
s
})
.collect();
if let Ok(sessions) = runner.list_sessions() {
let plan = reconcile(&retired, &sessions, host);
let mut report = UpReport::default();
let mut cap = FlappingCap::default();
execute(&plan, runner, &mut cap, &mut report);
}
if reap_all
&& let Ok(remaining) = runner.list_sessions()
{
for s in &remaining {
let _ = runner.kill(&s.pty_id);
let _ = runner.remove(&s.pty_id);
}
}
}
fn teardown_team(specs: &[AgentSpec], host: &str, root: &Path, reap_all: bool) {
let runner = SystemRunner::new(root.to_path_buf(), root.join("exec"));
teardown_team_with_runner(specs, host, &runner, reap_all);
}
/// `st2 eval <folder>` — run the eval end to end: mint a hermetic temp catalog, copy the fixture
/// (`_git`→`.git`), boot the base team + eval-only agents, pretrust their workspaces, deliver the
/// kickoff, wait for the sup's confirmation (post-dating a worker report) or `max-timeout`, tear down.
/// (P4 runs the judges after done and returns the verdict.) The temp catalog is removed on the way out.
pub fn run_eval(spec_file: &Path, host: Option<String>, keep: bool) -> Result<EvalReport> {
let _signal_guard = EvalSignalGuard(install_eval_signal_handlers());
let (spec, spec_dir) = load_spec(spec_file)?;
let eval = spec.eval.clone().ok_or_else(|| {
anyhow::anyhow!("{} has no `eval {{}}` block — use `st2 up` to just boot the team", spec_file.display())
})?;
// --host (explicit) › the spec's top-level `host` › the OS hostname.
let host = host.or_else(|| spec.host.clone()).unwrap_or_else(detect_host);
// Hermetic temp catalog + PTY_ROOT. Setting PTY_ROOT OVERRIDES any inherited ambient, so eval
// sessions can NEVER leak into a live/prod pty registry (isolation by construction).
let catalog = std::env::temp_dir().join(format!("st2e-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&catalog);
std::fs::create_dir_all(&catalog)?;
let _guard = EvalCleanupGuard { runner: SystemRunner::new(catalog.clone(), catalog.join("exec")), catalog: catalog.clone(), host: host.clone(), keep };
// SAFETY: st2 eval is single-threaded up to the boot; set before any seat spawns.
unsafe { std::env::set_var("PTY_ROOT", catalog.join("pty")) };
// Root exec-task state under the catalog too, so ANY st2 sub-invocation spawned INSIDE the eval — a
// run-step's `st2 up`, a seat's bare `st2` — resolves `exec_state_dir(host)` = $XDG_STATE_HOME/st2/…
// to an EVAL-LOCAL dir, not the shared per-host (live-fleet) one. The in-process eval path is already
// hermetic (boot_team/tick use <catalog>/exec directly); this extends that isolation to spawned
// sub-processes so a sub-`st2 up --host X` can't see or reap another eval's or the fleet's exec tasks.
unsafe { std::env::set_var("XDG_STATE_HOME", catalog.join("state")) };
// Make the eval SELF-CONSISTENT on the st2 binary: the spec's bare `st2 ding`/`st2 message` commands
// are PATH-resolved, so a STALE `st2` earlier on PATH (e.g. an old `cargo install`) would run the
// wrong version in the sidecars even when `st2 eval` itself is fresh — the ding-wake failure mode.
// Prepend THIS binary's dir so every bare `st2` in the eval resolves to the same binary as the runner.
if let Ok(exe) = std::env::current_exe()
&& let Some(dir) = exe.parent()
{
let path = std::env::var("PATH").unwrap_or_default();
unsafe { std::env::set_var("PATH", format!("{}:{path}", dir.display())) };
}
let result = if EVAL_INTERRUPTED.load(Ordering::SeqCst) {
Err(anyhow::anyhow!("eval interrupted by SIGINT/SIGTERM"))
} else {
run_eval_inner(&spec, &eval, &spec_dir, &catalog, &host)
};
reap_all_eval_sessions(&catalog, &host)?;
// Seats are already torn down inside run_eval_inner (no leaks). `--keep` preserves the catalog
// files (worker repo base..HEAD, judge outputs, bus) for post-run inspection — e.g. a gate
// reproduction reading the folder before it's "real"; otherwise the hermetic catalog is removed.
if keep {
eval_log!("catalog preserved (--keep): {}", catalog.display());
} else {
let _ = std::fs::remove_dir_all(&catalog);
}
result
}
fn reap_all_eval_sessions_with_runner<R: Runner>(runner: &R, host: &str) -> Result<()> {
let _host = host;
let mut last_error = None;
for _ in 0..5 {
let sessions = runner.list_sessions().with_context(|| format!("listing eval sessions for host {host}"))?;
if sessions.is_empty() { return Ok(()); }
for session in sessions {
if session.alive && let Err(error) = runner.kill(&session.pty_id) { last_error = Some(format!("kill {}: {error:#}", session.pty_id)); }
if let Err(error) = runner.remove(&session.pty_id) { last_error = Some(format!("remove {}: {error:#}", session.pty_id)); }
}
std::thread::sleep(Duration::from_millis(20));
}
anyhow::bail!("eval session reap did not reach empty state on host {host}; last error: {}", last_error.unwrap_or_else(|| "none".into()))
}
fn reap_all_eval_sessions(catalog: &Path, host: &str) -> Result<()> {
let runner = SystemRunner::new(catalog.to_path_buf(), catalog.join("exec"));
reap_all_eval_sessions_with_runner(&runner, host)
}
/// Idempotent safety net for eval catalog lifetime. Normal teardown remains responsible for
/// sessions; this guard ensures an unwind cannot strand the hermetic catalog on disk.
struct EvalCleanupGuard<R: Runner> { runner: R, catalog: PathBuf, host: String, keep: bool }
impl<R: Runner> Drop for EvalCleanupGuard<R> {
fn drop(&mut self) {
let reap = reap_all_eval_sessions_with_runner(&self.runner, &self.host);
if let Err(error) = reap {
eprintln!("st2 eval cleanup: {error:#}; preserving catalog {}", self.catalog.display());
return;
}
if !self.keep { let _ = std::fs::remove_dir_all(&self.catalog); }
}
}
/// Run the eval's `run { }` stage: its command steps, sequentially (declaration order), BEFORE judging.
/// Each step is `sh -c <command>` with cwd = its `workspace` in the catalog and env = the top-level
/// cascade + per-step `env` − `unset` (plus `$CATALOG`, `$RUNS_DIR`, and every earlier step's
/// `$RUN_<id>_EXIT`), retried on non-zero per its policy. stdout/stderr/exit are captured to
/// `$CATALOG/.runs/<id>.{out,err,exit}` for the judges to read. By DEFAULT a non-zero final exit
/// contributes a FAILING synthetic judge result (a step must succeed); an `allow-nonzero` step opts out,
/// leaving the exit for a judge to assert. (No per-step timeout yet: these are deterministic terminating
/// commands; a hard timeout is a follow-up seam.)
fn run_steps(
steps: &[RunStep],
catalog: &Path,
top_env: &BTreeMap<String, String>,
) -> (Vec<JudgeResult>, BTreeMap<String, String>) {
use std::process::Command;
let mut results = Vec::new();
// The env the JUDGES also get: $RUNS_DIR + each step's $RUN_<id>_EXIT (so a bash judge can read the
// captures). Empty when there are no run steps.
let mut judge_env: BTreeMap<String, String> = BTreeMap::new();
if steps.is_empty() {
return (results, judge_env);
}
let runs_dir = catalog.join(".runs");
let _ = std::fs::create_dir_all(&runs_dir);
judge_env.insert("RUNS_DIR".to_string(), runs_dir.display().to_string());
// Unified, judge-greppable command logs: `<catalog>/logs/<label>.log` (same dir the exec sidecars
// auto-log to). Judges get `$LOGS_DIR` so a judge can review/assert a run step's output by log.
let logs_dir = catalog.join("logs");
let _ = std::fs::create_dir_all(&logs_dir);
judge_env.insert("LOGS_DIR".to_string(), logs_dir.display().to_string());
let mut runtime: BTreeMap<String, String> = BTreeMap::new(); // RUN_<id>_EXIT, accumulated across steps
for step in steps {
// Effective env: the cascade + per-step override − unset. Values are `$CATALOG`-expanded.
let mut env = top_env.clone();
env.extend(step.env.clone());
for u in &step.unset {
env.remove(u);
}
let cwd = match &step.workspace {
Some(w) => catalog.join(expand_catalog(w, catalog)),
None => catalog.to_path_buf(),
};
let (attempts, backoff) =
step.retry.as_ref().map(|r| (r.attempts.max(1), r.delay)).unwrap_or((1, Duration::ZERO));
let mut exit = -1;
let (mut out, mut err) = (Vec::new(), Vec::new());
for attempt in 0..attempts {
let mut cmd = Command::new("sh");
cmd.arg("-c")
.arg(&step.command)
.current_dir(&cwd)
.env("CATALOG", catalog)
.env("RUNS_DIR", &runs_dir);
for (k, v) in &env {
cmd.env(k, expand_catalog(v, catalog));
}
for (k, v) in &runtime {
cmd.env(k, v);
}
match cmd.output() {
Ok(o) => {
exit = o.status.code().unwrap_or(-1);
out = o.stdout;
err = o.stderr;
}
Err(e) => {
exit = -1;
err = format!("run step spawn failed: {e}").into_bytes();
}
}
if exit == 0 {
break; // success — no more retries
}
if attempt + 1 < attempts {
std::thread::sleep(backoff);
}
}
let _ = std::fs::write(runs_dir.join(format!("{}.out", step.id)), &out);
let _ = std::fs::write(runs_dir.join(format!("{}.err", step.id)), &err);
let _ = std::fs::write(runs_dir.join(format!("{}.exit", step.id)), exit.to_string());
// Also a unified, judge-greppable combined log (stdout then stderr) named after the run label.
let mut combined = out.clone();
combined.extend_from_slice(&err);
let _ = std::fs::write(logs_dir.join(format!("{}.log", step.id)), &combined);
runtime.insert(format!("RUN_{}_EXIT", env_key(&step.id)), exit.to_string());
eval_log!("== run step {} → exit {}{} ==", step.id, exit, if step.allow_nonzero { " (allow-nonzero)" } else { "" });
if !step.allow_nonzero {
// Default: a run step must succeed. A non-zero final exit hard-fails the verdict as a
// gating synthetic judge. `allow-nonzero` steps skip this — the exit is the judges' to assert.
results.push(JudgeResult {
name: format!("step:{} exit 0", step.id),
passed: exit == 0,
detail: format!("exit {exit}"),
signal: false, // a must-succeed step GATES the verdict
});
}
}
// Hand the judges $RUNS_DIR + every $RUN_<id>_EXIT.
judge_env.extend(runtime);
(results, judge_env)
}
/// Snapshot each PTY task's terminal output to `<catalog>/logs/<id>.log` (plain-text full scrollback via
/// `pty peek`), so judges can review/assert an agent's output by log. Best-effort: `pty` has no
/// continuous plain-text log, so this is the scrollback captured at judge time — enough to inspect a
/// wedged/finished agent's history. A truly continuous agent log would need a `pty` feature.
fn dump_agent_logs(pty_task_ids: &[String], catalog: &Path) {
if pty_task_ids.is_empty() {
return;
}
let logs_dir = catalog.join("logs");
let _ = std::fs::create_dir_all(&logs_dir);
let pty_root = crate::run::effective_pty_root(catalog);
for task_id in pty_task_ids {
let out = std::process::Command::new("pty")
.args(["peek", "--full", "--plain", task_id])
.env("PTY_ROOT", &pty_root)
.output();
if let Ok(o) = out
&& o.status.success()
&& !o.stdout.is_empty()
{
let _ = std::fs::write(logs_dir.join(format!("{task_id}.log")), &o.stdout);
}
}
}
/// An env-var-safe form of a step id (non-alphanumerics → `_`), for `RUN_<id>_EXIT`.
fn env_key(id: &str) -> String {
id.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect()
}
/// The supervisor chain of `agent_id`, walked transitively via each agent's `supervisor` field to the
/// root (whose supervisor is `None` — the cos). Returns the ancestor ids, nearest first. A cycle or a
/// supervisor that names no declared agent terminates the walk (the named id is still included — we ding
/// its inbox regardless of whether it has a running task).
fn supervisor_chain(agent_id: &str, specs: &[AgentSpec], host: &str) -> Vec<String> {
let mut chain = Vec::new();
let mut seen = std::collections::HashSet::new();
let find = |identity: &str| {
specs
.iter()
.find(|spec| spec.identity == identity || spec.bus_id(host) == identity)
};
let mut current = find(agent_id).and_then(|s| s.supervisor.clone());
while let Some(sup) = current {
if !seen.insert(sup.clone()) {
break; // cycle guard
}
chain.push(sup.clone());
current = find(&sup).and_then(|s| s.supervisor.clone());
}
chain
}
/// Emit a crash-ding for a crashed task to every ancestor in its owning agent's supervisor chain.
fn crash_ding(
agent_id: &str,
task_id: &str,
specs: &[AgentSpec],
bus: &Path,
host: &str,
canonical_routes: Option<&BTreeMap<String, CanonicalRoute>>,
) {
let chain = supervisor_chain(agent_id, specs, host);
if chain.is_empty() {
return;
}
let subject = format!("worker crash: {task_id}");
let body = format!(
"Agent task '{task_id}' crashed — its session died non-cleanly (non-zero exit / killed / vanished). \
st2 respawned it from spec; surfacing the crash up the supervision chain."
);
for ancestor in &chain {
let inbox = match canonical_routes {
Some(routes) => admitted_route(routes, ancestor).inbox.clone(),
None => bus.join(ancestor).join("inbox"),
};
let _ = crate::message::send_to_inbox(&inbox, "st2", Some(&subject), None, &[], &body);
eval_log!("== crash-ding: {task_id} → {ancestor} ==");
}
}
fn run_eval_inner(spec: &Spec, eval: &Eval, spec_dir: &Path, catalog: &Path, host: &str) -> Result<EvalReport> {
// Copy the fixture's CONTENTS into the catalog root (the start world), _git → .git.
if let Some(copy) = &eval.copy {
let src = spec_dir.join(copy);
copy_tree(&src, catalog).with_context(|| format!("copying fixture {}", src.display()))?;
}
let bus = bus_root(spec, catalog);
let requester = eval.message.as_ref().map(|m| m.from.clone()).unwrap_or_else(|| "eval-runner".to_string());
// The run{} stage runs to completion BEFORE judging — the WHOLE work of a team-less eval, or setup
// before a team. must-exit-0 failures come back as failing synthetic judge results (folded into
// the verdict); `run_env` ($RUNS_DIR + each $RUN_<id>_EXIT) is handed to the judges to read captures.
let (mut judges, run_env) = run_steps(&eval.run_steps, catalog, &spec.env);
// The base team + eval-only compact agents. `canonical-agents` is a mutually exclusive authority:
// it discovers the post-run hermetic catalog rather than projecting this compact grammar.
let mut compact_agents = spec.agents.clone();
compact_agents.extend(eval.agents.clone());
let (done, specs, pty_task_ids) = if compact_agents.is_empty() && !eval.canonical_agents {
// TEAM-LESS: nothing to boot, kick off, or wait on — the run steps did the work → straight to judging.