[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M69945M03JYXAVDMA2YVY1N5":3,"skill-same:01M69945M03JYXAVDMA2YVY1N5":74},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":7,"sourceHtmlUrl":17,"categories":18,"keywords":29,"publishedAt":32,"linkOnly":33,"markdownContent":34,"markdownBody":35,"frontMatter":36,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":7,"ownerHtmlUrl":42,"ownerBlogUrl":43,"ownerDescription":44,"updatedAt":45,"install":46,"resources":59},"01M69945M03JYXAVDMA2YVY1N5","dev-rust-patterns","Rust 开发模式",null,"","google\u002Fcapsem","google","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1342004?v=4","01M698VYEFDM0VJBZDYYJ2T83S","Google","01M69939YZJTP726NQK4NZNB48",186,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fdev-rust-patterns\u002FSKILL.md",[19,24],{"categoryNo":20,"categoryName":21,"taxonomyType":22,"taxonomyTypeDesc":23},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师","PROFESSION","适用职业",{"categoryNo":25,"categoryName":26,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BSNPHVX9Y1H3B2ZX3V06RF","Rust 开发","SCENARIO","使用场景",[30,31],"rust","dev rust patterns","2026-11-10 10:12:30",false,"---\nname: dev-rust-patterns\ndescription: Rust patterns and hard-won lessons. Use when writing Rust in capsem-core, capsem-app, or capsem-agent: async\u002Ftokio, non-blocking I\u002FO, cross-compilation.\n---\n\n# Rust Patterns\n\n## Data paths: zero-copy first, no speculative hashing or JSON\n\nRead [data-path performance](references\u002Fdata-path-performance.md) before changing\ntransport, admission, serialization, hashing or buffer ownership. Prefer moving\nor borrowing bytes and one bounded encoding into the final frame. Hashing and\nJSON require a concrete, documented contract; neither is a default safety step.\n\n## Async \u002F non-blocking\n\nCapsem uses tokio for all async I\u002FO. The MITM proxy, vsock manager, and file monitor are all async.\n\nPublish matching in-memory ownership inside the serialized blocking admission,\nbefore releasing its I\u002FO permit. A reader can observe the durable record before\nthe async caller resumes after `spawn_blocking`; publishing its ticket after\n`.await` exposed valid managed-session claims to `recovery_pending`. The\ncontroller regression pauses that continuation and claims through the real store.\n\n### Never block the tokio runtime\n\nLong-running synchronous work (FUSE request processing, disk I\u002FO, compression) must run on a dedicated thread via `tokio::task::spawn_blocking` or a dedicated `std::thread`. Blocking inside a tokio task starves other tasks.\n\nThe VirtioFS FUSE server runs on its own thread for this reason -- FUSE ops are synchronous by nature (read, write, lookup) and can't be made async without significant complexity.\n\n### Blocking-in-async anti-pattern (systemic -- audit, don't spot-fix)\n\nAny code path that does blocking I\u002FO inside an async function or while holding a `tokio::sync::Mutex` is a bug. This causes the tokio worker thread to stall, freezing the entire gateway, UI, or network stack until the blocking operation completes.\n\n**What counts as blocking I\u002FO:**\n- `std::process::Command` (subprocess execution)\n- `std::fs::*` (read, write, copy, remove_dir_all, create_dir_all)\n- `walkdir::WalkDir` (directory traversal)\n- `blake3::Hasher` on large data (hash computation)\n- `std::thread::sleep`\n\n**The fix pattern** -- in `capsem-service`, route handlers go through `ServiceState::off_worker` (`crates\u002Fcapsem-service\u002Fsrc\u002Fblocking.rs`), and `crates\u002Fcapsem-service\u002Fsrc\u002Ftests\u002Fasync_io_contract.rs` refuses direct blocking calls. Elsewhere, the shape is:\n```rust\nlet result = tokio::task::spawn_blocking(move || {\n    let rt = tokio::runtime::Handle::current();\n    rt.block_on(async {\n        let mut guard = mutex.lock().await;\n        sync_blocking_work(&mut guard)\n    })\n}).await.unwrap_or_else(|e| \u002F* handle panic *\u002F);\n```\n\n**Example site:** the fork clone (`crates\u002Fcapsem-service\u002Fsrc\u002Fvm_files\u002Ffork.rs`) runs `clone_sandbox_state` -- fsync, clonefile, and a full tree walk -- on the blocking pool. Any new tree copy, hash, or directory walk reachable from an async handler needs the same treatment.\n\n### Channel patterns\n\n- `tokio::sync::mpsc` for producer-consumer (vsock data flow, telemetry events)\n- `tokio::sync::broadcast` for fan-out (serial output to multiple subscribers)\n- `tokio::sync::oneshot` for single-response request-reply (control messages)\n\n### Logger DB boundary\n\n`capsem-logger` owns SQLite connection\u002Fthread\u002Fstorage mechanics. Rust service,\ngateway, MCP, UI, and benchmark code must not call `rusqlite::Connection::open`\nor `DbReader::open` directly for telemetry\u002Fsecurity ledgers, and must not add\nservice-owned projection caches.\n\nCallers may own query intent, but the DB object owns execution:\n\n```rust\ndb.ready().await?;\ndb.query(sql, params).await?;\ndb.write(event).await?;\n```\n\n`db.write(event).await` is an accept boundary: the DB-owned producer buffer\nhas taken responsibility for the event. Read-after-write tests must use the DB\nflush barrier or shutdown\u002Freopen before asserting route-visible rows. Never add\nroute sleeps, route projection caches, or caller-owned SQLite reads to force\nvisibility.\n\nDo not hide route SQL by adding route-specific helpers to `DbWriter`; the DB\nwriter is not a product route registry. Put connection threads, `mem`\u002Fdisk\ntables, batching, flushing, WAL tuning, and future FTS5\u002Fsearch in\nthe DB layer. Empty tables are fine. Missing tables or columns are schema\ncontract failures and must not be converted into empty results.\n\n### Coalescing buffer\n\nTerminal output uses a `CoalesceBuffer` (8ms window, 64KB cap) to batch small vsock reads into larger writes. This prevents xterm.js from choking on thousands of tiny updates. The pattern: accumulate into a buffer, flush on timer or size threshold.\n\n### Graceful shutdown\n\nUse `tokio::select!` with a cancellation token or shutdown signal. Every long-running task must respect shutdown. Dangling tasks after VM exit cause resource leaks.\n\n## Cross-compilation\n\nGuest binaries target `aarch64-unknown-linux-musl` and `x86_64-unknown-linux-musl`. Key gotchas:\n\n- **Platform-specific types**: `libc::ioctl` request param is `c_ulong` on macOS but `c_int` on Linux. Use `as _` to let the compiler infer the correct type.\n- **Linker**: `.cargo\u002Fconfig.toml` sets `linker = \"rust-lld\"` for both musl targets.\n- **No std dependencies**: musl builds are fully static. Avoid crates that link to system libraries.\n- **Test on both**: `cargo check --target aarch64-unknown-linux-musl` catches cross-compile errors without needing to boot a VM.\n\n## Error handling\n\n- Use `anyhow::Result` for application code (capsem-app, scripts)\n- Use `thiserror` for library errors in capsem-core (typed, matchable)\n- Propagate errors up, don't swallow them. If a function returns `Result`, the caller must handle it.\n- Log errors at the point where you have context, then propagate. Don't log AND propagate (causes duplicate log lines).\n\n## Host Unix boundary\n\nReusable host Unix mechanics belong in the small modules under\n`capsem_foundation::unix`; application crates consume their typed APIs instead\nof calling `nix` or `libc` directly. This keeps ownership, EINTR handling,\nerrno classification, CLOEXEC, no-follow behavior, and race checks identical\nacross the CLI, service, process, guard, credentials, and core.\n\n- Accept `BorrowedFd` and return `OwnedFd` or `File`. Never return a raw\n  descriptor whose close responsibility is implicit, and never pair\n  `ManuallyDrop\u003CFile>` with a manual `close`.\n- Expected races are typed outcomes: a missing process and lock contention are\n  not generic errors. Keep expected disconnects quiet; log unexpected failures\n  once where the caller knows the operation, object identity, and errno.\n- Use `unix::contained::ContainedDir` for guest-influenced paths. Its\n  descriptor-relative traversal, constrained open options, and regular-file\n  checks must remain in the same syscall sequence; do not put a path-based\n  check in front of a separate path-based action.\n- Use `unix::fs` for owner-only directories, no-follow regular-file access,\n  filesystem capacity, atomic private publication, permission bits\n  (`set_mode`), durability (`sync`, `sync_before_barrier`,\n  `sync_filesystem`) and copy-on-write cloning (`clone_file_into`,\n  `copy_sparse`). Use `unix::tree_clone` to copy a directory tree a guest can\n  write. Use `unix::lock` for advisory locks, including synchronous\n  read-modify-write sections.\n- When foundation lacks a primitive, add it to foundation with its tests;\n  never reach for `nix` or `libc` at the call site \"just this once\".\n- Inside foundation, `nix` is the syscall layer and `unix::errno::io` converts\n  its errors. A raw `libc::` call is allowed only where `nix` cannot express it\n  (no wrapper, or a platform gap such as `MSG_NOSIGNAL` on macOS), and each\n  one is listed with that reason in `tests\u002Fcitadel\u002Funix_boundary_debt.toml`.\n- Put each primitive in its own module with tests in the sibling `tests.rs`.\n  Cover errno preservation, ownership after the source is dropped, symlink and\n  path-replacement races, special files, exact modes, and concurrent callers.\n\nWhen transferring connected sockets with `unix::router_channel`, retain the\noriginal socket until a request-bound receipt confirms that the receiver owns\nand validated its descriptor. A completed `sendmsg` only queues SCM_RIGHTS;\nDarwin may collect sockets with no owner outside that queue. Bound the receipt\nwait, reject wrong identities, directions and extra descriptors, and preserve\nscope cancellation and positive child reaping. The native MCP regression is\n`upstream_broker\u002Fmcp_spawn\u002Ftests.rs`: it delays adoption, checks that the original\nstays alive, and proves it is released after the receipt. Keeping an extra\nsocket for the child's entire lifetime masks disconnects and leaks descriptors.\nThe same rule covers startup policy, proxy traffic\u002FMCP\u002Ftrace hints, ledger\nclients, gateway connections and the aggregator's owner connection. Auditing\nonly the native MCP bootstrap missed these paths and left a macOS policy-update\nbroken pipe. `tests\u002Fcitadel\u002Ftest_descriptor_adoption_lifetime.py` guards the\nearly-drop sites, including private cable handoff: its table reference can be\nreplaced by a reconnect before adoption. Gateway and upstream grant tests drop the received copy\nbefore acknowledging to prove the sender still owns its original, then assert\nEOF after adoption to rule out retention leaks.\n\nDirect Unix calls remain valid only in modules that implement a kernel or\nplatform ABI rather than reusable host policy, such as KVM\u002FFUSE and guest audit\nplumbing. `tests\u002Fcitadel\u002Ftest_unix_boundary.py` and its exact domain-ABI\ninventory enforce that distinction; extending the inventory requires explicit\nreview, not a convenience exemption. The same guard inventories every raw\n`libc::` call and `extern \"C\"` binding inside foundation itself, rejects a new\none that `nix` already wraps, and catches aliased imports (`use ::libc as sys`),\n`extern \"C\" { fn ... }` blocks and renamed or table-form manifest\ndependencies. Before it did, foundation's own internals were unscanned and\nraw calls with `nix` wrappers accumulated there unnoticed.\n\n## Guest RAM and VirtioFS performance\n\nBefore changing guest RAM, KVM storage or OCI boot, read\n[Guest RAM and VirtioFS performance](references\u002Fguest-memory-performance.md).\nKeep RAM and KVM slot offsets aligned to 2 MiB and request transparent huge\npages through `capsem_foundation::unix::guest_memory::GuestRam`. A regular\n4-KiB-backed mapping once made kernel startup take 1.1 seconds and a 352-MB\nEROFS scan wait 1.5 seconds in reads. The allocation and slot regression is\n`guest_ram_and_kvm_slot_offsets_preserve_huge_page_alignment` in\n`hypervisor\u002Fkvm\u002Fmemory\u002Ftests.rs`; alignment alone is insufficient without the\nper-mapping huge-page hint.\n\n## Bidirectional I\u002FO -- thread per direction\n\nWhen bridging two blocking file descriptors bidirectionally (e.g., TCP socket to vsock in `net_proxy.rs`, or master PTY to vsock in `capsem-pty-agent`), doing both reads and writes in a single thread using `poll(2)` causes deadlocks. If both outgoing buffers fill simultaneously, a single thread blocks on writing and stops reading, creating mutual lockup. Always spawn a dedicated thread for at least one direction (`std::thread::spawn` for `fd_b -> fd_a` while the main thread handles `fd_a -> fd_b`).\n\n## Serde -- avoid `serde_json::Value` on LLM payloads\n\nThe MITM proxy and ai_traffic parsers handle massive HTTP payloads (megabytes of tool calls, histories, images). Parsing these into `serde_json::Value` does full DOM allocation, which is inefficient and risks memory exhaustion.\n\n**Rules:**\n- Define targeted structs with `#[derive(Deserialize)]`. Serde skips and discards fields not in the struct without allocating memory for them.\n- For struct fields that hold large, unconstrained JSON (tool call arguments, function responses, full model outputs) and are only converted to strings: use `Box\u003Cserde_json::value::RawValue>` instead of `serde_json::Value`. `RawValue` keeps the JSON as an unparsed string slice -- zero DOM allocation. Access the raw JSON string via `.get()`.\n- Never add `serde_json::Value` fields to structs that parse LLM request\u002Fresponse bodies. If you only need a string representation, use `RawValue`. If you need to traverse nested fields, use a typed struct.\n- Remove unused fields from deserialization structs -- they still force Serde to allocate.\n\n**Example -- before (bad):**\n```rust\nstruct FunctionCall {\n    name: Option\u003CString>,\n    args: Option\u003Cserde_json::Value>,  \u002F\u002F full DOM parse of potentially huge args\n}\n\u002F\u002F later: let arguments = fc.args.as_ref().map(|v| v.to_string());\n```\n\n**After (good):**\n```rust\nstruct FunctionCall {\n    name: Option\u003CString>,\n    args: Option\u003CBox\u003Cserde_json::value::RawValue>>,  \u002F\u002F zero-copy string slice\n}\n\u002F\u002F later: let arguments = fc.args.as_ref().map(|v| v.get().to_owned());\n```\n\n## Memory and resource management\n\n- **File handle limits**: VirtioFS caps at 4096 open file handles, returns `EMFILE` beyond that.\n- **Read size limits**: VirtioFS clamps reads to 1MB, gather buffers to 2MB.\n- **Safe deserialization**: `read_struct` returns `Option\u003CT>` with bounds checks in all builds (not just debug).\n- **irqfd for interrupt delivery**: Guest interrupt signaling uses `irqfd` to avoid cross-thread syscall overhead.\n\n## Concurrency patterns\n\n- **Shared runtime caches**: Use `capsem-cache` primitives instead of a local\n  map and eviction policy. Import capacities and freshness windows from the\n  generated `capsem_proto::CACHE_*` constants; their only numeric source is\n  `[cache]` in `config\u002Fdata\u002Fruntime-limits.toml`.\n- **Arc for shared state**: VM state, proxy config, and telemetry handles are `Arc`-wrapped for sharing across tasks.\n- **Per-connection tasks**: The MITM proxy spawns a new tokio task per connection. Each task owns its TLS state and upstream connection. No shared mutable state between connections.\n- **Config-owned runtime ceilings**: Network concurrency and in-memory cache\n  policy are owned by\n  `config\u002Fdata\u002Fruntime-limits.toml` and generated into `capsem-proto`. Import\n  the shared protocol constant in host and guest consumers; never duplicate a\n  numeric capacity in individual crates. Ledger queue and batch capacities\n  derive from the same supported-client ceiling, and bounded coalescing waits\n  use the generated duration rather than a local sleep literal. Extend the\n  runtime-limit Citadel guard for every new consumer. See `\u002Fdev-mitm-proxy` for\n  the load proof required when a limit changes.\n\n### Host-serialization locks for per-host critical sections\n\nWhen a service orchestrates N sibling child processes on a single host and some operations cannot safely run two-at-a-time on that host -- whether because of a framework constraint (Apple VZ save\u002Frestore) or because of shared-resource starvation (VZ teardown + WAL checkpoint + virtiofs drain all competing for main-thread and I\u002FO bandwidth) -- park a `tokio::sync::Mutex\u003C()>` on the service's shared state struct and acquire it at the top of the handler for the whole duration of the critical section. `Mutex\u003C()>` isn't a weird construction: the unit value is the lock-token, the type signals \"pure serialization, no protected payload\". `Semaphore::new(1)` is equivalent -- pick one and stay consistent.\n\nCurrent instances in `crates\u002Fcapsem-service\u002Fsrc\u002Fmain.rs`:\n\n- **`save_restore_lock`**: serializes Apple VZ `saveMachineStateToURL` \u002F `restoreMachineStateFromURL` across sibling VMs. Concurrent save\u002Frestore corrupts the VirtioFS ring state on the unlucky VM, surfaces as ext4-on-loop0 I\u002FO errors after resume. Held through `handle_suspend` (IPC + child-exit wait) and `handle_resume` (spawn + `wait_for_vm_ready`). See `web\u002Fdocs\u002Fsrc\u002Fcontent\u002Fdocs\u002Fgotchas\u002Fconcurrent-suspend-resume.md`.\n\n- **`shutdown_lock`**: serializes VM teardown across `handle_delete` \u002F `handle_stop` \u002F `handle_purge` \u002F `handle_run`. Without it, N concurrent deletes under load starve each other of the bandwidth each `capsem-process` needs to exit cleanly within the 1s fast-path budget; past the budget the service SIGKILLs mid-checkpoint and leaves a non-empty `session.db-wal`. Held through `shutdown_vm_process` for the whole `SIGTERM` + `wait_for_process_exit` window.\n\nWhen to reach for this pattern:\n\n- Symptom is \"works solo, fails under concurrency on the same host.\"\n- Root cause is a *per-host* resource, not per-VM: Apple VZ main thread, virtiofsd, DbWriter checkpoint, APFS fsync.\n- Production runs exactly one service per host per user, so an in-process tokio mutex is enough -- no need for a file-lock or distributed primitive.\n\nWhen NOT to reach for it:\n\n- If the contention is per-VM (two handlers acting on the same VM), protect the VM entry in `instances: Mutex\u003CHashMap\u003C...>>` instead.\n- If the \"contention\" is really a durability race (writer thread hasn't flushed), the right fix is usually the signal-handler explicit-cleanup pattern below, not another serialization lock.\n\n### Signal-driven explicit cleanup for background-thread owners\n\nAny long-running Rust process that owns background threads (SQLite writer, the fs-monitor scan loop, MCP aggregator subprocess, vsock relay) and runs under a bounded SIGTERM-to-SIGKILL budget must NOT rely on `Drop` + tokio-runtime-drop ordering to finish cleanup. On SIGTERM, hand owned resources to the signal handler and drain them synchronously BEFORE letting the main run loop return.\n\nSymptom when this is missing: under concurrent teardowns on one host, the service SIGKILLs a child mid-checkpoint or mid-flush. Visible as `session.db-wal` left non-empty, missing `fs_events` rows, dangling aggregator subprocesses. Works solo, fails under `-n 4`.\n\nConcrete primitives in this tree:\n\n- **`DbWriter::shutdown_blocking(&self)`** — takes the stored mpsc sender, joins the writer thread, runs the final `PRAGMA wal_checkpoint(TRUNCATE)`. Arc-safe: other `Arc\u003CDbWriter>` clones remain valid but their writes become no-ops. Idempotent. Drop delegates to it.\n- **`FsMonitor::shutdown_and_join(&self)`** — sends on the shutdown channel so the scan loop runs one final scan and emission, then joins the thread. Bounded at two scans and two emissions. Must run BEFORE DbWriter shutdown, because fs_events fan into DbWriter.\n- **`CAPSEM_TEST_SLOW_CHECKPOINT_MS`** — test-only env var in `writer_loop` that inserts a sleep before the final checkpoint. Use in tests that need to distinguish explicit cleanup from implicit runtime-drop ordering.\n\nCanonical wiring in `crates\u002Fcapsem-process\u002Fsrc\u002Fmain.rs`:\n\n```rust\nstruct Shutdown {\n    db: Option\u003CArc\u003CDbWriter>>,\n    fs_monitor: Option\u003CFsMonitor>,\n}\n\nimpl Shutdown {\n    fn drain_blocking(&mut self) {\n        \u002F\u002F fs_events fan into DbWriter -- flush fs_monitor first.\n        if let Some(m) = self.fs_monitor.take() { m.shutdown_and_join(); }\n        if let Some(db) = self.db.take() { db.shutdown_blocking(); }\n    }\n}\n\n\u002F\u002F Populate as owners are constructed:\nshutdown.lock().await.db = Some(Arc::clone(&db));\nshutdown.lock().await.fs_monitor = Some(monitor);\n\n\u002F\u002F Signal handler drains through spawn_blocking, then stops the run loop:\nrt.spawn(async move {\n    \u002F* wait on SIGTERM\u002FSIGINT *\u002F\n    let mut owned = std::mem::take(&mut *shutdown.lock().await);\n    let _ = tokio::task::spawn_blocking(move || owned.drain_blocking()).await;\n    unsafe { core_foundation_sys::runloop::CFRunLoopStop(...); }\n});\n```\n\nKey properties:\n\n1. **Deterministic order.** The drain order is explicit (fs_monitor -> db), not \"whatever reverse-declaration-order Drop happens to give us after tokio aborts tasks.\"\n2. **Synchronous join.** The handler waits for each background thread to finish. No \"hope the task finishes before the runtime drops.\"\n3. **Run loop stops last.** `CFRunLoopStop` (macOS) fires only after drain returns. Main returns afterwards; the remaining tokio-runtime drop is now a no-op fast path because the heavy work already completed.\n4. **Arc-safe shutdown APIs.** `shutdown_blocking(&self)` works through a shared `Arc\u003CDbWriter>` — callers don't have to chase down every clone. Use `std::sync::Mutex\u003COption\u003CSender>>` internally; the hot-path `write()` clones the sender under the lock and releases it before `.await`.\n\nWhen to reach for this pattern:\n\n- The process has `std::thread::spawn` or `tokio::task::spawn_blocking` workers that run durability-critical work on shutdown (WAL checkpoint, queue flush, child-process wait).\n- A parent sends SIGTERM then SIGKILLs after a short, fixed budget.\n- Today's cleanup relies on Drop running inside tokio task abort — i.e., you can't draw a line between \"cleanup finished\" and \"run loop exited.\"\n\nCall out when NOT to use it:\n\n- One-shot CLIs that exit on natural task completion (no run loop, no signal window).\n- Workers whose only side effects are in-memory (no durability to lose).\n\nWhen adding a new long-running process or a new background-thread owner, wire it through `Shutdown` from day one. Don't ship a new binary that \"should be fine because Drop will run\" — under load, Drop won't run in time.\n\n## Logging\n\n- `tracing` crate with `FmtSpan::CLOSE` for timing spans\n- `RUST_LOG=capsem=debug` for full boot timing breakdown\n- `RUST_LOG=capsem=info` for top-level only\n- Use structured fields: `tracing::info!(domain = %domain, status = %code, \"request completed\")`\n\n## One rule, one function\n\n**A rule that lives in its callers is a rule that will be wrong in some of\nthem.** Resolution, precedence, and lifetime rules belong in a function; callers\ncall it.\n\nThis is the single most expensive pattern in this codebase's history. Two\ninstances, both found the same day:\n\n| Rule | Copies | Outcome |\n|---|---|---|\n| \"read the recent log\" | 4 (`support_bundle`, `\u002Fservice-logs`, `triage`, service session tails) | rotation landed, one copy learned, two silently returned nothing -- a daemon logging errors reported none |\n| \"point Capsem at a temp root\" | every fixture, by hand | `CAPSEM_RUN_DIR`\u002F`CAPSEM_ASSETS_DIR` outrank `CAPSEM_HOME`, so setting the home alone read the caller's directories: green locally, broken in the gate |\n\nBoth look locally correct in every copy. That is what makes them expensive:\nnothing is visibly wrong at any one site, and a fix applied to one never\nreaches the others.\n\n**Established wrappers -- use them, do not re-derive:**\n\n| Need | Call | Never |\n|---|---|---|\n| Host log content | `telemetry::read_log_tail(stream, max)` | `File::open`\u002F`fs::read` on a `*.log` path |\n| Session console\u002Ftranscript | `session::read_session_serial_log` \u002F `read_session_transcript` | Reopening a root-level log path or resolving worker-writable parents by path |\n| Enumerate a stream | `telemetry::log_stream_files(stream)` | `read_dir` + name filtering |\n| Redirect paths in a fixture | `paths::CapsemPathsGuard::redirect(root)` | `set_var(\"CAPSEM_HOME\", ...)` |\n| Any `~\u002F.capsem\u002F...` path | a `paths::` helper | `home.join(\".capsem\")` |\n| Checkpoint marker | `paths::checkpoint_complete_path(cp)` | rebuilding `\u003Cname>.complete` |\n\n`build_system\u002Ftests\u002Fgate\u002Ftest_path_and_log_wrappers_are_mandatory.py` enforces the first three.\n\n**When unifying, take the better implementation, not the first one.**\n`support_bundle`'s tail reader seeked to each file's end; the shared one read\nwhole files. Guest console output is guest-controlled, so read-whole let a\nchatty VM decide how much memory `capsem support` allocated. The shared\nfunction now seeks.\n\n**Two copies that agree today are still a bug.** `checkpoint_complete_path`\nexisted in capsem-process and capsem-service, identical except that one\nhardcoded the fallback name and the other used a constant. Changing that\nconstant would have left the process writing a resume marker the service never\nlooked for, with nothing wrong at either site.\n\n## Lessons learned\n\n1. **Content-Encoding**: Always handle response decompression generically. Gzip compressed SSE responses caused NULL telemetry because the parser got binary garbage. Never strip Accept-Encoding as a workaround.\n\n2. **Platform type widths**: `as _` is your friend for cross-platform libc calls. Explicit casts (`as c_ulong`) will fail on the other platform.\n\n3. **Debouncer timing**: If a VM shuts down before debounced events flush, telemetry is lost. Add `sleep 1` in test commands, or use explicit flush on shutdown.\n\n4. **VirtioFS whiteouts**: Apple VZ's VirtioFS doesn't support `mknod`, so overlayfs can't use it directly as upper. The ext4 loopback workaround provides full POSIX.\n\n5. **setsid for controlling terminal**: Without `setsid`, the PTY has no foreground process group and Ctrl-C (SIGINT) is not delivered. `capsem-init` uses `setsid` to fix this.\n\n6. **serde_json::Value on LLM hot path**: Three ai_traffic struct fields (`ResponseInfo.output`, `FunctionResponse.response`, `FunctionCall.args`) used `serde_json::Value` for large payloads that were only stringified. This forced full DOM allocation on every streaming request. Fixed by removing unused fields and switching to `Box\u003Cserde_json::value::RawValue>`.\n\n7. **Prefer syscalls over subprocesses**: `std::process::Command` costs 5-30ms per spawn (fork\u002Fexec). If a syscall does the same thing, use it. Example: `cp -c -R` for APFS clonefile was 20-30ms; a direct clone syscall is \u003C1ms. `capsem_foundation::unix::fs::clone_file_into` uses `fclonefileat` on macOS and the `FICLONE` ioctl on Linux -- no subprocess. Always check if the OS provides a syscall before reaching for `Command`.\n\n7. **Blocking I\u002FO in MCP tool handlers**: Tool handlers once ran blocking I\u002FO (clonefile subprocess, walkdir, blake3) directly on tokio worker threads while holding a `tokio::sync::Mutex`, so tool calls hung from the model's perspective. Fixed by wrapping in `spawn_blocking` everywhere; see the anti-pattern section above.\n\n7. **Clone guest-writable trees through descriptors, never paths**: Everything below `session_dir\u002Fguest\u002F` is guest-controlled and may change mid-copy (an entry swapped for a symlink to a host path). Fork\u002Fcreate-from therefore go through `capsem_core::session::clone_sandbox_state`, which composes `capsem_foundation::unix::tree_clone`: descriptor-relative `O_NOFOLLOW` opens, exclusive destination creation, symlinks recreated but never followed, special files skipped, setuid\u002Fsetgid\u002Fsticky bits dropped, and a non-regular `rootfs.img` refused. File contents clone from the open descriptor via `unix::fs::clone_file_into` (shared extents, or a sparse copy when the filesystem cannot share them). Never add a path-based `std::fs::copy`\u002F`walkdir` copy of guest state. A CoW clone is metadata-only, so flush `rootfs.img` before cloning (`flush_system_overlay`) or the clone captures stale data.\n\n8. **Platform-gate all macOS-only APIs**: Any code using macOS-only symbols (`libc::clonefile`, Apple framework bindings, etc.) must be wrapped in `#[cfg(target_os = \"macos\")]` -- both the struct\u002Fimpl and the tests. The Linux app build (Tauri deb\u002FAppImage) compiles the full workspace; ungated macOS symbols cause `cannot find function` errors on Linux CI. This burned v0.14.7: a clone helper used `libc::clonefile` without a cfg gate. Rule: when adding platform-specific code, gate the definition, the impl, and the tests.\n\n9. **Readiness gates must reflect actual state**: `handle_ipc_connection` responded to Ping with Pong the moment the UDS socket existed -- before vsock connections, boot handshake, or command handler spawn. `wait_for_vm_ready` treated Pong as \"ready\", so exec commands were sent to a process that couldn't handle them yet, blocking silently in a channel until `setup_vsock` finished. Tests masked this with `wait_exec_ready()` client-side retry loops, creating a double-wait: 30 client retries x 30s server wait each. Fix: `Arc\u003CAtomicBool>` (`vm_ready`) gated by `setup_vsock` after BootReady; IPC handler only sends Pong when the flag is set. One wait, one place -- the server waits; the client calls once. When adding any new IPC readiness check, never respond \"ready\" based on socket existence alone; check actual process state via a shared flag or state enum.\n\n10. **VirtioFS and FSEvents**: Apple VZ VirtioFS guest writes bypass macOS FSEvents (the kernel's file notification subsystem), so `notify::RecommendedWatcher` silently drops guest-originated events and a host directory shared into a guest has to be polled. Do **not** reach for `notify::poll::PollWatcher` to do it: it walks with `follow_links(true)` hardcoded (`notify-7.0.0\u002Fsrc\u002Fpoll.rs`) and its `configure` is a no-op, so one guest `ln -s \u002F workspace\u002Fevil` turns every scan into a walk of the host's entire filesystem. Own the loop instead, as `crates\u002Fcapsem-core\u002Fsrc\u002Ffs_monitor.rs` does: a `walkdir` walk with `follow_links(false)`, a snapshot of `(kind, len, mtime, ctime, ino)` per entry, and the difference between two walks as the events. Owning it also lets the cadence track the measured scan cost rather than a constant, and lets a symlink be recorded as a symlink instead of being descended.\n\n11. **Process sandbox: env_clear() on child spawn**: When spawning a child process (e.g., capsem-process from service), always call `env_clear()` then re-add only the minimal env vars needed (`HOME`, `PATH`, `USER`, `TMPDIR`, `RUST_LOG`). The service's shell environment may contain API keys, tokens, or secrets that the child process has no business seeing. The guest's `--env` args are a separate injection path and are already validated.\n\n12. **UDS socket permissions must be 0600**: After `UnixListener::bind()`, immediately `set_permissions(..., 0o600)`. The default umask leaves sockets world-accessible, meaning any local user can connect to a VM's IPC or terminal WebSocket with no auth. The gateway token file already does this; per-VM sockets must match.\n\n13. **Never process::exit() on guest-controlled I\u002FO**: A guest can close a vsock fd at any time. If the host handler calls `process::exit(1)` on read error, the guest has an unconditional DoS. Use `break` to exit the read loop and let the process shut down through normal channels.\n\n14. **Sensitive logs cross a worker boundary**: Terminal and serial files contain raw user data. Use `unix::fs` single-link, no-follow file helpers and bound reads; a confined writer can still plant a redirect at its own log path. Below worker-writable directories, anchor access through `ContainedDir` descriptors. Prepare `session::prepare_session_logs` under the exclusive owner lock before confinement: it retains `owner\u002Flogs\u002F` and migrates legacy generations without overwriting conflicts. Hypervisor console and terminal output share one `SharedLogWriter` and rotation counter; never open an independent appender. Writers retain directory descriptors across rotation, which needs directory authority rather than exact-file grants. Keep session root and ledger outside that grant. Create files with mode 0600 and repair permissions before confinement or through the authorized broker; confined writers must not call `set_permissions`. Session readers use the shared console\u002Ftranscript APIs, falling back only for a missing layout. Support exports redact recognized credential bytes even in mixed binary\u002Ftext lines, preserving unrelated bytes without a UTF-8 bypass. The PTY, telemetry, support-export and actual owner-sandbox regressions prove retention and malicious redirects.\n\n15. **VirtioFS share boundary -- only guest\u002F subtree**: The VirtioFS share must point at `session_dir\u002Fguest\u002F`, not `session_dir` itself. Host-only state (`session.db`, `owner\u002Flogs\u002F`, `owner\u002Fcheckpoint.vzsave`, `system\u002Frootfs.img`) stays outside the share. The system disk lives in the host-only `system\u002F` directory; never restore a compatibility link into guest storage. Put guest-visible content under `guest\u002F`. Use `capsem_core::guest_share_dir(session_dir)` to get the share root.\n\n16. **VM route id is not the display name**: `SandboxInfo.id`, route path ids,\n`InstanceInfo.id`, DB handle keys, session directory basenames, and\n`CAPSEM_VM_ID` must be the opaque VM\u002Fsession id. Persistent registry `name`\nvalues such as `co-work1` or `code-vm1` are display aliases only. User surfaces\nmay accept names, but they must translate to id before calling `\u002Fvms\u002F{id}\u002F...`.\nDo not use `registry.get(&id)` in route code unless the route id has first been\nresolved to the registry key; use the persistent identity helpers instead.\nWhen returning UI\u002FAPI payloads, preserve both `id` and `name`. Regression\ncoverage lives in `persistent_session_routes_keep_uuid_id_separate_from_display_name`,\n`resume_sandbox_requires_uuid_route_id_not_display_name`, and\n`persistent_route_identity_source_guard`.\n\n17. **Use `capsem_core::poll::poll_until` for all async polling**: All \"wait until ready\" patterns must use the shared `poll_until` utility in `capsem-core\u002Fsrc\u002Fpoll.rs`. It provides deadline-based timeout, exponential backoff, and structured tracing (attempt count, elapsed time, label). Never write ad-hoc `for _ in 0..N { sleep(X) }` or `while now \u003C deadline { sleep(fixed) }` loops -- they lack logging, use fixed intervals instead of backoff, and hardcode timeouts. For sync code (guest agent), `vsock_connect_retry` in `vsock_io.rs` has the same pattern with `eprintln` logging. Every retry loop must have a total deadline.\n\n18. **DRY wait patterns -- one wait, one place**: When a server endpoint already waits for a subprocess to become ready (e.g., `wait_for_vm_ready` in `handle_exec`), clients must not add their own retry loop on top. The test helper `wait_exec_ready` previously polled 30 times with 1s sleep, and each poll triggered a 30s server-side wait -- a 30x30s pathological cascade. After fixing the readiness gate (lesson 9), the client calls exec once with adequate HTTP timeout and the server handles the wait. Apply this DRY principle to any client\u002Fserver readiness pattern: decide which layer owns the wait and make others pass through.\n\n19. **Companions must not outlive their parent -- `kill_on_drop` is not enough**: `tokio::process::Command::kill_on_drop(true)` only fires when the parent's `Child` handle is dropped on graceful shutdown. Under SIGKILL\u002FOOM\u002Ftest-harness timeout\u002F pytest-xdist worker death, Drop never runs and companion processes (gateway, tray) get re-parented to PID 1 and survive forever. Every `just test -n 4` run leaked a fresh batch of orphans; accumulated orphans caused VM-ready poll spins, UDS-port collisions, and the suspend\u002Fresume regression. Defense in depth is mandatory for any spawned companion process, enforced on the COMPANION side so the parent can't get it wrong:\n    - Pass `--parent-pid \u003Cspawner_pid>` when spawning.\n    - Companion calls `capsem_guard::install(parent_pid, lock_path)?` at startup:\n      - Refuses to run if parent PID is missing, dead, or not our actual `getppid()` (`parent_is_expected`). Exit 0 — standalone launches become silent no-ops.\n      - Acquires an `flock(2)` singleton at `lock_path` (O_CLOEXEC opened atomically; process-local registry covers the brief fork-to-exec window where the flock fd can be inherited). Second instance exits 0.\n      - Spawns a 100ms-interval watcher thread that calls `std::process::exit(0)` the moment `getppid()` no longer equals the declared parent PID. `getppid()` is immune to zombie state and flips to 1 on re-parenting, which is the reliable signal across SIGKILL, SIGSEGV, and OOM.\n      - The mandatory terminator runs before any best-effort tracing. Parent death commonly closes a companion's stdout\u002Fstderr pipes; logging to that dead sink can panic the watcher thread, so observability must never stand between detecting reparenting and exiting.\n    - Lock paths: tray is SYSTEM-WIDE (`$HOME\u002F.capsem\u002Frun\u002Ftray.lock`) because the macOS menu bar is a shared global resource; gateway is per-run_dir because each test's gateway bridges a distinct UDS. Regression tests in `tests\u002Fcapsem-service\u002Ftest_companion_lifecycle.py` cover: refuse-standalone (no parent \u002F wrong parent), singleton (double spawn, 20-way hammer), and die-with-parent (SIGKILL the parent, companion exits within 5s). When adding any new companion process, wire it through `capsem-guard` — don't invent a new pattern.\n\n20. **Retry loops must classify errors, not time-bound a blanket wait**: When waiting for a resource to come up, the retry closure must distinguish *retryable* errors from *permanent* ones, and the classification depends on the caller's context, not the error itself. Identical `NotFound` \u002F `ConnectionRefused` errors mean \"service is down, give up\" on an initial probe but \"socket not bound yet, keep waiting\" one call later in the post-launch retry. Pattern:\n    - **Use `capsem_core::poll::poll_until`, not a hand-rolled backoff loop.** The poll primitive already gives you deadline, exponential backoff, per-attempt logging (label + elapsed + attempts), and a typed `TimedOut` error. Every new retry site that reinvents these is a future bug -- the `capsem doctor` \"Service manager started capsem but socket not ready\" bug existed only because `UdsClient::connect_with_timeout` hand-rolled its own loop and fast-failed on `ENOENT` before the just-started service had bound its socket.\n    - **Inside the `poll_until` closure:** return `None` on retryable errors (`poll_until` keeps polling), return `Some(Err(...))` on permanent errors (`poll_until` exits immediately).\n    - **Thread a small enum, not a `patient: bool`**, so every call site documents intent: `ConnectMode::FailFast` vs `ConnectMode::AwaitStartup`, `ProbeMode::Expected` vs `ProbeMode::MustBeRunning`. `crates\u002Fcapsem\u002Fsrc\u002Fclient.rs::UdsClient::connect_with_timeout` is the canonical example in the tree.\n    - **Don't `.map_err(|_| anyhow!(...))` on the timeout branch.** You erase the inner cause. Chain with `Context` so the root error lives in the error chain and `{err:#}` prints both the summary and the underlying io::Error kind.\n\n## Async reference\n\nRead `references\u002Frust-async-patterns.md` for comprehensive tokio patterns (tasks, channels, streams, error handling). From the community (6.4K installs).\n","# Rust Patterns\n\n## Data paths: zero-copy first, no speculative hashing or JSON\n\nRead [data-path performance](references\u002Fdata-path-performance.md) before changing\ntransport, admission, serialization, hashing or buffer ownership. Prefer moving\nor borrowing bytes and one bounded encoding into the final frame. Hashing and\nJSON require a concrete, documented contract; neither is a default safety step.\n\n## Async \u002F non-blocking\n\nCapsem uses tokio for all async I\u002FO. The MITM proxy, vsock manager, and file monitor are all async.\n\nPublish matching in-memory ownership inside the serialized blocking admission,\nbefore releasing its I\u002FO permit. A reader can observe the durable record before\nthe async caller resumes after `spawn_blocking`; publishing its ticket after\n`.await` exposed valid managed-session claims to `recovery_pending`. The\ncontroller regression pauses that continuation and claims through the real store.\n\n### Never block the tokio runtime\n\nLong-running synchronous work (FUSE request processing, disk I\u002FO, compression) must run on a dedicated thread via `tokio::task::spawn_blocking` or a dedicated `std::thread`. Blocking inside a tokio task starves other tasks.\n\nThe VirtioFS FUSE server runs on its own thread for this reason -- FUSE ops are synchronous by nature (read, write, lookup) and can't be made async without significant complexity.\n\n### Blocking-in-async anti-pattern (systemic -- audit, don't spot-fix)\n\nAny code path that does blocking I\u002FO inside an async function or while holding a `tokio::sync::Mutex` is a bug. This causes the tokio worker thread to stall, freezing the entire gateway, UI, or network stack until the blocking operation completes.\n\n**What counts as blocking I\u002FO:**\n- `std::process::Command` (subprocess execution)\n- `std::fs::*` (read, write, copy, remove_dir_all, create_dir_all)\n- `walkdir::WalkDir` (directory traversal)\n- `blake3::Hasher` on large data (hash computation)\n- `std::thread::sleep`\n\n**The fix pattern** -- in `capsem-service`, route handlers go through `ServiceState::off_worker` (`crates\u002Fcapsem-service\u002Fsrc\u002Fblocking.rs`), and `crates\u002Fcapsem-service\u002Fsrc\u002Ftests\u002Fasync_io_contract.rs` refuses direct blocking calls. Elsewhere, the shape is:\n```rust\nlet result = tokio::task::spawn_blocking(move || {\n    let rt = tokio::runtime::Handle::current();\n    rt.block_on(async {\n        let mut guard = mutex.lock().await;\n        sync_blocking_work(&mut guard)\n    })\n}).await.unwrap_or_else(|e| \u002F* handle panic *\u002F);\n```\n\n**Example site:** the fork clone (`crates\u002Fcapsem-service\u002Fsrc\u002Fvm_files\u002Ffork.rs`) runs `clone_sandbox_state` -- fsync, clonefile, and a full tree walk -- on the blocking pool. Any new tree copy, hash, or directory walk reachable from an async handler needs the same treatment.\n\n### Channel patterns\n\n- `tokio::sync::mpsc` for producer-consumer (vsock data flow, telemetry events)\n- `tokio::sync::broadcast` for fan-out (serial output to multiple subscribers)\n- `tokio::sync::oneshot` for single-response request-reply (control messages)\n\n### Logger DB boundary\n\n`capsem-logger` owns SQLite connection\u002Fthread\u002Fstorage mechanics. Rust service,\ngateway, MCP, UI, and benchmark code must not call `rusqlite::Connection::open`\nor `DbReader::open` directly for telemetry\u002Fsecurity ledgers, and must not add\nservice-owned projection caches.\n\nCallers may own query intent, but the DB object owns execution:\n\n```rust\ndb.ready().await?;\ndb.query(sql, params).await?;\ndb.write(event).await?;\n```\n\n`db.write(event).await` is an accept boundary: the DB-owned producer buffer\nhas taken responsibility for the event. Read-after-write tests must use the DB\nflush barrier or shutdown\u002Freopen before asserting route-visible rows. Never add\nroute sleeps, route projection caches, or caller-owned SQLite reads to force\nvisibility.\n\nDo not hide route SQL by adding route-specific helpers to `DbWriter`; the DB\nwriter is not a product route registry. Put connection threads, `mem`\u002Fdisk\ntables, batching, flushing, WAL tuning, and future FTS5\u002Fsearch in\nthe DB layer. Empty tables are fine. Missing tables or columns are schema\ncontract failures and must not be converted into empty results.\n\n### Coalescing buffer\n\nTerminal output uses a `CoalesceBuffer` (8ms window, 64KB cap) to batch small vsock reads into larger writes. This prevents xterm.js from choking on thousands of tiny updates. The pattern: accumulate into a buffer, flush on timer or size threshold.\n\n### Graceful shutdown\n\nUse `tokio::select!` with a cancellation token or shutdown signal. Every long-running task must respect shutdown. Dangling tasks after VM exit cause resource leaks.\n\n## Cross-compilation\n\nGuest binaries target `aarch64-unknown-linux-musl` and `x86_64-unknown-linux-musl`. Key gotchas:\n\n- **Platform-specific types**: `libc::ioctl` request param is `c_ulong` on macOS but `c_int` on Linux. Use `as _` to let the compiler infer the correct type.\n- **Linker**: `.cargo\u002Fconfig.toml` sets `linker = \"rust-lld\"` for both musl targets.\n- **No std dependencies**: musl builds are fully static. Avoid crates that link to system libraries.\n- **Test on both**: `cargo check --target aarch64-unknown-linux-musl` catches cross-compile errors without needing to boot a VM.\n\n## Error handling\n\n- Use `anyhow::Result` for application code (capsem-app, scripts)\n- Use `thiserror` for library errors in capsem-core (typed, matchable)\n- Propagate errors up, don't swallow them. If a function returns `Result`, the caller must handle it.\n- Log errors at the point where you have context, then propagate. Don't log AND propagate (causes duplicate log lines).\n\n## Host Unix boundary\n\nReusable host Unix mechanics belong in the small modules under\n`capsem_foundation::unix`; application crates consume their typed APIs instead\nof calling `nix` or `libc` directly. This keeps ownership, EINTR handling,\nerrno classification, CLOEXEC, no-follow behavior, and race checks identical\nacross the CLI, service, process, guard, credentials, and core.\n\n- Accept `BorrowedFd` and return `OwnedFd` or `File`. Never return a raw\n  descriptor whose close responsibility is implicit, and never pair\n  `ManuallyDrop\u003CFile>` with a manual `close`.\n- Expected races are typed outcomes: a missing process and lock contention are\n  not generic errors. Keep expected disconnects quiet; log unexpected failures\n  once where the caller knows the operation, object identity, and errno.\n- Use `unix::contained::ContainedDir` for guest-influenced paths. Its\n  descriptor-relative traversal, constrained open options, and regular-file\n  checks must remain in the same syscall sequence; do not put a path-based\n  check in front of a separate path-based action.\n- Use `unix::fs` for owner-only directories, no-follow regular-file access,\n  filesystem capacity, atomic private publication, permission bits\n  (`set_mode`), durability (`sync`, `sync_before_barrier`,\n  `sync_filesystem`) and copy-on-write cloning (`clone_file_into`,\n  `copy_sparse`). Use `unix::tree_clone` to copy a directory tree a guest can\n  write. Use `unix::lock` for advisory locks, including synchronous\n  read-modify-write sections.\n- When foundation lacks a primitive, add it to foundation with its tests;\n  never reach for `nix` or `libc` at the call site \"just this once\".\n- Inside foundation, `nix` is the syscall layer and `unix::errno::io` converts\n  its errors. A raw `libc::` call is allowed only where `nix` cannot express it\n  (no wrapper, or a platform gap such as `MSG_NOSIGNAL` on macOS), and each\n  one is listed with that reason in `tests\u002Fcitadel\u002Funix_boundary_debt.toml`.\n- Put each primitive in its own module with tests in the sibling `tests.rs`.\n  Cover errno preservation, ownership after the source is dropped, symlink and\n  path-replacement races, special files, exact modes, and concurrent callers.\n\nWhen transferring connected sockets with `unix::router_channel`, retain the\noriginal socket until a request-bound receipt confirms that the receiver owns\nand validated its descriptor. A completed `sendmsg` only queues SCM_RIGHTS;\nDarwin may collect sockets with no owner outside that queue. Bound the receipt\nwait, reject wrong identities, directions and extra descriptors, and preserve\nscope cancellation and positive child reaping. The native MCP regression is\n`upstream_broker\u002Fmcp_spawn\u002Ftests.rs`: it delays adoption, checks that the original\nstays alive, and proves it is released after the receipt. Keeping an extra\nsocket for the child's entire lifetime masks disconnects and leaks descriptors.\nThe same rule covers startup policy, proxy traffic\u002FMCP\u002Ftrace hints, ledger\nclients, gateway connections and the aggregator's owner connection. Auditing\nonly the native MCP bootstrap missed these paths and left a macOS policy-update\nbroken pipe. `tests\u002Fcitadel\u002Ftest_descriptor_adoption_lifetime.py` guards the\nearly-drop sites, including private cable handoff: its table reference can be\nreplaced by a reconnect before adoption. Gateway and upstream grant tests drop the received copy\nbefore acknowledging to prove the sender still owns its original, then assert\nEOF after adoption to rule out retention leaks.\n\nDirect Unix calls remain valid only in modules that implement a kernel or\nplatform ABI rather than reusable host policy, such as KVM\u002FFUSE and guest audit\nplumbing. `tests\u002Fcitadel\u002Ftest_unix_boundary.py` and its exact domain-ABI\ninventory enforce that distinction; extending the inventory requires explicit\nreview, not a convenience exemption. The same guard inventories every raw\n`libc::` call and `extern \"C\"` binding inside foundation itself, rejects a new\none that `nix` already wraps, and catches aliased imports (`use ::libc as sys`),\n`extern \"C\" { fn ... }` blocks and renamed or table-form manifest\ndependencies. Before it did, foundation's own internals were unscanned and\nraw calls with `nix` wrappers accumulated there unnoticed.\n\n## Guest RAM and VirtioFS performance\n\nBefore changing guest RAM, KVM storage or OCI boot, read\n[Guest RAM and VirtioFS performance](references\u002Fguest-memory-performance.md).\nKeep RAM and KVM slot offsets aligned to 2 MiB and request transparent huge\npages through `capsem_foundation::unix::guest_memory::GuestRam`. A regular\n4-KiB-backed mapping once made kernel startup take 1.1 seconds and a 352-MB\nEROFS scan wait 1.5 seconds in reads. The allocation and slot regression is\n`guest_ram_and_kvm_slot_offsets_preserve_huge_page_alignment` in\n`hypervisor\u002Fkvm\u002Fmemory\u002Ftests.rs`; alignment alone is insufficient without the\nper-mapping huge-page hint.\n\n## Bidirectional I\u002FO -- thread per direction\n\nWhen bridging two blocking file descriptors bidirectionally (e.g., TCP socket to vsock in `net_proxy.rs`, or master PTY to vsock in `capsem-pty-agent`), doing both reads and writes in a single thread using `poll(2)` causes deadlocks. If both outgoing buffers fill simultaneously, a single thread blocks on writing and stops reading, creating mutual lockup. Always spawn a dedicated thread for at least one direction (`std::thread::spawn` for `fd_b -> fd_a` while the main thread handles `fd_a -> fd_b`).\n\n## Serde -- avoid `serde_json::Value` on LLM payloads\n\nThe MITM proxy and ai_traffic parsers handle massive HTTP payloads (megabytes of tool calls, histories, images). Parsing these into `serde_json::Value` does full DOM allocation, which is inefficient and risks memory exhaustion.\n\n**Rules:**\n- Define targeted structs with `#[derive(Deserialize)]`. Serde skips and discards fields not in the struct without allocating memory for them.\n- For struct fields that hold large, unconstrained JSON (tool call arguments, function responses, full model outputs) and are only converted to strings: use `Box\u003Cserde_json::value::RawValue>` instead of `serde_json::Value`. `RawValue` keeps the JSON as an unparsed string slice -- zero DOM allocation. Access the raw JSON string via `.get()`.\n- Never add `serde_json::Value` fields to structs that parse LLM request\u002Fresponse bodies. If you only need a string representation, use `RawValue`. If you need to traverse nested fields, use a typed struct.\n- Remove unused fields from deserialization structs -- they still force Serde to allocate.\n\n**Example -- before (bad):**\n```rust\nstruct FunctionCall {\n    name: Option\u003CString>,\n    args: Option\u003Cserde_json::Value>,  \u002F\u002F full DOM parse of potentially huge args\n}\n\u002F\u002F later: let arguments = fc.args.as_ref().map(|v| v.to_string());\n```\n\n**After (good):**\n```rust\nstruct FunctionCall {\n    name: Option\u003CString>,\n    args: Option\u003CBox\u003Cserde_json::value::RawValue>>,  \u002F\u002F zero-copy string slice\n}\n\u002F\u002F later: let arguments = fc.args.as_ref().map(|v| v.get().to_owned());\n```\n\n## Memory and resource management\n\n- **File handle limits**: VirtioFS caps at 4096 open file handles, returns `EMFILE` beyond that.\n- **Read size limits**: VirtioFS clamps reads to 1MB, gather buffers to 2MB.\n- **Safe deserialization**: `read_struct` returns `Option\u003CT>` with bounds checks in all builds (not just debug).\n- **irqfd for interrupt delivery**: Guest interrupt signaling uses `irqfd` to avoid cross-thread syscall overhead.\n\n## Concurrency patterns\n\n- **Shared runtime caches**: Use `capsem-cache` primitives instead of a local\n  map and eviction policy. Import capacities and freshness windows from the\n  generated `capsem_proto::CACHE_*` constants; their only numeric source is\n  `[cache]` in `config\u002Fdata\u002Fruntime-limits.toml`.\n- **Arc for shared state**: VM state, proxy config, and telemetry handles are `Arc`-wrapped for sharing across tasks.\n- **Per-connection tasks**: The MITM proxy spawns a new tokio task per connection. Each task owns its TLS state and upstream connection. No shared mutable state between connections.\n- **Config-owned runtime ceilings**: Network concurrency and in-memory cache\n  policy are owned by\n  `config\u002Fdata\u002Fruntime-limits.toml` and generated into `capsem-proto`. Import\n  the shared protocol constant in host and guest consumers; never duplicate a\n  numeric capacity in individual crates. Ledger queue and batch capacities\n  derive from the same supported-client ceiling, and bounded coalescing waits\n  use the generated duration rather than a local sleep literal. Extend the\n  runtime-limit Citadel guard for every new consumer. See `\u002Fdev-mitm-proxy` for\n  the load proof required when a limit changes.\n\n### Host-serialization locks for per-host critical sections\n\nWhen a service orchestrates N sibling child processes on a single host and some operations cannot safely run two-at-a-time on that host -- whether because of a framework constraint (Apple VZ save\u002Frestore) or because of shared-resource starvation (VZ teardown + WAL checkpoint + virtiofs drain all competing for main-thread and I\u002FO bandwidth) -- park a `tokio::sync::Mutex\u003C()>` on the service's shared state struct and acquire it at the top of the handler for the whole duration of the critical section. `Mutex\u003C()>` isn't a weird construction: the unit value is the lock-token, the type signals \"pure serialization, no protected payload\". `Semaphore::new(1)` is equivalent -- pick one and stay consistent.\n\nCurrent instances in `crates\u002Fcapsem-service\u002Fsrc\u002Fmain.rs`:\n\n- **`save_restore_lock`**: serializes Apple VZ `saveMachineStateToURL` \u002F `restoreMachineStateFromURL` across sibling VMs. Concurrent save\u002Frestore corrupts the VirtioFS ring state on the unlucky VM, surfaces as ext4-on-loop0 I\u002FO errors after resume. Held through `handle_suspend` (IPC + child-exit wait) and `handle_resume` (spawn + `wait_for_vm_ready`). See `web\u002Fdocs\u002Fsrc\u002Fcontent\u002Fdocs\u002Fgotchas\u002Fconcurrent-suspend-resume.md`.\n\n- **`shutdown_lock`**: serializes VM teardown across `handle_delete` \u002F `handle_stop` \u002F `handle_purge` \u002F `handle_run`. Without it, N concurrent deletes under load starve each other of the bandwidth each `capsem-process` needs to exit cleanly within the 1s fast-path budget; past the budget the service SIGKILLs mid-checkpoint and leaves a non-empty `session.db-wal`. Held through `shutdown_vm_process` for the whole `SIGTERM` + `wait_for_process_exit` window.\n\nWhen to reach for this pattern:\n\n- Symptom is \"works solo, fails under concurrency on the same host.\"\n- Root cause is a *per-host* resource, not per-VM: Apple VZ main thread, virtiofsd, DbWriter checkpoint, APFS fsync.\n- Production runs exactly one service per host per user, so an in-process tokio mutex is enough -- no need for a file-lock or distributed primitive.\n\nWhen NOT to reach for it:\n\n- If the contention is per-VM (two handlers acting on the same VM), protect the VM entry in `instances: Mutex\u003CHashMap\u003C...>>` instead.\n- If the \"contention\" is really a durability race (writer thread hasn't flushed), the right fix is usually the signal-handler explicit-cleanup pattern below, not another serialization lock.\n\n### Signal-driven explicit cleanup for background-thread owners\n\nAny long-running Rust process that owns background threads (SQLite writer, the fs-monitor scan loop, MCP aggregator subprocess, vsock relay) and runs under a bounded SIGTERM-to-SIGKILL budget must NOT rely on `Drop` + tokio-runtime-drop ordering to finish cleanup. On SIGTERM, hand owned resources to the signal handler and drain them synchronously BEFORE letting the main run loop return.\n\nSymptom when this is missing: under concurrent teardowns on one host, the service SIGKILLs a child mid-checkpoint or mid-flush. Visible as `session.db-wal` left non-empty, missing `fs_events` rows, dangling aggregator subprocesses. Works solo, fails under `-n 4`.\n\nConcrete primitives in this tree:\n\n- **`DbWriter::shutdown_blocking(&self)`** — takes the stored mpsc sender, joins the writer thread, runs the final `PRAGMA wal_checkpoint(TRUNCATE)`. Arc-safe: other `Arc\u003CDbWriter>` clones remain valid but their writes become no-ops. Idempotent. Drop delegates to it.\n- **`FsMonitor::shutdown_and_join(&self)`** — sends on the shutdown channel so the scan loop runs one final scan and emission, then joins the thread. Bounded at two scans and two emissions. Must run BEFORE DbWriter shutdown, because fs_events fan into DbWriter.\n- **`CAPSEM_TEST_SLOW_CHECKPOINT_MS`** — test-only env var in `writer_loop` that inserts a sleep before the final checkpoint. Use in tests that need to distinguish explicit cleanup from implicit runtime-drop ordering.\n\nCanonical wiring in `crates\u002Fcapsem-process\u002Fsrc\u002Fmain.rs`:\n\n```rust\nstruct Shutdown {\n    db: Option\u003CArc\u003CDbWriter>>,\n    fs_monitor: Option\u003CFsMonitor>,\n}\n\nimpl Shutdown {\n    fn drain_blocking(&mut self) {\n        \u002F\u002F fs_events fan into DbWriter -- flush fs_monitor first.\n        if let Some(m) = self.fs_monitor.take() { m.shutdown_and_join(); }\n        if let Some(db) = self.db.take() { db.shutdown_blocking(); }\n    }\n}\n\n\u002F\u002F Populate as owners are constructed:\nshutdown.lock().await.db = Some(Arc::clone(&db));\nshutdown.lock().await.fs_monitor = Some(monitor);\n\n\u002F\u002F Signal handler drains through spawn_blocking, then stops the run loop:\nrt.spawn(async move {\n    \u002F* wait on SIGTERM\u002FSIGINT *\u002F\n    let mut owned = std::mem::take(&mut *shutdown.lock().await);\n    let _ = tokio::task::spawn_blocking(move || owned.drain_blocking()).await;\n    unsafe { core_foundation_sys::runloop::CFRunLoopStop(...); }\n});\n```\n\nKey properties:\n\n1. **Deterministic order.** The drain order is explicit (fs_monitor -> db), not \"whatever reverse-declaration-order Drop happens to give us after tokio aborts tasks.\"\n2. **Synchronous join.** The handler waits for each background thread to finish. No \"hope the task finishes before the runtime drops.\"\n3. **Run loop stops last.** `CFRunLoopStop` (macOS) fires only after drain returns. Main returns afterwards; the remaining tokio-runtime drop is now a no-op fast path because the heavy work already completed.\n4. **Arc-safe shutdown APIs.** `shutdown_blocking(&self)` works through a shared `Arc\u003CDbWriter>` — callers don't have to chase down every clone. Use `std::sync::Mutex\u003COption\u003CSender>>` internally; the hot-path `write()` clones the sender under the lock and releases it before `.await`.\n\nWhen to reach for this pattern:\n\n- The process has `std::thread::spawn` or `tokio::task::spawn_blocking` workers that run durability-critical work on shutdown (WAL checkpoint, queue flush, child-process wait).\n- A parent sends SIGTERM then SIGKILLs after a short, fixed budget.\n- Today's cleanup relies on Drop running inside tokio task abort — i.e., you can't draw a line between \"cleanup finished\" and \"run loop exited.\"\n\nCall out when NOT to use it:\n\n- One-shot CLIs that exit on natural task completion (no run loop, no signal window).\n- Workers whose only side effects are in-memory (no durability to lose).\n\nWhen adding a new long-running process or a new background-thread owner, wire it through `Shutdown` from day one. Don't ship a new binary that \"should be fine because Drop will run\" — under load, Drop won't run in time.\n\n## Logging\n\n- `tracing` crate with `FmtSpan::CLOSE` for timing spans\n- `RUST_LOG=capsem=debug` for full boot timing breakdown\n- `RUST_LOG=capsem=info` for top-level only\n- Use structured fields: `tracing::info!(domain = %domain, status = %code, \"request completed\")`\n\n## One rule, one function\n\n**A rule that lives in its callers is a rule that will be wrong in some of\nthem.** Resolution, precedence, and lifetime rules belong in a function; callers\ncall it.\n\nThis is the single most expensive pattern in this codebase's history. Two\ninstances, both found the same day:\n\n| Rule | Copies | Outcome |\n|---|---|---|\n| \"read the recent log\" | 4 (`support_bundle`, `\u002Fservice-logs`, `triage`, service session tails) | rotation landed, one copy learned, two silently returned nothing -- a daemon logging errors reported none |\n| \"point Capsem at a temp root\" | every fixture, by hand | `CAPSEM_RUN_DIR`\u002F`CAPSEM_ASSETS_DIR` outrank `CAPSEM_HOME`, so setting the home alone read the caller's directories: green locally, broken in the gate |\n\nBoth look locally correct in every copy. That is what makes them expensive:\nnothing is visibly wrong at any one site, and a fix applied to one never\nreaches the others.\n\n**Established wrappers -- use them, do not re-derive:**\n\n| Need | Call | Never |\n|---|---|---|\n| Host log content | `telemetry::read_log_tail(stream, max)` | `File::open`\u002F`fs::read` on a `*.log` path |\n| Session console\u002Ftranscript | `session::read_session_serial_log` \u002F `read_session_transcript` | Reopening a root-level log path or resolving worker-writable parents by path |\n| Enumerate a stream | `telemetry::log_stream_files(stream)` | `read_dir` + name filtering |\n| Redirect paths in a fixture | `paths::CapsemPathsGuard::redirect(root)` | `set_var(\"CAPSEM_HOME\", ...)` |\n| Any `~\u002F.capsem\u002F...` path | a `paths::` helper | `home.join(\".capsem\")` |\n| Checkpoint marker | `paths::checkpoint_complete_path(cp)` | rebuilding `\u003Cname>.complete` |\n\n`build_system\u002Ftests\u002Fgate\u002Ftest_path_and_log_wrappers_are_mandatory.py` enforces the first three.\n\n**When unifying, take the better implementation, not the first one.**\n`support_bundle`'s tail reader seeked to each file's end; the shared one read\nwhole files. Guest console output is guest-controlled, so read-whole let a\nchatty VM decide how much memory `capsem support` allocated. The shared\nfunction now seeks.\n\n**Two copies that agree today are still a bug.** `checkpoint_complete_path`\nexisted in capsem-process and capsem-service, identical except that one\nhardcoded the fallback name and the other used a constant. Changing that\nconstant would have left the process writing a resume marker the service never\nlooked for, with nothing wrong at either site.\n\n## Lessons learned\n\n1. **Content-Encoding**: Always handle response decompression generically. Gzip compressed SSE responses caused NULL telemetry because the parser got binary garbage. Never strip Accept-Encoding as a workaround.\n\n2. **Platform type widths**: `as _` is your friend for cross-platform libc calls. Explicit casts (`as c_ulong`) will fail on the other platform.\n\n3. **Debouncer timing**: If a VM shuts down before debounced events flush, telemetry is lost. Add `sleep 1` in test commands, or use explicit flush on shutdown.\n\n4. **VirtioFS whiteouts**: Apple VZ's VirtioFS doesn't support `mknod`, so overlayfs can't use it directly as upper. The ext4 loopback workaround provides full POSIX.\n\n5. **setsid for controlling terminal**: Without `setsid`, the PTY has no foreground process group and Ctrl-C (SIGINT) is not delivered. `capsem-init` uses `setsid` to fix this.\n\n6. **serde_json::Value on LLM hot path**: Three ai_traffic struct fields (`ResponseInfo.output`, `FunctionResponse.response`, `FunctionCall.args`) used `serde_json::Value` for large payloads that were only stringified. This forced full DOM allocation on every streaming request. Fixed by removing unused fields and switching to `Box\u003Cserde_json::value::RawValue>`.\n\n7. **Prefer syscalls over subprocesses**: `std::process::Command` costs 5-30ms per spawn (fork\u002Fexec). If a syscall does the same thing, use it. Example: `cp -c -R` for APFS clonefile was 20-30ms; a direct clone syscall is \u003C1ms. `capsem_foundation::unix::fs::clone_file_into` uses `fclonefileat` on macOS and the `FICLONE` ioctl on Linux -- no subprocess. Always check if the OS provides a syscall before reaching for `Command`.\n\n7. **Blocking I\u002FO in MCP tool handlers**: Tool handlers once ran blocking I\u002FO (clonefile subprocess, walkdir, blake3) directly on tokio worker threads while holding a `tokio::sync::Mutex`, so tool calls hung from the model's perspective. Fixed by wrapping in `spawn_blocking` everywhere; see the anti-pattern section above.\n\n7. **Clone guest-writable trees through descriptors, never paths**: Everything below `session_dir\u002Fguest\u002F` is guest-controlled and may change mid-copy (an entry swapped for a symlink to a host path). Fork\u002Fcreate-from therefore go through `capsem_core::session::clone_sandbox_state`, which composes `capsem_foundation::unix::tree_clone`: descriptor-relative `O_NOFOLLOW` opens, exclusive destination creation, symlinks recreated but never followed, special files skipped, setuid\u002Fsetgid\u002Fsticky bits dropped, and a non-regular `rootfs.img` refused. File contents clone from the open descriptor via `unix::fs::clone_file_into` (shared extents, or a sparse copy when the filesystem cannot share them). Never add a path-based `std::fs::copy`\u002F`walkdir` copy of guest state. A CoW clone is metadata-only, so flush `rootfs.img` before cloning (`flush_system_overlay`) or the clone captures stale data.\n\n8. **Platform-gate all macOS-only APIs**: Any code using macOS-only symbols (`libc::clonefile`, Apple framework bindings, etc.) must be wrapped in `#[cfg(target_os = \"macos\")]` -- both the struct\u002Fimpl and the tests. The Linux app build (Tauri deb\u002FAppImage) compiles the full workspace; ungated macOS symbols cause `cannot find function` errors on Linux CI. This burned v0.14.7: a clone helper used `libc::clonefile` without a cfg gate. Rule: when adding platform-specific code, gate the definition, the impl, and the tests.\n\n9. **Readiness gates must reflect actual state**: `handle_ipc_connection` responded to Ping with Pong the moment the UDS socket existed -- before vsock connections, boot handshake, or command handler spawn. `wait_for_vm_ready` treated Pong as \"ready\", so exec commands were sent to a process that couldn't handle them yet, blocking silently in a channel until `setup_vsock` finished. Tests masked this with `wait_exec_ready()` client-side retry loops, creating a double-wait: 30 client retries x 30s server wait each. Fix: `Arc\u003CAtomicBool>` (`vm_ready`) gated by `setup_vsock` after BootReady; IPC handler only sends Pong when the flag is set. One wait, one place -- the server waits; the client calls once. When adding any new IPC readiness check, never respond \"ready\" based on socket existence alone; check actual process state via a shared flag or state enum.\n\n10. **VirtioFS and FSEvents**: Apple VZ VirtioFS guest writes bypass macOS FSEvents (the kernel's file notification subsystem), so `notify::RecommendedWatcher` silently drops guest-originated events and a host directory shared into a guest has to be polled. Do **not** reach for `notify::poll::PollWatcher` to do it: it walks with `follow_links(true)` hardcoded (`notify-7.0.0\u002Fsrc\u002Fpoll.rs`) and its `configure` is a no-op, so one guest `ln -s \u002F workspace\u002Fevil` turns every scan into a walk of the host's entire filesystem. Own the loop instead, as `crates\u002Fcapsem-core\u002Fsrc\u002Ffs_monitor.rs` does: a `walkdir` walk with `follow_links(false)`, a snapshot of `(kind, len, mtime, ctime, ino)` per entry, and the difference between two walks as the events. Owning it also lets the cadence track the measured scan cost rather than a constant, and lets a symlink be recorded as a symlink instead of being descended.\n\n11. **Process sandbox: env_clear() on child spawn**: When spawning a child process (e.g., capsem-process from service), always call `env_clear()` then re-add only the minimal env vars needed (`HOME`, `PATH`, `USER`, `TMPDIR`, `RUST_LOG`). The service's shell environment may contain API keys, tokens, or secrets that the child process has no business seeing. The guest's `--env` args are a separate injection path and are already validated.\n\n12. **UDS socket permissions must be 0600**: After `UnixListener::bind()`, immediately `set_permissions(..., 0o600)`. The default umask leaves sockets world-accessible, meaning any local user can connect to a VM's IPC or terminal WebSocket with no auth. The gateway token file already does this; per-VM sockets must match.\n\n13. **Never process::exit() on guest-controlled I\u002FO**: A guest can close a vsock fd at any time. If the host handler calls `process::exit(1)` on read error, the guest has an unconditional DoS. Use `break` to exit the read loop and let the process shut down through normal channels.\n\n14. **Sensitive logs cross a worker boundary**: Terminal and serial files contain raw user data. Use `unix::fs` single-link, no-follow file helpers and bound reads; a confined writer can still plant a redirect at its own log path. Below worker-writable directories, anchor access through `ContainedDir` descriptors. Prepare `session::prepare_session_logs` under the exclusive owner lock before confinement: it retains `owner\u002Flogs\u002F` and migrates legacy generations without overwriting conflicts. Hypervisor console and terminal output share one `SharedLogWriter` and rotation counter; never open an independent appender. Writers retain directory descriptors across rotation, which needs directory authority rather than exact-file grants. Keep session root and ledger outside that grant. Create files with mode 0600 and repair permissions before confinement or through the authorized broker; confined writers must not call `set_permissions`. Session readers use the shared console\u002Ftranscript APIs, falling back only for a missing layout. Support exports redact recognized credential bytes even in mixed binary\u002Ftext lines, preserving unrelated bytes without a UTF-8 bypass. The PTY, telemetry, support-export and actual owner-sandbox regressions prove retention and malicious redirects.\n\n15. **VirtioFS share boundary -- only guest\u002F subtree**: The VirtioFS share must point at `session_dir\u002Fguest\u002F`, not `session_dir` itself. Host-only state (`session.db`, `owner\u002Flogs\u002F`, `owner\u002Fcheckpoint.vzsave`, `system\u002Frootfs.img`) stays outside the share. The system disk lives in the host-only `system\u002F` directory; never restore a compatibility link into guest storage. Put guest-visible content under `guest\u002F`. Use `capsem_core::guest_share_dir(session_dir)` to get the share root.\n\n16. **VM route id is not the display name**: `SandboxInfo.id`, route path ids,\n`InstanceInfo.id`, DB handle keys, session directory basenames, and\n`CAPSEM_VM_ID` must be the opaque VM\u002Fsession id. Persistent registry `name`\nvalues such as `co-work1` or `code-vm1` are display aliases only. User surfaces\nmay accept names, but they must translate to id before calling `\u002Fvms\u002F{id}\u002F...`.\nDo not use `registry.get(&id)` in route code unless the route id has first been\nresolved to the registry key; use the persistent identity helpers instead.\nWhen returning UI\u002FAPI payloads, preserve both `id` and `name`. Regression\ncoverage lives in `persistent_session_routes_keep_uuid_id_separate_from_display_name`,\n`resume_sandbox_requires_uuid_route_id_not_display_name`, and\n`persistent_route_identity_source_guard`.\n\n17. **Use `capsem_core::poll::poll_until` for all async polling**: All \"wait until ready\" patterns must use the shared `poll_until` utility in `capsem-core\u002Fsrc\u002Fpoll.rs`. It provides deadline-based timeout, exponential backoff, and structured tracing (attempt count, elapsed time, label). Never write ad-hoc `for _ in 0..N { sleep(X) }` or `while now \u003C deadline { sleep(fixed) }` loops -- they lack logging, use fixed intervals instead of backoff, and hardcode timeouts. For sync code (guest agent), `vsock_connect_retry` in `vsock_io.rs` has the same pattern with `eprintln` logging. Every retry loop must have a total deadline.\n\n18. **DRY wait patterns -- one wait, one place**: When a server endpoint already waits for a subprocess to become ready (e.g., `wait_for_vm_ready` in `handle_exec`), clients must not add their own retry loop on top. The test helper `wait_exec_ready` previously polled 30 times with 1s sleep, and each poll triggered a 30s server-side wait -- a 30x30s pathological cascade. After fixing the readiness gate (lesson 9), the client calls exec once with adequate HTTP timeout and the server handles the wait. Apply this DRY principle to any client\u002Fserver readiness pattern: decide which layer owns the wait and make others pass through.\n\n19. **Companions must not outlive their parent -- `kill_on_drop` is not enough**: `tokio::process::Command::kill_on_drop(true)` only fires when the parent's `Child` handle is dropped on graceful shutdown. Under SIGKILL\u002FOOM\u002Ftest-harness timeout\u002F pytest-xdist worker death, Drop never runs and companion processes (gateway, tray) get re-parented to PID 1 and survive forever. Every `just test -n 4` run leaked a fresh batch of orphans; accumulated orphans caused VM-ready poll spins, UDS-port collisions, and the suspend\u002Fresume regression. Defense in depth is mandatory for any spawned companion process, enforced on the COMPANION side so the parent can't get it wrong:\n    - Pass `--parent-pid \u003Cspawner_pid>` when spawning.\n    - Companion calls `capsem_guard::install(parent_pid, lock_path)?` at startup:\n      - Refuses to run if parent PID is missing, dead, or not our actual `getppid()` (`parent_is_expected`). Exit 0 — standalone launches become silent no-ops.\n      - Acquires an `flock(2)` singleton at `lock_path` (O_CLOEXEC opened atomically; process-local registry covers the brief fork-to-exec window where the flock fd can be inherited). Second instance exits 0.\n      - Spawns a 100ms-interval watcher thread that calls `std::process::exit(0)` the moment `getppid()` no longer equals the declared parent PID. `getppid()` is immune to zombie state and flips to 1 on re-parenting, which is the reliable signal across SIGKILL, SIGSEGV, and OOM.\n      - The mandatory terminator runs before any best-effort tracing. Parent death commonly closes a companion's stdout\u002Fstderr pipes; logging to that dead sink can panic the watcher thread, so observability must never stand between detecting reparenting and exiting.\n    - Lock paths: tray is SYSTEM-WIDE (`$HOME\u002F.capsem\u002Frun\u002Ftray.lock`) because the macOS menu bar is a shared global resource; gateway is per-run_dir because each test's gateway bridges a distinct UDS. Regression tests in `tests\u002Fcapsem-service\u002Ftest_companion_lifecycle.py` cover: refuse-standalone (no parent \u002F wrong parent), singleton (double spawn, 20-way hammer), and die-with-parent (SIGKILL the parent, companion exits within 5s). When adding any new companion process, wire it through `capsem-guard` — don't invent a new pattern.\n\n20. **Retry loops must classify errors, not time-bound a blanket wait**: When waiting for a resource to come up, the retry closure must distinguish *retryable* errors from *permanent* ones, and the classification depends on the caller's context, not the error itself. Identical `NotFound` \u002F `ConnectionRefused` errors mean \"service is down, give up\" on an initial probe but \"socket not bound yet, keep waiting\" one call later in the post-launch retry. Pattern:\n    - **Use `capsem_core::poll::poll_until`, not a hand-rolled backoff loop.** The poll primitive already gives you deadline, exponential backoff, per-attempt logging (label + elapsed + attempts), and a typed `TimedOut` error. Every new retry site that reinvents these is a future bug -- the `capsem doctor` \"Service manager started capsem but socket not ready\" bug existed only because `UdsClient::connect_with_timeout` hand-rolled its own loop and fast-failed on `ENOENT` before the just-started service had bound its socket.\n    - **Inside the `poll_until` closure:** return `None` on retryable errors (`poll_until` keeps polling), return `Some(Err(...))` on permanent errors (`poll_until` exits immediately).\n    - **Thread a small enum, not a `patient: bool`**, so every call site documents intent: `ConnectMode::FailFast` vs `ConnectMode::AwaitStartup`, `ProbeMode::Expected` vs `ProbeMode::MustBeRunning`. `crates\u002Fcapsem\u002Fsrc\u002Fclient.rs::UdsClient::connect_with_timeout` is the canonical example in the tree.\n    - **Don't `.map_err(|_| anyhow!(...))` on the timeout branch.** You erase the inner cause. Chain with `Context` so the root error lives in the error chain and `{err:#}` prints both the summary and the underlying io::Error kind.\n\n## Async reference\n\nRead `references\u002Frust-async-patterns.md` for comprehensive tokio patterns (tasks, channels, streams, error handling). From the community (6.4K installs).\n",{},"main","d357170bb677125c80cebed720e62bf47bf083ad","skills\u002Fdev-rust-patterns",26,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem","https:\u002F\u002Fgithub.com\u002Fgoogle","https:\u002F\u002Fopensource.google\u002F","Google ❤️ Open Source","2026-11-14 00:49:59",{"source":9,"skillName":5,"commands":47,"prompt":57,"zipAvailable":58},[48,51,54],{"tool":49,"command":50},"npx","npx skills add google\u002Fcapsem --skill dev-rust-patterns",{"tool":52,"command":53},"bunx","bunx skills add google\u002Fcapsem --skill dev-rust-patterns",{"tool":55,"command":56},"pnpm","pnpm dlx skills add google\u002Fcapsem --skill dev-rust-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fdev-rust-patterns\u002FSKILL.md",true,[60,66,70],{"path":61,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":64,"sourceHtmlUrl":65},"references\u002Fdata-path-performance.md","REFERENCE","参考文档",5016,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fdev-rust-patterns\u002Freferences\u002Fdata-path-performance.md",{"path":67,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":68,"sourceHtmlUrl":69},"references\u002Fguest-memory-performance.md",4663,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fdev-rust-patterns\u002Freferences\u002Fguest-memory-performance.md",{"path":71,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":72,"sourceHtmlUrl":73},"references\u002Frust-async-patterns.md",12348,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fdev-rust-patterns\u002Freferences\u002Frust-async-patterns.md",[75,92,108,123,135,147],{"skillNo":76,"name":77,"nameZh":78,"description":79,"descriptionZh":80,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":7,"sourceHtmlUrl":81,"categories":82,"keywords":89,"publishedAt":32},"01M699558T2T4DJMBN08ZCQ79K","use-capsem","Capsem 虚拟机任务执行","Run tasks in Capsem VMs through MCP. Use when an agent needs isolated execution, file analysis, or reports returned to the host.","通过 MCP 在 Capsem 虚拟机中运行任务。在智能体需要隔离执行、文件分析，或将报告返回到主机时使用。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fuse-capsem\u002FSKILL.md",[83,86],{"categoryNo":84,"categoryName":85,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BRN0DBCRG4XGJMB6QQEP11","编码任务委派",{"categoryNo":87,"categoryName":88,"taxonomyType":22,"taxonomyTypeDesc":23},"01M8BRZZF9D7PVFN5MXSPWWD61","AI 工程师",[90,91],"use capsem","MCP",{"skillNo":93,"name":94,"nameZh":95,"description":96,"descriptionZh":97,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":7,"sourceHtmlUrl":98,"categories":99,"keywords":106,"publishedAt":32},"01M69953Z1CSVQ4N07QX529CZY","site-marketing","营销网站内容维护","The marketing website, capsem.org. Use when editing copy, adding sections, or changing the site theme.","营销网站 capsem.org。在编辑文案、添加板块或更改网站主题时使用。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fsite-marketing\u002FSKILL.md",[100,103],{"categoryNo":101,"categoryName":102,"taxonomyType":22,"taxonomyTypeDesc":23},"01M8BQGD6C0J544QTJ9R38Z7ZG","营销专员",{"categoryNo":104,"categoryName":105,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BQV98WRP4APE9VKKKKJ6FV","社交媒体与内容平台管理",[107],"site marketing",{"skillNo":109,"name":110,"nameZh":111,"description":112,"descriptionZh":113,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":7,"sourceHtmlUrl":114,"categories":115,"keywords":120,"publishedAt":32},"01M69952B33KBBV37N8QTC4191","site-infra","文档站基础设施维护","The documentation site, docs.capsem.org. Use for user-directed Diátaxis documentation and Astro Starlight changes.","文档站点 docs.capsem.org。用于面向用户的 Diátaxis 文档和 Astro Starlight 相关更改。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fsite-infra\u002FSKILL.md",[116,119],{"categoryNo":117,"categoryName":118,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BQ6TK1MPB82068236GSXDE","文档处理",{"categoryNo":20,"categoryName":21,"taxonomyType":22,"taxonomyTypeDesc":23},[121,122],"site infra","docs",{"skillNo":124,"name":125,"nameZh":126,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":7,"sourceHtmlUrl":127,"categories":128,"keywords":133,"publishedAt":32},"01M69950YKCZKCDB98JDQNBBRJ","site-architecture","站点架构设计","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fsite-architecture\u002FSKILL.md",[129,132],{"categoryNo":130,"categoryName":131,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BQ6TKQDF2K4KQS863Q79P4","开发参考",{"categoryNo":20,"categoryName":21,"taxonomyType":22,"taxonomyTypeDesc":23},[134],"site architecture",{"skillNo":136,"name":137,"nameZh":138,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":7,"sourceHtmlUrl":139,"categories":140,"keywords":145,"publishedAt":32},"01M6994Z61JWZ0G2YRJTWFH933","release-process","版本发布流程","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Frelease-process\u002FSKILL.md",[141,142],{"categoryNo":20,"categoryName":21,"taxonomyType":22,"taxonomyTypeDesc":23},{"categoryNo":143,"categoryName":144,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BQNXPY1AV6BSR5VKHDMWRH","部署与发布管理",[146],"release process",{"skillNo":148,"name":149,"nameZh":150,"description":151,"descriptionZh":152,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":7,"sourceHtmlUrl":153,"categories":154,"keywords":159,"publishedAt":32},"01M6994XKHADM6FBTYTAPG7FYC","meta-skill-creation","智能体技能创建与优化","Create, improve, and evaluate skills. Use when writing a new skill, editing an existing one, or tuning a description for better triggering.","创建、改进和评估技能。在编写新技能、编辑现有技能或调整 description 以优化触发效果时使用。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fcapsem\u002Fblob\u002Fmain\u002Fskills\u002Fmeta-skill-creation\u002FSKILL.md",[155,158],{"categoryNo":156,"categoryName":157,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BRN0CV1NMDZ5TEJX1GVM29","插件与技能管理",{"categoryNo":87,"categoryName":88,"taxonomyType":22,"taxonomyTypeDesc":23},[160,161],"meta skill creation","writing"]