Repository navigation
08 Code Tour
Generated from
docs/at cded12f. Edit the source in the repository, not this page.
This chapter walks through the repository package by package, then follows three real requests through the code, function by function. Keep a terminal open next to it and look at the files as you read. Names of files and functions are stable; line numbers are not, so the guide does not use them.
- The M7 packages (
hostx,fsops,sshagent,broker,secrets) and a bash call followed end to end (sections 8.13 and 8.14). - Where every directory and file group lives, and what it is for.
- Which package imports which, and why the arrows only point one way.
- The key types and functions of each package, and the traps ("gotchas") that bit us before.
- The exact function-by-function path of an
action.run, a runner join and a revoke, and (section 8.9) of oneworkspace.execfrom the agent into a container and back (section 8.10 adds the agent's side: the MCP tool call that starts it). - The M3 packages:
internal/workspaceand its children (ctrd,osb,egress,wsconfig,initproc,fake), and where each sits in the import layers. - The M5 packages on the operator side (
internal/orch,internal/mcpserver,internal/handoff,integrations/claude-code/hook), the import rules that keep them light (TestOrchestratorDeps), the function-by-function path of oneexectool call (section 8.10), and how to add a tool (section 8.8). - The M4 package
internal/gui(the admin GUI): its files, why it may import onlyservice,api,authandstoretypes (TestGUIDeps), the function-by-function path of one Revoke click (section 8.11), and how to add a screen (section 8.8). - How build tags keep SQLite out of the macOS and Windows binaries (and containerd out of every non-Linux build), and where to add a new operator method, admin command, store method, action field or workspace executor.
Terms used here (principal, channel, tombstone, ...) are explained in glossary.md. The ideas behind them are in chapters 3, 5 and 7.
mirafleet/
├── CLAUDE.md ground rules for contributors and for Claude Code (read it first)
├── README.md quickstart and disclaimer
├── go.mod, go.sum module github.com/mirastacklabs-ai/mirafleet, Go 1.27.3
├── LICENSE, NOTICE Apache-2.0
├── scripts/
│ └── dev.sh every build/test/lint step, run inside a pinned container
│ (`integration` runs the containerd tests in a privileged dind)
├── docs/
│ ├── ARCHITECTURE.md the design
│ ├── PLAN.md milestones M1..M6 and the build order
│ ├── M2.md, M3.md, M4.md, M5.md per-milestone plans and decisions (M3 = workspaces, M4 = GUI, M5 = MCP)
│ ├── BRAND.md colours, fonts, tone
│ └── guide/ this developer guide
├── cmd/mirafleet/ the one binary: central | runner | mcp | version
│ ├── main.go os.Args switch, usage text, requireServerOS
│ ├── admin.go every `mirafleet central <admin command>` (a socket client)
│ ├── mcp.go `mirafleet mcp` routing and the helpers shared by the mcp files
│ ├── mcp_serve.go `mcp [serve]`: flags, signals, wires orch to the MCP server (M5)
│ ├── mcp_context.go `mcp context list|use|remove` (M5)
│ ├── mcp_hook.go `mcp hook claude-code <event>`: routes to integrations/ (M5)
│ ├── mcp_login.go, mcp_api.go `mcp login` and `mcp api` (operator side, cross-platform)
│ ├── central_linux.go `central init|run`: opens SQLite, builds service, starts server
│ ├── central_gui_linux.go the `-gui-*` flags of `central run`; starts and stops `internal/gui` (M4)
│ ├── admin_gui.go `central gui reset-admin`, `central fleet set -confirm` (M4)
│ ├── server_linux.go `runner join|run`, heartbeat constant (linux only)
│ ├── runner_ws_linux.go `runner run -workspace`, `tls-init`, `tls-front`, `workspace list|prune`;
│ │ the only file besides ctrd that links containerd (linux only)
│ ├── admin_workspace.go the workspace flags of `fleet create|workspace set`, `workspace list|kill`
│ ├── lock_linux.go flock on <data>/central.lock
│ ├── server_other.go !linux stubs that return "supported on linux only"
│ ├── platform_linux.go const serverSupported = true
│ ├── platform_other.go const serverSupported = false
│ └── *_test.go CLI parsing, central init, enrol end to end, deps_test.go,
│ e2e_integration_linux_test.go (built binary, real containerd),
│ mcp_stdio_linux_test.go (TestM5NoHooks: the built `mcp` over stdio)
├── integrations/ harness-specific files, one directory each (M5)
│ ├── claude-code/ the plugin: .claude-plugin/, .mcp.json, hooks/hooks.json, skills/,
│ │ └── hook/ Go package behind `mirafleet mcp hook claude-code <event>`
│ ├── opencode/, generic/ commands and config snippets for other harnesses (no hooks)
│ ├── commands/mirafleet.md the one shared command body
│ └── *_test.go the plugin and the harness files are checked by tests
├── .github/workflows/ orchestrator.yml: tests on windows-latest and macos-latest (M5)
└── internal/ all other code; nothing outside the module can import it
├── api/ wire protocol: methods, DTOs, error codes, framing, limits
├── transport/ SSH names (channel types, users), Heartbeat, ExecRequest/Result
├── keys/ Ed25519 generate/load, permission checks, known_hosts pinning
├── tokens/ join token (mfj1.) and registration code (mfr1.) formats
├── auth/ who is this SSH peer? Principal, KeyAuth, Encode/Decode
├── policy/ may this principal do this? TablePolicy
├── audit/ JSON-lines audit writer (runner side) and the Sink interface
├── actions/ the runner's guard: actions.yaml, Plan, Run
├── store/ persistence interface, domain types, validation, errors
│ ├── sqlite/ the SQLite implementation and migrations/0001_init.sql, 0002_workspaces.sql, 0003_gui.sql
│ └── storetest/ conformance suite every Store must pass
├── service/ the single code path behind CLI, API and GUI
├── central/ the SSH server, role handlers, admin socket
│ └── registry/ live runner sessions, Exec, Kick, tombstones
├── gui/ M4: the admin GUI (HTTPS, html/template, htmx); templates/ and static/ embedded
├── runner/ dial-out loop, heartbeat, exec@ and workspace@ handlers, runner.yaml, join
├── workspace/ M3: the Executor interface, validation helpers, output capture
│ ├── fake/ in-memory Executor for unit tests
│ ├── wsconfig/ parse and validate the runner's workspace.yaml (fail closed)
│ ├── egress/ allow-list HTTP/CONNECT proxy, private-range blocking, setns helper
│ ├── initproc/ `mirafleet workspace-init`: PID 1 inside a container
│ ├── ctrd/ containerd executor (linux only)
│ └── osb/ OpenSandbox executor, TLS client, TLS front, PKI
├── apiclient/ SSH client for operators and enrol (cross-platform)
├── opconf/ operator config and state dirs, contexts.yaml, .mirafleet.yaml (cross-platform)
├── handoff/ M5: the session id a hook leaves for the MCP server (cross-platform)
├── orch/ M5: context/fleet/session resolution, SSH pool, typed calls, output cap
└── mcpserver/ M5: the MCP stdio server and the nine tools (the only go-sdk importer)
A rule of thumb: cmd/ only parses flags and wires things together. All behaviour lives in
internal/, which is why almost everything is testable without starting the binary.
The picture groups the packages into four layers. An arrow A --> B means "code in A imports
code in B". Every arrow points down or sideways inside a layer, never up, which is why Go never
reports an import cycle. The groups come from the real import lines of the non-test files
(M3 added the internal/workspace family; go list -f '{{.Imports}}' reproduces the table).
flowchart TD
cmd["4. cmd/mirafleet<br/>parses flags and wires everything"]
top["3. central, service, runner, gui<br/>the behaviour of each role"]
exe["2b. executors: workspace/ctrd (linux only),<br/>workspace/osb, workspace/fake"]
mid["2a. store, store/sqlite, auth, policy,<br/>central/registry, apiclient, opconf, workspace/wsconfig"]
leaf["1. leaves: api, transport, keys, tokens, actions,<br/>audit, workspace, workspace/egress, workspace/initproc"]
cmd -->|"builds and starts"| top
cmd -->|"opens the database (linux only)"| mid
cmd -->|"builds the executor (linux only for ctrd)"| exe
top -->|"stores, authorises, dials, tracks sessions"| mid
top -->|"vocabulary, guard, local audit"| leaf
mid -->|"vocabulary and key handling"| leaf
exe -->|"Executor interface, validation, proxy"| leaf
exe -->|"reads the runner's limits"| mid
storetest (imports only store) is test support and is not drawn. runner does not import any
executor: it is handed a workspace.Executor value (the interface, in a leaf package), and only
cmd/mirafleet knows which concrete executor it is. Inside layers 2 and 3 the details are:
central calls service and registry; service calls policy, registry and store;
policy and auth use store; store/sqlite implements store; runner calls apiclient,
actions and the egress proxy. The full table (this is the Linux build; the darwin and windows
cmd/mirafleet drops ctrd and store/sqlite):
| Package | Imports (inside this repo) |
|---|---|
cmd/mirafleet |
actions, api, apiclient, audit, auth, central, central/registry, gui, keys, mcpserver, opconf, orch, policy, runner, service, store, store/sqlite, transport, workspace, workspace/ctrd, workspace/initproc, workspace/osb, workspace/wsconfig, and integrations/claude-code/hook
|
internal/central |
api, auth, central/registry, service, store, transport |
internal/central/registry |
transport |
internal/gui (M4) |
api, auth, service, store, workspace, workspace/units |
internal/service |
api, auth, central/registry, policy, store, tokens, transport, workspace |
internal/policy |
api, auth, store |
internal/auth |
store |
internal/store |
keys, workspace, workspace/egress |
internal/store/sqlite |
store |
internal/store/storetest |
store |
internal/runner |
actions, api, apiclient, audit, keys, transport, workspace, workspace/egress, workspace/wsconfig |
internal/workspace/ctrd |
workspace, workspace/egress, workspace/wsconfig |
internal/workspace/osb |
workspace, workspace/wsconfig |
internal/workspace/wsconfig |
workspace |
internal/workspace/fake |
workspace |
internal/apiclient |
api, keys, tokens, transport |
internal/opconf |
keys |
internal/handoff (M5) |
api |
internal/orch (M5) |
api, apiclient, handoff, keys, opconf, transport |
internal/mcpserver (M5) |
api, orch (and the go-sdk, from here only) |
integrations/claude-code/hook (M5) |
api, handoff, opconf, orch |
internal/api |
workspace (for the shared validators CleanPath, ValidArgv, FilterEnv) |
transport, keys, tokens, actions, audit, workspace, workspace/egress, workspace/initproc
|
nothing (leaves) |
The M5 packages form a separate, small stack: the orchestrator side (what runs on the
operator's laptop). mcpserver sits on orch, orch on apiclient, opconf, handoff and
keys, and the Claude Code hook package sits beside mcpserver on the same orch. None of it
imports the server side, which TestOrchestratorDeps enforces (section 8.7, point 4).
The M4 package internal/gui is a fourth kind: a second front end on the server side, beside
central. It sits on service and never touches the store, the registry or the SSH server
directly, which TestGUIDeps enforces (section 8.7, point 5).
Six consequences worth remembering:
-
internal/centralnever importsstore/sqlite. It sees only thestore.Storeinterface. Onlycmd/mirafleet/central_linux.go(a file that exists only on Linux) importsinternal/store/sqlite;server_linux.goholds the runner commands. That is how the macOS and Windows binaries avoid linking SQLite (section 8.7). -
transport,tokens,actions,auditandworkspaceare leaves. They import nothing from the repo, so they can never create an import cycle and are cheap to reuse. (apisits one step above: it imports onlyworkspace, so central and the runner validate paths, argv and env with literally the same code.workspaceitself is pure stdlib Go on purpose.) -
runnerdoes not importcentral, andcentraldoes not importrunner. They only share the vocabulary intransportandapi. (Tests are the exception:internal/central's tests start a realrunnerin process.) -
Nothing above
cmdimportsctrd.runnertalks to whatever implementsworkspace.Executor;servicenever touches a container at all (it sendsworkspace@requests throughregistry). So containerd and gRPC reach exactly one place in the linked binary,cmd/mirafleet/runner_ws_linux.go, and only on Linux (section 8.7). -
orch,mcpserverand the hook never import the server side. Notservice,store,central,runner,workspace/ctrd, SQLite or containerd. They reach central only the way a remote operator does: over SSH, throughapiclient. Without this rule the laptop binary could quietly start linking the database, and an agent's tool call could bypass the SSH boundary with a function call. -
internal/guinever importscentral,central/registry,store/sqlite,apiclient,orchormcpserver. It calls*service.Servicethrough the smallgui.Backendinterface. That is why a revoke from a browser takes exactly the code path ofcentral runner revoke: there is no second implementation to keep in line.
Each package below has an If you only read one line: the single file to open first.
-
If you only read one:
internal/api/api.go(methods, DTOs, error codes). -
Purpose: everything two sides must agree on to talk
api@mirafleet, the admin socket and the enrol channels. No SSH, no unix-only calls. -
Key names: method constants (
MethodActionRun,MethodFleetsList, ...);IsOperatorMethod,IsAdminMethod,IsEnrollMethod(three disjoint sets, each aswitchso they cannot change at run time);Request,Response,Errorand theCode*constants; DTOs such asActionRunParamsandActionRunResultand, from M3, theWorkspace*DTOs and methods (MethodWorkspaceOpen, ...); limits (MaxRequestBytes64 KiB,MaxResultBytes1 MiB,MaxParams32,DefaultActionTimeout2 min,MaxActionTimeout10 min). -
Functions:
ReadFrame/WriteFrame(4-byte length prefix, seeframe.go),ReadRequestTimeout(reads one request with an arrival deadline),ParseRequest,DecodeParams(strict: unknown fields arebad_request),WriteResponse,ActionTimeout. -
Body frames (M3):
frame.goalso hasWriteBodyandReadBodyTimeout: the second length-prefixed frame behind a request (limitMaxFileChunk1 MiB, zero length allowed,BodyTimeout30 s).ValidateArgv,ValidatePath,ValidateEnv,ValidateSessionandWorkspaceExecTimeoutwrap the shared validators ofinternal/workspace. - Used by: almost everything.
-
Gotchas:
ReadRequestonly works for readers withSetReadDeadline(anet.Conn). Anssh.Channelhas no deadline, so every handler on a channel must callReadRequestTimeoutinstead, or a silent peer can hold a goroutine forever.api.Internal(err)deliberately drops the cause so nothing internal can leak to the peer.
-
If you only read one:
internal/transport/transport.go. - Purpose: the strings and tiny structs shared by central and runner.
-
Key names:
ChanExec(exec@mirafleet),ChanAPI,ChanJoin,ChanRegister,ReqHeartbeat; usersUserOperator,UserEnroll,UserRunner;Heartbeat,ExecRequest,ExecResult;MaxResultBytes(8 MiB, the most central will read back from a runner). M3 addsworkspace.go:ChanWorkspace(workspace@mirafleet), the ops (OpCreate,OpExec,OpRead,OpWrite,OpDestroy,OpList),WorkspaceRequest/WorkspaceResult/WorkspaceSpec,Encode/DecodeWorkspaceRequest,WriteResult/ReadResult(one length-prefixed result frame),CopyBody/WriteBody(exactly N raw bytes, then EOF) and the workspace fields ofHeartbeat(Slots,Executor,SecureRuntime,Images, checked byHeartbeat.Validate). - Gotcha: the SSH user name decides the role. It is not a login name. See chapter 7.
-
If you only read one: the file with
LoadSignerandPinnedHostKeys. -
Key functions:
Generate(dir, name, comment)(private key 0600 plus.pub0644, refuses to overwrite viaO_EXCL),LoadSigner(path)(refuses any key readable by group or others),EnsureDir(0700, tightened if it exists),PinnedHostKeys(path)(aHostKeyCallbackthat accepts only keys listed in a known_hosts-style file, re-read on every connection),RunnerNameRE. -
Platform files:
perm_unix.gochecks the mode bits. On Windows (M5),acl_windows.gocreates every directory and private file with a protected DACL (inheritance off, owner is the current user, allow-entries only for that user, SYSTEM and Administrators) andperm_windows.gore-checks all of it on load; anything else fails closed.perm_other.go(not unix, not Windows) still refuses to load any key. -
Gotcha:
PinnedHostKeyshas no "trust on first use" mode. A key not in the file is an error:host key for ... not pinned in ....
-
If you only read one: the file with
CodeandVerifyCode. -
Formats: join token
mfj1.<id>.<secret>.<host-key hash>, registration codemfr1.<26 base32>.<host-key hash>. See chapter 5 for why both carry the host-key hash. -
Key functions:
NewJoinToken(hostKey)(returns the token, its id andSHA-256(secret); central stores only the hash),ParseJoinToken,Code(secret, step, hostKey),ParseCode,VerifyCode(current 60-second step only, constant-time compare),Step,SecondsLeft,HostKeyHash. -
Gotcha: parsers are strict and canonical: a value must re-encode to exactly the same
string.
kat_test.goandtokens_test.gopin the format with a known-answer test, so changing the HMAC input breaks old codes and the test tells you.
-
If you only read one: the file defining
PrincipalandKeyAuth. -
Key names:
Principal{Kind, ID, Name, Fingerprint, Remote, Status}; kindsKindRunner,KindOperator,KindEnroll,KindAdmin;AuthProviderinterface;KeyAuth(the OSS provider, looks keys up in the store);Encode/Decode(identity travels inssh.Permissions.Extensions);PublicKeyCallback;LocalAdmin(uid). -
Gotcha:
Decodefails closed and never acceptsKindAdmin: the admin principal exists only on the local socket. Identity must never be kept in closure variables shared between connections (an old class of SSH-library bugs); that is why it rides in the permissions of the one connection.
-
If you only read one:
internal/policy/policy.go(it is short). -
Key names:
PolicyEngineinterface (Authorize(ctx, principal, action, resource)),TablePolicy(the OSS implementation),ErrForbidden,Resource. -
Rules in
TablePolicy: admin may do anything; an operator may dohello,fleets.list,runners.listandaction.runonly while its current status isactive; an enrol principal may do the two enrol methods; everything else is forbidden (deny by default). -
Gotcha: the policy cannot look anything up. The caller (
service.authorize) loads the operator's current status and passes it inResource.ActorStatus. This is the "seam" for an enterprise RBAC policy later.
-
If you only read one: the file with
WriterandSink. -
Key names:
Event,Writer(Open(path)appends JSON lines, mode 0600),Sinkinterface withRecord(ctx, ev) error,Writer.Log(best effort, swallows errors). -
Gotcha: a nil
*Writeris a valid no-op sink. Anything that must fail closed on an audit failure callsRecordand checks the error, neverLog. Central's audit is not this package: central writes audit rows throughstore.Store.
-
If you only read one:
internal/actions/actions.go(ParseandPlan). -
Key names:
Set,Action,ParamSpec;Load(path)/Parse(bytes);Set.Plan(name, params)returns the final argv and timeout or a*RefusedError;Set.Run(ctx, name, params);Set.Names();MaxOutput(1 MiB, stdout and stderr combined). -
Why it matters: this is the security boundary in actions mode.
Parserejects unknown YAML fields (KnownFields(true)), resolves a bare command name to an absolute path once at load time against a fixedPATH, compiles every param pattern twice (alone first, then wrapped in\A(?:...)\zso the author's anchors cannot be escaped), and checks that every{{placeholder}}has a param.Plansubstitutes in a single pass, so a value is never re-scanned for placeholders. -
Files:
kill_unix.goputs the child in its own process group and kills the group;kill_other.gois a fallback that is unreachable in shipped runners. -
Gotcha:
execArgvgives the child an empty environment exceptPATHandLANG=C, and/as working directory. Actions that "work in my shell" often fail here for that reason.
-
If you only read one:
internal/store/store.go(the interface and its doc comments). -
Key names:
Storeinterface; typesFleet,Runner,JoinToken,Operator,AuditEvent, and for M3WorkspaceConfig(withValidateandImageAllowed),Workspace,WorkspaceState(CanTransitionWorkspace),WorkspaceFilter,ErrFull;Status/CanTransition(pending to active, active to and from disabled, any non-revoked to revoked, revoked is final);ParseRef("fleet/runner"); name validators; errorsErrNotFound,ErrInvalid,ErrConflict,ErrStale. -
Rule written into the interface: every state-changing method takes an
AuditEventand commits it in the same transaction as the change. No method callstime.Now(); the caller passesnow. -
Gotcha:
Enrollmaps an unknown token id and a wrong secret to the sameErrNotFound, and the service maps both that andErrStaleto one identical error, so a probe learns nothing.
-
If you only read one:
migrations/0001_init.sql(the whole schema). -
Files:
sqlite.go(Open, two connection pools),migrate.go(embedded migrations), one file per entity (fleets.go,runners.go,tokens.go,operators.go,settings.go,audit.go, and for M3fleetws.goandworkspaces.go, and for M4gui.go: the admin, setup-token and session tables),driver.go(maps driver error codes toErrConflict),open_unix.go/open_other.go(open withO_NOFOLLOWon unix),migrations/0001_init.sql,0002_workspaces.sqland0003_gui.sql.audit.goalso hasQueryAudit, the filtered keyset read behindaudit.listand the Audit screen. -
How it works: one single-connection writer pool doing
BEGIN IMMEDIATEtransactions, plus a smallquery_onlyreader pool, in WAL mode withbusy_timeout(5000)andforeign_keys(1). Migrations are numberedNNNN_name.sql, must be contiguous from 0001, run in one transaction and are tracked inPRAGMA user_version. A database whose version is newer than the binary is refused. -
Gotchas:
Openrefuses:memory:(each pooled connection would get its own empty database), refuses symlinks and non-regular files, and tightens the file to 0600. Usefilepath.Join(t.TempDir(), "mirafleet.db")in tests. The audit table has triggers that abort everyUPDATEandDELETE, so "append-only" is enforced by the database itself.
If you only read one: internal/store/storetest/storetest.go.
storetest.Run(t, newStore) runs the same subtests (Fleets, Audit, Enroll,
EnrollRaceSingleUse, KeyDisjoint, Runners, Tokens, Operators, Settings,
Validation, ContextCancelled, ...) against any store.Store. store/sqlite/sqlite_test.go
calls it from TestConformance. A future Postgres store will call the same function.
-
If you only read one:
internal/service/exec.go(RunAction). -
Purpose: every front end (the operator API, the admin socket, the enrol channels and, since
M4, the GUI) calls the same
*Servicemethods. Each method authorises, validates, changes state and audits. -
Files:
service.go(Config,New,authorize,deny,ToAPIError,Source),exec.go(RunAction),lifecycle.go(ListRunners,Approve,Disable,Enable,Revoke,Lifecycle),enroll.go(Join,Register),operators.go(InitRegistrationSecret,RotateRegistrationSecret,OperatorCode,ListOperators,RevokeOperator),tokens.go(CreateToken,ListTokens,RevokeToken),fleets.go. M3 addedworkspace.go(OpenWorkspace,CloseWorkspace,SetFleetWorkspace,WorkspaceDefaults, the stickyreuse),workspace_sched.go(candidates: placement),workspace_ops.go(ExecWorkspace,ReadWorkspaceFile,WriteWorkspaceFile,ListWorkspaces,classify),workspace_admin.go(AdminListWorkspaces,KillWorkspace) andworkspace_reaper.go(RunReaper,ReapOnce,ReconcileRunner,RecoverWorkspaces). M4 addedgui.go(the admin account and its sessions:EnsureGUISetup,CompleteGUISetup,GUILogin,GUIAuthenticate,ChangeGUIPassword,ResetGUIAdmin,GUILogout,PurgeGUISessions, and theAction*names of thegui.*audit rows) andaudit.go(ListAudit,RecordAuditExport);SetFleetConfirmis infleets.goandListRunnersAllinlifecycle.go. The principal of a GUI request isauth.GUIAdmin(username, remote)and the source isservice.SourceGUI. -
Dependencies are injected through
service.Config:Store,Policy,Live(theregistry.Liveinterface),HostKey,Now,OperatorConns,Logf. Tests pass fakes (fakeLive,fakeConns) and a fixed clock. -
Gotchas:
authorizeapplies the policy and, for admin-only methods, a directp.Kind == auth.KindAdmincheck. The method table (incentral) and the policy are two independent gates; the direct kind check is a third for admin-only calls, so a buggy policy cannot open an admin door. A denial is audited with outcomedenied.ToAPIErrorgives every error a fixed message per code so SQL or paths cannot leak.
-
If you only read one:
internal/central/roles.go(dispatch,serveRunner). -
Files:
central.go(Config,Server,New,Start,Close,handle),roles.go(dispatch,serveRunner, the channel allow-list),api.go(serveOperator,serveAPIChannel),dispatch.go(methodTable,operatorTable, the four operator handlers),enroll.go(serveEnroll,enrollCall, per-IP limiter),hslimit.go(pre-handshake connection caps),conns.go(OperatorConns),admin.go(ServeAdmin,adminTable,adminConn),admin_handlers.go(the admin handlers),adminclient.go(AdminCall, the client end of the socket), and for M3workspace_handlers.go(the sixworkspace.*handlers, the lazy body readerslazyStdinandlazyFileBody, the admin workspace handlers,wsInfo: store row to DTO). -
Platform files:
admin_unix.go(socket +checkPeer),admin_peer_linux.go(SO_PEERCRED),admin_peer_darwin.go(LOCAL_PEERCRED),admin_peer_other.go(other unix: rejects every peer),admin_other.go(non-unix: fails closed). -
Roles:
dispatchswitches onp.KindtoserveRunner,serveOperatororserveEnroll. The allowed channel types per role live in one map,allowedChannels. -
Gotchas:
methodTable.servehas its ownallowedpredicate in front of the policy, so a method that is not in a table's set never reaches a handler.serveRunnerregisters a session on the first heartbeat, not at connect time, because only then has the runner installed its channel handler. Database writes oflast_seen_athappen in a backgroundtoucherso a slow disk never delays a heartbeat reply.
-
If you only read one: the file with
Registry.ExecandRegistry.Kick. -
Key names:
Registry,Session, theLiveinterface (Exec,Kick,Tombstone,ClearTombstone,SetStatus,Snapshot, and for M3Workspace),KickError,ErrPending,ErrDisabled,ErrTombstoned,ErrNoExecutor,ErrBusy,Options{StaleAfter}.SessionInfocarries the heartbeat'sSlots,Executor,SecureRuntimeandImages. -
Registry.Workspace: opens aworkspace@mirafleetchannel on the runner's connection (workspaceOn), streams the raw body, reads one result frame (and, for a read, the raw bytes). Status gating is per op:destroyandlistwork on anactiveordisabledrunner; every other op needsactive. -
How it works: sessions are keyed by the runner's database id.
Registerrejects a tombstoned id under the same lock that inserts the session, so a revoke cannot slip in between.Execopens anexec@mirafleetchannel on the runner's own connection (execOn). A session context derived fromcontext.WithCancelCauseletsKickcancel an in-flight exec with the reason. -
Gotcha: tombstones live in memory only. After a restart, revoked runners are refused at
authentication because their database status is
revoked; the tombstone only closes the short window while a revoke is in flight.
-
If you only read one:
internal/runner/runner.go(Run,serveExec). -
Files:
runner.go(Config,New,Run,session,heartbeat,serveExec,execute),join.go(Join),config.go(FileConfig,LoadConfig,SaveConfig, path helpers,ErrNotJoined,ErrAlreadyJoined). -
How it works:
Runloops forever: dial, authenticate as SSH userrunner, heartbeat every 15 s, serveexec@mirafleetchannels, and on any failure back off exponentially (1 s up to 60 s, plus or minus 20% jitter). A connection only resets the backoff after it stayed up 30 s with an acknowledged heartbeat. -
Gotchas: a semaphore (
MaxExec, default 4) caps concurrent actions; extra ones are rejected withrunner busy.Joinwritesrunner.yamllast, so its existence means "the join fully succeeded". The runner never listens on a port. -
Workspace mode (M3):
workspace.goholdsserveWorkspace(decode,prepare= re-validate againstworkspace.yaml,admit= slot and exec permits before accepting the channel, then run and answer),runWS/runExec(call theworkspace.Executor),fillHeartbeat, and the disk sampler.Config.Workspace(the executor) andConfig.WorkspaceConfigare set instead of actions;Config.Validaterequires the executor and its config together and refuses actions plus workspace. The runner knows only the interface, neverctrdorosb.
The parent package is the contract; the children are implementations and helpers. Read them in this order.
internal/workspace (pure stdlib, imports nothing from the repo)
-
If you only read one:
internal/workspace/workspace.go. -
Key names: the
Executorinterface (Name,Create,Exec,ReadFile,WriteFile,Destroy,List,Close),ID(32 lowercase hex, assigned by central),Spec,Limits,Network,ExecRequest/ExecResult,Info, the errorsErrNotFound,ErrRefused,ErrBusy,ErrTooLarge,ErrQuota,ErrUnavailable,ErrUnsupported, andRoot(/workspace). -
validate.go:CleanPath(lexical:..can never escape/workspace; symlinks are the executor's job),ValidArgv,EnvDenied,FilterEnv(allowlist, then the denylist that always wins),MatchImage/NormalizeImage(exact refs,repo:*,repo@sha256:*).capture.go:Capture, a head-and-tail writer whose result fits a JSON-encoded byte budget. - Gotcha: this code runs on central and the runner. Change a rule here and both change together, which is the point: central rejects early, the runner re-checks because it does not trust central.
internal/workspace/wsconfig: parses workspace.yaml with KnownFields(true).
Parse checks everything that needs no disk; Load adds ownership and mode checks of the
containerd root and the secret files. There is deliberately no field for privileged
containers, unconfined profiles or host mounts. See chapter 10.
internal/workspace/ctrd (//go:build linux): the containerd executor. Files:
executor_linux.go (New, Create, Destroy, Options), spec_linux.go (buildSpec: the OCI
spec from a fixed template, asserted by spec_linux_test.go), userns_linux.go (probeUserNS: kernel at
least 5.19, user namespaces enabled, an idmapping snapshotter), exec_linux.go (task.Exec, FIFOs, kill on timeout),
files_linux.go (os.Root, O_NOFOLLOW|O_NONBLOCK, regular-file check), egress_linux.go
(listener in the container's network namespace), disk_linux.go (usage and soft quota),
list_linux.go, doc.go (keeps the package visible to non-Linux tools).
internal/workspace/egress: Proxy (a stdlib HTTP and CONNECT proxy), allow.go (the
allowlist grammar host[:port], *.domain), blocked.go (private, loopback, link-local and
metadata ranges), netns_linux.go / netns_other.go (LockOSThread + unix.Setns, never reuse
a thread that failed to switch back). Pure Go except the setns file.
internal/workspace/osb: the OpenSandbox executor and everything around its TLS: client.go
(the REST client, no redirects, URLs rebuilt on the configured base), tls.go (TLS 1.3 only, CA
or SPKI pin, mTLS, never the system pool), sse.go (server-sent events of /command),
executor.go (maps workspace.Executor onto OpenSandbox calls), front.go (mirafleet runner tls-front), pki.go (tls-init). All stdlib, compiles everywhere, wired on Linux only.
internal/workspace/initproc: Run, PID 1 inside a container (reap zombies, exit on SIGTERM).
Reached through the hidden mirafleet workspace-init command; the binary is bind-mounted
read-only at /.mirafleet/init, so it works in any image, distroless included.
internal/workspace/fake: an in-memory Executor with hooks. Service, registry, runner and
the TestM3Done scenario use it, so the logic is tested without a daemon.
-
If you only read one: the file with
apiclient.DialandClient.Call. -
apiclient:Dial(ctx, addr, user, signer, hostKeyCallback)(callback mandatory, no fallback),Client.Call, typed helpers (Hello,FleetsList,RunnersList,ActionRun),JoinandRegister(enrol with the host key pinned from the token or code), host-key callbacksPinnedHash,KnownHosts,Fingerprint,Prompt. -
opconf:Dir()($MIRAFLEET_CONFIG_DIRor the OS user config dir plusmirafleet; on Windows%LocalAppData%\mirafleet, never Roaming),StateDir()(where handoff files live;$MIRAFLEET_STATE_DIRoverrides),KeyPath,KnownHostsPath,ContextsPath,ContextswithLoadContexts/SaveContexts/UseContext/RemoveContext(M5: per-contextdefault_fleet, the top-leveloutput_cap_bytes, ajumpkey refused), andLoadProjectfor.mirafleet.yaml(keysfleetandcontextonly, looked up from the project directory upward, stopping at a.gitor at home). -
Gotcha: both are cross-platform on purpose (the operator runs on a laptop). They must not
import anything unix-only.
Promptrefuses to ask when stdin is not a terminal, so a script can never be tricked into trust-on-first-use.
These four are what turn "an agent wants to run a command" into the SSH calls of earlier chapters. They run on the operator's machine (linux, darwin or windows) and never link the server side (section 8.2, point 5).
internal/handoff: a harness-neutral note passed from a hook to the MCP server.
-
If you only read one:
handoff.go. Key functions:Write(stateDir, Key{PID, Project}, session, now),Read,Remove,RemoveIf(removes only if the file still names that session). The file is<state>/sessions/<sha256(pid|project)[:32]>.json, directory 0700, file 0600, written atomically; files older than 7 days are pruned on write. - Gotcha: a planted file can only point at another session of the same operator, because central checks ownership on every call. It carries no secret.
internal/orch: the orchestrator core. It has no MCP code and does not read the process
environment (a test, TestNoEnvAccessInSource, scans the source).
-
If you only read one:
calls.go(call, the only path toapiclient). -
orch.go:New(Config)always succeeds, even with no key or contexts (calls then returnErrNotSetUp);Closecancels in-flight calls and closes connections, never workspaces. -
resolve.go:Resolve(context and fleet, with sources, precedence argument > flag >.mirafleet.yaml> context default; refuses a guarded fleet that came from a default),SessionFor(flag, else handoff file, else a randomp:<32 hex>, re-read on every call). -
pool.go: one SSH connection per context, dialled lazily withknown_hostspinning and never trust-on-first-use, a 30 s keepalive, a semaphore ofapi.MaxChannelsPerConn(8). -
calls.go: typed wrappers (FleetsList,RunnersList,ActionRun,WorkspaceOpen,WorkspaceExec,WorkspaceReadFile,WorkspaceWriteFile,WorkspaceClose,WorkspaceList).callrefuses any method for whichapi.IsOperatorMethodis false, redials once on a dead connection but retries only idempotent methods (neverexec,write_file,action.run,workspace.close), and maps every error to an*orch.Errorwhose text holds no path, fingerprint or internal detail. -
output.go:SanitizeandCapOutput(chapter 7).limit.go:CallLimit, the client-side timeout per method. -
Gotcha: the guard in
callis gate 1 of three for "no admin reach from the agent" (the others: central refuses admin methods onapi@whatever the principal; the tool table is fixed). A test makes it panic instead of return an error, so a new code path that reaches it cannot go unnoticed.
internal/mcpserver: the MCP server and the tools.
-
If you only read one:
tools_ws.go(exec,read_file,write_file). -
server.go:Serve,Config,Tool,Request,Handler,DecodeArgs,Error,PublicError, the result and error encoding.backend.go: theBackendinterface (what tools need;*orch.Orchimplements it, a fake does in tests) and thewheretype.tools_list.go:ListTools(list_fleets,list_runners,run_action,workspace_list).tools_ws.go:WorkspaceTools(workspace_open,exec,read_file,write_file,workspace_close) and the per-process binding of (context, fleet, session) to a workspace id. -
Gotcha: this is the only package allowed to import the go-sdk (
github.com/modelcontextprotocol/go-sdk). Tools are plain structs; if you ever swap the SDK, only this package changes.
integrations/claude-code/hook: parses Claude Code's hook JSON and implements the three
events (session-start, session-end, pre-tool-use). It imports orch, handoff, opconf
and api, and is reached only through cmd/mirafleet/mcp_hook.go. It always exits 0, so a
broken hook can never block a session (chapter 11).
If you only read one: cmd/mirafleet/admin.go.
main.go switches on os.Args[1]. central and runner first call requireServerOS. All
admin subcommands go through adminCLI.run in admin.go; its call field is a function value
(normally central.AdminCall) so tests replace it with a fake and never need a running central.
adminParse lets flags appear after positional arguments (fleet create web -mode workspace).
M3 added: admin_workspace.go (the wsFlags shared by fleet create and fleet workspace set,
workspaceList, workspaceKill; no SQLite or containerd), runner_ws_linux.go (runnerWorkspace
for list and prune, runnerTLSInit, runnerTLSFront, loadWorkspace, and the newExecutor
variable that tests replace with a fake), and in mcp_api.go the -in and -out flags of
mcp api (bodies for write_file, stdin of exec, the file a read_file writes). The
client-side deadline per method started life there as mcpCallLimit; M5 moved it to
orch.CallLimit so mcp api and the MCP server share it. runner run takes exactly one of
-actions FILE or -workspace FILE; workspace mode never falls back to actions.
M5 added the mcp files: mcp.go routes mirafleet mcp [serve|context|login|api|hook] (no
subcommand, or a first argument starting with -, means serve); mcp_login.go and mcp_api.go
were split out of the old mcp.go unchanged; mcp_serve.go parses the flags (-context,
-fleet, -session, -project-dir), builds an orch.Orch (the only place the server reads its
environment: the config and state directories and the parent PID), starts mcpserver.Serve with
append(mcpserver.ListTools(o), mcpserver.WorkspaceTools(o)...), and on return closes orch with
a 5 s bound; mcp_context.go is context list|use|remove; mcp_hook.go hands a hook event to
integrations/claude-code/hook. They are cross-platform and import no server-side package.
M4 added central_gui_linux.go (parseCentralRun reads -gui-listen, -gui-cert, -gui-key,
-gui-host and -advertise and checks them; startGUI builds gui.New, prepares the setup token
and starts the listener; runningGUI.stop drains it within 5 s, before the store closes) and
admin_gui.go (guiResetAdmin for central gui reset-admin, fleetSet for central fleet set NAME -confirm=BOOL). The audit command gained the filter flags (-fleet, -source,
-action-prefix and so on). The GUI is linux-only because the file that wires it is.
-
If you only read one:
internal/gui/handlers_runners.go(runnerOp): one page with a list, a detail view, a confirmation page and a state-changing POST, in about 400 lines. -
Purpose: a human administrator's web console. It is a second front end on
service, like the admin socket, with its own listener (HTTPS only), its own authentication (a password and a session cookie, not an SSH key), and no logic of its own beyond turning forms into service calls and results into HTML. -
The seam:
backend.goholdsBackend, the narrow interface of exactly the*Servicemethods the GUI uses;var _ Backend = (*service.Service)(nil)makes the compiler check it.ResetGUIAdminis deliberately missing, so recovery stays on the CLI. Tests giveServera real service over a temporary SQLite file. -
Files, in the order a request meets them:
-
server.go(Config,New,Start,Shutdown,CheckHostName): builds the certificate, the Host guard, the templates and the handler;listen.go(hostGuard,ownIPs, the start-up notice);tlscert.go(ensureSelfSigned,Fingerprint, operator certificates;tlscert_unix.go/tlscert_other.gocheck the key file's owner and mode). -
middleware.go(buildHandler): request id and security headers, panic recovery, access log, the Host allowlist (421), the in-flight cap (503), method, content type and body size, then the mux. -
routes.go:adminMux(HandleFuncwraps a handler inrequireAdmin,Passivedoes the same and marks the route as not counting as activity) androutes(), which calls oneroutes<Screen>function per screen. -
session.go(cookies,authenticate, the purge ticker),csrf.go(CSRF.Check, form and htmx tokens, signed flash values),limiter.go(LoginLimiter,HashSem,ParseForm). -
handlers_*.go: one file per screen (auth,overview,fleets,runners,tokens,operators,workspaces,audit,account). Each has itsroutesXfunction, the handlers, and the view models. -
render.go(Page,Render,ErrorPage,Redirect, the flash table) andassets.go(the embeddedstatic/tree, content-hashed URLs). The HTML is intemplates/*.html(layout.html,partials.html, one file per screen).
-
-
How a screen is built: a handler authenticates (
screenAuth), reads and checks the form (screenForm: size, type, CSRF), callss.cfg.Backend, and either callss.Renderwith a view model ors.Redirectwith a flash message id. View models are small structs; a store row with secret material (a password hash, a join token's secret hash, a runner's public key) is never passed to a template. -
Gotchas:
-
gui.Serveris not given the store, so a handler cannot read the database even by mistake. -
routes.goregisters by calling eachroutesX; the security suite finds routes by scanning the source forHandle(,HandleFunc(andPassive(calls with a literal"METHOD /path". A route registered any other way failsTestSecurityAuthRequiredOnEveryRouteon purpose, because it could escape the checks. - A page and its fragment share one handler:
Render(w, r, status, screen, fragment, pg)picks the fragment only when the request hasHX-Request: true. - Every template is parsed once at start. A syntax error therefore stops central from starting
its GUI;
TestS3TemplatesParsefinds it earlier.
-
durga's agent runs this on their laptop. prod is a guarded fleet (created with -confirm), so
the call must carry "confirm":"prod":
mirafleet mcp api action.run '{"fleet":"prod","runner":"db-1","action":"tail-logs","params":{"lines":"200"},"confirm":"prod"}'Look at: the request goes down through central into the runner and back up; both audit rows
(start and the outcome) share one request_id.
- durga's agent calls
action.run(prod/db-1,tail-logs,lines=200) throughmirafleet mcp. -
mcpsends one frame (4-byte length + JSON) on anapi@channel. The operator method table routes it. -
service.RunActionchecks policy, fleet mode, confirm "prod" (guarded fleet's name), runner active. - The audit row "start" is written first. If that fails, nothing runs (fail closed).
-
registry.Execopens anexec@channel on the runner's own connection and sends the request. - The runner's actions guard checks
tail-logsand regex-checkslines=200into an argv. - The process runs (no shell, own process group, timeout). The result JSON goes back.
- The audit row "outcome" is written with the same
request_id. - The response frame returns the same way: exit code, stdout, stderr.
The list below is the same journey with function names. Follow it with the files open.
On durga's laptop
-
mainincmd/mirafleet/main.goseesmcpand callsmcpMain, which callsmcpAPI(cmd/mirafleet/mcp_api.go). -
mcpAPIchecks the JSON withjson.Valid, then finds the config directory (opconf.Dir), readscontexts.yaml(opconf.LoadContexts) and picks the address of the current context. It loads the key withloadOperatorKey, which callskeys.LoadSigner. -
apiclient.Dialopens TCP and runs the SSH handshake as usertransport.UserOperator. The host-key callback isapiclient.KnownHosts, i.e.keys.PinnedHostKeysover theknown_hostsfile in the operator config directory (opconf.KnownHostsPath, found withos.UserConfigDir, e.g.~/.config/mirafleeton Linux): central's key must have been pinned atmcp login. -
Client.CallcallscallOn, which builds anapi.Request(random 16-hex id), opens one channel of typeapi@mirafleet, sends the request withapi.WriteFrameand waits inapi.ReadFrame.
On central
-
Server.handle(central.go) first askshsLimiter.acquirefor a handshake slot, then runsssh.NewServerConn. During the handshake the public-key callback isauth.PublicKeyCallback, which callsKeyAuth.Authenticate. Because the user isoperator, it callsstore.GetOperatorByKey; a revoked operator or unknown key givesauth.ErrDenied. -
handlerecovers the identity withauth.Decodeand callsServer.dispatch(roles.go), which callsserveOperator(api.go). -
serveOperatorregisters the connection inOperatorConns(so a revoke can kick it), then reloads the operator by id (GetOperatorByID) and closes if it is notactive, thenTouchOperator. It buildsoperatorTable()and acallCtx. - For each new channel it checks
channelAllowed(auth.KindOperator, ...)and a per-connection cap ofapi.MaxChannelsPerConn, then runsserveAPIChannel. -
serveAPIChannelreads the request withapi.ReadRequestTimeout(size and time limits), then callsmethodTable.serve(dispatch.go). -
servechecks the allow predicateapi.IsOperatorMethod, looks uphandleActionRun, and applies a timeout (none foraction.run; the service sets its own).handleActionRundecodes the params strictly withapi.DecodeParamsand callsService.RunAction.
In the service
-
Service.RunAction(service/exec.go) callsauthorize, which loads the operator's current status and callspolicy.TablePolicy.Authorize. A denial is audited and returned asforbidden. - It validates the input (
store.ParseRef,api.ValidateActionParams,api.ValidateTimeoutS,api.ActionTimeout), loads the fleet (GetFleet), requires modeactions, checks theconfirmguard, loads the runner (GetRunner) and requires statusactive. - It creates a
request_id(newRequestID) and writes the start audit row withstore.RecordAudit. If that write fails, nothing runs (unavailable: audit unavailable). - It calls
s.live.Exec, i.e.registry.Registry.Exec.Execfinds the live session (Get), re-checks the session status (pending and disabled are refused), andexecOnopens a channel of typeexec@mirafleeton the runner's own SSH connection, carrying theExecRequestJSON as channel data.
On the runner
- In
Runner.session,client.HandleChannelOpen(transport.ChanExec)hands the channel toserveExec(runner.go). -
serveExecdecodes the request, takes a slot from the semaphore, accepts the channel and logs astartevent to the localaudit.jsonl. -
executecallsactions.Set.Run, which callsPlan(the guard: unknown action, unknown or missing parameter, pattern, leading dash, then single-pass substitution) andexecArgv(exec.CommandContext, no shell, minimal environment, own process group, output cap, timeout). A refusal becomes anExecResult{Refused: true}; nothing ran. -
serveExecencodes the result (encodeResult), logs the outcome event before replying, then writes the JSON to the channel and callsCloseWrite.
Back up
-
execOnin central reads at mosttransport.MaxResultBytes, decodes theExecResultand returns it.RunActionbuilds the outcome audit row (ok,timeout,cancelledorerror, samerequest_id) and writes it with a context that survives cancellation (context.WithoutCancel). A runner refusal becomesbad_request: refused by runner: .... -
RunActionreturnsapi.ActionRunResult.methodTable.servewraps it withapi.NewResult;writeResponseTimeoutwrites the frame (and closes the connection if the peer stops reading). - Back in
callOn, the client checks version and id, decodes the result, andmcpAPIpretty-prints it withjson.Indent.
That is two SSH connections, two audit tables (central's SQLite and the runner's file) and four checks (policy, service rules, registry status, runner guard) for one command.
aarvee (the MIRASTACK LABS admin) has created a token on central with
mirafleet central token create -fleet dev and pipes it into runner join on build-1.
Look at: the host-key hash inside the token pins central before anything secret is sent.
- aarvee runs
token createon central. It printsmfj1.ID.SECRET.HASHonce (HASH pins central). - aarvee hands the token to the build-1 host by any channel, never through central.
-
runner joindials:2222as userenroll. A host key not matching HASH is refused (no TOFU). - It sends one
join@mirafleetframe: token, runner name, labels. -
Store.Enroll, one transaction: look up by ID, constant-time compare, check stale, insert. - Status is
pending(activeonly if the token auto-approves). The enroll connection closes. - aarvee runs
runner approve dev/build-1: status becomesactive. - The runner reconnects as user
runnerwith its own key and sends heartbeats.
On build-1
-
maincallsrunnerMain(server_linux.go), which callsrunnerJoin. -
runnerJoinparses flags (splitAddrtakes the address off first so flags may follow it), insists on-token -, setsumask 077, and refuses before reading stdin ifrunner.yamlalready exists (runner.ErrAlreadyJoined). ThenreadSecretreads the token from stdin (max 4096 bytes). -
runner.Join(join.go) validates the address and name, callskeys.EnsureDir(0700), generatesrunner_ed25519if absent (keys.Generate) and loads it (keys.LoadSigner). -
apiclient.Joinparses the token (tokens.ParseJoinToken), takes the embedded host-key hash and callsenroll.enrollwrapsPinnedHash(hash)as the host-key callback, thenDial(..., transport.UserEnroll, ...)andcallOn(..., transport.ChanJoin, api.MethodEnrollJoin, ...). If central presents any other host key, the dial fails withhost key does not match the pinned keybefore any secret is sent.
On central
-
Server.handleruns the handshake. For SSH userenroll,KeyAuth.Authenticateaccepts any Ed25519 key and returnsPrincipal{Kind: KindEnroll}; the wrapper incentral.Newadds the presented key to the permissions underextPubKey. -
dispatchcallsserveEnroll(central/enroll.go):ipLimiter.allow(per-IP and global rate limits), a hard deadline (EnrollDeadline, 30 s),enrollKey(cross-checks the key against the authenticated fingerprint), then exactly one channel. -
serveEnrollChannelreads the request (api.ReadRequestTimeout) andenrollCall, which requires the method to match the channel (join@mirafleetwithenroll.join) and callsService.Join. -
Service.Join(service/enroll.go):requireEnroll(policy plus a direct kind check), validates the key and name,tokens.ParseJoinToken, compares the token's host-key pin withtokens.HostKeyHash(s.hostKey)in constant time, hashes the secret and callsstore.Enroll. -
sqlite.DB.Enrollruns one transaction, in this order: look up the token id; compare the hash in constant time (against a dummy hash when the id is unknown); do a conditionaluses+1that fails if the token is stale (expired, revoked or used up); refuse a key already held by an operator; insert the runner (pending, oractiveif the token was made with-approve); write theenroll.joinaudit row. All succeed or none. - Every failure except a name/key conflict returns the same
unauthenticated: join refused; the real reason is only in central's log.
Back on build-1
-
runner.Joinwritesknown_hosts(the verified host key,apiclient.KnownHostsLine) and finallyrunner.yaml(SaveConfig).runnerJoinprints the status; if it is notactiveit says an admin must approve. - Later
runner runcallsrunnerRun:runner.LoadConfig,keys.LoadSigner,actions.Load,audit.Open, thenrunner.New(cfg).Run(ctx). The runner connects as userrunner;serveRunneron central registers it on the first heartbeat (Server.registerthenRegistry.Register) with its current database status. - On central,
mirafleet central runner approve dev/build-1goesadminCLI.lifecycle(api.OpApprove)thencentral.AdminCallthen the admin socket (adminConnthenmethodTable.servethenhandleRunnerLifecycle) thenService.Lifecycle, which callsstore.SetRunnerStatus(status change plus audit in one transaction) andRegistry.SetStatus(so the live session can exec at once).
aarvee revokes dev/build-1 while an action is running on it:
mirafleet central runner revoke dev/build-1Look at: the tombstone and kick happen before the database commit, so nothing can slip through the gap.
- aarvee runs
central runner revoke dev/build-1. The CLI sendsrunner.lifecycle(oprevoke) over the admin socket. - Tombstone: build-1's id goes into the registry, so no new session can slip in during the commit.
- Kick: the session context is cancelled and the runner's SSH connection is closed.
- In-flight action cancelled: the runner kills the process group; the outcome row says
cancelled. - Commit:
status = revokedand the audit row are written in one transaction. - The runner redials. Auth finds a revoked key and refuses it: it never gets a session.
-
maincallscentralMain(admin.go); the first word is notinit/run, so it goes todefaultAdminCLI().run, thengroup, thenadminCLI.lifecycle(api.OpRevoke). It validates the reference withstore.ParseRefand callscentral.AdminCall(sock, api.MethodRunnerLifecycle, ...). -
AdminCalldials the unix socket<data>/admin.sock, writes one frame and waits. In central, theServeAdminaccept loop runscheckPeerfirst (same UID or the connection is dropped before anything is read), thenadminConnreads the request and callsmethodTable.serveonadminTable(), which reacheshandleRunnerLifecycleandService.Lifecycle. -
Service.Lifecyclecallsauthorize(..., adminOnly=true), loads the runner, and checks thatCanTransitionallows the move. Forrevokeonly, it then does, in this order:Registry.Tombstone(id)(future registrations are refused),Registry.Kick(id, "runner revoked")(session context cancelled with aKickError, connection closed), thenstore.SetRunnerStatuswhich commits the new status and therunner.revokeaudit row. - The in-flight
RunAction(in the operator's handler goroutine) is blocked inregistry.execOn. Its context was cancelled by the kick, soRegistry.Execreturnscontext.Cause(session ctx), a*registry.KickError.RunActionmatches it witherrors.As, writes the outcome rowcancelledwith messagerunner revoked, and returnsunavailable: runner revokedto the operator. - If
SetRunnerStatusfails,Lifecycleclears the tombstone, but only if a fresh read shows the runner is verifiably not revoked. If it cannot tell, it keeps the tombstone (fail closed). - The runner reconnects within seconds.
KeyAuth.AuthenticateseesStatusRevokedand returnsErrDenied; and even if it did not,Registry.Registerwould returnErrTombstoned.
Revoking an operator is the same shape: Service.RevokeOperator commits first, then calls
OperatorConns.KickOperator, which closes the SSH connection; the operator's handler context
dies with it, which cancels its in-flight action.run. The window between "authenticated" and
"added to OperatorConns" is closed by the re-check in serveOperator (step 7 above).
A build tag (or a file-name suffix such as _linux.go) tells the Go compiler to include a
file only on some platforms. mirafleet uses them for two reasons.
1. Server roles are Linux-only. Central and runner run on Linux servers; only mirafleet mcp also runs on macOS and Windows (a developer's laptop). The binary still builds for all six
targets (linux, darwin, windows times amd64, arm64), which scripts/dev.sh cross
checks.
| File | Tag | What it does |
|---|---|---|
cmd/mirafleet/platform_linux.go / platform_other.go
|
linux / !linux
|
serverSupported true or false; main refuses central and runner otherwise |
cmd/mirafleet/central_linux.go, server_linux.go, lock_linux.go
|
_linux suffix |
the real central init/run, runner join/run, flock
|
cmd/mirafleet/server_other.go |
!linux |
stubs returning central and runner are supported on linux only
|
internal/central/admin_unix.go |
unix |
unix socket with umask 077, checkPeer
|
internal/central/admin_peer_linux.go / _darwin.go
|
linux / darwin
|
read the peer's UID (SO_PEERCRED / LOCAL_PEERCRED) |
internal/central/admin_peer_other.go |
unix && !linux && !darwin |
rejects every peer |
internal/central/admin_other.go |
!unix |
every admin-socket function returns an error (fails closed) |
internal/keys/perm_unix.go |
unix |
refuse keys with group/other mode bits |
internal/keys/acl_windows.go, perm_windows.go
|
windows |
create directories and key files with a protected owner-only DACL; check it on load (M5) |
internal/keys/perm_other.go |
!unix && !windows |
refuse to load any key (no check is possible) |
internal/opconf/dir_windows.go / dir_other.go
|
windows / !windows
|
config and state dirs under %LocalAppData% / from os.UserConfigDir and os.UserCacheDir (M5) |
internal/actions/kill_unix.go / kill_other.go
|
unix / !unix
|
kill the whole process group / plain Kill
|
internal/store/sqlite/open_unix.go / open_other.go
|
unix / !unix
|
open with O_NOFOLLOW / without |
internal/workspace/ctrd/*_linux.go |
_linux suffix |
the whole containerd executor; only doc.go has no tag, so tools can still list the package on other systems |
internal/workspace/egress/netns_linux.go / netns_other.go
|
_linux / !linux
|
setns into a container's network namespace / an error |
internal/workspace/initproc/init_linux.go / init_other.go
|
_linux / !linux
|
PID 1 reaper / an error |
cmd/mirafleet/runner_ws_linux.go |
_linux suffix |
the only file that imports ctrd; server_other.go provides stubs elsewhere |
cmd/mirafleet/central_gui_linux.go |
_linux suffix |
the only file that imports internal/gui (M4); the -gui-* flags and startGUI exist only on Linux |
internal/gui/tlscert_unix.go / tlscert_other.go
|
unix / !unix
|
check that the operator's -gui-key is owned by central's uid and mode 0600 / fail closed: an operator key is refused (no check is possible) |
*_integration_linux_test.go, e2e_integration_linux_test.go
|
linux && integration |
tests that need a real containerd; run only by scripts/dev.sh integration
|
The pattern is fail closed: where a security check cannot be done on a platform, the code returns an error instead of silently skipping the check.
2. The darwin and windows binaries never link SQLite. modernc.org/sqlite is large. The
admin CLI in admin.go compiles on every platform and imports internal/central, but
internal/central only knows the store.Store interface. The only import of
store/sqlite in cmd/mirafleet is in central_linux.go. cmd/mirafleet/deps_test.go
proves it: TestNoSQLiteOnNonLinux runs go list -deps with GOOS=darwin and windows and
fails if any modernc.org/... or internal/store/sqlite package appears, and
TestLinuxLinksSQLite is the positive control (without it, a broken filter would let the first
test pass for the wrong reason). If you add an import of sqlite anywhere outside the
_linux.go files, that test fails.
3. The darwin and windows binaries never link containerd (M3). The containerd Go client pulls
in gRPC, protobuf and OpenTelemetry: tens of megabytes an operator's laptop would never use, and
code with its own licences to review. Only ctrd (Linux-only files) imports
github.com/containerd/containerd/v2, and only runner_ws_linux.go imports ctrd.
deps_test.go has the same two-test shape as for SQLite: TestNoContainerdOnNonLinux runs
go list -deps for GOOS=darwin and windows and fails on any github.com/containerd/... or
google.golang.org/grpc... package, and TestLinuxLinksContainerd is the positive control: it
checks that a Linux build does link them, so a broken filter cannot make the first test pass for
the wrong reason. The OpenSandbox executor (osb) and the egress proxy are pure stdlib and
compile everywhere, but are wired only on Linux, because only a Linux runner runs workspaces.
4. The orchestrator side links only what it needs (M5). TestOrchestratorDeps in
cmd/mirafleet/deps_test.go has three rules, checked for all six targets (linux, darwin and
windows, each on amd64 and arm64):
-
internal/orch,internal/mcpserverandintegrations/claude-code/hooknever linkinternal/service,internal/store,internal/central,internal/runner,internal/workspace/ctrd,modernc.org/*,github.com/containerd/*, gRPC or JWT packages. Why: these are the packages that run on a laptop at the request of an agent. If one linked the service layer, a tool handler could call it directly and skip the SSH boundary and its policy and audit; and the laptop binary would carry a database. -
The go-sdk is imported only from
internal/mcpserver's shipped code. The test lists every package's imports without test files and fails if anything else importsgithub.com/modelcontextprotocol/go-sdk. Test files are exempt on purpose:TestM5Done, ininternal/central, uses the SDK's client to drive the server, and tests never ship. - A positive control:
internal/mcpservermust link some go-sdk package. Without it, a broken filter would let both checks above pass for the wrong reason (the same trick asTestLinuxLinksSQLite). Every target package must also exist, so renaming one cannot silently disable the check.
Everything in the orchestrator packages must also build on Windows, which scripts/dev.sh cross
checks (compile and vet only) and the CI workflow actually tests on Windows and macOS
(chapter 9).
5. The GUI is wired in one Linux file and links no database code of its own (M4).
TestGUIDeps in cmd/mirafleet/deps_test.go lists what internal/gui imports (linux, darwin and
windows) and fails if it names internal/store/sqlite, internal/central,
internal/central/registry, internal/apiclient, internal/orch or internal/mcpserver. A
second pass over the whole dependency closure also rejects modernc.org/*, containerd and gRPC,
but allows registry there, because service legitimately uses it. Why: the GUI is a web
server that parses untrusted input from a browser. If it could reach the store, one handler bug
could skip the service's policy and audit. TestGUILinkedOnlyOnLinux is the other half: the
darwin and windows binaries must not link internal/gui at all, and the Linux binary must (the
positive control, same trick as TestLinuxLinksSQLite).
Each recipe lists the files in the order you should touch them. Always add the test in the same change.
Example: runners.get.
-
internal/api/api.go: addMethodRunnersGet, add it toIsOperatorMethod, addRunnersGetParams/RunnersGetResult.TestMethodSetsDisjointmust still pass. -
internal/policy/policy.go: add it to the operatorcaseinTablePolicy.Authorize. Forget this and every call returnsforbidden. -
internal/service/: add the method, starting withs.authorize(ctx, p, src, api.MethodRunnersGet, false). Validate input; uses.failfor store errors. -
internal/central/dispatch.go: writehandleRunnersGet(decode withapi.DecodeParams, call the service, map to the DTO) and add it tooperatorTable().handlers. -
internal/central/admin.go: if admins may use it too, add it toadminTable(). -
internal/apiclient/client.go: add a typed helper next toRunnersList. - Tests:
internal/service/service_test.go(policy and behaviour),internal/central/ api_test.go(end to end over SSH), and extend the method-set tests. - Docs: update chapter 7 and the CLI reference in chapter 10.
Example: mirafleet central fleet delete.
-
internal/api/api.go: addMethodFleetDelete, add it toIsAdminMethod(not to the operator set), add the DTOs. -
internal/service/: method that callss.authorize(..., true)(thetrueadds the direct admin-kind check on top of the method table and the policy). -
internal/central/admin_handlers.go: the handler; register it inadminTable()inadmin.go. -
cmd/mirafleet/admin.go: add a method onadminCLI(flags viac.flags, positional arguments viaadminParse/adminWantArgs), add it to the map inadminCLI.run. -
cmd/mirafleet/main.go: add a line to theusagetext. - Tests:
cmd/mirafleet/admin_test.go(argument parsing with the fakecall),internal/central/admin_test.go(TestAdminMethodsEndToEnd), service tests including "non-admin is forbidden and audited" (TestNonAdminForbiddenAndAudited).
-
internal/store/store.go: add the method to theStoreinterface with a doc comment that says which errors it returns and that it audits in the same transaction if it changes state. -
internal/store/sqlite/: implement it in the matching file. State changes use the writer pool inside a transaction that also inserts the audit row. - If the schema changes: add
internal/store/sqlite/migrations/0003_<name>.sql(0002isworkspaces, M3). Numbers must be contiguous and files are embedded automatically. Never edit0001_init.sqlor0002_workspaces.sqlafter they shipped; a deployed database has already run them.TestMigrationsContiguousguards the numbering; extendTestFreshMigrateAndReopeninsqlite_test.gofor new tables. -
internal/store/storetest/storetest.go: add a subtest to the conformance suite so every future store must behave the same. - Update any test double that implements
store.Storeby hand (most embedstore.Storeand override one method, so they keep compiling). - Update chapter 6.
Example: an env list.
-
internal/actions/actions.go: add the field with ayaml:"..."tag toActionorParamSpec.KnownFields(true)means a runner running an older binary will reject a file that uses the new field. That is intended, but mention it in release notes. - Validate it in
Parse(fail at load, never at run time). - Use it in
PlanorexecArgv. Keep the security properties: argv only, no shell, a parameter value only ever inside one argv element. - Tests in
internal/actions/actions_test.go, including an injection attempt. - Update the YAML reference in chapter 10 and the threat discussion in chapter 5.
Example: a Firecracker or Kubernetes executor. Everything above the interface (scheduling, sticky
sessions, the reaper, audit, policy, concurrent slots, the wire protocol) stays as it is.
- Read
internal/workspace/workspace.go(theExecutorcontract) andinternal/workspace/fake/fake.go(the smallest correct implementation). The contract in short:Createis idempotent on the id and cleans up after itself on failure;Destroyis idempotent (absent isnil);Execobeys the context (deadline = timeout, cancel = kill) and never writes to the caller's writers after it returns;Listreturns only this executor's own workspaces; errors wrap theworkspace.Err*sentinels so the runner can map them to result codes. - Create
internal/workspace/<name>/. Keep it pure stdlib if you can (the licence gate and the "ask before adding a dependency" rule apply). If it needs Linux-only code, use_linux.gofile names and adoc.gowithout a tag, exactly likectrd. -
Re-check the policy yourself. Treat the spec as untrusted: image against the allowlist
(
workspace.MatchImage) before pulling, paths throughworkspace.CleanPathand then a symlink-safe open, env throughworkspace.FilterEnv. The runner'spreparealready did this, but an executor is the last line of defence. -
internal/workspace/wsconfig/config.go: add the executor name to the constants and a config block with strict validation (fail closed, no insecure defaults). Add the block to thevalidateswitch and tests inconfig_test.go. -
cmd/mirafleet/runner_ws_linux.go: add acasetonewExecutor. This is the only wiring. -
internal/serviceand the store need no change except the executor name: add it to thestore.Executorconstants and to theCHECKlist offleet_workspace.executorin a new migration (aCHECKcannot be altered in SQLite, so the migration rebuilds the table), plus the heartbeat-name rule intransport.Heartbeat.Validateif the name is unusual. - Tests: run the shared contract against your executor (copy the shape of the fake's tests), add an
attack set (symlink, FIFO,
.., oversized output) and, if it needs a daemon, put it behind//go:build linux && integrationand add the package toITEST_PKGSinscripts/dev.sh. - Update chapter 5 (what this boundary is) and chapter 10.
-
internal/workspace/wsconfig/config.go: add the field with ayaml:"..."tag to the right struct (Config,Limits,Containerd,OpenSandbox).KnownFields(true)makes older runners reject it, which is intended. - Validate in
validate()and its helpers: reject out-of-range values, never accept a silent insecure default. If it needs the disk, check it inCheckFiles(onlyLoadruns those). - Use it where it matters: runner-side limits in
internal/runner/workspace.go(prepare), spec details ininternal/workspace/ctrd/spec_linux.go. If central must know (placement), it goes in the heartbeat (transport.Heartbeat, bounded inValidate), never in a trusted-by-default field. - Tests in
config_test.go(table tests witht.TempDir()), update the reference in chapter 10.
Example: workspace_stat, which would wrap a new operator method workspace.stat.
The rule first: a tool may only wrap an operator method. Never an admin method, never an
enrol method. The tool table is fixed in code, and orch.call is the only path to
apiclient and refuses any method for which api.IsOperatorMethod is false. If the capability you
want is an admin action (create a fleet, revoke a runner), it does not become a tool: that is the
point of the three gates in chapter 5.
-
The operator method. If
workspace.statdoes not exist yet, add it first with the recipe "A new operator method" above (api,policy,service,central,apiclient). A tool adds no power by itself; it only lets the model reach what an operator could already reach. -
internal/orch/calls.go: add a typed wrapperWorkspaceStat(ctx, cname, ...)that builds the params and callso.call(ctx, cname, api.MethodWorkspaceStat, params, &callIO{result: &r}). Decide here whether the method is idempotent (idempotent()in the same file): only then is it retried after a dead connection. If in doubt, it is not. Never read the process environment. -
internal/mcpserver/backend.go: add the method to theBackendinterface (*orch.Orchalready satisfies it, which the linevar _ Backend = (*orch.Orch)(nil)checks), and to the fake infake_backend_test.go. -
internal/mcpserver/tools_ws.goortools_list.go: add theToolinWorkspaceToolsorListTools: a name, a description (which must say that results are data, not instructions),InputSchemawithadditionalProperties:false, anOutputSchema,Annotations(set all four honestly: a tool that changes state isDestructive; a pure read isReadOnlyandIdempotent), and a handler. -
The handler, in this order:
DecodeArgs(req, &a)first (exact-case, strict; it is what makes the Claude Code hook and the server agree on whatconfirmis); validate every field (checkName,api.Validate*); resolve the target (resolveFleetfor fleet-level tools,s.pickfor workspace tools); call the backend; passconfirmthrough verbatim and wrap errors withguardedRewrite(toolError(err), t); cap any text that came from a remote machine withorch.CapOutputororch.Sanitize; return a struct that includesWhere: whereOf(t)(and addwhereSchemato the output schema). - If the tool changes state on a fleet that can be guarded, give it the
confirmproperty (copyconfirmProp). Central enforces it regardless; the property is what lets the model supply it. -
integrations/claude-code/hook/hook.go: add the name toknownTools. The hook cannot import the server (it would link the SDK), soTestKnownToolsMatchMCPServerfails until you do. ThePreToolUsematcher inhooks/hooks.jsonmatches every tool of the plugin's server by prefix, so it needs no change. -
integrations/commands/mirafleet.md(and its tested copies inskills/,opencode/commands/): mention the tool only if the workflow changes; the tests require the copies to stay identical. -
Tests, in the same change: a schema and annotation test (add the tool to the expected set in
TestListToolsSchemasAndAnnotationsorTestWSToolSet); a case inTestEveryToolRejectsMiscasedAndDuplicateKeys; argument-validation tests; a test that the result carrieswhere; for a state-changing tool,confirmpass-through.TestM5Doneasserts thattools/listreturns exactly the nine tools, so update that list on purpose. Run themcpserver,orchandintegrationstests andscripts/dev.sh cross. - Docs: the tool table in chapter 7, and
docs/ARCHITECTURE.md.
Example: a "Settings" page at /settings. Read handlers_workspaces.go and workspaces.html side
by side first; they are the smallest complete screen. Chapter 11
has the template checklist.
-
The service method. If the screen needs data or a change the service does not offer yet,
add it to
internal/servicefirst (with its audit row and its tests), exactly as for an operator method. The GUI never reads the store. -
internal/gui/backend.go: add the method toBackend.*service.Servicealready satisfies it if you added the method there; the compile-time assertion at the bottom checks. -
internal/gui/handlers_settings.go: aroutesSettings(mux adminMux)method that registers every route with a literal pattern:mux.HandleFunc("GET /settings", s.settingsPage). Usemux.Passive(...)only for a polled fragment. AddRegisterFlash(id, kind, format)calls in aninitfor the success messages. The handler isscreenAuth, then (for a POST)screenForm, then the backend call, thens.Render(...)ors.Redirect(...). -
internal/gui/routes.go: one line,s.routesSettings(am). Also add the screen's key tonavKeys(handlers_auth.go) and a link inui/nav-links(templates/partials.html). -
internal/gui/templates/settings.html:define "content"for the page anddefine "settings/..."for each fragment. The file name is the screen name passed toRender;newRendererpicks every*.htmlup, so nothing else registers it. -
Tests. You write the screen's own test (a
*_test.gousing the harness inhelpers_test.go). The rest comes free, because the security suite discovers routes by scanning the sources:TestSecurityAuthRequiredOnEveryRoute(anonymous gets a redirect to/login),TestSecurityCSRFOnEveryPost(a POST without a valid token is refused),TestSecurityHeadersAndCacheControlOnEveryResponseandTestSecurityPolledFragmentsArePassiveall pick the new routes up.TestTemplateLintSourcesandTestTemplateLintRenderedPagescheck the new template against the CSP-safe rules. A route that is registered some other way than with a literal pattern fails the route-count check, so no route can hide from the suite. - Docs: the routes table in chapter 7, and the screen list in chapter 10.
durga's agent runs a command in the workspace it opened earlier. This is the M3 counterpart of section 8.4; read them side by side. Watch for two things that are new: the body frame is read late, and the runner re-validates everything.
Look at: the start audit row is written before the runner is contacted; the runner trusts nothing central sent.
- durga's agent calls
workspace.exec(argvgo test ./...) throughmirafleet mcp. - One
api@frame arrives; the method table routes it toservice.ExecWorkspace. - Operator, ownership (
not_foundfor others), stateopen, argv, cwd, env (denylist), confirm and timeout are checked; then thestartaudit row is written FIRST. No row, no exec. -
registry.Workspaceopens aworkspace@mirafleetchannel on the runner's own SSH connection; the op is JSON in the channel-open data, any stdin follows as raw bytes. - The runner re-validates argv, cwd, env (its
env_allowplus the denylist) and the timeout. Central is not trusted. - The command runs inside the container as an unprivileged user, with no shell. Output is captured head and tail, trimmed to the budget; timeout or cancel sends SIGKILL.
- The runner writes one result frame: exit code, stdout, stderr,
truncated,timed_out. - Central writes the
outcomeaudit row (samerequest_id) and replies to durga.
mirafleet mcp api workspace.exec '{"workspace":"3f9a6c1e5b7d4820a1c3e5f708192a4b","argv":["go","test","./..."],"cwd":"src","env":{"CI":"1"},"timeout_s":300}'On durga's laptop (cmd/mirafleet/mcp_api.go, internal/apiclient/client.go)
-
mcpAPIparsesMETHOD [JSON] [-in FILE] [-out FILE]. Forworkspace.exec,orch.CallLimitcomputes the client deadline:timeout_splus a 30 s margin, and whentimeout_sis absent the server's 24 h ceiling plus the margin (the client cannot see the fleet's default; the server enforces the real one). With-in FILE, the file becomes the body and"stdin":trueis added. -
apiclient.Client.CallBodyopens anapi@mirafleetchannel, writes the request frame (api.WriteFrame) and, if there is a body, immediately a body frame (api.WriteBody), then reads the response frame.
On central (internal/central)
-
Server.serveAPIChannelreads the request withapi.ReadRequestTimeout(10 s, 64 KiB), makes a per-callcallBody{r: ch, closer: ch}and callstable.serve.takesBody("workspace.exec")is true, so nothing drains the channel yet. -
methodTable.servechecksallowed(api.IsOperatorMethod) and findshandleWorkspaceExecinworkspace_handlers.go. It decodes params strictly (api.DecodeParams) and, ifstdinis true, wraps the channel in alazyStdin. The handler callsService.ExecWorkspace.
In the service (internal/service/workspace_ops.go), in this order:
-
wsTarget:requireOperator(policy: the operator must beactivenow; kind must be operator),ownedWorkspace(not the owner, or an unknown or malformed id:not_found), state must beopen(elseconflict), then the fleet and itsWorkspaceConfig. - Input:
api.ValidateArgv,workspace.CleanPath(cwd),workspace.FilterEnv(shape and the hard denylist: a refusal is audited asdenied, naming the variable, never the value), confirm on a guarded fleet, the effective timeout (api.WorkspaceExecTimeoutfromtimeout_sand the fleet'sexec_defaultandexec_max). -
Only now is the stdin body read:
lazyStdin.Bodycallsapi.ReadBodyTimeout(1 MiB max, 30 s). A caller who failed any earlier check never made central buffer a byte. -
newRequestID, thenstartRow: thestartaudit row (argv JSON clipped to 4 KiB, cwd, env names, stdin byte count, timeout). If the write fails the call returnsunavailable: audit unavailableand nothing runs. Thentouch(activity for the idle reaper) andbeginOp(marks the workspace busy so the reaper never idle-closes it mid-command).
Central to the runner (internal/central/registry)
-
registry.Workspacelooks up the live session by runner id, applies per-op status gating (disabledandpendingrefuse an exec) and callsworkspaceOn:transport.EncodeWorkspaceRequest(validated JSON),OpenChannel("workspace@mirafleet", payload),transport.WriteBodyfor stdin (exactlystdin_lenraw bytes, thenCloseWrite), thentransport.ReadResult. The caller's context bounds all of it (exec timeout plusexecMargin, 15 s), and aKick(revoke) cancels it.
On the runner (internal/runner/workspace.go)
-
Runner.serveWorkspacedecodes the open data (transport.DecodeWorkspaceRequest, strict).wsState.preparere-validates everything against the runner'sworkspace.yaml: argv, cwd, env againstenv_allowand the denylist, stdin size, the timeout capped bylimits.exec_max. A refusal comes back as a normal result frame (code: refused). -
wsState.admittakes a runner-wide permit and one of the workspace's 4 exec permits before accepting the channel. None free:Reject(ResourceShortage), which central reports asrunner busy. Thennch.Accept, a runner-side auditstartline, the body is read (60 s timer) andrunWScallsrunExec. -
runExecmakes twoworkspace.NewCapturebuffers (head and tail, half the budget each) and callsExecutor.Execwith a context that expires at the timeout. The runner also watches the channel: central closing it cancels the context.
In the container (internal/workspace/ctrd/exec_linux.go)
-
Executor.Execre-validates argv and cwd (a second time, because the executor is the last line), adds the proxy variables if the workspace has egress, loads the container and its running task, and builds the process from the container's own spec (execProcessSpec: uid 1000, no capabilities, no_new_privs, cwd under/workspace). It creates the exec with containerd FIFOs wired to the capture buffers and waits for the exit. On timeout or cancel,killTreesends SIGKILL to the exec and its descendants. A command that cannot start gives exit 127 or 126 with the reason on stderr, like a shell. There is no shell:argv[0]is run as given.
Back up the chain
-
runExecbuilds aWorkspaceResult(exit_code, trimmedstdoutandstderr,truncated,timed_out); the runner writes its outcome audit line, then one frame withtransport.WriteResult, thenCloseWrite. - In the service,
classifymaps transport problems to API errors and audit outcomes; a normal result becomesapi.WorkspaceExecResult. Theoutcomeaudit row (ok,error,cancelledortimeout, samerequest_id, exit code, duration) is written withrecordBestEffort: a failure here is only logged, because the command already ran.touchagain. -
writeResponseBodyTimeoutwrites the response frame and closes the channel. The client prints it.
The same skeleton serves workspace.read_file (the result frame, then the body frame) and
workspace.write_file (body read late, SHA-256 verified in the service before the start row).
workspace.open has a different shape, because it has to choose a runner first:
Look at: the unique index makes the second open of s1 return the same workspace.
- durga's agent calls
workspace.open(fleetdev, sessions1) throughmirafleet mcp. - The
api@frame reachesservice.OpenWorkspace: active operator, workspace-mode fleet, image on the allowlist,confirmon a guarded fleet, valid session id. - Sticky reuse: a live workspace for (durga,
dev,s1) is returned withreused:true. If its runner is offline the answer isunavailable; a fresh workspace is never created elsewhere. - Placement: active, online runners whose executor, trusted labels and image patterns fit, with free slots (heartbeat slots minus live rows). The most free slots wins, random tie-break.
-
ReserveWorkspacerecounts the slots in one transaction and inserts theopeningrow with the start audit row. - A full runner (
ErrFull) or a busy one moves to the next candidate (3 tries at most). Otherwise central sends opcreateonworkspace@mirafleet. - The runner re-validates the spec against its own
workspace.yaml, builds the container spec from its fixed template, pulls the image if needed and creates the container. - The row becomes
open, the outcome audit row is written and the reply saysreused:false.
The code for that picture: OpenWorkspace (checks, sticky reuse, the 3-try loop),
candidates in workspace_sched.go (the filters and the sort), Store.ReserveWorkspace in
store/sqlite/workspaces.go (the transaction), registry.Workspace with op create, then
wsState.prepare/admit and ctrd.Executor.Create on the runner (allowlist re-check, pull,
buildSpec, user-namespace id range for the slot, egress listener).
Section 8.9 started at mirafleet mcp api, the hand-driven way in. This is the same command from
the real front door: Claude Code, with the plugin installed, running in durga's project. The
model has decided to call the exec tool with {"command":"go test ./..."}. The project's
.mirafleet.yaml says fleet: dev; durga's contexts.yaml has one context, work, pointing at
central.example.com:2222. No workspace is open yet.
-
Harness. Claude Code asks its tool-approval prompt (and the plugin's
PreToolUsehook runs:hook.preToolUsereads the call, finds noconfirm, prints nothing). It then writes one JSON-RPC line to the stdin ofmirafleet mcp:{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"exec","arguments":{"command":"go test ./..."}}}.
In the MCP server (internal/mcpserver)
- The go-sdk reads the line and calls the handler registered by
newServerthroughwrap(server.go).wrapchecks the arguments are a JSON object, starts the progress ticker if the request has aprogressToken, and runssafeCall, which recovers panics. -
safeCallcallswsState.exec(tools_ws.go). It runsDecodeArgs(strict, exact-case), enforces exactly one ofcommandorargv(commandbecomes["/bin/sh","-c","go test ./..."]) and validates argv,cwd,env,timeout_sandstdinwith the sameapi.Validate*functions central uses. -
wsState.pickchooses the target and the workspace.resolveFleetcallsBackend.Resolve(orch.Resolve, below) and gets contextwork(only context) and fleetdev(project file).Backend.SessionForreturns the session: no-sessionflag and no handoff file, so with Claude Code the hook'scc:<session_id>, otherwise a randomp:<32 hex>. There is no binding for (work,dev, session), so this is an implicit open, allowed only becausedevis not guarded:pickcallsFleetsListto check, thenWorkspaceOpen(each goes through steps 7 to 9 below, with its own method), and remembers the workspace id inwsState.
In the orchestrator (internal/orch)
-
orch.Resolvere-readscontexts.yamland.mirafleet.yaml(opconf.LoadContexts,opconf.LoadProject) on every call, applies the precedence argument, flag, project file, context default, and returns aTargetthat records where each value came from. If the fleet had come from the project file and were guarded,Resolvewould refuse it here. -
Orch.WorkspaceExecre-checksenvwithapi.ValidateEnv, caps stdin at 1 MiB, setsStdintrue when there is any, and callsOrch.call. -
callis the choke point. It refuses any method that is not an operator method; finds the context incontexts.yaml; takes the context's connection pool; sets the deadline (CallLimit:timeout_splus 30 s, or the 24 h ceiling plus 30 s when none was given); and waits for one of the 8 channel slots. -
pool.getreturns the live SSH connection or dials one.pool.connectfirst requires a non-emptyknown_hostsand a key file (elseErrNotSetUp: "runmirafleet mcp login ...", and nothing is dialled), loads the operator key (keys.LoadSigner, which checks the file's permissions or Windows DACL), builds the host-key callback fromknown_hosts(apiclient.KnownHosts: pinned or refused, no trust on first use) and callsapiclient.Dialas SSH useroperator, then sayshelloand checks the protocol version. -
invokesends the request:Client.CallBodyopens anapi@mirafleetchannel and writes the request frame and, because there is stdin, a body frame. From here the path is exactly 8.9, from step 3 on: the method table,service.ExecWorkspace, the start audit row, the runner, the container, the outcome audit row, the reply frame. If the connection is dead,calldrops it and redials only for idempotent methods;workspace.execis not one, so the model getsunavailable: the connection to central was lost; the call may or may not have completed, never a silent re-run ofgo test(or worse, ofrm).
Back in the MCP server
- The result is
api.WorkspaceExecResult.execruns it throughorch.CapOutputwith the output cap (30 KiB by default): sanitises, keeps head and tail with a[mirafleet: N bytes omitted]marker if needed. It buildsexecOut, which includesworkspaceandwhere. -
toResultJSON-encodes it once and returns it asstructuredContentplus one text item. If any step above had failed,errResultwould produce anisErrorresult with the code and a safe message instead, andguardedRewritewould have turned central's "requires confirm" into "ask the user" text. - The SDK writes one JSON line to stdout. Claude Code shows the tool result to the model. Nothing
else was ever printed on stdout. On the other side, central's audit log has the
startandoutcomerows with durga as the operator: it cannot tell (and does not need to tell) that the command came from an agent rather than frommirafleet mcp api.
What to look at first when debugging: mirafleet mcp context list and the where in the result
(step 5), the stderr of mirafleet mcp (Claude Code's /mcp panel or --debug; step 8 errors),
then central's audit log (steps 9 onwards). Chapter 10
has the symptom table.
aarvee opens https://central.example.com:8443/runners/dev/build-1, clicks Revoke, types
dev/build-1 and confirms. This is the same revoke as section 8.6, entered through a browser.
Look at: the four gates in the middle column. The service is only called when all of them pass, and from there on the path is the one of 8.6.
- aarvee types dev/build-1 on the revoke page and submits: POST /runners/dev/build-1/revoke.
- Middleware: the Host must be allowed, the body a urlencoded form under 64 KiB (421, 415, 413).
- Session: the cookie's hash finds a live row of the active admin, else 303 to /login.
- CSRF: same-origin headers, then the
_csrftoken must match the cookie's key (403). - The typed name must equal dev/build-1 (422), then
Service.Lifecycleruns with sourcegui. - Same path as the CLI: tombstone, kick, cancel, one commit with the audit row. Then 303 back.
- The Revoke button is a link to
GET /runners/{fleet}/{runner}/revoke.runnerRevokeFormfinds the runner withfindRunner(which callsBackend.ListRunnersAll) and renders therunners/revokefragment: a red dialog, a hidden_csrffield and a text field namedconfirm. The form posts to/runners/dev/build-1/revoke, which matches the patternPOST /runners/{fleet}/{runner}/{op}. -
buildHandler(middleware.go) runs first for every request. It sets the security headers, thenhostGuard.allowed(r.Host)(a name that is not on the list gets421and the request goes no further), then takes a slot in the in-flight semaphore (503when 32 are busy), thencheckRequest(urlencoded only, body wrapped inhttp.MaxBytesReader), then looks up the mux pattern and sets the request timeout. - The mux hands the request to the handler that
adminMux.HandleFuncwrapped inrequireAdmin. It callsauthenticate:SessionToken(r)reads the__Host-mf_sessioncookie, andBackend.GUIAuthenticate(ctx, r.RemoteAddr, token, passive=false)reachesService.GUIAuthenticate. That hashes the token with SHA-256, loads the session row joined to the active admin (store.GetGUISession), and checks the admin's credential generation, the 30-minute idle limit and the 12-hour absolute limit. A dead row is deleted and the request is redirected to/login. A live one gets a throttledlast_activetouch (at most once a minute) and yieldsauth.GUIAdmin(username, remote), whichWithSessionputs in the request context. -
runnerOpcallsscreenAuth(reads that principal back and derives the CSRF key from the cookie withCSRFKey) and thenscreenForm:ParseFormreads the body, thenCSRF.Checkruns two layers. The first is Go'shttp.CrossOriginProtection(it refuses a request whoseSec-Fetch-SiteorOriginsays it came from another site). The second compares the_csrffield withFormToken(key)in constant time. Either failure is403and nothing has changed. -
opis checked againstapprove,disable,enable,revoke. Forrevokethe handler compares the trimmedconfirmfield withfleet/runnerexactly. A mismatch re-renders the dialog with status422and the error text; the typed text is shown back as plain text (inertRunnerText). Then it callsBackend.Lifecycle(ctx, principal, service.SourceGUI, "dev/build-1", "revoke"). -
Service.Lifecycleis the function of section 8.6:authorizewithadminOnly=true(policy plus the direct kind check, so the GUI principal needsKind == KindAdmin),Registry.Tombstone,Registry.Kick, thenSetRunnerStatuswith therunner.revokeaudit row in the same transaction. The only differences from the CLI are in the row:sourceisgui,actoris aarvee's GUI username, andremoteis the browser's address. -
s.Redirect(w, r, "/runners/dev/build-1", "runner.revoke", "dev/build-1")sets the__Host-mf_flashcookie (a message id and the subject, signed so a page cannot forge one) and answers303. The browser fetches the detail page,takeFlashshows "Runner dev/build-1 revoked." once, and the page shows the runner asrevoked.
Why the order matters: nothing before step 6 changes state, so any refusal (wrong Host, expired session, forged form, mistyped name) leaves the fleet exactly as it was and writes no audit row of a change. And because step 6 is the CLI's function, a bug in the revoke itself would show up in both places, not only in the browser.
Everything in this section is about getting the binary to users, not about what it does. Almost
none of it is Go code that ends up in mirafleet: it is scripts, config files and one separate
tool. The map of new directories:
| Path | What it is |
|---|---|
tools/relgen/ |
A separate package main (stdlib only, never linked into mirafleet) that keeps release files in step with the tag and renders generated files. |
scripts/release.sh, scripts/release/*
|
The release test and build targets. Like dev.sh, every step runs in a digest-pinned container. |
.goreleaser.yaml |
The build, archive, package, checksum, SBOM and signing recipe. |
packaging/ |
What goes inside the Linux packages: systemd/ units (the system units, the mirafleet-runner@.service template for host mode, and systemd/user/mirafleet-runner.service), env/ files, scripts/ (maintainer scripts), examples/ (actions.yaml, workspace.yaml, workspace-host.yaml), oci/Dockerfile. |
deploy/compose/ |
The Compose files (central/, runner/, lab/). |
npm/ |
Templates for the npm wrapper and platform packages. |
scripts/install.sh, scripts/install.ps1
|
The curl-style installers. |
internal/protover/ |
The protocol-level rule (section 7.15). |
.github/workflows/ |
gate.yml and ci.yml (checks), orchestrator.yml (Windows, macOS), dco.yml, release.yml (publishing). |
Why a separate tool and not a shell script? The jobs are text surgery with exact rules (change a version in four files, render a formula from a checksum list), and Go lets us write golden-file tests for them. Why stdlib only? It runs in CI with release permissions, and the fewer dependencies it has, the less there is to trust. It does not shell out and edits JSON by decoding into structs and encoding again, so a stray character cannot corrupt a file.
main.go holds a registry: each subcommand lives in its own file and calls register from
init(). Two people adding commands never edit the same file. Run it with
scripts/dev.sh go run ./tools/relgen <command>.
| Command | File | What it does |
|---|---|---|
bump X.Y.Z |
bump.go |
Sets the version in every versioned file at once: the plugin manifest, pluginVersion in cmd/mirafleet/mcp_hook.go, the marketplace ref, server.json, the Compose image tags and protover.Current (see compose.go). |
check vX.Y.Z |
check.go |
Fails unless every one of those files agrees with the tag. release.yml's verify job and release.sh m6check both run it. |
licenses |
licenses.go |
Joins go-licenses save output and licenses/extra/ into THIRD_PARTY_LICENSES.txt. |
npm |
npm.go |
Generates the 7 npm packages from the release archives, checking each archive against checksums.txt first. npmfixture writes stand-in archives for tests. |
brew |
brew.go |
Renders Formula/mirafleet.rb from checksums.txt. |
serverjson |
serverjson.go |
Sets the version fields of server.json from the tag. |
wiki |
wiki.go |
Turns docs/guide and the quickstart into wiki pages: renames files, rewrites relative links, copies diagrams, adds Home and _Sidebar and a "generated from docs/ at COMMIT" banner. Output only; it never pushes. |
harness |
harness.go |
Fails when a harness's command copy drifts from integrations/commands/mirafleet.md. |
Why does check exist when bump exists? A person can edit one file by hand and forget the
others. check is the tripwire that stops a release with a plugin saying 0.5.0 and a binary
saying 0.6.0.
A POSIX shell script with one target per call, like dev.sh. It uses the same pinned Go image
as dev.sh (a relgen test compares the two) so a "works in release, not in dev" difference cannot
creep in. The targets, in the order m6check runs them after the normal gate:
vuln (govulncheck), lint-sh (shellcheck), lint-actions (actionlint), snapshot, relgen
(the check above), pkgtest, installtest, image, lab, npmtest, harnesscheck. Helpers
are licenses-report, stage (collects the documents that go into archives) and clean
(removes dist/ and everything labelled org.mirastacklabs.mirafleet.release=1). Chapter 9
(9.16) says what each proves.
goreleaser is the open-source release builder. One config produces, from one commit:
-
builds:
CGO_ENABLED=0,-trimpath,-ldflags "-s -w -X main.version={{.Version}}", a fixed file time from the commit (mod_timestamp), for the six OS and CPU targets; -
archives:
mirafleet_<version>_<os>_<arch>.tar.gz(zip on Windows) containing the binary and the licence and quickstart documents; -
packages (
nfpms):.deb,.rpm,.apk, built by nFPM, with the files and maintainer scripts frompackaging/; -
checksums.txt(SHA-256), SBOMs (one per archive and package, from syft), and a keyless cosign signature ofchecksums.txt(a.sigstore.jsonbundle); - a draft GitHub release (
draft: true, pre-release detected from the tag).
What it does not do is publish images, the Homebrew formula or npm. Those are separate jobs in
release.yml, each with its own credential and its own human approval, so the tool that builds
never holds a publishing secret. The tools (goreleaser, syft, cosign, nFPM) come from
scripts/release/tools.Dockerfile, every FROM pinned by tag and digest. The local snapshot
target runs goreleaser with signing and publishing skipped.
npm/mirafleet/ is the template of the package @mirastacklabs/mirafleet; npm/platform/ is the
template of the six per-platform packages (@mirastacklabs/mirafleet-<os>-<cpu>). The wrapper
has no dependencies but lists the six platform packages as exact optionalDependencies. Each
platform package declares os and cpu, so npm installs only the one that fits the machine.
bin/mirafleet.js finds that package, starts its binary with the same arguments and
stdio: "inherit", forwards signals and exits with the child's exit code. It never writes to
stdout (the MCP protocol owns stdout) and has no lifecycle scripts and no download step; that is
what npmtest asserts. Neither template carries a version: relgen npm fills it in.
M7 adds a second kind of workspace. Instead of a container, the host executor runs tool calls
directly on the runner's VM as the runner's own unprivileged user, and central stores credentials
for it. Read chapter 7, section 7.16
for the wire view first. The new code sits next to ctrd and osb and implements the same
workspace.Executor interface, so sessions, placement, ownership, audit and the reaper are the
M3 code, unchanged.
Caption: follow one session from open (top row) to cleanup (bottom row); the directory outlives every step except the last.
- The agent calls
workspace_open; the session id (cc:abc) comes from the hook, never a path. - Central refuses a runner another operator holds, and a runner lacking a requested credential.
- The runner creates
<root>/sessions/<slug>(0700) and a session record in its state directory. - It starts the session's ssh-agent socket (0600) and HTTPS broker and sets the tool environment.
- Bash, background jobs and file tools run as the runner's own user; the cwd persists.
-
workspace_closekills the process groups and closes the socket and broker; the directory stays. - Opening the same session id again, or restarting the runner, re-adopts the directory and jobs.
- Only the sweep,
runner host prune,workspace.kill -deleteorworkspace_close {delete:true}delete it.
internal/secrets central only: AES-256-GCM seal/open, key from env, key check, rekey
internal/service/credentials.go central: set/list/assign/delete/rotate, delivery, placement filter
internal/service/{fsdispatch,jobs}.go central: workspace.fs / job_* / output_read dispatch
internal/runner/creds.go runner: the in-memory credential holder (atomic swap)
internal/runner/hostops.go runner: per-session wiring (agent socket, broker, env, ssh_config)
internal/runner/events.go runner: aggregated credential.use events to central
internal/workspace/hostx runner: the host executor (Linux only; doc_other.go elsewhere)
internal/workspace/fsops pure Go file tools (no OS-specific code)
internal/workspace/sshagent restricted ssh-agent
internal/workspace/broker HTTPS credential broker (local TLS-terminating proxy)
cmd/mirafleet/host_shim_linux.go the job supervisor: `mirafleet host-shim job`
packaging/systemd/ the two unit files
Why service does not import secrets: internal/service talks to a small KeyRing
interface (Seal, Open, Check, VerifyCheck). cmd/mirafleet/central_secrets_linux.go
adapts the real key to it. The deps_test in cmd/mirafleet then proves the orchestrator
binaries (macOS, Windows) never link hostx, secrets, broker or sshagent: the laptop
build cannot even contain the code that handles secrets.
Seal(key, plaintext, aad) produces version | key id | nonce | ciphertext+tag. The nonce is 12
random bytes per value (never reused under one key). The additional authenticated data (AAD) is
the credential id plus its version: a sealed value copied onto another row, or an old version
replayed, fails to open. A Key prints as secrets.Key{redacted} even with %#v, so a stray log
line cannot leak it. Central stores only a key check value (an HMAC of a constant under the
key) so that at start-up it can say "wrong key" instead of failing on the first credential.
Rekey opens with the old key and seals with the new one; central secrets rekey does all rows in
one SQLite transaction.
| File | What it does |
|---|---|
harden_linux.go |
Harden: prctl(PR_SET_DUMPABLE, 0) first (so a same-user process cannot read the runner's memory through ptrace or /proc/<pid>/mem), RLIMIT_CORE 0, refuse uid 0, refuse any effective capability, refuse a state dir that is not private to the user. Runs before any secret is loaded. |
xdg.go |
Paths: config, state and data directories from the XDG variables, with ~/.config, ~/.local/state, ~/.local/share as defaults. A relative XDG value is ignored (as the XDG spec says). |
sessions.go |
Manager: the session directories. OpenFor(sessionID, workspaceID, workdir) creates or reattaches; metadata is a JSON file per session in the state dir; Slug turns the session id into a safe directory name. Close keeps the directory; Delete removes it. |
sweep.go |
Sweep (daily): delete session directories unused for delete_after; Prune: the same on demand (runner host prune). Never touches a shared workdir, never a busy session. |
exec_linux.go |
Engine: foreground Bash, the clean child environment (childEnv), cwd persistence, per-exec output files, process-group kill. |
job_linux.go, shim_linux.go
|
Background jobs: Engine starts mirafleet host-shim job, which supervises the command in its own process group and writes status.json, stdout and stderr under jobs/<id>/; after a runner restart Adopt re-reads them. |
files.go |
Files: the file tools for one directory: wraps fsops, optionally delegates grep to rg. |
executor_linux.go |
Executor: implements workspace.Executor plus the extra interfaces in internal/runner/hostops.go (BashExecutor, FSExecutor, JobExecutor, SessionHooks, DestroyDeleter). |
Two design rules are worth understanding:
-
Children are not the runner.
execveresets the dumpable flag, so a command the agent runs is an ordinary process of the same user that canptraceits siblings, as on any laptop. The runner is the one non-dumpable process, and it is where the secrets are. The child's environment is built from nothing (childEnv): onlyHOME USER LOGNAME PATH LANG, the names inenv_allow, and the tool variables the runner sets for that session (SSH_AUTH_SOCK,GIT_SSH_COMMAND, the proxy and CA variables). Only fds 0 to 2 (plus fd 3 for the cwd report) reach a child. -
Close never deletes. A developer expects
git statusto be the same tomorrow. Deleting is explicit (delete: true,prune, or the 30-day sweep).
The file tools are not confined (as built, fsops/root.go, osRoot: plain OS calls). They run
as the runner's OS user, which is the boundary, as with local Claude Code. An absolute path works
anywhere that user can read or write; a relative path resolves from the session directory (or the
workdir, fsops.Open). Paths in results are shown relative inside that start directory and
absolute outside it; Grep and Glob echo the path in the form the caller gave. Anything that is not
a regular file (FIFO, device, socket) is refused before and after open, with O_NONBLOCK, so a
planted FIFO cannot hang the runner. Bash is not confined either. os.Root is used only by the
container executor (ctrd/files_linux.go).
No goroutines of its own, no network, no OS-specific code except one O_NONBLOCK open flag
(open_unix.go, open_other.go). It implements Read, Write, Edit, MultiEdit,
NotebookEdit, LS, Stat, Glob and Grep with Claude Code's semantics and error messages
(edit.go, read.go, notebook.go, grep*.go, glob.go, gitignore.go). Notable choices:
-
Not a regular file means refused. A FIFO or device planted in the repo would hang a
blocking
open;fsopsopens non-blocking and checks the file type before and after. - Atomic writes: write a temp file, then rename, keeping the mode.
-
Editneeds a unique match unlessreplace_all, because an ambiguous edit is the classic way a model changes the wrong line.MultiEditapplies in order and is all-or-nothing. -
Binary detection: a NUL byte or more than 5% control bytes in the first 8 KiB; Latin-1 text
is still text.
Globincludes hidden files but never enters.git, and honours.gitignore,.ignoreand.rgignore. -
Tests: golden fixtures under
testdata/and fuzz tests (fuzz_test.go), so the rg-compatible behaviour is pinned.
An SSH agent is a small server that holds private keys and signs challenges, so the key never
leaves it. This one (agent.go, userauth.go, serve.go) answers only List and Sign, signs
only an SSH user authentication request for the credential's user (it parses the signed blob
itself, userauth.go; the parser has a fuzz test), and with host binding on (the default) it
requires the client's session-bind@openssh.com message and signs only if the server host key is
in the credential's pinned known_hosts. Add, remove, lock and export are refused. It listens on
<session state dir>/agent.sock (0600 in a 0700 directory) and checks the peer's uid with
SO_PEERCRED (peercred_linux.go; on other systems it refuses everyone). Without host binding a
tricked client could ask the agent to sign for an attacker's server. OpenSSH older than 8.9 does
not send the bind message; set host_binding off for that credential and accept the weaker rule.
The broker is a local forward proxy on 127.0.0.1. For each session the runner starts one and
gives the session's tools HTTPS_PROXY with a per-session proxy password (other users on the VM
share loopback; the password keeps them off this broker). For a host with no credential the broker
just tunnels (CONNECT). For a credential host it terminates TLS with a certificate from a
per-session CA (ca.go: ECDSA P-256, key in memory only, NameConstraints limited to that
session's credential hosts, so even a stolen CA key could not mint a certificate for any other
site), checks that the SNI matches the CONNECT host, connects upstream with real verification
(system roots plus the optional corporate CA), replaces the client's auth header with the injected
one (cred.go: basic, bearer, header) and never follows redirects. For a registry
credential (registry.go) it answers the 401 Bearer challenge itself: it fetches a token from the
realm with the stored user and password, caches it per scope, and retries, so docker pull-style
clients never see a JWT. The CA certificate is appended to the VM's bundle at <state>/ca.pem and
announced to common tools through SSL_CERT_FILE, GIT_SSL_CAINFO, CURL_CA_BUNDLE,
REQUESTS_CA_BUNDLE, PIP_CERT, NODE_EXTRA_CA_CERTS and JAVA_TOOL_OPTIONS.
The Credential type prints as credential(name) under every formatter, so a log line cannot
leak the secret.
internal/runner/creds.go holds the set delivered by creds_sync (an atomic replace, so an
unassigned credential stops working at once and a rotated one is used on the next request).
hostops.go (devMgr) wires each session: it starts the agent and the broker, writes the
ssh_config (pinned known_hosts, IdentitiesOnly, IdentityAgent), sets
GIT_SSH_COMMAND="ssh -F <state>/ssh_config", and on close tears them down but keeps the files.
events.go aggregates credential.use records into 60-second windows for central.
Caption: the value moves left to right once, from central to runner memory, and never reaches the agent.
- aarvee runs
central credential set gl-token < file; central seals the value (AES-256-GCM). - aarvee assigns it to a runner or a whole fleet; a runner gets the union of both.
- Central pushes the set with
creds_syncover the runner's own SSH connection; the runner keeps it in memory only. - At session open the runner starts a restricted ssh-agent and an HTTPS broker for that session.
-
gitover SSH: the agent signs. Over HTTPS: the broker adds the header on credential hosts only. - Each use is logged on the runner and sent to central as aggregated
credential.useevents. - aarvee replaces the value, or central rotates an opted-in GitLab token itself.
-
creds_syncagain: the runner swaps the set atomically and the new value is used at once.
-
internal/mcpserver/tools_fs.goandtools_bash.go: the fifteen M7 tools (schemas, hints, handlers).server.go'sneutralizeis applied to every result and error. -
internal/orch/devws.go: typed calls (WorkspaceFS,JobStart,JobTail,OutputRead, ...).internal/orch/transfer.go:upload/downloadconfinement withos.OpenRoot. -
internal/opconf/project.go:.mirafleet.yamlgainsremoteandworkdir. -
integrations/claude-code: the skill text and thePreToolUsedeny hook for remote projects.
The runner's own enrolment key must stay on disk so the runner can reconnect, and the agent runs
as the same user, so a determined agent could read that key, connect to central as this runner
and receive its assigned secrets. M7 accepts this gap (a better answer needs a second user or a
hardware key, which is enterprise scope) and records a runner.replaced audit row when a newer
connection takes over (the GUI audit page shows it; there is no separate flag). Root on the VM can
read anything. See chapter 5.
A foreground bash call from the model to the VM and back, then the follow-up that pages its
output. It repeats the shape of 8.10 and
8.9; only the differences are spelled out.
sequenceDiagram
participant H as Harness (Claude Code)
participant M as mcpserver (tools_bash.go)
participant O as orch
participant C as central (service)
participant R as runner (runBash)
participant X as hostx.Engine
H->>M: tools/call bash {command: "go build ./..."}
M->>M: DecodeArgs, timeout 120, argv = [bash, -lc, command]
M->>O: WorkspaceExec(ctx, params)
O->>C: api@ workspace.exec (argv, timeout_s)
C->>C: ownership, state, confirm, start audit row
C->>R: workspace@ op exec
R->>R: argv is [bash -lc X], no stdin/env/cwd: BashExecutor
R->>X: Executor.Bash(id, X, timeout, requestID)
X->>X: childEnv, open out/Ref, run, read cwd from fd 3
X-->>R: WorkspaceExec{exit, stdout, stderr, Ref, byte counts, Omitted, Cwd}
R-->>C: result frame
C->>C: outcome audit row (same request_id)
C-->>O: WorkspaceExecResult
O-->>M: result
M->>M: scrub tags, CapOutput 30 KiB, note with ref
M-->>H: structuredContent + text (neutralised)
H->>M: tools/call read_output {ref, tail_lines: 50}
M->>C: workspace.output_read {ref, tail_lines}
C->>R: workspace@ op output_read
R->>X: OutputRead -> reads out/Ref from disk
X-->>H: page: content, next_offset, eof (via the same path back)
-
mcpserver.(*wsState).bash(internal/mcpserver/tools_bash.go) decodes the arguments strictly (DecodeArgs), checkstimeout_s(0 to 600; 0 means 120) and builds the argv["bash","-lc",command]. Withrun_in_backgroundit takes the other branch,bashBackground, which sendsworkspace.job_startinstead. It then callss.pickto find this session's workspace (opening one on an unguarded default fleet if there is none) ands.b.WorkspaceExec.confirmis passed through verbatim. -
orchandcentralare exactly theworkspace.execpath of 8.9:service.ExecWorkspacevalidates, writes the start audit row first, and opens aworkspace@channel to the runner. There is no new method for foregroundbash: that is deliberate, because it means ownership, guardedconfirmand audit are the code that M3 already tested. -
The runner recognises the shape.
Runner.runExec(internal/runner/workspace.go) checks that the executor implementsBashExecutor, that there is no stdin, no env and the default cwd, and that argv isbash -lc X. ThenrunBashcallsExecutor.Bash. Any otherexecgoes the old way. A container fleet's executor does not implementBashExecutor, so it is untouched. -
hostx.Engine.Bash(exec_linux.go):- refuses an empty command or one containing a NUL byte;
-
prepare: ensuresout/andjobs/exist in the session state dir (0700); -
childEnv: builds the clean environment (see 8.13); -
openSink: createsout/<Ref>, the file that will hold the full output; - starts
bash -lc 'trap "pwd >&3" EXIT; eval "$1"' bash <command>withSetsid: true(its own process group) and a pipe as fd 3. After the command exits, the finalpwdis read from the pipe and stored in the session'scwdfile. That is how "the directory persists between calls" works without keeping a shell alive; - on timeout (default 120 s, at most 10 min) or when central cancels, it kills the whole process
group with
SIGKILL(cmd.Cancel), so no stray child survives; - both streams go through two writers: one into the file (up to 64 MiB), one into a
Capturethat keeps the head and tail of about 32 KiB. The result carriesStdoutBytes,StderrBytes(true totals),Omitted(bytes not inline) andRef; -
pruneOutputskeeps the 32 newest output files.
-
The way back. The runner puts the result in the transport result frame. Central writes
the outcome audit row (it records exit code, sizes and
ref, never the output) and replies.orchreturns the DTO;mcpserver.bashrunsscrub(removes harness control tags from each stream, then caps), appliesorch.CapOutput(30 KiB, one third head, two thirds tail), setstruncated,omitted_bytesand anotethat names therefand how to page it. Finallyneutralizeruns over the JSON. -
Paging.
read_output {ref}becomesworkspace.output_read, the transport opoutput_read, andExecutor.OutputRead, which opensout/<ref>(the ref is validated as a plain name, so it cannot point elsewhere), seeks tooffset, appliestail_linesorgrep, and returns at mostlimitbytes withnext_offset.
What can go wrong, and what you see: a timeout_s of 700 is a bad_request before anything is
sent; a command that runs 5 minutes comes back timed_out: true with the note to use
run_in_background; a guarded fleet without confirm gets the "ask the user" rewrite of chapter 7;
a runner that restarts mid-command loses the command (foreground commands do not survive a runner
restart; background jobs do, because KillMode=process leaves their supervisors running).
- Why does
runExeccheck for the exact argvbash -lc Xinstead of a new method? - How does the cwd persist when every
bashcall is a fresh shell? - Why does the broker's CA carry NameConstraints?
Answers
- Foreground bash then reuses the tested ownership, confirm and audit path of
workspace.exec. - The wrapper runs
pwd >&3on exit; the engine stores it in the session'scwdfile and starts the next call there. - So a stolen session CA key still could not mint a certificate for any host other than the credential hosts.
-
internal/centralhandles SSH connections for a database-backed server, yet it does not importinternal/store/sqlite. How does it get a store, and what does this buy us? - In the
action.runtrace, name the two places where a start audit row and an outcome audit row are written, and say what happens if the first write fails. - A teammate adds a new operator method and registers a handler in
operatorTable(), but every call returnsforbidden. Name three other places a new operator method must be wired, and say which of them they forgot. - Why does
Service.Lifecycletombstone and kick a runner before committing the revoke to the database? - You add
import ".../internal/store/sqlite"tocmd/mirafleet/mcp.go. Which test fails, and why does that matter to someone on a MacBook? - In the
workspace.exectrace, the runner re-validates argv, cwd and env that central already validated. Why, and which import-graph fact keepsservicefrom ever touching a container? - You write a new executor. Which single file wires it in, and which two tests protect the macOS binary from accidentally linking containerd?
- A refused
workspace.execfrom an unauthorised caller carries a 1 MiB stdin body. At which step of the trace is it not read, and what would go wrong if it were read first? - Which test stops
internal/mcpserverfrom reaching intointernal/serviceto "save a round trip", and what does it list as the one place the go-sdk may be imported? - In section 8.10, why does a dead connection make
execfail with "may or may not have completed" instead of quietly trying again? - You want a tool that revokes a runner. Where does the plan fail, and at how many places?
- A handler in
internal/guineeds one more database column. Why can it not just open the database, and which test says so? - You add
mux.HandleFunc("GET /settings", ...)for a new screen but forget the session check in the handler. Which test catches it, and why can you not hide the route from that test? - In the Revoke click, name the first step that changes state, and three refusals that happen before it.
- Why is
tools/relgenstdlib-only and kept out of themirafleetbinary? Which two places runrelgen check, and what does it protect against? - What does goreleaser build here, and which three channels does it deliberately not publish to?
- Why does the npm wrapper have no
postinstallscript that downloads the binary?
Answers
-
cmd/mirafleet/central_linux.goopens the database withsqlite.Openand passes the value as astore.Storeincentral.Config. Central only knows the interface, so tests can use a fake or temp store, a future Postgres store needs no change incentral, and the macOS and Windows binaries do not link SQLite. - Both are written in
Service.RunActionthroughstore.RecordAudit:startbeforeregistry.Exec, the outcome after. If the start write fails,RunActionreturnsunavailable: audit unavailableand nothing is executed (fail closed). A failed outcome write is only logged, because the action already ran. - (1)
api.IsOperatorMethodininternal/api/api.go, somethodTable.servelets the method through; (2) thecaseinpolicy.TablePolicy.Authorize(deny by default); (3) the service method'sauthorizecall, which must use the same method name. They forgot the policy entry: a call that passes the method table but not the policy returnsforbidden. - Without the early tombstone and kick, a runner could reconnect or finish starting a new action in the time between "revoke decided" and "database updated". Tombstone plus kick close that window, and if the commit fails the tombstone is undone only when the runner is verifiably not revoked.
-
TestNoSQLiteOnNonLinuxincmd/mirafleet/deps_test.gofails because the darwin build now linksinternal/store/sqliteandmodernc.org/.... It matters because the laptop binary would grow by several megabytes and drag in a database engine the operator never uses. - Central is not trusted by the runner: a compromised or buggy central must not be able to
smuggle a path escape, a denied env variable or an oversized limit into a container, so the
runner's
preparechecks against its ownworkspace.yaml, and the executor checks once more.serviceimportsregistryand theworkspaceleaf package only; the only code that importsctrdiscmd/mirafleet/runner_ws_linux.go, so central never has a container API. -
cmd/mirafleet/runner_ws_linux.go(thenewExecutorswitch).TestNoContainerdOnNonLinuxfails if a darwin or windows build links anygithub.com/containerd/...or gRPC package;TestLinuxLinksContainerdproves the filter still works by requiring the Linux build to link it. - Steps 5 to 7 of "In the service" come before the body read: policy, ownership, state, input,
confirm and timeout. The body is read only in step 7, through the lazy
lazyStdin. Reading it first would let any authenticated caller make central buffer 1 MiB per channel (8 channels per connection) before being toldnot_foundorforbidden. -
TestOrchestratorDepsincmd/mirafleet/deps_test.go: it runsgo list -depsfororch,mcpserverand the hook on all six OS/architecture pairs and fails on any server-side package. The go-sdk may be imported only by non-test files ofinternal/mcpserver. - A dead connection says nothing about whether central already ran the command. Repeating a
go testis harmless; repeating adeployor anrmis not.orch.calltherefore redials and retries only the methods inidempotent()(lists,read_file,workspace.open), and reports an honest uncertainty for the rest. - At three gates:
revokeis an admin method, so there is no operator method to wrap;orch.callwould refuse it becauseapi.IsOperatorMethodis false; and central refuses admin methods on theapi@channel whatever the caller. The tool table is also fixed in code, sotools/callfor such a name finds nothing. See "A new MCP tool" in section 8.8. -
TestGUIDepsfails the build ifinternal/guiimportsinternal/store/sqlite(orcentral, the registry,apiclient,orch,mcpserver). The GUI parses input from a browser; it may reach data only throughservice, which authorises, validates and audits. Add the column to the store, expose it in a service method, add that togui.Backend. -
TestSecurityAuthRequiredOnEveryRoute: it requests every route anonymously and wants a redirect to/login. (A handler registered withHandleFunconadminMuxis wrapped inrequireAdminanyway, so the check is a second line of defence.) The suite finds routes by scanning the source for literal"METHOD /path"patterns, and it fails if the number of registration calls differs from the number it could parse, so a clever registration that the scan cannot read fails the test instead of escaping it. - Step 6,
Service.Lifecycle. Before it: a Host not on the allowlist (421), no live session (redirect to/login), a missing or wrong_csrftoken or a cross-site request (403), and a typed name that is notdev/build-1(422). - It runs in CI with release permissions, so fewer dependencies means less to trust, and it is
release plumbing that users should not have to download.
release.yml'sverifyjob andrelease.sh m6checkrun it. It stops a release where one versioned file (plugin manifest, marketplaceref,server.json, Compose tags, protocol level) still has the old version. - The six OS/CPU binaries, archives,
.deb/.rpm/.apkpackages,checksums.txt, SBOMs and the keyless signature, as a draft GitHub release. Not images, Homebrew or npm: separate jobs, each with its own credential and approval, so the builder never holds a publish secret. - Install scripts run arbitrary code on the user's machine at install time and need network
access. Shipping the binary inside a platform package means
npm installonly copies files, andnpmtestasserts that no lifecycle scripts exist.
- mirafleet quickstart
- The mirafleet developer guide
- Glossary
- 1. What is mirafleet?
- 2. Background: the ideas mirafleet builds on
- 3. Architecture
- 4. Flows
- 5. Security
- 6. Data model
- 7. Protocols
- 8. Code tour
- 9. Dev setup and testing
- 10. Operations
- 11. Contributing
- 12. Why mirafleet? A comparison with the alternatives
Generated from docs/ at cded12f; edit there.