-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.rs
More file actions
3424 lines (3316 loc) · 125 KB
/
Copy pathmain.rs
File metadata and controls
3424 lines (3316 loc) · 125 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
//! st2 CLI. M0 exposes a single read-only command — `st2 ls <root>` — that slurps a catalog+inbox
//! folder and prints what it discovered (specs, warnings, errors). Reconcile/run land in later
//! milestones; this is the smoke test that discovery works end to end against a real folder.
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result};
use clap::{CommandFactory, Parser};
use st2::{
HostLock, Runner, SystemRunner, UpReport, detect_host, ding, discover, exec_state_dir, message,
up_loop, up_once,
};
mod cli;
use cli::*;
fn main() -> Result<()> {
let Cli {
catalog_path,
command,
} = Cli::parse();
// Claude's status-line tee is the one subcommand whose cadence a HARNESS sets rather than an
// operator or an event: `refreshInterval: 5` makes it ~720 short-lived processes per hour per
// seat, and Claude waits for each to exit. Building an OTel pipeline per render — and, at
// exit, flushing it — would put a collector round-trip in the render path for a run that is
// not an operation worth a span, so the tee never builds one (`DQ-C13`). This is a cadence
// rule, not a hook rule: `claude-observe` is event-driven and stays instrumented, exactly as
// `06-observability`'s spec names it.
let mut telemetry = if matches!(command, Command::Driver(DriverCmd::ClaudeStatusline { .. })) {
st2::telemetry::Telemetry::local_only()
} else {
st2::telemetry::Telemetry::init(if matches!(command, Command::Up { once: false, .. }) {
"supervisor"
} else if matches!(
command,
// Hook executions are their own process unit: `st2 driver claude-observe` runs per
// Claude hook event and records hook_invocations_total, which the documented
// process-unit contract assigns to `st2-hook`, not `st2-cli`.
Command::Driver(DriverCmd::ClaudeObserve { .. })
) {
"hook"
} else {
"cli"
})
};
let result = dispatch(command, catalog_path.as_deref());
telemetry.shutdown();
result
}
fn dispatch(command: Command, catalog_path: Option<&std::path::Path>) -> Result<()> {
initialize_catalog_env(catalog_path.map(|path| path.to_path_buf()).as_deref())?;
match command {
Command::Ls { root } => {
let root = catalog_arg(root)?;
ls(&root)
}
Command::Up {
root,
host,
once,
materialize_only,
interval,
agent,
task,
} => {
let root = catalog_arg(root)?;
if task.is_some() && !materialize_only && !once {
anyhow::bail!("--task requires --once or --materialize-only");
}
if agent.is_some() && !materialize_only {
anyhow::bail!("--agent requires --materialize-only");
}
up(&root, host, once, materialize_only, interval, agent, task)
}
Command::Message(cmd) => message_cmd(cmd),
Command::Event(cmd) => event_cmd(cmd),
Command::Stream(cmd) => stream_cmd(cmd),
Command::Request(cmd) => request_cmd(cmd),
Command::Context(cmd) => context_cmd(cmd),
Command::Resource(cmd) => resource_cmd(cmd),
Command::Service(cmd) => service_cmd(cmd),
Command::ClaudeChannel(cmd) => claude_channel_cmd(cmd),
Command::Hooks(cmd) => hooks_cmd(cmd),
Command::Ding {
session,
identity,
agent_id,
root,
host,
interval,
} => ding_cmd(session, identity, agent_id, root, host, interval),
Command::CodexAppServer {
identity,
runtime_id,
codex_argv,
} => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::codex_app_server::run_controlled(&catalog, identity, runtime_id, codex_argv)
}
Command::ClaudeMcp { identity } => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::claude_mcp::run(&catalog, &identity)
}
Command::Driver(DriverCmd::Codex {
identity,
runtime_id,
argv,
}) => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::codex_app_server::run_controlled(&catalog, identity, runtime_id, argv)
}
Command::Driver(DriverCmd::PiChannel { identity }) => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::pi_channel::run(&catalog, &identity)
}
Command::Driver(DriverCmd::PiSession {
identity,
runtime_id,
argv,
}) => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::pi_session::run(&catalog, identity, runtime_id, argv)
}
Command::Driver(DriverCmd::ClaudeMcp { identity }) => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
let identity = identity
.or_else(|| std::env::var("ST_AGENT").ok())
.context("--identity is required when ST_AGENT is not set")?;
st2::claude_mcp::run(&catalog, &identity)
}
Command::Driver(DriverCmd::OmpChannel { identity }) => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::pi_channel::run_omp(&catalog, &identity)
}
Command::Driver(DriverCmd::OmpSession {
identity,
runtime_id,
argv,
}) => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::omp_session::run(&catalog, identity, runtime_id, argv)
}
Command::Driver(DriverCmd::Claude { identity }) => {
eprintln!("warning: `st2 driver claude` is deprecated; use `st2 driver claude-mcp`");
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::claude_mcp::run(&catalog, &identity)
}
Command::Driver(DriverCmd::ClaudeSession {
identity,
runtime_id,
argv,
}) => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::claude_session::run(&catalog, identity, runtime_id, argv)
}
Command::Driver(DriverCmd::ClaudeObserve {
identity,
runtime_id,
event,
}) => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::claude_session::run_observe(&catalog, &identity, runtime_id.as_deref(), &event)
}
Command::Driver(DriverCmd::ClaudeStatusline { identity }) => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::claude_session::run_statusline(&catalog, &identity)
}
Command::Driver(DriverCmd::OpencodeSession {
identity,
runtime_id,
argv,
}) => {
let catalog = catalog_arg(None)?;
let catalog = catalog.canonicalize().unwrap_or(catalog);
st2::opencode_session::run(&catalog, identity, runtime_id, argv)
}
Command::Driver(DriverCmd::Expand { spec, agent, host }) => {
let catalog = catalog_arg(None)?;
driver_expand_cmd(&catalog, &spec, agent.as_deref(), host.as_deref())
}
Command::Status {
identity,
agent_id,
set,
ctx,
} => status_cmd(identity, agent_id, set, ctx),
Command::Rename(args) => presentation_cmd(st2::agent_author::PresentationField::Name, args),
Command::Describe(args) => {
presentation_cmd(st2::agent_author::PresentationField::Description, args)
}
Command::Agent(AgentCmd::Address(args)) => address_cmd(args),
Command::Agent(AgentCmd::DesiredState {
first,
second,
agent_id,
reason,
managed_by,
host,
json,
}) => {
let (identity, state) = match &agent_id {
Some(_) => (None, first),
None => (first, second),
};
let state = state.context(
"a desired state is required: `running`, `suspended`, or `retired`",
)?;
anyhow::ensure!(
matches!(state.as_str(), "running" | "suspended" | "retired"),
"desired state must be `running`, `suspended`, or `retired`, not '{state}'"
);
desired_state_cmd(identity, agent_id, state, reason, managed_by, host, json)
}
Command::Agent(AgentCmd::Publish {
spec,
bundle,
expect_absent,
expect_sha256,
input_sha256,
managed_by,
json,
}) => {
let catalog = catalog_arg(None)?;
let source = match (spec, bundle) {
(Some(path), None) => st2::agent_publish::PublishSource::Spec(path),
(None, Some(path)) => st2::agent_publish::PublishSource::Bundle(path),
_ => unreachable!("clap enforces one publication source"),
};
let expectation = match (expect_absent, expect_sha256) {
(true, None) => st2::agent_publish::PublishExpectation::Absent,
(false, Some(hash)) => st2::agent_publish::PublishExpectation::Sha256(hash),
_ => unreachable!("clap enforces one publication expectation"),
};
let result = st2::agent_publish::publish(st2::agent_publish::PublishRequest {
catalog,
source,
expectation,
input_sha256,
managed_by,
})?;
if json {
println!("{}", serde_json::to_string_pretty(&result)?);
} else {
println!(
"{} {} {}",
match result.status {
st2::agent_publish::PublishStatus::Published => "published",
st2::agent_publish::PublishStatus::Unchanged => "unchanged",
},
result.bus_id,
result.path.display()
);
}
Ok(())
}
Command::Agent(AgentCmd::Digest { spec, bundle, json }) => {
let source = match (spec, bundle) {
(Some(path), None) => st2::agent_publish::PublishSource::Spec(path),
(None, Some(path)) => st2::agent_publish::PublishSource::Bundle(path),
_ => unreachable!("clap enforces one source"),
};
let digest = st2::agent_publish::digest_source(source)?;
if json {
println!("{}", serde_json::to_string_pretty(&digest)?);
} else {
println!("{}", digest.sha256);
}
Ok(())
}
Command::Catalog(CatalogCmd::Graph { host, json }) => {
if !json {
anyhow::bail!("`st2 catalog graph` v1 requires --json");
}
let graph = st2::catalog_graph::snapshot(
&catalog_arg(None)?,
&host.unwrap_or_else(detect_host),
)?;
let complete = graph.complete;
println!("{}", serde_json::to_string_pretty(&graph)?);
if !complete {
std::process::exit(1);
}
Ok(())
}
Command::Catalog(CatalogCmd::Bootstrap {
prepared,
input_sha256,
json,
}) => {
let result =
st2::catalog_transaction::bootstrap(st2::catalog_transaction::BootstrapRequest {
catalog: catalog_arg(None)?,
prepared,
input_sha256,
})?;
if json {
println!("{}", serde_json::to_string_pretty(&result)?);
} else {
println!(
"{} {}",
match result.status {
st2::catalog_transaction::BootstrapStatus::Created => "created",
st2::catalog_transaction::BootstrapStatus::Unchanged => "unchanged",
},
result.root_sha256
);
}
Ok(())
}
Command::Catalog(CatalogCmd::Digest { prepared, json }) => {
let digest = st2::catalog_transaction::digest_prepared(&catalog_arg(None)?, &prepared)?;
if json {
println!("{}", serde_json::to_string_pretty(&digest)?);
} else {
println!("{}", digest.root_sha256);
}
Ok(())
}
Command::Catalog(CatalogCmd::Diff {
prepared,
expect_sha256,
json,
}) => {
if !json {
anyhow::bail!("`st2 catalog diff` v1 requires --json");
}
let result = st2::catalog_transaction::diff(st2::catalog_transaction::DiffRequest {
catalog: catalog_arg(None)?,
prepared,
expect_sha256,
})?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
Command::Catalog(CatalogCmd::Snapshot {
output,
raw_preimage,
json,
}) => {
let result =
st2::catalog_transaction::snapshot(st2::catalog_transaction::SnapshotRequest {
catalog: catalog_arg(None)?,
output,
raw_preimage,
})?;
if json {
println!("{}", serde_json::to_string_pretty(&result)?);
} else {
println!(
"{} {} {}",
match result.status {
st2::catalog_transaction::SnapshotStatus::Created => "created",
st2::catalog_transaction::SnapshotStatus::Unchanged => "unchanged",
},
result.root_sha256,
result.output.display()
);
}
Ok(())
}
Command::Catalog(CatalogCmd::Apply {
prepared,
input_sha256,
expect_sha256,
raw_preimage,
resume,
json,
}) => {
let mode = if resume {
st2::catalog_transaction::ApplyMode::Resume
} else {
let prepared = prepared.context("clap requires --prepared unless --resume")?;
let input_sha256 =
input_sha256.context("clap requires --input-sha256 unless --resume")?;
let expect_sha256 =
expect_sha256.context("clap requires --expect-sha256 unless --resume")?;
if raw_preimage {
st2::catalog_transaction::ApplyMode::RawPreimage {
prepared,
input_sha256,
expect_sha256,
}
} else {
st2::catalog_transaction::ApplyMode::Prepared {
prepared,
input_sha256,
expect_sha256,
}
}
};
let result = st2::catalog_transaction::apply(st2::catalog_transaction::ApplyRequest {
catalog: catalog_arg(None)?,
mode,
})?;
if json {
println!("{}", serde_json::to_string_pretty(&result)?);
} else {
println!(
"{} {}",
match result.status {
st2::catalog_transaction::ApplyStatus::Applied => "applied",
st2::catalog_transaction::ApplyStatus::Unchanged => "unchanged",
},
result.after_sha256
);
}
Ok(())
}
Command::Catalog(CatalogCmd::Archive {
identity,
all_retired,
host,
dry_run,
json,
}) => {
let selection = if all_retired {
st2::catalog_archive::Selection::AllRetired
} else {
st2::catalog_archive::Selection::Identities(identity)
};
let result = st2::catalog_archive::archive(st2::catalog_archive::ArchiveRequest {
catalog: catalog_arg(None)?,
host: host.unwrap_or_else(detect_host),
selection,
dry_run,
})?;
if json {
println!("{}", serde_json::to_string_pretty(&result)?);
} else {
let verb = if result.dry_run {
"would-archive"
} else {
"archived"
};
for entry in &result.archived {
println!("{verb} {} {} -> {}", entry.id, entry.from, entry.to);
}
for refusal in &result.refused {
println!(
"skipped {} [{}] {}",
refusal.id, refusal.code, refusal.message
);
}
}
Ok(())
}
Command::Catalog(CatalogCmd::Unarchive {
identity,
host,
json,
}) => {
let result = st2::catalog_archive::unarchive(st2::catalog_archive::UnarchiveRequest {
catalog: catalog_arg(None)?,
host: host.unwrap_or_else(detect_host),
identity,
})?;
if json {
println!("{}", serde_json::to_string_pretty(&result)?);
} else {
println!("unarchived {} {} -> {}", result.id, result.from, result.to);
}
Ok(())
}
Command::Agents {
catalog,
status,
identity,
agent_id,
json,
enrich,
ctx,
} => agents_cmd(catalog, status, identity, agent_id, json, enrich, ctx),
Command::Tasks { host, json } => {
if !json {
anyhow::bail!("`st2 tasks` v1 requires --json");
}
let catalog = catalog_arg(None)?;
tasks_cmd(&catalog, host)
}
Command::Unpark { task, host } => {
let catalog = catalog_arg(None)?;
unpark_cmd(&catalog, &task, host)
}
Command::Down { root, host } => {
if root.is_none() && catalog_path.is_none() {
anyhow::bail!(
"refusing implicit teardown target; pass --catalog <path> or an explicit catalog path"
);
}
let root = catalog_arg(root)?;
down_cmd(&root, host)
}
Command::Env { root } => {
let root = catalog_arg(root)?;
env_cmd(&root)
}
Command::Pretrust { dirs } => pretrust_cmd(&dirs),
Command::Eval {
folder,
host,
keep,
json,
} => eval_cmd(&folder, host, keep, json),
Command::Validate {
root,
host,
candidate,
strict,
json,
} => {
let root = catalog_arg(root)?;
validate_cmd(&root, host, candidate, strict, json)
}
Command::Pty { args } => pty_cmd(&args),
Command::Shell { args } => shell_cmd(&args),
Command::Doctor {
root,
host,
require_supervisor,
} => {
let root = catalog_arg(root)?;
doctor_cmd(&root, host, require_supervisor)
}
Command::Completions { shell } => {
// Generate from the live command tree so the script can never drift
// from the actual flags (the flake gates this at build time).
let mut cmd = Cli::command();
clap_complete::generate(shell, &mut cmd, "st2", &mut std::io::stdout());
Ok(())
}
}
}
fn driver_expand_cmd(
catalog: &Path,
path: &Path,
agent: Option<&str>,
host: Option<&str>,
) -> Result<()> {
let (mut specs, warnings) = st2::discover_file(catalog, path)
.with_context(|| format!("reading driver declaration {}", path.display()))?;
for warning in warnings {
eprintln!("warning: {warning}");
}
if let Some(agent) = agent {
specs.retain(|spec| spec.identity == agent || spec.bus_id(host.unwrap_or("")) == agent);
}
anyhow::ensure!(
specs.len() == 1,
if agent.is_some() {
format!(
"{} contains {} matching agent blocks; expected exactly one",
path.display(),
specs.len()
)
} else {
format!(
"{} contains {} agent blocks; use --agent when it contains more than one",
path.display(),
specs.len()
)
}
);
let output = st2::driver::expand_driver(&specs[0], host.unwrap_or(""))?;
print!("{output}");
Ok(())
}
fn hooks_cmd(command: HooksCmd) -> Result<()> {
match command {
HooksCmd::Install {
replace,
allow_downgrade,
} => {
let dir = st2::hooks::install(replace || allow_downgrade)?;
let root = st2::hooks::hooks_root()?;
println!(
"installed hook set {} in {}\nreceipt {}",
st2::hooks::hookset_id(),
dir.display(),
root.join("current.json").display()
);
}
HooksCmd::Verify => {
let dir = st2::hooks::verify_installed()?;
println!(
"verified hook set {} in {}",
st2::hooks::hookset_id(),
dir.display()
);
}
HooksCmd::VerifyOwn => {
let dir = st2::hooks::verify_required_set()?;
println!(
"verified this binary's hook set {} in {}",
st2::hooks::hookset_id(),
dir.display()
);
}
}
Ok(())
}
fn down_cmd(root: &Path, host: Option<String>) -> Result<()> {
// A single-file team spec: tear down the DECLARED team's sessions (symmetric with `st2 up`/`st2 ls`
// over a spec — the "stop the fleet cleanly" verb). A catalog dir falls through to catalog teardown.
if let Some(spec_file) = st2::eval_run::resolve_spec_path(root) {
let (spec, spec_root) = st2::eval_run::load_spec(&spec_file)?;
// Same host resolution as `st2 up <spec>`: --host › the spec's top-level host › OS hostname.
let this_host = host
.or_else(|| spec.host.clone())
.unwrap_or_else(detect_host);
let specs = st2::eval_run::spec_to_agent_specs(&spec.agents, &this_host, &spec_root);
let runner = SystemRunner::new(spec_root, exec_state_dir(&this_host));
let report = st2::down_specs(&specs, &this_host, &runner)?;
println!(
"teardown of spec {} on host '{this_host}':",
spec_file.display()
);
print_report(&report);
return Ok(());
}
let this_host = host.unwrap_or_else(detect_host);
let catalog_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let runner = SystemRunner::new(catalog_root, exec_state_dir(&this_host));
let report = st2::down(root, &this_host, &runner)?;
println!("teardown on host '{this_host}':");
print_report(&report);
Ok(())
}
fn eval_cmd(folder: &Path, host: Option<String>, keep: bool, json: bool) -> Result<()> {
let spec_file = st2::eval_run::resolve_spec_path(folder).with_context(|| {
format!(
"{} is not an st2 spec (a *.kdl file, or a folder with one)",
folder.display()
)
})?;
let keep = keep || std::env::var_os("ST2_EVAL_KEEP").is_some();
if json {
unsafe {
std::env::set_var("ST2_EVAL_JSON", "1");
}
}
let report = st2::eval_run::run_eval(&spec_file, host, keep)?;
if json {
println!("{}", serde_json::to_string_pretty(&report)?);
if report.passed() {
return Ok(());
}
anyhow::bail!("VERDICT: FAIL")
}
if !report.done {
println!(
"(note: the team did not send a confirmation within max-timeout — judged the final state)"
);
}
println!("\n== judges ==");
let (mut pass, mut fail) = (0, 0);
for j in &report.judges {
if j.signal {
// Show-but-don't-gate: runs + prints, but never counts toward SCORE/verdict.
println!(" [SIGNAL] {} ({})", j.name, j.detail);
continue;
}
if j.passed {
pass += 1;
} else {
fail += 1;
}
println!(
" {} {} ({})",
if j.passed { "[PASS]" } else { "[FAIL]" },
j.name,
j.detail
);
}
println!(
"SCORE: {pass} PASS / {fail} FAIL / {} gating judges",
pass + fail
);
if report.passed() {
println!("VERDICT: PASS");
Ok(())
} else {
anyhow::bail!("VERDICT: FAIL")
}
}
fn validate_cmd(
root: &Path,
host: Option<String>,
candidate: Option<PathBuf>,
strict: bool,
json: bool,
) -> Result<()> {
let catalog_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let host = host.unwrap_or_else(detect_host);
let report = if let Some(candidate) = candidate {
st2::agent_publish::validate_candidate_for_host(
&catalog_root,
st2::agent_publish::PublishSource::Spec(candidate),
&host,
)
} else {
let _catalog_lock = st2::CatalogLock::shared(&catalog_root)
.context("acquire shared catalog-authoring lock for validation")?;
st2::validate::validate_for_host(&catalog_root, &host)
};
let (errors, warnings) = (report.errors(), report.warnings());
if json {
let issues: Vec<serde_json::Value> = report
.issues
.iter()
.map(|i| {
serde_json::json!({
"severity": i.severity.tag(),
"code": i.code,
"path": i.path,
"agent": i.agent,
"message": i.message,
})
})
.collect();
let out = serde_json::json!({
"schema": st2::validate::VALIDATE_RECEIPT_SCHEMA,
"policyProfile": st2::validate::CORE_CATALOG_POLICY_PROFILE,
"agentSpecRevision": agent_spec::AGENT_SPEC_REVISION,
"issues": issues,
"agents": report.agents,
"errors": errors,
"warnings": warnings,
});
println!("{}", serde_json::to_string_pretty(&out)?);
} else {
for i in &report.issues {
println!("{} {}: {}", i.severity.label(), i.path, i.message);
}
println!(
"─ {errors} error{}, {warnings} warning{} across {} agent{}",
plural(errors),
plural(warnings),
report.agents,
plural(report.agents),
);
}
// Exit non-zero on any error; under --strict, warnings fail too. Use a clean process exit so a
// scriptable caller does not also get anyhow's "Error:" line after the report it already printed.
if errors > 0 || (strict && warnings > 0) {
std::process::exit(1);
}
Ok(())
}
/// The standard user catalog: `${XDG_STATE_HOME:-$HOME/.local/state}/st2/default/catalog`.
fn default_catalog_root() -> Option<PathBuf> {
nonempty_env_path("XDG_STATE_HOME")
.map(|state| state.join("st2/default/catalog"))
.or_else(|| {
nonempty_env_path("HOME").map(|home| home.join(".local/state/st2/default/catalog"))
})
}
fn nonempty_env_path(name: &str) -> Option<PathBuf> {
std::env::var_os(name)
.filter(|value| !value.is_empty())
.map(PathBuf::from)
}
/// Make even a not-yet-created output catalog absolute, so a later cwd change cannot retarget it.
fn absolute_catalog_path(path: &Path) -> Result<PathBuf> {
let absolute = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir()
.context("resolving the current directory")?
.join(path)
};
Ok(absolute.canonicalize().unwrap_or(absolute))
}
/// Seed `$CATALOG` once for every command. An explicit global flag wins over an inherited env var;
/// without either, the standard per-user catalog becomes the process default.
fn initialize_catalog_env(explicit: Option<&Path>) -> Result<()> {
let selected = explicit
.map(Path::to_path_buf)
.or_else(|| nonempty_env_path("CATALOG"))
.or_else(default_catalog_root);
if let Some(path) = selected {
let path = absolute_catalog_path(&path)?;
// SAFETY: this is the first action after single-threaded CLI parsing, before any worker
// threads or child processes exist.
unsafe { std::env::set_var("CATALOG", path) };
}
Ok(())
}
/// Resolve an optional legacy positional path, otherwise use the shared catalog selection.
fn catalog_arg(explicit: Option<PathBuf>) -> Result<PathBuf> {
match explicit {
Some(path) => absolute_catalog_path(&path),
None => catalog_root_for_env(),
}
}
/// The selected catalog root for bus-aware commands: `$CATALOG`, then the standard user catalog.
/// `main` initializes `$CATALOG` from global `--catalog` before dispatch.
fn catalog_root_for_env() -> Result<PathBuf> {
let root = nonempty_env_path("CATALOG")
.or_else(default_catalog_root)
.context(
"no catalog selected: pass --catalog, set $CATALOG, or set $XDG_STATE_HOME/$HOME",
)?;
absolute_catalog_path(&root)
}
/// Set the same native catalog environment that `st2 env` prints. The catalog's own declared session
/// registry is used, not the caller's ambient one: these hand `pty` the roots of the *catalog*.
fn with_bus_env(cmd: &mut std::process::Command, root: &Path) {
cmd.env("CATALOG", root)
.env("ST_ROOT", root)
.env("PTY_ROOT", st2::catalog::pty_root(root));
}
/// `st2 pty [<pty-args>…]` — a thin pass-through to `pty` with the catalog's bus env pre-set, so
/// the maintainer never has to `eval "$(st2 env …)"` first. **Replaces** this process with `pty` (via exec)
/// so the interactive UI keeps the tty, signals, and exit code.
fn pty_cmd(args: &[String]) -> Result<()> {
use std::os::unix::process::CommandExt;
let root = catalog_root_for_env()?;
let mut cmd = std::process::Command::new("pty");
cmd.args(args);
with_bus_env(&mut cmd, &root);
// exec() only returns on failure (e.g. `pty` not on PATH).
let err = cmd.exec();
Err(anyhow::anyhow!("failed to exec `pty`: {err}"))
}
/// `st2 shell [<args>…]` — drop into `$SHELL` with the native catalog environment set. The general
/// form of `st2 pty`.
fn shell_cmd(args: &[String]) -> Result<()> {
use std::os::unix::process::CommandExt;
let root = catalog_root_for_env()?;
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
let mut cmd = std::process::Command::new(&shell);
cmd.args(args);
with_bus_env(&mut cmd, &root);
let err = cmd.exec();
Err(anyhow::anyhow!("failed to exec `{shell}`: {err}"))
}
fn env_cmd(root: &Path) -> Result<()> {
let canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let c = canonical.display();
// The same roots st2 sets on every task it spawns.
println!("export CATALOG={c}");
println!("export ST_ROOT={c}");
println!(
"export PTY_ROOT={}",
st2::catalog::pty_root(&canonical).display()
);
Ok(())
}
fn pretrust_cmd(dirs: &[PathBuf]) -> Result<()> {
let n = st2::pretrust::pretrust(dirs)?;
println!(
"pre-trusted {n} workspace{} in the ambient Claude and Codex configs",
if n == 1 { "" } else { "s" }
);
Ok(())
}
fn doctor_cmd(root: &Path, host: Option<String>, require_supervisor: bool) -> Result<()> {
let this_host = host.unwrap_or_else(detect_host);
let catalog = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
println!(
"st2 doctor — catalog {}, host '{this_host}'",
catalog.display()
);
let mut problems = 0usize;
// 1) The tools a running fleet needs.
report_check(
&mut problems,
tool_on_path("pty"),
"`pty` on PATH",
"not found",
);
// 2) Supervision mode. A one-shot/manual host intentionally has no lock. A caller that expects
// a resident loop can opt into enforcing one; a stale file always indicates an unclean exit.
let host_lock = st2::HostLock::new(root, &this_host);
match host_lock.live_owner() {
Some(_) => report_check(&mut problems, true, "supervisor (st2 up) running", ""),
None if host_lock.has_stale_lock() => report_check(
&mut problems,
false,
"supervision host-lock healthy",
"stale host-lock from a dead supervisor",
),
None if !require_supervisor => report_check(
&mut problems,
true,
"supervision mode manual/--once (no live host-lock)",
"",
),
None => report_check(
&mut problems,
false,
"supervisor (st2 up) running",
"required but no live host-lock — run `st2 up`",
),
}
// 3) Per this-host declaration: active tasks require liveness and fresh presence; suspended
// tasks require no live work; retired tasks require complete record absence.
let _catalog_lock = st2::CatalogLock::shared(&catalog)
.context("acquire shared catalog-authoring lock for doctor snapshot")?;
let found = discover(&catalog);
for e in &found.errors {
report_check(
&mut problems,
false,
&format!("catalog file {}", e.path.display()),
&e.message,
);
}
let runner = SystemRunner::new(catalog.clone(), exec_state_dir(&this_host));
let sessions = match runner.list_sessions() {
Ok(sessions) => sessions,
Err(error) => {
report_check(
&mut problems,
false,
"task runtime readable",
&format!("{error:#}"),
);
anyhow::bail!("{problems} problem(s) found");
}
};
let live: std::collections::HashSet<String> = sessions
.iter()
.filter(|s| s.alive)
.map(|s| s.pty_id.clone())
.collect();
let present: std::collections::HashMap<String, bool> = sessions
.into_iter()
.map(|session| (session.pty_id, session.alive))
.collect();
for spec in &found.specs {
if spec.resolved_host(&this_host) != this_host {
continue;
}
let bus_id = spec.bus_id(&this_host);
if let Some(dir) = spec.path.parent() {
match message::inspect_sent(dir, false) {
Ok(_) => report_check(
&mut problems,
true,
&format!("{bus_id} outbound message ledger"),
"",
),
Err(error) => report_check(
&mut problems,
false,
&format!("{bus_id} outbound message ledger"),
&format!("cannot send: {error:#}"),
),
}
}
// DELTA-006's Resolution Signal, per seat. Silence means both clauses are clear here, so
// the `delivery-state.json` boundary arm is removable once every admitted host is silent
// for the record's window — a trigger nobody produces resolves on memory instead.
// Advisory, not a problem: a carried-forward attempt is correct behaviour today.
let delivery_state_dirs = [