1use std::collections::BTreeMap;
10use std::fmt::Write as _;
11
12use serde::Serialize;
13
14use crate::mode::HarnessMode;
15use crate::policy::{PolicySwitches, TableDecision, TableRow, decision_cell};
16use crate::web::WebSearchPath;
17
18pub const HARNESS_BLOCK_MAX_BYTES: usize = 6 * 1024;
20
21pub const HARNESS_HELP_MAX_BYTES: usize = 32 * 1024;
23
24#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
45#[serde(rename_all = "camelCase")]
46#[non_exhaustive]
47pub struct HarnessManifest {
48 pub harness_version: String,
50 pub surface: SurfaceManifest,
52 pub default_mode: HarnessMode,
54 pub classes: Vec<ClassEntry>,
56 pub members: Vec<MemberEntry>,
58 pub packs: Vec<PackEntry>,
60 pub web: WebSearchPath,
62 pub memory: MemoryEntry,
64 pub safety: Vec<SafetyEntry>,
66 pub languages: Vec<LanguageEntry>,
68 #[serde(skip_serializing_if = "Option::is_none")]
71 pub multi_file_edit: Option<String>,
72 #[serde(skip_serializing_if = "Option::is_none")]
75 pub background_shells: Option<String>,
76 pub help_topics: Vec<String>,
78}
79
80#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
82#[serde(rename_all = "camelCase")]
83#[non_exhaustive]
84pub struct ClassEntry {
85 pub class: String,
87 pub tools: Vec<String>,
89 pub decisions: [ModeDecision; 4],
91 #[serde(skip_serializing_if = "Option::is_none")]
94 pub note: Option<String>,
95}
96
97#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
107#[serde(rename_all = "camelCase")]
108pub enum ModeDecision {
109 Allow,
111 Ask,
113 AskEveryTime,
115 Deny,
117}
118
119impl ModeDecision {
120 pub fn label(self) -> &'static str {
122 match self {
123 Self::Allow => "allow",
124 Self::Ask => "ask",
125 Self::AskEveryTime => "ask every time",
126 Self::Deny => "deny",
127 }
128 }
129
130 fn of(decision: TableDecision) -> Self {
131 match decision {
132 TableDecision::Allow => Self::Allow,
133 TableDecision::Deny => Self::Deny,
134 TableDecision::RequireApproval { non_waivable: false } => Self::Ask,
135 TableDecision::RequireApproval { non_waivable: true } => Self::AskEveryTime,
136 }
137 }
138}
139
140#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
156#[serde(rename_all = "camelCase")]
157#[non_exhaustive]
158pub struct SurfaceManifest {
159 pub name: String,
161 pub version: String,
163 pub commands: Vec<CommandEntry>,
165 #[serde(skip_serializing_if = "Option::is_none")]
167 pub kernel: Option<KernelEntry>,
168 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
170 pub pack_switches: BTreeMap<String, String>,
171}
172
173impl SurfaceManifest {
174 pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
176 Self {
177 name: name.into(),
178 version: version.into(),
179 commands: Vec::new(),
180 kernel: None,
181 pack_switches: BTreeMap::new(),
182 }
183 }
184
185 pub fn library() -> Self {
193 Self::new("library", env!("CARGO_PKG_VERSION"))
194 }
195
196 #[must_use]
198 pub fn command(mut self, entry: CommandEntry) -> Self {
199 self.commands.push(entry);
200 self
201 }
202
203 #[must_use]
205 pub fn commands(mut self, entries: impl IntoIterator<Item = CommandEntry>) -> Self {
206 self.commands.extend(entries);
207 self
208 }
209
210 #[must_use]
212 pub fn with_kernel(mut self, kernel: KernelEntry) -> Self {
213 self.kernel = Some(kernel);
214 self
215 }
216
217 #[must_use]
219 pub fn pack_switch(mut self, pack: impl Into<String>, how: impl Into<String>) -> Self {
220 self.pack_switches.insert(pack.into(), how.into());
221 self
222 }
223}
224
225#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
236#[serde(rename_all = "camelCase")]
237#[non_exhaustive]
238pub struct CommandEntry {
239 pub kind: CommandKind,
241 pub name: String,
243 pub summary: String,
245 #[serde(skip_serializing_if = "Option::is_none")]
247 pub usage: Option<String>,
248}
249
250impl CommandEntry {
251 pub fn slash(name: impl Into<String>, summary: impl Into<String>) -> Self {
253 Self { kind: CommandKind::Slash, name: name.into(), summary: summary.into(), usage: None }
254 }
255
256 pub fn subcommand(
258 name: impl Into<String>,
259 summary: impl Into<String>,
260 long_help: Option<String>,
261 ) -> Self {
262 Self {
263 kind: CommandKind::Subcommand,
264 name: name.into(),
265 summary: summary.into(),
266 usage: long_help,
267 }
268 }
269
270 pub fn flag(name: impl Into<String>, summary: impl Into<String>) -> Self {
272 Self { kind: CommandKind::Flag, name: name.into(), summary: summary.into(), usage: None }
273 }
274
275 fn typed(&self, surface: &str) -> String {
276 match self.kind {
277 CommandKind::Slash => format!("/{}", self.name),
278 CommandKind::Subcommand => format!("{surface} {}", self.name),
279 CommandKind::Flag => format!("{surface} {}", self.name),
280 }
281 }
282}
283
284#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
286#[serde(rename_all = "camelCase")]
287pub enum CommandKind {
288 Slash,
290 Subcommand,
292 Flag,
294}
295
296#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
298#[serde(rename_all = "camelCase")]
299#[non_exhaustive]
300pub struct KernelEntry {
301 pub compiled: bool,
303 pub running: bool,
305}
306
307impl KernelEntry {
308 pub fn new(compiled: bool, running: bool) -> Self {
310 Self { compiled, running }
311 }
312}
313
314#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
316#[serde(rename_all = "camelCase")]
317#[non_exhaustive]
318pub struct MemberEntry {
319 pub name: String,
321 pub kind: String,
323 pub tools: String,
325 pub workspace: String,
327}
328
329impl MemberEntry {
330 pub fn new(name: impl Into<String>, kind: impl Into<String>, tools: impl Into<String>) -> Self {
332 Self {
333 name: name.into(),
334 kind: kind.into(),
335 tools: tools.into(),
336 workspace: "shared".into(),
337 }
338 }
339}
340
341#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
343#[serde(rename_all = "camelCase")]
344#[non_exhaustive]
345pub struct PackEntry {
346 pub name: String,
348 pub state: PackState,
350 #[serde(skip_serializing_if = "Option::is_none")]
352 pub enable: Option<String>,
353}
354
355#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
357#[serde(rename_all = "camelCase")]
358pub enum PackState {
359 Active,
361 Off,
363 NotCompiled,
365}
366
367#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
369#[serde(rename_all = "camelCase")]
370#[non_exhaustive]
371pub struct MemoryEntry {
372 pub working_notes: bool,
374 pub long_term_facts: bool,
376 #[serde(skip_serializing_if = "Option::is_none")]
379 pub embedder: Option<String>,
380}
381
382#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
384#[serde(rename_all = "camelCase")]
385#[non_exhaustive]
386pub struct SafetyEntry {
387 pub mechanism: String,
389 pub covers: String,
391 pub does_not_cover: String,
393}
394
395impl SafetyEntry {
396 fn new(mechanism: &str, covers: &str, does_not_cover: &str) -> Self {
397 Self {
398 mechanism: mechanism.into(),
399 covers: covers.into(),
400 does_not_cover: does_not_cover.into(),
401 }
402 }
403}
404
405#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
407#[serde(rename_all = "camelCase")]
408#[non_exhaustive]
409pub struct LanguageEntry {
410 pub extensions: Vec<String>,
412 pub server: String,
414 pub running: bool,
416}
417
418pub(crate) struct ManifestInputs<'a> {
420 pub(crate) surface: SurfaceManifest,
421 pub(crate) default_mode: HarnessMode,
422 pub(crate) rows: Vec<(String, TableRow)>,
424 pub(crate) switches: PolicySwitches,
425 pub(crate) web_allowlist: &'a [String],
426 pub(crate) shell: Option<&'a crate::shell::IsolationStatus>,
427 pub(crate) unsandboxed_retry: bool,
428 pub(crate) members: Vec<MemberEntry>,
429 pub(crate) active_packs: &'a [String],
430 pub(crate) web: WebSearchPath,
431 pub(crate) memory: MemoryEntry,
432 pub(crate) ledger_durable: bool,
433 pub(crate) plan_rewind: bool,
434 pub(crate) snapshots: Option<crate::snapshot::SnapshotConfig>,
436 pub(crate) model: &'a str,
438}
439
440fn compiled_packs() -> [(&'static str, bool); 5] {
442 [
443 ("browser", cfg!(feature = "browser")),
444 ("computer-use", cfg!(feature = "computer-use")),
445 ("managed", cfg!(feature = "managed")),
446 ("payments", cfg!(feature = "payments")),
447 ("voice", cfg!(feature = "voice")),
448 ]
449}
450
451fn row_name(row: TableRow) -> &'static str {
452 match row {
453 TableRow::ReadTodoDelegate => "read, todos and members",
454 TableRow::PlanExit => "plan exit",
455 TableRow::Edit => "edit",
456 TableRow::EditProtected => "edit, protected path",
457 TableRow::ShellOsSandbox => "shell (OS sandbox)",
458 TableRow::ShellContainer => "shell (container)",
459 TableRow::ShellHost => "shell (host)",
460 TableRow::ShellEscalation => "shell, unsandboxed retry",
461 TableRow::MemoryWrite => "memory write",
462 TableRow::MemoryPropose => "memory, assumed facts",
463 TableRow::WebAllowlisted => "web, allowlisted host",
464 TableRow::WebOther => "web, other host",
465 TableRow::Payment => "payment",
466 TableRow::ComputerUse => "desktop action",
467 TableRow::ExternalReadOnlyTrusted => "other, read-only from a trusted publisher",
468 TableRow::ExternalOther => "other (MCP servers, drivers, skills, extras)",
469 }
470}
471
472fn decisions(row: TableRow, switches: &PolicySwitches) -> [ModeDecision; 4] {
473 HarnessMode::ALL.map(|mode| ModeDecision::of(decision_cell(mode, row).resolve(switches)))
474}
475
476impl HarnessManifest {
477 pub(crate) fn generate(inputs: ManifestInputs<'_>) -> Self {
478 let mut rows: BTreeMap<usize, (TableRow, Vec<String>, Option<String>)> = BTreeMap::new();
480 let position = |row: TableRow| TableRow::ALL.iter().position(|r| *r == row).unwrap_or(0);
481 for (tool, row) in &inputs.rows {
482 rows.entry(position(*row)).or_insert((*row, Vec::new(), None)).1.push(tool.clone());
483 }
484 let mut add = |row: TableRow, note: Option<String>| {
485 rows.entry(position(row)).or_insert((row, Vec::new(), None)).2 = note;
486 };
487 if inputs.rows.iter().any(|(_, row)| *row == TableRow::Edit) {
488 add(
489 TableRow::EditProtected,
490 Some(
491 "AGENTS.md, CLAUDE.md, MEMORY.md, .envrc, lefthook.yml and anything under \
492 .git, .adk, .skills or .claude"
493 .into(),
494 ),
495 );
496 }
497 if inputs.unsandboxed_retry {
498 add(TableRow::ShellEscalation, Some("bash with unsandboxed: true".into()));
499 }
500 if inputs.rows.iter().any(|(_, row)| *row == TableRow::WebOther)
501 && !inputs.web_allowlist.is_empty()
502 {
503 add(TableRow::WebAllowlisted, Some(inputs.web_allowlist.join(", ")));
504 }
505 add(TableRow::ExternalOther, None);
507 let classes = rows
508 .into_values()
509 .map(|(row, mut tools, note)| {
510 tools.sort();
511 tools.dedup();
512 ClassEntry {
513 class: row_name(row).to_string(),
514 tools,
515 decisions: decisions(row, &inputs.switches),
516 note,
517 }
518 })
519 .collect();
520 let packs = compiled_packs()
521 .into_iter()
522 .map(|(name, compiled)| {
523 let state = if inputs.active_packs.iter().any(|pack| pack == name) {
524 PackState::Active
525 } else if compiled {
526 PackState::Off
527 } else {
528 PackState::NotCompiled
529 };
530 PackEntry {
531 name: name.to_string(),
532 state,
533 enable: (state == PackState::Off)
534 .then(|| inputs.surface.pack_switches.get(name).cloned())
535 .flatten(),
536 }
537 })
538 .collect();
539 let mut safety = vec![SafetyEntry::new(
540 "action ledger",
541 "a tool call with side effects that already ran is answered from its record, not run \
542 again, when a run resumes",
543 if inputs.ledger_durable {
544 "effects of commands the shell runs"
545 } else {
546 "effects of commands the shell runs; the ledger lives in memory, so a restart forgets it"
547 },
548 )];
549 if let Some(shell) = inputs.shell {
550 safety.push(sandbox_entry(shell));
551 }
552 safety.push(match &inputs.snapshots {
553 Some(config) => {
555 let (covers, does_not_cover) =
556 crate::snapshot::safety_covers(config, inputs.plan_rewind);
557 SafetyEntry::new("rewind", &covers, &does_not_cover)
558 }
559 None => SafetyEntry::new(
560 "rewind",
561 if inputs.plan_rewind {
562 "the plan graph's position only"
563 } else {
564 "nothing: no rewind in this build"
565 },
566 "files: no file is restored; nor pushes, payments, sent messages or webhooks",
567 ),
568 });
569 let mut help_topics: Vec<String> =
570 ["commands", "cli <subcommand>", "manifest"].into_iter().map(String::from).collect();
571 help_topics.sort();
572 Self {
573 harness_version: env!("CARGO_PKG_VERSION").to_string(),
574 surface: inputs.surface,
575 default_mode: inputs.default_mode,
576 classes,
577 members: inputs.members,
578 packs,
579 web: inputs.web,
580 memory: inputs.memory,
581 safety,
582 languages: Vec::new(),
583 multi_file_edit: inputs
584 .rows
585 .iter()
586 .any(|(tool, _)| tool == crate::edits::APPLY_PATCH)
587 .then(|| crate::edits::preferred_multi_file_edit(inputs.model).to_string()),
588 background_shells: inputs
589 .rows
590 .iter()
591 .any(|(tool, _)| tool == crate::shell::SHELL_KILL)
592 .then(|| background_note(inputs.shell)),
593 help_topics,
594 }
595 }
596
597 pub fn render(&self) -> String {
607 let header = format!(
608 "<harness version=\"{}\" surface=\"{} {}\">\n",
609 self.harness_version, self.surface.name, self.surface.version
610 );
611 let footer = "</harness>";
612 let sections = [
616 ("classes", 0, vec![self.render_classes()]),
617 (
618 "commands",
619 3,
620 vec![
621 self.render_commands(Listing::Commands),
622 self.render_commands(Listing::CommandNames),
623 ],
624 ),
625 ("setup", 4, vec![self.render_setup()]),
626 ("safety", 1, vec![self.render_safety()]),
627 ("flags", 5, vec![self.render_commands(Listing::Flags)]),
628 (
629 "help",
630 2,
631 vec![format!(
632 "harness_help explains the harness on demand; topics: {}, or a page name.\n",
633 self.help_topics.join(", ")
634 )],
635 ),
636 ];
637 let reserve = "Cut for length: . harness_help <topic> returns them.\n".len()
639 + sections.iter().map(|(name, ..)| name.len() + ", ".len()).sum::<usize>();
640 let mut room =
641 HARNESS_BLOCK_MAX_BYTES.saturating_sub(header.len() + footer.len() + reserve);
642 let mut ranked: Vec<&(&str, u8, Vec<String>)> = sections.iter().collect();
643 ranked.sort_by_key(|(_, rank, _)| *rank);
644 let mut kept: Vec<(&str, &String)> = Vec::new();
645 for (name, _, forms) in ranked {
646 if let Some(text) = forms.iter().find(|text| text.len() <= room) {
648 room -= text.len();
649 kept.push((*name, text));
650 }
651 }
652 let mut out = header;
653 let mut cut = Vec::new();
654 for (name, _, forms) in §ions {
655 if forms[0].is_empty() {
656 continue;
657 }
658 match kept.iter().find(|(kept, _)| kept == name) {
659 Some((_, text)) => out.push_str(text),
660 None => cut.push(*name),
661 }
662 }
663 if !cut.is_empty() {
664 let _ = writeln!(
665 out,
666 "Cut for length: {}. harness_help <topic> returns them.",
667 cut.join(", ")
668 );
669 }
670 out.push_str(footer);
671 out
672 }
673
674 fn render_classes(&self) -> String {
675 let mut out = String::from("Classes (read-only | plan | ask | auto):\n");
676 for class in &self.classes {
677 let decisions =
678 class.decisions.iter().map(|d| d.label()).collect::<Vec<_>>().join(" | ");
679 let mut what = class.tools.join(" ");
680 if let Some(note) = &class.note {
681 if !what.is_empty() {
682 what.push_str("; ");
683 }
684 what.push_str(note);
685 }
686 if what.is_empty() {
687 let _ = writeln!(out, " {}: {decisions}", class.class);
688 } else {
689 let _ = writeln!(out, " {} ({what}): {decisions}", class.class);
690 }
691 }
692 out.push_str(
693 "Standing rules can turn \"ask\" into allow or deny; the reminder lists the ones that \
694 apply. \"ask every time\" is never covered by a rule.\n",
695 );
696 out
697 }
698
699 fn render_commands(&self, listing: Listing) -> String {
701 let flags = listing == Listing::Flags;
702 let mut commands: Vec<&CommandEntry> = self
703 .surface
704 .commands
705 .iter()
706 .filter(|command| (command.kind == CommandKind::Flag) == flags)
707 .collect();
708 if commands.is_empty() {
709 return String::new();
710 }
711 commands.sort_by(|a, b| (a.kind, &a.name).cmp(&(b.kind, &b.name)));
712 let mut out = if flags {
713 String::from("Flags the person passes:\n")
714 } else {
715 String::from(
716 "Commands the person types (you cannot run them; when input looks like a \
717 mistyped command, name the closest one and say what it does, and never claim a \
718 command ran):\n",
719 )
720 };
721 let mut names = Vec::new();
722 for command in commands {
723 if listing == Listing::CommandNames && command.kind == CommandKind::Subcommand {
724 names.push(command.name.as_str());
725 } else {
726 let _ =
727 writeln!(out, " {} {}", command.typed(&self.surface.name), command.summary);
728 }
729 }
730 if !names.is_empty() {
731 let _ = writeln!(
732 out,
733 " {} subcommands (harness_help cli <subcommand> says what one does): {}",
734 self.surface.name,
735 names.join(", ")
736 );
737 }
738 out
739 }
740
741 fn render_setup(&self) -> String {
742 let mut out = String::new();
743 if let Some(kernel) = self.surface.kernel {
744 let _ = writeln!(
745 out,
746 "Kernel: {}",
747 match (kernel.compiled, kernel.running) {
748 (_, true) => "this session runs under the agent kernel",
749 (true, false) => "compiled in; this session does not run under it",
750 (false, false) => "not compiled into this build",
751 }
752 );
753 }
754 if !self.members.is_empty() {
755 let members: Vec<String> = self
756 .members
757 .iter()
758 .map(|m| format!("{} ({}, {} tools)", m.name, m.kind, m.tools))
759 .collect();
760 let _ = writeln!(out, "Members: {}", members.join(", "));
761 }
762 let packs: Vec<String> = self
763 .packs
764 .iter()
765 .map(|pack| match (pack.state, &pack.enable) {
766 (PackState::Active, _) => format!("{} (active)", pack.name),
767 (PackState::Off, Some(how)) => format!("{} (off: {how})", pack.name),
768 (PackState::Off, None) => format!("{} (off)", pack.name),
769 (PackState::NotCompiled, _) => format!("{} (not compiled)", pack.name),
770 })
771 .collect();
772 let _ = writeln!(out, "Packs: {}", packs.join(", "));
773 let web = match &self.web {
775 WebSearchPath::Provider {
776 provider,
777 filter: Some(filter),
778 filter_applied: true,
779 ..
780 } => {
781 format!("{provider}'s built-in search, {filter}")
782 }
783 WebSearchPath::Provider {
784 provider, filter: Some(_), filter_applied: false, ..
785 } => {
786 format!(
787 "{provider}'s built-in search, every domain ({provider} takes no search \
788 filter, so search_domains is not applied)"
789 )
790 }
791 WebSearchPath::Provider { provider, filter: None, .. } => {
792 format!("{provider}'s built-in search, every domain")
793 }
794 WebSearchPath::Governed { provider, filter } => format!(
795 "the governed web_search over {provider}, {}",
796 filter.as_ref().map_or_else(|| "every domain".to_string(), ToString::to_string)
797 ),
798 WebSearchPath::None { reason } => format!("none ({reason})"),
799 };
800 let _ = writeln!(out, "Web search: {web}");
801 let memory = match (self.memory.working_notes, self.memory.long_term_facts) {
802 (false, false) => "off".to_string(),
803 (notes, facts) => {
804 let mut parts = Vec::new();
805 if notes {
806 parts.push("working notes".to_string());
807 }
808 if facts {
809 parts.push(format!(
810 "long-term facts ({})",
811 self.memory.embedder.as_deref().unwrap_or("lexical recall")
812 ));
813 }
814 parts.join(", ")
815 }
816 };
817 let _ = writeln!(out, "Memory: {memory}");
818 if let Some(tool) = &self.multi_file_edit {
819 let _ = writeln!(
820 out,
821 "Edits: edit_file takes several replacements in one file as edits; apply_patch \
822 changes several files, all or none; prefer {tool} across files. An edit of a \
823 file changed since you read it is refused as stale: read it again."
824 );
825 }
826 out.push_str(&self.render_background());
827 out
828 }
829
830 fn render_background(&self) -> String {
831 self.background_shells
832 .as_ref()
833 .map(|note| format!("Background shells: {note}\n"))
834 .unwrap_or_default()
835 }
836
837 fn render_safety(&self) -> String {
838 let mut out = String::from("Safety (promise only what these cover):\n");
839 for entry in &self.safety {
840 let _ = writeln!(
841 out,
842 " {}: covers {}; does not cover {}",
843 entry.mechanism, entry.covers, entry.does_not_cover
844 );
845 }
846 out
847 }
848
849 pub(crate) fn help(
852 &self,
853 topic: Option<&str>,
854 pages: &BTreeMap<String, String>,
855 ) -> Option<String> {
856 let topic = topic.map(str::trim).filter(|topic| !topic.is_empty());
857 let body = match topic {
858 None => {
859 let mut topics = self.help_topics.clone();
860 topics.extend(pages.keys().cloned());
861 format!("Topics: {}\n\n{}", topics.join(", "), self.render())
862 }
863 Some("commands") => {
864 let commands = format!(
865 "{}{}",
866 self.render_commands(Listing::Commands),
867 self.render_commands(Listing::Flags)
868 );
869 if commands.is_empty() {
870 "This surface has no commands: the harness runs as a library.".to_string()
871 } else {
872 commands
873 }
874 }
875 Some("manifest") => serde_json::to_string_pretty(self).ok()?,
876 Some(topic) if topic.starts_with("cli") => {
877 let wanted = topic.trim_start_matches("cli").trim();
878 let entry = self.surface.commands.iter().find(|command| {
879 command.kind == CommandKind::Subcommand && command.name == wanted
880 })?;
881 match &entry.usage {
882 Some(usage) => format!("{} {}\n\n{usage}", self.surface.name, entry.name),
883 None => format!("{} {}: {}", self.surface.name, entry.name, entry.summary),
884 }
885 }
886 Some("classes") => self.render_classes(),
888 Some("setup") => self.render_setup(),
889 Some("safety") => self.render_safety(),
890 Some("flags") => {
891 let flags = self.render_commands(Listing::Flags);
892 if flags.is_empty() { "This surface lists no flags.".to_string() } else { flags }
893 }
894 Some(page) => pages.get(page)?.clone(),
895 };
896 let topic = topic.unwrap_or("");
897 let mut text = format!(
898 "<harness-help topic=\"{topic}\" version=\"{}\">\n{body}\n</harness-help>",
899 self.harness_version
900 );
901 if text.len() > HARNESS_HELP_MAX_BYTES {
902 let mut end = HARNESS_HELP_MAX_BYTES - 64;
903 while !text.is_char_boundary(end) {
904 end -= 1;
905 }
906 text.truncate(end);
907 text.push_str("\n[truncated]\n</harness-help>");
908 }
909 Some(text)
910 }
911}
912
913#[derive(Clone, Copy, PartialEq, Eq)]
915enum Listing {
916 Commands,
918 CommandNames,
920 Flags,
922}
923
924fn background_note(shell: Option<&crate::shell::IsolationStatus>) -> String {
927 match shell {
928 Some(crate::shell::IsolationStatus::OsSandbox { .. }) => {
929 "builds, tests, watchers; a server \
930 started in the sandbox is unreachable from later commands"
931 .to_string()
932 }
933 _ => "servers and watchers run on the host".to_string(),
934 }
935}
936
937fn sandbox_entry(shell: &crate::shell::IsolationStatus) -> SafetyEntry {
938 use crate::shell::IsolationStatus;
939 match shell {
940 IsolationStatus::OsSandbox { enforcer } => SafetyEntry {
941 mechanism: format!("OS sandbox ({enforcer})"),
942 covers: "bash writes outside the workspace and its scratch directory, and the network"
943 .into(),
944 does_not_cover: "the file tools, which run on the host under the policy".into(),
945 },
946 IsolationStatus::Container { image } => SafetyEntry {
947 mechanism: format!("container ({image})"),
948 covers: "bash runs in the container with the workspace mounted".into(),
949 does_not_cover: "the workspace itself, which bash can change".into(),
950 },
951 IsolationStatus::Remote { provider, off_host: true } => SafetyEntry {
952 mechanism: format!("remote sandbox ({provider})"),
953 covers: "bash runs off this host, out of reach of the workspace and the host".into(),
954 does_not_cover: "what the sandbox can reach on the network, and what was copied \
955 into it"
956 .into(),
957 },
958 IsolationStatus::Remote { provider, off_host: false } => SafetyEntry {
959 mechanism: format!("sandbox client ({provider})"),
960 covers: "nothing beyond a separate working directory: bash runs on this host".into(),
961 does_not_cover: "anything the user's account can reach".into(),
962 },
963 IsolationStatus::Degraded { requested, .. } => SafetyEntry {
964 mechanism: "sandbox".into(),
965 covers: format!(
966 "nothing: the {requested} sandbox is unavailable, so bash runs on the host"
967 ),
968 does_not_cover: "anything the user's account can reach".into(),
969 },
970 IsolationStatus::Host => SafetyEntry::new(
971 "sandbox",
972 "nothing: bash runs on the host with the user's permissions",
973 "anything the user's account can reach",
974 ),
975 }
976}
977
978#[cfg(test)]
979mod tests {
980 use super::*;
981
982 fn manifest(commands: usize) -> HarnessManifest {
983 manifest_with(commands, None)
984 }
985
986 fn manifest_with(
987 commands: usize,
988 snapshots: Option<crate::snapshot::SnapshotConfig>,
989 ) -> HarnessManifest {
990 let surface =
991 SurfaceManifest::new("adk-rust", "3.0.0")
992 .commands((0..commands).map(|n| {
993 CommandEntry::flag(format!("--flag-{n:04}"), "a flag with a summary")
994 }));
995 manifest_for(surface, snapshots)
996 }
997
998 fn manifest_for(
999 surface: SurfaceManifest,
1000 snapshots: Option<crate::snapshot::SnapshotConfig>,
1001 ) -> HarnessManifest {
1002 HarnessManifest::generate(ManifestInputs {
1003 surface,
1004 default_mode: HarnessMode::Ask,
1005 rows: vec![
1006 ("read_file".into(), TableRow::ReadTodoDelegate),
1007 ("edit_file".into(), TableRow::Edit),
1008 ("bash".into(), TableRow::ShellHost),
1009 ],
1010 switches: PolicySwitches::default(),
1011 web_allowlist: &[],
1012 shell: None,
1013 unsandboxed_retry: false,
1014 members: Vec::new(),
1015 active_packs: &[],
1016 web: WebSearchPath::None { reason: "off".into() },
1017 memory: MemoryEntry::default(),
1018 ledger_durable: true,
1019 plan_rewind: false,
1020 snapshots,
1021 model: "scripted",
1022 })
1023 }
1024
1025 #[test]
1028 fn the_rewind_entry_follows_the_snapshot_configuration() {
1029 let off = manifest(0).render();
1030 assert!(off.contains("rewind: covers nothing: no rewind in this build"), "{off}");
1031 assert!(off.contains("no file is restored"), "{off}");
1032 let on = manifest_with(0, Some(crate::snapshot::SnapshotConfig::default())).render();
1033 assert!(on.contains("shell writes included"), "{on}");
1034 assert!(on.contains("/rewind restores those files"), "{on}");
1035 assert!(on.contains("reaches 50000 files is partial"), "{on}");
1036 assert!(!on.contains("no file is restored"), "{on}");
1037 }
1038
1039 #[test]
1040 fn the_block_names_the_preferred_multi_file_edit_tool_for_the_model() {
1041 let generate = |model: &str| {
1042 HarnessManifest::generate(ManifestInputs {
1043 surface: SurfaceManifest::library(),
1044 default_mode: HarnessMode::Ask,
1045 rows: vec![
1046 ("edit_file".into(), TableRow::Edit),
1047 ("apply_patch".into(), TableRow::Edit),
1048 ],
1049 switches: PolicySwitches::default(),
1050 web_allowlist: &[],
1051 shell: None,
1052 unsandboxed_retry: false,
1053 members: Vec::new(),
1054 active_packs: &[],
1055 web: WebSearchPath::None { reason: "off".into() },
1056 memory: MemoryEntry::default(),
1057 ledger_durable: true,
1058 plan_rewind: false,
1059 snapshots: None,
1060 model,
1061 })
1062 };
1063 let openai = generate("gpt-5.6-terra");
1064 assert_eq!(openai.multi_file_edit.as_deref(), Some("apply_patch"));
1065 assert!(openai.render().contains("prefer apply_patch across files"));
1066 let anthropic = generate("claude-sonnet-5-5").render();
1067 assert!(anthropic.contains("prefer edit_file across files"), "{anthropic}");
1068 assert!(anthropic.contains("edit (apply_patch edit_file): deny | deny | ask | allow"));
1069 assert_eq!(manifest(3).multi_file_edit, None, "no apply_patch, no recommendation");
1070 }
1071
1072 #[test]
1073 fn a_long_block_is_cut_at_its_cap_and_names_what_it_cut() {
1074 let block = manifest(400).render();
1075 assert!(block.len() <= HARNESS_BLOCK_MAX_BYTES, "{} bytes", block.len());
1076 assert!(block.contains("Cut for length: flags"), "{block}");
1077 assert!(block.contains("Safety"), "the sections after a cut one still go in: {block}");
1078 assert!(
1079 block.contains("edit (edit_file): deny | deny | ask | allow"),
1080 "classes are never cut"
1081 );
1082 assert!(block.ends_with("</harness>"));
1083 }
1084
1085 #[test]
1089 fn the_commands_never_push_out_the_safety_lines() {
1090 let pages = BTreeMap::new();
1091 for count in 0..=120 {
1092 let surface = SurfaceManifest::new("adk-rust", "3.0.0")
1093 .commands((0..count).map(|n| {
1094 CommandEntry::subcommand(format!("command-{n:03}"), "a subcommand", None)
1095 }))
1096 .commands(
1097 (0..count).map(|n| CommandEntry::flag(format!("--flag-{n:03}"), "a flag")),
1098 );
1099 let manifest = manifest_for(surface, None);
1100 let block = manifest.render();
1101 assert!(block.len() <= HARNESS_BLOCK_MAX_BYTES, "{count}: {} bytes", block.len());
1102 assert!(
1103 block.contains("edit (edit_file): deny | deny | ask | allow"),
1104 "{count}: {block}"
1105 );
1106 assert!(
1107 block.contains("Safety (promise only what these cover):\n"),
1108 "{count}: {block}"
1109 );
1110 assert!(block.contains("\nharness_help explains the harness"), "{count}: {block}");
1111 let short = block.lines().find_map(|line| {
1112 line.strip_prefix(
1113 " adk-rust subcommands (harness_help cli <subcommand> says what one does): ",
1114 )
1115 });
1116 for n in 0..count {
1117 let name = format!("command-{n:03}");
1118 let listed = block.contains(&format!(" adk-rust {name} a subcommand\n"))
1119 || short.is_some_and(|names| names.split(", ").any(|listed| listed == name));
1120 assert!(listed, "{count}: {name} is in the block, by name at least: {block}");
1121 }
1122 let cut = block.lines().find_map(|line| line.strip_prefix("Cut for length: "));
1123 let names = cut.and_then(|line| line.split_once(". ")).map_or("", |(names, _)| names);
1124 for name in names.split(", ").filter(|name| !name.is_empty()) {
1125 assert!(
1126 manifest.help(Some(name), &pages).is_some(),
1127 "{count}: harness_help {name}"
1128 );
1129 }
1130 }
1131 let crowded = |count: usize| {
1132 let surface = SurfaceManifest::new("adk-rust", "3.0.0")
1133 .command(CommandEntry::slash("approvals", "Calls waiting for a decision"))
1134 .commands((0..count).map(|n| {
1135 CommandEntry::subcommand(format!("command-{n:03}"), "a subcommand", None)
1136 }));
1137 manifest_for(surface, None).render()
1138 };
1139 let names = crowded(200);
1140 assert!(names.contains(" /approvals Calls waiting for a decision\n"), "{names}");
1141 assert!(
1142 names.contains(
1143 " adk-rust subcommands (harness_help cli <subcommand> says what one does): \
1144 command-000, command-001, "
1145 ),
1146 "the subcommands stay by name: {names}"
1147 );
1148 assert!(!names.contains("Cut for length"), "{names}");
1149 let cut = crowded(600);
1150 assert!(cut.contains("Cut for length: commands."), "{cut}");
1151 assert!(cut.contains("Safety (promise only what these cover):\n"), "{cut}");
1152 }
1153
1154 #[test]
1155 fn harness_help_returns_each_section_the_block_can_cut() {
1156 let manifest = manifest(400);
1157 let pages = BTreeMap::new();
1158 assert!(manifest.render().contains("Cut for length: flags."));
1159 let flags = manifest.help(Some("flags"), &pages).unwrap();
1160 assert!(flags.contains("adk-rust --flag-0399 a flag with a summary"), "{flags}");
1161 for (topic, line) in [
1162 ("classes", " edit (edit_file): deny | deny | ask | allow\n"),
1163 ("setup", "Packs: "),
1164 ("safety", " rewind: covers nothing: no rewind in this build"),
1165 ] {
1166 let help = manifest.help(Some(topic), &pages).unwrap();
1167 assert!(help.contains(line), "harness_help {topic}: {help}");
1168 }
1169 let none = manifest_for(SurfaceManifest::library(), None);
1170 assert!(none.help(Some("flags"), &pages).unwrap().contains("This surface lists no flags."));
1171 }
1172
1173 #[test]
1174 fn the_block_names_the_search_filter_and_the_embedder_never_the_fetch_allowlist() {
1175 let allowlist = vec!["internal.example".to_string()];
1176 let generate = |web: WebSearchPath| {
1177 HarnessManifest::generate(ManifestInputs {
1178 surface: SurfaceManifest::library(),
1179 default_mode: HarnessMode::Ask,
1180 rows: vec![("web_fetch".into(), TableRow::WebAllowlisted)],
1181 switches: PolicySwitches::default(),
1182 web_allowlist: &allowlist,
1183 shell: None,
1184 unsandboxed_retry: false,
1185 members: Vec::new(),
1186 active_packs: &[],
1187 web,
1188 memory: MemoryEntry {
1189 working_notes: false,
1190 long_term_facts: true,
1191 embedder: Some("embedded by onnx/BAAI/bge-small-en-v1.5".into()),
1192 },
1193 ledger_durable: true,
1194 plan_rewind: false,
1195 snapshots: None,
1196 model: "scripted",
1197 })
1198 .render()
1199 };
1200 let provider = |provider: &str, filter, filter_applied| WebSearchPath::Provider {
1201 provider: provider.into(),
1202 tool: "web_search".into(),
1203 filter,
1204 filter_applied,
1205 };
1206 let block = generate(provider("anthropic", None, true));
1207 assert!(
1208 block.contains("Web search: anthropic's built-in search, every domain\n"),
1209 "{block}"
1210 );
1211 assert!(
1212 block.contains("long-term facts (embedded by onnx/BAAI/bge-small-en-v1.5)"),
1213 "{block}"
1214 );
1215 let only = Some(crate::web::SearchDomains::Allowed(vec!["docs.rs".into()]));
1216 let block = generate(provider("anthropic", only.clone(), true));
1217 assert!(block.contains("Web search: anthropic's built-in search, only docs.rs"), "{block}");
1218 let block = generate(provider("gemini", only, false));
1219 assert!(block.contains("gemini takes no search filter"), "{block}");
1220 assert!(!block.contains("Web search: gemini's built-in search, only"), "{block}");
1221 }
1222
1223 #[test]
1224 fn a_short_block_cuts_nothing() {
1225 let block = manifest(3).render();
1226 assert!(!block.contains("Cut for length"), "{block}");
1227 assert!(block.contains("adk-rust --flag-0002 a flag with a summary"));
1228 }
1229
1230 #[test]
1231 fn help_is_capped_and_unknown_topics_are_none() {
1232 let manifest = manifest(4000);
1233 let pages = BTreeMap::new();
1234 let commands = manifest.help(Some("commands"), &pages).unwrap();
1235 assert!(commands.len() <= HARNESS_HELP_MAX_BYTES, "{} bytes", commands.len());
1236 assert!(commands.ends_with("[truncated]\n</harness-help>"));
1237 assert!(manifest.help(Some("cli nope"), &pages).is_none());
1238 assert!(manifest.help(Some("nope"), &pages).is_none());
1239 }
1240}