git clone https://garage44.eu/jeroen/midas.git.. /src/flush.rs
//! The node's checkout follows the agent's worktree (DESIGN.md §7).
//!
//! **The barrier is ssh's own.** The agent container's ssh configuration has,
//! for every node,
//!
//! ```text
//! Match host gpu-1 exec "midas flush gpu-1"
//! ```
//!
//! and OpenSSH runs that *locally, before it connects*, for every `ssh`, `scp`,
//! `rsync` and `git` it carries to the node. So `ssh gpu-1 'cargo test'` right
//! after an edit tests that edit — synchronously, with no daemon, and with the
//! agent typing plain `ssh`.
//!
//! What travels, and only what changed since the last flush of this lease:
//!
//! * **A new HEAD.** The node fetches it from the hub's mirror if it is pushed;
//! otherwise it arrives as a git bundle of the commits the mirror lacks, so
//! local commits work too. Then the node's tree is reset to it (`target/`
//! kept) and every uncommitted file is sent again.
//! * **Uncommitted changes**: modified and untracked files (`.gitignore`
//! respected), deletions, and files that went back to clean.
//!
//! Nothing travels while another ssh session from this worktree still runs a
//! command on the node — a build in the background, a second agent's test —
//! because the sync would change files under it. The node says so (its
//! session wrapper keeps a marker per running command), the flush says so, and
//! the edits go with the next ssh after it ends; `MIDAS_SYNC=force` sends them
//! anyway.
//!
//! Rules this has to keep:
//!
//! * **Never stdout.** Match-exec output would land in the middle of an scp or
//! git stream; everything here goes to stderr, children's stdout to null.
//! * **Never recurse.** The flush's own ssh to the node would run the Match
//! again; `MIDAS_FLUSHING` stops it.
//! * **Only for the holder.** A worktree whose session does not hold the node
//! sends nothing and says so — otherwise an agent would quietly overwrite
//! somebody else's checkout.
//! * **Always exit 0.** Match exec's status only decides whether an (empty)
//! config block applies; a failure is reported on stderr, not as a refusal
//! to connect.
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Instant, UNIX_EPOCH};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::events;
use crate::registry;
use crate::util::git;
#[derive(Serialize, Deserialize, Default)]
struct State {
lease: i64,
head: String,
/// The worktree's repository (`owner/name`): another one is another checkout on the node.
#[serde(default)]
repo: String,
/// Uncommitted paths at the last flush → fingerprint ("size:mtime_ns", or
/// "deleted").
files: BTreeMap<String, String>,
}
fn state_path(node: &str) -> PathBuf {
let base = std::env::var("XDG_CACHE_HOME")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| "/tmp".into())).join(".cache"));
base.join("midas").join(format!("flush-{node}.json"))
}
/// Uncommitted paths and their fingerprints; `"deleted"` for tracked files that
/// are gone. Renames count as the new path changed and the old one deleted.
fn uncommitted(top: &Path) -> Result<BTreeMap<String, String>> {
let raw = Command::new("git")
.arg("-C")
.arg(top)
.args(["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"])
.output()?;
if !raw.status.success() {
bail!("git status failed");
}
let mut m = BTreeMap::new();
for entry in raw.stdout.split(|b| *b == 0).filter(|e| e.len() > 3) {
let path = String::from_utf8_lossy(&entry[3..]).to_string();
let full = top.join(&path);
match fs::symlink_metadata(&full) {
Ok(md) if md.is_file() || md.is_symlink() => {
let mtime = md.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map(|d| d.as_nanos()).unwrap_or(0);
m.insert(path, format!("{}:{mtime}", md.len()));
}
Ok(_) => {}
Err(_) => {
m.insert(path, "deleted".into());
}
}
}
Ok(m)
}
fn ssh_node(node: &str) -> Command {
let mut c = Command::new("ssh");
c.args(["-o", "BatchMode=yes", "--", node]).env("MIDAS_FLUSHING", "1");
c
}
pub fn flush(node: &str) -> Result<i32> {
if std::env::var_os("MIDAS_FLUSHING").is_some() {
return Ok(0);
}
run_flush(node, None);
Ok(0)
}
/// Who holds a node, as `client::lease` says it, beside how many notes wait
/// for this session (said on the ssh it runs anyway; its hooks hand them
/// over, collab.rs). Asked together: every ssh to a node waits for both.
fn lease_and_notes(node: &str, owner: &str) -> Result<Option<(String, i64)>> {
std::thread::scope(|s| {
s.spawn(|| crate::collab::mention_waiting(owner));
crate::client::lease(node)
})
}
/// The flush, with the lease when the caller has already asked for it. Whether
/// the node now has this worktree's files.
fn run_flush(node: &str, known: Option<Option<(String, i64)>>) -> bool {
match flush_inner(node, known) {
Ok(()) => true,
Err(e) => {
eprintln!("midas: could not bring {node} up to date with this worktree: {e:#}");
events::emit("sync_failed", json!({"node": node, "what": format!("{e:#}")}));
false
}
}
}
fn flush_inner(node: &str, known: Option<Option<(String, i64)>>) -> Result<()> {
let Ok(top) = git(Path::new("."), &["rev-parse", "--show-toplevel"]) else {
return Ok(()); // not in a worktree: nothing to follow
};
let top = PathBuf::from(top.trim());
let owner = worktree_owner(&top);
let lease = match known {
Some(l) => l,
None => lease_and_notes(node, &owner)?,
};
// Said only when the connection goes ahead anyway: otherwise `midas holds`
// has already refused it, with the same reason.
let anyway = std::env::var_os("MIDAS_SSH_ANYWAY").is_some();
let Some((held, lease_id)) = lease else {
if anyway {
eprintln!("midas: {node} is not leased; nothing synced");
}
return Ok(());
};
// The worktree's session, or the landing gate it runs (a project's
// verify-branch claims as `gate-<worktree>` so a gate and its session can
// each hold a node).
if held != owner && held != format!("gate-{owner}") {
if anyway {
eprintln!("midas: {node} is held by {held}, not this worktree ({owner}); nothing synced");
}
return Ok(());
}
let started = Instant::now();
let head = git(&top, &["rev-parse", "HEAD"])?.trim().to_string();
let repo = worktree_repo(&top).unwrap_or_default();
let now_files = uncommitted(&top)?;
let sp = state_path(node);
let prev: State = fs::read_to_string(&sp).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
let full = prev.lease != lease_id || prev.head != head || prev.repo != repo;
let (send, delete, revert) = changes(&prev, &now_files, full);
if !full && send.is_empty() && delete.is_empty() && revert.is_empty() {
return Ok(()); // the common case: nothing changed since the last command
}
// Not under a running command: a second ssh while a build runs would change
// its files mid-build. The node decides (it knows what runs there), and an
// older node ignores the field and applies as it always did.
let force = std::env::var("MIDAS_SYNC").is_ok_and(|v| v == "force");
let manifest = json!({
"head": head, "full": full, "delete": delete, "revert": revert,
"owner": owner, "lease": lease_id, "unless_busy": !force, "repo": repo,
});
// A commit the node does not have arrives as a bundle of what the mirror
// lacks — empty when HEAD is pushed, and then the node fetches from the hub.
// A repository the hub does not mirror (or a node that has never seen it)
// cannot fetch the rest: the node says so, and it is sent the whole history.
let (mut tar_ok, mut ssh) = std::thread::scope(|s| {
// Something changed: tell the hub which files this branch now touches,
// so a session changing the same ones hears of it. Beside the transfer,
// which the agent's ssh waits for, rather than before it.
s.spawn(|| crate::collab::send_work(&top, &owner));
send_once(node, &top, &head, &manifest, &send, full, false)
})?;
if tar_ok && ssh.code() == Some(NEED_HISTORY) {
(tar_ok, ssh) = send_once(node, &top, &head, &manifest, &send, full, true)?;
}
if tar_ok && ssh.code() == Some(BUSY) {
// Nothing was applied, and the state stays as it was: the next flush
// sends all of it.
eprintln!("midas: a command is still running on {node}; your edits wait there unapplied (they would change \
files under it). A build or test you run next waits up to a minute for it to end, then applies them; \
anything else runs on the files as they are (MIDAS_SYNC=force applies them now).");
events::emit("sync_deferred", json!({"node": node, "actor": owner, "full": full, "files": send.len() + delete.len() + revert.len()}));
return Ok(());
}
if !tar_ok || !ssh.success() {
bail!("the transfer failed (tar {}, ssh {})", if tar_ok { "ok" } else { "failed" }, ssh.code().unwrap_or(-1));
}
let st = State { lease: lease_id, head: head.clone(), repo, files: now_files };
fs::create_dir_all(sp.parent().unwrap())?;
fs::write(&sp, serde_json::to_string(&st)?)?;
let ms = started.elapsed().as_millis() as u64;
eprintln!(
"midas: {node} now matches this worktree ({}{} file(s), {} deleted, {} reverted, {ms} ms)",
if full { "reset to HEAD, " } else { "" },
send.len(), delete.len(), revert.len()
);
events::emit("barrier", json!({
"node": node, "actor": owner, "full": full, "head": head,
"sent": send.len(), "deleted": delete.len(), "reverted": revert.len(), "ms": ms,
}));
Ok(())
}
/// One tar, one ssh: the changed files from the worktree, then the manifest
/// and any bundle (`whole`: all of HEAD's history). Whether tar did its part,
/// and how `midas node apply` ended.
fn send_once(node: &str, top: &Path, head: &str, manifest: &serde_json::Value, send: &[String], full: bool, whole: bool)
-> Result<(bool, std::process::ExitStatus)> {
let incoming = tempdir()?;
if full {
bundle(top, head, &incoming, whole)?;
}
fs::write(incoming.join(".midas-manifest.json"), manifest.to_string())?;
// Its stderr the agent's, as ssh's is: piped and never read, 64 KB of warnings (files gone
// between `git status` and tar) filled the pipe, tar stopped, and the ssh waited on it for good.
let mut tar = pack(top, &incoming, send)?
.stdout(Stdio::piped()).stderr(Stdio::inherit())
.spawn().context("tar")?;
let tar_out = tar.stdout.take().unwrap();
let ssh = ssh_node(node)
.arg("midas node apply")
.stdin(tar_out).stdout(Stdio::null()).stderr(Stdio::inherit())
.status().context("ssh")?;
let tar_ok = tar.wait()?.success();
let _ = fs::remove_dir_all(&incoming);
Ok((tar_ok, ssh))
}
/// `midas node apply`'s status when it left the checkout alone because a
/// command still runs on the node (EX_TEMPFAIL).
const BUSY: i32 = 75;
/// `midas node apply`'s status when the bundle and the hub between them left
/// HEAD's history short: the flush sends it again with all of it.
const NEED_HISTORY: i32 = 76;
/// What to send: changed and new files, deleted ones, and ones clean again
/// since the last flush (`prev`). On a `full` flush (a new lease or HEAD)
/// every uncommitted file is sent, whatever was sent before.
fn changes(prev: &State, now_files: &BTreeMap<String, String>, full: bool) -> (Vec<String>, Vec<String>, Vec<String>) {
let mut send: Vec<String> = Vec::new();
let mut delete: Vec<String> = Vec::new();
let mut revert: Vec<String> = Vec::new();
for (p, fp) in now_files {
let same = !full && prev.files.get(p) == Some(fp);
if same {
continue;
}
if fp == "deleted" { delete.push(p.clone()) } else { send.push(p.clone()) }
}
if !full {
for p in prev.files.keys() {
if !now_files.contains_key(p) {
revert.push(p.clone()); // clean again: back to HEAD's version, or gone
}
}
}
(send, delete, revert)
}
/// The commits the mirror lacks, as `.midas-bundle` in `incoming` — none when
/// HEAD is pushed, and then the node fetches from the hub; or, `whole`, all
/// of HEAD's history, for a node with no mirror to fetch the rest from.
fn bundle(top: &Path, head: &str, incoming: &Path, whole: bool) -> Result<()> {
let unpushed = if whole {
1
} else {
git(top, &["rev-list", "--count", head, "--not", "--remotes=origin"])
.map(|n| n.trim().parse::<u64>().unwrap_or(1))
.unwrap_or(1)
};
if unpushed > 0 {
let b = incoming.join(".midas-bundle");
// A bundle carries refs, not bare commits: `git bundle create … <sha>`
// refuses as "empty". HEAD is the ref, and is the commit just read.
let mut args = vec!["bundle", "create", b.to_str().context("a temp path that is not UTF-8")?, "HEAD"];
if !whole {
args.extend(["--not", "--remotes=origin"]);
}
let ok = Command::new("git").arg("-C").arg(top).args(&args)
.stdout(Stdio::null()).stderr(Stdio::null())
.status()?.success();
if !ok {
bail!("could not bundle {}", if whole { "HEAD's history".to_string() } else { format!("the {unpushed} unpushed commit(s)") });
}
}
Ok(())
}
/// The tar of a flush: the `send` files from the worktree, then the manifest
/// (written beforehand) and any bundle from `incoming`.
fn pack(top: &Path, incoming: &Path, send: &[String]) -> Result<Command> {
let list = incoming.join(".midas-list");
fs::write(&list, send.join("\0"))?;
let mut tar = Command::new("tar");
tar.args(["-cf", "-", "--null", "-C"]).arg(top).arg("-T").arg(&list)
.arg("-C").arg(incoming)
.args([".midas-manifest.json"])
.args(incoming.join(".midas-bundle").exists().then_some(".midas-bundle"));
Ok(tar)
}
fn tempdir() -> Result<PathBuf> {
let base = std::env::temp_dir().join(format!("midas-flush-{}-{}", std::process::id(), registry::now()));
fs::create_dir_all(&base)?;
Ok(base)
}
// ─── the node's side ─────────────────────────────────────────────────────────
/// The worktree's repository, `owner/name`, from its `origin`: the last two
/// segments of the URL, whatever the scheme.
/// Whose a worktree is: the session whose folder it is in (`sessions::SESSION_MARK`,
/// a session that spans projects has one worktree per project there), else its own name.
pub(crate) fn worktree_owner(top: &Path) -> String {
let name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
match top.parent().filter(|d| d.join(crate::sessions::SESSION_MARK).is_file()) {
Some(folder) => name(folder),
None => name(top),
}
}
fn worktree_repo(top: &Path) -> Option<String> {
repo_of_url(git(top, &["remote", "get-url", "origin"]).ok()?.trim())
}
pub(crate) fn repo_of_url(url: &str) -> Option<String> {
let path = url.trim_end_matches('/').trim_end_matches(".git");
let mut parts = path.rsplit(['/', ':']);
let (name, owner) = (parts.next()?, parts.next()?);
crate::mirror::repo_name(&format!("{owner}/{name}")).ok().map(|r| r.trim_end_matches(".git").to_string())
}
/// Where a flush of `repo` lands on a node whose own checkout is `main`:
/// the node's repository in `main` (warm, and the only one an older agent
/// names), any other in a checkout of its own beside it, `/work/repos/owner/name`,
/// filled from the bundles the agent sends: the hub need not mirror it.
fn checkout_for(main: &Path, repo: &str) -> PathBuf {
let own = git(main, &["remote", "get-url", "origin"]).ok().and_then(|u| repo_of_url(u.trim()));
if repo.is_empty() || own.as_deref() == Some(repo) || own.is_none() {
return main.to_path_buf();
}
main.parent().unwrap_or(Path::new("/work")).join("repos").join(repo)
}
/// A second repository's checkout: an empty repository the first time, which
/// the agent's bundles fill (the first flush finds it short and sends all).
fn ensure_checkout(checkout: &Path) -> Result<()> {
if checkout.join(".git").exists() {
return Ok(());
}
let _ = fs::remove_dir_all(checkout);
fs::create_dir_all(checkout)?;
let out = Command::new("git").arg("init").arg("--quiet").arg(checkout).output()?;
if !out.status.success() {
let _ = fs::remove_dir_all(checkout);
bail!("git init {}: {}", checkout.display(), String::from_utf8_lossy(&out.stderr).trim());
}
Ok(())
}
/// Which checkout the last flush went to: where the node's sessions start.
pub const CURRENT: &str = "/work/.midas-checkout";
/// `midas node apply`: read the tar on stdin and make the worktree's checkout match.
pub fn apply() -> Result<i32> {
let incoming = PathBuf::from("/work/.midas-incoming");
let _ = fs::remove_dir_all(&incoming);
fs::create_dir_all(&incoming)?;
let ok = Command::new("tar").arg("-xf").arg("-").arg("-C").arg(&incoming).status()?.success();
if !ok {
bail!("could not unpack what the agent sent");
}
let m: serde_json::Value = serde_json::from_str(&fs::read_to_string(incoming.join(".midas-manifest.json"))?)?;
// A command of this worktree still runs here: leave its files alone, and
// keep what was sent for a build that comes next to apply once it ends
// (`apply_pending`). Each flush sends everything since the last one that
// was applied, so the newest replaces any older one.
if m["unless_busy"] == true && !crate::node::running_commands().is_empty() {
let _ = fs::remove_dir_all(PENDING);
if fs::rename(&incoming, PENDING).is_err() {
let _ = fs::remove_dir_all(&incoming);
}
return Ok(BUSY);
}
let _ = fs::remove_dir_all(PENDING);
apply_unpacked(&incoming, &m)
}
/// A flush held back while a command ran (`BUSY`), kept on the node.
pub const PENDING: &str = "/work/.midas-pending";
/// Whether a held-back flush waits to be applied.
pub fn pending() -> bool {
Path::new(PENDING).join(".midas-manifest.json").exists()
}
/// Apply the held-back flush, now that nothing runs that it would change
/// files under. Claimed by a rename first: two sessions may both get here.
pub fn apply_pending() -> Result<i32> {
let claimed = PathBuf::from(format!("{PENDING}-{}", std::process::id()));
if fs::rename(PENDING, &claimed).is_err() {
return Ok(0); // another session applied it
}
let m: serde_json::Value = serde_json::from_str(&fs::read_to_string(claimed.join(".midas-manifest.json"))?)?;
apply_unpacked(&claimed, &m)
}
fn apply_unpacked(incoming: &Path, m: &serde_json::Value) -> Result<i32> {
let main = PathBuf::from(std::env::var("MIDAS_CHECKOUT").unwrap_or_else(|_| crate::node::CHECKOUT.into()));
let repo = m["repo"].as_str().unwrap_or("");
let checkout = checkout_for(&main, repo);
if checkout != main {
ensure_checkout(&checkout)?;
}
if !apply_manifest(&checkout, incoming, m)? {
let _ = fs::remove_dir_all(incoming);
return Ok(NEED_HISTORY);
}
let _ = fs::write(CURRENT, checkout.to_string_lossy().as_bytes());
Ok(0)
}
/// Make `checkout` match what was unpacked in `incoming`, as its manifest `m`
/// says: reset to its HEAD (from the bundle or origin) on a full flush, revert
/// and delete what it lists, and place the sent files. `incoming` is gone after.
/// False, and nothing changed, when HEAD's commit could not be had: the bundle
/// needs history the checkout lacks, and there is no origin to fetch it from.
fn apply_manifest(checkout: &Path, incoming: &Path, m: &serde_json::Value) -> Result<bool> {
let head = m["head"].as_str().context("manifest without head")?;
let run = |args: &[&str]| -> Result<()> {
let out = Command::new("git").arg("-C").arg(&checkout).args(args).output()?;
if !out.status.success() {
bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
}
Ok(())
};
if m["full"] == true {
let have = Command::new("git").arg("-C").arg(&checkout)
.args(["cat-file", "-e", &format!("{head}^{{commit}}")])
.stderr(Stdio::null()).status()?.success();
if !have {
let bundle = incoming.join(".midas-bundle");
let origin = Command::new("git").arg("-C").arg(&checkout).args(["remote", "get-url", "origin"])
.stdout(Stdio::null()).stderr(Stdio::null()).status()?.success();
if bundle.exists() {
// The bundle holds only what origin lacks; its prerequisites are
// origin's commits, which the checkout may not have fetched yet.
if origin {
let _ = run(&["fetch", "--quiet", "origin"]);
}
let fetched = run(&["fetch", "--quiet", &bundle.to_string_lossy(), "HEAD:refs/midas/head"])
.or_else(|_| run(&["fetch", "--quiet", &bundle.to_string_lossy()]));
if fetched.is_err() && !origin {
return Ok(false);
}
fetched?;
}
let still = Command::new("git").arg("-C").arg(&checkout)
.args(["cat-file", "-e", &format!("{head}^{{commit}}")])
.stderr(Stdio::null()).status()?.success();
if !still {
if !origin {
return Ok(false);
}
run(&["fetch", "--quiet", "origin"])?;
}
}
run(&["checkout", "--quiet", "--force", "--detach", head])?;
// The build directory survives (that is what keeps a node warm), and so
// does midas's own state beside it, and a JS project's node_modules.
run(&["clean", "-qfdx", "-e", "/target", "-e", "/.midas*", "-e", "node_modules"])?;
}
// Files that went back to clean: HEAD's version if tracked, gone if not.
for p in m["revert"].as_array().into_iter().flatten().filter_map(|v| v.as_str()) {
let tracked = Command::new("git").arg("-C").arg(&checkout)
.args(["cat-file", "-e", &format!("HEAD:{p}")]).stderr(Stdio::null()).status()?.success();
if tracked {
run(&["checkout", "--quiet", "HEAD", "--", p])?;
} else {
let _ = fs::remove_file(checkout.join(p));
}
}
for p in m["delete"].as_array().into_iter().flatten().filter_map(|v| v.as_str()) {
let _ = fs::remove_file(checkout.join(p));
}
// The sent files, moved over the checkout.
let _ = fs::remove_file(incoming.join(".midas-manifest.json"));
let _ = fs::remove_file(incoming.join(".midas-bundle"));
let copied = Command::new("cp").arg("-a").arg(format!("{}/.", incoming.display())).arg(checkout)
.status()?.success();
let _ = fs::remove_dir_all(incoming);
if !copied {
bail!("could not place the sent files in the checkout");
}
Ok(true)
}
/// `midas holds <node>`: exit 0 if the worktree this runs in holds the node (or
/// its landing gate does). ssh asks it before every connection to a node
/// (`Match … !exec "midas holds %n"` in the generated config), so a session
/// that does not hold the node is refused there, with the reason, instead of
/// landing in somebody else's checkout — the node itself cannot tell sessions
/// of one container apart (DESIGN.md §6). `MIDAS_SSH_ANYWAY=1` overrides it.
/// `Match … !exec "midas holds %n"`: refuse a node this worktree does not
/// hold, and bring one it does hold up to date with it (the flush) — one
/// question to the hub for both, where a separate `midas flush %n` asked again.
pub fn holds(node: &str) -> Result<i32> {
if std::env::var_os("MIDAS_FLUSHING").is_some() {
return Ok(0);
}
if std::env::var_os("MIDAS_SSH_ANYWAY").is_some() {
run_flush(node, None);
return Ok(0);
}
let Ok(top) = git(Path::new("."), &["rev-parse", "--show-toplevel"]) else {
// Outside any worktree (`cd /tmp && scp node:/tmp/x.png .`, the usual
// way to fetch a capture), the session is still known by MIDAS_OWNER:
// connect when it holds the node, only without sending any files.
if let Some(owner) = std::env::var("MIDAS_OWNER").ok().map(|o| o.trim().to_string()).filter(|o| !o.is_empty()) {
if let Ok(Some((h, _))) = crate::client::lease(node) {
if h == owner || h == format!("gate-{owner}") {
return Ok(0);
}
}
}
eprintln!("midas: {node} is used from a worktree that holds it (midas take); this is not a git worktree. \
MIDAS_SSH_ANYWAY=1 to connect anyway.");
return Ok(1);
};
let owner = worktree_owner(Path::new(top.trim()));
// Fails open when the hub cannot be asked: the node itself still checks the
// lease, and a hub outage must not stop every build.
let lease = match lease_and_notes(node, &owner) {
Ok(l) => l,
Err(e) => {
eprintln!("midas: could not ask the hub who holds {node} ({e:#}); connecting");
return Ok(0);
}
};
match lease.as_ref().map(|(o, _)| o.clone()) {
Some(h) if h == owner || h == format!("gate-{owner}") => {
if run_flush(node, Some(lease)) || std::env::var("MIDAS_SYNC").is_ok_and(|v| v == "stale") {
return Ok(0);
}
// A build or a test on the files the node had before would pass or
// fail for code this worktree no longer has, and look like a result.
eprintln!("midas: not connecting to {node}: it does not have this worktree's files (above). Try \
again; MIDAS_SYNC=stale connects to it as it is.");
events::emit("ssh_blocked", json!({"node": node, "actor": owner, "holder": h, "sync_failed": true}));
Ok(1)
}
Some(h) if crate::collab::subagent_worktree(Path::new(top.trim())) => {
eprintln!("midas: {node} is held by {h}; this is a Claude Code subagent's own worktree ({owner}), which \
the node does not follow — not connecting. Give the build back to the session that started \
you: it runs `ssh {node} …` from its own worktree.");
events::emit("ssh_blocked", json!({"node": node, "actor": owner, "holder": h, "subagent": true}));
Ok(1)
}
Some(h) => {
eprintln!("midas: {node} is held by {h}, not by this worktree ({owner}) — not connecting. \
`midas take` gets you a node of your own; MIDAS_SSH_ANYWAY=1 connects anyway.");
events::emit("ssh_blocked", json!({"node": node, "actor": owner, "holder": h}));
Ok(1)
}
None => {
eprintln!("midas: {node} is not leased — `midas take` first (MIDAS_SSH_ANYWAY=1 connects anyway).");
Ok(1)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sh(dir: &Path, script: &str) {
let out = Command::new("sh").arg("-c").arg(script).current_dir(dir)
.env("GIT_AUTHOR_NAME", "t").env("GIT_AUTHOR_EMAIL", "t@t").env("GIT_COMMITTER_NAME", "t").env("GIT_COMMITTER_EMAIL", "t@t")
.env("GIT_CONFIG_GLOBAL", "/dev/null").env("GIT_CONFIG_NOSYSTEM", "1")
.output().unwrap();
assert!(out.status.success(), "{script}: {}", String::from_utf8_lossy(&out.stderr));
}
/// Every file but git's own, with its content.
fn tree(dir: &Path) -> BTreeMap<String, String> {
let mut m = BTreeMap::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
for e in fs::read_dir(&d).unwrap().flatten() {
let p = e.path();
if e.file_name() == ".git" {
continue;
}
if p.is_dir() {
stack.push(p);
} else {
m.insert(p.strip_prefix(dir).unwrap().display().to_string(), fs::read_to_string(&p).unwrap_or_default());
}
}
}
m
}
/// One flush from the worktree to the node's checkout, as flush_inner and
/// `midas node apply` do it, with the ssh between them replaced by a file.
fn flush_once(work: &Path, node: &Path, scratch: &Path, prev: &State, lease: i64) -> State {
// As flush_inner: once more with the whole history when the node lacks some.
flush_try(work, node, scratch, prev, lease, false).unwrap_or_else(|| flush_try(work, node, scratch, prev, lease, true).expect("the whole history"))
}
/// One send and apply; None when the node answered that it lacks history.
fn flush_try(work: &Path, node: &Path, scratch: &Path, prev: &State, lease: i64, whole: bool) -> Option<State> {
let head = git(work, &["rev-parse", "HEAD"]).unwrap().trim().to_string();
let now_files = uncommitted(work).unwrap();
let full = prev.lease != lease || prev.head != head;
let (send, delete, revert) = changes(prev, &now_files, full);
let out = scratch.join("out");
let _ = fs::remove_dir_all(&out);
fs::create_dir_all(&out).unwrap();
if full {
bundle(work, &head, &out, whole).unwrap();
}
let manifest = json!({"head": head, "full": full, "delete": delete, "revert": revert, "owner": "wt", "lease": lease});
fs::write(out.join(".midas-manifest.json"), manifest.to_string()).unwrap();
let tar = scratch.join("flush.tar");
let ok = pack(work, &out, &send).unwrap().stdout(fs::File::create(&tar).unwrap()).status().unwrap().success();
assert!(ok, "tar");
// The node's side.
let incoming = scratch.join("incoming");
let _ = fs::remove_dir_all(&incoming);
fs::create_dir_all(&incoming).unwrap();
assert!(Command::new("tar").arg("-xf").arg(&tar).arg("-C").arg(&incoming).status().unwrap().success());
let m: serde_json::Value = serde_json::from_str(&fs::read_to_string(incoming.join(".midas-manifest.json")).unwrap()).unwrap();
apply_manifest(node, &incoming, &m).unwrap().then(|| State { lease, head, repo: String::new(), files: now_files })
}
#[test]
fn a_worktrees_repository_is_the_last_two_segments_of_its_origin() {
assert_eq!(repo_of_url("ssh://git@code.example:2222/acme/midas.git").as_deref(), Some("acme/midas"));
assert_eq!(repo_of_url("hub:acme/cartopolis.git").as_deref(), Some("acme/cartopolis"));
assert_eq!(repo_of_url("git@host:owner/name").as_deref(), Some("owner/name"));
assert_eq!(repo_of_url("https://host/a/b/"), Some("a/b".into()));
assert_eq!(repo_of_url("nonsense"), None);
}
#[test]
fn a_repository_the_hub_does_not_mirror_arrives_whole_then_in_parts() {
let root = std::env::temp_dir().join(format!("midas-flush-unmirrored-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
let (work, node, scratch) = (root.join("work"), root.join("node"), root.join("scratch"));
fs::create_dir_all(&scratch).unwrap();
sh(&root, "git init -q --bare -b main origin.git && git clone -q origin.git work 2>/dev/null");
sh(&work, "echo a > a.txt && git add . && git commit -qm one && git push -q origin HEAD:main");
// The node's checkout of it: empty, with no origin to fetch from.
ensure_checkout(&node).unwrap();
let mut st = flush_try(&work, &node, &scratch, &State::default(), 1, false);
assert!(st.is_none(), "pushed, so not bundled: the node says it lacks the commit");
st = flush_try(&work, &node, &scratch, &State::default(), 1, true);
assert_eq!(tree(&node).get("a.txt").map(String::as_str), Some("a\n"));
// A pushed commit on top: the node has the one before, but not this one.
sh(&work, "echo b > a.txt && git commit -qam two && git push -q origin HEAD:main");
let st = flush_once(&work, &node, &scratch, &st.unwrap(), 1);
assert_eq!(tree(&node).get("a.txt").map(String::as_str), Some("b\n"));
// An unpushed one: its bundle is enough.
sh(&work, "echo c > a.txt && git commit -qam three");
assert!(flush_try(&work, &node, &scratch, &st, 1, false).is_some());
assert_eq!(tree(&node).get("a.txt").map(String::as_str), Some("c\n"));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn another_repository_gets_a_checkout_of_its_own_beside_the_nodes() {
let root = std::env::temp_dir().join(format!("midas-flush-repos-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
sh(&root, "git init -q checkout && git -C checkout remote add origin hub:acme/cartopolis.git");
let main = root.join("checkout");
assert_eq!(checkout_for(&main, "acme/cartopolis"), main, "the node's own repository");
assert_eq!(checkout_for(&main, ""), main, "an older agent names none");
assert_eq!(checkout_for(&main, "acme/midas"), root.join("repos/acme/midas"));
let _ = fs::remove_dir_all(&root);
}
// It packs with GNU tar, as the container that flushes does; macOS has bsdtar: Linux only, so a landing gated on a Mac node passes without it.
#[cfg(target_os = "linux")]
#[test]
fn a_nodes_checkout_follows_the_worktree_through_commits_edits_deletes_and_reverts() {
let root = std::env::temp_dir().join(format!("midas-flush-test-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
let (origin, work, node) = (root.join("origin.git"), root.join("work"), root.join("node"));
sh(&root, "git init -q --bare -b main origin.git && git clone -q origin.git work 2>/dev/null");
sh(&work, "mkdir dir && echo a > a.txt && echo b > b.txt && echo c > dir/c.txt && echo d > d.txt \
&& git add -A && git commit -qm one && git push -q origin HEAD:main");
sh(&root, "git clone -q origin.git node");
assert!(origin.exists());
// An unpushed commit (an edit and a delete), then uncommitted work on top:
// an edit, a new file, a deleted tracked file.
sh(&work, "echo a2 > a.txt && git rm -q b.txt && git commit -qm two \
&& echo c2 > dir/c.txt && echo new > new.txt && rm d.txt");
let st = flush_once(&work, &node, &root, &State::default(), 1);
assert_eq!(tree(&node), tree(&work), "a full flush: the bundle's commit, then the uncommitted files");
assert!(!node.join("d.txt").exists() && node.join("new.txt").exists());
// Back to clean, a new file gone, another edit: only what changed travels.
sh(&work, "git checkout -q -- dir/c.txt d.txt && rm new.txt && echo a3 > a.txt");
let st = flush_once(&work, &node, &root, &st, 1);
assert_eq!(tree(&node), tree(&work), "reverted, removed and edited");
assert_eq!(fs::read_to_string(node.join("dir/c.txt")).unwrap(), "c\n", "a revert is HEAD's version");
// Nothing changed: nothing to send.
let now_files = uncommitted(&work).unwrap();
let (send, delete, revert) = changes(&st, &now_files, false);
assert!(send.is_empty() && delete.is_empty() && revert.is_empty());
let _ = fs::remove_dir_all(&root);
}
}