git clone https://garage44.eu/jeroen/midas.gitcartopolis-agent · 2026-11-27T17:42:10Z
feat: new projects hosted by the hub itself, with main guarded by the landing
Step 1 of docs/git-hosting.md. A session makes a project with
`midas project create` (MCP project_create): a bare repository in the hub's
state with a first commit on main, and its landing in hosted.json, which
conf::hub adds to `repos` and `projects` so every reader sees it as any other.
No Forgejo repository, deploy key or hub.conf edit by hand.
- Git over the hub's ssh login by key (`midas hub git --key`): a person's key
may do anything; an agent's pushes every branch but main, and main only
forward, from the session holding the turn (land sends
-o midas-owner=<session>), to a head with a gate pass on record. The
repository's pre-receive hook says why it refuses.
- Keys: `sudo -u midas midas hub git-key add <name> --role person|agent`.
- LFS uploads for hosted repositories (batch upload, PUT, sha256-checked); the
LFS directory is their store.
- Public projects: pages (files, README, log, commit), smart-HTTP clones
through git http-backend and archive tarballs at /git/<owner>/<name>, with
no login. A private one answers 404 there.
- `midas project set/show/log`, MCP project_set and project_read;
GET /v1/repos/<owner>/<name>/{show,log,branches,commit}.
- Making a private project public is the person's (admin login).docs/git-hosting.md | 5 +-
docs/hub.md | 42 +++++
docs/usage.md | 3 +
skills/finish-branch/land | 6 +-
src/cli.rs | 84 +++++++++
src/codeview.rs | 110 ++++++++++++
src/conf.rs | 17 +-
src/hosted.rs | 437 ++++++++++++++++++++++++++++++++++++++++++++++
src/hub.rs | 169 +++++++++++++++++-
src/hubsetup.rs | 4 +-
src/main.rs | 111 +++++++++++-
src/mcp.rs | 48 ++++-
src/mirror.rs | 154 +++++++++++++++-
src/registry.rs | 7 +
src/sessions.rs | 9 +-
src/tests.rs | 117 +++++++++++++
16 files changed, 1309 insertions(+), 14 deletions(-)
diff --git a/docs/git-hosting.md b/docs/git-hosting.md
index 0395472..53fd913 100644
--- a/docs/git-hosting.md
+++ b/docs/git-hosting.md
@@ -1,6 +1,9 @@
# midas as the git host — a design
-Status: **proposal** (2026-11-27, session s874). Nothing here is built yet.
+Status: **step 1 built** (2026-11-27, session s874): new projects are hosted by
+the hub (`midas project create`, docs/hub.md "Projects the hub hosts"), with the
+landing rule on main, LFS uploads, and public pages, clones and archives. The
+existing projects are still on Forgejo. The rest is a proposal.
midas hosts the workspace's repositories itself, and Forgejo goes. midas does not
become a forge. It keeps what agents and the one person steering them use, and
diff --git a/docs/hub.md b/docs/hub.md
index 6a3cdd1..c757038 100644
--- a/docs/hub.md
+++ b/docs/hub.md
@@ -249,6 +249,48 @@ so changing a gate is a commit, not an edit of this file. A session reads its
project's with `midas project` (`--get gate`); the hub reads the file afresh
each time.
+### Projects the hub hosts
+
+A new project needs no Forgejo and no edit of this file
+([git-hosting.md](git-hosting.md), step 1). `midas project create <name>`
+(MCP `project_create`; any caller key) makes it:
+
+- a bare repository in `/srv/midas/state/git/<owner>/<name>.git`, with a first
+ commit on `main`;
+- its landing, in `/srv/midas/state/hosted.json`. The hub adds it to `repos`
+ and `projects` as it reads hub.conf, and changes it with `midas project set`.
+
+Its `origin` is `midas@<hub>:<owner>/<name>.git`, over the hub's ssh login.
+Nodes fetch it as they fetch a mirror. Sessions clone and push it with a key
+the hub knows, which is added on the hub as its user:
+
+```bash
+sudo -u midas midas hub git-key add container --role agent "$(cat ~/.ssh/id_ed25519.pub)"
+sudo -u midas midas hub git-key add mini --role person "ssh-ed25519 AAAA…"
+sudo -u midas midas hub git-key list
+```
+
+- **A `person` key** may do anything.
+- **An `agent` key** may push every branch but main. It moves main only
+ forward, from the session holding the turn to land (the land script sends
+ `-o midas-owner=<session>`), and to a head with the gate's pass on record.
+ The repository's `pre-receive` hook (`midas hub pre-receive`) refuses
+ anything else, and says why.
+
+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.
+
+**A public project** (`--public`; making a private one public later takes the
+person's admin login) is readable by anyone at `/git/<owner>/<name>`:
+
+- pages for files, README, log and commits;
+- `git clone https://<host>/git/<owner>/<name>.git`;
+- `/git/<owner>/<name>/archive/<rev>.tar.gz`.
+
+A private project answers 404 there, as one that does not exist. Caddy passes
+`GET /git/*` with the page; the clone's `POST /git/*/git-upload-pack` needs a
+route of its own.
+
## 6. Hear about pushes
The hub learns that a branch moved when it next fetches. If the git server runs
diff --git a/docs/usage.md b/docs/usage.md
index 55a9852..7099e54 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -110,6 +110,9 @@ midas bot stop # stop it and give the node back (midas release does
```bash
~/.claude/skills/finish-branch/land # what the finish-branch skill runs
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 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/skills/finish-branch/land b/skills/finish-branch/land
index a0b10d1..e61d22c 100755
--- a/skills/finish-branch/land
+++ b/skills/finish-branch/land
@@ -65,6 +65,10 @@ project=$(midas project --get repo) || exit 1
main=$(midas project --get main) || exit 1
gate=$(midas project --get gate) || exit 1
gate_nodes=$(midas project --get gate_nodes) || exit 1
+# A repository the hub hosts moves main only for the session holding the turn
+# (src/hosted.rs): the push says whose landing it is.
+push_opts=()
+[ "$(midas project --get host 2>/dev/null)" = midas ] && push_opts=(-o "midas-owner=$(midas whoami)")
pre_land=$(midas project --get pre_land) || exit 1
if [ -z "$gate" ] && [ -z "$allow_unverified" ]; then
echo "refusing: $project has no gate at the hub (hub.conf \`projects\`, docs/hub.md)." >&2
@@ -303,7 +307,7 @@ fi
# keeping the turn — `exec` runs no EXIT trap, so nothing is released.
echo "==> fast-forwarding $main to ${sha:0:8}"
step "pushing ${sha:0:8}"
-if ! git push --quiet origin "HEAD:refs/heads/$main"; then
+if ! git push --quiet ${push_opts[@]+"${push_opts[@]}"} origin "HEAD:refs/heads/$main"; then
attempt=${MIDAS_LAND_ATTEMPT:-1}
if [ -n "${renewer:-}" ] && [ "$attempt" -lt 3 ]; then
echo "$main moved outside the landing queue — going round again, keeping the turn" >&2
diff --git a/src/cli.rs b/src/cli.rs
index bc4e5d5..405325b 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -848,3 +848,87 @@ pub fn verified(sha: Option<String>, steps: Option<String>, scope: Option<String
println!("receipt recorded at the hub for {}", sha.get(..8).unwrap_or(&sha));
Ok(0)
}
+
+// ── Projects the hub hosts (hosted.rs) ───────────────────────────────────────
+
+pub fn project_act(a: crate::ProjectCmd, owner: &str) -> Result<i32> {
+ use crate::ProjectCmd as P;
+ let enc = crate::hub::pct_encode;
+ let repo_path = |r: &str| -> Result<String> {
+ let r = crate::mirror::repo_name(r)?;
+ Ok(r.trim_end_matches(".git").to_string())
+ };
+ let v = match a {
+ P::Create { name, description, public, gate, gate_nodes, owner: repo_owner } => client::post("/v1/projects/create", &json!({
+ "owner": owner, "name": name, "description": description, "public": public,
+ "gate": gate, "gate_nodes": gate_nodes, "repo_owner": repo_owner,
+ }))?,
+ P::Set { repo, gate, gate_nodes, pre_land, description, public, private } => {
+ let mut b = json!({"owner": owner, "repo": repo_path(&repo)?});
+ for (k, v) in [("gate", gate), ("gate_nodes", gate_nodes), ("pre_land", pre_land), ("description", description)] {
+ if let Some(v) = v {
+ b[k] = json!(v);
+ }
+ }
+ if public || private {
+ b["public"] = json!(public);
+ }
+ client::post("/v1/projects/set", &b)?
+ }
+ 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()))?;
+ match v["kind"].as_str() {
+ Some("file") => print!("{}", v["text"].as_str().unwrap_or("(binary)\n")),
+ _ => for e in v["entries"].as_array().into_iter().flatten() {
+ println!("{}{}", e["name"].as_str().unwrap_or("?"), if e["kind"] == "dir" { "/" } else { "" });
+ },
+ }
+ return Ok(0);
+ }
+ P::Log { repo, rev, n } => {
+ let v = client::get(&format!("/v1/repos/{}/log?n={n}{}", repo_path(&repo)?,
+ rev.map(|r| format!("&rev={}", enc(&r))).unwrap_or_default()))?;
+ for c in v.as_array().into_iter().flatten() {
+ println!("{} {} {}", c["sha"].as_str().unwrap_or("").get(..10).unwrap_or(""),
+ c["at"].as_str().unwrap_or("").get(..10).unwrap_or(""), c["subject"].as_str().unwrap_or(""));
+ }
+ return Ok(0);
+ }
+ };
+ println!("{}", serde_json::to_string_pretty(&v)?);
+ Ok(0)
+}
+
+/// `midas hub git-key …`, on the hub as its user: the key list and the
+/// `authorized_keys` written from it must stay the hub user's files.
+pub fn git_key(c: crate::GitKeyCmd) -> Result<i32> {
+ use crate::GitKeyCmd as K;
+ if !matches!(c, K::List) {
+ let me = std::env::var("USER").unwrap_or_default();
+ let hub_user = std::fs::metadata(crate::hosted::root().parent().unwrap_or(std::path::Path::new("/")))
+ .map(|m| std::os::unix::fs::MetadataExt::uid(&m)).ok();
+ // SAFETY: getuid has no preconditions.
+ if hub_user.is_some_and(|u| u != unsafe { libc::getuid() }) {
+ bail!("run it as the hub's user, so its files stay the hub's: sudo -u midas midas hub git-key … (you are {me:?})");
+ }
+ }
+ let by = format!("hub:{}", std::env::var("SUDO_USER").or_else(|_| std::env::var("USER")).unwrap_or_default());
+ match c {
+ K::Add { name, role, key } => {
+ crate::hosted::add_key(&name, &role, &key, &by)?;
+ crate::hubsetup::refresh_ssh()?;
+ eprintln!("{name} ({role}) may now push and fetch the hub's repositories: git@ is midas@{}", crate::conf::hub().ip());
+ }
+ K::Remove { name } => {
+ if !crate::hosted::remove_key(&name, &by)? {
+ bail!("no key {name}");
+ }
+ crate::hubsetup::refresh_ssh()?;
+ }
+ K::List => for (name, k) in crate::hosted::keys() {
+ println!("{name} {} {}", k["role"].as_str().unwrap_or("?"), k["key"].as_str().unwrap_or("").get(..40).unwrap_or(""));
+ },
+ }
+ Ok(0)
+}
diff --git a/src/codeview.rs b/src/codeview.rs
new file mode 100644
index 0000000..289c5bf
--- /dev/null
+++ b/src/codeview.rs
@@ -0,0 +1,110 @@
+//! The pages a public hosted repository is read by, at
+//! `/git/<owner>/<name>/…` (hub.rs `public_git`): files, the README, the log
+//! and one commit. Plain HTML from the server, with no script and no login, so a
+//! reader and a search engine see the same thing. Private repositories never
+//! reach here.
+//!
+//! - `/git/o/n` — the root directory and the README;
+//! - `/git/o/n/tree/<path>?rev=<rev>` — a directory or a file;
+//! - `/git/o/n/log?rev=<rev>` — the last 50 commits;
+//! - `/git/o/n/commit/<sha>` — one commit and its diff.
+
+use anyhow::Result;
+
+use crate::hosted;
+
+fn esc(s: &str) -> String {
+ s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
+}
+
+/// A path segment or query value as it goes into a link.
+fn link(s: &str) -> String {
+ crate::hub::pct_encode(s).replace("%2F", "/")
+}
+
+fn frame(repo: &str, host: &str, title: &str, body: &str) -> String {
+ let key = repo.trim_end_matches(".git");
+ format!(
+ "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
+ <title>{t} · {k}</title><style>\
+ body{{font:15px/1.5 system-ui,sans-serif;margin:0 auto;max-width:60rem;padding:1rem;color:#222}}\
+ a{{color:#1a5fb4;text-decoration:none}}a:hover{{text-decoration:underline}}\
+ header{{display:flex;gap:1rem;align-items:baseline;flex-wrap:wrap;border-bottom:1px solid #ddd;margin-bottom:1rem}}\
+ header h1{{font-size:1.2rem;margin:.4rem 0}}pre{{background:#f6f6f6;padding:.8rem;overflow:auto;font-size:13px}}\
+ table{{border-collapse:collapse;width:100%}}td{{padding:.2rem .5rem;border-bottom:1px solid #eee}}\
+ code{{background:#f6f6f6;padding:0 .3rem}}.muted{{color:#777}}\
+ </style></head><body><header><h1><a href=\"/git/{k}\">{k}</a></h1>\
+ <a href=\"/git/{k}/log\">log</a><span class=\"muted\">clone: <code>git clone https://{h}/git/{k}.git</code></span></header>\
+ {body}</body></html>",
+ t = esc(title), k = esc(key), h = esc(host), body = body,
+ )
+}
+
+fn query(q: &str, k: &str) -> Option<String> {
+ q.split('&').find_map(|p| p.strip_prefix(&format!("{k}="))).map(crate::hub::pct_decode)
+}
+
+/// The page for `tail` (what follows `/git/<owner>/<name>/`), or none for a
+/// path that is not one.
+pub fn page(repo: &str, host: &str, tail: &str, q: &str) -> Result<Option<String>> {
+ let key = repo.trim_end_matches(".git");
+ let rev = query(q, "rev");
+ let revq = rev.as_deref().map(|r| format!("?rev={}", link(r))).unwrap_or_default();
+ if tail.is_empty() || tail == "tree" || tail.starts_with("tree/") {
+ let path = crate::hub::pct_decode(tail.strip_prefix("tree").unwrap_or("").trim_start_matches('/'));
+ let v = hosted::show(repo, rev.as_deref(), &path)?;
+ let mut body = String::new();
+ if !path.is_empty() {
+ let up = path.rsplit_once('/').map(|(u, _)| u).unwrap_or("");
+ body += &format!("<p><a href=\"/git/{}/tree/{}{}\">..</a> <span class=\"muted\">/{}</span></p>", esc(key), link(up), revq, esc(&path));
+ }
+ if v["kind"] == "dir" {
+ body += "<table>";
+ for e in v["entries"].as_array().into_iter().flatten() {
+ let n = e["name"].as_str().unwrap_or("");
+ let full = if path.is_empty() { n.to_string() } else { format!("{path}/{n}") };
+ let dir = e["kind"] == "dir";
+ body += &format!("<tr><td><a href=\"/git/{}/tree/{}{}\">{}{}</a></td><td class=\"muted\">{}</td></tr>",
+ esc(key), link(&full), revq, esc(n), if dir { "/" } else { "" },
+ e["size"].as_u64().map(|s| format!("{s} B")).unwrap_or_default());
+ }
+ body += "</table>";
+ // The README of the directory, as text.
+ if let Some(readme) = v["entries"].as_array().into_iter().flatten()
+ .filter_map(|e| e["name"].as_str()).find(|n| n.to_ascii_lowercase().starts_with("readme")) {
+ let p = if path.is_empty() { readme.to_string() } else { format!("{path}/{readme}") };
+ if let Some(t) = hosted::show(repo, rev.as_deref(), &p)?["text"].as_str() {
+ body += &format!("<h2>{}</h2><pre>{}</pre>", esc(readme), esc(t));
+ }
+ }
+ } else if let Some(t) = v["text"].as_str() {
+ body += &format!("<pre>{}</pre>", esc(t));
+ } else {
+ body += &format!("<p class=\"muted\">A binary file of {} bytes.</p>", v["size"]);
+ }
+ let title = if path.is_empty() { key.to_string() } else { path.clone() };
+ return Ok(Some(frame(repo, host, &title, &body)));
+ }
+ if tail == "log" {
+ let mut body = "<table>".to_string();
+ for c in hosted::log(repo, rev.as_deref(), 50)? {
+ let sha = c["sha"].as_str().unwrap_or("");
+ body += &format!("<tr><td><a href=\"/git/{}/commit/{}\"><code>{}</code></a></td><td>{}</td><td class=\"muted\">{}</td></tr>",
+ esc(key), esc(sha), esc(sha.get(..10).unwrap_or(sha)), esc(c["subject"].as_str().unwrap_or("")),
+ esc(c["at"].as_str().unwrap_or("").get(..10).unwrap_or("")));
+ }
+ body += "</table>";
+ return Ok(Some(frame(repo, host, "log", &body)));
+ }
+ if let Some(sha) = tail.strip_prefix("commit/") {
+ if !sha.chars().all(|c| c.is_ascii_hexdigit()) {
+ return Ok(None);
+ }
+ let c = hosted::commit(repo, sha)?;
+ let body = format!("<p class=\"muted\">{} · {}</p><pre>{}</pre><pre>{}</pre>",
+ esc(c["author"].as_str().unwrap_or("")), esc(c["at"].as_str().unwrap_or("")),
+ esc(c["message"].as_str().unwrap_or("")), esc(c["diff"].as_str().unwrap_or("")));
+ return Ok(Some(frame(repo, host, sha, &body)));
+ }
+ Ok(None)
+}
diff --git a/src/conf.rs b/src/conf.rs
index 8465e8d..0666916 100644
--- a/src/conf.rs
+++ b/src/conf.rs
@@ -291,7 +291,20 @@ impl Default for HubConf {
/// `MIDAS_HUB_CONF` names another file: a scratch hub of one's own, with projects (docs/development.md).
pub fn hub() -> HubConf {
let path = std::env::var("MIDAS_HUB_CONF").ok().filter(|p| !p.is_empty()).unwrap_or_else(|| HUB_CONF.to_string());
- read(Path::new(&path)).ok().flatten().unwrap_or_default()
+ let mut c = read(Path::new(&path)).ok().flatten().unwrap_or_default();
+ // The repositories the hub hosts itself are projects like any other
+ // (hosted.rs): their settings are the hub's to write, not this file's.
+ if crate::registry::is_hub() {
+ for (repo, r) in crate::hosted::repos() {
+ if !c.repos.iter().any(|x| x.trim_end_matches(".git") == repo) {
+ c.repos.push(repo.clone());
+ }
+ if let Ok(p) = serde_json::from_value::<Project>(r["project"].clone()) {
+ c.projects.entry(repo).or_insert(p);
+ }
+ }
+ }
+ c
}
pub fn read(path: &Path) -> Result<Option<HubConf>> {
@@ -331,6 +344,8 @@ impl HubConf {
.collect();
Some(serde_json::json!({
"repo": repo,
+ // Where its git lives: the hub (hosted.rs), or Forgejo.
+ "host": if crate::registry::is_hub() && crate::hosted::is_hosted(repo) { "midas" } else { "forgejo" },
"gate": p.gate,
"gate_nodes": p.gate_nodes.unwrap_or_else(|| "any".into()),
"pre_land": p.pre_land,
diff --git a/src/hosted.rs b/src/hosted.rs
new file mode 100644
index 0000000..565dda2
--- /dev/null
+++ b/src/hosted.rs
@@ -0,0 +1,437 @@
+//! Repositories the hub hosts itself, in place of Forgejo, for new projects
+//! (docs/git-hosting.md, step 1). Each is a bare repository in the state
+//! directory, `git/<owner>/<name>.git`, described in `hosted.json` beside it:
+//! its visibility, its description, who made it, and its project's landing
+//! settings, which `conf::hub` adds to hub.conf's `repos` and `projects` so
+//! every reader of those sees a hosted project as any other.
+//!
+//! Git goes over the hub's ssh login (`midas hub git --key <name>`), by key.
+//! A key is the person's (`person`: everything) or an agent's (`agent`: every
+//! branch but main, and main only from a landing: the turn to land held, a
+//! fast-forward, the gate's pass on record for the new head — what the land
+//! script did by convention, here the server's rule). Nodes fetch as they
+//! fetch a mirror. Public repositories are also read without a login over HTTPS
+//! (`hub::public_git`); private ones never.
+
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use anyhow::{bail, Context, Result};
+use serde_json::{json, Map, Value};
+
+use crate::{registry, store};
+
+pub fn root() -> PathBuf {
+ registry::root().join("git")
+}
+
+fn file() -> PathBuf {
+ registry::root().join("hosted.json")
+}
+
+/// `owner/name` (no `.git`): the key every list in hub.conf uses.
+fn key(repo: &str) -> String {
+ repo.trim_end_matches(".git").to_string()
+}
+
+/// The bare repository of `repo` (`owner/name` or `owner/name.git`).
+pub fn path(repo: &str) -> PathBuf {
+ root().join(format!("{}.git", key(repo)))
+}
+
+fn read() -> Value {
+ store::read::<Value>(&file()).unwrap_or_else(|| json!({}))
+}
+
+/// Every hosted repository, `owner/name` → its record.
+pub fn repos() -> Map<String, Value> {
+ read()["repos"].as_object().cloned().unwrap_or_default()
+}
+
+pub fn get(repo: &str) -> Option<Value> {
+ repos().get(&key(repo)).cloned()
+}
+
+pub fn is_hosted(repo: &str) -> bool {
+ get(repo).is_some()
+}
+
+pub fn is_public(repo: &str) -> bool {
+ get(repo).is_some_and(|r| r["visibility"] == "public")
+}
+
+fn update<R>(f: impl FnOnce(&mut Value) -> Result<R>) -> Result<R> {
+ store::update(file(), |v: &mut Value| {
+ store::objects(v, &["repos", "keys"]);
+ f(v)
+ })
+}
+
+fn git(dir: &Path, args: &[&str]) -> Result<String> {
+ let out = Command::new("git").arg("-C").arg(dir).args(args)
+ .env("GIT_AUTHOR_NAME", "midas").env("GIT_AUTHOR_EMAIL", "midas@localhost")
+ .env("GIT_COMMITTER_NAME", "midas").env("GIT_COMMITTER_EMAIL", "midas@localhost")
+ .output().with_context(|| format!("running git {}", args.join(" ")))?;
+ if !out.status.success() {
+ bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
+ }
+ Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
+}
+
+fn git_in(dir: &Path, args: &[&str], stdin: &str) -> Result<String> {
+ use std::io::Write;
+ let mut child = Command::new("git").arg("-C").arg(dir).args(args)
+ .stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped())
+ .spawn()?;
+ child.stdin.take().unwrap().write_all(stdin.as_bytes())?;
+ let out = child.wait_with_output()?;
+ if !out.status.success() {
+ bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
+ }
+ Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
+}
+
+/// What a new project says of itself.
+pub struct New<'a> {
+ pub owner: &'a str,
+ pub name: &'a str,
+ pub description: &'a str,
+ pub public: bool,
+ pub gate: Option<&'a str>,
+ pub gate_nodes: Option<&'a str>,
+ pub by: &'a str,
+}
+
+/// Make a repository and its project: a bare repository with a first commit on
+/// `main` (a README of its name and description, so a session's worktree has a
+/// main to branch from), the hooks that guard and report pushes, and its record.
+/// A name hub.conf already has (a Forgejo project) is refused.
+pub fn create(n: &New) -> Result<Value> {
+ let repo = crate::mirror::repo_name(&format!("{}/{}", n.owner, n.name))?;
+ let k = key(&repo);
+ if crate::conf::read(Path::new(&conf_path()))?.unwrap_or_default().repos.iter().any(|r| key(r) == k) {
+ bail!("{k} is already a project of the workspace, on Forgejo");
+ }
+ let dir = path(&repo);
+ if dir.exists() || is_hosted(&k) {
+ bail!("{k} is already hosted here");
+ }
+ fs::create_dir_all(dir.parent().unwrap())?;
+ let made = (|| -> Result<()> {
+ git(Path::new("."), &["init", "--quiet", "--bare", "--initial-branch=main", &dir.to_string_lossy()])?;
+ for (k, v) in [("receive.advertisePushOptions", "true"), ("uploadpack.allowFilter", "true"),
+ ("receive.fsckObjects", "true"), ("core.logAllRefUpdates", "true")] {
+ git(&dir, &["config", k, v])?;
+ }
+ install_hooks(&dir)?;
+ let readme = format!("# {}\n\n{}\n", n.name, n.description.trim());
+ let blob = git_in(&dir, &["hash-object", "-w", "--stdin"], &readme)?;
+ let tree = git_in(&dir, &["mktree"], &format!("100644 blob {blob}\tREADME.md\n"))?;
+ let commit = git(&dir, &["commit-tree", &tree, "-m", &format!("Start {}", n.name)])?;
+ git(&dir, &["update-ref", "refs/heads/main", &commit])?;
+ Ok(())
+ })();
+ if let Err(e) = made {
+ let _ = fs::remove_dir_all(&dir);
+ return Err(e);
+ }
+ let mut project = json!({});
+ if let Some(g) = n.gate.filter(|g| !g.trim().is_empty()) {
+ project["gate"] = json!(g);
+ }
+ if let Some(g) = n.gate_nodes.filter(|g| !g.trim().is_empty()) {
+ project["gate_nodes"] = json!(g);
+ }
+ let record = json!({
+ "visibility": if n.public { "public" } else { "private" },
+ "description": n.description.trim(),
+ "created_by": n.by, "created_at": registry::now(),
+ "project": project,
+ });
+ update(|v| {
+ v["repos"][&k] = record.clone();
+ Ok(())
+ })?;
+ crate::events::emit("repo_created", json!({"repo": k, "actor": n.by, "visibility": record["visibility"]}));
+ Ok(json!({"repo": k, "url": url(&k), "visibility": record["visibility"]}))
+}
+
+fn conf_path() -> String {
+ std::env::var("MIDAS_HUB_CONF").ok().filter(|p| !p.is_empty()).unwrap_or_else(|| crate::conf::HUB_CONF.to_string())
+}
+
+/// The hooks every hosted repository runs: they hand over to this binary.
+fn install_hooks(dir: &Path) -> Result<()> {
+ let bin = std::env::current_exe().ok().filter(|p| p.starts_with("/usr/local/bin"))
+ .map_or_else(|| crate::hubsetup::BIN.to_string(), |p| p.display().to_string());
+ for hook in ["pre-receive", "post-receive"] {
+ let f = dir.join("hooks").join(hook);
+ fs::write(&f, format!("#!/bin/sh\n# midas: {hook} for a repository the hub hosts (src/hosted.rs).\nexec {bin} hub {hook}\n"))?;
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(&f, fs::Permissions::from_mode(0o755))?;
+ }
+ Ok(())
+}
+
+/// Where clients in the workspace push and fetch: the hub's ssh login, by key.
+pub fn url(repo: &str) -> String {
+ format!("midas@{}:{}.git", crate::conf::hub().ip(), key(repo))
+}
+
+/// Change a project's landing settings or description. `public` changes its
+/// visibility, which only the person may make public (`by_person`): publishing
+/// a private repository is outward-facing and not undone by turning it back.
+pub fn set(repo: &str, fields: &Value, by: &str, by_person: bool) -> Result<Value> {
+ let k = key(repo);
+ let out = update(|v| {
+ let Some(r) = v["repos"].get_mut(&k) else { bail!("{k} is not hosted here") };
+ for f in ["gate", "gate_nodes", "pre_land", "main"] {
+ match fields.get(f) {
+ Some(Value::String(s)) if !s.trim().is_empty() => r["project"][f] = json!(s),
+ Some(Value::String(_)) | Some(Value::Null) => {
+ if let Some(o) = r["project"].as_object_mut() {
+ o.remove(f);
+ }
+ }
+ _ => {}
+ }
+ }
+ if let Some(d) = fields["description"].as_str() {
+ r["description"] = json!(d.trim());
+ }
+ if let Some(p) = fields["public"].as_bool() {
+ if p && r["visibility"] != "public" && !by_person {
+ bail!("making {k} public is the person's to do: ask them, and they make it public on the page");
+ }
+ r["visibility"] = json!(if p { "public" } else { "private" });
+ }
+ Ok(r.clone())
+ })?;
+ crate::events::emit("repo_changed", json!({"repo": k, "actor": by, "fields": fields}));
+ Ok(out)
+}
+
+// ── Keys ─────────────────────────────────────────────────────────────────────
+
+pub fn keys() -> Map<String, Value> {
+ read()["keys"].as_object().cloned().unwrap_or_default()
+}
+
+pub fn role_of(name: &str) -> Option<String> {
+ keys().get(name).and_then(|k| k["role"].as_str()).map(str::to_string)
+}
+
+/// Let a key push and fetch hosted repositories: `role` is `person` or `agent`.
+/// Run on the hub (`midas hub git-key add`); the hub's `authorized_keys` is
+/// rewritten from the list.
+pub fn add_key(name: &str, role: &str, key: &str, by: &str) -> Result<()> {
+ if !matches!(role, "person" | "agent") {
+ bail!("a key is a person's or an agent's, not {role:?}");
+ }
+ if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || "-_".contains(c)) {
+ bail!("a key's name is letters, digits, - and _: {name:?}");
+ }
+ let key = key.trim();
+ let parts: Vec<&str> = key.split_whitespace().collect();
+ if parts.len() < 2 || !parts[0].starts_with("ssh-") && !parts[0].starts_with("ecdsa-") || key.contains(['"', '\n']) {
+ bail!("not an ssh public key: {key:?}");
+ }
+ let line = format!("{} {}", parts[0], parts[1]);
+ update(|v| {
+ v["keys"][name] = json!({"key": line, "role": role, "by": by, "at": registry::now()});
+ Ok(())
+ })?;
+ crate::events::emit("git_key_added", json!({"name": name, "role": role, "actor": by}));
+ Ok(())
+}
+
+pub fn remove_key(name: &str, by: &str) -> Result<bool> {
+ let had = update(|v| Ok(v["keys"].as_object_mut().and_then(|k| k.remove(name)).is_some()))?;
+ if had {
+ crate::events::emit("git_key_removed", json!({"name": name, "actor": by}));
+ }
+ Ok(had)
+}
+
+/// The `authorized_keys` lines for the keys: each may run git, and nothing else.
+pub fn authorized_lines(bin: &str) -> String {
+ keys().iter().filter_map(|(name, k)| {
+ Some(format!("restrict,command=\"{bin} hub git --key {name}\" {} midas-key-{name}\n", k["key"].as_str()?))
+ }).collect()
+}
+
+// ── Pushes ───────────────────────────────────────────────────────────────────
+
+const ZERO: &str = "0000000000000000000000000000000000000000";
+
+/// One ref a push moves.
+pub struct Update<'a> {
+ pub old: &'a str,
+ pub new: &'a str,
+ pub refname: &'a str,
+}
+
+/// May `role` make these updates to `repo`? `owner` is the session the push
+/// says it lands for (`git push -o midas-owner=<session>`). The person may do
+/// anything. An agent may move any branch but main, and main only forward,
+/// from the session holding the turn to land, to a head the gate passed.
+pub fn may_push(role: &str, owner: Option<&str>, repo: &str, updates: &[Update]) -> std::result::Result<(), String> {
+ if role == "person" {
+ return Ok(());
+ }
+ if role != "agent" {
+ return Err(format!("a {role:?} key does not push"));
+ }
+ let main = crate::conf::hub().project(&key(repo)).and_then(|p| p["main"].as_str().map(str::to_string))
+ .unwrap_or_else(|| "main".into());
+ let main_ref = format!("refs/heads/{main}");
+ for u in updates {
+ if u.refname != main_ref {
+ continue;
+ }
+ if u.new == ZERO {
+ return Err(format!("{main} is never deleted by an agent"));
+ }
+ if u.old == ZERO {
+ return Err(format!("{main} exists already; an agent moves it only forward"));
+ }
+ let dir = path(repo);
+ let forward = Command::new("git").arg("-C").arg(&dir).args(["merge-base", "--is-ancestor", u.old, u.new])
+ .status().is_ok_and(|s| s.success());
+ if !forward {
+ return Err(format!("{main} moves only forward: {} is not on top of {}", &u.new[..8], &u.old[..8]));
+ }
+ let Some(owner) = owner else {
+ return Err(format!("{main} is moved by a landing: land with the finish-branch skill, which says whose it is"));
+ };
+ let holder = registry::land_holder();
+ if holder.as_deref() != Some(owner) {
+ return Err(format!("{owner} does not hold the turn to land (`midas land status`); {main} moves only for the landing that does"));
+ }
+ if crate::deploy::verification(u.new).is_none() {
+ return Err(format!("no gate pass is on record for {}: run the gate (land --verify-only), then land", &u.new[..8]));
+ }
+ }
+ Ok(())
+}
+
+/// `midas hub pre-receive`, in a hosted repository: git hands it the updates
+/// on stdin; the key's role comes from `hub git --key` in the environment.
+pub fn pre_receive() -> Result<i32> {
+ use std::io::Read;
+ let mut text = String::new();
+ std::io::stdin().read_to_string(&mut text)?;
+ let role = std::env::var("MIDAS_GIT_ROLE").unwrap_or_default();
+ let name = std::env::var("MIDAS_GIT_KEY").unwrap_or_default();
+ let options: Vec<String> = (0..std::env::var("GIT_PUSH_OPTION_COUNT").ok().and_then(|n| n.parse().ok()).unwrap_or(0))
+ .filter_map(|i| std::env::var(format!("GIT_PUSH_OPTION_{i}")).ok()).collect();
+ let owner = options.iter().find_map(|o| o.strip_prefix("midas-owner=")).map(str::to_string);
+ let repo = repo_of_cwd()?;
+ let updates: Vec<Update> = text.lines().filter_map(|l| {
+ let mut w = l.split_whitespace();
+ Some(Update { old: w.next()?, new: w.next()?, refname: w.next()? })
+ }).collect();
+ match may_push(&role, owner.as_deref(), &repo, &updates) {
+ Ok(()) => Ok(0),
+ Err(why) => {
+ crate::mirror::log("git_refused", json!({"repo": repo, "key": name, "why": why}));
+ eprintln!("midas: {why}");
+ Ok(1)
+ }
+ }
+}
+
+/// `midas hub post-receive`: tell the hub what moved, as Forgejo's hook did.
+pub fn post_receive() -> Result<i32> {
+ use std::io::Read;
+ let mut text = String::new();
+ std::io::stdin().read_to_string(&mut text)?;
+ let repo = repo_of_cwd()?;
+ let refs: Vec<Value> = text.lines().filter_map(|l| {
+ let mut w = l.split_whitespace();
+ Some(json!({"old": w.next()?, "new": w.next()?, "ref": w.next()?}))
+ }).collect();
+ let _ = crate::hub::request(&crate::conf::hub().url(), "POST", "/v1/pushed",
+ Some(&json!({"repo": format!("{repo}.git"), "refs": refs}).to_string()));
+ Ok(0)
+}
+
+/// `owner/name` of the bare repository a hook runs in.
+fn repo_of_cwd() -> Result<String> {
+ let dir = std::env::current_dir()?;
+ let rel = dir.strip_prefix(root()).with_context(|| format!("{} is not a hosted repository", dir.display()))?;
+ Ok(key(&rel.to_string_lossy()))
+}
+
+// ── Reading ──────────────────────────────────────────────────────────────────
+
+/// A file's or a directory's contents at `rev` (default the main branch): a
+/// directory as its entries, a file as text (or a note that it is binary).
+pub fn show(repo: &str, rev: Option<&str>, file: &str) -> Result<Value> {
+ let dir = path(repo);
+ let rev = rev.filter(|r| !r.is_empty()).unwrap_or("HEAD");
+ if rev.starts_with('-') || file.starts_with('-') || file.contains("..") {
+ bail!("not a revision or a path");
+ }
+ let file = file.trim_matches('/');
+ let spec = format!("{rev}:{file}");
+ let kind = git(&dir, &["cat-file", "-t", &spec]).with_context(|| format!("{file:?} is not at {rev}"))?;
+ let commit = git(&dir, &["rev-parse", &format!("{rev}^{{commit}}")])?;
+ if kind == "tree" {
+ let entries: Vec<Value> = git(&dir, &["ls-tree", "-l", &spec])?.lines().filter_map(|l| {
+ let (meta, name) = l.split_once('\t')?;
+ let m: Vec<&str> = meta.split_whitespace().collect();
+ Some(json!({"name": name, "kind": if m.get(1) == Some(&"tree") { "dir" } else { "file" },
+ "size": m.get(3).and_then(|s| s.parse::<u64>().ok())}))
+ }).collect();
+ return Ok(json!({"repo": key(repo), "commit": commit, "path": file, "kind": "dir", "entries": entries}));
+ }
+ let out = Command::new("git").arg("-C").arg(&dir).args(["cat-file", "blob", &spec]).output()?;
+ let bytes = out.stdout;
+ let text = (bytes.len() <= 1 << 20).then(|| String::from_utf8(bytes.clone()).ok()).flatten();
+ Ok(json!({"repo": key(repo), "commit": commit, "path": file, "kind": "file", "size": bytes.len(),
+ "text": text, "binary": text.is_none()}))
+}
+
+/// The last `n` commits on `rev`, newest first.
+pub fn log(repo: &str, rev: Option<&str>, n: usize) -> Result<Vec<Value>> {
+ let rev = rev.filter(|r| !r.is_empty()).unwrap_or("HEAD");
+ if rev.starts_with('-') {
+ bail!("not a revision");
+ }
+ let out = git(&path(repo), &["log", &format!("-{}", n.min(200)), "--format=%H%x1f%an%x1f%aI%x1f%s", rev, "--"])?;
+ Ok(out.lines().filter_map(|l| {
+ let f: Vec<&str> = l.split('\x1f').collect();
+ Some(json!({"sha": f.first()?, "author": f.get(1)?, "at": f.get(2)?, "subject": f.get(3)?}))
+ }).collect())
+}
+
+/// The branches, with their heads.
+pub fn branches(repo: &str) -> Result<Vec<Value>> {
+ let out = git(&path(repo), &["for-each-ref", "--format=%(refname:short)%x1f%(objectname)%x1f%(committerdate:iso-strict)", "refs/heads"])?;
+ Ok(out.lines().filter_map(|l| {
+ let f: Vec<&str> = l.split('\x1f').collect();
+ Some(json!({"name": f.first()?, "sha": f.get(1)?, "at": f.get(2)?}))
+ }).collect())
+}
+
+/// One commit: its message and its diff (cut at 200 kB).
+pub fn commit(repo: &str, sha: &str) -> Result<Value> {
+ if sha.starts_with('-') {
+ bail!("not a revision");
+ }
+ let dir = path(repo);
+ let head = git(&dir, &["show", "-s", "--format=%H%x1f%an%x1f%aI%x1f%B", sha])?;
+ let f: Vec<&str> = head.splitn(4, '\x1f').collect();
+ let mut diff = git(&dir, &["show", "--format=", "--stat", "--patch", sha])?;
+ if diff.len() > 200_000 {
+ let mut cut = 200_000;
+ while !diff.is_char_boundary(cut) {
+ cut -= 1;
+ }
+ diff.truncate(cut);
+ diff.push_str("\n… (cut)");
+ }
+ Ok(json!({"sha": f.first(), "author": f.get(1), "at": f.get(2), "message": f.get(3), "diff": diff}))
+}
diff --git a/src/hub.rs b/src/hub.rs
index b780fe8..6063c14 100644
--- a/src/hub.rs
+++ b/src/hub.rs
@@ -180,6 +180,8 @@ pub(crate) fn handle(mut stream: TcpStream, peer: &str) -> Result<()> {
let (mut media_name, mut media_caption, mut media_tech, mut range) = (String::new(), String::new(), String::new(), String::new());
// The page's own files: what the browser has already, and whether it takes gzip.
let (mut if_none_match, mut gzip_ok) = (String::new(), false);
+ // A git client's, for a public repository's smart HTTP (`public_git`).
+ let (mut content_type, mut git_protocol, mut content_encoding) = (String::new(), String::new(), String::new());
// The address the caller reached the hub at. Not always the hub's own: a Mac
// node's VM comes through its machine's forwarder, at the VM's gateway.
let mut host = String::new();
@@ -219,6 +221,12 @@ pub(crate) fn handle(mut stream: TcpStream, peer: &str) -> Result<()> {
fwd_proto = value().to_ascii_lowercase();
} else if lower.starts_with("x-forwarded-host:") {
fwd_host = value();
+ } else if lower.starts_with("content-type:") {
+ content_type = value();
+ } else if lower.starts_with("git-protocol:") {
+ git_protocol = value();
+ } else if lower.starts_with("content-encoding:") {
+ content_encoding = value();
} else if lower.starts_with("upgrade:") {
upgrade = value().to_ascii_lowercase();
} else if lower.starts_with("sec-websocket-key:") {
@@ -271,6 +279,14 @@ pub(crate) fn handle(mut stream: TcpStream, peer: &str) -> Result<()> {
};
return crate::device::serve_link(stream, reader, &ws_key, &id);
}
+ // A public repository the hub hosts, to anyone (hosted.rs): clone, archive,
+ // and pages to read it by. A private one is not found, as one that is not there.
+ if let Some(rest) = target.strip_prefix("/git/") {
+ let shown_host = if fwd_host.is_empty() { host.clone() } else { fwd_host.clone() };
+ let g = PublicGit { method: &method, rest, len, content_type: &content_type, git_protocol: &git_protocol, host: &shown_host,
+ content_encoding: &content_encoding, peer };
+ return public_git(&mut stream, &mut reader, &g);
+ }
// Machines' paths are never a person's: not through the web proxy.
if who.web && (target.starts_with("/lfs/") || target.starts_with("/v1/forgejo")) {
return respond(&mut stream, 403, "text/plain", b"not through the web");
@@ -606,6 +622,9 @@ fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &st
}
// Whether the page may offer to talk a session over (discuss.rs).
("GET", "hosted/projects") => return Ok((200, crate::sessions::projects())),
+ // A repository the hub hosts, read without a checkout (hosted.rs):
+ // repos/<owner>/<name>/{show,log,branches,commit}.
+ ("GET", p) if p.starts_with("repos/") => return repo_read(&p["repos/".len()..], &q),
// Templates and their schedules (templates.rs), for the page's Autopilot.
("GET", "hosted/templates") => return Ok((200, crate::templates::all())),
// The research tree: goals, techs, insights and the scout's rounds (tree.rs).
@@ -1263,6 +1282,27 @@ fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &st
ok
}
("POST", "nodes/add") => { registry::add_node(body)?; crate::hubsetup::refresh_ssh()?; ok }
+ // A new project, hosted here (hosted.rs): its repository and its landing.
+ ("POST", "projects/create") => {
+ let default_owner = crate::conf::hub().first_repo().and_then(|r| r.split('/').next().map(str::to_string))
+ .unwrap_or_else(|| "midas".into());
+ let new_owner = s("repo_owner").unwrap_or(default_owner);
+ let name = s("name").unwrap_or_default();
+ match crate::hosted::create(&crate::hosted::New {
+ owner: &new_owner, name: &name, description: &s("description").unwrap_or_default(),
+ public: body["public"] == true, gate: s("gate").as_deref(), gate_nodes: s("gate_nodes").as_deref(), by: &by,
+ }) {
+ Ok(v) => (200, v),
+ Err(e) => (409, json!({"error": format!("{e:#}")})),
+ }
+ }
+ ("POST", "projects/set") => {
+ let by_person = p.account.is_some() && crate::accounts::at_least(&p.role, "admin");
+ match crate::hosted::set(&s("repo").unwrap_or_default(), body, &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();
@@ -1468,6 +1508,20 @@ fn lfs(
return respond(stream, 401, LFS_JSON, br#"{"message":"a token from midas hub git is required"}"#);
};
if let Some(oid) = rest.strip_prefix("objects/") {
+ // An upload to a repository the hub hosts, with a token for one.
+ if method == "PUT" {
+ let upload = crate::mirror::check_token_op(bearer).is_some_and(|(_, op)| op == "upload");
+ if !upload || !crate::hosted::is_hosted(&repo) {
+ return respond(stream, 403, LFS_JSON, br#"{"message":"uploads go only to a repository the hub hosts"}"#);
+ }
+ return match crate::mirror::store_object(oid, reader, len as u64) {
+ Ok(()) => {
+ events::emit("lfs_stored", json!({"repo": repo, "oid": oid, "size": len}));
+ respond(stream, 200, LFS_JSON, b"{}")
+ }
+ Err(e) => respond(stream, 422, LFS_JSON, json!({"message": format!("{e:#}")}).to_string().as_bytes()),
+ };
+ }
if method != "GET" {
return respond(stream, 422, LFS_JSON, br#"{"message":"download only"}"#);
}
@@ -1502,6 +1556,119 @@ fn lfs(
}
}
+struct PublicGit<'a> {
+ method: &'a str,
+ rest: &'a str,
+ len: usize,
+ content_type: &'a str,
+ git_protocol: &'a str,
+ content_encoding: &'a str,
+ host: &'a str,
+ peer: &'a str,
+}
+
+/// `/git/<owner>/<name>…` for a public hosted repository, with no login:
+/// `.git/info/refs` and `.git/git-upload-pack` (a clone, through `git
+/// http-backend`; never a push), `/archive/<rev>.tar.gz`, and the pages
+/// (`codeview.rs`). Anything else, a private repository included, is a 404.
+fn public_git(stream: &mut TcpStream, reader: &mut BufReader<TcpStream>, g: &PublicGit) -> Result<()> {
+ let (path, query) = g.rest.split_once('?').unwrap_or((g.rest, ""));
+ let mut seg = path.splitn(3, '/');
+ let (owner, name, tail) = (seg.next().unwrap_or(""), seg.next().unwrap_or(""), seg.next().unwrap_or(""));
+ let git_suffix = name.ends_with(".git");
+ let name = name.trim_end_matches(".git");
+ let not_found = |s: &mut TcpStream| respond(s, 404, "text/plain", b"no such public repository\n");
+ let Ok(repo) = crate::mirror::repo_name(&format!("{owner}/{name}")) else { return not_found(stream) };
+ if !crate::hosted::is_public(&repo) {
+ return not_found(stream);
+ }
+ // Smart HTTP, for clones (Cargo's `git =`, anybody's `git clone`).
+ if git_suffix {
+ let fetch = matches!((g.method, tail), ("GET", "info/refs") | ("POST", "git-upload-pack"))
+ && (tail != "info/refs" || query.split('&').any(|p| p == "service=git-upload-pack"));
+ if !fetch || g.len > 16 << 20 {
+ return respond(stream, 403, "text/plain", b"read-only: clones and fetches\n");
+ }
+ let mut body = vec![0u8; g.len];
+ reader.read_exact(&mut body)?;
+ let mut child = std::process::Command::new("git").arg("http-backend")
+ .env_clear().env("PATH", std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".into()))
+ .env("GIT_PROJECT_ROOT", crate::hosted::root()).env("GIT_HTTP_EXPORT_ALL", "1")
+ .env("PATH_INFO", format!("/{}/{tail}", repo)).env("QUERY_STRING", query)
+ .env("REQUEST_METHOD", g.method).env("CONTENT_TYPE", g.content_type).env("CONTENT_LENGTH", g.len.to_string())
+ .env("GIT_PROTOCOL", g.git_protocol).env("HTTP_CONTENT_ENCODING", g.content_encoding).env("REMOTE_ADDR", g.peer)
+ .stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null())
+ .spawn()?;
+ let mut stdin = child.stdin.take().unwrap();
+ let feeder = std::thread::spawn(move || {
+ let _ = stdin.write_all(&body);
+ });
+ let mut out = BufReader::new(child.stdout.take().unwrap());
+ // The CGI's headers, then its body as it comes.
+ let mut status = "200 OK".to_string();
+ let mut headers = String::new();
+ loop {
+ let mut h = String::new();
+ if out.read_line(&mut h)? == 0 || h.trim().is_empty() {
+ break;
+ }
+ match h.split_once(':') {
+ Some((k, v)) if k.eq_ignore_ascii_case("status") => status = v.trim().to_string(),
+ _ => headers.push_str(&format!("{}\r\n", h.trim_end())),
+ }
+ }
+ write!(stream, "HTTP/1.1 {status}\r\n{headers}Connection: close\r\n\r\n")?;
+ std::io::copy(&mut out, stream)?;
+ let _ = feeder.join();
+ let _ = child.wait();
+ events::emit("git_public", json!({"repo": repo, "what": tail, "peer": g.peer}));
+ return Ok(());
+ }
+ if g.method != "GET" {
+ return respond(stream, 405, "text/plain", b"read-only\n");
+ }
+ // archive/<rev>.tar.gz: what Bun takes as a dependency.
+ if let Some(rev) = tail.strip_prefix("archive/").and_then(|r| r.strip_suffix(".tar.gz")) {
+ if rev.is_empty() || rev.starts_with('-') || !rev.chars().all(|c| c.is_ascii_alphanumeric() || "-_./".contains(c)) {
+ return not_found(stream);
+ }
+ let out = std::process::Command::new("git").arg("-C").arg(crate::hosted::path(&repo))
+ .args(["archive", "--format=tar.gz", &format!("--prefix={name}/"), rev]).output()?;
+ if !out.status.success() {
+ return not_found(stream);
+ }
+ write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/gzip\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", out.stdout.len())?;
+ stream.write_all(&out.stdout)?;
+ return Ok(());
+ }
+ match crate::codeview::page(&repo, g.host, tail, query) {
+ Ok(Some(html)) => respond(stream, 200, "text/html; charset=utf-8", html.as_bytes()),
+ Ok(None) | Err(_) => not_found(stream),
+ }
+}
+
+/// `GET /v1/repos/<owner>/<name>/<what>`: a hosted repository read through
+/// the API, for sessions and the page. `q` is the query reader of `api`.
+fn repo_read(rest: &str, q: &dyn Fn(&str) -> Option<String>) -> Result<(u16, Value)> {
+ let mut parts = rest.splitn(3, '/');
+ let (Some(owner), Some(name), Some(what)) = (parts.next(), parts.next(), parts.next()) else {
+ return Ok((404, json!({"error": "repos/<owner>/<name>/show|log|branches|commit"})));
+ };
+ let repo = crate::mirror::repo_name(&format!("{owner}/{name}"))?;
+ if !crate::hosted::is_hosted(&repo) {
+ return Ok((404, json!({"error": format!("{} is not hosted here (a Forgejo project: the forgejo_* tools read it)", repo.trim_end_matches(".git"))})));
+ }
+ let rev = q("rev").map(|r| pct_decode(&r));
+ let v = match what {
+ "show" => crate::hosted::show(&repo, rev.as_deref(), &pct_decode(&q("path").unwrap_or_default()))?,
+ "log" => json!(crate::hosted::log(&repo, rev.as_deref(), q("n").and_then(|n| n.parse().ok()).unwrap_or(30))?),
+ "branches" => json!(crate::hosted::branches(&repo)?),
+ "commit" => crate::hosted::commit(&repo, &rev.unwrap_or_else(|| "HEAD".into()))?,
+ _ => return Ok((404, json!({"error": "show, log, branches or commit"}))),
+ };
+ Ok((200, v))
+}
+
/// The callers allowed to use the hub's Forgejo proxy: `/srv/midas/callers.json`,
/// `{"<name>": {"key": "<random>", "token": "<Forgejo token>", "api"?: "…"}}`,
/// readable by the hub's user only. A caller is a trust level (the agent
@@ -1782,7 +1949,7 @@ pub fn pct_encode(s: &str) -> String {
s.bytes().map(|b| if b.is_ascii_alphanumeric() || b" .,-_()!?'".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect()
}
-fn pct_decode(s: &str) -> String {
+pub(crate) fn pct_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
diff --git a/src/hubsetup.rs b/src/hubsetup.rs
index 39678e2..0e8d3fc 100644
--- a/src/hubsetup.rs
+++ b/src/hubsetup.rs
@@ -156,7 +156,9 @@ pub fn refresh_ssh() -> Result<()> {
Some(format!("restrict,command=\"{BIN} hub git --node {}\" {} midas-node-{}\n",
n["id"].as_str()?, n["git_key"].as_str()?, n["id"].as_str()?))
}).collect();
- let head = "# Written by the midas hub from its node list; nodes register their own keys.\n";
+ // And the person's and agents' keys for the repositories the hub hosts.
+ let keys = keys + &crate::hosted::authorized_lines(BIN);
+ let head = "# Written by the midas hub from its node list and its git keys; nodes register their own.\n";
write_if_changed(&format!("{ssh}/authorized_keys"), &format!("{head}{keys}"), 0o600)?;
Ok(())
}
diff --git a/src/main.rs b/src/main.rs
index 804b671..61cc542 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -34,6 +34,8 @@ mod handoff;
mod hook;
mod host;
mod hub;
+mod codeview;
+mod hosted;
mod hubsetup;
mod import;
mod mcp;
@@ -157,6 +159,9 @@ enum Cmd {
/// Another repository, `owner/name` (default: this checkout's origin).
#[arg(long)]
repo: Option<String>,
+ /// Make a project the hub hosts, change one, or read one without a checkout.
+ #[command(subcommand)]
+ act: Option<ProjectCmd>,
},
/// The shared workflow skills and the session hooks, in ~/.claude.
#[command(subcommand)]
@@ -408,6 +413,9 @@ enum Cmd {
#[arg(long)]
command: Option<String>,
},
+ /// Whose this worktree is, as the hub names it (a landing's turn, a lease).
+ #[command(hide = true)]
+ Whoami,
/// The node this worktree holds, as JSON (exit 1 if none).
#[command(hide = true)]
Mine,
@@ -1037,11 +1045,23 @@ enum HubCmd {
#[arg(long)]
listen: Option<String>,
},
- /// The hub sshd's command for a node's key: git fetches and LFS auth, nothing else.
+ /// The hub sshd's command for a node's key (git fetches and LFS auth,
+ /// nothing else), or for a person's or an agent's (`--key`), which also
+ /// pushes the repositories the hub hosts.
Git {
- #[arg(long)]
- node: String,
+ #[arg(long, required_unless_present = "key")]
+ node: Option<String>,
+ #[arg(long, conflicts_with = "node")]
+ key: Option<String>,
},
+ /// A hosted repository's pre-receive hook: may this key move these refs?
+ PreReceive,
+ /// A hosted repository's post-receive hook: tell the hub what moved.
+ PostReceive,
+ /// The keys that push and fetch the repositories the hub hosts. Run on the
+ /// hub as its user: `sudo -u midas midas hub git-key …`.
+ #[command(subcommand)]
+ GitKey(GitKeyCmd),
/// Warm every free node that is cold, over its ceiling or stale (a timer runs it),
/// then mail any node problem that has lasted an hour.
Warm {
@@ -1199,6 +1219,78 @@ enum HookCmd {
},
}
+#[derive(Subcommand)]
+pub enum ProjectCmd {
+ /// A new project, its repository hosted by the hub (docs/git-hosting.md):
+ /// a first commit on main, its landing, and the URL to clone. Then
+ /// `project_add` (or `midas sessions add-project`) brings it into a session.
+ Create {
+ name: String,
+ /// What it is: the README's first line.
+ #[arg(long, default_value = "")]
+ description: String,
+ /// Readable by anyone, without a login. Private (the default) is the
+ /// workspace's only; making a private project public later is the person's.
+ #[arg(long)]
+ public: bool,
+ /// Its landing gate, a command run on a build node (unset: no landing until set).
+ #[arg(long)]
+ gate: Option<String>,
+ #[arg(long)]
+ gate_nodes: Option<String>,
+ /// Whose namespace (default: the workspace's first project's owner).
+ #[arg(long)]
+ owner: Option<String>,
+ },
+ /// Change a hosted project's landing or description (`--public` is the person's).
+ Set {
+ repo: String,
+ #[arg(long)]
+ gate: Option<String>,
+ #[arg(long)]
+ gate_nodes: Option<String>,
+ #[arg(long)]
+ pre_land: Option<String>,
+ #[arg(long)]
+ description: Option<String>,
+ #[arg(long, conflicts_with = "private")]
+ public: bool,
+ #[arg(long)]
+ private: bool,
+ },
+ /// A file or directory of a hosted project, without a checkout.
+ Show {
+ repo: String,
+ #[arg(default_value = "")]
+ path: String,
+ #[arg(long)]
+ rev: Option<String>,
+ },
+ /// A hosted project's last commits.
+ Log {
+ repo: String,
+ #[arg(long)]
+ rev: Option<String>,
+ #[arg(short, default_value_t = 20)]
+ n: usize,
+ },
+}
+
+#[derive(Subcommand)]
+pub enum GitKeyCmd {
+ /// Let a key push and fetch: `--role person` may do anything, `agent` every
+ /// branch but main, and main only from a landing.
+ Add {
+ name: String,
+ #[arg(long)]
+ role: String,
+ /// The public key, `ssh-ed25519 AAAA…`.
+ key: String,
+ },
+ Remove { name: String },
+ List,
+}
+
#[derive(Subcommand)]
enum MemoryCmd {
/// Merge this checkout's memory directory with the hub's: this repository's
@@ -1342,7 +1434,8 @@ fn run(cmd: Cmd, owner: Option<String>) -> anyhow::Result<i32> {
Cmd::Land(LandCmd::Release { outcome, sha }) => cli::land_release(&who(), outcome.as_deref(), sha.as_deref()),
Cmd::Land(LandCmd::Status) => cli::land_status(),
Cmd::Land(LandCmd::Targets { base, pick, record, json }) => cli::land_targets(base.as_deref(), pick.as_deref(), record, json, &who()),
- Cmd::Project { get, repo } => cli::project(get.as_deref(), repo),
+ Cmd::Project { act: Some(a), .. } => cli::project_act(a, &who()),
+ Cmd::Project { get, repo, act: None } => cli::project(get.as_deref(), repo),
Cmd::Claude(c) => {
let home = PathBuf::from(std::env::var("HOME").map_err(|_| anyhow::anyhow!("no HOME"))?);
match c {
@@ -1469,6 +1562,10 @@ fn run(cmd: Cmd, owner: Option<String>) -> anyhow::Result<i32> {
}
Cmd::Renew { command } => cli::renew(&who(), command.as_deref()),
Cmd::Mine => cli::mine(&who()),
+ Cmd::Whoami => {
+ println!("{}", who());
+ Ok(0)
+ }
Cmd::Faster { than, machine, fastest_for } => {
let enc = crate::hub::pct_encode;
let v = client::get(&format!("/v1/faster?owner={}&machine={}&than={}{}", enc(&who()), enc(&machine), enc(&than),
@@ -1601,7 +1698,11 @@ fn run(cmd: Cmd, owner: Option<String>) -> anyhow::Result<i32> {
}
Cmd::Hub(HubCmd::Caller(CallerCmd::List)) => hubsetup::caller_list(),
Cmd::Hub(HubCmd::Caller(CallerCmd::Remove { name })) => hubsetup::caller_remove(&name),
- Cmd::Hub(HubCmd::Git { node }) => mirror::serve_git(&node),
+ Cmd::Hub(HubCmd::Git { node: Some(node), .. }) => mirror::serve_git(&node),
+ Cmd::Hub(HubCmd::Git { key, .. }) => mirror::serve_key(&key.unwrap_or_default()),
+ Cmd::Hub(HubCmd::PreReceive) => hosted::pre_receive(),
+ Cmd::Hub(HubCmd::PostReceive) => hosted::post_receive(),
+ Cmd::Hub(HubCmd::GitKey(c)) => cli::git_key(c),
Cmd::Hub(HubCmd::Warm { node, dry_run }) => warm::warm(node.as_deref(), dry_run),
Cmd::Hub(HubCmd::Backup) => hubsetup::backup(),
Cmd::Hub(HubCmd::DeployBuild) => deploy::build_pending(),
diff --git a/src/mcp.rs b/src/mcp.rs
index 97f453e..f3e867e 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -202,7 +202,17 @@ fn tools() -> Vec<Value> {
tool("devices", "The devices paired to the hub (an app on the person's phone): online or not, and the tools each offers. A session opened after a device was paired has its tools as an MCP server of their own; this and device_call are for one paired since.", json!({}), &[]),
tool("device_call", "Call one tool of a paired device (see devices), relayed through the hub while its app is open. Pictures are saved and shown to the person.",
json!({"device": s("the device's id, from devices"), "tool": s("the tool's name"), "arguments": json!({"type": "object"})}), &["device", "tool"]),
- 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!({}), &[]),
+ tool("project_create", "Make a new project, its git repository hosted by the hub (no Forgejo, nobody's hand needed): a first commit on main, its landing gate, a URL to clone. Then project_add brings it into this session. Private unless public is true; turning a private project public later is the person's.",
+ json!({"name": s("the project's name: letters, digits, - and _"), "description": s("what it is, one line"),
+ "public": json!({"type": "boolean", "description": "readable by anyone without a login"}),
+ "gate": s("its landing gate: a command run on a build node in the checkout; unset, it cannot land until set"),
+ "gate_nodes": s("which nodes may gate it: any (default), gpu, or a machine")}), &["name"]),
+ 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_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!({}), &[]),
tool("node_readings", "Each node's latest heartbeat: memory used against its limit, OOM kills, free disk, load, the GPU's shared memory pool, what its checkout is at and warm for, and how long ago it reported.",
json!({"node": s("only this node")}), &[]),
tool("node_drain", "Take a node out of the pool on purpose, with a reason (a current lease runs on; nobody new gets it, the warmer included). Stays drained until node_undrain.",
@@ -271,6 +281,42 @@ fn call(name: &str, a: &Value) -> Result<String> {
None => String::new(),
}).collect::<Vec<_>>().join("\n"))
}
+ "project_create" => {
+ let mut b = json!({"owner": crate::client::setting("MIDAS_OWNER").unwrap_or_default(),
+ "name": arg(a, "name").context("name is required")?, "public": a.get("public").and_then(Value::as_bool) == Some(true)});
+ for k in ["description", "gate", "gate_nodes"] {
+ if let Some(v) = arg(a, k) {
+ b[k] = json!(v);
+ }
+ }
+ crate::client::post("/v1/projects/create", &b).map(|v| v.to_string())
+ }
+ "project_set" => {
+ let mut b = json!({"owner": crate::client::setting("MIDAS_OWNER").unwrap_or_default(), "repo": arg(a, "repo").context("repo is required")?});
+ for k in ["gate", "gate_nodes", "pre_land", "description"] {
+ if let Some(v) = a.get(k).and_then(Value::as_str) {
+ b[k] = json!(v);
+ }
+ }
+ if let Some(p) = a.get("public").and_then(Value::as_bool) {
+ b["public"] = json!(p);
+ }
+ crate::client::post("/v1/projects/set", &b).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");
+ let enc = crate::hub::pct_encode;
+ let mut q = vec![];
+ if let Some(p) = arg(a, "path") {
+ q.push(format!("path={}", enc(p)));
+ }
+ if let Some(r) = arg(a, "rev") {
+ q.push(format!("rev={}", enc(r)));
+ }
+ crate::client::get(&format!("/v1/repos/{}/{what}?{}", repo.trim_end_matches(".git"), q.join("&")))
+ .map(|v| v["text"].as_str().map(str::to_string).unwrap_or_else(|| serde_json::to_string_pretty(&v).unwrap_or_default()))
+ }
"workspace_check" => Ok(String::from_utf8_lossy(&Command::new(crate::util::exe()?).arg("check").output()?.stdout).to_string()),
"nodes_log" => {
let mut v = vec!["log".to_string(), "--since".into(), arg(a, "since").unwrap_or("2h").into()];
diff --git a/src/mirror.rs b/src/mirror.rs
index f2953ae..5109f6e 100644
--- a/src/mirror.rs
+++ b/src/mirror.rs
@@ -80,19 +80,29 @@ fn allowed(repo: &str) -> bool {
crate::conf::hub().allows(repo)
}
+/// A hosted repository is its own mirror (hosted.rs): nothing to fetch.
pub fn mirror_path(repo: &str) -> PathBuf {
+ if crate::hosted::is_hosted(repo) {
+ return crate::hosted::path(repo);
+ }
base().join("mirrors").join(repo)
}
/// Fetch now, however recently it was fetched: a deploy is asked for seconds
/// after the push it publishes.
pub fn fetch_now(repo: &str) -> Result<()> {
+ if crate::hosted::is_hosted(repo) {
+ return Ok(());
+ }
let _ = fs::remove_file(mirror_path(repo).join("midas-fetched"));
refresh(repo)
}
/// Bring the mirror up to date with Forgejo, creating it the first time.
pub fn refresh(repo: &str) -> Result<()> {
+ if crate::hosted::is_hosted(repo) {
+ return Ok(());
+ }
let path = mirror_path(repo);
let stamp = path.join("midas-fetched");
let age = fs::metadata(&stamp)
@@ -209,6 +219,58 @@ pub fn serve_git(node: &str) -> Result<i32> {
}
}
+/// The hub's `authorized_keys` command for a person's or an agent's key
+/// (`hosted::add_key`): fetch any repository the hub serves, push those it
+/// hosts — main guarded by the repository's pre-receive hook (`hosted::may_push`).
+pub fn serve_key(name: &str) -> Result<i32> {
+ let Some(role) = crate::hosted::role_of(name) else {
+ log("git_refused", json!({"key": name, "why": "no such key"}));
+ bail!("this key is no longer let in");
+ };
+ let cmd = std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default();
+ match git_ask(&cmd)? {
+ GitAsk::Fetch(repo) => {
+ if !allowed(&repo) {
+ bail!("{repo} is not a repository of the workspace");
+ }
+ refresh(&repo)?;
+ let err = Command::new("git").args(["upload-pack", &mirror_path(&repo).to_string_lossy()]).exec();
+ bail!("could not start git upload-pack: {err}")
+ }
+ GitAsk::Push => {
+ let (_, rest) = cmd.split_once(' ').unwrap_or((&cmd, ""));
+ let repo = repo_name(rest)?;
+ if !crate::hosted::is_hosted(&repo) {
+ bail!("{repo} is on Forgejo: push it there (only repositories the hub hosts take pushes here)");
+ }
+ log("git_push", json!({"key": name, "repo": repo}));
+ let err = Command::new("git").args(["receive-pack", &crate::hosted::path(&repo).to_string_lossy()])
+ .env("MIDAS_GIT_KEY", name).env("MIDAS_GIT_ROLE", &role).exec();
+ bail!("could not start git receive-pack: {err}")
+ }
+ GitAsk::Lfs(repo, op) => {
+ if !allowed(&repo) || op == "upload" && !crate::hosted::is_hosted(&repo) {
+ bail!("LFS {op} of {repo} is not offered here");
+ }
+ let token = issue_token_for(&repo, name, &op)?;
+ println!("{}", json!({
+ "href": format!("{}/lfs/{repo}/info/lfs", hub_url()),
+ "header": {"Authorization": format!("Bearer {token}")},
+ "expires_in": TOKEN_SECS,
+ }));
+ Ok(0)
+ }
+ GitAsk::Transfer => {
+ eprintln!("git-lfs-transfer is not offered; use git-lfs-authenticate");
+ Ok(1)
+ }
+ GitAsk::Other(cmd) => {
+ log("git_refused", json!({"key": name, "command": cmd.chars().take(120).collect::<String>()}));
+ bail!("this key may only fetch and push git and LFS objects")
+ }
+ }
+}
+
fn hub_url() -> String {
crate::conf::hub().url()
}
@@ -217,7 +279,7 @@ fn hub_url() -> String {
/// which cannot write the log on the agent volume (root-only from the host), so
/// it goes through the hub's event endpoint as nodes do; `hub serve` (root) falls
/// back to writing directly if the endpoint is not answering.
-fn log(kind: &str, mut fields: Value) {
+pub fn log(kind: &str, mut fields: Value) {
fields["kind"] = json!(kind);
let posted = crate::hub::request(&hub_url(), "POST", "/v1/events", Some(&fields.to_string()))
.map(|(code, _)| code == 204)
@@ -249,6 +311,66 @@ fn issue_token(repo: &str, node: &str) -> Result<String> {
Ok(t)
}
+/// A token for an LFS `op` (`download`, or `upload` to a hosted repository) by
+/// a person's or an agent's key.
+fn issue_token_for(repo: &str, key: &str, op: &str) -> Result<String> {
+ let t = random_hex(24)?;
+ fs::create_dir_all(tokens_dir())?;
+ let mut f = fs::File::create(tokens_dir().join(&t))?;
+ writeln!(f, "{}", json!({"repo": repo, "key": key, "op": op}))?;
+ Ok(t)
+}
+
+/// The repository and operation a valid, unexpired token was issued for (a
+/// node's tokens are downloads).
+pub fn check_token_op(token: &str) -> Option<(String, String)> {
+ if token.is_empty() || !token.bytes().all(|b| b.is_ascii_hexdigit()) {
+ return None;
+ }
+ let p = tokens_dir().join(token);
+ let age = SystemTime::now().duration_since(fs::metadata(&p).ok()?.modified().ok()?).ok()?;
+ if age > Duration::from_secs(TOKEN_SECS) {
+ let _ = fs::remove_file(&p);
+ return None;
+ }
+ let v: Value = serde_json::from_str(fs::read_to_string(&p).ok()?.trim()).ok()?;
+ Some((v["repo"].as_str()?.to_string(), v["op"].as_str().unwrap_or("download").to_string()))
+}
+
+/// Keep an uploaded LFS object of a hosted repository: `len` bytes from
+/// `from`, kept only when they hash to `oid`. The cache is the store for those.
+pub fn store_object(oid: &str, from: &mut impl std::io::Read, len: u64) -> Result<()> {
+ use sha2::{Digest, Sha256};
+ if !valid_oid(oid) {
+ bail!("not an LFS object id");
+ }
+ let dest = lfs_cache(oid);
+ fs::create_dir_all(dest.parent().unwrap())?;
+ let tmp = dest.with_extension(format!("part-{}", std::process::id()));
+ let mut f = fs::File::create(&tmp)?;
+ let mut hash = Sha256::new();
+ let mut left = len;
+ let mut buf = vec![0u8; 1 << 16];
+ while left > 0 {
+ let want = left.min(buf.len() as u64) as usize;
+ let n = from.read(&mut buf[..want])?;
+ if n == 0 {
+ break;
+ }
+ hash.update(&buf[..n]);
+ f.write_all(&buf[..n])?;
+ left -= n as u64;
+ }
+ let got = data_encoding::HEXLOWER.encode(&hash.finalize());
+ if left > 0 || got != oid {
+ let _ = fs::remove_file(&tmp);
+ bail!("the upload is not object {oid}");
+ }
+ f.sync_all()?;
+ fs::rename(&tmp, &dest)?;
+ Ok(())
+}
+
/// The repository a valid, unexpired token was issued for.
pub fn check_token(token: &str) -> Option<String> {
if token.is_empty() || !token.bytes().all(|b| b.is_ascii_hexdigit()) {
@@ -298,6 +420,10 @@ fn forgejo_lfs(repo: &str) -> Result<(String, String)> {
/// Forgejo in one batch. Returns the oids that could not be had.
pub fn ensure_cached(repo: &str, objects: &[(String, u64)]) -> Result<Vec<String>> {
let missing: Vec<&(String, u64)> = objects.iter().filter(|(o, _)| !lfs_cache(o).exists()).collect();
+ // A hosted repository's objects are uploaded here: what is not, is not anywhere.
+ if crate::hosted::is_hosted(repo) {
+ return Ok(missing.iter().map(|(o, _)| o.clone()).collect());
+ }
if missing.is_empty() {
return Ok(vec![]);
}
@@ -366,6 +492,9 @@ pub fn cached_object(oid: &str) -> Option<PathBuf> {
/// The batch response nodes get: every object they can have points at the hub,
/// at the address the request came to (`host`), which is the one the node can reach.
pub fn batch(repo: &str, body: &Value, token: &str, host: &str) -> Result<Value> {
+ if body["operation"] == "upload" {
+ return batch_upload(repo, body, token, host);
+ }
if body["operation"] != "download" {
bail!("only downloads");
}
@@ -396,6 +525,29 @@ pub fn batch(repo: &str, body: &Value, token: &str, host: &str) -> Result<Value>
}))
}
+/// An upload to a hosted repository, with a token issued for one: each object
+/// the store lacks gets a PUT to the hub; one it has, none.
+fn batch_upload(repo: &str, body: &Value, token: &str, host: &str) -> Result<Value> {
+ if !crate::hosted::is_hosted(repo) || check_token_op(token).map(|(_, op)| op).as_deref() != Some("upload") {
+ bail!("uploads go only to a repository the hub hosts, with an upload token");
+ }
+ let hub = crate::registry::hub_url_at(host).unwrap_or_else(hub_url);
+ let objects: Vec<Value> = body["objects"].as_array().into_iter().flatten().filter_map(|o| {
+ let oid = o["oid"].as_str().filter(|o| valid_oid(o))?;
+ let size = o["size"].as_u64().unwrap_or(0);
+ Some(if lfs_cache(oid).exists() {
+ json!({"oid": oid, "size": size, "authenticated": true})
+ } else {
+ json!({"oid": oid, "size": size, "authenticated": true, "actions": {"upload": {
+ "href": format!("{hub}/lfs/objects/{oid}"),
+ "header": {"Authorization": format!("Bearer {token}")},
+ "expires_in": TOKEN_SECS,
+ }}})
+ })
+ }).collect();
+ Ok(json!({"transfer": "basic", "objects": objects}))
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/registry.rs b/src/registry.rs
index c59a44f..4f72e16 100644
--- a/src/registry.rs
+++ b/src/registry.rs
@@ -1020,6 +1020,13 @@ pub fn land_release(owner: &str, outcome: Option<&str>, sha: Option<&str>) -> Re
Ok(false)
}
+/// The session holding the turn to land, if one does: a hosted repository's
+/// pre-receive hook moves main only for it (`hosted::may_push`).
+pub fn land_holder() -> Option<String> {
+ let reg = Locked::open().ok()?;
+ reg.landing()["holder"]["owner"].as_str().map(str::to_string)
+}
+
/// The git server said a branch moved (its post-receive hook, through the hub).
/// Kept beside the queue, so `status` can say what the warm branch is now.
pub fn note_push(repo: &str, refname: &str, old: &str, new: &str) -> Result<()> {
diff --git a/src/sessions.rs b/src/sessions.rs
index 2c7ddd0..70978d4 100644
--- a/src/sessions.rs
+++ b/src/sessions.rs
@@ -113,7 +113,8 @@ fn folder_brief(id: &str, dir: &Path, repos: &[String]) -> String {
format!("\n\nYou run in {}, this session's own folder, which is not a repository. The workspace's projects are {} ({}); \
this session works in {now}. When the task needs a project's code — to read it, change it or build it — add the project \
with the midas MCP tool `project_add` (`project: \"<name>\"`, or `midas sessions add-project <name>`): it makes a worktree of it at ./<name>, on \
- branch session/{id} off its main, and links its skills here. Add as many as the task spans and no more; a question that \
+ branch session/{id} off its main, and links its skills here. A project that does not exist yet is made with `project_create` (the hub hosts it; \
+ nobody need set it up by hand), then added. Add as many as the task spans and no more; a question that \
needs no code needs none. Work in each worktree as in a checkout of its own: read its CLAUDE.md first, commit there, and \
run builds (`ssh <node> …`, which sends the node the worktree you run it from) and the finish-branch skill from inside it. \
Each project lands on its own: when a change in one needs a change in another, land the one depended on first, and make \
@@ -600,7 +601,11 @@ pub fn repos_of(m: &Value) -> Vec<String> {
pub fn projects() -> Value {
let conf = crate::conf::hub();
let git = conf.forgejo_ssh.trim_end_matches('/').to_string();
- json!(project_names().iter().map(|r| json!({"repo": r, "name": r.rsplit('/').next(), "git": format!("{git}/{r}.git")})).collect::<Vec<_>>())
+ json!(project_names().iter().map(|r| {
+ // A project the hub hosts is cloned from the hub, by key (hosted.rs).
+ let url = if crate::hosted::is_hosted(r) { crate::hosted::url(r) } else { format!("{git}/{r}.git") };
+ json!({"repo": r, "name": r.rsplit('/').next(), "git": url, "hosted": crate::hosted::is_hosted(r)})
+ }).collect::<Vec<_>>())
}
pub(crate) fn project_names() -> Vec<String> {
diff --git a/src/tests.rs b/src/tests.rs
index e5c4d5e..a58cb12 100644
--- a/src/tests.rs
+++ b/src/tests.rs
@@ -2692,3 +2692,120 @@ fn a_free_gpu_node_somebody_waits_for_is_theirs() {
assert!(!claim("a", "any", None, false), "the freed GPU node is queued behind w");
assert!(claim("w", "gpu", None, true));
}
+
+// ── Repositories the hub hosts (hosted.rs) ───────────────────────────────────
+
+fn sh(dir: &std::path::Path, args: &[&str]) -> String {
+ 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()
+}
+
+fn new_project(name: &str, public: bool) -> serde_json::Value {
+ crate::hosted::create(&crate::hosted::New {
+ owner: "acme", name, description: "A test project", public, gate: Some("true"), gate_nodes: None, by: "test",
+ }).unwrap()
+}
+
+#[test]
+fn a_new_project_is_a_hosted_repository_with_a_main_and_a_landing() {
+ let _g = SERIAL.lock().unwrap();
+ scratch("hosted-create");
+ let v = new_project("widget", false);
+ assert_eq!(v["repo"], "acme/widget");
+ let dir = crate::hosted::path("acme/widget");
+ assert!(dir.join("hooks/pre-receive").exists() && dir.join("hooks/post-receive").exists());
+ assert_eq!(sh(&dir, &["show", "main:README.md"]), "# widget\n\nA test project");
+ assert!(crate::hosted::create(&crate::hosted::New {
+ owner: "acme", name: "widget", description: "", public: false, gate: None, gate_nodes: None, by: "test",
+ }).is_err(), "never twice");
+ assert!(crate::hosted::create(&crate::hosted::New {
+ owner: "acme", name: "../x", description: "", public: false, gate: None, gate_nodes: None, by: "test",
+ }).is_err(), "a name does not walk out");
+ // The workspace sees it as a project like any other.
+ let conf = crate::conf::hub();
+ assert!(conf.allows("acme/widget.git"));
+ let p = conf.project("acme/widget").unwrap();
+ assert_eq!((p["gate"].as_str(), p["host"].as_str(), p["main"].as_str()), (Some("true"), Some("midas"), Some("main")));
+ assert_eq!(crate::mirror::mirror_path("acme/widget.git"), dir, "its own mirror");
+ let listed = crate::sessions::projects();
+ let w = listed.as_array().unwrap().iter().find(|p| p["repo"] == "acme/widget").unwrap();
+ assert!(w["git"].as_str().unwrap().starts_with("midas@") && w["hosted"] == true, "{w}");
+ // Reading without a checkout.
+ assert_eq!(crate::hosted::show("acme/widget", None, "").unwrap()["entries"][0]["name"], "README.md");
+ assert_eq!(crate::hosted::log("acme/widget", None, 5).unwrap().len(), 1);
+}
+
+#[test]
+fn an_agent_moves_main_only_forward_from_the_landing_with_a_pass() {
+ let _g = SERIAL.lock().unwrap();
+ scratch("hosted-push");
+ new_project("gadget", false);
+ let dir = crate::hosted::path("acme/gadget");
+ let old = sh(&dir, &["rev-parse", "main"]);
+ // A commit on top of main, and one beside it, made in the bare repository.
+ let tree = sh(&dir, &["rev-parse", "main^{tree}"]);
+ let on_top = sh(&dir, &["commit-tree", &tree, "-p", &old, "-m", "on top"]);
+ let beside = sh(&dir, &["commit-tree", &tree, "-m", "beside"]);
+ fn to<'a>(old: &'a str, new: &'a str) -> Vec<crate::hosted::Update<'a>> {
+ vec![crate::hosted::Update { old, new, refname: "refs/heads/main" }]
+ }
+ let may = |role: &str, owner: Option<&str>, u: &[crate::hosted::Update]| crate::hosted::may_push(role, owner, "acme/gadget", u);
+ // Any other branch, as an agent likes.
+ let zero = "0000000000000000000000000000000000000000";
+ assert!(may("agent", None, &[crate::hosted::Update { old: zero, new: &beside, refname: "refs/heads/session/s1" }]).is_ok());
+ // Main: not without a landing, not to a head without a pass, never backwards.
+ assert!(may("agent", None, &to(&old, &on_top)).unwrap_err().contains("landing"));
+ assert!(land("s1"));
+ assert!(may("agent", Some("s2"), &to(&old, &on_top)).unwrap_err().contains("does not hold the turn"));
+ assert!(may("agent", Some("s1"), &to(&old, &on_top)).unwrap_err().contains("no gate pass"));
+ crate::deploy::record_verified(&on_top, "test", &json!({"node": "cpu-1"})).unwrap();
+ assert!(may("agent", Some("s1"), &to(&old, &on_top)).is_ok(), "the landing, forward, gated");
+ crate::deploy::record_verified(&beside, "test", &json!({"node": "cpu-1"})).unwrap();
+ assert!(may("agent", Some("s1"), &to(&old, &beside)).unwrap_err().contains("only forward"));
+ assert!(may("agent", Some("s1"), &to(&old, zero)).unwrap_err().contains("never deleted"));
+ // The person may do anything; a node's key nothing.
+ assert!(may("person", None, &to(&old, &beside)).is_ok());
+ assert!(may("node", None, &to(&old, &on_top)).is_err());
+}
+
+#[test]
+fn only_the_person_makes_a_project_public_and_keys_become_git_only_logins() {
+ let _g = SERIAL.lock().unwrap();
+ scratch("hosted-set");
+ new_project("secret", false);
+ assert!(!crate::hosted::is_public("acme/secret"));
+ let e = crate::hosted::set("acme/secret", &json!({"public": true}), "agent", false).unwrap_err();
+ assert!(format!("{e:#}").contains("the person's"), "{e:#}");
+ crate::hosted::set("acme/secret", &json!({"gate": "cargo test", "description": "Now described"}), "agent", false).unwrap();
+ assert_eq!(crate::conf::hub().project("acme/secret").unwrap()["gate"], "cargo test");
+ crate::hosted::set("acme/secret", &json!({"public": true}), "person", true).unwrap();
+ assert!(crate::hosted::is_public("acme/secret"));
+ crate::hosted::set("acme/secret", &json!({"public": false}), "agent", false).unwrap();
+ assert!(!crate::hosted::is_public("acme/secret"), "back to private: anyone may");
+ // Keys.
+ assert!(crate::hosted::add_key("box", "root", "ssh-ed25519 AAAA x", "t").is_err());
+ assert!(crate::hosted::add_key("box", "agent", "not a key", "t").is_err());
+ crate::hosted::add_key("box", "agent", "ssh-ed25519 AAAAC3Nz comment here", "t").unwrap();
+ let lines = crate::hosted::authorized_lines("/usr/local/bin/midas");
+ assert_eq!(lines, "restrict,command=\"/usr/local/bin/midas hub git --key box\" ssh-ed25519 AAAAC3Nz midas-key-box\n");
+ assert_eq!(crate::hosted::role_of("box").as_deref(), Some("agent"));
+ assert!(crate::hosted::remove_key("box", "t").unwrap());
+ assert!(crate::hosted::authorized_lines("x").is_empty());
+}
+
+#[test]
+fn a_public_repository_has_pages_and_a_private_one_none() {
+ let _g = SERIAL.lock().unwrap();
+ scratch("hosted-view");
+ new_project("open", true);
+ let home = crate::codeview::page("acme/open.git", "midas.example", "", "").unwrap().unwrap();
+ assert!(home.contains("README.md") && home.contains("A test project") && home.contains("git clone https://midas.example/git/acme/open.git"));
+ let log = crate::codeview::page("acme/open.git", "h", "log", "").unwrap().unwrap();
+ assert!(log.contains("Start open"));
+ assert!(crate::codeview::page("acme/open.git", "h", "nowhere", "").unwrap().is_none());
+ let file = crate::codeview::page("acme/open.git", "h", "tree/README.md", "").unwrap().unwrap();
+ assert!(file.contains("<pre># open"), "{file}");
+}