git clone https://garage44.eu/jeroen/midas.gitcartopolis-agent · 2026-11-28T19:03:30Z
feat(hosted): rename and delete a project the hub hosts s896 made jeroen/flits, then the browser became flitz; with no way to rename, jeroen/flitz was made beside it and the empty flits stayed. Rename (`midas project rename`, MCP project_rename, the page's project Settings) moves the bare repository, its record and landing, and rewrites every session meta, goal and note set that names it. The old name stays an alias (hosted.json `renamed`) that git over ssh, LFS and project_add resolve, so worktrees, nodes and clones made before keep working without being touched; runners move their own checkout to the new name at their next poll (worktree repair, origin set-url), and project_worktree finds a session's worktree by origin, since its folder keeps the old name under an agent that may be in it. Renaming a directory under a live agent was the alternative, and rejected. Delete is the person's only (an admin on the page; a key is refused and told to ask). It moves the repository aside to state/deleted-git rather than removing it, so a mistaken yes can still be undone by hand. Both refuse a name hub.conf gives: that file is root's, and the hub runs as midas, so it cannot change it.
docs/git-hosting.md | 3 +-
docs/hub.md | 24 ++++++
docs/usage.md | 2 +
src/cli.rs | 2 +
src/hosted.rs | 170 ++++++++++++++++++++++++++++++++++++++
src/hub.rs | 21 +++++
src/main.rs | 10 +++
src/mcp.rs | 6 ++
src/memory.rs | 11 +++
src/mirror.rs | 12 ++-
src/sessions.rs | 58 ++++++++++++-
src/tests.rs | 84 +++++++++++++++++++
src/tree.rs | 11 +++
web/src/components/projectmap.tsx | 51 ++++++++++--
web/src/lib/api.ts | 4 +
15 files changed, 457 insertions(+), 12 deletions(-)
diff --git a/docs/git-hosting.md b/docs/git-hosting.md
index ed8ff1e..00a1f14 100644
--- a/docs/git-hosting.md
+++ b/docs/git-hosting.md
@@ -11,7 +11,8 @@ from disk; every branch and tag checked identical, 639 LFS objects, none
missing). Port 2222 is the hub's sshd and code.garage44.eu its proxy, so no URL
changed. Forgejo and its runner are stopped and disabled, their data kept in
`/var/lib/forgejo`; the nightly CI and mithril's test workflow went with them.
-What is below past step 1 is the design as it was proposed; reports from
+Renaming and deleting a hosted project were built 2026-11-28 (s899, docs/hub.md):
+an agent renames, the person deletes on the page. What is below past step 1 is the design as it was proposed; reports from
outside, the reads without a checkout and branch hygiene are not built.
midas hosts the workspace's repositories itself, and Forgejo goes. midas does not
diff --git a/docs/hub.md b/docs/hub.md
index c43d247..9428a0d 100644
--- a/docs/hub.md
+++ b/docs/hub.md
@@ -280,6 +280,30 @@ sudo -u midas midas hub git-key list
LFS objects are uploaded to the hub, which keeps them in `/srv/midas/lfs`. That
directory is the store for a hosted repository, not a cache.
+**Renaming one** is `midas project rename <owner>/<name> <new>` (MCP
+`project_rename`; any caller key, or an admin on the page's project ▸
+Settings). The bare repository moves to the new name with its record and
+landing, and every session meta, goal and note set that names the project says
+the new name. The old name stays an alias in hosted.json `renamed`: a fetch,
+push or LFS request for it over ssh reaches the new repository, so checkouts
+need nothing, and a session's `project_add` of the old name gets the new one.
+Each runner moves its checkout (`repos/<owner>/<old>` → `<new>`, `git worktree
+repair`, `origin` set to the new URL) at its next poll; a session's worktree
+keeps its folder's name. Nodes check the new name out afresh. Public pages and
+HTTPS clones answer only at the new name. A name hub.conf gives (a project
+from its Forgejo days, or one with deploys) is refused: hub.conf is root's, so
+rename it there first.
+
+**Deleting one is the person's**: an admin on the page (project ▸ Settings ▸
+Delete, after a confirm). A caller key, `midas project delete` included, is
+refused and told to ask. The repository is moved aside to
+`/srv/midas/state/deleted-git/<owner>/<name>-<unix time>.git`, out of every
+list and serving, with its record in hosted.json `deleted`; sessions and goals
+stop listing it, and its old names stop leading anywhere. Its LFS objects stay
+in the store. To put it back, move the directory to `git/<owner>/<name>.git`
+and its record back into `repos` (as the hub's user); to remove it for good,
+`rm -rf` the directory.
+
**A public project** (`--public`; making a private one public later takes the
person's admin login) is readable by anyone at `/<owner>/<name>`, the paths
Forgejo had, so old links, `Cargo.toml`'s `git =` and `package.json`'s tarballs
diff --git a/docs/usage.md b/docs/usage.md
index 66eab7e..33b5776 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -121,6 +121,8 @@ midas bot stop # stop it and give the node back (midas release does
midas project # what this project gates on (hub.conf `projects`)
midas project create <name> [--public] [--gate "…"] [--description "…"] # a new project the hub hosts
midas project set <owner/name> --gate "…" # change a hosted project's landing (--public is the person's)
+midas project rename <owner/name> <new> # another name; the old one still clones and pushes
+midas project delete <owner/name> # the person's, on the page: a key is told to ask
midas project show <owner/name> [path] # read a hosted project without a checkout; `log` for its commits
midas land status # who is landing, who is next (`midas status` too)
midas land targets [--pick +wasm] # which deploy targets this branch's landing builds
diff --git a/src/cli.rs b/src/cli.rs
index 58d2f8b..b255619 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -875,6 +875,8 @@ pub fn project_act(a: crate::ProjectCmd, owner: &str) -> Result<i32> {
}
client::post("/v1/projects/set", &b)?
}
+ P::Rename { repo, to } => client::post("/v1/projects/rename", &json!({"owner": owner, "repo": repo_path(&repo)?, "to": to}))?,
+ P::Delete { repo } => client::post("/v1/projects/delete", &json!({"owner": owner, "repo": repo_path(&repo)?}))?,
P::Show { repo, path, rev } => {
let v = client::get(&format!("/v1/repos/{}/show?path={}{}", repo_path(&repo)?, enc(&path),
rev.map(|r| format!("&rev={}", enc(&r))).unwrap_or_default()))?;
diff --git a/src/hosted.rs b/src/hosted.rs
index c32f1c5..9ec3433 100644
--- a/src/hosted.rs
+++ b/src/hosted.rs
@@ -146,6 +146,10 @@ pub fn create(n: &New) -> Result<Value> {
});
update(|v| {
v["repos"][&k] = record.clone();
+ // An old name of a renamed project, taken for a new one: it leads here now.
+ if let Some(r) = v["renamed"].as_object_mut() {
+ r.remove(&k);
+ }
Ok(())
})?;
crate::events::emit("repo_created", json!({"repo": k, "actor": n.by, "visibility": record["visibility"]}));
@@ -351,6 +355,172 @@ pub fn set(repo: &str, fields: &Value, by: &str, by_person: bool) -> Result<Valu
Ok(out)
}
+// ── Renaming and deleting ────────────────────────────────────────────────────
+
+/// The name `repo` goes by now: itself, or the project it was renamed to
+/// (hosted.json `renamed`, old → new), so a clone, a worktree's origin or a
+/// node's checkout made under the old name keeps fetching and pushing. A
+/// project hosted under the name outranks an old name of another. `.git` is
+/// kept as given.
+pub fn current(repo: &str) -> String {
+ let k = key(repo);
+ let v = read();
+ if v["repos"].get(&k).is_some() {
+ return repo.to_string();
+ }
+ match v["renamed"][&k].as_str() {
+ Some(now) if repo.ends_with(".git") => format!("{now}.git"),
+ Some(now) => now.to_string(),
+ None => repo.to_string(),
+ }
+}
+
+/// Every old name that still leads somewhere: (old, new).
+pub fn renames() -> Vec<(String, String)> {
+ read()["renamed"].as_object().into_iter().flatten()
+ .filter_map(|(o, n)| Some((o.clone(), n.as_str()?.to_string()))).collect()
+}
+
+/// A name hub.conf itself gives `k` (a project from its Forgejo days, or one
+/// with deploys): hub.conf is root's, which the hub's user does not write.
+fn named_by_hub_conf(k: &str) -> Result<bool> {
+ let c = crate::conf::read(Path::new(&conf_path()))?.unwrap_or_default();
+ Ok(c.repos.iter().any(|r| key(r) == k) || c.projects.keys().any(|r| key(r) == k))
+}
+
+/// `repo` under the name `to` (`name`, or `owner/name` for another owner):
+/// its bare repository moved, its record and landing with it, and every
+/// session, goal and note set that names it changed to say the new name. The
+/// old name stays an alias (`current`), so what was cloned from it goes on
+/// working; runners move their checkouts to the new name at their next poll
+/// (sessions.rs `follow_renames`). A project hub.conf names is refused: its
+/// entries are root's to change.
+pub fn rename(repo: &str, to: &str, by: &str) -> Result<Value> {
+ let from = key(&crate::mirror::repo_name(repo)?);
+ let owner = from.split('/').next().unwrap_or_default();
+ let to = to.trim();
+ let new = key(&crate::mirror::repo_name(&if to.contains('/') { to.to_string() } else { format!("{owner}/{to}") })?);
+ if !is_hosted(&from) {
+ bail!("{from} is not hosted here");
+ }
+ if new == from {
+ bail!("{from} is called that already");
+ }
+ if is_hosted(&new) || path(&new).exists() {
+ bail!("{new} is a project already");
+ }
+ for k in [&from, &new] {
+ if named_by_hub_conf(k)? {
+ bail!("hub.conf names {k}, which only root changes: rename it there first (sudo on the hub), then here");
+ }
+ }
+ fs::create_dir_all(path(&new).parent().unwrap())?;
+ fs::rename(path(&from), path(&new)).with_context(|| format!("moving {} to {}", path(&from).display(), path(&new).display()))?;
+ let moved = update(|v| {
+ store::objects(v, &["renamed"]);
+ let Some(mut r) = v["repos"].as_object_mut().and_then(|m| m.remove(&from)) else { bail!("{from} is not hosted here") };
+ let mut was: Vec<Value> = r["renamed_from"].as_array().cloned().unwrap_or_default();
+ was.push(json!({"name": from, "at": registry::now(), "by": by}));
+ r["renamed_from"] = json!(was);
+ v["repos"][&new] = r;
+ let renamed = v["renamed"].as_object_mut().expect("an object");
+ // The new name was this one's before (a rename undone): it is no alias any more.
+ renamed.remove(&new);
+ for n in renamed.values_mut() {
+ if n == from.as_str() {
+ *n = json!(new);
+ }
+ }
+ renamed.insert(from.clone(), json!(new));
+ Ok(())
+ });
+ if let Err(e) = moved {
+ let _ = fs::rename(path(&new), path(&from));
+ return Err(e);
+ }
+ let sessions = crate::sessions::repo_renamed(&from, Some(&new))?;
+ crate::tree::repo_renamed(&from, Some(&new))?;
+ crate::memory::rename_set(&from, &new)?;
+ crate::events::emit("repo_renamed", json!({"repo": new, "from": from, "actor": by, "sessions": sessions}));
+ Ok(json!({"repo": new, "from": from, "url": url(&new), "sessions": sessions, "public": is_public(&new)}))
+}
+
+/// Delete `repo`, which only the person does (`by_person`): it loses every
+/// branch nobody else has. Its bare repository is moved aside, out of every
+/// listing and serving (`deleted-git/<owner>/<name>-<when>.git` in the state
+/// directory), where the hub's user can put it back or remove it for good;
+/// its record goes to hosted.json `deleted`, and sessions and goals stop
+/// naming it. Its LFS objects stay in the store, which repositories share.
+pub fn delete(repo: &str, by: &str, by_person: bool) -> Result<Value> {
+ let k = key(&crate::mirror::repo_name(repo)?);
+ if !by_person {
+ bail!("deleting {k} loses what is only there: it is the person's to do. Ask them; they delete it on the page \
+ (Map ▸ {} ▸ Settings ▸ Delete)", k.rsplit('/').next().unwrap_or(&k));
+ }
+ if !is_hosted(&k) {
+ bail!("{k} is not hosted here");
+ }
+ if named_by_hub_conf(&k)? {
+ bail!("hub.conf names {k}, which only root changes: take it out there first (sudo on the hub), then delete it here");
+ }
+ let at = registry::now();
+ let kept = registry::root().join("deleted-git").join(format!("{k}-{at}.git"));
+ fs::create_dir_all(kept.parent().unwrap())?;
+ fs::rename(path(&k), &kept).with_context(|| format!("moving {} aside", path(&k).display()))?;
+ let head = git(&kept, &["rev-parse", "--verify", "--quiet", "HEAD"]).unwrap_or_default();
+ let moved = update(|v| {
+ store::objects(v, &["renamed", "deleted"]);
+ let Some(r) = v["repos"].as_object_mut().and_then(|m| m.remove(&k)) else { bail!("{k} is not hosted here") };
+ v["renamed"].as_object_mut().expect("an object").retain(|_, n| n != k.as_str());
+ v["deleted"][format!("{k}@{at}")] = json!({"repo": k, "at": at, "by": by, "kept": kept, "head": head, "record": r});
+ Ok(())
+ });
+ if let Err(e) = moved {
+ let _ = fs::rename(&kept, path(&k));
+ return Err(e);
+ }
+ let sessions = crate::sessions::repo_renamed(&k, None)?;
+ crate::tree::repo_renamed(&k, None)?;
+ crate::events::emit("repo_deleted", json!({"repo": k, "actor": by, "kept": kept, "head": head, "sessions": sessions}));
+ Ok(json!({"repo": k, "deleted": true, "kept": kept, "head": head, "sessions": sessions}))
+}
+
+/// `from` as `to` (or gone, with `None`) in a record of the hub's: every
+/// `repo` that names it, and every `repos` list. A deleted project's `repo`
+/// stays, as history of what a session worked in; it leaves the lists that
+/// say what one works in now. Whether anything changed.
+pub(crate) fn rename_in(v: &mut Value, from: &str, to: Option<&str>) -> bool {
+ let mut changed = false;
+ match v {
+ Value::Object(o) => {
+ for (k, x) in o.iter_mut() {
+ match (k.as_str(), &mut *x, to) {
+ ("repo", Value::String(s), Some(to)) if s == from => {
+ *s = to.to_string();
+ changed = true;
+ }
+ ("repos", Value::Array(a), _) if a.iter().any(|r| r == from) => {
+ match to {
+ Some(to) => a.iter_mut().filter(|r| *r == from).for_each(|r| *r = json!(to)),
+ None => a.retain(|r| r != from),
+ }
+ // Renamed onto one it had already: once.
+ let mut seen = std::collections::HashSet::new();
+ a.retain(|r| seen.insert(r.to_string()));
+ changed = true;
+ }
+ _ => changed |= rename_in(x, from, to),
+ }
+ }
+ }
+ Value::Array(a) => for x in a {
+ changed |= rename_in(x, from, to);
+ },
+ _ => {}
+ }
+ changed
+}
+
// ── Keys ─────────────────────────────────────────────────────────────────────
pub fn keys() -> Map<String, Value> {
diff --git a/src/hub.rs b/src/hub.rs
index 616a351..c0dd5d2 100644
--- a/src/hub.rs
+++ b/src/hub.rs
@@ -1366,6 +1366,27 @@ fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &st
Err(e) => (409, json!({"error": format!("{e:#}")})),
}
}
+ // Another name for a hosted project (hosted.rs `rename`): an admin's on the page, any caller key's.
+ ("POST", "projects/rename") => {
+ if p.account.is_some() && !crate::accounts::at_least(&p.role, "admin") {
+ return Ok((403, json!({"error": "renaming a project is an admin's"})));
+ }
+ match crate::hosted::rename(&s("repo").unwrap_or_default(), &s("to").unwrap_or_default(), &by) {
+ Ok(v) => (200, v),
+ Err(e) => (409, json!({"error": format!("{e:#}")})),
+ }
+ }
+ // Deleting one is the person's alone, an admin logged in on the page (hosted.rs `delete`).
+ ("POST", "projects/delete") => {
+ let by_person = p.account.is_some() && crate::accounts::at_least(&p.role, "admin");
+ if p.account.is_some() && !by_person {
+ return Ok((403, json!({"error": "deleting a project is an admin's"})));
+ }
+ match crate::hosted::delete(&s("repo").unwrap_or_default(), &by, by_person) {
+ Ok(v) => (200, v),
+ Err(e) => (409, json!({"error": format!("{e:#}")})),
+ }
+ }
("POST", "nodes/remove") => { registry::remove_node(&s("id").unwrap_or_default())?; crate::hubsetup::refresh_ssh()?; ok }
("POST", "deploy") => {
let target = s("target").unwrap_or_default();
diff --git a/src/main.rs b/src/main.rs
index 6f5ae5b..9e9c2c9 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1290,6 +1290,16 @@ pub enum ProjectCmd {
#[arg(long)]
private: bool,
},
+ /// Give a hosted project another name: its repository, landing, sessions,
+ /// goals and notes move with it, and the old name still clones and pushes.
+ Rename {
+ repo: String,
+ /// The new name (or `owner/name`).
+ to: String,
+ },
+ /// Delete a hosted project: the person's, who does it on the page (Map ▸
+ /// project ▸ Settings); a key is refused and told so.
+ Delete { repo: String },
/// A file or directory of a hosted project, without a checkout.
Show {
repo: String,
diff --git a/src/mcp.rs b/src/mcp.rs
index f3e867e..e90810d 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -210,6 +210,8 @@ fn tools() -> Vec<Value> {
tool("project_set", "Change a project the hub hosts: its gate, gate nodes, pre-land check or description (an empty string unsets). public: false makes it private; true is the person's to do.",
json!({"repo": s("owner/name"), "gate": s(""), "gate_nodes": s(""), "pre_land": s(""), "description": s(""),
"public": json!({"type": "boolean"})}), &["repo"]),
+ tool("project_rename", "Give a project the hub hosts another name (a project renamed during its work, as flits to flitz): its repository, landing, sessions, goals and notes move to it, and the old name still clones and pushes, so checkouts need nothing. Runners move their checkouts; worktrees keep their folder's name. Deleting a project is the person's: they do it on the page (Map ▸ project ▸ Settings ▸ Delete), so ask them (session_await) rather than making a second one beside it.",
+ json!({"repo": s("owner/name"), "to": s("the new name (or owner/name)")}), &["repo", "to"]),
tool("project_read", "Read a project the hub hosts without a checkout: a file or directory (what: show, with path and rev), its last commits (log), its branches, or one commit with its diff (commit, rev = sha).",
json!({"repo": s("owner/name"), "what": s("show, log, branches or commit"), "path": s("for show"), "rev": s("a branch, tag or sha")}), &["repo", "what"]),
tool("workspace_check","Is the workspace healthy? The hub, registry permissions, every node's heartbeat, disk, build-directory size and warmth, this container's ssh config, Forgejo through the hub, and the last day's failures.", json!({}), &[]),
@@ -303,6 +305,10 @@ fn call(name: &str, a: &Value) -> Result<String> {
}
crate::client::post("/v1/projects/set", &b).map(|v| v.to_string())
}
+ "project_rename" => crate::client::post("/v1/projects/rename", &json!({
+ "owner": crate::client::setting("MIDAS_OWNER").unwrap_or_default(),
+ "repo": arg(a, "repo").context("repo is required")?, "to": arg(a, "to").context("to is required")?,
+ })).map(|v| v.to_string()),
"project_read" => {
let repo = crate::mirror::repo_name(arg(a, "repo").context("repo is required")?)?;
let what = arg(a, "what").unwrap_or("show");
diff --git a/src/memory.rs b/src/memory.rs
index f46ab4c..338a111 100644
--- a/src/memory.rs
+++ b/src/memory.rs
@@ -79,6 +79,17 @@ fn set_path(repo: Option<&str>) -> Result<PathBuf> {
Ok(crate::registry::root().join("memory").join(format!("{name}.json")))
}
+/// A renamed project's notes, under its new name (hosted.rs `rename`). A set the
+/// new name has already (notes kept from a project once called so) stays, and the
+/// old one beside it.
+pub(crate) fn rename_set(from: &str, to: &str) -> Result<()> {
+ let (old, new) = (set_path(Some(from))?, set_path(Some(to))?);
+ if old.exists() && !new.exists() {
+ std::fs::rename(&old, &new)?;
+ }
+ Ok(())
+}
+
fn read_set(repo: Option<&str>) -> Result<Notes> {
Ok(store::read(&set_path(repo)?).unwrap_or_default())
}
diff --git a/src/mirror.rs b/src/mirror.rs
index 7a7eeda..e39b278 100644
--- a/src/mirror.rs
+++ b/src/mirror.rs
@@ -160,10 +160,10 @@ enum GitAsk {
fn git_ask(cmd: &str) -> Result<GitAsk> {
let (verb, rest) = cmd.split_once(' ').unwrap_or((cmd, ""));
Ok(match verb {
- "git-upload-pack" => GitAsk::Fetch(repo_name(rest)?),
+ "git-upload-pack" => GitAsk::Fetch(named(rest)?),
"git-lfs-authenticate" => {
let mut words = rest.split_whitespace();
- let repo = repo_name(words.next().unwrap_or(""))?;
+ let repo = named(words.next().unwrap_or(""))?;
GitAsk::Lfs(repo, words.next().unwrap_or("download").to_string())
}
"git-lfs-transfer" => GitAsk::Transfer,
@@ -172,6 +172,12 @@ fn git_ask(cmd: &str) -> Result<GitAsk> {
})
}
+/// The repository `raw` names, by the name it goes by now: a renamed project's
+/// old name leads to it (hosted.rs `current`), for what was cloned before.
+fn named(raw: &str) -> Result<String> {
+ Ok(crate::hosted::current(&repo_name(raw)?))
+}
+
/// The hub's `authorized_keys` command for nodes.
pub fn serve_git(node: &str) -> Result<i32> {
let cmd = std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default();
@@ -239,7 +245,7 @@ pub fn serve_key(name: &str) -> Result<i32> {
}
GitAsk::Push => {
let (_, rest) = cmd.split_once(' ').unwrap_or((&cmd, ""));
- let repo = repo_name(rest)?;
+ let repo = named(rest)?;
if !crate::hosted::is_hosted(&repo) {
bail!("{repo} is on Forgejo: push it there (only repositories the hub hosts take pushes here)");
}
diff --git a/src/sessions.rs b/src/sessions.rs
index de799e4..d258b06 100644
--- a/src/sessions.rs
+++ b/src/sessions.rs
@@ -625,7 +625,8 @@ fn project_in(names: &[String], repo: Option<&str>) -> Result<Option<String>> {
if let Some(n) = names.iter().find(|n| !r.contains('/') && n.rsplit('/').next() == Some(r)) {
return Ok(Some(n.clone()));
}
- let r = crate::mirror::repo_name(r)?.trim_end_matches(".git").to_string();
+ // A renamed project's old name, from a checkout cloned before (hosted.rs `current`).
+ let r = crate::hosted::current(crate::mirror::repo_name(r)?.trim_end_matches(".git"));
if !names.contains(&r) {
bail!("{r} is not one of the workspace's projects ({}): add it to the hub's repos (midas hub setup --repo …)", names.join(", "));
}
@@ -699,6 +700,21 @@ fn take_project(m: &mut Value, repo: &str) -> Option<bool> {
free.then_some(true)
}
+/// Project `from` renamed to `to`, or deleted (`None`), in every session's meta
+/// (hosted.rs `rename_in`): the sessions it changed.
+pub(crate) fn repo_renamed(from: &str, to: Option<&str>) -> Result<Vec<String>> {
+ let _l = lock()?;
+ let mut changed = vec![];
+ for id in fs::read_dir(root()).into_iter().flatten().flatten().filter_map(|e| e.file_name().to_str().filter(|n| id_ok(n)).map(str::to_string)) {
+ let Ok(mut m) = meta(&id) else { continue };
+ if crate::hosted::rename_in(&mut m, from, to) {
+ write_meta(&id, &m)?;
+ changed.push(id);
+ }
+ }
+ Ok(changed)
+}
+
/// Every session, newest first.
pub fn list() -> Value {
let mut v: Vec<Value> = fs::read_dir(root()).into_iter().flatten().flatten()
@@ -1846,7 +1862,11 @@ pub fn poll_with(runner: &str, have: &Value, take: bool, can: &[&str]) -> Result
let scouts = if take && can.contains(&"scout") { crate::tree::rounds_take() } else { Vec::new() };
if !start.is_empty() || !inputs.is_empty() || !bots.is_empty() || !asks.is_empty() || !reviews.is_empty() || !scouts.is_empty() || Instant::now() >= until {
let gone: Vec<Value> = deleted().iter().map(|g| g["id"].clone()).collect();
- return Ok(json!({"start": start, "inputs": inputs, "deleted": gone, "bots": bots, "asks": asks, "reviews": reviews, "scouts": scouts}));
+ // Projects renamed (hosted.rs): the runner moves its checkouts of them (`follow_renames`).
+ let renamed: Vec<Value> = crate::hosted::renames().into_iter()
+ .map(|(from, to)| json!({"from": from, "git": crate::hosted::url(&to), "to": to})).collect();
+ return Ok(json!({"start": start, "inputs": inputs, "deleted": gone, "bots": bots, "asks": asks, "reviews": reviews, "scouts": scouts,
+ "renamed": renamed}));
}
// Until something arrives (a message, a start, a session queued again, a bot asked for),
// or a few seconds for what does not say so: a start given before and never taken up.
@@ -3338,7 +3358,8 @@ fn folder(home: &Path, m: &Value) -> Result<PathBuf> {
fn project_worktree(home: &Path, dir: &Path, id: &str, repo: &str, base: &str) -> Result<(PathBuf, String)> {
let _one = one_at_a_time(home)?;
let name = repo.rsplit('/').next().unwrap_or(repo);
- let mut work = dir.join(name);
+ // One made before its project was renamed is at the old name (`follow_renames`).
+ let mut work = folder_worktrees(dir).into_iter().find(|(r, _)| r == repo).map_or_else(|| dir.join(name), |(_, p)| p);
if work.exists() && crate::cli::repo_in(&work).as_deref() != Some(repo) {
work = dir.join(repo.replace('/', "-"));
}
@@ -4122,6 +4143,7 @@ pub fn runner() -> Result<i32> {
// A session whose thread has ended hears nothing more.
runs.retain(|_, (tx, _)| tx.send(Ev::Input(json!({"kind": "ping"}))).is_ok());
crate::runners::SESSIONS.store(runs.len(), std::sync::atomic::Ordering::SeqCst);
+ follow_renames(&sessions_home().expect("checked at the start"), &v["renamed"]);
// Deleted on the page: its worktree goes; its branch stays, with the work.
for id in v["deleted"].as_array().into_iter().flatten().filter_map(Value::as_str) {
if let Some(work) = worktree_of(id).filter(|w| w.exists()) {
@@ -4136,6 +4158,36 @@ pub fn runner() -> Result<i32> {
}
}
+/// The runner's checkouts of projects renamed at the hub (`renamed`: from, to,
+/// git), under their new names: the checkout moved to `repos/<to>`, its
+/// worktrees told where it went (`git worktree repair`), and its `origin` set
+/// to the new URL, which every worktree of it shares. A session's worktree
+/// keeps its folder's name (`./<old>`) under an agent that may be in it;
+/// `project_worktree` finds it there by its origin. Done once: a checkout at
+/// the new name already is left as it is.
+pub(crate) fn follow_renames(home: &Path, renamed: &Value) {
+ for r in renamed.as_array().into_iter().flatten() {
+ let (Some(from), Some(to), Some(git)) = (r["from"].as_str(), r["to"].as_str(), r["git"].as_str()) else { continue };
+ let (Ok(f), Ok(t)) = (crate::mirror::repo_name(from), crate::mirror::repo_name(to)) else { continue };
+ let (old, new) = (home.join("repos").join(f.trim_end_matches(".git")), home.join("repos").join(t.trim_end_matches(".git")));
+ if !old.join(".git").exists() || new.exists() {
+ continue;
+ }
+ let moved = (|| -> Result<()> {
+ let _one = one_at_a_time(home)?;
+ fs::create_dir_all(new.parent().expect("under repos"))?;
+ fs::rename(&old, &new)?;
+ crate::util::git(&new, &["worktree", "repair"])?;
+ crate::util::git(&new, &["remote", "set-url", "origin", git])?;
+ Ok(())
+ })();
+ match moved {
+ Ok(()) => eprintln!("{from} is {to} now: its checkout moved to {}", new.display()),
+ Err(e) => eprintln!("{from} is {to} now; moving its checkout: {e:#}"),
+ }
+ }
+}
+
/// The binary the runner started from, to see a deploy replace it.
pub(crate) struct Build {
pub(crate) path: PathBuf,
diff --git a/src/tests.rs b/src/tests.rs
index 1cc58da..4a5c4ef 100644
--- a/src/tests.rs
+++ b/src/tests.rs
@@ -3178,3 +3178,87 @@ fn a_session_started_from_a_session_remembers_it() {
sessions::set_from(&parent, "s99999").unwrap();
assert!(sessions::meta(&parent).unwrap()["from"].is_null());
}
+
+#[test]
+fn a_renamed_project_moves_with_its_sessions_and_its_old_name_still_leads_to_it() {
+ let _g = SERIAL.lock().unwrap();
+ scratch("hosted-rename");
+ new_project("flits", false);
+ new_project("other", false);
+ let state = registry::root();
+ let meta = |id: &str, m: Value| {
+ std::fs::create_dir_all(state.join("hosted").join(id)).unwrap();
+ std::fs::write(state.join("hosted").join(id).join("meta.json"), m.to_string()).unwrap();
+ };
+ meta("s1", json!({"id": "s1", "repo": "acme/other", "repos": ["acme/other", "acme/flits"], "layout": "folder"}));
+ meta("s2", json!({"id": "s2", "repo": "acme/other"}));
+ std::fs::create_dir_all(state.join("memory")).unwrap();
+ std::fs::write(state.join("memory/acme--flits.json"), "{}").unwrap();
+
+ assert!(crate::hosted::rename("acme/flits", "other", "t").unwrap_err().to_string().contains("a project already"));
+ assert!(crate::hosted::rename("acme/flits", "../x", "t").is_err(), "a name does not walk out");
+ let v = crate::hosted::rename("acme/flits", "flitz", "agent:s1").unwrap();
+ assert_eq!((v["repo"].as_str(), v["sessions"].clone()), (Some("acme/flitz"), json!(["s1"])));
+ assert!(crate::hosted::path("acme/flitz").join("HEAD").exists() && !crate::hosted::path("acme/flits").exists());
+ assert_eq!(crate::hosted::get("acme/flitz").unwrap()["renamed_from"][0]["name"], "acme/flits");
+ assert!(state.join("memory/acme--flitz.json").exists(), "its notes go with it");
+ let s1 = crate::sessions::meta("s1").unwrap();
+ assert_eq!(s1["repos"], json!(["acme/other", "acme/flitz"]));
+ // The old name, from a checkout made before: it leads to the new one.
+ assert_eq!(crate::hosted::current("acme/flits.git"), "acme/flitz.git");
+ assert_eq!(crate::mirror::mirror_path(&crate::hosted::current("acme/flits.git")), crate::hosted::path("acme/flitz"));
+ assert!(crate::conf::hub().allows("acme/flitz.git") && !crate::conf::hub().allows("acme/flits.git"));
+ // Renamed again, and back: no chain, no alias of a name in use.
+ crate::hosted::rename("acme/flitz", "blitz", "t").unwrap();
+ assert_eq!(crate::hosted::current("acme/flits"), "acme/blitz");
+ crate::hosted::rename("acme/blitz", "flits", "t").unwrap();
+ assert_eq!(crate::hosted::current("acme/flits"), "acme/flits");
+ let mut r = crate::hosted::renames();
+ r.sort();
+ assert_eq!(r, [("acme/blitz".to_string(), "acme/flits".to_string()), ("acme/flitz".to_string(), "acme/flits".to_string())]);
+
+ // Deleting is the person's; it goes aside, out of every list.
+ assert!(crate::hosted::delete("acme/flits", "agent:s1", false).unwrap_err().to_string().contains("the person's"));
+ let d = crate::hosted::delete("acme/flits", "web:person", true).unwrap();
+ let kept = std::path::PathBuf::from(d["kept"].as_str().unwrap());
+ assert!(kept.join("HEAD").exists() && !crate::hosted::path("acme/flits").exists(), "moved aside, not lost");
+ assert!(!crate::hosted::is_hosted("acme/flits") && !crate::conf::hub().allows("acme/flits.git"));
+ assert!(crate::hosted::renames().is_empty(), "no old name leads to a deleted one");
+ let s1 = crate::sessions::meta("s1").unwrap();
+ assert_eq!((s1["repos"].clone(), s1["repo"].as_str()), (json!(["acme/other"]), Some("acme/other")));
+ assert!(crate::hosted::delete("acme/flits", "web:person", true).is_err(), "once");
+ // Its name is free for a new project.
+ new_project("flits", false);
+}
+
+#[test]
+fn a_runner_moves_its_checkout_of_a_renamed_project_and_its_worktrees_follow() {
+ let home = std::env::temp_dir().join(format!("midas-test-follow-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&home);
+ let old = home.join("repos/acme/flits");
+ std::fs::create_dir_all(&old).unwrap();
+ let git = |dir: &std::path::Path, args: &[&str]| {
+ let out = std::process::Command::new("git").arg("-C").arg(dir).args(args)
+ .env("GIT_AUTHOR_NAME", "t").env("GIT_AUTHOR_EMAIL", "t@t").env("GIT_COMMITTER_NAME", "t").env("GIT_COMMITTER_EMAIL", "t@t")
+ .output().unwrap();
+ assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).trim().to_string()
+ };
+ git(&old, &["init", "-q", "-b", "main"]);
+ git(&old, &["commit", "-q", "--allow-empty", "-m", "Start flits"]);
+ git(&old, &["remote", "add", "origin", "midas@10.44.0.1:acme/flits.git"]);
+ let work = home.join("session-s1/flits");
+ git(&old, &["worktree", "add", "-q", "-b", "session/s1", &work.to_string_lossy()]);
+ let renamed = json!([{"from": "acme/flits", "to": "acme/flitz", "git": "midas@10.44.0.1:acme/flitz.git"}]);
+ crate::sessions::follow_renames(&home, &renamed);
+ let new = home.join("repos/acme/flitz");
+ assert!(new.join(".git").exists() && !old.exists());
+ assert_eq!(git(&new, &["remote", "get-url", "origin"]), "midas@10.44.0.1:acme/flitz.git");
+ // The session's worktree, in its folder as it was, finds its checkout and says the new name.
+ assert_eq!(git(&work, &["rev-parse", "--abbrev-ref", "HEAD"]), "session/s1");
+ assert_eq!(crate::cli::repo_in(&work).as_deref(), Some("acme/flitz"));
+ assert_eq!(crate::sessions::folder_projects(&home.join("session-s1")), ["acme/flitz"]);
+ crate::sessions::follow_renames(&home, &renamed);
+ assert!(new.join(".git").exists(), "once");
+ let _ = std::fs::remove_dir_all(&home);
+}
diff --git a/src/tree.rs b/src/tree.rs
index 0e439da..5c1c02b 100644
--- a/src/tree.rs
+++ b/src/tree.rs
@@ -156,6 +156,17 @@ fn migrate(mut v: Value) -> Value {
v
}
+/// Project `from` renamed to `to`, or deleted (`None`), in the goals and rounds that name it (hosted.rs).
+pub(crate) fn repo_renamed(from: &str, to: Option<&str>) -> Result<()> {
+ if !path().exists() {
+ return Ok(());
+ }
+ change(|v| {
+ crate::hosted::rename_in(v, from, to);
+ Ok(())
+ })
+}
+
fn save(v: &Value) -> Result<()> {
let p = path();
if let Some(dir) = p.parent() {
diff --git a/web/src/components/projectmap.tsx b/web/src/components/projectmap.tsx
index e61939f..39ae3fc 100644
--- a/web/src/components/projectmap.tsx
+++ b/web/src/components/projectmap.tsx
@@ -31,7 +31,7 @@ const state = local({
about: {} as Record<string, RepoAbout | {error: string}>,
files: {} as Record<string, RepoEntry | {error: string}>,
/** The settings form, for the project it was filled from. */
- form: {repo: '', description: '', public: false, main: '', gate: '', gate_nodes: '', pre_land: ''},
+ form: {repo: '', description: '', public: false, main: '', gate: '', gate_nodes: '', pre_land: '', name: ''},
})
function load() {
@@ -406,7 +406,7 @@ function settingsTab(name: string): m.Children {
const f = state.form
if (f.repo !== name) {
Object.assign(f, {repo: name, description: a.description ?? '', public: a.public, main: a.project?.main ?? '', gate: a.project?.gate ?? '',
- gate_nodes: a.project?.gate_nodes ?? '', pre_land: a.project?.pre_land ?? ''})
+ gate_nodes: a.project?.gate_nodes ?? '', pre_land: a.project?.pre_land ?? '', name: short(name)})
}
const save = async () => {
if (f.public && !a.public) {
@@ -425,7 +425,32 @@ function settingsTab(name: string): m.Children {
f.repo = ''
state.graph = null
}
- return (
+ const rename = async () => {
+ const to = f.name.trim()
+ if (!to || to === short(name)) return
+ let renamed = ''
+ const done = await act(`${short(name)} is ${to} now`, async () => (renamed = (await api.projectRename(name, to)).repo))
+ if (!done) return
+ delete state.about[name]
+ f.repo = ''
+ state.graph = null
+ go(`research/map/${renamed}/settings`)
+ }
+ const remove = async () => {
+ const yes = await askConfirm({
+ title: `Delete ${short(name)}?`,
+ text: `Its repository, every branch in it and its settings go: nothing serves it any more, and its sessions stop naming it. The hub keeps the repository aside (deleted-git in its state directory), from where only someone on the hub can put it back.`,
+ yes: 'Delete it',
+ danger: true,
+ })
+ if (!yes) return
+ if (!(await act(`${short(name)} deleted`, () => api.projectDelete(name)))) return
+ delete state.about[name]
+ f.repo = ''
+ state.graph = null
+ go('research/map')
+ }
+ return [
<Card title="Settings" class="pset">
<FieldText model={bind(f, 'description')} label="What it is" placeholder="One line, as the README's first" />
<FieldSwitch model={bind(f, 'public')} label="Public" help="Anyone can read and clone it, without a login, and the public map shows it." />
@@ -438,8 +463,24 @@ function settingsTab(name: string): m.Children {
Save
</Button>
</div>
- </Card>
- )
+ </Card>,
+ <Card title="Name" class="pset">
+ <FieldText model={bind(f, 'name')} label="Name" help="Its repository, sessions and notes take the new name; clones of the old one keep working." />
+ <div class="tree-bar__row">
+ <Button variant="secondary" disabled={!f.name.trim() || f.name.trim() === short(name)} onclick={() => void rename()}>
+ Rename
+ </Button>
+ </div>
+ </Card>,
+ <Card title="Delete" class="pset">
+ <p class="hint">Deletes the project and its repository, with every branch in it.</p>
+ <div class="tree-bar__row">
+ <Button variant="danger" onclick={() => void remove()}>
+ Delete {short(name)}
+ </Button>
+ </div>
+ </Card>,
+ ]
}
const TABS: [string, string][] = [['', 'Over time'], ['files', 'Files'], ['settings', 'Settings']]
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 0445824..3ca76b3 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -694,6 +694,10 @@ export const api = {
repoShow: (repo: string, path: string) => get<RepoEntry>(`/v1/repos/${repo}/show?path=${encodeURIComponent(path)}`),
/** A project's description, visibility or landing, changed (hosted.rs `set`; on the page, an admin's). */
projectSet: (repo: string, fields: Record<string, unknown>) => post('/v1/projects/set', {repo, ...fields}),
+ /** Another name for it (hosted.rs `rename`); the old one still clones. */
+ projectRename: (repo: string, to: string) => post('/v1/projects/rename', {repo, to}) as Promise<{repo: string}>,
+ /** Deleted, by the person (hosted.rs `delete`): moved aside on the hub. */
+ projectDelete: (repo: string) => post('/v1/projects/delete', {repo}),
/** A change to it, by op (goal_save, goal_delete, idea, insight_drop, tech_confirm, tech_drop, tech_restore, tech_built, scout): the whole tree after. */
treeOp: (op: string, fields: Record<string, unknown>) => post('/v1/hosted/tree', {op, ...fields}) as Promise<TreeState>,
reopen: (id: string) => post(`/v1/hosted/${id}/reopen`, {}),