agentleFS
tinylabscomtinylabscom/mvm/AGENTS.md

mvm

AGENTS.md51 starsChanged 17 days agoApache-2.0View on GitHub

Backing: shipped-source Validation: check-all This file is the short, always-applicable rule index loaded into every session. The fuller AI-assisted issue-to-PR playbook lives in public/src/content/docs/contributing/ai-coding-workflow.md; human environment setup in public/src/content/docs/contributing/development.md. If you change anything this file describes, update this file in the same change. For security-sensitive runtime, policy, package, backend, networking, or lifecycle changes, read .agents/skills/secure-execution-review/SKILL.md before designing the change. This file's invariants apply even to agents that cannot invoke skills directly. Build secure execution infrastructure, not a product defined solely…

  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.

    Of the AGENTS.md files we read, the 33,398 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository3 other files it gives its agents.

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

47 rules. About 1 is common, 21 are distinctive, and 25 are very specific to this project.

  • ≈1

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈21

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 25

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Start authoring with one editable workload file and compose smaller files when reuse warrants it.

    line 49
  2. Distinctive:

    Artifacts stay immutable and verifiable: Keep published signed pack and wire meanings intact unless an approved versioned migration changes …

    line 56
  3. Very specific:

    Prefer a signed target index with digest-pinned, self-contained .mvmpkg variants over making every small device download every platform's …

    line 58
  4. Distinctive:

    Keep the change small and complete, reuse the source of truth, and prove changed observable behavior and failure paths.

    line 88
  5. Very specific:

    Task context has one route: Start from the GitHub issue, read only the ADRs/contracts it links, then use Trail for implementation discovery.

    line 95
  6. Very specific:

    Builder VM requirement: All Nix builds/evals, Firecracker operations, mvmctl runtime commands (anything that boots, talks to, or manages …

    line 103
  7. Distinctive:

    Run the requested test from its worktree:

    line 152
  8. Very specific:

    Put artifacts that must be downloaded in $MVM_GCP_KVM_RESULTS_DIR.

    line 165
  9. Distinctive:

    Before every real invocation, obtain explicit operator authorization for both the billable VM and transfer of the tracked-file checkout …

    line 173
  10. Very specific:

    Do not pass --keep-instance to either entry point unless the operator explicitly requests an interactive diagnostic host.

    line 187
  11. Very specific:

    The main checkout stays on synchronized main: Verify at the start and end of every task: clean, on main, synced with origin/main (git …

    line 203
  12. Distinctive:

    No assistant or tool attribution in pull requests: Never name an AI assistant, coding agent, model, or tool (Claude Code, Codex, Kimi, Qwen …

    line 217
  13. Distinctive:

    Every change — code, docs, dependency bumps, refactors, bug fixes — is developed in a git worktree.

    line 224
  14. Distinctive:

    No task is complete without all of:

    line 296
  15. Distinctive:

    Tests first: Write or update tests covering the new/changed behavior before marking a task done.

    line 298
  16. Very specific:

    All tests green: Run cargo nextest run --workspace and cargo test --workspace --doc (nextest skips doctests) and confirm zero failures.

    line 299
  17. Very specific:

    Zero clippy warnings/errors: Run cargo clippy --workspace -- -D warnings and fix all findings before calling a feature done.

    line 300
  18. Very specific:

    Do not create or update a shared sprint, refactor, delivery, or progress dashboard in specs/.

    line 307
  19. Very specific:

    Verify completion before checking each item.

    line 312
  20. Very specific:

    Use Refs #123 for partial work.

    line 314
  21. Distinctive:

    State the lifecycle for risky changes: when a change touches ownership, cancellation, cleanup or rollback, unsafe/FFI, or a panic path, the …

    line 322
  22. Very specific:

    If a function can fail, test that it fails correctly (Err, not panic).

    line 340
  23. Very specific:

    Never use sleep N && <check> as a wait strategy.

    line 370
  24. Very specific:

    Run the full workspace suite once before declaring the task done, not after each edit.

    line 386
  25. Distinctive:

    After roughly 50 tool calls without reaching the session goal, stop and re-plan.

    line 398
  26. Distinctive:

    Before launching a subagent, declare its exact workspace paths, environment setup, read-only or write scope and tools, and a …

    line 410
  27. Distinctive:

    If any pre-flight item is unknown, do not launch it.

    line 412
  28. Distinctive:

    Every change is evaluated through a security lens:

    line 416
  29. Very specific:

    Never log, store, or expose secrets/tokens/keys/credentials/user data in plaintext — in code, logs, config, or error messages.

    line 418
  30. Common:

    No hardcoded secrets — environment, secure config, or runtime injection only.

    line 426
  31. Distinctive:

    Consider attack surface in every feature: listeners, file permissions, IPC channels, CLI commands.

    line 427
  32. Very specific:

    Run cargo clippy --workspace -- -D warnings after every code change.

    line 434
  33. Very specific:

    Never .unwrap() in production code — use .expect("descriptive message") so a panic explains what failed and where.

    line 451
  34. Very specific:

    Never cite a plan, ADR, PR, sprint, or workstream in a code comment — process artifacts belong in specs, commit messages, and PR …

    line 457
  35. Distinctive:

    Write as little code as possible: Prefer the fewest lines that correctly solve the task: reuse existing code, delete unnecessary code, and …

    line 467
  36. Distinctive:

    Never reimplement existing functionality.

    line 476
  37. Distinctive:

    Follow the existing pattern — match surrounding naming, idiom, and layout.

    line 502
  38. Very specific:

    Async (Tokio): no blocking calls in async context (tokio::fs, offload CPU work with spawn_blocking/rayon).

    line 549
  39. Very specific:

    Do not ship TODO, TBD, placeholder values, pseudo-code, or stub implementations where a concrete answer is required.

    line 555
  40. Distinctive:

    Keep guides aligned with shipped behavior, not aspirational features.

    line 567
  41. Very specific:

    Never put agent-created scratch or intermediate files anywhere in a worktree, including gitignored paths.

    line 570
  42. Distinctive:

    Never immediately repeat an identical failed command.

    line 576
  43. Very specific:

    Run trail map first — a token-budgeted orientation (dir clusters, hubs, hotspots), no LLM, no key.

    line 594
  44. Very specific:

    Run trail ask "<your question>" --source → ranked nodes with the relevant code spans inlined (each hit's ≤8-line crux by default.

    line 597
  45. Very specific:

    Add --direction out for what it calls, or --depth N to walk transitively for the full blast radius.

    line 609
  46. Distinctive:

    If a returned span is truncated ("+N more lines"), open the file at that exact range before finalizing.

    line 617
  47. Very specific:

    After big code changes, refresh the graph with trail build (deterministic, no API key, $0).

    line 622

≈ “Common” is an estimate: at least 1 in 5 of the 43,423 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

Agent Working Agreement

Backing: shipped-source Validation: check-all

This file is the short, always-applicable rule index loaded into every session. The fuller AI-assisted issue-to-PR playbook lives in public/src/content/docs/contributing/ai-coding-workflow.md; human environment setup in public/src/content/docs/contributing/development.md. If you change anything this file describes, update this file in the same change.

For security-sensitive runtime, policy, package, backend, networking, or lifecycle changes, read .agents/skills/secure-execution-review/SKILL.md before designing the change. This file's invariants apply even to agents that cannot invoke skills directly.

Product and design boundaries

Build secure execution infrastructure, not a product defined solely by microVMs. This repository owns the canonical local workload, signed-plan, policy, mailbox, host-service, guest-runtime, and backend contracts. Local execution must work without mvmd; mvmd adds fleet coordination and cross-host transport, not a second local authority. mvm-images owns the Linux image layer, while mvm-packs owns official pack publication. A new target such as an embedded device, Wasm, or Windows must use the common contracts where applicable and advertise only the isolation and capabilities it actually enforces. The current backend claims and their witnesses remain in ADR-001; the product direction here is not evidence that an unshipped target works.

  • Security claims are conditional. Name the adversary, data state, backend, required trust, enforced boundary, and witness before claiming a guarantee. Protect against a compromised workload on a trusted host; do not promise confidentiality from a compromised active host without an independently qualified hardware boundary. Destroying the last recoverable key may protect encrypted data at rest, but cannot undo plaintext exposure or prove physical erasure. Hardware assurance is optional unless signed policy requires it.
  • One admitted path. Complete required launch preflight and establish isolation and signed-plan enforcement before boot. An isolated guest may initialize while capability-specific checks finish, but no readiness claim, secret use, writable volume, egress, or mailbox authority precedes its applicable admission check. A failed required check refuses or stops execution; optional monitoring is not a substitute for admission. Workload microVMs have no guest NIC and no SSH. The host mediates authorized effects and owns the canonical local mailbox path, even without mvmd.
  • Compose without widening. A pack or application requests permissions; it does not grant them. Host, organization, user, pack, application, and invocation limits must be resolved by the existing policy owner into one effective, explainable policy; a deny or ceiling cannot be overridden by a later layer. Start authoring with one editable workload file and compose smaller files when reuse warrants it. Do not introduce another policy or network data path.
  • Capabilities are contracts. Reuse the existing backend traits for real variation. An unsupported requested guarantee fails before execution; never return success from a stub or silently downgrade to another backend. A target without durable mailbox storage may use an authorized durable provider, but cannot acknowledge a message as durable before that provider commits it.
  • Artifacts stay immutable and verifiable. Keep published signed pack and wire meanings intact unless an approved versioned migration changes them. Prefer a signed target index with digest-pinned, self-contained .mvmpkg variants over making every small device download every platform's assets. A locally signed development build never gains official publisher authority. Rebuild from declared inputs; reuse verified bytes, never cached authorization. A development watch session may build alongside the running workload and automatically cut over only after the candidate passes verification, admission, and readiness. Preserve accepted, still-authorized mailbox messages and keep the old workload on candidate failure unless its enforcement is no longer trustworthy; production rollout has its own policy. Do not claim this workflow is shipped without a live witness on the named backend.
  • Offline is bounded. Retry lost coordinator connections with bounded exponential backoff and jitter; retries cannot extend a signed lease. Only already-authorized operations continue before expiry. Managed workloads stop at expiry by default; an explicitly authorized alternative may allow isolated computation without external effects. The host controller must remain able to reconnect and re-admit under a fresh epoch. Choose finite lease durations and organization ceilings from operational evidence, not an invented constant.
  • Speed is measured end to end. Preserve the cold <300 ms and warm <50 ms launch requirements, including admission; do not move required checks outside the measured boundary or weaken them for a benchmark. Measure deterministic image construction, first-use preparation, launch, and safe replacement separately. Design for 1,000 concurrent workloads per suitably provisioned host with bounded memory, threads, queues, idle CPU, and backpressure. Treat one million handwritten, non-test production source lines per repository as a preferred ceiling, excluding generated and vendored code; never compress readable code or remove security coverage to meet it.
  • Review the lifecycle you touch. For launch, build/cutover, mailbox, lease/reconnect, containment, and pack admission, identify state transitions, their owner, durable evidence, deadlines, cancellation, and crash recovery. Keep the change small and complete, reuse the source of truth, and prove changed observable behavior and failure paths. Do not cite a planned feature as shipped, name competitors in new prose or filenames, or attribute work to an assistant in commits, PRs, or documentation.

Documentation and editing hygiene

  • Task context has one route. Start from the GitHub issue, read only the ADRs/contracts it links, then use Trail for implementation discovery. Never recursively read specs/ or treat a legacy plan as current work.
  • Placeholders, docs that must move with behavior, and scratch files are covered under "No placeholders" and "Documentation and scratch files" below.

Execution boundaries

Builder VM requirement. All Nix builds/evals, Firecracker operations, mvmctl runtime commands (anything that boots, talks to, or manages microVMs), and Linux-specific syscalls MUST run inside the project builder VM — never a Lima VM; do not use limactl for this repo. The builder VM is the Linux execution boundary.

Builder VM images are treated as published artifacts produced by the mvm-images repository and are downloaded and verified by default. Building the builder VM from a local mvm-images checkout is a contributor-only, opt-in path and is not performed automatically. Operator-facing knobs:

  • To opt into a local builder-image build for a single invocation, set MVM_IMAGES_DIR to an mvm-images checkout and set MVM_ALLOW_LOCAL_BUILDER_BUILD=1 in the same environment. Without MVM_ALLOW_LOCAL_BUILDER_BUILD present, mvmctl will prefer the published builder image even when an mvm-images checkout is available locally.
  • MVM_BOOT_IMAGE continues to accept build / fetch values, but a build request without MVM_ALLOW_LOCAL_BUILDER_BUILD is refused rather than silently falling back.

Image boundary. The signed image set from mvm-images is the Linux layer: the builder image, kernels, base workload root filesystems and Stage 0 seeds (#4100, ADR-054). mvm-images' source no longer has an mvm flake input. The pinned published set predates that and still lists a runtime overlay, SDK sidecars and an initramfs, which mvmctl reads as retired roles and never requires. The guest runtime ships as a signed asset with each mvmctl release (a source build makes the archive from this tree), and mvmctl assembles the overlay, initramfs and sidecars from it. Do not add guest-runtime work to mvm-images.

Owner-approved exceptions (unchanged):

  • Native macOS HVF live lifecycle tests and teardown benchmarks — explicit HVF test/benchmark commands, because the Linux builder VM cannot provide Hypervisor.framework. All other runtime commands still require the builder VM.
  • mvmctl machine run --hypervisor wasm (or any explicit wasm backend target) — runs a wasm32-wasip1 module under host wasmtime; no KVM, no Firecracker/jailer/seccomp/netns tooling. May run on the macOS host.

Cargo defaults to the macOS host. cargo test / check / build run on the host so worktrees do not deadlock on shared builder state. Tests needing Linux (vsock, jailer/seccomp, dm-verity, network namespaces, /dev/kvm, /proc/net) are gated #[cfg(target_os = "linux")] and only those sub-targets run inside the builder VM. mvmctl via cargo run (build, machine run, machine stop, machine logs, machine ls) runs inside the builder VM (explicit wasm target excepted).

Disposable GCP KVM test host. Linux/KVM E2E tests that cannot run on the builder VM or GitHub-hosted runners have one repository-owned remote lifecycle. Run the requested test from its worktree:

just e2e gcp-kvm just e2e live-ci

The command creates an Intel C3 Spot VM with nested KVM, uploads only files tracked by git from the current worktree, prepares the pinned Rust/Zig/Firecracker toolchain, runs the exact argument vector after gcp-kvm, downloads a result archive under the printed /tmp path, and deletes the outer VM on success or failure. Compute Engine also deletes it after a two-hour maximum runtime if the local runner disappears before its cleanup trap can run. Put artifacts that must be downloaded in $MVM_GCP_KVM_RESULTS_DIR. Use the direct scripts/run-gcp-kvm-test.sh [options] -- PROGRAM [ARG ...] entry point for project, zone, machine, result-directory, dry-run, or diagnostic options.

This host is a test/dev-tier KVM provider only. Never use it for Nix builds or evals, ordinary compilation, or work the builder VM can perform. The VM has no Google service account or OAuth scopes and refuses project-wide SSH keys. Before every real invocation, obtain explicit operator authorization for both the billable VM and transfer of the tracked-file checkout unless that exact run was already authorized.

Issue #3655's destructive witness is the pinned preset:

just e2e cve-3655-gcp --dry-run
just e2e cve-3655-gcp

It delegates host ownership to the generic runner and supplies only the pinned CVE bootstrap and witness command. Do not substitute an ad-hoc cloud VM.

Do not pass --keep-instance to either entry point unless the operator explicitly requests an interactive diagnostic host. When requested, the runner prints exact gcloud compute ssh and gcloud compute instances delete commands. Run the printed delete command as soon as diagnosis ends and verify the instance is gone. If automatic cleanup reports a failure, use that same printed delete command immediately; never leave a retained or uncertain instance billable.

Git: one operator, one main

Git runs only from the main mvm/ checkout — never from inside a worktree directory, never from inside the builder VM. Act on a worktree's branch with git -C /path/to/.worktrees/mvm-<slug> <cmd> from the main checkout. This serializes the shared .git/objects, packed refs, and hooks and eliminates the contention that has caused lost work. Cargo/nix/firecracker/mvmctl run from each worktree's own directory; only git is centralized.

The main checkout stays on synchronized main. Verify at the start and end of every task: clean, on main, synced with origin/main (git fetch origin && git pull --ff-only origin main). Never do change work on a topic branch there; if one lands there accidentally, preserve changes, switch back, sync, and attach the branch to a worktree. After any PR merge, sync main immediately. The only git commands targeting main are read-only (git log, git show) or routine sync.

Never commit directly to main. Main advances only via merged PRs — including docs-only and typo fixes. Reasons: parallel agents sharing .git can wipe local-only commits with routine recovery moves; the full clippy/nextest/supply-chain matrix only runs on PRs; PR history is the audit trail. Push to a branch and open a PR.

No assistant or tool attribution in pull requests. Never name an AI assistant, coding agent, model, or tool (Claude Code, Codex, Kimi, Qwen Code, etc.) in PR titles, bodies, contributor lists, acknowledgements, commit trailers, or generated-by notices; no assistant Co-authored-by trailers.

Worktree workflow for all changes

Every change — code, docs, dependency bumps, refactors, bug fixes — is developed in a git worktree. No docs-only or trivial-change exception.

cd /path/to/mvm                           # main checkout
mkdir -p ../.worktrees
branch=feat/example                        # choose feat/, fix/, docs/, or chore/
git worktree add ../.worktrees/mvm-example -b "$branch"
cd ../.worktrees/mvm-example               # code + cargo live here

Branch names: feat/<slug>, fix/<slug>, chore/<slug> (docs topics: docs/<slug>). All git work happens from the main checkout: git -C ../.worktrees/mvm-<slug> status|add|commit|push. Agents inside a worktree do not invoke git directly; a read-only git -C <main> status is acceptable. Remove the worktree after merge (git worktree remove ...).

Isolate mutable state per worktree by overriding three env vars (or just source scripts/dev-env.sh, resolved relative to the worktree root; bin/dev builds this checkout's mvmctl on the dev contributor surface and its native helpers together (so launch needs no implicit helper build), without embedding the Linux builder payload; it verifies published image-set signatures and runs with pair-isolated state; .envrc.example covers direnv users):

export MVM_HOME="$PWD/.mvm-test"
export CARGO_TARGET_DIR="$PWD/.mvm-test/target"
export CARGO_HOME="$PWD/.mvm-test/cargo"

These exports apply to commands in the current shell until it is closed or the variables are unset.

Still shared between worktrees — vary microVM names if two worktrees run microVMs concurrently: .git/objects + packed refs + hooks (the git rule above is what keeps these safe), the builder VM's /var/lib/mvm/; the Nix store (shared by design; Nix locking handles it). The builder VM itself is shared across worktrees — never fork a per-worktree VM (boot cost, duplicated tens-of-GB store, warm-cache loss).

One-time per clone: just setup hooks points core.hooksPath at .githooks/. The pre-commit hook runs cargo fmt --all (auto-restaging), scoped stable clippy -D warnings, and actionlint for workflow changes — never Nix on the host or the full test suite. Nix flake checks run in CI; local Nix evaluation and builds run only in the builder VM. CI does not currently enforce Nix formatting because the flake declares no formatter. MVM_SKIP_CLIPPY=1 bypasses the clippy pass.

The DX rule: binary development is single-repo

Developing the binaries that run inside a microVM — agent, egress client, protocol crates — happens entirely in this repository. A guest-binary-only change must never require an mvm-images checkout, edit, or release. A source build assembles the runtime overlay, the initramfs and the SDK sidecars from this checkout on the host. The image boundary in #4100 (ADR-054) makes the rule true by construction: every guest piece ships with mvmctl, and mvm-images has no mvm input to change. mvm-images is entered deliberately, only for Linux-layer work (packages, kernels, the builder image, base root filesystems), and even then this repo stays the front door (bin/dev build image-set). The acceptance test is the one-clone bootstrap: a contributor who clones only mvm and follows the quickstart never needs to know the image repository exists.

The queue-wall tripwire this rule used to carry (keep the merge-group wall under 20 minutes or re-open the repo split) assumed the merge queue builds images. Under the boundary it builds none: the lanes that still build guest pieces through mvm-images move to the pinned base set with a tree-built guest runtime under #4108, which measures the wall before and after over at least ten merge-group runs.

Definition of Done

No task is complete without all of:

  1. Tests first: Write or update tests covering the new/changed behavior before marking a task done. Unit tests for logic, integration tests for CLI and cross-crate interactions.
  2. All tests green: Run cargo nextest run --workspace and cargo test --workspace --doc (nextest skips doctests) and confirm zero failures. New tests must pass alongside all existing tests.
  3. Zero clippy warnings/errors: Run cargo clippy --workspace -- -D warnings and fix all findings before calling a feature done. Never suppress a clippy lint with #[allow(...)] — fix the underlying issue instead.
  4. Compiling workspace: Run cargo check --workspace (or full cargo test/cargo build) and fix any errors before you finish. Never leave the workspace in a non-compiling state. --all-targets is not exhaustive: it silently skips targets behind required-features (the mvm-conformance cucumber runner needs --features bdd), and on macOS it cannot compile cfg(target_os = "linux") files at all — including Linux-gated test files, which just check linux also misses because that recipe is --lib only. Changing the shape of a shared type (adding a struct field, a trait method, an enum variant) therefore needs just check gated before pushing. Skipping it costs a CI round trip: the break surfaces there as a compile error in the "Build workspace tests" job.
  5. Keep the issue authoritative: GitHub issues own work status, remaining scope, dependencies, and acceptance criteria. Every PR for issue-related work must link to each issue it addresses in its description, including partial work, and leave verification results in the PR. After merge, update the issue's checkboxes to reflect verified completion and link the merged PR. Do not create or update a shared sprint, refactor, delivery, or progress dashboard in specs/. An issue is only complete when all its checkboxes are checked, or it is deliberately closed or superseded with the reason recorded on the issue and a link to the replacement issue when superseded. Verify completion before checking each item; never check or delete unfinished items merely to permit closure. A merged PR alone does not complete an issue. Use Refs #123 for partial work; use auto-closing keywords such as Fixes or Closes only when the PR completes all remaining checklist items.
  6. Update active technical documents only when their substance changes: ADRs own durable decisions and contracts own stable interfaces. An exceptional new plan is an immutable design attachment linked to one issue, never a progress ledger. When implementation changes a durable decision, update or supersede the owning ADR. Legacy plans are frozen historical inputs and are not completion gates.
  7. State the lifecycle for risky changes: when a change touches ownership, cancellation, cleanup or rollback, unsafe/FFI, or a panic path, the PR states the state transitions and who owns each resource, and adds a test that fails before the fix. The areas already reviewed, and those not, are recorded in specs/contracts/lifecycle-review-ledger.md.

Test expectations

  • Broad BDD coverage of user-visible workflows (mvm-conformance, --features bdd); add/update scenarios when behavior changes, and keep focused unit and integration tests for lower-level logic and failure paths.
  • New types: serde roundtrip tests, default-value tests where applicable.
  • New protocol/wire code: roundtrip through mock I/O (UnixStream::pair()), error-path tests (invalid input, wrong keys, malformed data).
  • New CLI flags/commands: integration tests in tests/cli.rs (help text, argument parsing).
  • Security code: positive path, negative path (tampered/invalid rejected), and edge cases (replay, wrong key, expired session).
  • If a function can fail, test that it fails correctly (Err, not panic).

Waiting model

Pick the wait primitive from the condition being observed:

  • Owned live resources → events. Processes, child handles, sockets, pipes, eventfd, kqueue filters, pidfd: arm the observer before triggering the transition, block on the event; keep a bounded deadline, a compatibility fallback, and a final identity/state verification before cleanup.
  • Time conditions → timers. TTLs, leases, backoff, health cadence, watchdogs: monotonic clock, explicit cancellation.
  • Crash recovery / external state → reconciliation. State owned by another process, service, or a crashed predecessor has no trustworthy live event: re-read at a bounded cadence; every pass idempotent under stale/duplicated observations.
  • Durable markers are evidence, not wakeups. A file/record may be the cross-process source of truth while an owned event accelerates the foreground path; never delete or trust durable state solely because a best-effort notification fired.
  • Measure before converting compatibility polls. Boot/readiness markers and attach/recovery paths may keep bounded polling until profiling shows a user-visible cost and an ownership-safe event exists; record why a remaining poll is timer-driven, externally owned, or a recovery fallback.

An event-driven change does not imply a repo-wide async runtime — use the smallest event primitive matching the existing ownership boundary.

No sleep-polling and long operations

Never use sleep N && <check> as a wait strategy. For CI, use gh pr checks <n> --watch or a background watch. Owned processes use an armed event handle, not a sleep loop. Reconcile externally owned state only when no event source exists: at most five polls with escalating backoff, and record the event that would replace the poll.

Commands expected to exceed 60 seconds (builds, workspace tests, image builds, CI watches) run as background tasks. Wait on the task notification or handle; do not extend a foreground timeout and rerun the same command.

Scoped feedback and worktree shell

Debug with just test scoped <crate> <filter>: read the failure, make one change, and rerun that scoped test. Append --lib for a library unit test or --test <name> for one integration target, avoiding compilation of unrelated test binaries. Use an empty filter ("") to run every test in that target. Run the full workspace suite once before declaring the task done, not after each edit. Source scripts/dev-env.sh once per worktree shell and then use plain commands; do not repeat inline MVM_HOME/CARGO_TARGET_DIR/CARGO_HOME or cd prefixes. Use bin/dev for a one-off mvmctl call from an unconfigured shell. A genuinely one-command override is an exception, not the default.

Session and delegation discipline

Think once at each decision point, then act; after two reasoning turns with no action, make the tool call, ask, or write and test a hypothesis. At each plan phase boundary, record decisions, files touched, blocker, and exact next step. After roughly 50 tool calls without reaching the session goal, stop and re-plan; close finished sessions and split long multi-part efforts.

Do not end a turn with a progress report while the requested goal still has actionable work. Continue through validation, review, commit, push, PR and authorized tracker updates without asking routine permission or handing the next step back to the user. End silently when waiting on an owned background task that will notify the thread. Pause only for a genuinely unresolved product/security/design decision, required authorization for a destructive, billable or shared-branch action, unavailable credentials, or a blocker that cannot be resolved from the repository and available tools.

Before launching a subagent, declare its exact workspace paths, environment setup, read-only or write scope and tools, and a denial/missing-path fallback. If any pre-flight item is unknown, do not launch it.

Privacy & security

Every change is evaluated through a security lens:

  • Never log, store, or expose secrets/tokens/keys/credentials/user data in plaintext — in code, logs, config, or error messages.
  • Validate and sanitize all inputs at system boundaries (CLI args, config files, network data, vsock messages).
  • Least privilege everywhere; default to secure configurations (encryption on, auth required, restrictive permissions) — users opt out, never opt in.
  • Guard secrets in transit and at rest; signing, encryption, and secure channels (vsock, not plaintext TCP) for sensitive communication.
  • No hardcoded secrets — environment, secure config, or runtime injection only.
  • Consider attack surface in every feature: listeners, file permissions, IPC channels, CLI commands.
  • Security tests are mandatory for every security-relevant path (positive, negative, edge).

Clippy: zero warnings, always

Run cargo clippy --workspace -- -D warnings after every code change; the CI pre-commit hook treats warnings as errors.

  • Never suppress with #[allow(...)] — fix the underlying issue; a genuinely necessary suppression needs a comment and explicit approval.
  • #[allow(clippy::too_many_arguments)] is banned outright, everywhere. The instant a function trips it, introduce a dedicated params struct with a builder (::builder() or #[derive(Default)] + with_* setters + validated build()) and thread that value through. The only legitimate suppression is bindgen-generated FFI (crates/deps/libkrun-sys/src/sys.rs); convert any existing hand-written suppression to a builder as you touch it.
  • Fix warnings immediately; common findings: too many arguments (→ builder), redundant closures, unnecessary owned parameters, single-arm matches (→ if let), and unused imports/variables.

No unwrap() in production code

Never .unwrap() in production code — use .expect("descriptive message") so a panic explains what failed and where. unwrap() is acceptable only in test code (#[cfg(test)] modules and tests/).

No spec references in code comments

Never cite a plan, ADR, PR, sprint, or workstream in a code comment — process artifacts belong in specs, commit messages, and PR descriptions. The check-no-spec-refs-in-comments lint (a CI gate) fails the build on any such reference. Keep the reasoning, drop the citation. Spec numbers remain fine in string literals that are genuinely runtime data (error messages, audit-log fields); the lint scans comment text only. Record why-a-decision-was-made in the commit message or the owning spec, and link the code from there.

Reuse first; compose small, testable units

Write as little code as possible. Prefer the fewest lines that correctly solve the task: reuse existing code, delete unnecessary code, and avoid speculative abstractions. Do not trade readability, safety, or required tests for a lower line count.

Use the ponytail skill and, for Rust work, rust-skills. Load and follow them before implementing; if either required skill is unavailable, report that explicitly rather than silently skipping it.

Never reimplement existing functionality. Before writing anything, search for an existing helper, type, trait impl, or crate that does the job — grep the workspace, check facade re-exports, read the module the work belongs in. If a helper is almost right, extend it; don't fork a second copy. Duplicated logic drifts, doubles the test surface, and is the most common source of bugs here.

  • Use the helpers. All ~/.mvm paths go through mvm-core::config helpers (mvm_home, vm_state_dir, mvm_keys_dir, mvm_cache_dir, …) — never build them from std::env::var("HOME") + .join(...), which ignores MVM_HOME and breaks worktree isolation. Shell/VM ops go through the ShellEnvironment/BuildEnvironment traits.
  • Small, single-purpose functions you can write a focused test for; if you can't test it, split it. A helper extracted to be testable ships with tests in the same change — positive, negative, and edge paths.
  • Make illegal states unrepresentable — newtypes over bare String/u64, enums over stringly-typed flags, Option/Result over sentinels.
  • Don't over-abstract (YAGNI). Traits/builders/generics for a real second case or genuine construction complexity, not speculatively.
  • Builder pattern for multi-field construction (also kills too_many_arguments at the source).
  • Traits for behavior that varies (VmBackend, ShellEnvironment) — never a match scattered across call sites. One impl is one path, not the only path.
  • Structs over loose tuples/params; match exhaustively on owned enums — no _ => catch-alls, so new variants break the build where they must be handled.
  • Follow the existing pattern — match surrounding naming, idiom, and layout.

Dependencies: fewer is the default

Lean on fewer dependencies, always. A new crate needs a reason in the PR.

  • Prefer, in order: std, then a crate already in the closure, then a small tested helper, then a new crate. Never add a crate for a few lines.
  • Measure. State what the crate replaces and the closure before and after: cargo tree -p mvmctl -e normal,build --prefix none | sort -u | wc -l, and -p mvm-builder-guest for the guest binaries. Check what a feature pulls in with cargo tree -e features -i <crate>.
  • Default features off, enabling only what is used.
  • Removing is measured too. Record accepted and declined reductions in specs/contracts/build-dependency-decisions.md with the numbers.
  • Trust boundaries: replacing a parser, signature or cryptography crate with hand-written code to save dependencies needs a fuzz target and an owner decision first.

Rust best practices

External best-practices guide; where this file states a stricter rule (clippy, unwrap(), reuse-first), this file governs.

  • API & types: builder over many-input functions; trait for multiple behaviors; borrowed args (&str, &[T], impl AsRef<Path>), return owned only when needed; newtypes; #[must_use] where dropping is a bug; minimal visibility (pub(crate) before pub); #[non_exhaustive] on growing public shapes; derive Debug, Clone, PartialEq, Default where sensible.
  • Idioms & errors: propagate with ?; thiserror in libraries, anyhow/eyre only at app boundaries; context on errors (.with_context/.map_err); iterators over index loops; if let/let else; minimize macros — prefer functions and From/TryFrom/AsRef; &self over &mut self; Cow<'_, str> for maybe-borrowed strings; unsafe confined to small blocks each with a // SAFETY: comment; TryFrom/try_into() over lossy as; explicit checked_*/saturating_* where arithmetic can overflow; .get()/.first() over slice indexing in fallible contexts; libraries return Result rather than panicking (document deliberate panics under # Panics); OnceLock/LazyLock for real globals; RAII Drop guards for cleanup (never rely on Drop across mem::forget).
  • Dependencies & tooling: small audited dependency set (cargo audit, cargo deny, cargo machete); aggressive clippy (--all-targets --all-features; pedantic/nursery via [lints] with per-lint justification over group disables); cargo fmt --check in CI; explicit MSRV; minimal default features behind cargo features (mvm-core carries no async runtime by default).
  • Async (Tokio): no blocking calls in async context (tokio::fs, offload CPU work with spawn_blocking/rayon); bound concurrency with Semaphore / JoinSet; no repo-wide runtime for event-driven changes (see Waiting model).

No placeholders in shipped plans, code, or guidance

Do not ship TODO, TBD, placeholder values, pseudo-code, or stub implementations where a concrete answer is required. Read existing code before planning a change; compute unknown values before writing the plan, or specify the exact command, source, and verification for execution time. Operator-supplied install-time values need an explicit error, not a checked-in placeholder.

Documentation and scratch files

User-facing behavior changes update the matching docs in the same PR, including the CLI reference (public/src/content/docs/reference/cli-commands.md) for commands, flags, defaults, or environment variables. Keep guides aligned with shipped behavior, not aspirational features; do not mark work done while docs are stale. Verify the changed reference against code.

Never put agent-created scratch or intermediate files anywhere in a worktree, including gitignored paths. Use /tmp for logs, merge scratch, screenshots, and snapshots; .agent-memory/notes/ is the sole findings exception.

Retry discipline

Never immediately repeat an identical failed command. Read the full error, form a root-cause hypothesis, change one thing, then rerun a scoped command. For cargo/mvmctl one-offs, mvm_run from scripts/dev-env.sh records a failed-command fingerprint in .mvm-test/last-failed-cmd and refuses an identical retry; clear it only after diagnosis. At three failures on one task, record what failed, why, and the next single change in the failure journal before another attempt. If the same hypothesis fails twice, change strategy.

<!-- trail:start -->

Trail — repo context graph

This repo is indexed in .trail/cache/: small linked markdown nodes that explain each system and carry exact file:line spans, kept in sync with the code through git.

For ANY task here — understanding how something works, finding where code lives, or scoping a change — get context from the graph before grepping or opening source files. Re-ask freely (it's cheap) and reuse literal identifiers you already have (symbol, error string, file name) as the query. New to this repo? Run trail map first — a token-budgeted orientation (dir clusters, hubs, hotspots), no LLM, no key.

  • Run trail ask "<your question>" --source → ranked nodes with the relevant code spans inlined (each hit's ≤8-line crux by default; --full for whole definitions when the crux isn't enough). Match the tool to the task shape: for understanding or editing, the top node IS the answer — cite its covers: file:line spans and edit straight from --source. For exhaustive tasks ("every occurrence / every caller of this pattern"), ranked results are top-N, not complete — run trail grep "<literal>" instead (exhaustive over indexed files, grouped by enclosing symbol), falling back to raw grep -rn only for unindexed files.
  • trail skeleton <file> → every definition's signature + span, ~10× cheaper than reading the file; use it to skim an API surface.
  • trail callers <symbol> gives precomputed, exact edges — who calls this. Add --direction out for what it calls, or --depth N to walk transitively for the full blast radius. For structural questions, skip ranking and use this directly.
  • Or browse: .trail/cache/INDEX.md lists every node; follow the links.
  • Monorepos and folders of multiple repos rank fairly across sub-projects — hits carry [scope/] labels naming which one they're from. Narrow with trail ask "<task>" --in <scope>/ once you know where you're working.

If a returned span is truncated ("+N more lines"), open the file at that exact range before finalizing. Only open source files when a node genuinely lacks a needed detail, and then at the exact file:line the node points to — never re-read whole files.

After big code changes, refresh the graph with trail build (deterministic, no API key, $0).

<!-- trail:end -->

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.