diff --git a/CHANGELOG.md b/CHANGELOG.md index 132fa3a0..0a70c989 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,14 @@ and listed with their assets on the a popover with the hub's and the shown stack's devstack, a "Check for updates" button (`POST /hub/update/check`: the hub asks GitHub now instead of at its next 12-hour look) and, when there is one, the update to install. +- **Lanes can be started from the main tree** + ([#103](https://github.com/nuetzliches/devstack/issues/103)). `devstack + lane start [--on ]` and the MCP tools `lane_start` and + `lane_stop` start and stop another worktree's lane from wherever they run, + so an agent in the main tree can run another branch or commit in + isolation instead of building a separate environment. `devstack status` + (and the MCP `status`) in the main tree names the lanes in one line. The + `devstack` skill has the recipe "run a commit beside the main stack". - **The pool knows which devstack each party runs** ([ADR-0031](docs/adr/0031-a-coordinator-places-lanes.md) point 8; [pool.md](docs/pool.md#versions-in-a-pool)). Nodes and members diff --git a/README.md b/README.md index 52d8deec..2520af08 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,7 @@ devstack down [--infra] [--all] # running lanes keep the daemon; --all stops ```sh git worktree add ../shop-login -b login-fix # a worktree is a lane at once cd ../shop-login && devstack up # its own builds, ports +100, its own containers +devstack lane start login-fix # the same, from the main tree devstack lane list # every lane, where it runs, who has the main ports devstack promote --lane login-fix # it answers on the main ports; --lane main gives them back devstack lane stop login-fix diff --git a/crates/devstack/src/client.rs b/crates/devstack/src/client.rs index fe9b7bfa..4f22111b 100644 --- a/crates/devstack/src/client.rs +++ b/crates/devstack/src/client.rs @@ -620,6 +620,13 @@ pub fn print_status(stack: &Value) { /// no longer match. pub fn print_status_for(stack: &Value, stack_file: &Path) { print_status(stack); + if let Some(n) = Client::probe(&state_dir(stack_file).unwrap_or_default()) + .ok() + .flatten() + .and_then(|c| lanes_note(&c)) + { + println!("\n{n}"); + } if let Some(n) = crate::skills::outdated_note(stack_file) { println!("\n{n}"); } @@ -1285,10 +1292,148 @@ pub fn lane_stop(stack_file: &Path, name: &str) -> Result<()> { if status >= 400 { bail!("{}", error_text(&body)); } - println!("lane `{name}` stopped; `devstack up` in its worktree starts it again"); + println!( + "lane `{name}` stopped; `devstack lane start {name}` (or `devstack up` in its worktree) starts it again" + ); Ok(()) } +/// A lane started from wherever this runs (#103): its name and its +/// node's version warning, if any; `client` then talks to it. +pub struct StartedLane { + pub client: Client, + pub name: String, + pub file: PathBuf, + pub warning: Option, +} + +/// Start the lane `name` (its name or branch, see `lane list`) of this +/// repository, here or on a node (`on`), from the main working tree or any +/// worktree: the daemon is started if it does not run. `step` hears a start +/// on a node step by step. +pub fn start_lane( + stack_file: &Path, + name: &str, + on: Option<&str>, + within: Option, + step: impl FnMut(&Value), +) -> Result { + let main_file = daemon_file(stack_file); + // A lane on a node needs no Docker here: everything of it runs there. + if on.is_none() { + ensure_engine(&main_file, |l| println!("{l}"))?; + } + let mut c = ensure_daemon(&main_file, &state_dir(stack_file)?)?; + let lanes: Vec = serde_json::from_str(&c.get("/v1/lanes")?)?; + let lane = lanes + .iter() + .find(|l| l["name"] == name) + .or_else(|| lanes.iter().find(|l| l["branch"] == name)) + .ok_or_else(|| { + let known: Vec<&str> = lanes.iter().filter_map(|l| l["name"].as_str()).collect(); + anyhow!( + "no lane `{name}`: {} (a lane is a `git worktree` of the repository)", + if known.is_empty() { + "the repository has no other worktree".to_string() + } else { + format!("the lanes are {}", known.join(", ")) + } + ) + })?; + let path = PathBuf::from(lane["path"].as_str().unwrap_or_default()); + // Its own stack file says which services it starts; its branch may + // differ from the main tree's. + let file = main_file + .file_name() + .map(|f| path.join(f)) + .filter(|f| f.is_file()) + .unwrap_or_else(|| main_file.clone()); + let wt = Worktree { + path, + main_file: main_file.clone(), + }; + let name = c.join_lane(&wt, false, false, on, within, step)?; + let warning = on.and_then(|_| { + c.call_raw("GET", "/v1/lanes", None) + .ok() + .and_then(|(_, body)| serde_json::from_str::>(&body).ok()) + .and_then(|ls| ls.into_iter().find(|l| l["name"] == name.as_str())) + .and_then(|l| l["node_warning"].as_str().map(str::to_string)) + }); + Ok(StartedLane { + client: c, + name, + file, + warning, + }) +} + +/// `devstack lane start [--on ]`: as `devstack up` in that +/// worktree, from anywhere in the repository. +pub fn lane_start(stack_file: &Path, name: &str, on: Option<&str>) -> Result<()> { + if let Some(node) = on { + println!("leasing, syncing and starting the lane on {node}..."); + } + let started = start_lane(stack_file, name, on, None, |m| { + if m["step"] != 0 { + println!("{}", step_line(m)); + } + })?; + if let Some(w) = &started.warning { + eprintln!("warning: {w}"); + } + println!("lane `{}` started", started.name); + let t0 = Instant::now(); + let outcome = start_and_wait(&started.client, &started.file, None, |name, st| { + println!("{:>6.1}s {name:<22} {st}", t0.elapsed().as_secs_f64()); + })?; + match outcome { + UpOutcome::Ready(stack) => { + println!(); + print!("{}", status_text(&stack)); + Ok(()) + } + UpOutcome::Failed { service, reason } => { + eprintln!("\n{service} failed:\n{reason}"); + std::process::exit(1); + } + UpOutcome::TimedOut(_) => unreachable!("no timeout given"), + } +} + +/// One line on the lanes for `status` in the main working tree (#103): that +/// worktrees exist, which run, and how to start one beside the main tree. +pub fn lanes_note(c: &Client) -> Option { + if c.lane().is_some() { + return None; + } + let lanes: Vec = serde_json::from_str(&c.get("/v1/lanes").ok()?).ok()?; + if lanes.is_empty() { + return None; + } + let started: Vec = lanes + .iter() + .filter(|l| l["active"] != false) + .map(|l| { + let name = l["name"].as_str().unwrap_or(""); + match l["node"].as_str() { + Some(node) => format!("{name} on {node}"), + None => name.to_string(), + } + }) + .collect(); + Some(format!( + "lanes: {} worktree(s), {} started{}; `devstack lane list`, `devstack lane start `", + lanes.len(), + started.len(), + if started.is_empty() { + String::new() + } else { + format!(" ({})", started.join(", ")) + } + )) +} + pub fn promote_lane(stack_file: &Path, lane: &str) -> Result<()> { let c = main_client(stack_file)?; let (status, body) = c.call_raw("POST", &format!("/v1/lanes/{lane}/main"), None)?; diff --git a/crates/devstack/src/dispatch/lane.rs b/crates/devstack/src/dispatch/lane.rs index 188f5dd6..eccf8e8c 100644 --- a/crates/devstack/src/dispatch/lane.rs +++ b/crates/devstack/src/dispatch/lane.rs @@ -7,6 +7,7 @@ use std::path::Path; pub(crate) fn run(file: &Path, action: LaneAction) -> Result<()> { match action { LaneAction::List => client::lane_list(file), + LaneAction::Start { name, on } => client::lane_start(file, &name, on.as_deref()), LaneAction::Stop { name } => client::lane_stop(file, &name), LaneAction::Move { name, to } => client::lane_move(file, &name, &to), LaneAction::Share { name, with } => client::lane_share(file, &name, &with), diff --git a/crates/devstack/src/main.rs b/crates/devstack/src/main.rs index d4810103..c834c1a0 100644 --- a/crates/devstack/src/main.rs +++ b/crates/devstack/src/main.rs @@ -335,6 +335,16 @@ enum PoolAction { enum LaneAction { /// The lanes (the repository's worktrees), their branches and ports. List, + /// Start a lane (its name or branch, see `lane list`) from anywhere in + /// the repository, as `devstack up` in its worktree does: its own ports + /// and containers, beside the main tree. + Start { + name: String, + /// Run it on this node of the pool (its name or member id), or + /// `pool` to let the coordinator choose (ADR-0025). + #[arg(long, value_name = "NODE")] + on: Option, + }, /// Stop a lane: its services stop and it is no longer started (its /// builds stay). The worktree is git's: devstack never creates or removes /// one. diff --git a/crates/devstack/src/mcp.rs b/crates/devstack/src/mcp.rs index a25f92d9..f8ceb106 100644 --- a/crates/devstack/src/mcp.rs +++ b/crates/devstack/src/mcp.rs @@ -310,6 +310,26 @@ pub fn tools() -> Vec { &[], true, ), + tool( + "lane_start", + "Start a lane (a git worktree of this repository, see `lanes`) beside the main working tree, from wherever this MCP server runs: its own ports (moved by its offset), its own containers and database, no background workers. Waits until its services are ready, like `up`. Use it to run another branch or commit in isolation instead of building a separate environment: `git worktree add ` makes the lane, `lane_stop` stops it, `git worktree remove ` ends it. POST /v1/lanes, then the lane's /v1/up.", + json!({ + "lane": { "type": "string", "description": "The lane's name or branch (see `lanes`)" }, + "on": { "type": "string", "description": "Run it on this node of the pool, or `pool` to let the coordinator choose; default: this machine" }, + "timeout_s": { "type": "integer", "description": "How long to wait for its services (default 600)" }, + }), + &["lane"], + false, + ), + tool( + "lane_stop", + "Stop a started lane: its services stop, its builds and containers' data stay; `lane_start` starts it again. Not the lane serving the main ports (`promote_lane` main first). POST /v1/lanes/{lane}/stop.", + json!({ + "lane": { "type": "string", "description": "The lane's name (see `lanes`)" }, + }), + &["lane"], + false, + ), tool( "lane_move", "Move a started lane to another node of the pool, or back to this machine (`local`): a cold start there that takes over once it is ready; its data comes from the seed jobs again. POST /v1/lanes/{lane}/move.", @@ -433,7 +453,11 @@ fn checked(status: u16, body: String) -> Result { fn call(name: &str, args: &Value, file: &Path) -> Result { match name { "status" => { - let mut text = client::status_text(&connect(file)?.stack()?); + let c = connect(file)?; + let mut text = client::status_text(&c.stack()?); + if let Some(n) = client::lanes_note(&c) { + text.push_str(&format!("\n{n}\n")); + } if let Some(n) = crate::skills::outdated_note(file) { text.push_str(&format!("\n{n}\n")); } @@ -550,6 +574,41 @@ fn call(name: &str, args: &Value, file: &Path) -> Result { devstack_daemon::ansi::strip(&text).into_owned() }) } + "lane_start" => { + let lane = name_arg(args, "lane")?; + let timeout = Duration::from_secs(args["timeout_s"].as_u64().unwrap_or(600)); + let on = args["on"].as_str().filter(|o| !o.trim().is_empty()); + let started = client::start_lane(file, lane, on, Some(timeout), |_| {})?; + let mut notes = format!("lane `{}` started\n", started.name); + if let Some(w) = &started.warning { + notes.push_str(&format!("warning: {w}\n")); + } + match client::start_and_wait(&started.client, &started.file, Some(timeout), |_, _| {})? + { + UpOutcome::Ready(stack) => { + Ok(format!("{notes}ready\n\n{}", client::status_text(&stack))) + } + UpOutcome::Failed { service, reason } => { + anyhow::bail!("{notes}{service} failed:\n{reason}") + } + UpOutcome::TimedOut(stack) => anyhow::bail!( + "{notes}still starting after {} s (it continues; check `status`)\n\n{}", + timeout.as_secs(), + client::status_text(&stack) + ), + } + } + "lane_stop" => { + let lane = name_arg(args, "lane")?; + let c = client::main_client(file)?; + let (status, text) = c.call_raw("POST", &format!("/v1/lanes/{lane}/stop"), None)?; + if status >= 400 { + anyhow::bail!("{}", client::error_text(&text)); + } + Ok(format!( + "lane `{lane}` stopped; `lane_start` starts it again" + )) + } "lane_move" | "lane_share" | "promote_lane" => { let lane = name_arg(args, "lane")?; let (path, body) = match name { @@ -749,7 +808,13 @@ mod tests { #[test] fn lane_names_from_the_agent_stay_plain() { let file = Path::new("no-such-dir/devstack.toml"); - for tool in ["lane_move", "lane_share", "promote_lane"] { + for tool in [ + "lane_start", + "lane_stop", + "lane_move", + "lane_share", + "promote_lane", + ] { for bad in ["wt/stop?", "wt/v1/down?", "../x", ""] { let args = json!({ "lane": bad, "to": "local", "with": [] }); let e = call(tool, &args, file).unwrap_err().to_string(); diff --git a/crates/devstack/tests/daemon_lifecycle.rs b/crates/devstack/tests/daemon_lifecycle.rs index 1d3b0ee0..a175c575 100644 --- a/crates/devstack/tests/daemon_lifecycle.rs +++ b/crates/devstack/tests/daemon_lifecycle.rs @@ -1703,6 +1703,38 @@ fn a_worktree_runs_as_a_lane() { ); assert!(s.ok(&["lane", "list"]).contains(&extra_name)); + // 7. The main tree names its lanes, and starts and stops one without + // going to its worktree (#103). + let status = s.ok(&["status"]); + assert!( + status.contains("lanes: 1 worktree(s), 0 started"), + "{status}" + ); + let out = s.cli(&["lane", "start", &extra_name], None); // `broken` fails, the rest runs + let started = String::from_utf8_lossy(&out.stdout).to_string(); + assert!( + started.contains(&format!("lane `{extra_name}` started")), + "{started}" + ); + let row = |name: &str| { + s.ok(&["lane", "list"]) + .lines() + .find(|l| l.starts_with(name)) + .unwrap_or_default() + .to_string() + }; + assert!( + !row(&extra_name).contains("stopped"), + "{}", + row(&extra_name) + ); + assert!( + s.ok(&["status"]) + .contains(&format!("1 started ({extra_name})")) + ); + s.ok(&["lane", "stop", &extra_name]); + assert!(row(&extra_name).contains("stopped"), "{}", row(&extra_name)); + s.ok(&["down", "--all"]); for dir in [&wt, &extra] { let _ = Command::new("git") diff --git a/docs/stack-file.md b/docs/stack-file.md index 552304a9..fccadbd4 100644 --- a/docs/stack-file.md +++ b/docs/stack-file.md @@ -420,8 +420,10 @@ in the snapshot: `prepare` installs what is missing. fixed port is the main tree's). - `devstack promote --lane ` lets a lane's services answer on the main ports (dev servers through a TCP forward); `--lane main` gives them back. -- `devstack lane list`; `devstack lane stop ` stops a lane (its - builds stay, the worktree too). +- `devstack lane list`; `devstack lane start ` starts a lane from + anywhere in the repository, as `devstack up` in its worktree does; + `devstack lane stop ` stops a lane (its builds stay, the worktree + too). ## `[commands.]`: operations diff --git a/skills/devstack/SKILL.md b/skills/devstack/SKILL.md index 4e86af25..80af41b0 100644 --- a/skills/devstack/SKILL.md +++ b/skills/devstack/SKILL.md @@ -56,6 +56,7 @@ Run from the repository root (devstack looks for `{{devstack:stack_file}}` there | `devstack hot-reload on\|off` | for a debugging session: the toolchain's watcher (e.g. `dotnet watch`) from the source tree instead of builds and candidates; needs `hot_reload` in the stack file. Switch it off again afterwards | | `devstack up` in a `git worktree` | starts that worktree's **lane** (every worktree is one) in the main tree's daemon: its own builds, ports moved by +100 (+200, ...), its own containers (a Compose project per lane, ports moved alike; `shared` services come from the main tree), no background workers (`--workers` turns them on; `--force` skips the memory check). Every command in the worktree then acts on the lane (`devstack lane list` shows all) | | `git worktree add -b ` | a new worktree is a lane at once, not started (devstack never creates or removes worktrees; use git or your tool). A lane runs from a copy of its worktree, so `git worktree remove` works while it runs and stops it. `devstack lane stop ` stops a lane and keeps the worktree | +| `devstack lane start [--on ]` | start a lane from the main tree (or anywhere in the repository), as `devstack up` in its worktree does; `status` in the main tree lists the lanes in one line. **To run another branch or commit beside the main stack** (an end-to-end run against a given commit, a review): `git worktree add `, `devstack lane start ` (its ports are the main ports plus its offset, `devstack lane list`), test against those, `devstack lane stop `, `git worktree remove `. A worktree another tool or script created is a lane too: starting it gives its own ports, containers and database without building a separate environment | | `devstack promote --lane ` | the lane's services, dev servers included, answer on the main ports; ask the user first, `--lane main` gives them back. A lane on a node may take them only on a dedicated node (a server) | | `devstack up --on ` in a worktree | the lane runs on that machine of the pool (`pool`: the coordinator picks one, `:` in another pool): build, services, its own containers; its ports are forwarded here as if it ran locally. Ask the user first: the worktree's files go to that machine, untracked env files git does not ignore included | | `devstack lane move --to ` | move a started lane: a cold start there that takes over once ready; its data comes from the seed jobs again | @@ -119,8 +120,10 @@ port tell within a second, and they are the evidence to quote. `devstack mcp` is an MCP server (stdio) with `status`, `up` (`on` for a lane on a node), `down`, `start_service`, `stop_service`, `restart_service`, `promote_service`, `rollback_service`, `hot_reload`, `logs`, `builds`, -`diagnostics`, `doctor`, `run_command`, `usage`, `lanes`, `lane_move`, -`lane_share`, `promote_lane`, `hub_status`, `hub_start`. +`diagnostics`, `doctor`, `run_command`, `usage`, `lanes`, `lane_start`, +`lane_stop`, `lane_move`, `lane_share`, `promote_lane`, `hub_status`, +`hub_start`. `lane_start` and `lane_stop` work from the main tree too: an +agent there runs another worktree's lane without moving to it. Register it once (project `.mcp.json` or user configuration): ```json