infra: agent runner, builder sandbox and compose project
- Commit
8238b14f7e9b632401714d878800648f86846598- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-05 00:15 UTC (1 month ago)
- Parents
e783c32
The sandbox side of the on-server coding-agent system: an HTTP runner inside a locked-down builder container, the compose project that hosts it alongside agentd, and the idempotent host-prep script. agent-runner (infra/agents/runner) is a Tokio+axum server implementing every proto route exactly (JSON bodies, ErrorBody on non-2xx, no auth: internal network only, inside the untrusted sandbox). Slots are plain checkouts at <slots-dir>/slot-N. Path ops resolve relative to the slot root and reject absolute paths, .. escapes, .git/ access, and symlinks resolving outside (canonicalizing the longest existing prefix, so new files through symlinked dirs are covered too). exec runs bash -lc in its own process group with concurrent stdio draining: Shell is niced, Build serializes on a single-permit semaphore (queued_ms reported) and runs ./gradlew --stop after kills/timeouts since daemons escape killpg. Output is capped (64 KiB/stream, head+tail). prepare clones --shared from the mirror, resets to origin/main, cleans -fd (keeping ignored warm caches), and records the base sha in .git/agent-base. diff stages untracked files then diffs vs base; bundle streams a thin base..branch pack for agentd's mirror import; search shells out to rg with build-artifact excludes, mapping zero-file globs to empty results. Security boundaries: the builder service runs as 10001:10001 with caps dropped (6 CPU / 14 GiB / 4k pids), on agents-internal (sealed) plus agents-egress (172.31.250.0/24), never the prod network; the host firewall drops sandbox egress to RFC1918/APIPA and container->host (INPUT) traffic. Toolchain/cache/slot volumes live in the 60 GiB loop-mounted builds image as bind-backed named volumes so Docker seeds image content on first use. Nothing touches the location-share project, its volumes (except a read-only release-lock mount), or snap Docker. Tested: 17 runner tests pass (confinement incl. symlink escape, edit 0/N-match 409s, truncation, timeout+group kill via heartbeat, cancel, build serialization with queued_ms, build-kill endpoint, full prepare->write->diff->commit->bundle against a temp bare mirror with bundle verify + fetch into a mirror clone); clippy clean for the runner crate; live HTTP smoke test of every route; bash -n on host-setup.sh (refuses non-Linux/non-root). Server-only verification still needed: compose config/up, image volume seeding, firewall behavior, and the real Gradle build path.
Diff
infra/agents/.env.example
diff --git a/infra/agents/.env.example b/infra/agents/.env.examplenew file mode 100644index 0000000000..ef81ae81b0--- /dev/null+++ b/infra/agents/.env.example@@ -0,0 +1,18 @@+# agentd environment (/root/agent-world/.env on the host).+# Copy to /root/agent-world/.env and fill in secrets. Never commit the file.+# Consumed via `env_file` by the agentd service only (builder/sandbox gets+# no secrets).++# OpenRouter API key for the coding model.+OPENROUTER_API_KEY=+# Argon2 PHC hash of the UI password (generate with e.g.+# `python3 -c "import argon2..."` or `mkpasswd --method=argon2id`).+AGENTD_PASSWORD_HASH=+# Git push token for the git.maproj.org mirror (agent branches push here).+GIT_AGENT_PUSH_TOKEN=+# Mirror origin for agent branches.+AGENTD_REPO_URL=https://git.maproj.org/Modern-Apps.git+# Public origin served by Caddy (agents.maproj.org -> agents-ui:8080).+AGENTD_PUBLIC_ORIGIN=https://agents.maproj.org+# Default model for coding turns.+AGENTD_DEFAULT_MODEL=
infra/agents/Cargo.lock
diff --git a/infra/agents/Cargo.lock b/infra/agents/Cargo.lockindex 7be9b6696f..db6a8ba86d 100644--- a/infra/agents/Cargo.lock+++ b/infra/agents/Cargo.lock@@ -6,9 +6,13 @@ version = 4 name = "agent-runner" version = "0.1.0" dependencies = [+ "axum",+ "libc", "proto", "serde", "serde_json",+ "tempfile",+ "tokio", ] [[package]]@@ -20,18 +24,338 @@ dependencies = [ "serde_json", ] +[[package]]+name = "async-trait"+version = "0.1.92"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "axum"+version = "0.7.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f"+dependencies = [+ "async-trait",+ "axum-core",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-util",+ "itoa",+ "matchit",+ "memchr",+ "mime",+ "percent-encoding",+ "pin-project-lite",+ "rustversion",+ "serde",+ "serde_json",+ "serde_path_to_error",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tower",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "axum-core"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199"+dependencies = [+ "async-trait",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "mime",+ "pin-project-lite",+ "rustversion",+ "sync_wrapper",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys",+]++[[package]]+name = "fastrand"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "futures-core"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"++[[package]]+name = "futures-task"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"++[[package]]+name = "futures-util"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"+dependencies = [+ "futures-core",+ "futures-task",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+]++[[package]]+name = "http"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "http-body"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"+dependencies = [+ "bytes",+ "http",+]++[[package]]+name = "http-body-util"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "pin-project-lite",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "httpdate"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"++[[package]]+name = "hyper"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "httparse",+ "httpdate",+ "itoa",+ "pin-project-lite",+ "smallvec",+ "tokio",+]++[[package]]+name = "hyper-util"+version = "0.1.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"+dependencies = [+ "bytes",+ "http",+ "http-body",+ "hyper",+ "pin-project-lite",+ "tokio",+ "tower-service",+]+ [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"++[[package]]+name = "matchit"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"+ [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"++[[package]]+name = "mio"+version = "1.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"+dependencies = [+ "libc",+ "wasi",+ "windows-sys",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"+ [[package]] name = "proc-macro2" version = "1.0.107"@@ -57,6 +381,52 @@ dependencies = [ "proc-macro2", ] +[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags",+]++[[package]]+name = "rustix"+version = "1.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"+dependencies = [+ "bitflags",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"+ [[package]] name = "serde" version = "1.0.229"@@ -100,6 +470,61 @@ dependencies = [ "zmij", ] +[[package]]+name = "serde_path_to_error"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"+dependencies = [+ "itoa",+ "serde",+ "serde_core",+]++[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]++[[package]]+name = "signal-hook-registry"+version = "1.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"+dependencies = [+ "errno",+ "libc",+]++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.16.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"++[[package]]+name = "socket2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"+dependencies = [+ "libc",+ "windows-sys",+]+ [[package]] name = "syn" version = "3.0.9"@@ -111,12 +536,128 @@ dependencies = [ "unicode-ident", ] +[[package]]+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"++[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom",+ "once_cell",+ "rustix",+ "windows-sys",+]++[[package]]+name = "tokio"+version = "1.54.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"+dependencies = [+ "bytes",+ "libc",+ "mio",+ "parking_lot",+ "pin-project-lite",+ "signal-hook-registry",+ "socket2",+ "tokio-macros",+ "windows-sys",+]++[[package]]+name = "tokio-macros"+version = "2.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tower"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+dependencies = [+ "futures-core",+ "futures-util",+ "pin-project-lite",+ "sync_wrapper",+ "tokio",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "tower-layer"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"++[[package]]+name = "tower-service"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "log",+ "pin-project-lite",+ "tracing-core",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+]+ [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]+ [[package]] name = "zmij" version = "1.0.23"
infra/agents/Dockerfile.builder
diff --git a/infra/agents/Dockerfile.builder b/infra/agents/Dockerfile.buildernew file mode 100644index 0000000000..128dec2b2b--- /dev/null+++ b/infra/agents/Dockerfile.builder@@ -0,0 +1,73 @@+# ---------------------------------------------------------------------------+# agents builder — the sandbox image agent code runs in.+#+# FROM location-share-builder:local (Ubuntu 24.04, JDK 21, Android SDK ++# NDK 29.0.14206865 at /opt/android-sdk, Rust 1.97 in /cargo-home,+# GRADLE_USER_HOME=/gradle-cache, /root/.cargo -> /cargo-home). On top it+# adds the agent-runner HTTP server plus the sandbox conventions the agents+# harness expects:+# - unprivileged `agent` user (uid/gid 10001); the `builder` compose+# service runs as this user,+# - /home/agent/.cargo -> /cargo-home (build-logic/RustNative.kt invokes+# $HOME/.cargo/bin/cargo and ignores CARGO_HOME),+# - baked /opt/agent/gradle.properties (copied into /gradle-cache by the+# builder-init service at first boot),+# - ripgrep for the runner's /search route.+#+# Build context is infra/agents (a Cargo workspace with proto, agentd,+# runner); only the runner is compiled in. The `location-share-builder:local`+# base must exist first (built from /root/location_share_server), so this+# image is built with `docker compose -p agents -f infra/agents/compose.yml+# build` on the host, never here.+#+# NOTE: the base image declares VOLUME ["/gradle-cache","/cargo-home",+# "/opt/android-sdk"]. A VOLUME path cannot be chowned in later RUN layers+# and becomes an anonymous volume if not mounted, so compose mounts all+# three explicitly (bind-backed named volumes seeded from the image).+# ---------------------------------------------------------------------------++# ---- stage 1: compile agent-runner ---------------------------------------+FROM rust:1-bookworm AS runner-build+WORKDIR /src+# Workspace layout: Cargo.toml + the three member crates. Copying only these+# keeps the build cache stable when unrelated tree files change.+COPY Cargo.toml Cargo.lock ./+COPY proto ./proto+COPY runner ./runner+# agentd has its own Dockerfile (another agent owns it); exclude it from this+# build so this image never depends on that crate.+RUN cargo build -p agent-runner --release --locked++# ---- stage 2: sandbox -------------------------------------------------------+FROM location-share-builder:local++ENV ANDROID_HOME=/opt/android-sdk \+ ANDROID_SDK_ROOT=/opt/android-sdk++RUN apt-get update && apt-get install -y --no-install-recommends \+ ripgrep \+ tini \+ && rm -rf /var/lib/apt/lists/*++# Unprivileged sandbox user. The compose file runs the builder service as+# 10001:10001 and bind-mounts the caches; /home/agent/.cargo mirrors the+# base image's /root/.cargo symlink so Gradle's RustNative.kt finds cargo.+RUN groupadd -g 10001 agent \+ && useradd -m -u 10001 -g 10001 -d /home/agent -s /bin/bash agent \+ && ln -sfn /cargo-home /home/agent/.cargo++COPY --from=runner-build /src/target/release/agent-runner /usr/local/bin/agent-runner++# Gradle memory/concurrency profile for the 6-CPU / 14 GB sandbox (smaller+# than release builds: 4 workers / 12 GB). builder-init copies this into+# /gradle-cache/gradle.properties on first boot; a repo-level+# gradle.properties is left untouched.+COPY gradle.properties /opt/agent/gradle.properties++WORKDIR /builds/slots++# Undo the base image's release ENTRYPOINT: this container serves the runner+# API instead. tini reaps stray grandchildren so killpg'd builds don't leak+# zombies into pid 1.+ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/agent-runner"]+CMD []
infra/agents/README.md
diff --git a/infra/agents/README.md b/infra/agents/README.mdnew file mode 100644index 0000000000..9f48f8b2f3--- /dev/null+++ b/infra/agents/README.md@@ -0,0 +1,31 @@+# Agents sandbox (compose project `agents`)++- Runner: `agent-runner` (Tokio+axum, `infra/agents/runner/`) serves the+ `proto` HTTP API from inside the sandbox: per-slot checkouts at+ `/builds/slots/slot-N`, `bash -lc` exec in its own process group (Build+ kind serialized on a single permit), path confinement, `git` ops.+- Image: `Dockerfile.builder` builds the runner, then extends+ `location-share-builder:local` with ripgrep, user `agent` (10001), and a+ small-Gradle profile; ENTRYPOINT runs the runner under tini.+- Isolation: `builder` runs as 10001, caps (6 CPU/14 GB/4k pids),+ `cap_drop: ALL`, no-new-privileges, only on `agents-internal` (sealed)+ and `agents-egress` (172.31.250.0/24, host-firewalled from RFC1918).+- Orchestrator: `agentd` (separate image) talks to `http://builder:7070`,+ serves the UI as `agents-ui` on prod net, pushes via the mirror volume.+- Release back-pressure: `release-signal` mirrors prod's+ `/srv/release_in_progress` into `/signal/release` for agentd to defer.++Deploy (once, on the host as root, from /root/agent-world/Modern-Apps):+1. `git clone <Modern-Apps> /root/agent-world/Modern-Apps`+2. Review `infra/agents/host-setup.sh`, then `sudo bash infra/agents/host-setup.sh`+3. Copy `infra/agents/.env.example` to `/root/agent-world/.env`, fill secrets+4. Ensure base exists: `docker compose -f /root/location_share_server/compose.yml --profile release build builder`+5. `docker compose -p agents -f infra/agents/compose.yml up -d --build`++Verify: `docker compose -p agents ps`; `docker exec agents-builder-1 curl -s localhost:7070/v1/health`;+agentd UI via Caddy; run one `agent/` task end to end, then check+`docker stats` (builder ≤ 6 CPU/14 GB) and `iptables -S DOCKER-USER`.++Stop/remove (never touches `location-share`):+`docker compose -p agents -f infra/agents/compose.yml down` (add `-v` to+drop agents-* volumes too; the builds image + mirror stay until deleted).
infra/agents/compose.yml
diff --git a/infra/agents/compose.yml b/infra/agents/compose.ymlnew file mode 100644index 0000000000..212e834d55--- /dev/null+++ b/infra/agents/compose.yml@@ -0,0 +1,204 @@+# Compose project `agents`: on-server coding-agent sandbox + orchestrator.+#+# Coexists with the prod `location-share` project (server, caddy, watcher):+# nothing here touches that project, its containers, or its volumes. The only+# shared state is read-only: the `location-share_srv-data` volume (release+# lock file) and the external `location-share_default` network (agentd gets+# the `agents-ui` alias on it so Caddy can route agents.maproj.org).+#+# Disk bounding: the toolchain/cache/slot volumes live inside+# /root/agent-world/builds (a size-bounded loop-mounted ext4 image created by+# host-setup.sh). Named volumes with local-driver bind options are used+# instead of plain bind mounts so that on first use Docker seeds /cargo-home+# and /opt/android-sdk from the builder image (plain binds would hide the+# image content behind empty host dirs).+#+# Run from the deploy checkout (/root/agent-world/Modern-Apps):+# docker compose -p agents -f infra/agents/compose.yml up -d --build++name: agents++services:+ # One-shot (runs once per `up`, as root): verifies the image-seeded+ # toolchain volumes arrived, installs gradle.properties, fixes ownership.+ builder-init:+ build:+ context: .+ dockerfile: Dockerfile.builder+ image: agents-builder:local+ pull_policy: build+ user: root+ # The image ENTRYPOINT runs the runner; override it: init runs a shell+ # script instead (compose `command` alone would only replace CMD args).+ entrypoint: ["/bin/bash"]+ volumes:+ - gradle-cache:/gradle-cache+ - cargo-home:/cargo-home+ - android-sdk:/opt/android-sdk+ - slots:/builds/slots+ command:+ - -c+ - |+ set -euo pipefail+ MARKER=/gradle-cache/.agents-init-done+ if [ -e "$$MARKER" ]; then echo "builder-init: already done, skipping"; exit 0; fi+ test -x /cargo-home/bin/cargo || { echo "builder-init: FATAL: /cargo-home/bin/cargo missing (image seeding of the cargo-home volume did not happen)" >&2; exit 1; }+ test -d /opt/android-sdk/ndk/29.0.14206865 || { echo "builder-init: FATAL: /opt/android-sdk/ndk/29.0.14206865 missing (image seeding of the android-sdk volume did not happen)" >&2; exit 1; }+ cp /opt/agent/gradle.properties /gradle-cache/gradle.properties+ chown -R 10001:10001 /gradle-cache /cargo-home /opt/android-sdk /builds/slots+ touch "$$MARKER"+ echo "builder-init: done"+ networks:+ - agents-internal+ restart: "no"++ # The sandbox: agent-runner as uid/gid 10001, capped well below the box so+ # the live server keeps headroom (box: 8 vCPU / 31 GiB; releases cap at+ # 5 CPU / 20 GB — never run an agent build during a release build).+ builder:+ build:+ context: .+ dockerfile: Dockerfile.builder+ image: agents-builder:local+ pull_policy: build+ user: "10001:10001"+ depends_on:+ builder-init:+ condition: service_completed_successfully+ cpus: 6+ mem_limit: 14g+ memswap_limit: 16g+ pids_limit: 4096+ cpu_shares: 256+ cap_drop:+ - ALL+ security_opt:+ - no-new-privileges:true+ restart: unless-stopped+ environment:+ RUNNER_LISTEN: "0.0.0.0:7070"+ RUNNER_SLOTS: "4"+ RUNNER_SLOTS_DIR: /builds/slots+ RUNNER_MIRROR: /mirror/Modern-Apps.git+ volumes:+ - gradle-cache:/gradle-cache+ - cargo-home:/cargo-home+ - android-sdk:/opt/android-sdk+ - slots:/builds/slots+ - agents-mirror:/mirror:ro+ networks:+ - agents-internal+ - agents-egress++ # The trusted orchestrator (another agent owns Dockerfile.agentd): talks to+ # the sandbox over agents-internal, serves the UI on location-share_default+ # as `agents-ui`, pushes via the mirror volume.+ agentd:+ build:+ context: .+ dockerfile: Dockerfile.agentd+ image: agents-agentd:local+ pull_policy: build+ env_file:+ - /root/agent-world/.env+ environment:+ AGENTD_RUNNER_URL: http://builder:7070+ AGENTD_STATE_DIR: /state+ AGENTD_MIRROR_DIR: /mirror/Modern-Apps.git+ AGENTD_RELEASE_SIGNAL: /signal/release+ AGENTD_LISTEN: "0.0.0.0:8080"+ AGENTD_SLOTS: "4"+ volumes:+ - agents-state:/state+ - agents-mirror:/mirror+ - agents-signal:/signal:ro+ mem_limit: 1g+ cap_drop:+ - ALL+ security_opt:+ - no-new-privileges:true+ restart: unless-stopped+ networks:+ agents-internal:+ location-share_default:+ aliases:+ - agents-ui++ # Mirrors the prod release lock into the agents world every 5s so agentd+ # can defer builds while a release runs. Watched path overridable for+ # testing via RELEASE_LOCK_FILE.+ release-signal:+ image: alpine:3.21+ environment:+ RELEASE_LOCK_FILE: /srv/release_in_progress+ volumes:+ - location-share_srv-data:/srv:ro+ - agents-signal:/signal+ command:+ - /bin/sh+ - -c+ - |+ LOCK="$${RELEASE_LOCK_FILE:-/srv/release_in_progress}";+ while true; do+ if [ -e "$$LOCK" ]; then touch /signal/release; else rm -f /signal/release; fi;+ sleep 5;+ done+ network_mode: none+ mem_limit: 32m+ cap_drop:+ - ALL+ restart: unless-stopped++volumes:+ # Toolchain/cache/slot data, bounded by the /root/agent-world/builds ext4+ # image. Bind-backed named volumes: Docker seeds image content+ # (/cargo-home toolchain, /opt/android-sdk) into them on first use.+ gradle-cache:+ driver: local+ driver_opts:+ type: none+ o: bind+ device: /root/agent-world/builds/gradle-cache+ cargo-home:+ driver: local+ driver_opts:+ type: none+ o: bind+ device: /root/agent-world/builds/cargo-home+ android-sdk:+ driver: local+ driver_opts:+ type: none+ o: bind+ device: /root/agent-world/builds/android-sdk+ slots:+ driver: local+ driver_opts:+ type: none+ o: bind+ device: /root/agent-world/builds/slots+ # agentd-owned: mirror checkout, persistent state, release signal flag.+ agents-mirror:+ agents-state:+ agents-signal:+ # Prod server state (external): release-signal reads only the+ # release_in_progress lock file from it. Must be declared external —+ # otherwise compose would create an empty project-scoped volume of the+ # same name instead of attaching the prod one.+ location-share_srv-data:+ external: true++networks:+ # Sandbox <-> agentd only. No route out (egress goes via agents-egress,+ # which the host firewall constrains).+ agents-internal:+ internal: true+ # Sandbox egress with a pinned subnet the host firewall rules reference.+ agents-egress:+ driver: bridge+ ipam:+ config:+ - subnet: 172.31.250.0/24+ # Prod stack network (external): agentd serves the UI here as `agents-ui`.+ location-share_default:+ external: true
infra/agents/gradle.properties
diff --git a/infra/agents/gradle.properties b/infra/agents/gradle.propertiesnew file mode 100644index 0000000000..2afd123bca--- /dev/null+++ b/infra/agents/gradle.properties@@ -0,0 +1,8 @@+# Gradle profile for the agent sandbox (6 vCPU / 14 GB container cap).+# builder-init copies this file to /gradle-cache/gradle.properties on first+# boot. Smaller than the release profile (4 workers / 12 GB heap) because the+# sandbox shares the box with the live server.+org.gradle.jvmargs=-Xmx6g -Xms512m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8+org.gradle.workers.max=5+kotlin.daemon.jvm.options=-Xmx1536m+org.gradle.daemon.idletimeout=1800000
infra/agents/host-setup.sh
diff --git a/infra/agents/host-setup.sh b/infra/agents/host-setup.shnew file mode 100755index 0000000000..c126ce9d64--- /dev/null+++ b/infra/agents/host-setup.sh@@ -0,0 +1,158 @@+#!/usr/bin/env bash+# ---------------------------------------------------------------------------+# agents host setup: one-time, idempotent preparation of the maproj host for+# the `agents` compose project (infra/agents/compose.yml).+#+# sudo bash infra/agents/host-setup.sh # apply+# sudo bash infra/agents/host-setup.sh --dry-run # print actions only+#+# Steps:+# (a) create /root/agent-world (0700),+# (b) add an 8 GiB swapfile /swapfile-agents (only if no swap is active;+# never touches existing swap),+# (c) create a sparse 60 GiB ext4 image /root/agent-world/builds.img,+# loop-mount it at /root/agent-world/builds via fstab, and create the+# gradle-cache / cargo-home / android-sdk / slots subdirs,+# (d) install a systemd oneshot (agents-firewall.service) that idempotently+# blocks sandbox-egress abuse: drops 172.31.250.0/24 -> RFC1918/APIPA+# in DOCKER-USER (established replies allowed first) and drops+# 172.31.250.0/24 -> host in INPUT (container->host services such as+# the wg-mail tunnel's 10.66.0.2:25 hit INPUT, not FORWARD).+#+# It never runs a docker command that changes state, and never touches+# /root/location_share_server, existing swap, or snap Docker itself.+# ---------------------------------------------------------------------------+set -euo pipefail++AGENT_WORLD=/root/agent-world+BUILDS_DIR=$AGENT_WORLD/builds+BUILDS_IMG=$AGENT_WORLD/builds.img+SWAPFILE=/swapfile-agents+EGRESS_SUBNET=172.31.250.0/24+FIREWALL_SERVICE=/etc/systemd/system/agents-firewall.service+FIREWALL_SCRIPT=/usr/local/sbin/agents-firewall.sh++DRY_RUN=0+if [[ "${1:-}" == "--dry-run" ]]; then+ DRY_RUN=1+elif [[ -n "${1:-}" ]]; then+ echo "usage: $0 [--dry-run]" >&2+ exit 2+fi++log() { echo "[host-setup] $*"; }++if [[ "$(uname -s)" != "Linux" ]]; then+ echo "host-setup: refusing: not Linux ($(uname -s))" >&2+ exit 1+fi+if [[ $EUID -ne 0 ]]; then+ echo "host-setup: refusing: must run as root" >&2+ exit 1+fi+if [[ $DRY_RUN -eq 1 ]]; then+ log "dry-run mode: printing actions without changing state"+fi++# -- (a) agent world dir -----------------------------------------------------+log "ensuring $AGENT_WORLD (0700)"+if [[ $DRY_RUN -eq 1 ]]; then+ echo "[dry-run] would run: mkdir -p $AGENT_WORLD && chmod 0700 $AGENT_WORLD"+else+ mkdir -p "$AGENT_WORLD"+ chmod 0700 "$AGENT_WORLD"+fi++# -- (b) swap (only if the host has none active) -----------------------------+if swapon --show=NAME --noheadings 2>/dev/null | grep -q .; then+ log "swap already active; leaving existing swap untouched"+else+ log "no active swap: creating 8 GiB $SWAPFILE"+ if [[ $DRY_RUN -eq 1 ]]; then+ echo "[dry-run] would run: fallocate -l 8G $SWAPFILE && chmod 600 $SWAPFILE && mkswap $SWAPFILE && swapon $SWAPFILE"+ echo "[dry-run] would append to /etc/fstab: $SWAPFILE none swap sw 0 0"+ else+ fallocate -l 8G "$SWAPFILE"+ chmod 600 "$SWAPFILE"+ mkswap "$SWAPFILE"+ swapon "$SWAPFILE"+ grep -qs "^$SWAPFILE " /etc/fstab || echo "$SWAPFILE none swap sw 0 0" >> /etc/fstab+ fi+fi++# -- (c) size-bounded builds image -------------------------------------------+log "ensuring 60 GiB ext4 image $BUILDS_IMG mounted at $BUILDS_DIR"+if [[ $DRY_RUN -eq 1 ]]; then+ echo "[dry-run] would run: truncate -s 60G $BUILDS_IMG && mkfs.ext4 -F $BUILDS_IMG"+ echo "[dry-run] would append to /etc/fstab: $BUILDS_IMG $BUILDS_DIR ext4 loop,nofail 0 0"+ echo "[dry-run] would run: mkdir -p $BUILDS_DIR && mount $BUILDS_DIR"+ echo "[dry-run] would run: mkdir -p $BUILDS_DIR/{gradle-cache,cargo-home,android-sdk,slots}"+else+ if [[ ! -f "$BUILDS_IMG" ]]; then+ truncate -s 60G "$BUILDS_IMG"+ mkfs.ext4 -F "$BUILDS_IMG"+ fi+ FSTAB_LINE="$BUILDS_IMG $BUILDS_DIR ext4 loop,nofail 0 0"+ grep -qsF "$BUILDS_IMG $BUILDS_DIR" /etc/fstab || echo "$FSTAB_LINE" >> /etc/fstab+ mkdir -p "$BUILDS_DIR"+ mountpoint -q "$BUILDS_DIR" || mount "$BUILDS_DIR"+ mkdir -p "$BUILDS_DIR"/{gradle-cache,cargo-home,android-sdk,slots}+fi++# -- (d) egress firewall ------------------------------------------------------+log "installing $FIREWALL_SERVICE"+if [[ $DRY_RUN -eq 1 ]]; then+ echo "[dry-run] would write $FIREWALL_SCRIPT (idempotent iptables script)"+ echo "[dry-run] would write $FIREWALL_SERVICE (oneshot, After/Requires snap.docker.dockerd.service)"+ echo "[dry-run] would run: systemctl daemon-reload && systemctl enable --now agents-firewall.service"+else+ cat > "$FIREWALL_SCRIPT" <<EOF+#!/usr/bin/env bash+# agents-firewall: confine the agents-egress subnet ($EGRESS_SUBNET).+# Idempotent: rules carry a comment marker and are only added when absent.+set -euo pipefail+MARK="agents-egress-guard"+have() { iptables -C "\$@" -m comment --comment "\$MARK" 2>/dev/null; }+# Replies to connections the sandbox initiated must keep working.+have DOCKER-USER -s $EGRESS_SUBNET -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT \\+ || iptables -I DOCKER-USER 1 -s $EGRESS_SUBNET -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT -m comment --comment "\$MARK"+# No sandbox -> private-network traffic (lateral movement, metadata, proxies).+for NET in 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 169.254.0.0/16; do+ have DOCKER-USER -s $EGRESS_SUBNET -d "\$NET" -j DROP \\+ || iptables -I DOCKER-USER 2 -s $EGRESS_SUBNET -d "\$NET" -j DROP -m comment --comment "\$MARK"+done+# No sandbox -> host services (container-to-host packets traverse INPUT;+# e.g. the wg-mail tunnel's 10.66.0.2:25/:8081 must stay unreachable).+have INPUT -s $EGRESS_SUBNET -j DROP \\+ || iptables -I INPUT 1 -s $EGRESS_SUBNET -j DROP -m comment --comment "\$MARK"+EOF+ chmod 0755 "$FIREWALL_SCRIPT"+ cat > "$FIREWALL_SERVICE" <<EOF+[Unit]+Description=Confine agents sandbox egress (agents-egress subnet)+After=snap.docker.dockerd.service+Requires=snap.docker.dockerd.service++[Service]+Type=oneshot+RemainAfterExit=yes+ExecStart=$FIREWALL_SCRIPT++[Install]+WantedBy=multi-user.target+EOF+ systemctl daemon-reload+ systemctl enable --now agents-firewall.service+fi++# -- (e) next steps -----------------------------------------------------------+cat <<'NEXT'++host-setup done. Next steps (on the host, as root):+ 1. Clone the deploy checkout: git clone <Modern-Apps> /root/agent-world/Modern-Apps+ 2. Create /root/agent-world/.env from infra/agents/.env.example (fill secrets).+ 3. Ensure the base image exists: docker compose -f /root/location_share_server/compose.yml --profile release build builder+ (produces location-share-builder:local; never touch the running project).+ 4. Review, then start: cd /root/agent-world/Modern-Apps && docker compose -p agents -f infra/agents/compose.yml up -d --build+ 5. Verify: curl the runner via agentd; see infra/agents/README.md.+NEXT
infra/agents/runner/Cargo.toml
diff --git a/infra/agents/runner/Cargo.toml b/infra/agents/runner/Cargo.tomlindex 8cffcdd407..fcb9d454b0 100644--- a/infra/agents/runner/Cargo.toml+++ b/infra/agents/runner/Cargo.toml@@ -13,3 +13,9 @@ path = "src/main.rs" proto.workspace = true serde.workspace = true serde_json.workspace = true+axum = "0.7"+tokio = { version = "1", features = ["full"] }+libc = "0.2"++[dev-dependencies]+tempfile = "3"
infra/agents/runner/src/lib.rs
diff --git a/infra/agents/runner/src/lib.rs b/infra/agents/runner/src/lib.rsnew file mode 100644index 0000000000..88c8b1c316--- /dev/null+++ b/infra/agents/runner/src/lib.rs@@ -0,0 +1,1193 @@+//! agent-runner: HTTP sandbox API served from inside the builder container.+//!+//! Implements every route in `proto` exactly. See `proto/src/lib.rs` for the+//! wire contract. No auth: this server only listens on the internal Docker+//! network and itself runs inside the untrusted sandbox.++use std::collections::HashMap;+use std::os::unix::process::CommandExt;+use std::path::{Component, Path, PathBuf};+use std::process::Stdio;+use std::sync::Arc;+use std::sync::atomic::{AtomicBool, Ordering};+use std::time::{Duration, Instant};++use axum::body::Bytes;+use axum::extract::{Path as AxumPath, State};+use axum::http::{StatusCode, header};+use axum::response::{IntoResponse, Json};+use axum::routing::{get, post};+use axum::Router;+use proto::{+ CommitRequest, CommitResponse, DiffResponse, EditRequest, ErrorBody, ExecKind, ExecRequest,+ ExecResponse, HealthResponse, KillResponse, ListRequest, ListResponse, PrepareRequest,+ PrepareResponse, ReadRequest, ReadResponse, SearchRequest, SearchResponse, WriteRequest,+ AGENT_BRANCH_PREFIX, RUNNER_PORT,+};+use tokio::sync::{Mutex, Semaphore};++/// Stdout/stderr cap per stream for exec/search (head + tail kept).+pub const OUTPUT_CAP_BYTES: usize = 64 * 1024;+/// Cap for `diff.stat`.+pub const DIFF_STAT_CAP_BYTES: usize = 32 * 1024;+/// Cap for `diff.diff`.+pub const DIFF_CAP_BYTES: usize = 256 * 1024;+/// Default line cap for reads.+pub const READ_DEFAULT_MAX_LINES: usize = 2000;+/// Hard ceiling for reads even when the caller asks for more.+pub const READ_HARD_MAX_LINES: usize = 100_000;+/// Max entries returned by list.+pub const LIST_MAX_ENTRIES: usize = 2000;+/// Bounded time for `./gradlew --stop` after a killed/timed-out build.+const GRADLE_STOP_TIMEOUT: Duration = Duration::from_secs(120);+/// Timeout for individual git invocations.+const GIT_TIMEOUT: Duration = Duration::from_secs(300);+/// Timeout for ripgrep searches.+const SEARCH_TIMEOUT: Duration = Duration::from_secs(120);+/// Grace period to drain stdio after the process exits (a backgrounded+/// grandchild can hold the pipes open; don't wait forever).+const STDIO_DRAIN_GRACE: Duration = Duration::from_secs(10);+/// Name of the file (inside `<slot>/.git/`) recording the branch base.+const AGENT_BASE_FILE: &str = "agent-base";++/// Error with an HTTP status, rendered as [`ErrorBody`] JSON.+#[derive(Debug)]+pub struct ApiError {+ pub status: StatusCode,+ pub message: String,+}++impl ApiError {+ fn new(status: StatusCode, message: impl Into<String>) -> Self {+ Self {+ status,+ message: message.into(),+ }+ }++ fn bad_request(message: impl Into<String>) -> Self {+ Self::new(StatusCode::BAD_REQUEST, message)+ }++ fn not_found(message: impl Into<String>) -> Self {+ Self::new(StatusCode::NOT_FOUND, message)+ }++ fn conflict(message: impl Into<String>) -> Self {+ Self::new(StatusCode::CONFLICT, message)+ }++ fn internal(message: impl Into<String>) -> Self {+ Self::new(StatusCode::INTERNAL_SERVER_ERROR, message)+ }+}++type ErrTuple = (StatusCode, Json<ErrorBody>);++fn to_err_tuple(e: ApiError) -> ErrTuple {+ (e.status, Json(ErrorBody { error: e.message }))+}++struct RunningEntry {+ pgid: i32,+ killed: Arc<AtomicBool>,+ is_build: bool,+}++pub struct AppState {+ pub slots_dir: PathBuf,+ pub mirror: PathBuf,+ pub num_slots: u32,+ build_sem: Arc<Semaphore>,+ build_running: AtomicBool,+ running: Mutex<HashMap<u32, RunningEntry>>,+ build_slot: Mutex<Option<u32>>,+}++impl AppState {+ pub fn new(slots_dir: PathBuf, mirror: PathBuf, num_slots: u32) -> Self {+ Self {+ slots_dir,+ mirror,+ num_slots: num_slots.max(1),+ build_sem: Arc::new(Semaphore::new(1)),+ build_running: AtomicBool::new(false),+ running: Mutex::new(HashMap::new()),+ build_slot: Mutex::new(None),+ }+ }++ pub fn from_env() -> Self {+ let num_slots = std::env::var("RUNNER_SLOTS")+ .ok()+ .and_then(|v| v.parse::<u32>().ok())+ .unwrap_or(4);+ let slots_dir = std::env::var("RUNNER_SLOTS_DIR")+ .map(PathBuf::from)+ .unwrap_or_else(|_| PathBuf::from("/builds/slots"));+ let mirror = std::env::var("RUNNER_MIRROR")+ .map(PathBuf::from)+ .unwrap_or_else(|_| PathBuf::from("/mirror/Modern-Apps.git"));+ Self::new(slots_dir, mirror, num_slots)+ }++ pub fn listen_addr() -> String {+ std::env::var("RUNNER_LISTEN").unwrap_or_else(|_| format!("0.0.0.0:{RUNNER_PORT}"))+ }+}++/// Parse a `{slot}` path param: integer in `0..num_slots`, else 404.+pub fn parse_slot(state: &AppState, raw: &str) -> Result<u32, ApiError> {+ match raw.parse::<u32>() {+ Ok(n) if n < state.num_slots => Ok(n),+ _ => Err(ApiError::not_found(format!(+ "unknown slot {raw:?}; valid slots are 0..{}",+ state.num_slots+ ))),+ }+}++pub fn slot_root(state: &AppState, slot: u32) -> PathBuf {+ state.slots_dir.join(format!("slot-{slot}"))+}++/// Resolve a request path relative to the slot root.+///+/// Rejects absolute paths, `..` escapes, NUL bytes, anything under `.git/`,+/// and symlinks (on existing ancestors) that resolve outside the slot root.+pub fn resolve_in_slot(slot_root: &Path, rel: &str) -> Result<PathBuf, String> {+ if rel.is_empty() {+ return Err("empty path".to_string());+ }+ if rel.contains('\0') {+ return Err("path contains NUL byte".to_string());+ }+ let rel_path = Path::new(rel);+ if rel_path.is_absolute() {+ return Err(format!("absolute paths are rejected: {rel:?}"));+ }+ // Lexical normalization: collapse `.`, reject escaping `..`.+ let mut parts: Vec<String> = Vec::new();+ for comp in rel_path.components() {+ match comp {+ Component::Prefix(_) | Component::RootDir => {+ return Err(format!("absolute paths are rejected: {rel:?}"));+ }+ Component::CurDir => {}+ Component::ParentDir => {+ if parts.pop().is_none() {+ return Err(format!("path escapes the slot root: {rel:?}"));+ }+ }+ Component::Normal(c) => parts.push(c.to_string_lossy().into_owned()),+ }+ }+ if parts.is_empty() {+ return Err(format!("path resolves to the slot root itself: {rel:?}"));+ }+ if parts[0] == ".git" {+ return Err("paths under .git/ are rejected".to_string());+ }+ let mut resolved = slot_root.to_path_buf();+ for p in &parts {+ resolved.push(p);+ }+ // Symlink check: canonicalize the longest existing prefix (the slot root+ // itself if nothing exists yet) and require it to stay inside the+ // canonical slot root. This covers new files created through a symlinked+ // directory as well as existing symlinked files.+ let canonical_root = slot_root+ .canonicalize()+ .map_err(|e| format!("slot root is not usable: {e}"))?;+ let mut probe = resolved.clone();+ loop {+ if probe.exists() {+ let canon = probe+ .canonicalize()+ .map_err(|e| format!("cannot canonicalize {probe:?}: {e}"))?;+ if !canon.starts_with(&canonical_root) {+ return Err(format!("path resolves outside the slot root: {rel:?}"));+ }+ break;+ }+ if !probe.pop() {+ break;+ }+ }+ Ok(resolved)+}++/// Validate an agent branch name: `agent/` prefix + safe ref name.+pub fn validate_branch(branch: &str) -> Result<(), String> {+ if !branch.starts_with(AGENT_BRANCH_PREFIX) {+ return Err(format!(+ "branch must start with {AGENT_BRANCH_PREFIX:?}, got {branch:?}"+ ));+ }+ if branch.contains('\0') || branch.chars().any(|c| c.is_control()) {+ return Err("branch contains control characters".to_string());+ }+ for bad in ["..", "@{", "//", "~", "^", ":", "?", "*", "[", "\\"] {+ if branch.contains(bad) {+ return Err(format!("branch contains forbidden sequence {bad:?}"));+ }+ }+ if branch.starts_with('/') || branch.starts_with('.') {+ return Err("branch has a forbidden leading character".to_string());+ }+ if branch.ends_with('/') || branch.ends_with('.') || branch.ends_with(".lock") {+ return Err("branch has a forbidden trailing component".to_string());+ }+ for comp in branch.split('/') {+ if comp.is_empty() || comp.starts_with('.') {+ return Err(format!("branch has a forbidden component in {branch:?}"));+ }+ if comp == "agent" && branch == "agent/" {+ return Err("branch name is empty after the agent/ prefix".to_string());+ }+ if !comp+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))+ {+ return Err(format!(+ "branch contains a forbidden character in {branch:?}"+ ));+ }+ }+ Ok(())+}++/// Keep head + tail of `data` over `cap` bytes, with a marker line.+pub fn truncate_bytes(data: &[u8], cap: usize) -> (String, bool) {+ if data.len() <= cap {+ return (String::from_utf8_lossy(data).into_owned(), false);+ }+ let half = cap / 2;+ let marker = format!("\n... [truncated {} bytes] ...\n", data.len() - cap);+ let mut out = String::from_utf8_lossy(&data[..half]).into_owned();+ out.push_str(&marker);+ out.push_str(&String::from_utf8_lossy(&data[data.len() - half..]));+ (out, true)+}++/// Replace exactly one occurrence of `old` with `new`.+pub fn apply_edit(content: &str, old: &str, new: &str) -> Result<String, String> {+ if old.is_empty() {+ return Err("`old` must not be empty".to_string());+ }+ let count = content.matches(old).count();+ if count != 1 {+ return Err(format!(+ "`old` matched {count} times (expected exactly 1); refusing to edit"+ ));+ }+ Ok(content.replacen(old, new, 1))+}++fn read_base_sha(slot: &Path) -> Result<String, ApiError> {+ let base_file = slot.join(".git").join(AGENT_BASE_FILE);+ let raw = std::fs::read_to_string(&base_file).map_err(|_| {+ ApiError::conflict("slot has no recorded base; run prepare first".to_string())+ })?;+ let sha = raw.trim().to_string();+ if sha.is_empty() {+ return Err(ApiError::conflict(+ "slot has no recorded base; run prepare first".to_string(),+ ));+ }+ Ok(sha)+}++fn git_args(mirror: &Path, slot: Option<&Path>, args: &[&str]) -> Vec<String> {+ let mut out = vec![+ "-c".to_string(),+ format!("safe.directory={}", mirror.display()),+ ];+ if let Some(slot) = slot {+ out.push("-c".to_string());+ out.push(format!("safe.directory={}", slot.display()));+ out.push("-C".to_string());+ out.push(slot.display().to_string());+ }+ out.extend(args.iter().map(|s| s.to_string()));+ out+}++async fn run_git(+ mirror: &Path,+ slot: Option<&Path>,+ args: &[&str],+) -> Result<std::process::Output, ApiError> {+ let argv = git_args(mirror, slot, args);+ let mut cmd = tokio::process::Command::new("git");+ cmd.args(&argv);+ cmd.stdin(Stdio::null());+ cmd.stdout(Stdio::piped());+ cmd.stderr(Stdio::piped());+ cmd.kill_on_drop(true);+ let child = cmd.spawn().map_err(|e| {+ ApiError::internal(format!("failed to spawn git {}: {e}", args.join(" ")))+ })?;+ let status_str = args.join(" ");+ let pid = child.id();+ match tokio::time::timeout(GIT_TIMEOUT, child.wait_with_output()).await {+ Ok(Ok(out)) => Ok(out),+ Ok(Err(e)) => Err(ApiError::internal(format!(+ "failed to wait for git {status_str}: {e}"+ ))),+ Err(_) => {+ // wait_with_output consumed the Child; kill by pid explicitly+ // (kill_on_drop cannot fire since the Child was moved). These are+ // leaf git invocations, so signalling the pid is sufficient.+ if let Some(pid) = pid {+ unsafe {+ libc::kill(pid as i32, libc::SIGKILL);+ }+ }+ Err(ApiError::internal(format!(+ "git {status_str} timed out after {}s",+ GIT_TIMEOUT.as_secs()+ )))+ }+ }+}++fn check_git_output(out: &std::process::Output, what: &str) -> Result<String, ApiError> {+ if out.status.success() {+ Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())+ } else {+ Err(ApiError::internal(format!(+ "{what} failed: {}",+ String::from_utf8_lossy(&out.stderr).trim()+ )))+ }+}++/// (Re)create the slot checkout on a fresh branch from the mirror's main.+pub async fn prepare_slot(+ state: &Arc<AppState>,+ slot: u32,+ branch: &str,+) -> Result<String, ApiError> {+ validate_branch(branch).map_err(ApiError::bad_request)?;+ let slot_path = slot_root(state, slot);+ let is_repo = slot_path.join(".git").is_dir();+ if !is_repo {+ if slot_path.exists() {+ if slot_path.is_dir() {+ std::fs::remove_dir_all(&slot_path).map_err(|e| {+ ApiError::internal(format!("failed to clear {slot_path:?}: {e}"))+ })?;+ } else {+ std::fs::remove_file(&slot_path).map_err(|e| {+ ApiError::internal(format!("failed to clear {slot_path:?}: {e}"))+ })?;+ }+ }+ if let Some(parent) = slot_path.parent() {+ std::fs::create_dir_all(parent)+ .map_err(|e| ApiError::internal(format!("failed to create slots dir: {e}")))?;+ }+ let out = run_git(+ &state.mirror,+ None,+ &[+ "clone",+ "--shared",+ &state.mirror.display().to_string(),+ &slot_path.display().to_string(),+ ],+ )+ .await?;+ check_git_output(&out, "git clone")?;+ } else {+ // Tear down leftover state first so the checkout below cannot fail on+ // untracked files shadowing the target branch.+ let out = run_git(&state.mirror, Some(&slot_path), &["reset", "--hard", "HEAD"]).await?;+ check_git_output(&out, "git reset")?;+ let out = run_git(&state.mirror, Some(&slot_path), &["clean", "-fd"]).await?;+ check_git_output(&out, "git clean")?;+ }+ let out = run_git(&state.mirror, Some(&slot_path), &["fetch", "origin"]).await?;+ check_git_output(&out, "git fetch")?;+ let out = run_git(+ &state.mirror,+ Some(&slot_path),+ &["rev-parse", "--verify", "origin/main"],+ )+ .await?;+ if !out.status.success() {+ return Err(ApiError::internal(+ "mirror has no origin/main; cannot prepare slot".to_string(),+ ));+ }+ let out = run_git(+ &state.mirror,+ Some(&slot_path),+ &["checkout", "-B", branch, "origin/main"],+ )+ .await?;+ check_git_output(&out, "git checkout")?;+ let out = run_git(+ &state.mirror,+ Some(&slot_path),+ &["reset", "--hard", "origin/main"],+ )+ .await?;+ check_git_output(&out, "git reset")?;+ // `clean -fd` without `-x`: drop untracked work but keep ignored+ // build outputs (build/, target/, .gradle/) warm.+ let out = run_git(&state.mirror, Some(&slot_path), &["clean", "-fd"]).await?;+ check_git_output(&out, "git clean")?;+ let out = run_git(+ &state.mirror,+ Some(&slot_path),+ &["config", "user.name", "maproj agent"],+ )+ .await?;+ check_git_output(&out, "git config user.name")?;+ let out = run_git(+ &state.mirror,+ Some(&slot_path),+ &["config", "user.email", "[email protected]"],+ )+ .await?;+ check_git_output(&out, "git config user.email")?;+ let out = run_git(&state.mirror, Some(&slot_path), &["rev-parse", "HEAD"]).await?;+ let base_sha = check_git_output(&out, "git rev-parse")?;+ std::fs::write(+ slot_path.join(".git").join(AGENT_BASE_FILE),+ format!("{base_sha}\n"),+ )+ .map_err(|e| ApiError::internal(format!("failed to record base sha: {e}")))?;+ Ok(base_sha)+}++fn kill_process_group(pgid: i32) {+ // ESRCH (no such group) just means nothing was running.+ unsafe {+ libc::killpg(pgid, libc::SIGKILL);+ }+}++/// Run `bash -lc <command>` in the slot root, in its own process group.+pub async fn exec_in_slot(+ state: &Arc<AppState>,+ slot: u32,+ req: &ExecRequest,+) -> Result<ExecResponse, ApiError> {+ let slot_path = slot_root(state, slot);+ if !slot_path.is_dir() {+ return Err(ApiError::not_found(+ "slot is not prepared; run prepare first".to_string(),+ ));+ }+ let mut queued_ms = 0u64;++ // Build commands serialize behind the single build permit.+ let _permit = match req.kind {+ ExecKind::Build => {+ let wait_start = Instant::now();+ let permit = state+ .build_sem+ .clone()+ .acquire_owned()+ .await+ .map_err(|e| ApiError::internal(format!("build semaphore closed: {e}")))?;+ queued_ms = wait_start+ .elapsed()+ .as_millis()+ .min(u128::from(u64::MAX)) as u64;+ state.build_running.store(true, Ordering::SeqCst);+ *state.build_slot.lock().await = Some(slot);+ Some(permit)+ }+ ExecKind::Shell => None,+ };++ let result = run_command(state, slot, &slot_path, req).await;++ if _permit.is_some() {+ state.build_running.store(false, Ordering::SeqCst);+ *state.build_slot.lock().await = None;+ drop(_permit);+ }++ let mut resp = result?;+ resp.queued_ms = queued_ms;+ Ok(resp)+}++/// Drain an async reader, bounded by a deadline; returns bytes + whether the+/// deadline cut the drain short (a backgrounded grandchild can hold pipes).+async fn drain_bounded<R>(mut reader: R, deadline: Instant) -> (Vec<u8>, bool)+where+ R: tokio::io::AsyncRead + Unpin,+{+ let mut buf = Vec::new();+ let mut chunk = [0u8; 8192];+ loop {+ let now = Instant::now();+ if now >= deadline {+ return (buf, true);+ }+ tokio::select! {+ res = tokio::io::AsyncReadExt::read(&mut reader, &mut chunk) => {+ match res {+ Ok(0) => return (buf, false),+ Ok(n) => buf.extend_from_slice(&chunk[..n]),+ Err(_) => return (buf, true),+ }+ }+ _ = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)) => {+ return (buf, true);+ }+ }+ }+}++async fn run_command(+ state: &Arc<AppState>,+ slot: u32,+ slot_path: &Path,+ req: &ExecRequest,+) -> Result<ExecResponse, ApiError> {+ let started = Instant::now();+ let use_nice = req.kind == ExecKind::Shell && Path::new("/usr/bin/nice").exists();+ let mut std_cmd = std::process::Command::new(if use_nice { "/usr/bin/nice" } else { "bash" });+ if use_nice {+ std_cmd.arg("-n").arg("10").arg("bash");+ }+ std_cmd+ .arg("-lc")+ .arg(&req.command)+ .current_dir(slot_path)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .process_group(0);++ let mut child = tokio::process::Command::from(std_cmd)+ .kill_on_drop(true)+ .spawn()+ .map_err(|e| ApiError::internal(format!("failed to spawn command: {e}")))?;+ // With `process_group(0)` the child is its own group leader, so its pid+ // doubles as the pgid we signal for timeout/cancel.+ let pgid = child.id().map(|id| id as i32).ok_or_else(|| {+ ApiError::internal("spawned command has no pid".to_string())+ })?;+ let killed_flag = Arc::new(AtomicBool::new(false));+ {+ let mut running = state.running.lock().await;+ running.insert(+ slot,+ RunningEntry {+ pgid,+ killed: killed_flag.clone(),+ is_build: req.kind == ExecKind::Build,+ },+ );+ }++ let stdout = child.stdout.take().ok_or_else(|| {+ ApiError::internal("spawned command has no stdout pipe".to_string())+ })?;+ let stderr = child.stderr.take().ok_or_else(|| {+ ApiError::internal("spawned command has no stderr pipe".to_string())+ })?;+ // Drain concurrently: a child writing more than the pipe buffer must not+ // block forever while we wait for its exit.+ let drain_deadline = Instant::now()+ + Duration::from_secs(req.timeout_secs)+ + STDIO_DRAIN_GRACE;+ let out_task = tokio::spawn(drain_bounded(stdout, drain_deadline));+ let err_task = tokio::spawn(drain_bounded(stderr, drain_deadline));++ // Wait for exit or timeout; on timeout SIGKILL the whole process group+ // (daemons that double-fork out of the group are handled separately for+ // builds via `./gradlew --stop` below).+ let mut timed_out = false;+ let wait_status = tokio::select! {+ status = child.wait() => status.map_err(|e| {+ ApiError::internal(format!("failed to wait for command: {e}"))+ })?,+ _ = tokio::time::sleep(Duration::from_secs(req.timeout_secs)) => {+ timed_out = true;+ kill_process_group(pgid);+ child.wait().await.map_err(|e| {+ ApiError::internal(format!("failed to reap timed-out command: {e}"))+ })?+ }+ };+ let (out_buf, out_cut) = out_task.await.unwrap_or_default();+ let (err_buf, err_cut) = err_task.await.unwrap_or_default();++ let was_killed = killed_flag.load(Ordering::SeqCst);+ {+ let mut running = state.running.lock().await;+ running.remove(&slot);+ }++ let exit_code = if timed_out || was_killed {+ None+ } else {+ wait_status.code()+ };+ let (stdout_str, stdout_trunc) = truncate_bytes(&out_buf, OUTPUT_CAP_BYTES);+ let (stderr_str, stderr_trunc) = truncate_bytes(&err_buf, OUTPUT_CAP_BYTES);++ // Gradle/Kotlin daemons detach from the process group, so killpg alone+ // does not free their RAM. Ask Gradle to stop them after a killed build.+ if req.kind == ExecKind::Build && (timed_out || was_killed) {+ gradle_stop(slot_path).await;+ }++ Ok(ExecResponse {+ exit_code,+ stdout: stdout_str,+ stderr: stderr_str,+ truncated: stdout_trunc || stderr_trunc || out_cut || err_cut,+ timed_out,+ killed: was_killed && !timed_out,+ queued_ms: 0,+ duration_ms: started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,+ })+}++async fn gradle_stop(slot_path: &Path) {+ if !slot_path.join("gradlew").exists() {+ return;+ }+ let mut cmd = tokio::process::Command::new("bash");+ cmd.arg("-lc")+ .arg("./gradlew --stop")+ .current_dir(slot_path)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .kill_on_drop(true);+ if let Ok(mut child) = cmd.spawn() {+ let _ = tokio::time::timeout(GRADLE_STOP_TIMEOUT, child.wait()).await;+ }+}++pub async fn cancel_slot(state: &Arc<AppState>, slot: u32) -> bool {+ let running = state.running.lock().await;+ match running.get(&slot) {+ Some(entry) => {+ entry.killed.store(true, Ordering::SeqCst);+ kill_process_group(entry.pgid);+ true+ }+ None => false,+ }+}++pub async fn kill_build(state: &Arc<AppState>) -> bool {+ let slot = { *state.build_slot.lock().await };+ match slot {+ Some(slot) => {+ let running = state.running.lock().await;+ match running.get(&slot) {+ Some(entry) if entry.is_build => {+ entry.killed.store(true, Ordering::SeqCst);+ kill_process_group(entry.pgid);+ true+ }+ _ => false,+ }+ }+ None => false,+ }+}++pub async fn read_slot_file(+ state: &Arc<AppState>,+ slot: u32,+ req: &ReadRequest,+) -> Result<ReadResponse, ApiError> {+ let root = slot_root(state, slot);+ let path = resolve_in_slot(&root, &req.path).map_err(ApiError::not_found)?;+ if path.is_dir() {+ return Err(ApiError::bad_request(format!(+ "{:?} is a directory",+ req.path+ )));+ }+ let content = std::fs::read(&path)+ .map_err(|e| ApiError::not_found(format!("cannot read {:?}: {e}", req.path)))?;+ let text = String::from_utf8_lossy(&content).into_owned();+ let lines: Vec<&str> = text.lines().collect();+ let total_lines = lines.len();+ let start = req.start_line.unwrap_or(1).max(1);+ let max_lines = req+ .max_lines+ .unwrap_or(READ_DEFAULT_MAX_LINES)+ .min(READ_HARD_MAX_LINES);+ let selected: Vec<&str> = if start > lines.len() {+ Vec::new()+ } else {+ lines[(start - 1)..].iter().take(max_lines).copied().collect()+ };+ let truncated = lines.len() > (start - 1) + selected.len();+ Ok(ReadResponse {+ content: selected.join("\n"),+ total_lines,+ truncated,+ })+}++pub async fn write_slot_file(+ state: &Arc<AppState>,+ slot: u32,+ req: &WriteRequest,+) -> Result<(), ApiError> {+ let root = slot_root(state, slot);+ let path = resolve_in_slot(&root, &req.path).map_err(ApiError::bad_request)?;+ if path.is_dir() {+ return Err(ApiError::bad_request(format!(+ "{:?} is a directory",+ req.path+ )));+ }+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)+ .map_err(|e| ApiError::internal(format!("cannot create parent dirs: {e}")))?;+ }+ std::fs::write(&path, &req.content)+ .map_err(|e| ApiError::internal(format!("cannot write {:?}: {e}", req.path)))?;+ Ok(())+}++pub async fn edit_slot_file(+ state: &Arc<AppState>,+ slot: u32,+ req: &EditRequest,+) -> Result<(), ApiError> {+ let root = slot_root(state, slot);+ let path = resolve_in_slot(&root, &req.path).map_err(ApiError::bad_request)?;+ let content = std::fs::read_to_string(&path)+ .map_err(|e| ApiError::not_found(format!("cannot read {:?}: {e}", req.path)))?;+ let updated = apply_edit(&content, &req.old, &req.new).map_err(ApiError::conflict)?;+ std::fs::write(&path, updated)+ .map_err(|e| ApiError::internal(format!("cannot write {:?}: {e}", req.path)))?;+ Ok(())+}++pub async fn list_slot_dir(+ state: &Arc<AppState>,+ slot: u32,+ req: &ListRequest,+) -> Result<ListResponse, ApiError> {+ let root = slot_root(state, slot);+ let dir: PathBuf = if req.path.is_empty() || req.path == "." {+ root.clone()+ } else {+ resolve_in_slot(&root, &req.path).map_err(ApiError::bad_request)?+ };+ let read_dir =+ std::fs::read_dir(&dir).map_err(|e| ApiError::not_found(format!("cannot list: {e}")))?;+ let mut entries: Vec<String> = Vec::new();+ for entry in read_dir {+ let entry = entry.map_err(|e| ApiError::internal(format!("cannot list: {e}")))?;+ let name = entry.file_name().to_string_lossy().into_owned();+ let file_type = entry+ .file_type()+ .map_err(|e| ApiError::internal(format!("cannot stat entry: {e}")))?;+ if file_type.is_dir() {+ entries.push(format!("{name}/"));+ } else {+ entries.push(name);+ }+ if entries.len() >= LIST_MAX_ENTRIES {+ break;+ }+ }+ entries.sort();+ // `truncated` is approximate: we stopped early at the cap.+ let truncated = entries.len() >= LIST_MAX_ENTRIES;+ Ok(ListResponse { entries, truncated })+}++const SEARCH_EXCLUDES: &[&str] = &[+ "!build/",+ "!target/",+ "!.gradle/",+ "!.kotlin/",+ "!metadata_data/photos/",+ "!third_party/",+ "!*.onnx",+ "!*.log",+];++pub async fn search_slot(+ state: &Arc<AppState>,+ slot: u32,+ req: &SearchRequest,+) -> Result<SearchResponse, ApiError> {+ let root = slot_root(state, slot);+ let cwd: PathBuf = match &req.path {+ Some(p) if !p.is_empty() && *p != "." => {+ resolve_in_slot(&root, p).map_err(ApiError::bad_request)?+ }+ _ => root.clone(),+ };+ if !cwd.exists() {+ return Err(ApiError::not_found(+ "search path does not exist".to_string(),+ ));+ }+ let mut cmd = tokio::process::Command::new("rg");+ cmd.arg("--line-number")+ .arg("--no-heading")+ .arg("--max-columns")+ .arg("300");+ if req.fixed_string {+ cmd.arg("--fixed-strings");+ }+ if let Some(glob) = &req.glob {+ cmd.arg("--glob").arg(glob);+ }+ for excl in SEARCH_EXCLUDES {+ cmd.arg("--glob").arg(excl);+ }+ cmd.arg("--").arg(&req.pattern);+ if cwd != root {+ let rel = cwd+ .strip_prefix(&root)+ .map_err(|e| ApiError::internal(format!("search path escaped slot root: {e}")))?;+ cmd.arg(rel);+ }+ cmd.current_dir(&root)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true);+ let child = cmd.spawn().map_err(|e| {+ ApiError::internal(format!("failed to spawn rg (is ripgrep installed?): {e}"))+ })?;+ let rg_pid = child.id();+ let out = match tokio::time::timeout(SEARCH_TIMEOUT, child.wait_with_output()).await {+ Ok(Ok(out)) => out,+ Ok(Err(e)) => return Err(ApiError::internal(format!("failed to wait for rg: {e}"))),+ Err(_) => {+ // wait_with_output consumed the Child; kill by pid (leaf process).+ if let Some(pid) = rg_pid {+ unsafe {+ libc::kill(pid as i32, libc::SIGKILL);+ }+ }+ return Err(ApiError::internal("rg search timed out".to_string()));+ }+ };+ match out.status.code() {+ // 0 = matches, 1 = no matches.+ Some(0) | Some(1) => {}+ // The include glob filtered out every file: not a failure, just no+ // matches. (Other exit-2 causes, e.g. a bad regex, still 500 below.)+ Some(2)+ if String::from_utf8_lossy(&out.stderr).contains("No files were searched") =>+ {+ return Ok(SearchResponse {+ matches: String::new(),+ truncated: false,+ });+ }+ other => {+ return Err(ApiError::internal(format!(+ "rg failed (exit {other:?}): {}",+ String::from_utf8_lossy(&out.stderr).trim()+ )));+ }+ }+ let (matches, truncated) = truncate_bytes(&out.stdout, OUTPUT_CAP_BYTES);+ Ok(SearchResponse { matches, truncated })+}++pub async fn diff_slot(state: &Arc<AppState>, slot: u32) -> Result<DiffResponse, ApiError> {+ let slot_path = slot_root(state, slot);+ if !slot_path.join(".git").is_dir() {+ return Err(ApiError::not_found(+ "slot is not prepared; run prepare first".to_string(),+ ));+ }+ let base_sha = read_base_sha(&slot_path)?;+ let out = run_git(&state.mirror, Some(&slot_path), &["add", "-A"]).await?;+ check_git_output(&out, "git add")?;+ let out = run_git(+ &state.mirror,+ Some(&slot_path),+ &["diff", "--no-color", "--stat", &base_sha, "--"],+ )+ .await?;+ let stat_raw = check_git_output(&out, "git diff --stat")?;+ let out = run_git(+ &state.mirror,+ Some(&slot_path),+ &["diff", "--no-color", &base_sha, "--"],+ )+ .await?;+ let diff_raw = check_git_output(&out, "git diff")?;+ let (stat, stat_trunc) = truncate_bytes(stat_raw.as_bytes(), DIFF_STAT_CAP_BYTES);+ let (diff, diff_trunc) = truncate_bytes(diff_raw.as_bytes(), DIFF_CAP_BYTES);+ Ok(DiffResponse {+ stat,+ diff,+ truncated: stat_trunc || diff_trunc,+ })+}++pub async fn commit_slot(+ state: &Arc<AppState>,+ slot: u32,+ req: &CommitRequest,+) -> Result<String, ApiError> {+ let slot_path = slot_root(state, slot);+ if !slot_path.join(".git").is_dir() {+ return Err(ApiError::not_found(+ "slot is not prepared; run prepare first".to_string(),+ ));+ }+ let out = run_git(&state.mirror, Some(&slot_path), &["add", "-A"]).await?;+ check_git_output(&out, "git add")?;+ let out = run_git(+ &state.mirror,+ Some(&slot_path),+ &["status", "--porcelain"],+ )+ .await?;+ let status = check_git_output(&out, "git status")?;+ if status.is_empty() {+ return Err(ApiError::conflict("nothing to commit".to_string()));+ }+ let out = run_git(+ &state.mirror,+ Some(&slot_path),+ &["commit", "-m", &req.message],+ )+ .await?;+ check_git_output(&out, "git commit")?;+ let out = run_git(&state.mirror, Some(&slot_path), &["rev-parse", "HEAD"]).await?;+ check_git_output(&out, "git rev-parse")+}++pub async fn bundle_slot(state: &Arc<AppState>, slot: u32) -> Result<(String, Vec<u8>), ApiError> {+ let slot_path = slot_root(state, slot);+ if !slot_path.join(".git").is_dir() {+ return Err(ApiError::not_found(+ "slot is not prepared; run prepare first".to_string(),+ ));+ }+ let base_sha = read_base_sha(&slot_path)?;+ let out = run_git(+ &state.mirror,+ Some(&slot_path),+ &["branch", "--show-current"],+ )+ .await?;+ let branch = check_git_output(&out, "git branch --show-current")?;+ if branch.is_empty() {+ return Err(ApiError::conflict(+ "slot is not on a branch; run prepare first".to_string(),+ ));+ }+ let out = run_git(&state.mirror, Some(&slot_path), &["rev-parse", "HEAD"]).await?;+ let head = check_git_output(&out, "git rev-parse")?;+ if head == base_sha {+ return Err(ApiError::conflict(+ "no commits on the branch; nothing to bundle".to_string(),+ ));+ }+ let range = format!("{base_sha}..{branch}");+ let out = run_git(+ &state.mirror,+ Some(&slot_path),+ &["bundle", "create", "-", &range],+ )+ .await?;+ if !out.status.success() {+ return Err(ApiError::conflict(format!(+ "git bundle failed: {}",+ String::from_utf8_lossy(&out.stderr).trim()+ )));+ }+ Ok((branch, out.stdout))+}++// ---------------------------------------------------------------------------+// HTTP layer+// ---------------------------------------------------------------------------++fn parse_json<T: serde::de::DeserializeOwned>(body: &Bytes) -> Result<T, ApiError> {+ serde_json::from_slice(body)+ .map_err(|e| ApiError::bad_request(format!("invalid JSON body: {e}")))+}++async fn h_prepare(+ State(state): State<Arc<AppState>>,+ AxumPath(slot_raw): AxumPath<String>,+ body: Bytes,+) -> Result<Json<PrepareResponse>, ErrTuple> {+ let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;+ let req: PrepareRequest = parse_json(&body).map_err(to_err_tuple)?;+ let base_sha = prepare_slot(&state, slot, &req.branch)+ .await+ .map_err(to_err_tuple)?;+ Ok(Json(PrepareResponse { base_sha }))+}++async fn h_exec(+ State(state): State<Arc<AppState>>,+ AxumPath(slot_raw): AxumPath<String>,+ body: Bytes,+) -> Result<Json<ExecResponse>, ErrTuple> {+ let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;+ let req: ExecRequest = parse_json(&body).map_err(to_err_tuple)?;+ let resp = exec_in_slot(&state, slot, &req).await.map_err(to_err_tuple)?;+ Ok(Json(resp))+}++async fn h_read(+ State(state): State<Arc<AppState>>,+ AxumPath(slot_raw): AxumPath<String>,+ body: Bytes,+) -> Result<Json<ReadResponse>, ErrTuple> {+ let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;+ let req: ReadRequest = parse_json(&body).map_err(to_err_tuple)?;+ let resp = read_slot_file(&state, slot, &req).await.map_err(to_err_tuple)?;+ Ok(Json(resp))+}++async fn h_write(+ State(state): State<Arc<AppState>>,+ AxumPath(slot_raw): AxumPath<String>,+ body: Bytes,+) -> Result<Json<serde_json::Value>, ErrTuple> {+ let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;+ let req: WriteRequest = parse_json(&body).map_err(to_err_tuple)?;+ write_slot_file(&state, slot, &req).await.map_err(to_err_tuple)?;+ Ok(Json(serde_json::json!({})))+}++async fn h_edit(+ State(state): State<Arc<AppState>>,+ AxumPath(slot_raw): AxumPath<String>,+ body: Bytes,+) -> Result<Json<serde_json::Value>, ErrTuple> {+ let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;+ let req: EditRequest = parse_json(&body).map_err(to_err_tuple)?;+ edit_slot_file(&state, slot, &req).await.map_err(to_err_tuple)?;+ Ok(Json(serde_json::json!({})))+}++async fn h_list(+ State(state): State<Arc<AppState>>,+ AxumPath(slot_raw): AxumPath<String>,+ body: Bytes,+) -> Result<Json<ListResponse>, ErrTuple> {+ let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;+ let req: ListRequest = parse_json(&body).map_err(to_err_tuple)?;+ let resp = list_slot_dir(&state, slot, &req).await.map_err(to_err_tuple)?;+ Ok(Json(resp))+}++async fn h_search(+ State(state): State<Arc<AppState>>,+ AxumPath(slot_raw): AxumPath<String>,+ body: Bytes,+) -> Result<Json<SearchResponse>, ErrTuple> {+ let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;+ let req: SearchRequest = parse_json(&body).map_err(to_err_tuple)?;+ let resp = search_slot(&state, slot, &req).await.map_err(to_err_tuple)?;+ Ok(Json(resp))+}++async fn h_diff(+ State(state): State<Arc<AppState>>,+ AxumPath(slot_raw): AxumPath<String>,+) -> Result<Json<DiffResponse>, ErrTuple> {+ let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;+ let resp = diff_slot(&state, slot).await.map_err(to_err_tuple)?;+ Ok(Json(resp))+}++async fn h_commit(+ State(state): State<Arc<AppState>>,+ AxumPath(slot_raw): AxumPath<String>,+ body: Bytes,+) -> Result<Json<CommitResponse>, ErrTuple> {+ let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;+ let req: CommitRequest = parse_json(&body).map_err(to_err_tuple)?;+ let sha = commit_slot(&state, slot, &req).await.map_err(to_err_tuple)?;+ Ok(Json(CommitResponse { sha }))+}++async fn h_bundle(+ State(state): State<Arc<AppState>>,+ AxumPath(slot_raw): AxumPath<String>,+) -> Result<impl IntoResponse, ErrTuple> {+ let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;+ let (_branch, bytes) = bundle_slot(&state, slot).await.map_err(to_err_tuple)?;+ Ok((+ StatusCode::OK,+ [(header::CONTENT_TYPE, "application/octet-stream")],+ bytes,+ ))+}++async fn h_cancel(+ State(state): State<Arc<AppState>>,+ AxumPath(slot_raw): AxumPath<String>,+) -> Result<Json<KillResponse>, ErrTuple> {+ let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;+ let killed = cancel_slot(&state, slot).await;+ Ok(Json(KillResponse { killed }))+}++async fn h_builds_kill(State(state): State<Arc<AppState>>) -> Json<KillResponse> {+ let killed = kill_build(&state).await;+ Json(KillResponse { killed })+}++async fn h_health(State(state): State<Arc<AppState>>) -> Json<HealthResponse> {+ Json(HealthResponse {+ slots: state.num_slots,+ build_running: state.build_running.load(Ordering::SeqCst),+ })+}++pub fn router(state: Arc<AppState>) -> Router {+ Router::new()+ .route("/v1/slots/:slot/prepare", post(h_prepare))+ .route("/v1/slots/:slot/exec", post(h_exec))+ .route("/v1/slots/:slot/read", post(h_read))+ .route("/v1/slots/:slot/write", post(h_write))+ .route("/v1/slots/:slot/edit", post(h_edit))+ .route("/v1/slots/:slot/list", post(h_list))+ .route("/v1/slots/:slot/search", post(h_search))+ .route("/v1/slots/:slot/diff", post(h_diff))+ .route("/v1/slots/:slot/commit", post(h_commit))+ .route("/v1/slots/:slot/bundle", get(h_bundle))+ .route("/v1/slots/:slot/cancel", post(h_cancel))+ .route("/v1/builds/kill", post(h_builds_kill))+ .route("/v1/health", get(h_health))+ .with_state(state)+}++pub async fn run() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+ let state = Arc::new(AppState::from_env());+ std::fs::create_dir_all(&state.slots_dir)?;+ let addr = AppState::listen_addr();+ let listener = tokio::net::TcpListener::bind(&addr).await?;+ eprintln!(+ "agent-runner: listening on {addr} (slots={} dir={} mirror={})",+ state.num_slots,+ state.slots_dir.display(),+ state.mirror.display()+ );+ axum::serve(listener, router(state)).await?;+ Ok(())+}++#[cfg(test)]+mod tests;
infra/agents/runner/src/main.rs
diff --git a/infra/agents/runner/src/main.rs b/infra/agents/runner/src/main.rsindex f328e4d9d0..c5c029dece 100644--- a/infra/agents/runner/src/main.rs+++ b/infra/agents/runner/src/main.rs@@ -1 +1,7 @@-fn main() {}+#[tokio::main]+async fn main() {+ if let Err(e) = agent_runner::run().await {+ eprintln!("agent-runner: fatal: {e}");+ std::process::exit(1);+ }+}
infra/agents/runner/src/tests.rs
diff --git a/infra/agents/runner/src/tests.rs b/infra/agents/runner/src/tests.rsnew file mode 100644index 0000000000..75434452cc--- /dev/null+++ b/infra/agents/runner/src/tests.rs@@ -0,0 +1,679 @@+//! Tests for agent-runner: confinement, edit counts, truncation, timeout ++//! process-group kill, build-semaphore serialization, and the full+//! prepare -> write -> diff -> commit -> bundle flow against a temp bare+//! "mirror" repo.++use std::path::{Path, PathBuf};+use std::sync::Arc;++use super::*;+use proto::{EditRequest, ExecKind, ExecRequest, ReadRequest, WriteRequest};++fn test_state(slots_dir: &Path, mirror: &Path, num_slots: u32) -> Arc<AppState> {+ Arc::new(AppState::new(+ slots_dir.to_path_buf(),+ mirror.to_path_buf(),+ num_slots,+ ))+}++fn make_slot_root() -> tempfile::TempDir {+ tempfile::tempdir().expect("tempdir")+}++fn init_slot_root(dir: &tempfile::TempDir, slot: u32) -> PathBuf {+ let root = dir.path().join(format!("slot-{slot}"));+ std::fs::create_dir_all(&root).unwrap();+ root+}++// ---------------------------------------------------------------------------+// Path confinement+// ---------------------------------------------------------------------------++#[test]+fn confinement_rejects_absolute_paths() {+ let dir = make_slot_root();+ let root = init_slot_root(&dir, 0);+ assert!(resolve_in_slot(&root, "/etc/passwd").is_err());+ assert!(resolve_in_slot(&root, "/builds/slots/slot-0/x").is_err());+}++#[test]+fn confinement_rejects_dotdot_escapes() {+ let dir = make_slot_root();+ let root = init_slot_root(&dir, 0);+ assert!(resolve_in_slot(&root, "../other").is_err());+ assert!(resolve_in_slot(&root, "a/../../..").is_err());+ assert!(resolve_in_slot(&root, "a/b/../../../../etc").is_err());+ // `..` that stays inside is fine.+ let ok = resolve_in_slot(&root, "a/../b").expect("a/../b stays inside");+ assert_eq!(ok, root.join("b"));+}++#[test]+fn confinement_rejects_git_dir() {+ let dir = make_slot_root();+ let root = init_slot_root(&dir, 0);+ assert!(resolve_in_slot(&root, ".git/config").is_err());+ assert!(resolve_in_slot(&root, ".git").is_err());+ assert!(resolve_in_slot(&root, "a/.git/hooks").is_ok());+}++#[test]+fn confinement_rejects_empty_and_nul() {+ let dir = make_slot_root();+ let root = init_slot_root(&dir, 0);+ assert!(resolve_in_slot(&root, "").is_err());+ assert!(resolve_in_slot(&root, "a\0b").is_err());+}++#[cfg(unix)]+#[test]+fn confinement_rejects_symlink_escape() {+ use std::os::unix::fs::symlink;+ let dir = make_slot_root();+ let root = init_slot_root(&dir, 0);+ let outside = dir.path().join("outside");+ std::fs::create_dir_all(&outside).unwrap();+ std::fs::write(outside.join("secret.txt"), "secret").unwrap();+ // Symlink inside the slot pointing outside.+ symlink(&outside, root.join("link")).unwrap();+ // Direct traversal through the symlink.+ assert!(resolve_in_slot(&root, "link/secret.txt").is_err());+ // A new file created through a symlinked directory would land outside.+ assert!(resolve_in_slot(&root, "link/newfile.txt").is_err());+ // And a symlink directly at the requested path.+ symlink(outside.join("secret.txt"), root.join("evil")).unwrap();+ assert!(resolve_in_slot(&root, "evil").is_err());+ // Benign symlink staying inside is allowed.+ std::fs::create_dir_all(root.join("real")).unwrap();+ std::fs::write(root.join("real/ok.txt"), "ok").unwrap();+ symlink(root.join("real"), root.join("good")).unwrap();+ assert!(resolve_in_slot(&root, "good/ok.txt").is_ok());+}++// ---------------------------------------------------------------------------+// Branch validation+// ---------------------------------------------------------------------------++#[test]+fn branch_validation() {+ assert!(validate_branch("agent/foo").is_ok());+ assert!(validate_branch("agent/foo-bar_baz/qux").is_ok());+ assert!(validate_branch("main").is_err());+ assert!(validate_branch("agent/").is_err());+ assert!(validate_branch("agent/../x").is_err());+ assert!(validate_branch("agent/a..b").is_err());+ assert!(validate_branch("agent/a b").is_err());+ assert!(validate_branch("agent/.hidden").is_err());+ assert!(validate_branch("agent/a.lock").is_err());+ assert!(validate_branch("agent/a:b").is_err());+}++// ---------------------------------------------------------------------------+// Edit match counts+// ---------------------------------------------------------------------------++#[test]+fn edit_requires_exactly_one_match() {+ assert_eq!(+ apply_edit("aaa bbb", "bbb", "ccc").unwrap(),+ "aaa ccc".to_string()+ );+ assert!(apply_edit("aaa", "zzz", "ccc").is_err()); // zero matches+ assert!(apply_edit("x x x", "x", "y").is_err()); // N matches+ assert!(apply_edit("aaa", "", "ccc").is_err()); // empty old+}++// ---------------------------------------------------------------------------+// Output truncation+// ---------------------------------------------------------------------------++#[test]+fn truncate_bytes_keeps_head_and_tail() {+ let cap = 64usize;+ let data: Vec<u8> = (0..200u32).map(|i| b'a' + (i % 26) as u8).collect();+ let (s, truncated) = truncate_bytes(&data, cap);+ assert!(truncated);+ assert!(s.contains("truncated"));+ // Head and tail survive.+ assert!(s.starts_with("abcdef"));+ let tail: Vec<u8> = data[data.len() - cap / 2..].to_vec();+ assert!(s.ends_with(std::str::from_utf8(&tail).unwrap()));+ let (s2, t2) = truncate_bytes(b"small", cap);+ assert!(!t2);+ assert_eq!(s2, "small");+}++// ---------------------------------------------------------------------------+// Exec helpers: need a prepared slot root dir (plain dir, not git).+// ---------------------------------------------------------------------------++fn exec_state(dir: &tempfile::TempDir, num_slots: u32) -> Arc<AppState> {+ // Mirror unused for exec tests; point at the temp dir.+ test_state(dir.path(), dir.path(), num_slots)+}++#[tokio::test]+async fn exec_captures_output_and_exit_code() {+ let dir = make_slot_root();+ let state = exec_state(&dir, 2);+ init_slot_root(&dir, 0);+ let resp = exec_in_slot(+ &state,+ 0,+ &ExecRequest {+ command: "echo hello-out; echo hello-err >&2; exit 3".to_string(),+ kind: ExecKind::Shell,+ timeout_secs: 30,+ },+ )+ .await+ .unwrap();+ assert_eq!(resp.exit_code, Some(3));+ assert!(resp.stdout.contains("hello-out"));+ assert!(resp.stderr.contains("hello-err"));+ assert!(!resp.timed_out && !resp.killed && !resp.truncated);+}++#[tokio::test]+async fn exec_truncates_large_output() {+ let dir = make_slot_root();+ let state = exec_state(&dir, 2);+ init_slot_root(&dir, 0);+ let resp = exec_in_slot(+ &state,+ 0,+ &ExecRequest {+ command: "yes OUT | head -c 200000".to_string(),+ kind: ExecKind::Shell,+ timeout_secs: 30,+ },+ )+ .await+ .unwrap();+ assert!(resp.truncated, "expected truncated output");+ assert!(resp.stdout.len() < 200_000);+}++#[tokio::test]+async fn exec_timeout_kills_whole_process_group() {+ let dir = make_slot_root();+ let state = exec_state(&dir, 2);+ let root = init_slot_root(&dir, 0);+ let heartbeat = dir.path().join("heartbeat.log");+ // A background grandchild appends heartbeats forever; the foreground+ // sleep keeps the leader alive past the 2s timeout. If killpg kills the+ // whole group, heartbeats stop the moment exec returns; if only the+ // leader died, they keep growing.+ let resp = exec_in_slot(+ &state,+ 0,+ &ExecRequest {+ command: format!(+ "(while true; do date +%s >> {}; sleep 0.2; done) & sleep 30",+ heartbeat.display()+ ),+ kind: ExecKind::Shell,+ timeout_secs: 2,+ },+ )+ .await+ .unwrap();+ assert!(resp.timed_out, "expected timed_out");+ assert_eq!(resp.exit_code, None);+ assert!(root.exists());+ // The whole process group must die: after exec returns, the heartbeat+ // file stops growing. A grandchild that survived the killpg would keep+ // appending (it loops forever with no exit condition).+ let size_after = std::fs::metadata(&heartbeat).unwrap().len();+ tokio::time::sleep(Duration::from_secs(2)).await;+ let size_later = std::fs::metadata(&heartbeat).unwrap().len();+ assert_eq!(+ size_after, size_later,+ "background grandchild survived the process-group kill \+ (heartbeat grew from {size_after} to {size_later} bytes)"+ );+}++#[tokio::test]+async fn exec_cancel_kills_running_shell() {+ let dir = make_slot_root();+ let state = exec_state(&dir, 2);+ init_slot_root(&dir, 0);+ let state2 = state.clone();+ let handle = tokio::spawn(async move {+ exec_in_slot(+ &state2,+ 0,+ &ExecRequest {+ command: "sleep 60".to_string(),+ kind: ExecKind::Shell,+ timeout_secs: 120,+ },+ )+ .await+ .unwrap()+ });+ // Wait until the exec registers itself, then cancel.+ let mut saw_running = false;+ for _ in 0..100 {+ {+ if state.running.lock().await.contains_key(&0) {+ saw_running = true;+ break;+ }+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ assert!(saw_running, "exec never registered as running");+ assert!(cancel_slot(&state, 0).await);+ let resp = handle.await.unwrap();+ assert!(resp.killed, "expected killed, got {resp:?}");+ assert_eq!(resp.exit_code, None);+ assert!(!cancel_slot(&state, 0).await, "nothing left to cancel");+}++#[tokio::test]+async fn exec_build_serializes_and_reports_queue_time() {+ let dir = make_slot_root();+ let state = exec_state(&dir, 2);+ init_slot_root(&dir, 0);+ init_slot_root(&dir, 1);+ let mk = |cmd: &str| ExecRequest {+ command: cmd.to_string(),+ kind: ExecKind::Build,+ timeout_secs: 60,+ };+ let s1 = state.clone();+ let s2 = state.clone();+ let t0 = Instant::now();+ let req1 = mk("date +%s%N; sleep 3");+ let req2 = mk("date +%s%N");+ let (r1, r2) = tokio::join!(+ exec_in_slot(&s1, 0, &req1),+ async {+ // Start the second build slightly later so it must queue.+ tokio::time::sleep(Duration::from_millis(300)).await;+ exec_in_slot(&s2, 1, &req2).await.unwrap()+ }+ );+ let r1 = r1.unwrap();+ assert_eq!(r1.exit_code, Some(0));+ // Serialized: total wall time is at least the first build's sleep.+ assert!(+ t0.elapsed() >= Duration::from_secs(3),+ "builds overlapped: {:?}",+ t0.elapsed()+ );+ assert!(+ r2.queued_ms >= 2000,+ "second build should have queued ~3s, got {}ms",+ r2.queued_ms+ );+ // Health flag clears afterwards.+ assert!(!state.build_running.load(Ordering::SeqCst));+}++#[tokio::test]+async fn exec_build_kill_endpoint_kills_inflight_build() {+ let dir = make_slot_root();+ let state = exec_state(&dir, 2);+ init_slot_root(&dir, 0);+ let s2 = state.clone();+ let handle = tokio::spawn(async move {+ exec_in_slot(+ &s2,+ 0,+ &ExecRequest {+ command: "sleep 60".to_string(),+ kind: ExecKind::Build,+ timeout_secs: 120,+ },+ )+ .await+ .unwrap()+ });+ for _ in 0..100 {+ if state.build_running.load(Ordering::SeqCst) {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ assert!(state.build_running.load(Ordering::SeqCst));+ assert!(kill_build(&state).await);+ let resp = handle.await.unwrap();+ assert!(resp.killed, "expected killed, got {resp:?}");+ assert!(!kill_build(&state).await);+}++#[tokio::test]+async fn exec_invalid_slot_is_404() {+ let dir = make_slot_root();+ let state = exec_state(&dir, 2);+ assert!(parse_slot(&state, "2").is_err());+ assert!(parse_slot(&state, "99").is_err());+ assert!(parse_slot(&state, "-1").is_err());+ assert!(parse_slot(&state, "abc").is_err());+ assert_eq!(parse_slot(&state, "1").unwrap(), 1);+}++// ---------------------------------------------------------------------------+// Full git flow against a temp bare "mirror" repo.+// ---------------------------------------------------------------------------++fn git(dir: &Path, args: &[&str]) {+ let status = std::process::Command::new("git")+ .args(args)+ .current_dir(dir)+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .env("GIT_CONFIG_SYSTEM", "/dev/null")+ .status()+ .expect("spawn git");+ assert!(status.success(), "git {args:?} failed in {dir:?}");+}++fn git_out(dir: &Path, args: &[&str]) -> String {+ let out = std::process::Command::new("git")+ .args(args)+ .current_dir(dir)+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .env("GIT_CONFIG_SYSTEM", "/dev/null")+ .output()+ .expect("spawn git");+ assert!(out.status.success(), "git {args:?} failed: {out:?}");+ String::from_utf8(out.stdout).unwrap().trim().to_string()+}++/// Build a temp bare mirror with one commit on `main`, plus a surrounding+/// state with isolated slots/mirror dirs.+struct GitFlow {+ _tmp: tempfile::TempDir,+ state: Arc<AppState>,+}++fn setup_git_flow() -> GitFlow {+ let tmp = tempfile::tempdir().expect("tempdir");+ let seed = tmp.path().join("seed");+ std::fs::create_dir_all(&seed).unwrap();+ git(&seed, &["init", "-b", "main"]);+ git(&seed, &["config", "user.email", "[email protected]"]);+ git(&seed, &["config", "user.name", "test"]);+ std::fs::write(seed.join("README.md"), "hello\n").unwrap();+ // Tracked .gitignore, like the real repo's: ignored build outputs must+ // survive prepare's `git clean -fd` (which keeps ignored files).+ std::fs::write(seed.join(".gitignore"), "build/\n").unwrap();+ git(&seed, &["add", "-A"]);+ git(&seed, &["commit", "-m", "initial"]);+ let mirror = tmp.path().join("mirror.git");+ let status = std::process::Command::new("git")+ .args([+ "clone",+ "--bare",+ seed.to_str().unwrap(),+ mirror.to_str().unwrap(),+ ])+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .env("GIT_CONFIG_SYSTEM", "/dev/null")+ .status()+ .unwrap();+ assert!(status.success());+ let slots = tmp.path().join("slots");+ std::fs::create_dir_all(&slots).unwrap();+ let state = Arc::new(AppState::new(slots, mirror, 2));+ GitFlow { _tmp: tmp, state }+}++#[tokio::test]+async fn gitflow_prepare_write_diff_commit_bundle() {+ let flow = setup_git_flow();+ let state = &flow.state;++ // prepare+ let base = prepare_slot(state, 0, "agent/test-flow").await.unwrap();+ assert_eq!(base.len(), 40);+ // prepare is idempotent+ let base2 = prepare_slot(state, 0, "agent/test-flow").await.unwrap();+ assert_eq!(base, base2);+ // bad branch rejected+ assert!(prepare_slot(state, 0, "main").await.is_err());++ // clean -fd keeps ignored build outputs: an ignored build/ file created+ // after prepare survives the *next* prepare (warm caches persist).+ let slot = slot_root(state, 0);+ std::fs::create_dir_all(slot.join("build")).unwrap();+ std::fs::write(slot.join("build/warm.txt"), "warm").unwrap();+ prepare_slot(state, 0, "agent/test-flow").await.unwrap();+ assert!(+ slot.join("build/warm.txt").exists(),+ "ignored build/ output must survive prepare"+ );++ // write + edit + read+ write_slot_file(+ state,+ 0,+ &WriteRequest {+ path: "notes/todo.txt".to_string(),+ content: "line1\nline2 needle\nline3\n".to_string(),+ },+ )+ .await+ .unwrap();+ super::edit_slot_file(+ state,+ 0,+ &EditRequest {+ path: "notes/todo.txt".to_string(),+ old: "line2 needle".to_string(),+ new: "line2 done".to_string(),+ },+ )+ .await+ .unwrap();+ let read = super::read_slot_file(+ state,+ 0,+ &ReadRequest {+ path: "notes/todo.txt".to_string(),+ start_line: None,+ max_lines: None,+ },+ )+ .await+ .unwrap();+ assert!(read.content.contains("line2 done"));+ assert_eq!(read.total_lines, 3);+ assert!(!read.truncated);++ // zero-match and multi-match edits are 409s.+ let e0 = super::edit_slot_file(+ state,+ 0,+ &EditRequest {+ path: "notes/todo.txt".to_string(),+ old: "nope".to_string(),+ new: "x".to_string(),+ },+ )+ .await;+ assert_eq!(e0.unwrap_err().status, StatusCode::CONFLICT);+ std::fs::write(slot.join("multi.txt"), "a a a").unwrap();+ let e1 = super::edit_slot_file(+ state,+ 0,+ &EditRequest {+ path: "multi.txt".to_string(),+ old: "a".to_string(),+ new: "b".to_string(),+ },+ )+ .await;+ assert_eq!(e1.unwrap_err().status, StatusCode::CONFLICT);++ // read paging+ let page = super::read_slot_file(+ state,+ 0,+ &ReadRequest {+ path: "notes/todo.txt".to_string(),+ start_line: Some(2),+ max_lines: Some(1),+ },+ )+ .await+ .unwrap();+ assert_eq!(page.content, "line2 done");+ assert!(page.truncated);++ // list+ let list = super::list_slot_dir(+ state,+ 0,+ &proto::ListRequest {+ path: ".".to_string(),+ },+ )+ .await+ .unwrap();+ assert!(list.entries.iter().any(|e| e == "notes/"));++ // diff includes untracked files (multi.txt is untracked).+ let diff = diff_slot(state, 0).await.unwrap();+ assert!(diff.diff.contains("todo.txt"), "diff: {}", diff.diff);+ assert!(diff.diff.contains("multi.txt"), "diff: {}", diff.diff);++ // commit refuses empty, succeeds with changes.+ std::fs::remove_file(slot.join("multi.txt")).unwrap();+ std::fs::remove_file(slot.join("build/warm.txt")).unwrap();+ let sha = commit_slot(+ state,+ 0,+ &proto::CommitRequest {+ message: "agent work".to_string(),+ },+ )+ .await+ .unwrap();+ assert_eq!(sha.len(), 40);+ let empty = commit_slot(+ state,+ 0,+ &proto::CommitRequest {+ message: "nothing".to_string(),+ },+ )+ .await;+ assert_eq!(empty.unwrap_err().status, StatusCode::CONFLICT);++ // Bundle verifies, and it imports into a repo holding the base commit.+ // (`base..branch` bundles are thin packs whose prerequisite is the base;+ // agentd imports into the mirror, which has it. Verify from the slot, and+ // fetch into a clone of the mirror — a fresh empty repo correctly fails+ // with "lacks these prerequisite commits".)+ let (_branch, bytes) = bundle_slot(state, 0).await.unwrap();+ assert!(!bytes.is_empty());+ let bundle_path = state.slots_dir.join("test.bundle");+ std::fs::write(&bundle_path, &bytes).unwrap();+ let verify = std::process::Command::new("git")+ .args(["bundle", "verify", bundle_path.to_str().unwrap()])+ .current_dir(&slot)+ .output()+ .unwrap();+ assert!(+ verify.status.success(),+ "git bundle verify failed: {verify:?}"+ );+ let clone_dir = tempfile::tempdir().unwrap();+ git(+ clone_dir.path(),+ &[+ "clone",+ state.mirror.to_str().unwrap(),+ "imported",+ ],+ );+ let imported = clone_dir.path().join("imported");+ git(+ &imported,+ &[+ "fetch",+ bundle_path.to_str().unwrap(),+ "agent/test-flow:refs/heads/fetched",+ ],+ );+ let fetched = git_out(&imported, &["rev-parse", "fetched"]);+ assert_eq!(fetched, sha);++ // bundle with no commits is 409.+ prepare_slot(state, 1, "agent/empty-branch").await.unwrap();+ let b2 = bundle_slot(state, 1).await;+ assert_eq!(b2.unwrap_err().status, StatusCode::CONFLICT);+}++#[tokio::test]+async fn search_respects_excludes_and_globs() {+ let rg_available = std::process::Command::new("rg")+ .arg("--version")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false);+ if !rg_available {+ eprintln!("skipping search test: rg not installed");+ return;+ }+ let dir = make_slot_root();+ let state = exec_state(&dir, 2);+ let root = init_slot_root(&dir, 0);+ std::fs::write(root.join("hit.kt"), "needle here\n").unwrap();+ std::fs::create_dir_all(root.join("build")).unwrap();+ std::fs::write(root.join("build/hit.kt"), "needle here\n").unwrap();+ let resp = super::search_slot(+ &state,+ 0,+ &proto::SearchRequest {+ pattern: "needle".to_string(),+ path: None,+ glob: None,+ fixed_string: false,+ },+ )+ .await+ .unwrap();+ assert!(resp.matches.contains("hit.kt:1"), "got: {}", resp.matches);+ assert!(+ !resp.matches.contains("build/"),+ "build/ must be excluded: {}",+ resp.matches+ );+ // glob filter+ let resp2 = super::search_slot(+ &state,+ 0,+ &proto::SearchRequest {+ pattern: "needle".to_string(),+ path: None,+ glob: Some("*.java".to_string()),+ fixed_string: false,+ },+ )+ .await+ .unwrap();+ assert!(!resp2.matches.contains("hit.kt"), "glob must filter: {}", resp2.matches);+ // fixed strings: regex chars are literal.+ std::fs::write(root.join("re.txt"), "a.c\n").unwrap();+ let resp3 = super::search_slot(+ &state,+ 0,+ &proto::SearchRequest {+ pattern: "a.c".to_string(),+ path: None,+ glob: Some("re.txt".to_string()),+ fixed_string: true,+ },+ )+ .await+ .unwrap();+ assert!(resp3.matches.contains("re.txt"), "got: {}", resp3.matches);+}