Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/gaviero-cli/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Full user-facing flag tables: [README.md](README.md). Do not duplicate every fie
## Conventions

- **stdout = results, stderr = telemetry.** Observers always log to stderr.
- **Every `execute` run is published for the phone app.** `start_live_run` creates a core [`live_run`](../gaviero-core/src/swarm/live_run.rs) record under `~/.gaviero/remote/cli-runs/<id>/`, and both observers feed it (`LiveRunHandle`, flushed at most once a second, heartbeat every 30 s, finished on `execute`'s result). `--coordinated` planning is not published. `GAVIERO_CLI_RUNS_DIR` moves the folder; integration tests must set it so they never write into the user's list.
- **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`; `--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)).
Expand Down
150 changes: 143 additions & 7 deletions crates/gaviero-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use anyhow::{Context, Result};
use clap::Parser;

use gaviero_core::observer::{AcpObserver, SwarmObserver};
use gaviero_core::swarm::live_run::{CliRunStore, LiveRun, LiveRunHandle, LiveUpdate, PlannedAgent};
use gaviero_core::script_profiles::ProfileCatalog;
use gaviero_core::scripts::ScriptCatalog;
use gaviero_core::swarm::models::{AgentStatus, SwarmResult, WorkUnit};
Expand Down Expand Up @@ -696,6 +697,8 @@ struct CliAcpObserver {
agent_id: String,
verbose: bool,
stream_buffer: Mutex<String>,
/// The run's published record (`swarm::live_run`), for the phone app.
live: Option<LiveRunHandle>,
}

impl CliAcpObserver {
Expand All @@ -704,6 +707,18 @@ impl CliAcpObserver {
agent_id: agent_id.into(),
verbose,
stream_buffer: Mutex::new(String::new()),
live: None,
}
}

fn publishing(mut self, live: Option<LiveRunHandle>) -> Self {
self.live = live;
self
}

fn publish(&self, update: impl FnOnce(String) -> LiveUpdate) {
if let Some(live) = &self.live {
live.update(update(self.agent_id.clone()));
}
}

Expand All @@ -725,6 +740,10 @@ impl CliAcpObserver {

impl AcpObserver for CliAcpObserver {
fn on_stream_chunk(&self, text: &str) {
self.publish(|id| LiveUpdate::Text {
id,
text: text.to_string(),
});
if !self.verbose {
return;
}
Expand All @@ -736,6 +755,10 @@ impl AcpObserver for CliAcpObserver {
}

fn on_tool_call_started(&self, tool_summary: &str) {
self.publish(|id| LiveUpdate::Tool {
id,
summary: tool_summary.to_string(),
});
self.flush_stream_lines(true);
eprintln!(" [{}] ⚙ {}", self.agent_id, tool_summary);
}
Expand All @@ -744,6 +767,10 @@ impl AcpObserver for CliAcpObserver {
if role != "assistant" {
return;
}
self.publish(|id| LiveUpdate::Message {
id,
content: content.to_string(),
});
self.flush_stream_lines(true);
if self.verbose {
return;
Expand All @@ -760,14 +787,26 @@ impl AcpObserver for CliAcpObserver {
fn on_proposal_deferred(
&self,
path: &std::path::Path,
_old_content: Option<&str>,
_new_content: &str,
old_content: Option<&str>,
new_content: &str,
) {
let old_lines = old_content.map(|s| s.lines().count()).unwrap_or(0);
let new_lines = new_content.lines().count();
self.publish(|id| LiveUpdate::File {
id,
path: path.display().to_string(),
additions: new_lines.saturating_sub(old_lines),
deletions: old_lines.saturating_sub(new_lines),
});
self.flush_stream_lines(true);
eprintln!(" [{}] ✎ {}", self.agent_id, path.display());
}

fn on_streaming_status(&self, status: &str) {
self.publish(|id| LiveUpdate::Status {
id,
status: status.to_string(),
});
self.flush_stream_lines(true);
eprintln!(" [{}] … {}", self.agent_id, status);
}
Expand All @@ -792,15 +831,33 @@ impl AcpObserver for CliAcpObserver {
}
}

/// CLI observer for swarm events.
struct CliSwarmObserver;
/// CLI observer for swarm events. With `live`, every event also goes into
/// the run's published record (`swarm::live_run`) the phone app reads.
#[derive(Default)]
struct CliSwarmObserver {
live: Option<LiveRunHandle>,
}

impl CliSwarmObserver {
fn publish(&self, update: LiveUpdate) {
if let Some(live) = &self.live {
live.update(update);
}
}
}

impl SwarmObserver for CliSwarmObserver {
fn on_phase_changed(&self, phase: &str) {
self.publish(LiveUpdate::Phase(phase.to_string()));
eprintln!("[phase] {}", phase);
}

fn on_agent_state_changed(&self, work_unit_id: &str, status: &AgentStatus, detail: &str) {
self.publish(LiveUpdate::Agent {
id: work_unit_id.to_string(),
status: status.clone(),
detail: detail.to_string(),
});
match status {
AgentStatus::Running => {
if detail.is_empty() {
Expand All @@ -827,10 +884,15 @@ impl SwarmObserver for CliSwarmObserver {
}

fn on_tier_started(&self, current: usize, total: usize) {
self.publish(LiveUpdate::Tier { current, total });
eprintln!("[tier] {}/{}", current, total);
}

fn on_merge_conflict(&self, branch: &str, files: &[String]) {
self.publish(LiveUpdate::Notice(format!(
"Merge conflict in {branch}: {}",
files.join(", ")
)));
eprintln!("[conflict] branch={} files={}", branch, files.join(", "));
}

Expand Down Expand Up @@ -864,6 +926,11 @@ impl SwarmObserver for CliSwarmObserver {
}

fn on_tier_dispatch(&self, unit_id: &str, tier: gaviero_core::types::ModelTier, backend: &str) {
self.publish(LiveUpdate::Dispatch {
id: unit_id.to_string(),
tier,
backend: backend.to_string(),
});
eprintln!(
"[dispatch] {} → {} ({})",
unit_id,
Expand Down Expand Up @@ -896,6 +963,7 @@ impl SwarmObserver for CliSwarmObserver {
}

fn on_loop_iteration_started(&self, current: u32, max: u32, agents: &[String]) {
self.publish(LiveUpdate::Notice(format!("Loop pass {current}/{max}")));
eprintln!(
"[loop] iteration {}/{} agents=[{}]",
current,
Expand Down Expand Up @@ -923,13 +991,20 @@ impl SwarmObserver for CliSwarmObserver {
}

fn on_loop_gate_failed(&self, probe: &str, status: &str, output: &str) {
let diagnostic = output.lines().next().unwrap_or_default().trim();
self.publish(LiveUpdate::Notice(if diagnostic.is_empty() {
format!("Loop gate failed: {probe} ({status})")
} else {
format!("Loop gate failed: {probe} ({status}) - {diagnostic}")
}));
eprintln!("[loop] gate FAIL - {} ({})", probe, status);
if !output.trim().is_empty() {
eprintln!("{}", output.trim_end());
}
}

fn on_cost_update(&self, estimate: &gaviero_core::swarm::verify::CostEstimate) {
self.publish(LiveUpdate::Cost(estimate.estimated_usd));
eprintln!("[cost] ~${:.4}", estimate.estimated_usd);
}
}
Expand Down Expand Up @@ -4735,7 +4810,7 @@ async fn main() -> Result<()> {
}

// Execute via swarm pipeline
let swarm_observer = CliSwarmObserver;
let swarm_observer = CliSwarmObserver::default();
let specificity = workspace.resolve_specificity_config(Some(&repo));
let (swarm_extra_tools, _) = workspace.resolve_agent_tools(Some(&repo));
// Shell policy from the workspace cascade; agents run in worktrees
Expand Down Expand Up @@ -4908,6 +4983,11 @@ async fn main() -> Result<()> {
None
};

// Publish the run for the phone app (any TUI with remote on this machine
// serves `~/.gaviero/remote/cli-runs`).
let live = start_live_run(&cli, &plan, &repo);
let flusher = live.as_ref().map(LiveRunHandle::spawn_flusher);
let swarm_observer = CliSwarmObserver { live: live.clone() };
let result = gaviero_core::swarm::pipeline::execute(
&plan,
&config,
Expand All @@ -4916,11 +4996,22 @@ async fn main() -> Result<()> {
&swarm_observer,
|agent_id| {
let verbose = cli.script.is_none();
Box::new(CliAcpObserver::new(agent_id, verbose))
Box::new(CliAcpObserver::new(agent_id, verbose).publishing(live.clone()))
as Box<dyn gaviero_core::observer::AcpObserver>
},
)
.await?;
.await;
if let Some(flusher) = flusher {
flusher.stop().await;
}
if let Some(live) = live {
let outcome = match &result {
Ok(result) => LiveUpdate::Completed(Box::new(result.clone())),
Err(e) => LiveUpdate::Failed(format!("{e:#}")),
};
let _ = tokio::task::spawn_blocking(move || live.finish(outcome)).await;
}
let result = result?;

// Drain the extractor writer before the runtime shuts down, so in-flight
// swarm-finding extraction (slow LLM calls enqueued right up to the end
Expand Down Expand Up @@ -4988,6 +5079,51 @@ async fn main() -> Result<()> {
}
}

/// Start the run's published record (`swarm::live_run`): every planned agent
/// queued, labelled like the SWARM panel labels a run. None when there is no
/// machine folder; a write failure only logs.
fn start_live_run(
cli: &Cli,
plan: &gaviero_core::swarm::plan::CompiledPlan,
run_root: &std::path::Path,
) -> Option<LiveRunHandle> {
let store = CliRunStore::machine_default()?;
let stem = |p: &std::path::Path| {
p.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| p.display().to_string())
};
let mut script = if let Some(path) = &cli.script {
stem(path)
} else if let Some(path) = &cli.plan {
stem(path)
} else if cli.work_units.is_some() {
"work units".to_string()
} else {
"task".to_string()
};
if let Some(workflow) = &cli.workflow {
script = format!("{script} · {workflow}");
}
let folder = run_root
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
let planned = plan
.work_units_ordered()
.unwrap_or_default()
.iter()
.chain(plan.loop_judge_units.iter())
.map(|unit| PlannedAgent {
id: unit.id.clone(),
tier: unit.tier,
model: unit.model.clone(),
})
.collect();
let run = LiveRun::new(CliRunStore::new_run_id(), script, folder, planned);
Some(LiveRunHandle::start(store, run))
}

/// Build an extraction-LLM-equipped memory writer for the headless swarm
/// (PR-6-replacement, scope-B follow-up). Mirrors the TUI: resolve
/// `memory.extractor.model` (falling back to the agent model), build the
Expand Down
45 changes: 45 additions & 0 deletions crates/gaviero-cli/tests/state_modes_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ fn run(script: &Path, workspace: &Path, extra: &[&str]) -> Output {
.args(extra)
// Covers the isolated run with no settings to read.
.env("GAVIERO_EMBEDDER_MODEL", "null")
.env("GAVIERO_CLI_RUNS_DIR", shared_cli_runs_dir())
.output()
.expect("spawn gaviero-cli")
}
Expand Down Expand Up @@ -159,8 +160,18 @@ fn enclosed_by_a_workspace(dir: &Path) -> bool {
.any(|d| Some(d) != home.as_deref() && has_workspace_marker(d))
}

/// Where test runs publish their live record (`swarm::live_run`) — never
/// the user's `~/.gaviero/remote/cli-runs`, which the phone lists.
fn shared_cli_runs_dir() -> PathBuf {
std::env::temp_dir().join("gaviero-cli-runs-tests")
}

/// `gaviero-cli --script` started from `cwd`, with no root flags.
fn run_from(cwd: &Path, script: &Path) -> Output {
run_from_publishing(cwd, script, &shared_cli_runs_dir())
}

fn run_from_publishing(cwd: &Path, script: &Path, cli_runs: &Path) -> Output {
Command::new(gaviero_cli())
.current_dir(cwd)
.arg("--script")
Expand All @@ -172,6 +183,7 @@ fn run_from(cwd: &Path, script: &Path) -> Output {
.args(["--model", "ollama:qwen", "--no-mcp"])
.args(["--skip-mcp-preflight", "--run-timeout", "120"])
.env("GAVIERO_EMBEDDER_MODEL", "null")
.env("GAVIERO_CLI_RUNS_DIR", cli_runs)
.output()
.expect("spawn gaviero-cli")
}
Expand Down Expand Up @@ -224,6 +236,39 @@ fn a_run_from_the_workspace_folder_uses_its_memory_and_graph() {
assert!(!root.join(".gaviero/graphs").exists(), "{stderr}");
}

/// Every run is published for the phone app: one record under the machine
/// folder, finished, with the agent's row and its output.
#[test]
fn a_run_is_published_for_the_phone() {
let tmp = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(tmp.path()).unwrap().join("proj");
std::fs::create_dir_all(&root).unwrap();
configure(&root);
init_repo(&root);
let script = write_repo_script(&root);
let runs = tmp.path().join("cli-runs");

let stderr = stderr_of(&run_from_publishing(&root, &script, &runs));

let records: Vec<_> = std::fs::read_dir(&runs)
.unwrap_or_else(|e| panic!("no cli-runs folder ({e}): {stderr}"))
.flatten()
.map(|e| e.path())
.collect();
assert_eq!(records.len(), 1, "{records:?}");
let run: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(records[0].join("run.json")).unwrap())
.unwrap();
assert_eq!(run["script"], "wf", "{run}");
assert_eq!(run["folder"], "proj", "{run}");
assert_eq!(run["running"], false, "{run}");
assert_eq!(run["phase"], "completed", "{run}");
assert_eq!(run["agents"][0]["id"], "writer", "{run}");
assert_eq!(run["agents"][0]["status"], "completed", "{run}");
let output = std::fs::read_to_string(records[0].join("agents/writer.json")).unwrap();
assert!(output.contains("Running"), "{output}");
}

/// Each folder of a multi-folder workspace has its own graph in the TUI, so
/// a run from the second folder must use that one too.
#[test]
Expand Down
2 changes: 1 addition & 1 deletion crates/gaviero-core/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Network/model tests (Ollama, embedder downloads, Cursor/Codex/Claude CLI presenc
| Turn capture | [`turn_capture/`](src/turn_capture) | Host-side, git-free record of everything a chat turn changed: baseline manifest + SHA-256 blob store (`<root>/.gaviero/turns`, blobs ≤ 8 MiB), `begin`/`end` diff, host-write ledger, overlap marking, sensitive auto-revert, byte-exact file/hunk revert, persisted pending reviews, retention (last 5 reviewed turns + pending). Sessions honour it via `AgentOptions::host_capture`. |
| Repo map | [`repo_map/`](src/repo_map) | Graph + [`topology.rs`](src/repo_map/topology.rs) + symbol enrichment/search. Live per-folder graph: [`repo_map/service.rs`](src/repo_map/service.rs) (`GraphService`, single writer thread). |
| Skills | [`skills/`](src/skills) | Frontmatter, catalog, planner `ResolvedSkill` seam, opt-in constitution emit ([`skills/emit.rs`](src/skills/emit.rs)). |
| Scripts | [`scripts.rs`](src/scripts.rs), [`script_profiles.rs`](src/script_profiles.rs) | Named `.gaviero/dsl/<name>/<name>.gaviero` workflows and `.gaviero/dsl/profiles/<name>.gaviero` model profiles (located here, parsed by `gaviero-dsl`; `profiles` is therefore not a valid script name). Scopes and name resolution are shared with skills in [`scoped_folders.rs`](src/scoped_folders.rs); run preparation shared by CLI and TUI is in [`swarm/script_run.rs`](src/swarm/script_run.rs). |
| Scripts | [`scripts.rs`](src/scripts.rs), [`script_profiles.rs`](src/script_profiles.rs) | Named `.gaviero/dsl/<name>/<name>.gaviero` workflows and `.gaviero/dsl/profiles/<name>.gaviero` model profiles (located here, parsed by `gaviero-dsl`; `profiles` is therefore not a valid script name). Scopes and name resolution are shared with skills in [`scoped_folders.rs`](src/scoped_folders.rs); run preparation shared by CLI and TUI is in [`swarm/script_run.rs`](src/swarm/script_run.rs). Run records for the TUI SWARM panel's History and continue (`<folder>/.gaviero/swarm-runs/`, `resume_checkpoint` over the pipeline's `.gaviero/state/<plan-hash>.json`) are in [`swarm/run_history.rs`](src/swarm/run_history.rs). `gaviero-cli` runs publish a live record for the phone in [`swarm/live_run.rs`](src/swarm/live_run.rs) (machine folder `~/.gaviero/remote/cli-runs/`, `GAVIERO_CLI_RUNS_DIR` overrides; keeps 20; a running record not written for 90 s reads `interrupted`). `CliRunStore::list_json` / `detail_json` build the `GET /v1/cli-runs[/<id>]` bodies the TUI serves. |
| History | [`history/`](src/history) | Per-turn NDJSON log (`.gaviero/history/turns.ndjson`): record model, the single `HistoryRecorder` (keys every capture by `turn_id`), tolerant reader shared by the TUI panel and `gaviero-cli --history`, the one token estimator. Write-only from host capture points; nothing under `memory/`, `context_planner/`, `mcp/`, `agent_session/`, `swarm/` imports it. Size-rotated through [`util::ndjson`](src/util/ndjson.rs), shared with the MCP telemetry sink. |
| Session persistence | [`session_state.rs`](src/session_state.rs), [`session_journal.rs`](src/session_journal.rs) | State + conversations save only on a clean quit; the journal appends each prompt at dispatch (fsync) so a crash can't lose it. All saves are tmp-file + rename. |
| Other | `acp`, `context_planner`, `validation_gate`, `git`, `git_conflict`, `terminal`, `util`, `workspace`, … | See `lib.rs`. |
Expand Down
Loading
Loading