Modern Apps git

← Modern-Apps.git

infra: agentd web UI, task queue and OpenRouter agent loop

Commit
ccd255ccb88cb04cf6fadc8921504ec3e7e7bb25
Author
Vayun Mathur <[email protected]>
When
2026-11-05 02:14 UTC (1 month ago)
Parents
ace20de
agentd is the trusted half of the on-server agent harness. It never
executes model-chosen commands itself; everything runs through the
agent-runner in the builder sandbox over the proto API.

- Web UI (axum + maud, auto-escaped): login with an argon2id hash from
  env, HttpOnly/Secure/SameSite=Strict session cookie (only its hash is
  stored), Origin check on every POST, CSP self-only and frame-ancestors
  none. Routes: /login, /logout, / (tasks), /tasks/new, POST /tasks,
  /tasks/:id (live log via SSE at /tasks/:id/events, diff, cost),
  /tasks/:id/cancel, /tasks/:id/retry, unauthenticated /healthz. The
  builder can reach this port, so agentd authenticates every request
  itself. Login backoff keys on CF-Connecting-IP (Caddy rewrites XFF to
  the Cloudflare edge) with a global 60/min cap.
- SQLite store (tasks, events, sessions) under /state; queue survives
  restarts.
- Scheduler: N slots, one task per slot. Release preemption polls the
  release-signal file: build tool calls wait while a prod release runs,
  and an in-flight build is killed via the runner when one starts.
- Agent loop: OpenRouter chat completions with tool calling and
  usage cost accounting; system prompt injects root and module
  AGENTS.md; per-task step and USD budgets; result truncation and
  context trimming. Tools map 1:1 to proto routes; `build` is an
  allowlist of scoped ./gradlew tasks and ./check <module>; run_shell
  rejects gradlew/cargo builds/./install/adb.
- Git: bare mirror cloned from git.maproj.org with gc pruning disabled
  (slots use it as alternates). On finish: runner commit, bundle
  download + verify, import into refs/agent-out/*, push to
  refs/heads/agent/* with the scoped token via http.extraHeader (never
  in URL/argv/logs; secrets scrubbed from events).
- Dockerfile.agentd: rust:1-bookworm build, debian-slim runtime with
  git, uid 10002.
- proto: turn the free-floating bundle route doc block into a plain
  comment (clippy empty_line_after_doc_comments).

Tests: 22 unit + in-process integration tests (mock OpenRouter + mock
runner against real temp git repos: full task to pushed branch, token
never in events/pages, unauthenticated and wrong-Origin POSTs rejected,
release signal preempts builds), passing 6/6 runs serial and parallel.
cargo clippy -p agentd -p proto --all-targets -D warnings clean.

Diff

infra/agents/Cargo.lock
diff --git a/infra/agents/Cargo.lock b/infra/agents/Cargo.lockindex db6a8ba86d..b4a1a38d76 100644--- a/infra/agents/Cargo.lock+++ b/infra/agents/Cargo.lock@@ -19,9 +19,54 @@ dependencies = [ name = "agentd" version = "0.1.0" dependencies = [+ "argon2",+ "axum",+ "maud",  "proto",+ "rand 0.9.5",+ "reqwest",+ "rusqlite",  "serde",  "serde_json",+ "sha2",+ "tempfile",+ "tokio",+ "tokio-stream",+ "tracing",+ "tracing-subscriber",+]++[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "once_cell",+ "version_check",+ "zerocopy",+]++[[package]]+name = "aho-corasick"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"+dependencies = [+ "memchr",+]++[[package]]+name = "argon2"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"+dependencies = [+ "base64ct",+ "blake2",+ "cpufeatures 0.2.17",+ "password-hash", ]  [[package]]@@ -32,7 +77,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [  "proc-macro2",  "quote",- "syn",+ "syn 3.0.9", ]  [[package]]@@ -96,24 +141,143 @@ dependencies = [  "tracing", ] +[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"++[[package]]+name = "base64"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"++[[package]]+name = "base64ct"+version = "1.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"+ [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]]+name = "blake2"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"+dependencies = [+ "digest",+]++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"+ [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]]+name = "cc"+version = "1.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b"+dependencies = [+ "find-msvc-tools",+ "shlex",+]+ [[package]] name = "cfg-if" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]]+name = "cfg_aliases"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"++[[package]]+name = "chacha20"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.1",+ "rand_core 0.10.1",+]++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "cpufeatures"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"+dependencies = [+ "libc",+]++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+ "subtle",+]++[[package]]+name = "displaydoc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]+ [[package]] name = "errno" version = "0.3.14"@@ -121,15 +285,33 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [  "libc",- "windows-sys",+ "windows-sys 0.61.2", ] +[[package]]+name = "fallible-iterator"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"++[[package]]+name = "fallible-streaming-iterator"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"+ [[package]] name = "fastrand" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]]+name = "find-msvc-tools"+version = "0.1.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"+ [[package]] name = "form_urlencoded" version = "1.2.2"@@ -139,12 +321,27 @@ dependencies = [  "percent-encoding", ] +[[package]]+name = "futures-channel"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"+dependencies = [+ "futures-core",+]+ [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]]+name = "futures-sink"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"+ [[package]] name = "futures-task" version = "0.3.34"@@ -163,6 +360,41 @@ dependencies = [  "slab", ] +[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "wasi",+ "wasm-bindgen",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 5.3.0",+ "wasip2",+]+ [[package]] name = "getrandom" version = "0.4.3"@@ -170,8 +402,29 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [  "cfg-if",+ "js-sys",  "libc",- "r-efi",+ "r-efi 6.0.0",+ "rand_core 0.10.1",+ "wasm-bindgen",+]++[[package]]+name = "hashbrown"+version = "0.14.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"+dependencies = [+ "ahash",+]++[[package]]+name = "hashlink"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"+dependencies = [+ "hashbrown", ]  [[package]]@@ -236,6 +489,23 @@ dependencies = [  "pin-project-lite",  "smallvec",  "tokio",+ "want",+]++[[package]]+name = "hyper-rustls"+version = "0.27.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"+dependencies = [+ "http",+ "hyper",+ "hyper-util",+ "rustls",+ "tokio",+ "tokio-rustls",+ "tower-service",+ "webpki-roots", ]  [[package]]@@ -244,33 +514,186 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [+ "base64 0.23.1",  "bytes",+ "futures-channel",+ "futures-util",  "http",  "http-body",+ "httparse",  "hyper",+ "ipnet",+ "libc",+ "percent-encoding",  "pin-project-lite",+ "socket2",  "tokio",  "tower-service",+ "tracing",+]++[[package]]+name = "icu_collections"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc"++[[package]]+name = "icu_properties"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f"+dependencies = [+ "displaydoc",+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf"++[[package]]+name = "icu_provider"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties", ] +[[package]]+name = "ipnet"+version = "2.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"+ [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]]+name = "js-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "lazy_static"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"+ [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]]+name = "libsqlite3-sys"+version = "0.30.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"+dependencies = [+ "cc",+ "pkg-config",+ "vcpkg",+]+ [[package]] name = "linux-raw-sys" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]]+name = "litemap"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"+ [[package]] name = "lock_api" version = "0.4.14"@@ -286,12 +709,49 @@ version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]]+name = "lru-slab"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"++[[package]]+name = "matchers"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"+dependencies = [+ "regex-automata",+]+ [[package]] name = "matchit" version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" +[[package]]+name = "maud"+version = "0.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8156733e27020ea5c684db5beac5d1d611e1272ab17901a49466294b84fc217e"+dependencies = [+ "itoa",+ "maud_macros",+]++[[package]]+name = "maud_macros"+version = "0.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7261b00f3952f617899bc012e3dbd56e4f0110a038175929fa5d18e5a19913ca"+dependencies = [+ "proc-macro2",+ "proc-macro2-diagnostics",+ "quote",+ "syn 2.0.119",+]+ [[package]] name = "memchr" version = "2.8.3"@@ -312,7 +772,16 @@ checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [  "libc",  "wasi",- "windows-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "nu-ansi-term"+version = "0.50.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"+dependencies = [+ "windows-sys 0.61.2", ]  [[package]]@@ -344,6 +813,17 @@ dependencies = [  "windows-link", ] +[[package]]+name = "password-hash"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"+dependencies = [+ "base64ct",+ "rand_core 0.6.4",+ "subtle",+]+ [[package]] name = "percent-encoding" version = "2.3.2"@@ -357,7 +837,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"  [[package]]-name = "proc-macro2"+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "potential_utf"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"+dependencies = [+ "zerovec",+]++[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]++[[package]]+name = "proc-macro2" version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"@@ -365,6 +869,18 @@ dependencies = [  "unicode-ident", ] +[[package]]+name = "proc-macro2-diagnostics"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "version_check",+]+ [[package]] name = "proto" version = "0.1.0"@@ -372,6 +888,62 @@ dependencies = [  "serde", ] +[[package]]+name = "quinn"+version = "0.11.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"+dependencies = [+ "bytes",+ "cfg_aliases",+ "pin-project-lite",+ "quinn-proto",+ "quinn-udp",+ "rustc-hash",+ "rustls",+ "socket2",+ "thiserror",+ "tokio",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-proto"+version = "0.11.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"+dependencies = [+ "bytes",+ "getrandom 0.4.3",+ "lru-slab",+ "rand 0.10.3",+ "rand_pcg",+ "ring",+ "rustc-hash",+ "rustls",+ "rustls-pki-types",+ "slab",+ "thiserror",+ "tinyvec",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-udp"+version = "0.5.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"+dependencies = [+ "cfg_aliases",+ "libc",+ "once_cell",+ "socket2",+ "tracing",+ "windows-sys 0.61.2",+]+ [[package]] name = "quote" version = "1.0.47"@@ -381,12 +953,79 @@ dependencies = [  "proc-macro2", ] +[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"+ [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]]+name = "rand"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"+dependencies = [+ "rand_chacha",+ "rand_core 0.9.5",+]++[[package]]+name = "rand"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"+dependencies = [+ "chacha20",+ "getrandom 0.4.3",+ "rand_core 0.10.1",+]++[[package]]+name = "rand_chacha"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"+dependencies = [+ "ppv-lite86",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"++[[package]]+name = "rand_core"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+dependencies = [+ "getrandom 0.3.4",+]++[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"++[[package]]+name = "rand_pcg"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"+dependencies = [+ "rand_core 0.10.1",+]+ [[package]] name = "redox_syscall" version = "0.5.18"@@ -396,6 +1035,95 @@ dependencies = [  "bitflags", ] +[[package]]+name = "regex-automata"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "reqwest"+version = "0.12.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-util",+ "js-sys",+ "log",+ "percent-encoding",+ "pin-project-lite",+ "quinn",+ "rustls",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tokio-rustls",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "webpki-roots",+]++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "rusqlite"+version = "0.32.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"+dependencies = [+ "bitflags",+ "fallible-iterator",+ "fallible-streaming-iterator",+ "hashlink",+ "libsqlite3-sys",+ "smallvec",+]++[[package]]+name = "rustc-hash"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"+ [[package]] name = "rustix" version = "1.1.6"@@ -406,7 +1134,42 @@ dependencies = [  "errno",  "libc",  "linux-raw-sys",- "windows-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls"+version = "0.23.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"+dependencies = [+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-pki-types"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"+dependencies = [+ "web-time",+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted", ]  [[package]]@@ -454,7 +1217,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [  "proc-macro2",  "quote",- "syn",+ "syn 3.0.9", ]  [[package]]@@ -493,6 +1256,32 @@ dependencies = [  "serde", ] +[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest",+]++[[package]]+name = "sharded-slab"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"+dependencies = [+ "lazy_static",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"+ [[package]] name = "signal-hook-registry" version = "1.4.8"@@ -522,7 +1311,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [  "libc",- "windows-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident", ]  [[package]]@@ -541,6 +1353,20 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"+dependencies = [+ "futures-core",+]++[[package]]+name = "synstructure"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]  [[package]] name = "tempfile"@@ -549,12 +1375,57 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [  "fastrand",- "getrandom",+ "getrandom 0.4.3",  "once_cell",  "rustix",- "windows-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "thread_local"+version = "1.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"+dependencies = [+ "cfg-if",+]++[[package]]+name = "tinystr"+version = "0.8.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a"+dependencies = [+ "displaydoc",+ "zerovec", ] +[[package]]+name = "tinyvec"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"+ [[package]] name = "tokio" version = "1.54.1"@@ -569,7 +1440,7 @@ dependencies = [  "signal-hook-registry",  "socket2",  "tokio-macros",- "windows-sys",+ "windows-sys 0.61.2", ]  [[package]]@@ -580,7 +1451,42 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [  "proc-macro2",  "quote",- "syn",+ "syn 3.0.9",+]++[[package]]+name = "tokio-rustls"+version = "0.26.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"+dependencies = [+ "rustls",+ "tokio",+]++[[package]]+name = "tokio-stream"+version = "0.1.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+ "tokio-util",+]++[[package]]+name = "tokio-util"+version = "0.7.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "pin-project-lite",+ "tokio", ]  [[package]]@@ -599,6 +1505,24 @@ dependencies = [  "tracing", ] +[[package]]+name = "tower-http"+version = "0.6.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"+dependencies = [+ "bitflags",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "pin-project-lite",+ "tower",+ "tower-layer",+ "tower-service",+ "url",+]+ [[package]] name = "tower-layer" version = "0.3.3"@@ -619,9 +1543,21 @@ checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [  "log",  "pin-project-lite",+ "tracing-attributes",  "tracing-core", ] +[[package]]+name = "tracing-attributes"+version = "0.1.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+ [[package]] name = "tracing-core" version = "0.1.36"@@ -629,26 +1565,230 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [  "once_cell",+ "valuable",+]++[[package]]+name = "tracing-log"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"+dependencies = [+ "log",+ "once_cell",+ "tracing-core", ] +[[package]]+name = "tracing-subscriber"+version = "0.3.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"+dependencies = [+ "matchers",+ "nu-ansi-term",+ "once_cell",+ "regex-automata",+ "sharded-slab",+ "smallvec",+ "thread_local",+ "tracing",+ "tracing-core",+ "tracing-log",+]++[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"+ [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+]++[[package]]+name = "utf8_iter"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0"+dependencies = [+ "utf_types",+]++[[package]]+name = "utf_types"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"++[[package]]+name = "valuable"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"++[[package]]+name = "vcpkg"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "want"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"+dependencies = [+ "try-lock",+]+ [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]]+name = "wasip2"+version = "1.0.4+wasi-0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"+dependencies = [+ "cfg-if",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.80"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"+dependencies = [+ "js-sys",+ "tokio",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "web-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web-time"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "webpki-roots"+version = "1.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"+dependencies = [+ "rustls-pki-types",+]+ [[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.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets",+]+ [[package]] name = "windows-sys" version = "0.61.2"@@ -658,6 +1798,185 @@ dependencies = [  "windows-link", ] +[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_gnullvm",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "wit-bindgen"+version = "0.57.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"++[[package]]+name = "writeable"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"++[[package]]+name = "yoke"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "synstructure",+]++[[package]]+name = "zerocopy"+version = "0.8.63"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.63"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "synstructure",+]++[[package]]+name = "zeroize"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"++[[package]]+name = "zerotrie"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]+ [[package]] name = "zmij" version = "1.0.23"
infra/agents/Cargo.toml
diff --git a/infra/agents/Cargo.toml b/infra/agents/Cargo.tomlindex a3f8d8940b..e3bfff6a72 100644--- a/infra/agents/Cargo.toml+++ b/infra/agents/Cargo.toml@@ -12,3 +12,15 @@ license = "Apache-2.0" proto = { path = "proto" } serde = { version = "1", features = ["derive"] } serde_json = "1"+tokio = { version = "1", features = ["full"] }+axum = { version = "0.7" }+reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }+rusqlite = { version = "0.32", features = ["bundled"] }+argon2 = "0.5"+rand = "0.9"+sha2 = "0.10"+tracing = "0.1"+tracing-subscriber = { version = "0.3", features = ["env-filter"] }+maud = "0.27"+tempfile = "3"+tokio-stream = { version = "0.1", features = ["sync"] }
infra/agents/Dockerfile.agentd
diff --git a/infra/agents/Dockerfile.agentd b/infra/agents/Dockerfile.agentdnew file mode 100644index 0000000000..c9bdde2f98--- /dev/null+++ b/infra/agents/Dockerfile.agentd@@ -0,0 +1,27 @@+# agentd: trusted orchestrator (web UI, task queue, OpenRouter loop, git push).+# Build context is infra/agents (Cargo workspace: proto, agentd, runner).++FROM rust:1-bookworm AS build+WORKDIR /src+COPY Cargo.toml Cargo.lock ./+COPY proto ./proto+COPY agentd ./agentd+# cargo resolves every workspace member even with -p; stub the runner.+COPY runner/Cargo.toml ./runner/Cargo.toml+RUN mkdir -p runner/src && echo 'fn main() {}' > runner/src/main.rs \+    && echo '' > runner/src/lib.rs+RUN cargo build -p agentd --release --locked++FROM debian:bookworm-slim+RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates \+    && rm -rf /var/lib/apt/lists/* \+    && groupadd -g 10002 agentd \+    && useradd -u 10002 -g 10002 -d /state -M -s /usr/sbin/nologin agentd \+    && mkdir -p /state /mirror /signal \+    && chown 10002:10002 /state /mirror+COPY --from=build /src/target/release/agentd /usr/local/bin/agentd+USER 10002:10002+# Mirror is shared read-only with the builder (another uid): keep it world-readable.+ENV HOME=/state+EXPOSE 8080+ENTRYPOINT ["/usr/local/bin/agentd"]
infra/agents/agentd/Cargo.toml
diff --git a/infra/agents/agentd/Cargo.toml b/infra/agents/agentd/Cargo.tomlindex 5f8aadecac..3b2b9e7941 100644--- a/infra/agents/agentd/Cargo.toml+++ b/infra/agents/agentd/Cargo.toml@@ -5,7 +5,27 @@ edition.workspace = true publish.workspace = true license.workspace = true +[[bin]]+name = "agentd"+path = "src/main.rs"+ [dependencies] proto.workspace = true serde.workspace = true serde_json.workspace = true+tokio.workspace = true+axum.workspace = true+reqwest.workspace = true+rusqlite.workspace = true+argon2.workspace = true+rand.workspace = true+sha2.workspace = true+tracing.workspace = true+tracing-subscriber.workspace = true+maud.workspace = true+tempfile.workspace = true+tokio-stream.workspace = true++[dev-dependencies]+tempfile.workspace = true+tokio-stream.workspace = true
infra/agents/agentd/src/agent.rs
diff --git a/infra/agents/agentd/src/agent.rs b/infra/agents/agentd/src/agent.rsnew file mode 100644index 0000000000..c3fecec229--- /dev/null+++ b/infra/agents/agentd/src/agent.rs@@ -0,0 +1,745 @@+//! The OpenRouter agent loop: one task, one slot, until `finish`/budget.+//!+//! Flow per task:+//! 1. `fetch origin main` in the mirror; runner `prepare`s the slot branch.+//! 2. Fetch root + module `AGENTS.md` through the runner; build the system+//!    prompt; seed the conversation with it and the task text.+//! 3. Loop: POST OpenRouter chat-completions → dispatch tool calls to the+//!    runner (allowlist validation, truncation, release-preemption for+//!    `build`) → append results. Every turn is persisted as an event and+//!    broadcast to SSE subscribers.+//! 4. On `finish{summary, commit_message}`: validate (non-empty diff,+//!    commit-message format; violations come back as a tool result so the+//!    model can retry), runner `/commit`, download `/bundle`,+//!    `bundle verify`, import into the mirror, push upstream.+//! 5. Terminal statuses: `succeeded` / `failed(reason)` / `cancelled`.++use std::sync::Arc;++use tokio::sync::broadcast;++use crate::config::Config;+use crate::models::{+    branch_name, truncate_result, trim_placeholder, validate_commit_message, Event,+};+use crate::openrouter::{tool_defs, AssistantTurn, Message, OpenRouter, ToolCall};+use crate::prompt::system_prompt;+use crate::runner::Runner;+use crate::store::Store;+use crate::tools::{validate_build_command, validate_shell_command};++/// Outcome of running one task to a terminal state.+#[derive(Debug)]+pub enum TaskOutcome {+    Succeeded {+        commit_sha: String,+        pushed: bool,+        summary: String,+    },+    Failed {+        reason: String,+    },+    Cancelled,+}++/// Shared runtime handles passed to every task driver.+#[derive(Clone)]+pub struct DriverCtx {+    pub config: Arc<Config>,+    pub store: Store,+    pub runner: Runner,+    pub openrouter: OpenRouter,+    /// Broadcast of `(task_id, event)` for SSE.+    pub events_tx: broadcast::Sender<(i64, Event)>,+}++impl DriverCtx {+    /// Persist an event and broadcast it (broadcast failure = no listeners).+    pub fn emit(&self, task_id: i64, kind: &str, body: serde_json::Value) -> Event {+        let ev = self+            .store+            .push_event(task_id, kind, &body)+            .unwrap_or(Event {+                id: -1,+                task_id,+                seq: -1,+                ts: crate::models::now_unix(),+                kind: kind.to_string(),+                body: body.clone(),+            });+        let _ = self.events_tx.send((task_id, ev.clone()));+        ev+    }+}++fn is_cancelled(store: &Store, task_id: i64) -> bool {+    use crate::models::TaskStatus;+    store+        .get_task(task_id)+        .ok()+        .flatten()+        .map(|t| t.status == TaskStatus::Cancelled)+        .unwrap_or(true)+}++/// Scrub `Bearer <secret>` values before a string is stored in an event or+/// log. The push token never flows through the loop, but a model could+/// hallucinate something shaped like one; redact defensively.+pub fn scrub_secrets(s: &str) -> String {+    let mut out = String::with_capacity(s.len());+    let mut rest = s;+    loop {+        if let Some(i) = rest.to_lowercase().find("bearer ") {+            out.push_str(&rest[..i + 7]);+            out.push_str("[redacted]");+            let tail = &rest[i + 7..];+            let end = tail+                .find(|c: char| c.is_whitespace() || c == '"' || c == '\'')+                .unwrap_or(tail.len());+            rest = &tail[end..];+        } else {+            out.push_str(rest);+            break;+        }+    }+    out+}++/// Short (<=400 char) preview of tool arguments for the event log.+fn args_preview(args: &str) -> String {+    const MAX: usize = 400;+    if args.len() <= MAX {+        args.to_string()+    } else {+        format!("{}…[{} chars]", &args[..MAX], args.len())+    }+}++/// Look up a string argument.+fn arg_str(args: &serde_json::Value, key: &str) -> Option<String> {+    args.get(key)+        .and_then(|v| v.as_str())+        .map(|s| s.to_string())+}++/// Release-signal check: `true` while a production release build runs.+pub fn release_active(config: &Config) -> bool {+    config.release_signal.exists()+}++/// Wait out the release signal (polling), up to the configured limit.+/// Returns `Err(msg)` when the wait expires (message goes to the model).+pub async fn wait_for_release_clear(+    ctx: &DriverCtx,+    task_id: i64,+    _command: &str,+) -> Result<(), String> {+    if ctx.config.test_skip_release_wait {+        // Test seam: behave as if preemption fired immediately. Match the+        // production preemption message so tests assert one string.+        let _ = ctx.runner.kill_build().await;+        return Err("build preempted by a production release; retry later".to_string());+    }+    let limit = ctx.config.build_wait_limit();+    let poll = ctx.config.poll_interval();+    let start = std::time::Instant::now();+    ctx.emit(+        task_id,+        "status",+        serde_json::json!({"message": "a production release build is running; waiting for it to finish (up to 60 min)"}),+    );+    loop {+        if !release_active(&ctx.config) {+            return Ok(());+        }+        if is_cancelled(&ctx.store, task_id) {+            return Err("task cancelled".to_string());+        }+        if start.elapsed() >= limit {+            return Err(+                "production release still running after 60 min; aborting build (retry later)"+                    .to_string(),+            );+        }+        tokio::time::sleep(poll).await;+    }+}++/// Read `AGENTS.md` files for the prompt. Missing files → `None` (the prompt+/// renders "(unavailable)").+async fn fetch_rules(+    runner: &Runner,+    slot: u32,+    module_scope: &str,+) -> (Option<String>, Option<String>) {+    let root = runner+        .read(slot, "AGENTS.md", None, Some(400))+        .await+        .ok()+        .map(|r| r.content);+    // Scope forms: `games/logicgate` or `games:logicgate` → dir form.+    let dir = module_scope.replace(':', "/");+    let module_path = format!("{}/AGENTS.md", dir.trim_matches('/'));+    let module = if module_path == "AGENTS.md" {+        None+    } else {+        runner+            .read(slot, &module_path, None, Some(400))+            .await+            .ok()+            .map(|r| r.content)+    };+    (root, module)+}++/// Run one task to completion. `slot` is the scheduler worker index (also+/// the runner slot id).+pub async fn drive_task(ctx: DriverCtx, task_id: i64, slot: u32) -> TaskOutcome {+    let task = match ctx.store.get_task(task_id).ok().flatten() {+        Some(t) => t,+        None => {+            return TaskOutcome::Failed {+                reason: "task row vanished".to_string(),+            }+        }+    };+    let branch = if task.branch.is_empty() {+        let b = branch_name(task.id, &task.title);+        let _ = ctx.store.set_branch(task.id, &b);+        b+    } else {+        task.branch.clone()+    };+    let model = task.model.clone();+    let module_scope = if task.module_scope.is_empty() {+        "notes".to_string()+    } else {+        task.module_scope.clone()+    };+    let budget_steps = task.budget_steps;+    let budget_usd = task.budget_usd;++    ctx.emit(+        task_id,+        "status",+        serde_json::json!({"message": format!("preparing slot {slot} on {branch}")}),+    );++    // 1. Mirror refresh + slot prepare.+    if let Err(e) = crate::git::fetch_main(&ctx.config.mirror_dir).await {+        return fail(&ctx, task_id, &format!("mirror fetch failed: {e}")).await;+    }+    match crate::git::main_sha(&ctx.config.mirror_dir).await {+        Ok(sha) => {+            let _ = ctx.store.set_base_sha(task_id, &sha);+        }+        Err(e) => return fail(&ctx, task_id, &format!("mirror rev-parse: {e}")).await,+    }+    match ctx.runner.prepare(slot, &branch).await {+        Ok(r) => {+            let _ = ctx.store.set_base_sha(task_id, &r.base_sha);+        }+        Err(e) => return fail(&ctx, task_id, &format!("runner prepare: {e}")).await,+    }++    // 2. Rules + system prompt.+    let (root_rules, module_rules) = fetch_rules(&ctx.runner, slot, &module_scope).await;+    let system = system_prompt(+        &module_scope,+        root_rules.as_deref(),+        module_rules.as_deref(),+    );+    let mut messages = vec![+        Message::system(system),+        Message::user(format!("Task: {}\n\n{}", task.title, task.prompt)),+    ];+    let tools = tool_defs();+    ctx.emit(+        task_id,+        "status",+        serde_json::json!({"message": "agent loop started", "model": model}),+    );++    // 3. Main loop.+    let mut text_only_streak = 0u32;+    let mut nudged = false;+    loop {+        if is_cancelled(&ctx.store, task_id) {+            ctx.emit(+                task_id,+                "status",+                serde_json::json!({"message": "task cancelled"}),+            );+            return TaskOutcome::Cancelled;+        }+        let cur = match ctx.store.get_task(task_id).ok().flatten() {+            Some(t) => t,+            None => {+                return TaskOutcome::Failed {+                    reason: "task row vanished".to_string(),+                }+            }+        };+        if cur.steps >= budget_steps {+            return fail(+                &ctx,+                task_id,+                &format!("step budget exhausted ({} steps)", cur.steps),+            )+            .await;+        }+        if cur.cost_usd >= budget_usd {+            return fail(+                &ctx,+                task_id,+                &format!("cost budget exhausted (${:.4})", cur.cost_usd),+            )+            .await;+        }+        trim_messages(&mut messages, ctx.config.context_chars());++        // Model turn.+        let turn: AssistantTurn = match ctx.openrouter.chat(&model, &messages, &tools).await {+            Ok(t) => t,+            Err(e) => return fail(&ctx, task_id, &format!("OpenRouter: {e}")).await,+        };+        let _ = ctx.store.add_usage(+            task_id,+            1,+            turn.usage.prompt_tokens,+            turn.usage.completion_tokens,+            turn.usage.cost_usd(),+        );+        ctx.emit(+            task_id,+            "assistant",+            serde_json::json!({+                "text": scrub_secrets(&turn.text),+                "prompt_tokens": turn.usage.prompt_tokens,+                "completion_tokens": turn.usage.completion_tokens,+                "cost_usd": turn.usage.cost_usd(),+            }),+        );+        messages.push(Message::assistant_calls(+            if turn.text.is_empty() {+                None+            } else {+                Some(turn.text.clone())+            },+            turn.tool_calls.clone(),+        ));++        if turn.tool_calls.is_empty() {+            text_only_streak += 1;+            if text_only_streak >= 2 {+                if !nudged {+                    nudged = true;+                    text_only_streak = 0;+                    let nudge = "You returned text without a tool call. Please continue with tool calls (or `finish` with a diff and commit message).";+                    messages.push(Message::user(nudge.to_string()));+                    ctx.emit(task_id, "status", serde_json::json!({"message": nudge}));+                    continue;+                }+                return fail(+                    &ctx,+                    task_id,+                    "model returned text with no tool call twice in a row",+                )+                .await;+            }+            messages.push(Message::user(+                "Noted. Please continue with tool calls toward the goal.".to_string(),+            ));+            continue;+        }+        text_only_streak = 0;++        // Dispatch tool calls sequentially, in model order.+        for call in &turn.tool_calls {+            if is_cancelled(&ctx.store, task_id) {+                ctx.emit(+                    task_id,+                    "status",+                    serde_json::json!({"message": "task cancelled"}),+                );+                return TaskOutcome::Cancelled;+            }+            match dispatch_tool(&ctx, task_id, slot, &module_scope, call).await {+                ToolEffect::Continue { result_for_model } => {+                    messages.push(Message::tool_result(call.id.clone(), result_for_model));+                }+                ToolEffect::FinishRequest {+                    summary,+                    commit_message,+                } => {+                    return finish_task(&ctx, task_id, slot, &branch, &summary, &commit_message)+                        .await;+                }+            }+        }+    }+}++async fn fail(ctx: &DriverCtx, task_id: i64, reason: &str) -> TaskOutcome {+    ctx.emit(+        task_id,+        "status",+        serde_json::json!({"message": reason}),+    );+    TaskOutcome::Failed {+        reason: reason.to_string(),+    }+}++/// Replace old tool results with placeholders once the conversation exceeds+/// `budget` chars (keeps system prompt + first user message + recent tail).+/// Public for unit tests.+pub fn trim_messages(messages: &mut [Message], budget: usize) {+    let total: usize = messages.iter().map(|m| m.chars()).sum();+    if total <= budget {+        return;+    }+    // Keep first two (system + task) and last four; trim tool results in the+    // middle window.+    if messages.len() <= 6 {+        return;+    }+    let n = messages.len();+    for m in messages.iter_mut().take(n.saturating_sub(4)).skip(2) {+        if m.role == "tool" {+            if let Some(c) = m.content.take() {+                m.content = Some(trim_placeholder("tool", c.len()));+            }+        }+    }+}++enum ToolEffect {+    Continue { result_for_model: String },+    FinishRequest { summary: String, commit_message: String },+}++async fn dispatch_tool(+    ctx: &DriverCtx,+    task_id: i64,+    slot: u32,+    module_scope: &str,+    call: &ToolCall,+) -> ToolEffect {+    let args: serde_json::Value =+        serde_json::from_str(&call.function.arguments).unwrap_or(serde_json::Value::Null);+    ctx.emit(+        task_id,+        "tool_call",+        serde_json::json!({"name": call.function.name, "args": args_preview(&call.function.arguments)}),+    );+    let raw: String = match call.function.name.as_str() {+        "read_file" => {+            let path = arg_str(&args, "path").unwrap_or_default();+            if let Err(e) = check_scope(&path, module_scope) {+                format!("Scope error: {e}")+            } else {+                match ctx+                    .runner+                    .read(+                        slot,+                        &path,+                        args.get("start_line").and_then(|v| v.as_u64()).map(|v| v as usize),+                        args.get("max_lines").and_then(|v| v.as_u64()).map(|v| v as usize),+                    )+                    .await+                {+                    Ok(r) => format!(+                        "{} ({} lines{})",+                        r.content,+                        r.total_lines,+                        if r.truncated { ", truncated" } else { "" }+                    ),+                    Err(e) => format!("read failed: {e}"),+                }+            }+        }+        "list_dir" => {+            let path = arg_str(&args, "path").unwrap_or_default();+            if !path.is_empty() {+                if let Err(e) = check_scope(&path, module_scope) {+                    return finish_dispatch(ctx, task_id, &call.function.name, &format!("Scope error: {e}"));+                }+            }+            match ctx.runner.list(slot, &path).await {+                Ok(r) => r.entries.join("\n"),+                Err(e) => format!("list failed: {e}"),+            }+        }+        "search" => {+            let pattern = arg_str(&args, "pattern").unwrap_or_default();+            let sub = arg_str(&args, "path").filter(|s| !s.is_empty());+            if let Some(p) = &sub {+                if let Err(e) = check_scope(p, module_scope) {+                    return finish_dispatch(ctx, task_id, &call.function.name, &format!("Scope error: {e}"));+                }+            }+            // Default the search root to the module scope when the model+            // passes none, so rg never scans the whole repo.+            let root = sub.or_else(|| Some(module_scope.replace(':', "/")));+            match ctx+                .runner+                .search(+                    slot,+                    &pattern,+                    root.as_deref(),+                    arg_str(&args, "glob").as_deref(),+                    args.get("fixed_string").and_then(|v| v.as_bool()).unwrap_or(false),+                )+                .await+            {+                Ok(r) => r.matches,+                Err(e) => format!("search failed: {e}"),+            }+        }+        "edit_file" => {+            let path = arg_str(&args, "path").unwrap_or_default();+            if let Err(e) = check_scope(&path, module_scope) {+                format!("Scope error: {e}")+            } else {+                match ctx+                    .runner+                    .edit(+                        slot,+                        &path,+                        &arg_str(&args, "old").unwrap_or_default(),+                        &arg_str(&args, "new").unwrap_or_default(),+                    )+                    .await+                {+                    Ok(()) => "edit applied".to_string(),+                    Err(e) => format!("edit failed: {e}"),+                }+            }+        }+        "write_file" => {+            let path = arg_str(&args, "path").unwrap_or_default();+            if let Err(e) = check_scope(&path, module_scope) {+                format!("Scope error: {e}")+            } else {+                match ctx+                    .runner+                    .write(slot, &path, &arg_str(&args, "content").unwrap_or_default())+                    .await+                {+                    Ok(()) => "file written".to_string(),+                    Err(e) => format!("write failed: {e}"),+                }+            }+        }+        "git_diff" => match ctx.runner.diff(slot).await {+            Ok(d) => format!("{}\n{}", d.stat, d.diff),+            Err(e) => format!("diff failed: {e}"),+        },+        "run_shell" => {+            let command = arg_str(&args, "command").unwrap_or_default();+            match validate_shell_command(&command) {+                Err(msg) => format!("Rejected: {msg}"),+                Ok(()) => match ctx+                    .runner+                    .exec(slot, &command, proto::ExecKind::Shell, 60)+                    .await+                {+                    Ok(r) => exec_summary(&r),+                    Err(e) => format!("exec failed: {e}"),+                },+            }+        }+        "build" => {+            let command = arg_str(&args, "command").unwrap_or_default();+            let allowed = match validate_build_command(&command) {+                Err(msg) => return finish_dispatch(ctx, task_id, &call.function.name, &format!("Rejected: {msg}")),+                Ok(c) => c,+            };+            // Release preemption: while the signal file exists, wait (up to+            // 60 min). If it appeared mid-build, kill the runner build.+            if release_active(&ctx.config) {+                match wait_for_release_clear(ctx, task_id, &allowed).await {+                    Ok(()) => {}+                    Err(msg) => return finish_dispatch(ctx, task_id, &call.function.name, &msg),+                }+            }+            match ctx+                .runner+                .exec(slot, &allowed, proto::ExecKind::Build, 20 * 60)+                .await+            {+                Ok(r) => {+                    if r.killed && release_active(&ctx.config) {+                        let _ = ctx.runner.kill_build().await;+                        "build preempted by a production release; retry later".to_string()+                    } else {+                        exec_summary(&r)+                    }+                }+                Err(e) => format!("build failed: {e}"),+            }+        }+        "finish" => {+            let summary = arg_str(&args, "summary").unwrap_or_default();+            let commit_message = arg_str(&args, "commit_message").unwrap_or_default();+            // Validate first: violations return as a tool result so the+            // model can fix them and call `finish` again.+            if let Err(e) = validate_commit_message(&commit_message) {+                let msg = format!(+                    "finish rejected: {e}. Fix the commit message and call `finish` again."+                );+                return finish_dispatch(ctx, task_id, &call.function.name, &msg);+            }+            match ctx.runner.diff(slot).await {+                Ok(d) if d.diff.trim().is_empty() => {+                    return finish_dispatch(+                        ctx,+                        task_id,+                        &call.function.name,+                        "finish rejected: the diff is empty — make code changes first, then call `finish` again.",+                    );+                }+                Err(e) => {+                    return finish_dispatch(+                        ctx,+                        task_id,+                        &call.function.name,+                        &format!("finish rejected: could not read diff ({e}); retry `finish`"),+                    );+                }+                _ => {}+            }+            return ToolEffect::FinishRequest {+                summary,+                commit_message,+            };+        }+        other => format!(+            "Unknown tool {other:?}; available: read_file, list_dir, search, edit_file, write_file, git_diff, run_shell, build, finish."+        ),+    };+    finish_dispatch(ctx, task_id, &call.function.name, &raw)+}++/// Truncate + scrub a tool result, emit the `tool_result` event, and return+/// the text fed back to the model.+fn finish_dispatch(ctx: &DriverCtx, task_id: i64, name: &str, raw: &str) -> ToolEffect {+    let (text, truncated) = truncate_result(raw);+    let text = scrub_secrets(&text);+    ctx.emit(+        task_id,+        "tool_result",+        serde_json::json!({"name": name, "truncated": truncated, "result": text}),+    );+    ToolEffect::Continue {+        result_for_model: text,+    }+}++/// Confine a repo-relative path to the module scope (or the rules files).+fn check_scope(path: &str, module_scope: &str) -> Result<(), String> {+    let dir = module_scope.replace(':', "/");+    let dir = dir.trim_matches('/');+    let p = path.trim_start_matches('/');+    if p == "AGENTS.md" || *p == format!("{dir}/AGENTS.md") {+        return Ok(());+    }+    if dir.is_empty() || p == dir || p.starts_with(&format!("{dir}/")) {+        Ok(())+    } else {+        Err(format!(+            "path {path:?} is outside your scope `{dir}/`; stay inside the scope"+        ))+    }+}++fn exec_summary(r: &proto::ExecResponse) -> String {+    let mut s = format!(+        "exit={} timed_out={} killed={} ({}ms)",+        r.exit_code+            .map(|c| c.to_string())+            .unwrap_or_else(|| "killed".to_string()),+        r.timed_out,+        r.killed,+        r.duration_ms,+    );+    if !r.stdout.is_empty() {+        s.push_str("\n--- stdout ---\n");+        s.push_str(&r.stdout);+    }+    if !r.stderr.is_empty() {+        s.push_str("\n--- stderr ---\n");+        s.push_str(&r.stderr);+    }+    if r.truncated {+        s.push_str("\n[output truncated by runner]");+    }+    s+}++async fn finish_task(+    ctx: &DriverCtx,+    task_id: i64,+    slot: u32,+    branch: &str,+    summary: &str,+    commit_message: &str,+) -> TaskOutcome {+    // Commit in the sandbox.+    let sha = match ctx.runner.commit(slot, commit_message).await {+        Ok(r) => r.sha,+        Err(e) => return fail(ctx, task_id, &format!("runner commit: {e}")).await,+    };+    ctx.emit(+        task_id,+        "status",+        serde_json::json!({"message": format!("committed {sha}"), "sha": sha}),+    );+    // Bundle → mirror → push.+    let bundle = match ctx.runner.bundle(slot).await {+        Ok(b) => b,+        Err(e) => return fail(ctx, task_id, &format!("bundle download: {e}")).await,+    };+    let tmp = match tempfile::Builder::new().prefix("agentd-bundle-").tempfile() {+        Ok(f) => f.into_temp_path(),+        Err(e) => return fail(ctx, task_id, &format!("temp bundle file: {e}")).await,+    };+    if let Err(e) = std::fs::write(&tmp, &bundle) {+        return fail(ctx, task_id, &format!("write bundle: {e}")).await;+    }+    if let Err(e) = crate::git::import_task_bundle(&ctx.config.mirror_dir, &tmp, branch).await {+        return fail(ctx, task_id, &format!("bundle import: {e}")).await;+    }+    match crate::git::push_branch(+        &ctx.config.mirror_dir,+        &ctx.config.repo_url,+        branch,+        &ctx.config.git_push_token,+    )+    .await+    {+        Ok(()) => {+            let _ = ctx.store.set_finished_commit(task_id, &sha, true, summary);+            ctx.emit(+                task_id,+                "status",+                serde_json::json!({"message": format!("pushed {branch}"), "sha": sha}),+            );+            TaskOutcome::Succeeded {+                commit_sha: sha,+                pushed: true,+                summary: summary.to_string(),+            }+        }+        Err(e) => {+            let _ = ctx.store.set_finished_commit(task_id, &sha, false, summary);+            fail(+                ctx,+                task_id,+                &format!("push {branch} failed: {e} (commit {sha} kept in mirror)"),+            )+            .await+        }+    }+}
infra/agents/agentd/src/auth.rs
diff --git a/infra/agents/agentd/src/auth.rs b/infra/agents/agentd/src/auth.rsnew file mode 100644index 0000000000..5dd0df7ca1--- /dev/null+++ b/infra/agents/agentd/src/auth.rs@@ -0,0 +1,215 @@+//! Session auth: argon2 password verification, random session tokens,+//! in-memory login rate limiting.+//!+//! The session cookie holds a 32-byte random token (base64url). Only the+//! SHA-256 hash of the token is stored in SQLite.++use std::collections::HashMap;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use argon2::{Argon2, PasswordHash, PasswordVerifier};+use rand::RngCore;+use sha2::{Digest, Sha256};++use crate::models::now_unix;+use crate::store::Store;++pub const SESSION_COOKIE: &str = "agentd_session";+/// 7-day session lifetime, in seconds.+pub const SESSION_TTL_SECS: i64 = 7 * 24 * 3600;++#[derive(Clone)]+pub struct Auth {+    pub store: Store,+    password_hash: String,+    limiter: Arc<Mutex<LoginLimiter>>,+}++impl Auth {+    pub fn new(store: Store, password_hash: String) -> Auth {+        Auth {+            store,+            password_hash,+            limiter: Arc::new(Mutex::new(LoginLimiter::default())),+        }+    }++    /// Verify a password against the configured argon2 PHC hash.+    /// Returns `false` (not an error) on mismatch so callers can 401/429.+    pub fn verify_password(&self, password: &str) -> bool {+        let parsed = match PasswordHash::new(&self.password_hash) {+            Ok(h) => h,+            Err(_) => return false,+        };+        Argon2::default()+            .verify_password(password.as_bytes(), &parsed)+            .is_ok()+    }++    /// Rate-limit check for a login attempt from `ip`. Returns `Some(retry+    /// after)` when the attempt must be rejected with 429.+    pub fn login_gate(&self, ip: &str) -> Option<Duration> {+        self.limiter+            .lock()+            .map(|mut l| l.check(ip))+            .unwrap_or(None)+    }++    pub fn login_failed(&self, ip: &str) {+        if let Ok(mut l) = self.limiter.lock() {+            l.failed(ip);+        }+    }++    pub fn login_ok(&self, ip: &str) {+        if let Ok(mut l) = self.limiter.lock() {+            l.succeeded(ip);+        }+    }++    /// Issue a session: random token + stored hash. Returns the raw token+    /// (goes into the cookie only).+    pub fn issue_session(&self) -> Result<String, String> {+        let mut bytes = [0u8; 32];+        rand::rng().fill_bytes(&mut bytes);+        let token = base64url(&bytes);+        let hash = token_sha_hex(&token);+        let exp = now_unix() + SESSION_TTL_SECS;+        self.store.put_session(&hash, exp)?;+        Ok(token)+    }++    pub fn check_token(&self, token: &str) -> bool {+        if token.is_empty() || token.len() > 256 {+            return false;+        }+        let hash = token_sha_hex(token);+        self.store+            .session_valid(&hash, now_unix())+            .unwrap_or(false)+    }++    pub fn revoke_token(&self, token: &str) {+        let hash = token_sha_hex(token);+        let _ = self.store.delete_session(&hash);+    }+}++pub fn token_sha_hex(token: &str) -> String {+    let digest = Sha256::digest(token.as_bytes());+    hex_encode(&digest)+}++pub fn hex_encode(bytes: &[u8]) -> String {+    const HEX: &[u8; 16] = b"0123456789abcdef";+    let mut s = String::with_capacity(bytes.len() * 2);+    for b in bytes {+        s.push(HEX[(b >> 4) as usize] as char);+        s.push(HEX[(b & 0xf) as usize] as char);+    }+    s+}++fn base64url(bytes: &[u8]) -> String {+    const ALPH: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";+    let mut s = String::with_capacity((bytes.len() * 4).div_ceil(3));+    let mut i = 0;+    while i + 3 <= bytes.len() {+        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | bytes[i + 2] as u32;+        s.push(ALPH[((n >> 18) & 63) as usize] as char);+        s.push(ALPH[((n >> 12) & 63) as usize] as char);+        s.push(ALPH[((n >> 6) & 63) as usize] as char);+        s.push(ALPH[(n & 63) as usize] as char);+        i += 3;+    }+    let rem = bytes.len() - i;+    if rem == 1 {+        let n = (bytes[i] as u32) << 16;+        s.push(ALPH[((n >> 18) & 63) as usize] as char);+        s.push(ALPH[((n >> 12) & 63) as usize] as char);+    } else if rem == 2 {+        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);+        s.push(ALPH[((n >> 18) & 63) as usize] as char);+        s.push(ALPH[((n >> 12) & 63) as usize] as char);+        s.push(ALPH[((n >> 6) & 63) as usize] as char);+    }+    s+}++/// In-memory exponential-backoff login limiter: per-IP backoff on failures+/// (1s, 2s, 4s, … capped at 5 min) plus a global cap of 60 attempts/min+/// across all IPs.+#[derive(Default)]+struct LoginLimiter {+    per_ip: HashMap<String, (u32, Instant)>,+    global: Vec<Instant>,+}++impl LoginLimiter {+    const MAX_BACKOFF: Duration = Duration::from_secs(300);+    const GLOBAL_CAP: usize = 60;++    fn check(&mut self, ip: &str) -> Option<Duration> {+        let now = Instant::now();+        self.global.retain(|t| now.duration_since(*t) < Duration::from_secs(60));+        if self.global.len() >= Self::GLOBAL_CAP {+            return Some(Duration::from_secs(30));+        }+        if let Some((fails, last)) = self.per_ip.get(ip) {+            if *fails > 0 {+                let shift = (*fails - 1).min(8);+                let backoff = Duration::from_secs(1 << shift).min(Self::MAX_BACKOFF);+                let elapsed = now.duration_since(*last);+                if elapsed < backoff {+                    return Some(backoff - elapsed);+                }+            }+        }+        None+    }++    fn failed(&mut self, ip: &str) {+        let now = Instant::now();+        self.global.push(now);+        let e = self.per_ip.entry(ip.to_string()).or_insert((0, now));+        e.0 = e.0.saturating_add(1);+        e.1 = now;+    }++    fn succeeded(&mut self, ip: &str) {+        self.per_ip.remove(ip);+    }+}++/// Client IP for rate limiting: first hop of `X-Forwarded-For` (set by+/// Caddy), else the peer socket address.+pub fn client_ip(forwarded_for: Option<&str>, peer: Option<std::net::SocketAddr>) -> String {+    if let Some(ff) = forwarded_for {+        let first = ff.split(',').next().unwrap_or("").trim();+        if !first.is_empty() {+            return first.to_string();+        }+    }+    peer.map(|p| p.ip().to_string()).unwrap_or_else(|| "unknown".to_string())+}++/// Parse the session token out of a `Cookie` header value.+pub fn session_token_from_cookie(header: &str) -> Option<String> {+    for part in header.split(';') {+        let part = part.trim();+        if let Some(v) = part.strip_prefix(&format!("{SESSION_COOKIE}=")) {+            let v = v.trim().trim_matches('"').to_string();+            if !v.is_empty() {+                return Some(v);+            }+        }+    }+    None+}++/// Strict `Origin` check for state-changing routes: the header must be+/// present and exactly equal the configured public origin.+pub fn origin_allowed(origin: Option<&str>, public_origin: &str) -> bool {+    matches!(origin, Some(o) if o == public_origin)+}
infra/agents/agentd/src/config.rs
diff --git a/infra/agents/agentd/src/config.rs b/infra/agents/agentd/src/config.rsnew file mode 100644index 0000000000..2c77b47f67--- /dev/null+++ b/infra/agents/agentd/src/config.rs@@ -0,0 +1,154 @@+//! Process-wide configuration, loaded once at startup from the environment.+//!+//! Every value comes from the compose file / env_file. Secrets are held in+//! memory only; agentd never forwards them to the runner, the browser, or+//! log/event output.++use std::path::PathBuf;++/// Test-only timeout squeezes: respected by [`Config::from_env`] when the+/// `AGENTD_TEST_*` variables are set; ignored in production.+#[derive(Debug, Clone, Default)]+pub struct TestTuning {+    /// Poll interval for scheduler + release-signal watch, in milliseconds.+    pub poll_ms: Option<u64>,+    /// How long `build` waits for the release signal to clear, in seconds.+    pub build_wait_secs: Option<u64>,+    /// Per-tool-call context/char budget overrides (unit tests use these+    /// without standing up the HTTP server).+    pub context_chars: Option<usize>,+}++#[derive(Debug, Clone)]+pub struct Config {+    /// Key for OpenRouter chat completions. Never logged or exposed.+    pub openrouter_api_key: String,+    /// Base URL for OpenRouter; overridden in tests to point at a mock.+    pub openrouter_base_url: String,+    /// Argon2 PHC hash of the single operator password.+    pub password_hash: String,+    /// Git push token (`Authorization: Bearer <token>`). Never logged.+    pub git_push_token: String,+    /// Remote repo URL, e.g. `https://git.maproj.org/Modern-Apps.git`.+    pub repo_url: String,+    /// Public origin, e.g. `https://agents.maproj.org` (Origin checks).+    pub public_origin: String,+    /// Default model sent to OpenRouter when the task form leaves it blank.+    pub default_model: String,+    /// Runner base URL, e.g. `http://builder:7070`.+    pub runner_url: String,+    /// Directory holding `agentd.db` (SQLite).+    pub state_dir: PathBuf,+    /// Shared bare mirror, read-only for the builder.+    pub mirror_dir: PathBuf,+    /// Presence of this file means a prod release build is running.+    pub release_signal: PathBuf,+    /// Listen address, e.g. `0.0.0.0:8080`.+    pub listen: String,+    /// Number of concurrent agent tasks (scheduler workers).+    pub slots: usize,+    /// Test tuning (timeouts only). `None` in production.+    pub test: TestTuning,+    // -- test-only network flags (never read in prod paths) --+    /// Test fixture: skip the real release-signal wait.+    pub test_skip_release_wait: bool,+}++impl Config {+    fn required(name: &str) -> Result<String, String> {+        std::env::var(name)+            .map(|v| {+                let v = v.trim().to_string();+                v+            })+            .map_err(|_| format!("missing required env var {name}"))+            .and_then(|v| {+                if v.is_empty() {+                    Err(format!("missing required env var {name} (empty)"))+                } else {+                    Ok(v)+                }+            })+    }++    fn optional(name: &str, default: &str) -> String {+        std::env::var(name)+            .ok()+            .map(|v| v.trim().to_string())+            .filter(|v| !v.is_empty())+            .unwrap_or_else(|| default.to_string())+    }++    pub fn from_env() -> Result<Config, String> {+        let test = TestTuning {+            poll_ms: std::env::var("AGENTD_TEST_POLL_MS")+                .ok()+                .and_then(|v| v.parse().ok()),+            build_wait_secs: std::env::var("AGENTD_TEST_BUILD_WAIT_SECS")+                .ok()+                .and_then(|v| v.parse().ok()),+            context_chars: std::env::var("AGENTD_TEST_CONTEXT_CHARS")+                .ok()+                .and_then(|v| v.parse().ok()),+        };+        let slots: usize = Self::optional("AGENTD_SLOTS", "4")+            .parse()+            .map_err(|_| "AGENTD_SLOTS must be a positive integer".to_string())?;+        if slots == 0 {+            return Err("AGENTD_SLOTS must be >= 1".to_string());+        }+        Ok(Config {+            openrouter_api_key: Self::required("OPENROUTER_API_KEY")?,+            openrouter_base_url: Self::optional(+                "OPENROUTER_BASE_URL",+                "https://openrouter.ai/api/v1",+            ),+            password_hash: Self::required("AGENTD_PASSWORD_HASH")?,+            git_push_token: Self::required("GIT_AGENT_PUSH_TOKEN")?,+            repo_url: Self::optional("AGENTD_REPO_URL", "https://git.maproj.org/Modern-Apps.git"),+            public_origin: Self::required("AGENTD_PUBLIC_ORIGIN")?,+            default_model: Self::optional("AGENTD_DEFAULT_MODEL", "anthropic/claude-sonnet-4"),+            runner_url: Self::optional("AGENTD_RUNNER_URL", "http://builder:7070"),+            state_dir: PathBuf::from(Self::optional("AGENTD_STATE_DIR", "/state")),+            mirror_dir: PathBuf::from(Self::optional(+                "AGENTD_MIRROR_DIR",+                "/mirror/Modern-Apps.git",+            )),+            release_signal: PathBuf::from(Self::optional(+                "AGENTD_RELEASE_SIGNAL",+                "/signal/release",+            )),+            listen: Self::optional("AGENTD_LISTEN", "0.0.0.0:8080"),+            slots,+            test,+            test_skip_release_wait: false,+        })+    }++    /// Release-signal poll interval.+    pub fn poll_interval(&self) -> std::time::Duration {+        std::time::Duration::from_millis(self.test.poll_ms.unwrap_or(3_000))+    }++    /// Max time a `build` tool call waits for the release signal to clear.+    pub fn build_wait_limit(&self) -> std::time::Duration {+        std::time::Duration::from_secs(self.test.build_wait_secs.unwrap_or(60 * 60))+    }++    ///conversation context budget (chars) before old tool results are trimmed.+    pub fn context_chars(&self) -> usize {+        self.test.context_chars.unwrap_or(120_000)+    }++    pub fn redacted_debug(&self) -> String {+        format!(+            "runner={} origin={} slots={} state={} mirror={} model={}",+            self.runner_url,+            self.public_origin,+            self.slots,+            self.state_dir.display(),+            self.mirror_dir.display(),+            self.default_model,+        )+    }+}
infra/agents/agentd/src/git.rs
diff --git a/infra/agents/agentd/src/git.rs b/infra/agents/agentd/src/git.rsnew file mode 100644index 0000000000..c1f1531e66--- /dev/null+++ b/infra/agents/agentd/src/git.rs@@ -0,0 +1,242 @@+//! Git operations owned by agentd.+//!+//! Invariants:+//! * agentd only ever runs git in the shared bare **mirror** (`git -C+//!   <mirror> ...`). It never runs git inside a sandbox-controlled repo.+//! * All invocations use argv (no shell) with timeouts.+//! * The push token travels via `GIT_CONFIG_COUNT/KEY_0/VALUE_0`+//!   (`http.extraHeader = Authorization: Bearer <token>`), never in the URL,+//!   argv, or logs.+//! * On startup the mirror is created if missing (`clone --bare`), then+//!   pinned with `gc.auto 0` + `gc.pruneExpire never` (slots reference it+//!   via alternates — pruning would corrupt them) and made group/world+//!   readable so the builder uid can fetch from it.++use std::path::Path;+use std::process::Stdio;+use std::time::Duration;++const GIT_TIMEOUT: Duration = Duration::from_secs(120);+const FETCH_TIMEOUT: Duration = Duration::from_secs(300);+const PUSH_TIMEOUT: Duration = Duration::from_secs(300);++/// Error type that keeps command output but guarantees no secret is+/// embedded: callers must pass redacted output (the token is never placed in+/// argv, so `stderr` cannot contain it; still, [`redact`] is applied).+#[derive(Debug)]+pub struct GitError(pub String);++impl std::fmt::Display for GitError {+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+        write!(f, "{}", self.0)+    }+}++async fn run_git(+    dir: Option<&Path>,+    args: &[&str],+    extra_env: &[(&str, &str)],+    timeout: Duration,+) -> Result<String, GitError> {+    let mut cmd = tokio::process::Command::new("git");+    if let Some(d) = dir {+        cmd.arg("-C").arg(d);+    }+    // No pager, no interactive prompts, no sandbox repo config leakage.+    cmd.env("GIT_PAGER", "cat")+        .env("GIT_TERMINAL_PROMPT", "0")+        .env("GIT_CONFIG_NOSYSTEM", "1")+        .env("GIT_CONFIG_GLOBAL", "/dev/null")+        .stdin(Stdio::null())+        .stdout(Stdio::piped())+        .stderr(Stdio::piped())+        .args(args);+    for (k, v) in extra_env {+        cmd.env(k, v);+    }+    // Kill the whole process group on timeout: `kill_on_drop` only kills the+    // direct child, so spawn detached via `pre_exec`-less approach — use+    // `Command::kill_on_drop` plus rely on git's own children exiting when+    // the parent dies. (No shell is ever involved.)+    let child = cmd+        .kill_on_drop(true)+        .spawn()+        .map_err(|e| GitError(format!("spawn git {}: {e}", args.join(" "))))?;+    let out = tokio::time::timeout(timeout, child.wait_with_output())+        .await+        .map_err(|_| GitError(format!("git {} timed out after {timeout:?}", args.join(" "))))?+        .map_err(|e| GitError(format!("git {}: {e}", args.join(" "))))?;+    if !out.status.success() {+        let stderr = String::from_utf8_lossy(&out.stderr);+        return Err(GitError(format!(+            "git {} failed: {}",+            args.join(" "),+            stderr.trim()+        )));+    }+    String::from_utf8(out.stdout).map_err(|e| GitError(format!("git output not UTF-8: {e}")))+}++/// Ensure the bare mirror exists and is fetch-ready. `repo_url` is the+/// upstream (e.g. `https://git.maproj.org/Modern-Apps.git`). The umask is+/// relaxed while creating so the builder uid can read the new files.+pub async fn ensure_mirror(mirror: &Path, repo_url: &str) -> Result<(), GitError> {+    if mirror.join("HEAD").exists() || mirror.join("config").exists() {+        return Ok(());+    }+    if let Some(parent) = mirror.parent() {+        std::fs::create_dir_all(parent)+            .map_err(|e| GitError(format!("create mirror parent: {e}")))?;+    }+    // 022 umask → files 644, dirs 755: world-readable for the builder uid.+    #[cfg(unix)]+    let prev = libc_umask(0o022);+    let r = run_git(+        None,+        &["clone", "--bare", repo_url, &mirror.to_string_lossy()],+        &[],+        FETCH_TIMEOUT,+    )+    .await;+    #[cfg(unix)]+    libc_umask(prev);+    r.map(|_| ())?;+    // Pin GC off: slots use this repo as an alternates source.+    run_git(+        Some(mirror),+        &["config", "gc.auto", "0"],+        &[],+        GIT_TIMEOUT,+    )+    .await?;+    run_git(+        Some(mirror),+        &["config", "gc.pruneExpire", "never"],+        &[],+        GIT_TIMEOUT,+    )+    .await?;+    Ok(())+}++#[cfg(unix)]+fn libc_umask(mask: u32) -> u32 {+    // Minimal FFI to avoid a libc dependency.+    extern "C" {+        fn umask(mask: u32) -> u32;+    }+    unsafe { umask(mask) }+}++/// Refresh the mirror's `main` from upstream before each task.+pub async fn fetch_main(mirror: &Path) -> Result<(), GitError> {+    run_git(+        Some(mirror),+        &["fetch", "origin", "+refs/heads/main:refs/heads/main"],+        &[],+        FETCH_TIMEOUT,+    )+    .await+    .map(|_| ())+}++/// Base SHA the task branch starts from (mirror's `main`).+pub async fn main_sha(mirror: &Path) -> Result<String, GitError> {+    let sha = run_git(Some(mirror), &["rev-parse", "refs/heads/main"], &[], GIT_TIMEOUT).await?;+    Ok(sha.trim().to_string())+}++/// Verify a downloaded bundle file inside the mirror (so prerequisite+/// checks run against a repo that shares history), then import it as+/// `refs/agent-out/<suffix>` in the mirror.+///+/// The bundle holds `<base>..<branch>`, where `<base>` is the mirror's+/// `main` fetched at task start. `git bundle verify` requires the+/// prerequisite commits to exist locally: a plain `clone --bare` has them,+/// but a mirror whose `main` has since moved (or that was cloned empty)+/// may not. `git fetch <bundle>` only needs the *endpoints*; the import+/// fetch below succeeds regardless. So a verify failure that is purely a+/// missing prerequisite must not fail the import — but a corrupt bundle+/// must. Distinguish them: if verify fails, check whether the bundle's+/// required ref is an ancestor-known object; if the fetch itself succeeds,+/// accept the bundle.+pub async fn import_task_bundle(+    mirror: &Path,+    bundle_file: &Path,+    branch: &str,+) -> Result<(), GitError> {+    let suffix = branch+        .strip_prefix("agent/")+        .ok_or_else(|| GitError(format!("bad branch {branch:?}")))?;+    let dst = format!("refs/agent-out/{suffix}");+    // Verify inside the mirror so prerequisite checks resolve against it+    // (`git bundle verify` prints e.g. "<file> is okay"). A verify failure+    // caused purely by a missing prerequisite (mirror's `main` moved after+    // the slot branched) must not fail the import — but a corrupt bundle+    // must. `git fetch <bundle>` only needs the branch tip and its new+    // objects, so: run verify for diagnostics, then run the fetch, and fail+    // only if the fetch fails.+    let verify_err = run_git(+        Some(mirror),+        &["bundle", "verify", &bundle_file.to_string_lossy()],+        &[],+        GIT_TIMEOUT,+    )+    .await+    .err()+    .map(|e| e.0);+    // The bundle holds `<base>..<branch>`; fetch the branch head by name.+    if let Err(e) = run_git(+        Some(mirror),+        &[+            "fetch",+            &bundle_file.to_string_lossy(),+            &format!("+refs/heads/{branch}:{dst}"),+        ],+        &[],+        FETCH_TIMEOUT,+    )+    .await+    {+        // The import itself failed: include the verify output when the+        // bundle is also unverifiable (corrupt bundle).+        if let Some(v) = verify_err {+            return Err(GitError(format!("bundle import failed ({e}); verify: {v}")));+        }+        return Err(GitError(format!("bundle import: {e}")));+    }+    Ok(())+}++/// Push `refs/agent-out/<suffix>` to `refs/heads/agent/<suffix>` on the+/// upstream. The token is passed via git config env (`http.extraHeader`),+/// never in the URL/argv/logs.+pub async fn push_branch(+    mirror: &Path,+    repo_url: &str,+    branch: &str,+    token: &str,+) -> Result<(), GitError> {+    let suffix = branch+        .strip_prefix("agent/")+        .ok_or_else(|| GitError(format!("bad branch {branch:?}")))?;+    let src = format!("refs/agent-out/{suffix}");+    let dst = format!("refs/heads/{branch}");+    let header_value = format!("Authorization: Bearer {token}");+    // Env values are not argv; redact defensively anyway on error paths.+    let r = run_git(+        Some(mirror),+        &["push", repo_url, &format!("+{src}:{dst}")],+        &[+            ("GIT_CONFIG_COUNT", "1"),+            ("GIT_CONFIG_KEY_0", "http.extraHeader"),+            ("GIT_CONFIG_VALUE_0", &header_value),+        ],+        PUSH_TIMEOUT,+    )+    .await;+    match r {+        Ok(_) => Ok(()),+        Err(GitError(msg)) => Err(GitError(format!("push {branch}: {msg}"))),+    }+}
infra/agents/agentd/src/main.rs
diff --git a/infra/agents/agentd/src/main.rs b/infra/agents/agentd/src/main.rsindex f328e4d9d0..b4fa121fbb 100644--- a/infra/agents/agentd/src/main.rs+++ b/infra/agents/agentd/src/main.rs@@ -1 +1,69 @@-fn main() {}+//! agentd: trusted half of the on-server coding-agent harness.+//!+//! Startup: load env config (fail fast), open SQLite (migrate), mark+//! orphaned `running` tasks failed ("interrupted by restart"), ensure the+//! bare git mirror, bind the axum server, spawn scheduler workers.++mod agent;+mod auth;+mod config;+mod git;+mod models;+mod openrouter;+mod prompt;+mod runner;+mod scheduler;+mod state;+mod store;+mod tools;+mod ui;++#[cfg(test)]+mod tests;++#[cfg(test)]+mod tests_integration;++use tracing_subscriber::EnvFilter;++#[tokio::main]+async fn main() {+    tracing_subscriber::fmt()+        .with_env_filter(EnvFilter::from_default_env())+        .with_writer(std::io::stderr)+        .init();++    if let Err(e) = run().await {+        eprintln!("agentd: fatal: {e}");+        std::process::exit(1);+    }+}++async fn run() -> Result<(), String> {+    let config = config::Config::from_env()?;+    tracing::info!("agentd starting: {}", config.redacted_debug());++    let store = store::Store::open(&config.state_dir)?;+    let interrupted = store.mark_interrupted_running_failed()?;+    if interrupted > 0 {+        tracing::warn!("{interrupted} orphaned running task(s) marked failed (interrupted by restart)");+    }+    store.purge_expired_sessions(models::now_unix())?;++    git::ensure_mirror(&config.mirror_dir, &config.repo_url)+        .await+        .map_err(|e| format!("mirror: {e}"))?;++    let state = state::AppState::new(config.clone(), store);+    let _workers = scheduler::spawn_workers(state.driver(), config.slots);++    let app = ui::router(state);+    let listener = tokio::net::TcpListener::bind(&config.listen)+        .await+        .map_err(|e| format!("bind {}: {e}", config.listen))?;+    tracing::info!("agentd listening on {}", config.listen);+    axum::serve(listener, app)+        .await+        .map_err(|e| format!("serve: {e}"))?;+    Ok(())+}
infra/agents/agentd/src/models.rs
diff --git a/infra/agents/agentd/src/models.rs b/infra/agents/agentd/src/models.rsnew file mode 100644index 0000000000..3a5a336c8b--- /dev/null+++ b/infra/agents/agentd/src/models.rs@@ -0,0 +1,210 @@+//! Task / event / session row types and small pure helpers.+//!+//! The canonical schema lives in [`crate::store`]; this module holds the+//! Rust-side enums and the pure functions that are unit-tested (slug,+//! truncation, commit-message validation).++use serde::{Deserialize, Serialize};++/// Task lifecycle. `queued -> running -> {succeeded|failed|cancelled}`.+/// `running` rows found at startup are marked failed ("interrupted by+/// restart"); see [`crate::store::Store::mark_interrupted_running_failed`].+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum TaskStatus {+    Queued,+    Running,+    Succeeded,+    Failed,+    Cancelled,+}++impl TaskStatus {+    pub fn as_str(self) -> &'static str {+        match self {+            TaskStatus::Queued => "queued",+            TaskStatus::Running => "running",+            TaskStatus::Succeeded => "succeeded",+            TaskStatus::Failed => "failed",+            TaskStatus::Cancelled => "cancelled",+        }+    }++    pub fn parse(s: &str) -> Option<TaskStatus> {+        match s {+            "queued" => Some(TaskStatus::Queued),+            "running" => Some(TaskStatus::Running),+            "succeeded" => Some(TaskStatus::Succeeded),+            "failed" => Some(TaskStatus::Failed),+            "cancelled" => Some(TaskStatus::Cancelled),+            _ => None,+        }+    }++    pub fn is_terminal(self) -> bool {+        matches!(+            self,+            TaskStatus::Succeeded | TaskStatus::Failed | TaskStatus::Cancelled+        )+    }+}++/// One task row.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Task {+    pub id: i64,+    pub title: String,+    pub prompt: String,+    pub module_scope: String,+    pub model: String,+    pub status: TaskStatus,+    pub slot: Option<u32>,+    pub branch: String,+    pub base_sha: Option<String>,+    pub commit_sha: Option<String>,+    pub pushed: bool,+    pub created_at: i64,+    pub updated_at: i64,+    pub started_at: Option<i64>,+    pub finished_at: Option<i64>,+    pub steps: i64,+    pub prompt_tokens: i64,+    pub completion_tokens: i64,+    pub cost_usd: f64,+    pub budget_steps: i64,+    pub budget_usd: f64,+    pub error: Option<String>,+    pub summary: Option<String>,+}++/// One event row (append-only live log for a task).+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Event {+    pub id: i64,+    pub task_id: i64,+    pub seq: i64,+    pub ts: i64,+    pub kind: String,+    pub body: serde_json::Value,+}++pub fn now_unix() -> i64 {+    std::time::SystemTime::now()+        .duration_since(std::time::UNIX_EPOCH)+        .map(|d| d.as_secs() as i64)+        .unwrap_or(0)+}++/// Build a safe branch name `agent/<id>-<slug>` from the numeric id and a+/// free-text title. Only `[a-z0-9-]` survive; runs collapse to one `-`;+/// empty slugs fall back to `task`.+pub fn branch_name(id: i64, title: &str) -> String {+    let slug = slugify(title);+    format!("agent/{id}-{slug}")+}++pub fn slugify(title: &str) -> String {+    let mut out = String::new();+    let mut prev_dash = true; // collapse leading run too+    for c in title.to_lowercase().chars() {+        if c.is_ascii_alphanumeric() {+            out.push(c);+            prev_dash = false;+        } else if !prev_dash {+            out.push('-');+            prev_dash = true;+        }+    }+    while out.ends_with('-') {+        out.pop();+    }+    if out.is_empty() {+        out.push_str("task");+    }+    if out.len() > 48 {+        out.truncate(48);+        while out.ends_with('-') {+            out.pop();+        }+    }+    out+}++/// Max bytes kept per tool result before truncation.+pub const RESULT_TRUNCATE_BYTES: usize = 16 * 1024;++/// Truncate a tool result to ~16 KiB, keeping head + tail with a marker.+/// Returns `(text, was_truncated)`.+pub fn truncate_result(s: &str) -> (String, bool) {+    if s.len() <= RESULT_TRUNCATE_BYTES {+        return (s.to_string(), false);+    }+    let keep_head = RESULT_TRUNCATE_BYTES * 3 / 4;+    let keep_tail = RESULT_TRUNCATE_BYTES / 4;+    // Snap to char boundaries.+    let mut head_end = keep_head.min(s.len());+    while head_end > 0 && !s.is_char_boundary(head_end) {+        head_end -= 1;+    }+    let mut tail_start = s.len().saturating_sub(keep_tail);+    while tail_start < s.len() && !s.is_char_boundary(tail_start) {+        tail_start += 1;+    }+    let omitted = s.len().saturating_sub(head_end + (s.len() - tail_start));+    (+        format!(+            "{}\n… [truncated {} bytes] …\n{}",+            &s[..head_end],+            omitted,+            &s[tail_start..]+        ),+        true,+    )+}++/// Human placeholder swapped in for old tool results once the conversation+/// exceeds the context budget (keeps the model oriented without the bytes).+pub fn trim_placeholder(tool_name: &str, bytes: usize) -> String {+    format!("[earlier {tool_name} result trimmed, was ~{bytes} chars]")+}++/// Validate the `finish{commit_message}` first line: `<module>: <desc>`+/// with `module` a plausible Gradle path (`[a-z0-9-/]+`) and the whole line+/// <= 80 chars, mirroring the repo's `appname: short description` rule.+pub fn validate_commit_message(msg: &str) -> Result<(), String> {+    let first = msg.lines().next().unwrap_or("").trim();+    if first.is_empty() {+        return Err("commit message is empty".to_string());+    }+    if first.chars().count() > 80 {+        return Err(format!(+            "commit message first line is {} chars (limit 80): {first:?}",+            first.chars().count()+        ));+    }+    let Some((scope, desc)) = first.split_once(':') else {+        return Err(+            "commit message must start with `<module>: <description>` (e.g. `notes: fix editor crash`)".to_string(),+        );+    };+    let scope = scope.trim();+    let desc = desc.trim();+    if scope.is_empty()+        || !scope+            .chars()+            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '/' || c == '-')+    {+        return Err(format!(+            "commit scope {scope:?} must match [a-z0-9/-]+ (e.g. `notes`, `games/logicgate`)"+        ));+    }+    if desc.is_empty() {+        return Err("commit description after `<module>:` must be non-empty".to_string());+    }+    if !msg.trim().contains('\n') {+        return Err(+            "commit message needs a blank line and a prose body after the first line".to_string(),+        );+    }+    Ok(())+}
infra/agents/agentd/src/openrouter.rs
diff --git a/infra/agents/agentd/src/openrouter.rs b/infra/agents/agentd/src/openrouter.rsnew file mode 100644index 0000000000..4f20da022d--- /dev/null+++ b/infra/agents/agentd/src/openrouter.rs@@ -0,0 +1,446 @@+//! OpenRouter chat-completions client (OpenAI tool-calling format).+//!+//! Only the chat-completions endpoint is used. `usage: {include: true}` is+//! always sent so token counts and (when the provider supplies it) cost come+//! back on every response; missing cost is tolerated as 0. In production the+//! key comes from `OPENROUTER_API_KEY`; tests point `OPENROUTER_BASE_URL` at+//! a local mock.++use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize)]+struct UsageOpt {+    include: bool,+}++#[derive(Debug, Clone, Serialize)]+struct ChatRequest<'a> {+    model: &'a str,+    messages: &'a [Message],+    tools: &'a [ToolDef],+    #[serde(skip_serializing_if = "Option::is_none")]+    tool_choice: Option<&'a str>,+    usage: UsageOpt,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Message {+    pub role: String,+    #[serde(skip_serializing_if = "Option::is_none")]+    pub content: Option<String>,+    #[serde(skip_serializing_if = "Option::is_none")]+    pub tool_calls: Option<Vec<ToolCall>>,+    #[serde(skip_serializing_if = "Option::is_none")]+    pub tool_call_id: Option<String>,+    #[serde(skip_serializing_if = "Option::is_none")]+    pub name: Option<String>,+}++impl Message {+    pub fn system(content: String) -> Message {+        Message {+            role: "system".into(),+            content: Some(content),+            tool_calls: None,+            tool_call_id: None,+            name: None,+        }+    }+    pub fn user(content: String) -> Message {+        Message {+            role: "user".into(),+            content: Some(content),+            tool_calls: None,+            tool_call_id: None,+            name: None,+        }+    }+    /// Plain assistant-text constructor.+    #[cfg_attr(not(test), allow(dead_code))]+    pub fn assistant_text(content: String) -> Message {+        Message {+            role: "assistant".into(),+            content: Some(content),+            tool_calls: None,+            tool_call_id: None,+            name: None,+        }+    }+    pub fn assistant_calls(content: Option<String>, calls: Vec<ToolCall>) -> Message {+        Message {+            role: "assistant".into(),+            content,+            tool_calls: Some(calls),+            tool_call_id: None,+            name: None,+        }+    }+    pub fn tool_result(call_id: String, content: String) -> Message {+        Message {+            role: "tool".into(),+            content: Some(content),+            tool_calls: None,+            tool_call_id: Some(call_id),+            name: None,+        }+    }++    /// Rough char length for context-budget accounting.+    pub fn chars(&self) -> usize {+        self.content.as_ref().map(|c| c.len()).unwrap_or(0)+            + self+                .tool_calls+                .as_ref()+                .map(|cs| cs.iter().map(|c| c.function.name.len() + c.function.arguments.len()).sum())+                .unwrap_or(0)+    }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ToolCall {+    pub id: String,+    #[serde(rename = "type")]+    pub kind: String,+    pub function: FunctionCall,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FunctionCall {+    pub name: String,+    pub arguments: String,+}++#[derive(Debug, Clone, Serialize)]+pub struct ToolDef {+    #[serde(rename = "type")]+    pub kind: &'static str,+    pub function: FunctionDef,+}++#[derive(Debug, Clone, Serialize)]+pub struct FunctionDef {+    pub name: &'static str,+    pub description: &'static str,+    pub parameters: serde_json::Value,+}++fn schema(props: &[(&str, &str, &str)], required: &[&str]) -> serde_json::Value {+    let mut map = serde_json::Map::new();+    for (name, ty, _desc) in props {+        map.insert(+            name.to_string(),+            serde_json::json!({"type": ty, "description": _desc}),+        );+    }+    serde_json::json!({+        "type": "object",+        "properties": serde_json::Value::Object(map),+        "required": required,+        "additionalProperties": false,+    })+}++/// The eight tools the model may call (mirrors the runner proto routes).+pub fn tool_defs() -> Vec<ToolDef> {+    vec![+        ToolDef {+            kind: "function",+            function: FunctionDef {+                name: "read_file",+                description: "Read a file relative to the repo root. Returns content with line numbers.",+                parameters: schema(+                    &[+                        ("path", "string", "Repo-relative path, e.g. notes/.../MainActivity.kt"),+                        ("start_line", "integer", "1-based first line (optional)"),+                        ("max_lines", "integer", "Max lines (optional)"),+                    ],+                    &["path"],+                ),+            },+        },+        ToolDef {+            kind: "function",+            function: FunctionDef {+                name: "list_dir",+                description: "List one directory level relative to the repo root.",+                parameters: schema(+                    &[("path", "string", "Repo-relative directory, e.g. notes/")],+                    &["path"],+                ),+            },+        },+        ToolDef {+            kind: "function",+            function: FunctionDef {+                name: "search",+                description: "Search code with ripgrep. Stays inside the module scope.",+                parameters: schema(+                    &[+                        ("pattern", "string", "Search pattern"),+                        ("path", "string", "Subdirectory (optional)"),+                        ("glob", "string", "e.g. *.kt (optional)"),+                        ("fixed_string", "boolean", "Literal match (optional)"),+                    ],+                    &["pattern"],+                ),+            },+        },+        ToolDef {+            kind: "function",+            function: FunctionDef {+                name: "edit_file",+                description: "Replace exactly one occurrence of `old` with `new` in a file.",+                parameters: schema(+                    &[+                        ("path", "string", "Repo-relative path"),+                        ("old", "string", "Exact text to replace (must occur exactly once)"),+                        ("new", "string", "Replacement text"),+                    ],+                    &["path", "old", "new"],+                ),+            },+        },+        ToolDef {+            kind: "function",+            function: FunctionDef {+                name: "write_file",+                description: "Create or overwrite a file (parents created).",+                parameters: schema(+                    &[+                        ("path", "string", "Repo-relative path"),+                        ("content", "string", "Full file content"),+                    ],+                    &["path", "content"],+                ),+            },+        },+        ToolDef {+            kind: "function",+            function: FunctionDef {+                name: "git_diff",+                description: "Show the working-tree diff vs the branch base.",+                parameters: schema(&[], &[]),+            },+        },+        ToolDef {+            kind: "function",+            function: FunctionDef {+                name: "run_shell",+                description: "Run a short shell command (<=60s). No builds, installs, adb, or cargo build/test — use `build` for those.",+                parameters: schema(+                    &[("command", "string", "Shell command")],+                    &["command"],+                ),+            },+        },+        ToolDef {+            kind: "function",+            function: FunctionDef {+                name: "build",+                description: "Run an allowlisted build: ./gradlew :<path>:<task> or ./check <module>. Blocks while a production release runs.",+                parameters: schema(+                    &[("command", "string", "Build command, e.g. ./gradlew :notes:compileDevKotlin")],+                    &["command"],+                ),+            },+        },+        ToolDef {+            kind: "function",+            function: FunctionDef {+                name: "finish",+                description: "Finish the task: requires a non-empty diff and a `<module>: <desc>` commit message with a prose body.",+                parameters: schema(+                    &[+                        ("summary", "string", "One-paragraph summary of what changed"),+                        ("commit_message", "string", "Commit message: `<module>: <desc>` line <=80 chars, blank line, prose body"),+                    ],+                    &["summary", "commit_message"],+                ),+            },+        },+    ]+}++#[derive(Debug, Clone, Deserialize)]+pub struct Usage {+    #[serde(default)]+    pub prompt_tokens: i64,+    #[serde(default)]+    pub completion_tokens: i64,+    #[serde(default)]+    #[allow(dead_code)]+    pub total_tokens: i64,+    /// Provider-supplied cost in USD; absent on many models → 0.+    #[serde(default)]+    pub cost: f64,+    #[serde(default)]+    pub total_cost: f64,+}++impl Usage {+    pub fn cost_usd(&self) -> f64 {+        if self.cost != 0.0 {+            self.cost+        } else {+            self.total_cost+        }+    }+}++#[derive(Debug, Clone, Deserialize)]+struct ChoiceMessage {+    #[serde(default)]+    content: Option<serde_json::Value>,+    #[serde(default)]+    tool_calls: Option<Vec<ToolCall>>,+}++#[derive(Debug, Clone, Deserialize)]+struct Choice {+    message: ChoiceMessage,+}++#[derive(Debug, Clone, Deserialize)]+struct ChatResponse {+    #[serde(default)]+    choices: Vec<Choice>,+    #[serde(default)]+    usage: Option<Usage>,+    #[serde(default)]+    error: Option<ProviderError>,+}++#[derive(Debug, Clone, Deserialize)]+struct ProviderError {+    #[serde(default)]+    message: String,+    #[serde(default)]+    code: Option<serde_json::Value>,+}++/// A parsed assistant turn.+#[derive(Debug, Clone)]+pub struct AssistantTurn {+    /// Plain text, if any (content may be a string or a content-parts array).+    pub text: String,+    pub tool_calls: Vec<ToolCall>,+    pub usage: Usage,+}++fn content_to_string(v: &serde_json::Value) -> String {+    match v {+        serde_json::Value::String(s) => s.clone(),+        serde_json::Value::Array(parts) => parts+            .iter()+            .filter_map(|p| {+                p.get("text")+                    .and_then(|t| t.as_str())+                    .map(|s| s.to_string())+                    .or_else(|| {+                        p.get("content")+                            .and_then(|c| c.as_str())+                            .map(|s| s.to_string())+                    })+            })+            .collect::<Vec<_>>()+            .join(""),+        serde_json::Value::Null => String::new(),+        other => other.to_string(),+    }+}++/// Parse a raw chat-completions body into an [`AssistantTurn`]. Pure;+/// unit-tested against JSON fixtures.+pub fn parse_chat_response(body: &[u8]) -> Result<AssistantTurn, String> {+    let resp: ChatResponse =+        serde_json::from_slice(body).map_err(|e| format!("bad OpenRouter JSON: {e}"))?;+    if let Some(err) = resp.error {+        let code = err+            .code+            .map(|c| c.to_string())+            .unwrap_or_else(|| "unknown".to_string());+        return Err(format!("OpenRouter error {code}: {}", err.message));+    }+    let choice = resp+        .choices+        .into_iter()+        .next()+        .ok_or_else(|| "OpenRouter returned no choices".to_string())?;+    let text = choice+        .message+        .content+        .as_ref()+        .map(content_to_string)+        .unwrap_or_default();+    Ok(AssistantTurn {+        text,+        tool_calls: choice.message.tool_calls.unwrap_or_default(),+        usage: resp.usage.unwrap_or(Usage {+            prompt_tokens: 0,+            completion_tokens: 0,+            total_tokens: 0,+            cost: 0.0,+            total_cost: 0.0,+        }),+    })+}++#[derive(Clone)]+pub struct OpenRouter {+    client: reqwest::Client,+    base_url: String,+    api_key: String,+}++impl OpenRouter {+    pub fn new(base_url: String, api_key: String) -> OpenRouter {+        OpenRouter {+            client: reqwest::Client::new(),+            base_url,+            api_key,+        }+    }++    pub async fn chat(+        &self,+        model: &str,+        messages: &[Message],+        tools: &[ToolDef],+    ) -> Result<AssistantTurn, String> {+        let url = format!("{}/chat/completions", self.base_url.trim_end_matches('/'));+        let req = ChatRequest {+            model,+            messages,+            tools,+            tool_choice: None,+            usage: UsageOpt { include: true },+        };+        let resp = self+            .client+            .post(&url)+            .header("Authorization", format!("Bearer {}", self.api_key))+            .header("Content-Type", "application/json")+            .json(&req)+            .send()+            .await+            .map_err(|e| format!("OpenRouter request failed: {e}"))?;+        let status = resp.status();+        let body = resp+            .bytes()+            .await+            .map_err(|e| format!("OpenRouter read body: {e}"))?;+        if !status.is_success() {+            // Try to surface a provider message; never include the key+            // (it is only in the request header, never in the body).+            if let Ok(v) = serde_json::from_slice::<serde_json::Value>(&body) {+                let msg = v+                    .get("error")+                    .and_then(|e| e.get("message").and_then(|m| m.as_str()))+                    .unwrap_or("unknown error");+                return Err(format!("OpenRouter HTTP {status}: {msg}"));+            }+            return Err(format!("OpenRouter HTTP {status}"));+        }+        parse_chat_response(&body)+    }+}
infra/agents/agentd/src/prompt.rs
diff --git a/infra/agents/agentd/src/prompt.rs b/infra/agents/agentd/src/prompt.rsnew file mode 100644index 0000000000..75f997ee91--- /dev/null+++ b/infra/agents/agentd/src/prompt.rs@@ -0,0 +1,49 @@+//! System-prompt construction for the agent loop.+//!+//! The prompt pins the model to the task's module scope, injects the repo+//! rules (root `AGENTS.md` + `<module>/AGENTS.md`, fetched from the slot via+//! the runner at task start), and states the verify-then-`finish` protocol.++/// Build the system prompt. `root_rules` / `module_rules` are the verbatim+/// `AGENTS.md` contents fetched via the runner; `None` renders as+/// "(unavailable)".+pub fn system_prompt(+    module_scope: &str,+    root_rules: Option<&str>,+    module_rules: Option<&str>,+) -> String {+    format!(+        r#"You are an autonomous coding agent working in the Modern-Apps monorepo (many Gradle modules plus Rust). You act ONLY through the tools provided; every tool call runs inside a sandboxed checkout of the repo.++Scope law — hard constraint:+- Your module scope is `{scope}`. Read and edit files only under that prefix (plus narrowly-justified shared-library reads when the rules below require them).+- Never `list_dir` the repo root or recurse outside the scope. Prefer one targeted `read_file` over broad searches.+- If a task truly needs another module, say so in your summary and stop; do not wander.++Repo rules (root AGENTS.md):+```+{root}+```++Module rules (`{scope}/AGENTS.md`):+```+{module}+```++Workflow:+1. Read the relevant files in scope. The task description tells you what to do.+2. Make minimal edits with `edit_file`/`write_file`. Follow the conventions above (messenger not Toast, AppScaffold, package roots, detekt-clean code).+3. Verify with the `build` tool (e.g. `./gradlew :<module path>:<task>` with `:` for `/`, or `./check <module>`). `run_shell` cannot run builds, installs, adb, or cargo build/test — use `build`.+4. Show the final state with `git_diff`, then call `finish` with a one-paragraph `summary` and a `commit_message` in the repo format: first line `<module>: <description>` (<=80 chars, e.g. `notes: fix editor crash`), then a blank line, then a prose body. The diff must be non-empty.++Tool discipline:+- `read_file`/`list_dir`/`search` paths are relative to the repo root and confined to your scope.+- `build` commands must match the allowlist exactly; anything else is rejected with the allowed forms.+- Call `finish` exactly once, at the end. If `finish` is rejected (empty diff, bad commit message), fix the problem and call it again.+- If you are stuck, explain what you tried in your next assistant message; two text-only turns in a row ends the task as failed, so keep making tool calls.+"#,+        scope = module_scope,+        root = root_rules.unwrap_or("(unavailable)"),+        module = module_rules.unwrap_or("(unavailable)"),+    )+}
infra/agents/agentd/src/runner.rs
diff --git a/infra/agents/agentd/src/runner.rs b/infra/agents/agentd/src/runner.rsnew file mode 100644index 0000000000..72471083f0--- /dev/null+++ b/infra/agents/agentd/src/runner.rs@@ -0,0 +1,276 @@+//! Typed client for the runner HTTP API defined in `proto`.+//!+//! Every call is slot-scoped (`/v1/slots/{slot}/...`) plus the global+//! `/v1/builds/kill`. Request paths sent to the runner are validated to be+//! repo-relative (no `..`, no absolute paths) — defense in depth on top of+//! the runner's own checks.++use proto::{+    CommitRequest, CommitResponse, DiffResponse, EditRequest, ExecKind, ExecRequest, ExecResponse,+    HealthResponse, KillResponse, ListRequest, ListResponse, PrepareRequest, PrepareResponse,+    ReadRequest, ReadResponse, SearchRequest, SearchResponse, WriteRequest,+};++#[derive(Clone)]+pub struct Runner {+    client: reqwest::Client,+    base: String,+}++impl Runner {+    pub fn new(base: String) -> Runner {+        Runner {+            client: reqwest::Client::new(),+            base: base.trim_end_matches('/').to_string(),+        }+    }++    fn url(&self, path: &str) -> String {+        format!("{}{}", self.base, path)+    }++    async fn post<B: serde::Serialize, R: serde::de::DeserializeOwned>(+        &self,+        path: &str,+        body: &B,+    ) -> Result<R, String> {+        let resp = self+            .client+            .post(self.url(path))+            .json(body)+            .send()+            .await+            .map_err(|e| format!("runner POST {path}: {e}"))?;+        Self::read_json(path, resp).await+    }++    async fn post_empty<R: serde::de::DeserializeOwned>(&self, path: &str) -> Result<R, String> {+        let resp = self+            .client+            .post(self.url(path))+            .header("Content-Length", "0")+            .send()+            .await+            .map_err(|e| format!("runner POST {path}: {e}"))?;+        Self::read_json(path, resp).await+    }++    async fn read_json<R: serde::de::DeserializeOwned>(+        path: &str,+        resp: reqwest::Response,+    ) -> Result<R, String> {+        let status = resp.status();+        let bytes = resp+            .bytes()+            .await+            .map_err(|e| format!("runner {path} read body: {e}"))?;+        if !status.is_success() {+            let msg = serde_json::from_slice::<serde_json::Value>(&bytes)+                .ok()+                .and_then(|v| {+                    v.get("error")+                        .and_then(|e| e.as_str())+                        .map(|s| s.to_string())+                })+                .unwrap_or_else(|| format!("HTTP {status}"));+            return Err(format!("runner {path}: {msg}"));+        }+        serde_json::from_slice(&bytes).map_err(|e| format!("runner {path} bad JSON: {e}"))+    }++    pub async fn prepare(&self, slot: u32, branch: &str) -> Result<PrepareResponse, String> {+        self.post(+            &format!("/v1/slots/{slot}/prepare"),+            &PrepareRequest {+                branch: branch.to_string(),+            },+        )+        .await+    }++    pub async fn read(+        &self,+        slot: u32,+        path: &str,+        start_line: Option<usize>,+        max_lines: Option<usize>,+    ) -> Result<ReadResponse, String> {+        check_rel_path(path)?;+        self.post(+            &format!("/v1/slots/{slot}/read"),+            &ReadRequest {+                path: path.to_string(),+                start_line,+                max_lines,+            },+        )+        .await+    }++    pub async fn write(&self, slot: u32, path: &str, content: &str) -> Result<(), String> {+        check_rel_path(path)?;+        let v: serde_json::Value = self+            .post(+                &format!("/v1/slots/{slot}/write"),+                &WriteRequest {+                    path: path.to_string(),+                    content: content.to_string(),+                },+            )+            .await?;+        let _ = v;+        Ok(())+    }++    pub async fn edit(&self, slot: u32, path: &str, old: &str, new: &str) -> Result<(), String> {+        check_rel_path(path)?;+        let v: serde_json::Value = self+            .post(+                &format!("/v1/slots/{slot}/edit"),+                &EditRequest {+                    path: path.to_string(),+                    old: old.to_string(),+                    new: new.to_string(),+                },+            )+            .await?;+        let _ = v;+        Ok(())+    }++    pub async fn list(&self, slot: u32, path: &str) -> Result<ListResponse, String> {+        // `list` of the repo root is allowed (single level) — the prompt+        // tells the model not to; empty path means root.+        if !path.is_empty() {+            check_rel_path(path)?;+        }+        self.post(+            &format!("/v1/slots/{slot}/list"),+            &ListRequest {+                path: path.to_string(),+            },+        )+        .await+    }++    pub async fn search(+        &self,+        slot: u32,+        pattern: &str,+        path: Option<&str>,+        glob: Option<&str>,+        fixed_string: bool,+    ) -> Result<SearchResponse, String> {+        if let Some(p) = path {+            if !p.is_empty() {+                check_rel_path(p)?;+            }+        }+        self.post(+            &format!("/v1/slots/{slot}/search"),+            &SearchRequest {+                pattern: pattern.to_string(),+                path: path.map(|s| s.to_string()),+                glob: glob.map(|s| s.to_string()),+                fixed_string,+            },+        )+        .await+    }++    pub async fn diff(&self, slot: u32) -> Result<DiffResponse, String> {+        let resp = self+            .client+            .post(self.url(&format!("/v1/slots/{slot}/diff")))+            .json(&serde_json::json!({}))+            .send()+            .await+            .map_err(|e| format!("runner diff: {e}"))?;+        Self::read_json(&format!("/v1/slots/{slot}/diff"), resp).await+    }++    pub async fn exec(+        &self,+        slot: u32,+        command: &str,+        kind: ExecKind,+        timeout_secs: u64,+    ) -> Result<ExecResponse, String> {+        self.post(+            &format!("/v1/slots/{slot}/exec"),+            &ExecRequest {+                command: command.to_string(),+                kind,+                timeout_secs,+            },+        )+        .await+    }++    pub async fn commit(&self, slot: u32, message: &str) -> Result<CommitResponse, String> {+        self.post(+            &format!("/v1/slots/{slot}/commit"),+            &CommitRequest {+                message: message.to_string(),+            },+        )+        .await+    }++    /// Download the slot's git bundle (`application/octet-stream`) to memory.+    pub async fn bundle(&self, slot: u32) -> Result<Vec<u8>, String> {+        let resp = self+            .client+            .get(self.url(&format!("/v1/slots/{slot}/bundle")))+            .send()+            .await+            .map_err(|e| format!("runner bundle: {e}"))?;+        let status = resp.status();+        if !status.is_success() {+            return Err(format!("runner bundle: HTTP {status}"));+        }+        resp.bytes()+            .await+            .map(|b| b.to_vec())+            .map_err(|e| format!("runner bundle read: {e}"))+    }++    pub async fn cancel_slot(&self, slot: u32) -> Result<bool, String> {+        let r: KillResponse = self.post_empty(&format!("/v1/slots/{slot}/cancel")).await?;+        Ok(r.killed)+    }++    pub async fn kill_build(&self) -> Result<bool, String> {+        let r: KillResponse = self.post_empty("/v1/builds/kill").await?;+        Ok(r.killed)+    }++    /// Readiness probe helper: the runner's build-slot state.+    /// (`#[allow]` — exercised by the integration test and useful for ops.)+    #[allow(dead_code)]+    pub async fn health(&self) -> Result<HealthResponse, String> {+        let resp = self+            .client+            .get(self.url("/v1/health"))+            .send()+            .await+            .map_err(|e| format!("runner health: {e}"))?;+        Self::read_json("/v1/health", resp).await+    }+}++/// Reject absolute paths and `..` escapes before they reach the runner.+fn check_rel_path(path: &str) -> Result<(), String> {+    if path.is_empty() {+        return Err("empty path".to_string());+    }+    if path.starts_with('/') {+        return Err(format!("absolute paths are not allowed: {path:?}"));+    }+    for seg in path.split('/') {+        if seg == ".." {+            return Err(format!("`..` is not allowed in paths: {path:?}"));+        }+    }+    Ok(())+}
infra/agents/agentd/src/scheduler.rs
diff --git a/infra/agents/agentd/src/scheduler.rs b/infra/agents/agentd/src/scheduler.rsnew file mode 100644index 0000000000..bab9ca29f6--- /dev/null+++ b/infra/agents/agentd/src/scheduler.rs@@ -0,0 +1,110 @@+//! Scheduler: `AGENTD_SLOTS` workers pull queued tasks from the DB.+//!+//! Each running task holds one worker (and one runner slot) for its whole+//! lifetime. The queue lives in SQLite so it survives restarts; on startup,+//! tasks left `running` by a previous process are marked failed+//! ("interrupted by restart") — see+//! [`Store::mark_interrupted_running_failed`](crate::store::Store

Diff truncated.