diff --git a/CLAUDE.md b/CLAUDE.md index dd195bb4..74347b44 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -42,7 +42,7 @@ Subprocess coding agents (Claude Code, Codex, Cursor) reach core's in-process MC `.gaviero-workspace` files (any basename, fixed extension) describe multi-folder workspaces; bare directories are treated as single-folder workspaces — a bare directory holding a workspace file first asks whether to open that workspace instead (`--folder` skips the question). Dispatched at TUI startup in [crates/gaviero-tui/src/main.rs](crates/gaviero-tui/src/main.rs). `gaviero --workspace ` opens the workspace file already in ``, or has the first-run wizard ([crates/gaviero-tui/src/setup.rs](crates/gaviero-tui/src/setup.rs)) build `.gaviero-workspace` from the sub-folders the user picks. That setup screen is the only place initial configuration is authored — it runs before `App` exists, at every launch while the target has no `.gaviero/settings.json` (a folder's own, or the one beside an opened `.gaviero-workspace` file — the workspace layer), and offers: editor-only (preselected, also Esc — writes nothing; `App::enter_editor_only` hides the side panel and skips agents, memory, code graph, MCP, remote and the root `.cursor`/`.cursorignore` writes), minimal (`{}`), or full — a byte-for-byte copy of the global `$GAVIERO_ROOT/.gaviero/settings.json`, or gaviero's built-in full settings when that file does not exist. Workspaces get the same three choices for that one workspace-layer file, which every member inherits; `--workspace` on a directory without a workspace file first picks the members and writes it (editor-only then writes just the workspace file). A `gaviero-cli` run never creates `.gaviero/settings.json`: it finds the workspace the TUI would open by walking up from its run root ([crates/gaviero-cli/src/state.rs](crates/gaviero-cli/src/state.rs)) and shares its memory, or runs on throwaway state with `--isolated` (also the fallback when no workspace is found). -Scripts choose models in one way only: by tier. Every agent declares its default tier (`agent { tier high }`); a workflow's `tiers { }` block moves agents in that workflow, `gaviero-cli --tier =` moves one for a run (beating the block), and a list item's `tier` moves its clone. Scripts never declare `client` blocks, `tier ` lines or model-valued params. **Model profiles** are the one place a tier becomes a model: `.gaviero/dsl/profiles/.gaviero` holds only `client` + `tier` declarations (discovered like scripts — [crates/gaviero-core/src/script_profiles.rs](crates/gaviero-core/src/script_profiles.rs); merged in [crates/gaviero-dsl/src/profile.rs](crates/gaviero-dsl/src/profile.rs)). Chosen with `gaviero-cli --profile ` or the SWARM form; with no choice the profile named `default` is used. Shipped example: [crates/gaviero-dsl/examples/profiles/default.gaviero](crates/gaviero-dsl/examples/profiles/default.gaviero). +Scripts choose models in one way only: by tier. Every agent declares its default tier (`agent { tier high }`); a workflow's `tiers { }` block moves agents in that workflow, `gaviero-cli --tier =` moves one for a run (beating the block), and a list item's `tier` moves its clone; `gaviero-cli --tier-client =` / `--tier-effort =` (or the SWARM form's Tiers rows) point a tier at another client **of the selected profile** and/or another effort for one run. Scripts never declare `client` blocks, `tier ` lines or model-valued params. **Model profiles** are the one place a tier becomes a model: `.gaviero/dsl/profiles/.gaviero` holds only `client` + `tier` declarations (discovered like scripts — [crates/gaviero-core/src/script_profiles.rs](crates/gaviero-core/src/script_profiles.rs); merged in [crates/gaviero-dsl/src/profile.rs](crates/gaviero-dsl/src/profile.rs)). Chosen with `gaviero-cli --profile ` or the SWARM form; with no choice the profile named `default` is used. Shipped example: [crates/gaviero-dsl/examples/profiles/default.gaviero](crates/gaviero-dsl/examples/profiles/default.gaviero). ### Agent Runtime Parity diff --git a/crates/gaviero-cli/CLAUDE.md b/crates/gaviero-cli/CLAUDE.md index 99332516..67a5966e 100644 --- a/crates/gaviero-cli/CLAUDE.md +++ b/crates/gaviero-cli/CLAUDE.md @@ -39,7 +39,7 @@ Full user-facing flag tables: [README.md](README.md). Do not duplicate every fie - **stdout = results, stderr = telemetry.** Observers always log to stderr. - **Model spec:** `provider:model` required. Accepted prefixes include `claude:`, `codex:`, `cursor:`, `ollama:`, `local:`, `deepseek:`, `dsh:` ([`validate_model_spec`](../gaviero-core/src/swarm/backend/shared.rs)). Default: workspace `agent.model`, then `claude:sonnet`. - **`--repo` vs `--workspace`:** `execution repo` vs `execution document` ([`workflow_execution_mode`](../gaviero-dsl/src/lib.rs)). Conflicts with each other; `--workspace` defaults to the plan file's directory when `--var PLAN_FILE=...` is set. -- **DSL precedence.** Models: `--profile` (else the profile named `default`) says what each tier means; an agent's tier is `--tier AGENT=TIER` > the workflow's `tiers { }` > its own `tier`. Vars: agent-level > `--var` > script-level. Params: `--param` (see [`workflow_params`](../gaviero-dsl/src/workflow_params.rs)). +- **DSL precedence.** Models: `--profile` (else the profile named `default`) says what each tier means; an agent's tier is `--tier AGENT=TIER` > the workflow's `tiers { }` > its own `tier`; `--tier-client TIER=CLIENT` points a tier at another client of the same profile and `--tier-effort TIER=EFFORT` changes its effort, for one run (merged per tier by `gaviero_dsl::TierOverride::from_pairs`). Vars: agent-level > `--var` > script-level. Params: `--param` (see [`workflow_params`](../gaviero-dsl/src/workflow_params.rs)). - **State follows the TUI.** [`state::discover`](src/state.rs) walks the run root and its parents for `.gaviero/settings.json` or `.gaviero/memory.db` (never `$HOME`) and honours a `*.gaviero-workspace` listing that folder. Runs share that workspace's memory (`MemoryStores::open` at its state root, configured embedder, repo scope = the member folder containing the run root). `--isolated`, or no workspace found, means throwaway memory/graph/telemetry in a temp dir; settings are still read, skills are off, and synthesized agent configs are restored at exit. Admin commands require a discovered workspace; `--history` / `--mcp-stats` fall back to the run root. - **Never build a code graph for one root into another root's DB.** A build deletes every file it did not scan. A run from a workspace folder uses the graph the TUI keeps for that folder; subfolder runs use `/.gaviero/graphs//` (`RunState::graph_db`). - **Memory ops open the same `MemoryServices`** as the TUI; never bypass the writer task. @@ -49,7 +49,7 @@ Full user-facing flag tables: [README.md](README.md). Do not duplicate every fie - **Never add a flag without adding the field on `Cli` first.** Docs trail the struct. - **Never write directly to a file.** Synthetic-task mode still goes through the Write Gate (`AutoAccept` when `--auto-accept`). -- **Models come from tiers only.** There is no `--tiers-file` and no model-valued `--param`; do not add one. `--param` values are list items (`id=tier`). +- **Models come from tiers only.** There is no `--tiers-file` and no model-valued `--param`; do not add one. `--tier-client` names a client the profile declares, never a model string. `--param` values are list items (`id=tier`). - **Always validate the model spec via core** — do not re-parse prefixes in CLI code. - **Never document `--no-memory`.** It does not exist on `Cli`. diff --git a/crates/gaviero-cli/README.md b/crates/gaviero-cli/README.md index 7083b90a..73fbc691 100644 --- a/crates/gaviero-cli/README.md +++ b/crates/gaviero-cli/README.md @@ -154,6 +154,8 @@ No public library API. The `Cli` struct in `src/main.rs` is authoritative; this | `--param` | `NAME=VALUE` | Supply a workflow list `param`: `id=tier,…`, ids, or a list literal (repeatable, requires `--script`) | | `--profile` | `` | Model profile from `.gaviero/dsl/profiles/` or a file path (`client` + `tier` only; requires `--script`); default: the profile named `default` | | `--tier` | `AGENT=TIER` | Run one agent on another tier; beats the workflow's `tiers { }` entry (repeatable; requires `--script`) | +| `--tier-client` | `TIER=CLIENT` | For this run, point a tier at another client of the selected profile; a tier the profile lacks is added (repeatable; requires `--script`) | +| `--tier-effort` | `TIER=EFFORT` | For this run, run a tier at another effort (on its client, or the `--tier-client` one); other tiers sharing that client keep theirs (repeatable; requires `--script`) | | `--coordinated` | — | Emit a reviewable plan and exit (requires `--task`) | | `--output` | `` | Save the generated plan (`--coordinated` only) | diff --git a/crates/gaviero-cli/src/main.rs b/crates/gaviero-cli/src/main.rs index cde0e4ce..1a5cdb8d 100644 --- a/crates/gaviero-cli/src/main.rs +++ b/crates/gaviero-cli/src/main.rs @@ -258,6 +258,23 @@ struct Cli { #[arg(long = "profile", value_name = "NAME|PATH", requires = "script")] profile: Option, + /// Point one tier of the model profile at another of the profile's + /// clients for this run. Format: `TIER=CLIENT` (e.g. `--tier-client + /// high=sol` runs every `high` agent on the profile's `sol` client). A + /// tier the profile lacks is added. The profile file is not changed and + /// stays the only place a model is declared. Can be specified multiple + /// times. Only valid with `--script`. + #[arg(long = "tier-client", value_name = "TIER=CLIENT", requires = "script")] + tier_clients: Vec, + + /// Run one tier of the model profile at another effort for this run. + /// Format: `TIER=EFFORT` (e.g. `--tier-effort high=xhigh`). Applies to + /// the tier's client, or the one `--tier-client` gives it; other tiers on + /// the same client keep theirs. The model must offer that effort. + /// Can be specified multiple times. Only valid with `--script`. + #[arg(long = "tier-effort", value_name = "TIER=EFFORT", requires = "script")] + tier_efforts: Vec, + /// Print the N most recent retrieval manifests (Tier S / S4) and exit. /// Useful for auditing what memory was injected into recent chat turns. #[arg(long = "manifest-last")] @@ -1393,14 +1410,30 @@ fn parse_param_overrides(raw: &[String]) -> Result> { /// `--tier AGENT=TIER` pairs. fn parse_agent_tiers(raw: &[String]) -> Result> { + parse_pairs(raw, "--tier", "AGENT=TIER") +} + +/// `--tier-client TIER=CLIENT` and `--tier-effort TIER=EFFORT`, one override +/// per tier. +fn parse_tier_overrides( + clients: &[String], + efforts: &[String], +) -> Result> { + Ok(gaviero_dsl::TierOverride::from_pairs( + &parse_pairs(clients, "--tier-client", "TIER=CLIENT")?, + &parse_pairs(efforts, "--tier-effort", "TIER=EFFORT")?, + )) +} + +fn parse_pairs(raw: &[String], flag: &str, shape: &str) -> Result> { raw.iter() .map(|s| { - let (agent, tier) = s + let (key, value) = s .split_once('=') - .map(|(a, t)| (a.trim(), t.trim())) - .filter(|(a, t)| !a.is_empty() && !t.is_empty()) - .ok_or_else(|| anyhow::anyhow!("--tier `{s}`: expected AGENT=TIER"))?; - Ok((agent.to_string(), tier.to_string())) + .map(|(k, v)| (k.trim(), v.trim())) + .filter(|(k, v)| !k.is_empty() && !v.is_empty()) + .ok_or_else(|| anyhow::anyhow!("{flag} `{s}`: expected {shape}"))?; + Ok((key.to_string(), value.to_string())) }) .collect() } @@ -4475,6 +4508,7 @@ async fn main() -> Result<()> { ); let override_params = parse_param_overrides(&cli.params)?; let agent_tiers = parse_agent_tiers(&cli.agent_tiers)?; + let tier_overrides = parse_tier_overrides(&cli.tier_clients, &cli.tier_efforts)?; let profile = ProfileCatalog::scan(&workspace, &ScriptCatalog::global_scripts_dir()) .select( cli.profile.as_deref(), @@ -4487,9 +4521,18 @@ async fn main() -> Result<()> { } // Resolves any `include "..."` directives transitively, so multi-file // scripts (shared clients/prompts/etc.) work here. - gaviero_dsl::compile_file_with_profile( + for o in &tier_overrides { + eprintln!( + "[tier] {} -> client {}, effort {}", + o.tier, + o.client.as_deref().unwrap_or("(profile's)"), + o.effort.as_deref().unwrap_or("(client's)") + ); + } + gaviero_dsl::compile_file_with_models( script_path, profile.as_ref(), + &tier_overrides, cli.workflow.as_deref(), runtime_prompt.as_deref(), &override_vars, diff --git a/crates/gaviero-dsl/CLAUDE.md b/crates/gaviero-dsl/CLAUDE.md index 36196cb5..dd2bf79b 100644 --- a/crates/gaviero-dsl/CLAUDE.md +++ b/crates/gaviero-dsl/CLAUDE.md @@ -31,10 +31,12 @@ Examples: **12** workflows + **4** model profiles (`default`, `claude`, `codex`, - `compile` / `compile_with_vars` (inline, take a profile) / `compile_file` — `override_vars`, `agent_tiers` (`--tier`), `override_params`. - `compile_file_with_profile` — `compile_file` plus a [`SelectedProfile`](../gaviero-core/src/script_profiles.rs). Without a profile no tier is bound, so any script with agents fails to compile. +- `compile_file_with_models` — plus `&[TierOverride]` (`--tier-client TIER=CLIENT`, `--tier-effort TIER=EFFORT`): per-run rebinding of a tier to another client **of the same profile** and/or another effort (`profile::rebind_tiers`; an effort clones the client as `__` so tiers sharing it are untouched; unknown client or effort = error; a missing tier is added only with a client). +- `inspect_profile` — a profile's clients (model, effort) and tier bindings; `ScriptInspection::agent_tiers(workflow)` — the agents a workflow runs and their default tier. Both back the SWARM form's Agents / Tiers rows. - `workflow_execution_mode` / `peek_workflow_execution_mode` — `repo` vs `document` anchoring before full compile. - `inspect_file` ([`inspect.rs`](src/inspect.rs)) — a script's inputs (workflows, params, vars, prompt use) without compiling; backs the TUI SWARM form. -**Precedence:** agent-level `vars {}` > CLI `--var` > script-level `vars {}`. Item vars (`for` / roster) are substituted before agent, CLI and script vars. Models — one way only: the profile (chosen, else the one named `default`) maps tiers to clients; an agent's tier is `--tier` > the workflow's `tiers { }` > its own required `tier`, and a list item's `tier` moves its clone. Scripts declare no clients or tier lines. +**Precedence:** agent-level `vars {}` > CLI `--var` > script-level `vars {}`. Item vars (`for` / roster) are substituted before agent, CLI and script vars. Models — one way only: the profile (chosen, else the one named `default`) maps tiers to clients; an agent's tier is `--tier` > the workflow's `tiers { }` > its own required `tier`, and a list item's `tier` moves its clone; `--tier-client` / `--tier-effort` may point a tier at another of the profile's own clients and change its effort for one run. Scripts declare no clients or tier lines. Exact field shapes: [`ast.rs`](src/ast.rs). Language reference: [README.md](README.md). diff --git a/crates/gaviero-dsl/README.md b/crates/gaviero-dsl/README.md index 16feaba7..a3e311ef 100644 --- a/crates/gaviero-dsl/README.md +++ b/crates/gaviero-dsl/README.md @@ -114,6 +114,8 @@ The DSL has no runtime config — behaviour is declared in the script and adjust | Vars | `--var KEY=VALUE` | agent `vars {}` > CLI > script `vars {}` | | What each tier means | `--profile NAME\|PATH` | chosen profile, else the profile named `default` | | An agent's tier | `--tier AGENT=TIER` | CLI > workflow `tiers { }` > the agent's own `tier`; a list item's `tier` moves its clone | +| A tier's model, this run | `--tier-client TIER=CLIENT` | Points a tier at another client **of the same profile** (adds the tier if the profile lacks it); the profile file is unchanged | +| A tier's effort, this run | `--tier-effort TIER=EFFORT` | Runs that tier's client at another effort; other tiers on the same client are untouched | | Workflow list params | `--param NAME=VALUE` | Required params without defaults must be supplied | Provider resolution, memory namespaces, and verification execution are configured via `.gaviero/settings.json` on the `gaviero-core` side. See [gaviero-cli](../gaviero-cli/README.md#configuration). @@ -144,6 +146,7 @@ A script chooses models in one way only: by tier. Tier names are free-form; `low - **Every agent declares its default tier** with `tier `. An agent without one is a compile error. - **A workflow may move agents** to other tiers in its `tiers { … }` block; agents it does not name keep their own. - **A run may move agents** with `--tier AGENT=TIER`, which overrides the block. +- **A run may rebind a tier** with `--tier-client TIER=CLIENT` to another client the profile declares, and change its effort with `--tier-effort TIER=EFFORT` (the SWARM form's Tiers rows do both). Models are still declared only in the profile. - **A list item's `tier`** (`{ id "a" tier top }`, `--param panel=a=top`) moves that item's clones; items without one keep their body agent's tier. ```gaviero diff --git a/crates/gaviero-dsl/src/inspect.rs b/crates/gaviero-dsl/src/inspect.rs index a3f19693..8f48a002 100644 --- a/crates/gaviero-dsl/src/inspect.rs +++ b/crates/gaviero-dsl/src/inspect.rs @@ -6,7 +6,7 @@ use std::collections::HashSet; use std::path::Path; -use crate::ast::{Item, Script, VarKind}; +use crate::ast::{Item, PatternDecl, Script, StepItem, VarKind, WorkflowDecl}; use crate::compiler::peek_workflow_execution_mode; use crate::resolver; use crate::workflow_params::describe_workflow_params; @@ -42,6 +42,16 @@ pub struct ScriptInspection { /// Tiers the script asks for (agents, `tiers { }` blocks, list items), /// in order of appearance. The profile must define each of them. pub tiers: Vec, + /// Every agent, in declaration order, with the tier it declares. + pub agents: Vec, +} + +/// An agent and the tier it declares (`None` only in a script that does not +/// compile). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AgentInspection { + pub name: String, + pub tier: Option, } impl ScriptInspection { @@ -76,6 +86,28 @@ impl ScriptInspection { } vars } + + /// The agents a run of workflow `workflow` (an index into + /// [`Self::workflows`]) dispatches, in declaration order, each with the + /// tier it runs on unless the run moves it: the workflow's `tiers { }` + /// entry, else its own. With no such workflow, or one whose agents cannot + /// be told from its steps, every agent is listed. + pub fn agent_tiers(&self, workflow: usize) -> Vec<(String, String)> { + let wf = self.workflows.get(workflow); + let used = wf.map(|w| w.agents.as_slice()).unwrap_or_default(); + self.agents + .iter() + .filter(|a| used.is_empty() || used.contains(&a.name)) + .map(|a| { + let moved = wf.and_then(|w| w.tiers.iter().find(|(agent, _)| *agent == a.name)); + let tier = moved + .map(|(_, t)| t.clone()) + .or_else(|| a.tier.clone()) + .unwrap_or_default(); + (a.name.clone(), tier) + }) + .collect() + } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -83,6 +115,11 @@ pub struct WorkflowInspection { pub name: String, pub execution: ExecutionMode, pub params: Vec, + /// Agents its steps, loops, judges, `for` bodies and pattern name, in + /// order of appearance; empty when it has no steps. + pub agents: Vec, + /// Its `tiers { }` block. + pub tiers: Vec<(String, String)>, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -114,6 +151,74 @@ pub fn profile_tier_names(profile_path: &Path) -> Result, miette::Re Ok(tier_names(&profile)) } +/// What a model profile offers: its clients and which one each tier means. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ProfileInspection { + /// In declaration order. + pub clients: Vec, + /// `(tier, client)`, in declaration order. + pub tiers: Vec<(String, String)>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProfileClient { + pub name: String, + /// `provider:model`. + pub model: Option, + pub effort: Option, +} + +impl ProfileInspection { + /// The client tier `tier` is bound to. + pub fn client_of(&self, tier: &str) -> Option<&str> { + self.tiers + .iter() + .find(|(t, _)| t == tier) + .map(|(_, c)| c.as_str()) + } + + pub fn client(&self, name: &str) -> Option<&ProfileClient> { + self.clients.iter().find(|c| c.name == name) + } + + pub fn tier_names(&self) -> Vec { + self.tiers.iter().map(|(t, _)| t.clone()).collect() + } +} + +impl ProfileClient { + /// `claude:opus · high`, or the client's name when it has no model. + pub fn summary(&self) -> String { + match (&self.model, &self.effort) { + (Some(model), Some(effort)) => format!("{model} · {effort}"), + (Some(model), None) => model.clone(), + _ => self.name.clone(), + } + } +} + +/// Read a profile file (its includes resolved) without compiling a script. +pub fn inspect_profile(profile_path: &Path) -> Result { + let (profile, _) = resolver::resolve(profile_path).map_err(miette::Report::new)?; + let mut info = ProfileInspection::default(); + for item in &profile.items { + match item { + Item::Client(c) if info.client(&c.name).is_none() => { + info.clients.push(ProfileClient { + name: c.name.clone(), + model: c.model.as_ref().map(|(m, _)| m.clone()), + effort: c.effort.as_ref().map(|(e, _)| e.clone()), + }); + } + Item::TierAlias(t) if info.client_of(&t.name).is_none() => { + info.tiers.push((t.name.clone(), t.client_ref.clone())); + } + _ => {} + } + } + Ok(info) +} + fn tier_names(script: &Script) -> Vec { let mut names: Vec = Vec::new(); for item in &script.items { @@ -160,6 +265,46 @@ fn used_tier_names(script: &Script) -> Vec { names } +fn push_unique(names: &mut Vec, name: &str) { + if !names.iter().any(|n| n == name) { + names.push(name.to_string()); + } +} + +/// The agents a workflow dispatches, as its steps name them. +fn workflow_agents(wf: &WorkflowDecl) -> Vec { + let mut names = Vec::new(); + for step in wf.steps.iter().flat_map(|(steps, _)| steps) { + match step { + StepItem::Agent(name, _) => push_unique(&mut names, name), + StepItem::For(block) => { + for (name, _) in &block.agents { + push_unique(&mut names, name); + } + } + StepItem::Loop(block) => { + for (name, _) in &block.agents { + push_unique(&mut names, name); + } + for (name, _) in block.fors.iter().flat_map(|f| &f.agents) { + push_unique(&mut names, name); + } + for (name, _) in block.template_init.iter().chain(&block.template_refine) { + push_unique(&mut names, name); + } + for (name, _) in block.until.agents() { + push_unique(&mut names, name); + } + } + } + } + if let Some(PatternDecl::MapReduce(pattern)) = &wf.pattern { + push_unique(&mut names, &pattern.discover.0); + push_unique(&mut names, &pattern.reduce.0); + } + names +} + /// Inspect a script on disk, resolving its includes. pub fn inspect_file(entry_path: &Path) -> Result { let (script, sources) = resolver::resolve(entry_path).map_err(miette::Report::new)?; @@ -175,6 +320,12 @@ fn inspect_script(script: &Script, sources: &[(String, String)]) -> ScriptInspec name: wf.name.clone(), execution: peek_workflow_execution_mode(script, Some(&wf.name)), params: describe_workflow_params(script, wf), + agents: workflow_agents(wf), + tiers: wf + .tiers + .iter() + .map(|t| (t.agent.clone(), t.tier.clone())) + .collect(), }), _ => None, }) @@ -230,6 +381,17 @@ fn inspect_script(script: &Script, sources: &[(String, String)]) -> ScriptInspec accepts_prompt: requires_prompt || agent_without_prompt, default_execution: peek_workflow_execution_mode(script, None), tiers: used_tier_names(script), + agents: script + .items + .iter() + .filter_map(|item| match item { + Item::Agent(agent) => Some(AgentInspection { + name: agent.name.clone(), + tier: agent.tier_ref.as_ref().map(|(t, _)| t.clone()), + }), + _ => None, + }) + .collect(), } } @@ -429,6 +591,58 @@ mod tests { assert_eq!(info.tiers, ["mine", "low", "top", "high"]); } + #[test] + fn agents_are_listed_with_the_tier_each_workflow_runs_them_on() { + let info = inspect(concat!( + "agent scout { tier high prompt #\"x\"# }\n", + "agent unused { tier low prompt #\"x\"# }\n", + "agent worker { tier high prompt #\"x\"# }\n", + "agent judge { tier medium prompt #\"x\"# }\n", + "workflow w {\n", + " tiers { judge top }\n", + " steps [ scout loop { agents [worker] until agent judge } ]\n", + "}\n", + "workflow all { steps [ unused ] }\n", + )); + assert_eq!(info.workflows[0].agents, ["scout", "worker", "judge"]); + let tiers = info.agent_tiers(0); + let shown: Vec<(&str, &str)> = + tiers.iter().map(|(a, t)| (a.as_str(), t.as_str())).collect(); + assert_eq!(shown, [("scout", "high"), ("worker", "high"), ("judge", "top")]); + assert_eq!(info.agent_tiers(1), [("unused".to_string(), "low".to_string())]); + assert_eq!(info.agent_tiers(9).len(), 4, "no such workflow lists every agent"); + } + + #[test] + fn the_deep_explore_example_lists_every_agent_including_the_judge_and_the_for_body() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/deep_explore.gaviero"); + let info = inspect_file(&path).unwrap(); + let names: Vec = info.agent_tiers(0).into_iter().map(|(a, _)| a).collect(); + for agent in ["scout", "curator", "investigator", "verifier", "stop_judge"] { + assert!(names.iter().any(|n| n == agent), "{agent} missing from {names:?}"); + } + } + + #[test] + fn a_profile_reports_its_clients_and_bindings() { + let dir = tempfile::tempdir().unwrap(); + let profile = dir.path().join("p.gaviero"); + std::fs::write( + &profile, + concat!( + "client opus { model \"claude:opus\" privacy public effort high }\n", + "client sol { model \"codex:gpt-6.1-sol\" privacy public }\n", + "tier high opus\ntier high-codex sol\n", + ), + ) + .unwrap(); + let info = inspect_profile(&profile).unwrap(); + assert_eq!(info.tier_names(), ["high", "high-codex"]); + assert_eq!(info.client_of("high-codex"), Some("sol")); + assert_eq!(info.client("opus").unwrap().summary(), "claude:opus · high"); + assert_eq!(info.client("sol").unwrap().summary(), "codex:gpt-6.1-sol"); + } + #[test] fn agent_without_a_prompt_accepts_one_without_requiring_it() { let info = inspect("agent a { tier t description \"do it\" }\n"); diff --git a/crates/gaviero-dsl/src/lib.rs b/crates/gaviero-dsl/src/lib.rs index 01dac063..29ade7a6 100644 --- a/crates/gaviero-dsl/src/lib.rs +++ b/crates/gaviero-dsl/src/lib.rs @@ -19,9 +19,11 @@ pub use gaviero_core::swarm::plan::{CompiledPlan, ExecutionMode}; pub use compiler::CompiledScript; pub use error::{DslError, DslErrors}; pub use ast::VarKind; +pub use profile::TierOverride; pub use inspect::{ - ParamInspection, ParamKindInfo, ScriptInspection, VarInspection, WorkflowInspection, - inspect_file, profile_tier_names, + AgentInspection, ParamInspection, ParamKindInfo, ProfileClient, ProfileInspection, + ScriptInspection, VarInspection, WorkflowInspection, inspect_file, inspect_profile, + profile_tier_names, }; use gaviero_core::script_profiles::SelectedProfile; @@ -102,7 +104,8 @@ pub fn compile_with_vars( let mut sources = vec![(filename.to_string(), source.to_string())]; profile::reject_model_tables(&script, &sources).map_err(miette::Report::new)?; if let Some(profile) = profile { - profile::apply_profile(&mut script, &mut sources, profile).map_err(miette::Report::new)?; + profile::apply_profile(&mut script, &mut sources, profile, &[]) + .map_err(miette::Report::new)?; } // Phase 3: Compile @@ -162,11 +165,48 @@ pub fn compile_file_with_profile( override_vars: &[(String, String)], agent_tiers: &[(String, String)], override_params: &[(String, String)], +) -> Result { + compile_file_with_models( + entry_path, + profile, + &[], + workflow, + runtime_prompt, + override_vars, + agent_tiers, + override_params, + ) +} + +/// Like [`compile_file_with_profile`], with some of the profile's tiers +/// changed for this run only: pointed at other clients of the same profile +/// (`--tier-client TIER=CLIENT`) and/or run at another effort +/// (`--tier-effort TIER=EFFORT`). A tier the profile does not bind is added +/// when it is given a client. Models are still declared only by the profile. +#[allow(clippy::too_many_arguments)] +pub fn compile_file_with_models( + entry_path: &std::path::Path, + profile: Option<&SelectedProfile>, + tier_overrides: &[TierOverride], + workflow: Option<&str>, + runtime_prompt: Option<&str>, + override_vars: &[(String, String)], + agent_tiers: &[(String, String)], + override_params: &[(String, String)], ) -> Result { let (mut script, mut sources) = resolver::resolve(entry_path).map_err(miette::Report::new)?; profile::reject_model_tables(&script, &sources).map_err(miette::Report::new)?; - if let Some(profile) = profile { - profile::apply_profile(&mut script, &mut sources, profile).map_err(miette::Report::new)?; + match profile { + Some(profile) => { + profile::apply_profile(&mut script, &mut sources, profile, tier_overrides) + .map_err(miette::Report::new)?; + } + None if !tier_overrides.is_empty() => { + return Err(miette::Report::msg( + "--tier-client / --tier-effort need a model profile: no profile is selected", + )); + } + None => {} } compiler::compile_ast_with_sources( &script, diff --git a/crates/gaviero-dsl/src/profile.rs b/crates/gaviero-dsl/src/profile.rs index 0c7d481e..72bd7269 100644 --- a/crates/gaviero-dsl/src/profile.rs +++ b/crates/gaviero-dsl/src/profile.rs @@ -10,12 +10,63 @@ use std::collections::HashSet; use gaviero_core::script_profiles::SelectedProfile; +use gaviero_core::swarm::backend::effort::{is_known_effort, known_effort_names}; use miette::NamedSource; use crate::ast::{ClientDecl, Item, Script, Span, TierAlias}; use crate::error::{DslError, DslErrors}; use crate::resolver; +/// One run's change to what a tier means: another client of the same +/// profile (`--tier-client TIER=CLIENT`), another effort +/// (`--tier-effort TIER=EFFORT`), or both. Models stay declared only in the +/// profile. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TierOverride { + pub tier: String, + /// A client the profile declares; `None` keeps the tier's own. + pub client: Option, + /// An effort name; `None` keeps the client's. + pub effort: Option, +} + +impl TierOverride { + /// Merge `--tier-client` and `--tier-effort` pairs into one override per + /// tier, in order of first mention. + pub fn from_pairs(clients: &[(String, String)], efforts: &[(String, String)]) -> Vec { + let mut overrides: Vec = Vec::new(); + let mut entry = |tier: &str| -> usize { + match overrides.iter().position(|o| o.tier == tier) { + Some(i) => i, + None => { + overrides.push(Self { + tier: tier.to_string(), + client: None, + effort: None, + }); + overrides.len() - 1 + } + } + }; + let mut set = Vec::new(); + for (tier, client) in clients { + set.push((entry(tier), Some(client.clone()), None)); + } + for (tier, effort) in efforts { + set.push((entry(tier), None, Some(effort.clone()))); + } + for (i, client, effort) in set { + if client.is_some() { + overrides[i].client = client; + } + if effort.is_some() { + overrides[i].effort = effort; + } + } + overrides + } +} + /// Name a profile client takes inside the merged script. pub fn profile_client_name(client: &str) -> String { format!("__profile_{client}") @@ -58,13 +109,19 @@ pub(crate) fn reject_model_tables( /// Merge `selected` into `script`. Diagnostics for the profile point at the /// profile's own files, which are appended to `sources`. +/// +/// `overrides` change tiers for this run only, to other clients of the same +/// profile and/or another effort: the profile stays the one place a model +/// is declared. A tier the profile lacks is added (it needs a client). pub(crate) fn apply_profile( script: &mut Script, sources: &mut Vec<(String, String)>, selected: &SelectedProfile, + overrides: &[TierOverride], ) -> Result<(), DslErrors> { let (profile, profile_sources) = resolver::resolve(&selected.path)?; - let (clients, tiers) = split_profile(profile, &profile_sources)?; + let (mut clients, mut tiers) = split_profile(profile, &profile_sources)?; + rebind_tiers(&mut clients, &mut tiers, overrides)?; let offset = sources.len() as u32; sources.extend(profile_sources); @@ -81,6 +138,82 @@ pub(crate) fn apply_profile( Ok(()) } +/// Apply each override: point the tier at the named client, then, for an +/// effort, at a copy of its client with that effort (named +/// `__`, so the profile's own client and every other tier on +/// it are untouched). A rebound tier keeps the span of the line it replaces; +/// an added tier takes its client's. +fn rebind_tiers( + clients: &mut Vec, + tiers: &mut Vec, + overrides: &[TierOverride], +) -> Result<(), DslErrors> { + let mut errors = Vec::new(); + let error = |reason: String| DslError::Compile { + src: NamedSource::new("", String::new()), + span: (0, 0).into(), + reason, + }; + for o in overrides { + let tier = &o.tier; + let client_name = match (&o.client, tiers.iter().find(|t| t.name == *tier)) { + (Some(name), _) => name.clone(), + (None, Some(existing)) => existing.client_ref.clone(), + (None, None) => { + errors.push(error(format!( + "--tier-effort {tier}=…: the profile has no tier `{tier}`; \ + give it a client with --tier-client {tier}=CLIENT" + ))); + continue; + } + }; + let Some(client) = clients.iter().find(|c| c.name == client_name).cloned() else { + let known: Vec<&str> = clients.iter().map(|c| c.name.as_str()).collect(); + errors.push(error(format!( + "--tier-client {tier}={client_name}: the profile has no client \ + `{client_name}` (it has: {})", + known.join(", ") + ))); + continue; + }; + let bound = match &o.effort { + None => client.name.clone(), + Some(effort) if !is_known_effort(effort) => { + errors.push(error(format!( + "--tier-effort {tier}={effort}: unknown effort (known: {})", + known_effort_names() + ))); + continue; + } + Some(effort) => { + let mut copy = client.clone(); + copy.name = format!("{}__{tier}", client.name); + copy.effort = Some((effort.clone(), client.name_span)); + clients.retain(|c| c.name != copy.name); + let name = copy.name.clone(); + clients.push(copy); + name + } + }; + match tiers.iter_mut().find(|t| t.name == *tier) { + Some(existing) => existing.client_ref = bound, + None => tiers.push(TierAlias { + name: tier.clone(), + name_span: client.name_span, + client_ref: bound, + client_ref_span: client.name_span, + span: client.span, + file_id: client.file_id, + }), + } + } + if errors.is_empty() { + Ok(()) + } else { + Err(DslErrors::new(errors)) + } +} + /// Separate a resolved profile into its clients and tiers, rejecting anything /// that would make it more than a model table. fn split_profile( diff --git a/crates/gaviero-dsl/tests/profiles.rs b/crates/gaviero-dsl/tests/profiles.rs index d9a58924..005b0a59 100644 --- a/crates/gaviero-dsl/tests/profiles.rs +++ b/crates/gaviero-dsl/tests/profiles.rs @@ -332,3 +332,92 @@ fn compile_file_without_a_profile_names_the_fix() { let error = gaviero_dsl::compile_file(&script, None, None, &[], &[], &[]).unwrap_err(); assert!(format!("{error:?}").contains("no model profile is bound"), "{error:?}"); } + +/// A run can point a tier at another client of the same profile, or add a +/// tier bound to one, without editing the profile file. +#[test] +fn a_run_rebinds_tiers_to_other_clients_of_the_profile() { + let dir = tempfile::tempdir().unwrap(); + let script = write(dir.path(), "s.gaviero", AGNOSTIC_SCRIPT); + let claude = chosen(write(dir.path(), "claude.gaviero", CLAUDE_PROFILE)); + let rebind = |pairs: &[(&str, &str)], agent_tiers: &[(String, String)]| { + let pairs: Vec<(String, String)> = pairs + .iter() + .map(|(t, c)| (t.to_string(), c.to_string())) + .collect(); + gaviero_dsl::compile_file_with_models( + &script, + Some(&claude), + &gaviero_dsl::TierOverride::from_pairs(&pairs, &[]), + None, + None, + &[], + agent_tiers, + &[], + ) + .map_err(|report| format!("{report:?}")) + }; + + let plan = rebind(&[("low", "big")], &[]).unwrap(); + assert_eq!(models(&plan)["worker"], pair("claude:fable", "max")); + assert_eq!(models(&plan)["planner"], pair("claude:fable", "max")); + + // A tier the profile lacks is added, and an agent can be moved onto it. + let moved = [("planner".to_string(), "extra".to_string())]; + let plan = rebind(&[("extra", "small")], &moved).unwrap(); + assert_eq!(models(&plan)["planner"], pair("claude:haiku", "low")); + + let error = rebind(&[("low", "nope")], &[]).unwrap_err(); + assert!(error.contains("no client `nope`"), "{error}"); + assert!(error.contains("it has: small"), "{error}"); +} + +/// A run can change a tier's effort, alone or with its client, without +/// touching the client the other tiers share. +#[test] +fn a_run_changes_the_effort_of_one_tier() { + let dir = tempfile::tempdir().unwrap(); + let script = write( + dir.path(), + "s.gaviero", + "agent worker { tier low prompt \"w\" }\nagent other { tier same prompt \"o\" }\n", + ); + let profile = chosen(write( + dir.path(), + "p.gaviero", + concat!( + "client small { model \"claude:haiku\" effort low }\n", + "client big { model \"claude:fable\" effort max }\n", + "tier low small\ntier same small\n", + ), + )); + let run = |clients: &[(&str, &str)], efforts: &[(&str, &str)]| { + let owned = |list: &[(&str, &str)]| -> Vec<(String, String)> { + list.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect() + }; + gaviero_dsl::compile_file_with_models( + &script, + Some(&profile), + &gaviero_dsl::TierOverride::from_pairs(&owned(clients), &owned(efforts)), + None, + None, + &[], + &[], + &[], + ) + .map(|plan| models(&plan)) + .map_err(|report| format!("{report:?}")) + }; + + let effort_only = run(&[], &[("low", "high")]).unwrap(); + assert_eq!(effort_only["worker"], pair("claude:haiku", "high")); + assert_eq!(effort_only["other"], pair("claude:haiku", "low"), "the shared client is untouched"); + + let both = run(&[("low", "big")], &[("low", "medium")]).unwrap(); + assert_eq!(both["worker"], pair("claude:fable", "medium")); + + let error = run(&[], &[("low", "turbo")]).unwrap_err(); + assert!(error.contains("unknown effort"), "{error}"); + let error = run(&[], &[("nowhere", "high")]).unwrap_err(); + assert!(error.contains("no tier `nowhere`"), "{error}"); +} diff --git a/crates/gaviero-tui/CLAUDE.md b/crates/gaviero-tui/CLAUDE.md index 851cdd9c..3c5eea68 100644 --- a/crates/gaviero-tui/CLAUDE.md +++ b/crates/gaviero-tui/CLAUDE.md @@ -38,7 +38,7 @@ Workspace dispatch: directory → `Workspace::single_folder`; `*.gaviero-workspa **Observer bridge:** implements `WriteGateObserver` and `AcpObserver` from [`gaviero_core::observer`](../gaviero-core/src/observer.rs), plus the memory / manifest / MCP observers. Each holds an event-channel sender. **No background task mutates `App` directly.** -**SWARM panel** (`Alt+w`): [`panels/swarm_dashboard.rs`](src/panels/swarm_dashboard.rs) holds state and rendering, [`app/swarm_run.rs`](src/app/swarm_run.rs) launching and input. Three views: script picker (`ScriptCatalog`, plus a path typed in the filter), input form (`gaviero_dsl::inspect_file`, plus a Profile selector when any model profile exists; its Prompt field is the chat's box, [`widgets/prompt_input.rs`](src/widgets/prompt_input.rs), and `$skill` is expanded at launch; `file` and `dir` vars complete like `@`, and list params complete the tier after `id=` from the selected profile; the form opens on its first input, below the Folder / Workflow / Profile selectors; a list param is `FieldValue::List`, one input per item in `--param` entry syntax, split / rejoined by `split_list_value` / `join_list_items` — short form unless an item is a `{…}` literal, so free fields survive), and the run (one row per planned agent; the selected agent's output below). A run is `pipeline::execute` in-process, prepared by the same [`script_run`](../gaviero-core/src/swarm/script_run.rs) helpers as `gaviero-cli --script`; keep the two in step. It uses the pipeline's Write Gate, not TURN REVIEW. Every update carries a run id so a stopped run's stragglers are dropped. This panel is the only way the TUI runs a script: chat has no `/run`, and `/swarm`, `/cswarm` and `/undo-swarm` stay gone. Remote does not mirror the panel. +**SWARM panel** (`Alt+w`): [`panels/swarm_dashboard.rs`](src/panels/swarm_dashboard.rs) holds state and rendering, [`app/swarm_run.rs`](src/app/swarm_run.rs) launching and input. Three views: script picker (`ScriptCatalog`, plus a path typed in the filter), input form (`gaviero_dsl::inspect_file`, plus a Profile selector when any model profile exists; its Prompt field is the chat's box, [`widgets/prompt_input.rs`](src/widgets/prompt_input.rs), and `$skill` is expanded at launch; `file` and `dir` vars complete like `@`, and list params complete the tier after `id=` from the selected profile; below the vars, when the resolved profile reads, an **Agents** section (one `FieldRole::AgentTier` choice per agent the workflow runs — its tier, from the profile's tiers → `--tier`) and a **Tiers** section (per tier those agents now use, a `FieldRole::TierModel` choice — its client, from the profile's clients → `--tier-client` — and a `FieldRole::TierEffort` choice — the chosen model's levels from core `effort_completions` (`SwarmForm::effort_options`, stubbed in tests) plus the client's own effort or `(provider default)` → `--tier-effort`); on these rows Enter opens the options as a list in the form's popup (`AutocompleteMode::Choice`, `open_choice_list`), ↑/↓ move, Enter picks and moves to the next field, ←/→/Space still cycle; only changed rows are passed, the profile is re-read (`reload_profile_info`) when Folder or Profile changes, and choices survive where the new profile still offers them; the form opens on its first input, below the Folder / Workflow / Profile selectors; a list param is `FieldValue::List`, one input per item in `--param` entry syntax, split / rejoined by `split_list_value` / `join_list_items` — short form unless an item is a `{…}` literal, so free fields survive), and the run (one row per planned agent; the selected agent's output below). A run is `pipeline::execute` in-process, prepared by the same [`script_run`](../gaviero-core/src/swarm/script_run.rs) helpers as `gaviero-cli --script`; keep the two in step. It uses the pipeline's Write Gate, not TURN REVIEW. Every update carries a run id so a stopped run's stragglers are dropped. This panel is the only way the TUI runs a script: chat has no `/run`, and `/swarm`, `/cswarm` and `/undo-swarm` stay gone. Remote does not mirror the panel. **Turn review (mandatory):** [`app/turn_review.rs`](src/app/turn_review.rs) + the dispatch task in [`app/side_panel.rs`](src/app/side_panel.rs). Each chat turn is bracketed by `app.turn_capture.begin/end` (core `turn_capture`); the session runs with `AgentOptions::host_capture` and the conversation's gate mode `AutoAccept`. A non-empty change set opens the TURN REVIEW left panel (non-modal) and blocks *that* conversation's next prompt (desktop keeps the typed prompt; remote gets `turn_review_pending`). Pending reviews and their decisions persist under `.gaviero/turns/pending/` and reopen on startup. Any host write made while a turn may be running — editor saves, review reverts, MCP config synthesis — must go through `turn_review::note_host_write` or it is attributed to the agent. diff --git a/crates/gaviero-tui/src/app/swarm_run.rs b/crates/gaviero-tui/src/app/swarm_run.rs index 18d1a5bb..c9d7f87d 100644 --- a/crates/gaviero-tui/src/app/swarm_run.rs +++ b/crates/gaviero-tui/src/app/swarm_run.rs @@ -246,6 +246,7 @@ fn open_form(app: &mut App, script: ScriptRow) { app.swarm_dashboard.form = Some(SwarmForm::new(script, inspection, folders, selected).with_profiles(profiles)); app.swarm_dashboard.view = SwarmView::Form; + reload_profile_info(app); refresh_form_warnings(app); } Err(report) => { @@ -391,13 +392,27 @@ fn prepare_and_start(app: &mut App) -> Result<(), String> { expanded }); - let plan = gaviero_dsl::compile_file_with_profile( + for (agent, tier) in &values.agent_tiers { + notes.push(format!("Agent {agent} runs on tier {tier}")); + } + for o in &values.tier_overrides { + notes.push(match (&o.client, &o.effort) { + (Some(client), Some(effort)) => { + format!("Tier {} runs on client {client} at effort {effort}", o.tier) + } + (Some(client), None) => format!("Tier {} runs on client {client}", o.tier), + (None, Some(effort)) => format!("Tier {} runs at effort {effort}", o.tier), + (None, None) => continue, + }); + } + let plan = gaviero_dsl::compile_file_with_models( &script.path, profile.as_ref(), + &values.tier_overrides, values.workflow.as_deref(), prompt.as_deref(), &vars, - &[], + &values.agent_tiers, &values.params, ) .map_err(|report| report_text(&report))?; @@ -853,23 +868,36 @@ fn refresh_prompt_autocomplete(app: &mut App) { } } -/// The tiers a run would have right now: the profile the form has selected, -/// then whatever the script binds itself ([`gaviero_dsl`] merges them so). +/// The tiers a run would have right now: the ones the profile the form +/// resolves to binds. Only the profile defines tiers; the script merely names +/// them, so a name the profile lacks would not compile and is not offered. fn active_tiers(app: &App) -> Vec { + app.swarm_dashboard + .form + .as_ref() + .and_then(|form| form.profile_info.as_ref()) + .map(|info| info.tier_names()) + .unwrap_or_default() +} + +/// Read the profile the form's Folder and Profile choices resolve to, for its +/// agent and tier rows. A profile that cannot be read shows no rows; the run +/// reports the problem when it compiles. +fn reload_profile_info(app: &mut App) { let Some(form) = app.swarm_dashboard.form.as_ref() else { - return Vec::new(); + return; }; - let root = &form.folders[form.selected_folder()].1; - let canonical = std::fs::canonicalize(root).unwrap_or_else(|_| root.clone()); + let root = form.folders[form.selected_folder()].1.clone(); + let canonical = std::fs::canonicalize(&root).unwrap_or_else(|_| root.clone()); let repo = gaviero_core::memory::scope::hash_path(&canonical); - // Only the profile defines tiers; the script merely names them, so a - // name the profile lacks would not compile and is not offered. - ProfileCatalog::scan(&app.workspace, &ScriptCatalog::global_scripts_dir()) - .select(form.selected_profile().as_deref(), Some(&repo), root) + let info = ProfileCatalog::scan(&app.workspace, &ScriptCatalog::global_scripts_dir()) + .select(form.selected_profile().as_deref(), Some(&repo), &root) .ok() .flatten() - .and_then(|profile| gaviero_dsl::profile_tier_names(&profile.path).ok()) - .unwrap_or_default() + .and_then(|profile| gaviero_dsl::inspect_profile(&profile.path).ok()); + if let Some(form) = app.swarm_dashboard.form.as_mut() { + form.set_profile_info(info); + } } /// Bring the focused field's popup up to date after its text changed. @@ -1075,12 +1103,17 @@ fn handle_form(app: &mut App, action: Action) { Action::Tab | Action::CursorDown => form.focus_next(), Action::CursorUp => form.focus_previous(), Action::Enter if form.on_run_button() => launch(app), + Action::Enter if form.open_choice_list() => {} Action::Enter => form.focus_next(), Action::CursorLeft | Action::CursorRight | Action::InsertChar(' ') if form.focused_input().is_none() => { let delta = if action == Action::CursorLeft { -1 } else { 1 }; + let role = form.focused_role(); form.cycle_focused_choice(delta); + if matches!(role, Some(FieldRole::Folder | FieldRole::Profile)) { + reload_profile_info(app); + } refresh_form_warnings(app); } other => { @@ -1629,6 +1662,97 @@ workflow run { assert!(request.contains("the moon"), "prompt reached the agent: {request}"); } + /// Open the form with a profile offering two clients, apply `choose` to + /// it, press Run, and return the model the `writer` agent was planned on + /// and the run's notes. + fn run_with_model_choices(choose: impl Fn(&mut App)) -> (Option, String) { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + let profiles = root.join(".gaviero/dsl/profiles"); + std::fs::create_dir_all(&profiles).unwrap(); + std::fs::write( + profiles.join("default.gaviero"), + concat!( + "client local { model \"ollama:qwen\" privacy public } +", + "client other { model \"ollama:llama\" privacy public } +", + "tier local local +tier spare other +", + ), + ) + .unwrap(); + let (mut app, _rx) = app_with_script(&root, "http://127.0.0.1:9"); + open_filled_form(&mut app); + choose(&mut app); + press_run(&mut app); + let dash = &mut app.swarm_dashboard; + assert_eq!( + dash.view, + SwarmView::Run, + "error: {:?}", + dash.form.as_ref().and_then(|f| f.error.clone()) + ); + if let Some(abort) = dash.abort.take() { + abort.abort(); + } + (dash.agents[0].backend.clone(), dash.status_message.clone()) + } + + #[tokio::test(flavor = "multi_thread")] + async fn the_form_moves_an_agent_to_another_tier() { + let (model, notes) = run_with_model_choices(|app| { + let form = app.swarm_dashboard.form.as_mut().unwrap(); + form.focus_field("writer"); + assert_eq!(form.fields[form.focus].choice(), Some("local")); + handle_action(app, Action::CursorRight); + let form = app.swarm_dashboard.form.as_ref().unwrap(); + assert_eq!(form.fields[form.focus].choice(), Some("spare")); + }); + assert_eq!(model.as_deref(), Some("ollama:llama")); + assert!(notes.contains("Agent writer runs on tier spare"), "{notes}"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn the_form_points_a_tier_at_another_client_of_the_profile() { + let (model, notes) = run_with_model_choices(|app| { + let form = app.swarm_dashboard.form.as_mut().unwrap(); + let tier_row = form + .fields + .iter() + .position(|f| f.role == FieldRole::TierModel && f.name == "local") + .unwrap(); + form.focus = tier_row; + handle_action(app, Action::InsertChar(' ')); + }); + assert_eq!(model.as_deref(), Some("ollama:llama")); + assert!(notes.contains("Tier local runs on client other"), "{notes}"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_tier_model_is_picked_from_its_list_with_enter_and_arrows() { + let (model, notes) = run_with_model_choices(|app| { + let form = app.swarm_dashboard.form.as_mut().unwrap(); + form.focus = form + .fields + .iter() + .position(|f| f.role == FieldRole::TierModel && f.name == "local") + .unwrap(); + handle_action(app, Action::Enter); + let form = app.swarm_dashboard.form.as_ref().unwrap(); + assert!(form.completion.is_open(), "Enter lists the clients"); + assert_eq!(form.completion.matches.len(), 2); + handle_action(app, Action::CursorDown); + handle_action(app, Action::Enter); + let form = app.swarm_dashboard.form.as_ref().unwrap(); + assert!(!form.completion.is_open()); + assert_eq!(form.fields[form.focus].role, FieldRole::TierEffort); + }); + assert_eq!(model.as_deref(), Some("ollama:llama")); + assert!(notes.contains("Tier local runs on client other"), "{notes}"); + } + #[tokio::test(flavor = "multi_thread")] async fn stopping_ends_a_run_that_would_otherwise_never_finish() { let dir = tempfile::tempdir().unwrap(); @@ -1852,6 +1976,8 @@ workflow run { prompt: None, vars: vec![("IN".to_string(), value.to_string())], params: Vec::new(), + agent_tiers: Vec::new(), + tier_overrides: Vec::new(), }; let mut labelled = values("one/docs/a.md"); @@ -1896,6 +2022,7 @@ workflow run { accepts_prompt: false, default_execution: ExecutionMode::Repo, tiers: Vec::new(), + agents: Vec::new(), } } diff --git a/crates/gaviero-tui/src/panels/swarm_dashboard.rs b/crates/gaviero-tui/src/panels/swarm_dashboard.rs index f996a039..962023df 100644 --- a/crates/gaviero-tui/src/panels/swarm_dashboard.rs +++ b/crates/gaviero-tui/src/panels/swarm_dashboard.rs @@ -25,7 +25,8 @@ use gaviero_core::swarm::plan::ExecutionMode; use gaviero_core::types::ModelTier; use gaviero_dsl::ast::ReviewerEntry; use gaviero_dsl::workflow_params::{list_literal_entry, parse_reviewers_override}; -use gaviero_dsl::{ParamKindInfo, ScriptInspection, VarKind}; +use crate::widgets::prompt_input::AutocompleteMode; +use gaviero_dsl::{ParamKindInfo, ProfileInspection, ScriptInspection, TierOverride, VarKind}; /// Activity kept per agent; the oldest output goes first. const MAX_ACTIVITY_LINES: usize = 500; @@ -180,6 +181,24 @@ pub enum FieldRole { File, /// A var declared `dir`. Dir, + /// The tier one agent runs on; the field's name is the agent. + AgentTier, + /// The profile client one tier means for this run; the field's name is + /// the tier. + TierModel, + /// The effort one tier runs at for this run; the field's name is the tier. + TierEffort, +} + +impl FieldRole { + /// Selectors whose options open as a list on Enter. + pub fn picks_from_list(self) -> bool { + matches!(self, Self::AgentTier | Self::TierModel | Self::TierEffort) + } + + fn is_model_row(self) -> bool { + self.picks_from_list() + } } #[derive(Debug, Clone)] @@ -299,10 +318,22 @@ impl FormField { .collect(); now != split_list_value(default) } + FieldValue::Choice { options, selected } => self + .default + .as_deref() + .is_some_and(|d| options.get(*selected).is_some_and(|o| o != d)), _ => self.text().is_some_and(|t| t != default), } } + /// The selected option of a choice field. + pub fn choice(&self) -> Option<&str> { + match &self.value { + FieldValue::Choice { options, selected } => options.get(*selected).map(String::as_str), + _ => None, + } + } + fn label(&self) -> String { let required = if self.required { " *" } else { "" }; if matches!(self.value, FieldValue::List { .. }) { @@ -329,6 +360,36 @@ impl FormField { FieldRole::Var => "Script variable. Empty leaves it unset", FieldRole::File => "An existing file. Type to search, as with @ in chat", FieldRole::Dir => "A folder. Type to search the workspace", + FieldRole::AgentTier => "The tier this agent runs on. Enter: list ←/→ change", + FieldRole::TierModel => { + "This tier's model, from the profile's clients. Enter: list ←/→ change" + } + FieldRole::TierEffort => { + "This tier's effort; the model's levels. Enter: list ←/→ change" + } + } + } + + /// A choice from `options` starting on `previous` when it is one of them, + /// else on `default`. + fn choice_field( + name: &str, + role: FieldRole, + options: Vec, + default: &str, + previous: Option<&str>, + ) -> Self { + let position = |wanted: &str| options.iter().position(|o| o == wanted); + let selected = previous + .and_then(position) + .or_else(|| position(default)) + .unwrap_or(0); + Self { + name: name.to_string(), + role, + value: FieldValue::Choice { options, selected }, + default: Some(default.to_string()), + required: false, } } @@ -391,11 +452,25 @@ pub struct FormValues { pub prompt: Option, pub vars: Vec<(String, String)>, pub params: Vec<(String, String)>, + /// `--tier AGENT=TIER`: agents moved off the tier they run on by default. + pub agent_tiers: Vec<(String, String)>, + /// `--tier-client` / `--tier-effort`: tiers pointed at another profile + /// client and/or run at another effort. + pub tier_overrides: Vec, } /// First entry of the Profile selector: no explicit choice. const PROFILE_AUTO: &str = "auto"; +/// The Model choice of a tier the profile does not bind. +const TIER_UNBOUND: &str = "(not in profile)"; + +/// The Effort choice of a client that sets none (the provider decides). +const EFFORT_UNSET: &str = "(provider default)"; + +const AGENTS_HEADING: &str = "Agents — the tier each one runs on"; +const TIERS_HEADING: &str = "Tiers — the model each one means, this run only"; + /// Shown in place of the prompt box, so its absence does not look like a fault. const NO_PROMPT_NOTE: &str = "This script takes no prompt: its agents have fixed instructions."; @@ -406,12 +481,18 @@ pub struct SwarmForm { /// Profile names on offer; the selector is hidden when empty. pub profiles: Vec, pub fields: Vec, + /// The profile the run would use, read for the agent and tier rows; + /// `None` shows none (no profile, or one that does not parse). + pub profile_info: Option, /// `fields.len()` is the Run button. pub focus: usize, pub error: Option, pub warnings: Vec, - /// Popup of the focused file or param field. + /// Popup of the focused file or param field, or a selector's option list. pub completion: FileAutocomplete, + /// The efforts a model offers (`gaviero_core`'s list); replaceable in + /// tests, since the Codex lookup asks the installed CLI. + pub effort_options: fn(&str) -> Vec, /// Where the last frame drew each list field's `+`, `x` and items. list_hits: Vec<(Rect, usize, ListTarget)>, } @@ -430,13 +511,15 @@ impl SwarmForm { folders, profiles: Vec::new(), fields: Vec::new(), + profile_info: None, focus: 0, error: None, warnings: Vec::new(), completion: FileAutocomplete::new(), + effort_options: model_effort_options, list_hits: Vec::new(), }; - form.fields = form.build_fields(selected_folder, 0, 0); + form.fields = form.build_fields(selected_folder, 0, 0, &[]); form.focus = form.first_input_field(); form } @@ -444,11 +527,187 @@ impl SwarmForm { /// Offer these profiles in a selector. pub fn with_profiles(mut self, profiles: Vec) -> Self { self.profiles = profiles; - self.fields = self.build_fields(self.selected_folder(), self.selected_workflow(), 0); + self.fields = self.build_fields(self.selected_folder(), self.selected_workflow(), 0, &[]); self.focus = self.first_input_field(); self } + /// Show the agent and tier rows for this profile (the one the Profile + /// selector, or `default`, resolves to). Choices made for agents and + /// tiers the new profile still has are kept. + pub fn set_profile_info(&mut self, info: Option) { + self.profile_info = info; + self.rebuild(); + } + + /// The model a tier runs on as the form now stands: its Tiers row, else + /// the profile's binding. + fn client_for_tier(&self, tier: &str) -> Option { + let info = self.profile_info.as_ref()?; + let chosen = self + .fields + .iter() + .find(|f| f.role == FieldRole::TierModel && f.name == tier) + .and_then(FormField::choice); + match chosen { + Some(TIER_UNBOUND) => None, + Some(client) => Some(client.to_string()), + None => info.client_of(tier).map(str::to_string), + } + } + + /// The effort a tier runs at as the form now stands: its Effort row, else + /// its client's. `None` when it sets none. + fn effort_for_tier(&self, tier: &str) -> Option { + let chosen = self + .fields + .iter() + .find(|f| f.role == FieldRole::TierEffort && f.name == tier) + .and_then(FormField::choice); + let effort = match chosen { + Some(choice) => Some(choice.to_string()), + None => { + let info = self.profile_info.as_ref()?; + info.client(&self.client_for_tier(tier)?)?.effort.clone() + } + }; + effort.filter(|e| e != EFFORT_UNSET) + } + + /// `model · effort (client)` for a tier as the form now stands. + fn tier_summary(&self, tier: &str, with_client: bool) -> String { + let info = self.profile_info.as_ref(); + let Some(client) = self + .client_for_tier(tier) + .and_then(|c| info.and_then(|i| i.client(&c))) + else { + return "no model: the run will not compile".to_string(); + }; + let model = client.model.clone().unwrap_or_else(|| client.name.clone()); + let mut text = match self.effort_for_tier(tier) { + Some(effort) => format!("{model} · {effort}"), + None => model, + }; + if with_client { + text.push_str(&format!(" ({})", client.name)); + } + text + } + + /// What a choice row resolves to, drawn after its value: the model and + /// effort of an agent's tier, or the model of a tier's client. + pub fn choice_detail(&self, index: usize) -> Option { + let field = self.fields.get(index)?; + let info = self.profile_info.as_ref()?; + match field.role { + FieldRole::AgentTier => Some(self.tier_summary(field.choice()?, true)), + FieldRole::TierModel => Some(match info.client(field.choice()?) { + Some(client) => client.model.clone().unwrap_or_else(|| client.name.clone()), + None => "no model: the run will not compile".to_string(), + }), + FieldRole::TierEffort => { + let FieldValue::Choice { options, .. } = &field.value else { + return None; + }; + (options.len() < 2).then(|| "this model takes no effort setting".to_string()) + } + _ => None, + } + } + + /// The option labels of a list selector: each option and what it means. + fn choice_labels(&self, index: usize) -> Vec { + let Some(field) = self.fields.get(index) else { + return Vec::new(); + }; + let FieldValue::Choice { options, .. } = &field.value else { + return Vec::new(); + }; + let info = self.profile_info.as_ref(); + let width = options.iter().map(|o| o.chars().count()).max().unwrap_or(0); + options + .iter() + .map(|option| { + let detail = match field.role { + FieldRole::AgentTier => self.tier_summary(option, true), + FieldRole::TierModel => info + .and_then(|i| i.client(option)) + .map(|c| c.summary()) + .unwrap_or_default(), + _ => String::new(), + }; + if detail.is_empty() { + option.clone() + } else { + format!("{option: bool { + let Some(field) = self.fields.get(self.focus) else { + return false; + }; + let FieldValue::Choice { selected, .. } = field.value else { + return false; + }; + if !field.role.picks_from_list() { + return false; + } + let labels = self.choice_labels(self.focus); + self.completion.open_choices(labels, selected); + true + } + + /// Pick option `index` of the focused selector, as if cycled there. + fn set_focused_choice(&mut self, index: usize) { + let Some(field) = self.fields.get_mut(self.focus) else { + return; + }; + let FieldValue::Choice { options, selected } = &mut field.value else { + return; + }; + if index >= options.len() { + return; + } + *selected = index; + // Another workflow runs other agents; another tier may need a row; + // another model offers other efforts. + if matches!( + field.role, + FieldRole::Workflow | FieldRole::AgentTier | FieldRole::TierModel + ) { + self.rebuild(); + } + } + + /// Rebuild every field from the current choices, keeping what the user + /// typed or chose under the same name. + fn rebuild(&mut self) { + let focused = self.focus; + let folder = self.selected_folder(); + let workflow = self.selected_workflow(); + let profile = self.choice_of(FieldRole::Profile); + let old = std::mem::take(&mut self.fields); + let mut fresh = self.build_fields(folder, workflow, profile, &old); + for field in &mut fresh { + if matches!(field.value, FieldValue::Choice { .. }) { + continue; + } + if let Some(previous) = old + .iter() + .find(|o| o.name == field.name && o.role == field.role && o.is_edited()) + { + field.value = previous.value.clone(); + } + } + self.fields = fresh; + self.focus = focused.min(self.fields.len()); + } + /// The first field to type into. The Folder / Workflow / Profile /// selectors above it start on a usable choice, and every script run /// needs a profile, so the form opens on the Prompt (or first input) @@ -460,7 +719,15 @@ impl SwarmForm { .unwrap_or(0) } - fn build_fields(&self, folder: usize, workflow: usize, profile: usize) -> Vec { + /// `previous` carries the agent and tier choices the user made, where + /// they still apply. + fn build_fields( + &self, + folder: usize, + workflow: usize, + profile: usize, + previous: &[FormField], + ) -> Vec { let mut fields = Vec::new(); if self.folders.len() > 1 { fields.push(FormField { @@ -531,9 +798,94 @@ impl SwarmForm { required, )); } + if let Some(info) = &self.profile_info { + self.push_model_fields(&mut fields, info, workflow, previous); + } fields } + /// One row per agent the workflow runs (its tier) and one per tier those + /// agents now use (its client). Only edited choices carry over. + fn push_model_fields( + &self, + fields: &mut Vec, + info: &ProfileInspection, + workflow: usize, + previous: &[FormField], + ) { + let edited = |role: FieldRole, name: &str| { + previous + .iter() + .find(|f| f.role == role && f.name == name && f.is_edited()) + .and_then(FormField::choice) + .map(str::to_string) + }; + let profile_tiers = info.tier_names(); + + let mut used: Vec = Vec::new(); + for (agent, tier) in self.inspection.agent_tiers(workflow) { + let mut options = profile_tiers.clone(); + if !options.contains(&tier) { + options.insert(0, tier.clone()); + } + let field = FormField::choice_field( + &agent, + FieldRole::AgentTier, + options, + &tier, + edited(FieldRole::AgentTier, &agent).as_deref(), + ); + if let Some(now) = field.choice() + && !used.iter().any(|t| t == now) + { + used.push(now.to_string()); + } + fields.push(field); + } + + let clients: Vec = info.clients.iter().map(|c| c.name.clone()).collect(); + for tier in used { + let mut options = clients.clone(); + let default = match info.client_of(&tier) { + Some(client) => client.to_string(), + None => { + options.insert(0, TIER_UNBOUND.to_string()); + TIER_UNBOUND.to_string() + } + }; + let model_field = FormField::choice_field( + &tier, + FieldRole::TierModel, + options, + &default, + edited(FieldRole::TierModel, &tier).as_deref(), + ); + + // The efforts the chosen client's model offers; its own effort + // is the default, listed even when the model does not offer it + // (so the row shows what the profile says). + let client = model_field.choice().and_then(|c| info.client(c)); + let own = client + .and_then(|c| c.effort.clone()) + .unwrap_or_else(|| EFFORT_UNSET.to_string()); + let mut efforts = client + .and_then(|c| c.model.as_deref()) + .map(self.effort_options) + .unwrap_or_default(); + if !efforts.contains(&own) { + efforts.insert(0, own.clone()); + } + fields.push(model_field); + fields.push(FormField::choice_field( + &tier, + FieldRole::TierEffort, + efforts, + &own, + edited(FieldRole::TierEffort, &tier).as_deref(), + )); + } + } + fn choice_of(&self, role: FieldRole) -> usize { self.fields .iter() @@ -576,27 +928,9 @@ impl SwarmForm { return; }; let len = options.len() as isize; - *selected = (*selected as isize + delta).rem_euclid(len) as usize; - if field.role != FieldRole::Workflow { - return; - } - - let focused = self.focus; - let folder = self.selected_folder(); - let workflow = self.selected_workflow(); - let profile = self.choice_of(FieldRole::Profile); - let old = std::mem::take(&mut self.fields); - let mut fresh = self.build_fields(folder, workflow, profile); - for field in &mut fresh { - if let Some(previous) = old - .iter() - .find(|o| o.name == field.name && o.role == field.role && o.is_edited()) - { - field.value = previous.value.clone(); - } - } - self.fields = fresh; - self.focus = focused.min(self.fields.len()); + let next = (*selected as isize + delta).rem_euclid(len) as usize; + self.completion.reset(); + self.set_focused_choice(next); } pub fn focused_input(&mut self) -> Option<&mut TextInput> { @@ -808,6 +1142,13 @@ impl SwarmForm { } pub fn accept_completion(&mut self) { + if self.completion.mode == AutocompleteMode::Choice { + let picked = self.completion.selected; + self.completion.reset(); + self.set_focused_choice(picked); + self.focus_next(); + return; + } let input = match self.fields.get_mut(self.focus).map(|f| &mut f.value) { Some(FieldValue::Text(input)) => Some(input), Some(FieldValue::List { items, item }) => items.get_mut(*item), @@ -886,8 +1227,23 @@ impl SwarmForm { prompt: None, vars: Vec::new(), params: Vec::new(), + agent_tiers: Vec::new(), + tier_overrides: Vec::new(), }; + let mut tier_clients = Vec::new(); + let mut tier_efforts = Vec::new(); for field in &self.fields { + if field.is_edited() + && let Some(choice) = field.choice() + { + let pair = (field.name.clone(), choice.to_string()); + match field.role { + FieldRole::AgentTier => values.agent_tiers.push(pair), + FieldRole::TierModel if choice != TIER_UNBOUND => tier_clients.push(pair), + FieldRole::TierEffort if choice != EFFORT_UNSET => tier_efforts.push(pair), + _ => {} + } + } let Some(text) = field.text() else { continue }; match field.role { FieldRole::Prompt if !text.trim().is_empty() => { @@ -907,10 +1263,16 @@ impl SwarmForm { _ => {} } } + values.tier_overrides = TierOverride::from_pairs(&tier_clients, &tier_efforts); Ok(values) } } +/// What `gaviero_core` says a model accepts: its levels, then `auto` / `off`. +fn model_effort_options(model: &str) -> Vec { + gaviero_core::swarm::backend::effort::effort_completions(model, "") +} + // ── Agents ────────────────────────────────────────────────────── #[derive(Debug, Clone)] @@ -1593,6 +1955,13 @@ impl SwarmDashboardState { rows.push(FormRow::plain(line, fg(theme::TEXT_DIM))); } } + let model_label_width = form + .fields + .iter() + .filter(|f| f.role.is_model_row()) + .map(|f| f.name.chars().count()) + .max() + .unwrap_or(0); for (index, field) in form.fields.iter().enumerate() { let is_focused = index == form.focus; let label_style = if is_focused { @@ -1600,6 +1969,29 @@ impl SwarmDashboardState { } else { fg(theme::TEXT_FG) }; + if field.role.is_model_row() { + let section = |role: FieldRole| role == FieldRole::AgentTier; + let first_of_section = index == 0 + || !form.fields[index - 1].role.is_model_row() + || section(form.fields[index - 1].role) != section(field.role); + if first_of_section { + let heading = if field.role == FieldRole::AgentTier { + AGENTS_HEADING + } else { + TIERS_HEADING + }; + rows.push(FormRow::plain(String::new(), Style::default())); + rows.push(FormRow::plain(heading.to_string(), bold(theme::TEXT_DIM))); + } + let mut row = model_row(form, index, field, model_label_width, label_style); + // The open list hangs off the row being chosen. + if is_focused && form.completion.mode == AutocompleteMode::Choice { + row.anchor = true; + row.fill = form.completion.is_open().then_some(theme::INPUT_BG); + } + rows.push(row); + continue; + } let label = field.label(); let mut label_row = FormRow::field(label.clone(), label_style, index, None); if matches!(field.value, FieldValue::List { .. }) { @@ -2101,6 +2493,43 @@ impl SwarmDashboardState { // ── Helpers ───────────────────────────────────────────────────── +/// One line for an agent's tier or a tier's model: the name, the choice +/// (highlighted when changed from the script's or profile's), and what it +/// resolves to. +fn model_row( + form: &SwarmForm, + index: usize, + field: &FormField, + label_width: usize, + label_style: Style, +) -> FormRow { + let choice = field.choice().unwrap_or_default(); + let name = if field.role == FieldRole::TierEffort { + "" + } else { + field.name.as_str() + }; + let kind = match field.role { + FieldRole::TierModel => "model ", + FieldRole::TierEffort => "effort ", + _ => "", + }; + let label = format!("{name: ProfileInspection { + let client = |name: &str, model: &str, effort: Option<&str>| gaviero_dsl::ProfileClient { + name: name.into(), + model: Some(model.into()), + effort: effort.map(str::to_string), + }; + ProfileInspection { + clients: vec![ + client("sonnet", "claude:sonnet", None), + client("opus", "claude:opus", Some("high")), + client("sol", "codex:gpt-6.1-sol", None), + client("qwen", "ollama:qwen", None), + ], + tiers: vec![ + ("medium".into(), "sonnet".into()), + ("high".into(), "opus".into()), + ("high-codex".into(), "sol".into()), + ], + } + } + + /// A form for agents `scout` (high) and `judge` (medium), with a profile. + fn model_form() -> SwarmForm { + let mut info = inspection(vec![workflow("w", vec![])]); + info.agents = vec![ + gaviero_dsl::AgentInspection { + name: "scout".into(), + tier: Some("high".into()), + }, + gaviero_dsl::AgentInspection { + name: "judge".into(), + tier: Some("medium".into()), + }, + ]; + let mut form = SwarmForm::new(row(), info, folders(), 0); + form.effort_options = test_efforts; + form.set_profile_info(Some(profile_info())); + type_into(&mut form, "Prompt", "p"); + form + } + + /// Claude models offer three levels here, the rest none. + fn test_efforts(model: &str) -> Vec { + if model.starts_with("claude:") { + vec!["low".into(), "high".into(), "max".into()] + } else { + Vec::new() + } + } + + fn overrides(list: &[(&str, Option<&str>, Option<&str>)]) -> Vec { + list.iter() + .map(|(tier, client, effort)| TierOverride { + tier: tier.to_string(), + client: client.map(str::to_string), + effort: effort.map(str::to_string), + }) + .collect() + } + + fn rows_of(form: &SwarmForm, role: FieldRole) -> Vec<(String, String)> { + form.fields + .iter() + .filter(|f| f.role == role) + .map(|f| (f.name.clone(), f.choice().unwrap_or_default().to_string())) + .collect() + } + + fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect() + } + + fn choose(form: &mut SwarmForm, role: FieldRole, name: &str, option: &str) { + form.focus = form + .fields + .iter() + .position(|f| f.role == role && f.name == name) + .unwrap(); + for _ in 0..10 { + if form.fields[form.focus].choice() == Some(option) { + return; + } + form.cycle_focused_choice(1); + } + panic!("{option} is not an option of {name}"); + } + + #[test] + fn every_agent_and_tier_it_uses_gets_a_row_and_untouched_rows_pass_nothing() { + let mut form = model_form(); + assert_eq!( + rows_of(&form, FieldRole::AgentTier), + pairs(&[("scout", "high"), ("judge", "medium")]) + ); + assert_eq!( + rows_of(&form, FieldRole::TierModel), + pairs(&[("high", "opus"), ("medium", "sonnet")]) + ); + let values = form.collect().unwrap(); + assert!(values.agent_tiers.is_empty() && values.tier_overrides.is_empty()); + assert_eq!( + rows_of(&form, FieldRole::TierEffort), + pairs(&[("high", "high"), ("medium", EFFORT_UNSET)]), + "each tier shows its client's effort" + ); + } + + #[test] + fn moving_an_agent_and_rebinding_a_tier_are_passed_to_the_run() { + let mut form = model_form(); + choose(&mut form, FieldRole::AgentTier, "judge", "high-codex"); + // The judge left `medium`, so it has no row; `high-codex` gets one. + assert_eq!( + rows_of(&form, FieldRole::TierModel), + pairs(&[("high", "opus"), ("high-codex", "sol")]) + ); + choose(&mut form, FieldRole::TierModel, "high", "sonnet"); + + let values = form.collect().unwrap(); + assert_eq!(values.agent_tiers, pairs(&[("judge", "high-codex")])); + assert_eq!(values.tier_overrides, overrides(&[("high", Some("sonnet"), None)])); + + let scout = form.fields.iter().position(|f| f.name == "scout").unwrap(); + assert_eq!(form.choice_detail(scout).as_deref(), Some("claude:sonnet (sonnet)")); + } + + #[test] + fn choices_survive_a_new_profile_that_still_offers_them() { + let mut form = model_form(); + choose(&mut form, FieldRole::AgentTier, "judge", "high-codex"); + choose(&mut form, FieldRole::TierModel, "high", "sol"); + + let mut other = profile_info(); + other.tiers.retain(|(tier, _)| tier != "high-codex"); + form.set_profile_info(Some(other)); + let values = form.collect().unwrap(); + assert!(values.agent_tiers.is_empty(), "the new profile has no high-codex"); + assert_eq!(values.tier_overrides, overrides(&[("high", Some("sol"), None)])); + + form.set_profile_info(None); + assert!(rows_of(&form, FieldRole::AgentTier).is_empty()); + } + + #[test] + fn a_tier_the_profile_lacks_is_marked_and_not_bound_until_chosen() { + let mut form = model_form(); + let mut info = profile_info(); + info.tiers.retain(|(tier, _)| tier != "medium"); + form.set_profile_info(Some(info)); + assert!(rows_of(&form, FieldRole::TierModel).contains(&( + "medium".to_string(), + TIER_UNBOUND.to_string() + ))); + let judge = form.fields.iter().position(|f| f.name == "judge").unwrap(); + assert!(form.choice_detail(judge).unwrap().contains("will not compile")); + assert!(form.collect().unwrap().tier_overrides.is_empty()); + + choose(&mut form, FieldRole::TierModel, "medium", "opus"); + assert_eq!( + form.collect().unwrap().tier_overrides, + overrides(&[("medium", Some("opus"), None)]) + ); + } + + #[test] + fn agent_and_tier_rows_render_under_their_headings() { + let mut dash = SwarmDashboardState::new(); + dash.form = Some(model_form()); + dash.view = SwarmView::Form; + let text = render_rows(&mut dash, 70, 40).join(" +"); + assert!(text.contains(AGENTS_HEADING), "{text}"); + assert!(text.contains(TIERS_HEADING), "{text}"); + assert!(text.contains("scout ‹ high › claude:opus · high (opus)"), "{text}"); + assert!(text.contains("high model ‹ opus › claude:opus"), "{text}"); + assert!(text.contains(" effort ‹ high ›"), "{text}"); + } + + /// Pick `option` from the row's list, as Enter, arrows and Enter would. + fn pick(form: &mut SwarmForm, role: FieldRole, name: &str, option: &str) { + form.focus = form + .fields + .iter() + .position(|f| f.role == role && f.name == name) + .unwrap(); + let FieldValue::Choice { options, .. } = &form.fields[form.focus].value else { + panic!("{name} is not a choice"); + }; + let index = options.iter().position(|o| o == option).unwrap(); + assert!(form.open_choice_list()); + form.completion.selected = index; + form.accept_completion(); + } + + #[test] + fn a_tier_effort_is_passed_alone_or_with_its_client() { + let mut form = model_form(); + choose(&mut form, FieldRole::TierEffort, "high", "max"); + assert_eq!( + form.collect().unwrap().tier_overrides, + overrides(&[("high", None, Some("max"))]) + ); + let scout = form.fields.iter().position(|f| f.name == "scout").unwrap(); + assert_eq!( + form.choice_detail(scout).as_deref(), + Some("claude:opus · max (opus)") + ); + + // Another Claude model still offers `max`, so the choice stays. + pick(&mut form, FieldRole::TierModel, "high", "sonnet"); + assert_eq!( + form.collect().unwrap().tier_overrides, + overrides(&[("high", Some("sonnet"), Some("max"))]) + ); + + // A model without levels has nothing to choose, and says so. + pick(&mut form, FieldRole::TierModel, "high", "qwen"); + assert_eq!( + form.collect().unwrap().tier_overrides, + overrides(&[("high", Some("qwen"), None)]) + ); + let effort = form + .fields + .iter() + .position(|f| f.role == FieldRole::TierEffort && f.name == "high") + .unwrap(); + assert_eq!( + form.choice_detail(effort).as_deref(), + Some("this model takes no effort setting") + ); + } + + #[test] + fn enter_lists_the_options_and_picking_one_moves_on() { + let mut form = model_form(); + form.focus = form + .fields + .iter() + .position(|f| f.role == FieldRole::TierModel && f.name == "high") + .unwrap(); + assert!(form.open_choice_list()); + assert!(form.completion.is_open()); + assert_eq!(form.completion.mode, AutocompleteMode::Choice); + assert_eq!(form.completion.selected, 1, "the current choice is highlighted"); + assert_eq!( + form.completion.matches, + vec![ + "sonnet claude:sonnet".to_string(), + "opus claude:opus · high".to_string(), + "sol codex:gpt-6.1-sol".to_string(), + "qwen ollama:qwen".to_string(), + ] + ); + + form.completion.select_previous(); + form.accept_completion(); + assert!(!form.completion.is_open()); + assert_eq!( + rows_of(&form, FieldRole::TierModel)[0], + ("high".to_string(), "sonnet".to_string()) + ); + let focused = &form.fields[form.focus]; + assert_eq!( + (focused.role, focused.name.as_str()), + (FieldRole::TierEffort, "high"), + "the effort of the same tier is next" + ); + + assert!(form.open_choice_list()); + assert_eq!( + form.completion.matches, + vec![EFFORT_UNSET.to_string(), "low".into(), "high".into(), "max".into()] + ); + form.focus = form.fields.iter().position(|f| f.name == "Prompt").unwrap(); + form.completion.reset(); + assert!(!form.open_choice_list(), "only model rows open a list"); + } + + #[test] + fn an_agent_list_shows_what_each_tier_means() { + let mut form = model_form(); + form.focus = form.fields.iter().position(|f| f.name == "judge").unwrap(); + assert!(form.open_choice_list()); + assert_eq!( + form.completion.matches, + vec![ + "medium claude:sonnet (sonnet)".to_string(), + "high claude:opus · high (opus)".to_string(), + "high-codex codex:gpt-6.1-sol (sol)".to_string(), + ] + ); + } + fn planned(id: &str) -> PlannedAgent { PlannedAgent { id: id.into(), diff --git a/crates/gaviero-tui/src/widgets/prompt_input.rs b/crates/gaviero-tui/src/widgets/prompt_input.rs index 5ba5c99d..32ef08bf 100644 --- a/crates/gaviero-tui/src/widgets/prompt_input.rs +++ b/crates/gaviero-tui/src/widgets/prompt_input.rs @@ -38,6 +38,8 @@ pub enum AutocompleteMode { Effort, /// The tier after `id=` in a list param item — the active profile's tiers. Tier, + /// The options of a form selector; accepting picks one, inserting nothing. + Choice, } /// Rows the popup shows at most; longer lists scroll. @@ -140,6 +142,14 @@ impl FileAutocomplete { self.scroll = 0; } + /// Show `options` as a pick list with `selected` highlighted and on screen. + pub fn open_choices(&mut self, options: Vec, selected: usize) { + self.open(AutocompleteMode::Choice, 0, ""); + self.selected = selected.min(options.len().saturating_sub(1)); + self.scroll = (self.selected + 1).saturating_sub(POPUP_ROWS); + self.matches = options; + } + /// Back to the first match when the new list no longer reaches the /// selection. pub fn clamp_selection(&mut self) { @@ -519,7 +529,10 @@ pub fn accept_autocomplete(input: &mut TextInput, autocomplete: &mut FileAutocom input.text.push_str(&path); input.text.push(' '); } - AutocompleteMode::ModelSpec | AutocompleteMode::Effort | AutocompleteMode::Tier => { + AutocompleteMode::ModelSpec + | AutocompleteMode::Effort + | AutocompleteMode::Tier + | AutocompleteMode::Choice => { input.text.push_str(&path); } } @@ -757,7 +770,8 @@ pub fn render_autocomplete(autocomplete: &FileAutocomplete, area: Rect, buf: &mu | AutocompleteMode::DetachName | AutocompleteMode::ModelSpec | AutocompleteMode::Effort - | AutocompleteMode::Tier => { + | AutocompleteMode::Tier + | AutocompleteMode::Choice => { format!(" {}", path) } AutocompleteMode::SkillRef => path.clone(),