Code style
These are isolate’s project-specific Swift conventions for the host package
(Package.swift, Sources/, tests/swift/, fuzz/) and the companion
packages (iso-proxy/, iso-egress/, iso-sandbox/). The focus is on using the type
system to eliminate error states, not on formatting, which swift format
owns. The conventions and design lenses in the shared
review workflow enforce these; the
architecture doc shows where the patterns already live.
Apply these patterns when they pay for themselves; skip them when a primitive is genuinely fine. A type system that fights the reader is worse than one that lets a bug through.
Toolchain and formatting
-
Swift 6.4 toolchain, Swift 6 language mode (
swiftLanguageModes: [.v6]), strict concurrency, the pinned Xcode toolchain, macOS 27 deployment target. -
Strict memory safety is an error (the
strictMemorySafetysetting declared in the root,iso-policy,iso-proxyandiso-egressmanifests) inIsoCore,IsoConfiguration,IsoSecrets,IsoFuzzHarnesses,IsoPolicy,IsoGitIndex,IsoProxyCore,IsoProxyTransport,IsoProxy,IsoEgressCoreandIsoEgress: the shared core, configuration, secret-store and policy code (and the fuzz harnesses that drive it), and the proxy and egress companions that relay guest traffic. Keepunsafeacknowledgments on the smallest audited C/Foundation call, with the buffer bounds and pointer lifetime documented. Mark a type@safeonly when it owns its raw pointer and lends it out solely within a scoped call, and say why in its doc comment (ResolvedAddressesiniso-egress). A new shipped target iniso-policy,iso-proxyoriso-egressgets the setting too; test, test-support and benchmark targets do not. A new root target follows its layer: on for core and configuration code, off for host, CLI and secrets. -
Commit every
Package.resolved; build and test with--force-resolved-versionsso an unexpected resolution change fails. Add a dependency only with a reviewed reason; the host depends only on Swift Argument Parser and swift-crypto (CryptoExtras, for scrypt). -
swift format lint --strictmust be clean for every package:swift format lint --strict -r Package.swift Sources tests/swift fuzz/Targets fuzz/Entrypoints swift format lint --recursive --strict iso-proxy/Package.swift iso-proxy/Sources iso-proxy/Tests swift format lint --recursive --strict iso-egress/Package.swift iso-egress/Sources iso-egress/Tests swift format lint --recursive --strict iso-sandbox/Package.swift iso-sandbox/Sources iso-sandbox/Tests -
Tests use Swift Testing (
import Testing,@Test,#expect/#require). -
Keep module boundaries:
IsoCorehas no subprocess or network side effects, and its only filesystem mutation is the shared state-write primitives (AtomicFile,FileLock);IsoConfigurationhas no subprocesses and no TOML or configuration-provider dependency; side effects live inIsoHost;IsoCLIstays a thin layer of parsing, dispatch and presentation.
Lean on the type system before lean on validation
The default move when you see a bug is to add a runtime check. The better move is usually to change a type so the bug cannot be expressed. Before writing a check or throwing an error, ask: can the function signature make this case unreachable?
- Parse, don’t validate. A function that takes a
Stringand returns anInstanceName(or throws) is better than one that takes a validatedStringby convention. Convert untrusted input — CLI arguments, configuration, runtime and guest output, registry responses — into strong types at the boundary and pass the strong type inward.ConfigDecodingdoes this for the whole configuration, soConfigValidationonly checks environmental facts;RuntimeProtocoldoes it foriso-sandboxoutput. - Smart constructors. When an invariant can’t be expressed structurally,
keep the stored property
letand expose only a validating initializer or static factory that throwsValidationError. The invariant then holds everywhere the type appears (InstanceName,ImageName,EnvVarName,RepoSlug,GitRepoURL,VmMemory,InstanceIndex,GuestPath.absolute). - Make illegal states unrepresentable. Two optionals that are always both
set or both nil should be one optional tuple or struct. A
Boolplus a payload meaningful only when it is true should be an optional or an enum case with an associated value. AStringholding one of three values should be an enum.DevcontainerInput(explicit path, disabled, or discover) is one enum, not two flags.
Enums over booleans
A Bool parameter reads as true/false at the call site and invites
transposition. Prefer an enum (BootMode.firstBoot, OverflowPolicy.drain,
ConfigFormat.jsonc) or an argument label that names the choice. A boolean
flag on an options struct that mirrors a CLI flag is fine.
Lifecycles and liveness
isolate orchestrates VMs through setup → up/start → shell → stop → destroy.
Operations are legal only in certain states. When you find yourself writing
guard isRunning else { throw … } far from where the state was established,
consider whether the state belongs in a type:
- State enum with method gating. An enum for the state and methods that switch over it and throw for illegal transitions. Use when call sites are few and an explicit error is reasonable (journal states, proxy phases).
- Proof values.
AppleBackend.Running/AppleBackend.Stoppedhave initializers that are internal toIsoHost; commands get them only fromasRunning/resolveRunning/asStopped, and operations that need the precondition take the proof. Don’t reach for this on a type that mostly does something else.
Multi-step operations use explicit scoped cleanup (defer, journals,
Shutdown scopes). Never rely on deinit to stop a VM, terminate a process,
release a credential or roll back a step; actors do not replace interprocess
FileLocks.
Use noncopyable values for unique resource ownership (ChildProcess: ~Copyable)
and retain explicit scoped cleanup. In async runtime operations, register an
awaited defer immediately after acquiring the resource; shield necessary
teardown with withTaskCancellationShield so cancellation cannot skip it.
Preserve kill-on-failure behavior and the original operation error.
Borrow contiguous parser input with Span parameters and keep parsed results
owned. Fixed subprocess scratch buffers use InlineArray; only the initialized
read prefix reaches a sink. Public streaming sinks retain owned slices, so they
can keep a chunk after the next read.
Newtypes that earn their keep
The win from a wrapper type comes when:
- Two values of the same underlying type are easy to swap at a call site — use distinct types or argument labels.
- A primitive carries an invariant (non-empty, a character class, an absolute guest path, a non-zero quantity). The initializer is the one place that invariant is checked.
- A primitive is a domain concept that shows up in many signatures (instance and image names, guest paths, digests, runtime identifiers). The type reads as documentation and resists drift.
If a primitive appears in one place and crosses no boundary, leave it alone.
Error design
- Distinct failure modes → distinct error types or enum cases, so callers can
branch without string matching (
ProcessRunner.Failure,ConfigError,RuntimeError). Use typed throws (throws(ValidationError),throws(ProcessRunner.Failure)) where a function has one closed error type and callers switch on it; plainthrowsis fine where errors are composed. - Attach context where an error becomes user-facing (
ContextError), not at everytry. GenericHostErrormessages are for failures nobody branches on. - Never use
try?plus a default to hide a malformed, unreadable or wrong-typed value: missing,null, and invalid remain distinct. - No traps on untrusted input: no force unwraps,
try!,as!, unchecked integer arithmetic or unchecked indexing on values derived from configuration, guest, runtime, registry or network data. Use checked arithmetic (multipliedReportingOverflow) and bounded parsing. Where a trap is genuinely unreachable, a comment must say why the invariant holds. - Error text must not embed secrets, the configuration document, or raw Foundation decoding errors. Guest/runtime text reaching the terminal has control characters neutralized.
Processes, files and output
- One subprocess launcher. Every child process starts through
ProcessRunner(capture,stream,attached,pipeline) with an explicit argv and environment, its own process group, deadlines and bounded output. Don’t useProcess,posix_spawnorsystemelsewhere. Secrets go on stdin or into the child’s environment, never argv. - No shell interpolation. Guest shell commands are built with
RemoteCommand:.argfor every dynamic value,.literalonly for iso-authored fragments. The only intentional host shell is a user-authoredcmd:credential reference inCredentialResolver. - State writes go through
StateStore/AtomicFileunder the resource’sFileLock: write a temporary sibling, fsync, rename, never widen the mode. Control files are read without following symlinks and with a size bound. - Output streams. stdout carries command output and
--jsononly; diagnostics, prompts and progress go to stderr throughDiagnostics/OutputStreams. NoprintinIsoHost. - Recursive parsers for untrusted documents cap nesting and run on
ParserStack’s fixed stack.
CLI options and contracts
- Reuse the shared option groups and parsers (
BootArguments,DevcontainerArguments,EgressOptions,parseProfileList,parseDurationArgument,parseInstanceName) instead of redeclaring a flag. Add a flag to a group only if it applies to every command in it. - Parse, then decide. A malformed value or a conflicting combination is a
usage error from a transform or
validate(); never let one flag silently win over another, and never accept an option the selected mode ignores. - Keep meanings distinct.
--yesconfirms an ordinary prompt;--forceoverrides a check; neither approves a governed stage, unlocks the secret store or trusts a discovered devcontainer.--no-promptonly suppresses the GitHub PAT offer.--quietonly applies with--output jsonorjsonl. - Forwarded arguments are the child’s. Everything after
--reaches the guest command unchanged; do not reparse it for iso flags. - Status codes. iso’s own failures exit 1 and usage errors 2; a forwarded
workload’s non-zero status passes through, and a signal or lost proof is
never 0. A host receipt that is not
succeededfails the command. - Renaming a flag adds the new name next to the old one (same units,
limits and defaults), updates the compatibility table in
docs/commands.mdand the CLI inventory (tests/test-cli-surface.py --update-inventory), and pins both spellings in a test.
Review checklist (in priority order)
Before reviewing, sync to latest remote (git fetch origin).
- Correctness against the spec. Does the change do what was asked, including edge cases the author may not have surfaced? Run the relevant tests and re-read the diff against the request.
- Invariants in types vs. checks. Scan for
Boolparameters, primitive types representing domain concepts, sentinel values (-1,"",0meaning “missing”), and nested optionals. Each is a candidate for a stronger type. Flag the ones with real payoff. - Error paths. Every
tryproduces an error that surfaces somewhere. Is the eventual message specific enough to act on, and free of secrets and raw guest text? Are distinct failures distinguishable without string matching? Anytry?that turns a failure into a default? - Traps. Force unwraps,
try!,as!,fatalError,precondition, overflowing arithmetic, or unchecked subscripts reachable from input. - Processes and cleanup. New subprocesses go through
ProcessRunner; every spawned process, lock, PID file, temporary directory and credential is released on success, failure, timeout and cancellation. - API surface. Use
internalwithin a target andpackageacross targets in the same package. Reservepublicfor an intentional external API; the distribution exposes executables, not library products. Does the module boundary still hold (no side effects inIsoCorebeyondAtomicFile/FileLock)?Sendableconformances honest? - Tests cover behavior, not shape. Edge cases — empty input, boundaries,
each error case — have a test. Security-relevant behavior has a fault in
scripts/swift-host-fault-injection.pythat a test detects. - Diagnostics. Operations that take time, fail, or alter state log at an appropriate level (info for user-visible lifecycle, debug for internals, warn/error for problems), on stderr.
- Integration gates. Guest-visible or lifecycle changes: run the macOS
Apple sandbox integration suite (see
AGENTS.md“Before committing”).
Authoring checklist
- Sketch the types first. Write the signatures before the body. If they don’t make the legal call sequences obvious, the types are wrong.
- Take the smallest input you need. Pass the validated value or the specific fields, not the whole configuration, when a function needs one field.
- Value types by default. Prefer
struct/enumwithletproperties; use a class or actor only for identity or shared mutable state. Protect synchronous shared state withSynchronization.Mutexso classes can use checkedSendableconformances; use actors for asynchronous isolation. Keep mutable process-wide caches inside immutable mutexes rather than pairingnonisolated(unsafe)properties with separate locks. - One error case per user-meaningful failure. Five
trys that produce different actionable errors want an enum with five cases. - Resist the “configuration knob” reflex. A new flag, environment
variable, or config field is a long-lived commitment. Add it only when a real
caller needs it, and update
config.example.jsonc,ConfigTemplateand the docs in the same change. - Re-read your diff. Read your own change as the reviewer would before
pushing, and run
swift format lint --strict.