dispatcher

package
v0.3.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 14, 2026 License: MIT Imports: 56 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// LabelJobID / LabelWorkspace / LabelInstallID are exported aliases of
	// the label constants above, kept for the external callers that already
	// reference them.
	LabelJobID     = labelJobID
	LabelWorkspace = labelWorkspace
	LabelInstallID = labelInstallID
)
View Source
const NoWorkspaceProxyKey = "__no_workspace__"

NoWorkspaceProxyKey is the ProxyAllocator key the daemon uses, once at startup (internal/server's Server.Start), to bind a dedicated egress proxy listener for jobs with no workspace at all (`boid exec` / ProfileInit against an unlinked project — see resolveWorkspaceProxy's own doc comment). Exported so internal/server can seed this listener under the exact same key resolveWorkspaceProxy looks up via Runner.NoWorkspaceProxyPort, without either package hard-coding the other's literal.

Deliberately DISTINCT from orchestrator.DefaultWorkspaceSlug (BLOCKER, codex review round 3): the real "default"-slug workspace has its own workspace.yaml an operator can add AllowedDomains to, and ProxyManager.GetOrCreate mutates a listener's allowlist in place — keying the no-workspace listener by the SAME string as that real workspace would let a later default-workspace dispatch silently widen the no-workspace listener too. Contains "_", a character orchestrator.ValidWorkspaceSlug never permits in a real workspace slug (only lowercase letters, digits, and "-"), so this key can never collide with a real workspace's own allocator key, now or in the future.

Variables

View Source
var ErrRuntimeUnsupported = errors.New("job runtime operation is not supported")
View Source
var ErrWorkspaceHomeBusy = errors.New("the workspace HOME volume is busy in this daemon")

ErrWorkspaceHomeBusy is what a migration refused by the daemon's OWN in-flight registry comes back as (workspaceHomeInFlight): another operation in this process is already using that workspace's HOME volume.

Distinct from ErrWorkspaceHomeInUse, which is the ENGINE's answer about a running container. This one covers the interval the engine cannot see: a dispatch that has resolved the home but has not yet created the container that would make it in-use, and a concurrent migration. Both are 409s at the API and both mean "wait and re-run", so the split is about the message an operator reads, not about what they do next.

View Source
var ErrWorkspaceHomeImportEmpty = errors.New("the workspace home archive carries no entries")

ErrWorkspaceHomeImportEmpty is what a migration refused because its archive would replace the home with nothing comes back as.

A sentinel because the API layer answers it with a 400 rather than the 409 the two busy errors get: nothing is in flight, nothing needs waiting for, and the thing to fix is the request. See peekWorkspaceHomeTarHasEntries for why this is checked at all, and WorkspaceHomeSourceHasEntries for the CLI-side half.

View Source
var ErrWorkspaceHomeInUse = errors.New("the workspace HOME volume is in use by a running container")

ErrWorkspaceHomeInUse is what a migration refused because a job is running in that workspace comes back as.

It is a sentinel because the API layer has to turn it into a 409 and the CLI into an actionable message, and neither can do that by matching on the engine's prose. See containerBackend.RemoveWorkspaceHomeVolume for the engine-side fact it is derived from.

Functions

func BuildExecJobSpec added in v0.0.6

func BuildExecJobSpec(input SessionJobInput, argv []string, interactive bool) (*orchestrator.JobSpec, error)

BuildExecJobSpec is the shell-harness variant of BuildSessionJobSpec used by `boid exec` to run a user-supplied argv inside the project sandbox. It reuses BuildSessionJobSpec for project trait inheritance and overrides the result:

  • Kind = JobKindExec (TUI displays an "exec" badge instead of "session")
  • Argv = the user's argv (runner-inner-child hands this to the shell adapter)
  • Interactive = caller's tty detection (sessions are always PTY-attached; exec may be piped from a non-TTY stdin)
  • DisplayName falls back to argv[0] when the caller leaves it empty

HarnessType in input is ignored and forced to "shell"; argv must be non-empty. Propagates any error from BuildSessionJobSpec (in particular a session clone-declaration failure — see buildSessionCloneDeclaration).

func BuildSandboxSpec

func BuildSandboxSpec(spec *orchestrator.JobSpec, rt SandboxRuntimeInfo) (sandbox.Spec, error)

BuildSandboxSpec turns a business-level JobSpec and dispatcher-side runtime facts into a primitive sandbox.Spec. It contains no role-aware switch: the mount set and environment are derived purely from JobSpec.Visibility, HostCommands, Instruction and Argv.

func BuildSessionJobSpec added in v0.0.6

func BuildSessionJobSpec(input SessionJobInput) (*orchestrator.JobSpec, error)

BuildSessionJobSpec converts a resolved SessionJobInput into a JobSpec (JobKindSession, adapter-bound HarnessType). The result is fed straight to dispatcher.Runner which builds the sandbox and hands the agent process to adapter.Run().

Returns an error when the sandbox-internal clone declaration cannot be built for a non-empty ProjectWorkDir — see buildSessionCloneDeclaration's doc comment. The caller (WebUI POST /sessions, `boid exec` CLI) must surface that as a user-visible error rather than silently degrading, since the cutover contract (docs/plans/git-gateway-cutover.md PR6) requires a clone-based dispatch for every project-visible job.

func CaptureUpstreamURL added in v0.0.10

func CaptureUpstreamURL(dir string) (string, error)

CaptureUpstreamURL reads dir's `git config --get remote.origin.url` and normalizes it to an HTTPS URL suitable for a project's upstream_url. Returns an error if dir has no git repository, no origin remote is configured, or the origin URL is in an unrecognized form — the caller (project registration / reload / startup backfill) decides how to react.

func CleanupJobCheckout added in v0.1.0

func CleanupJobCheckout(stagingDir string) error

CleanupJobCheckout removes stagingDir (docs/plans/volume-only-daemon.md §論点b step 5: "job 終了時、 staging area を削除") — the bare repo cache at bareRepoPath (never touched by this function) remains untouched; stagingDir's own `.git/objects` is a full, standalone copy of what it needs (PrepareJobCheckout's own doc comment — a plain `file://` clone, not an alternates reference), so removing stagingDir never risks the bare repo's own object store either way.

A no-op (nil error) for an empty stagingDir — the same "nothing to do" convention os.RemoveAll itself already has for a path that doesn't exist, made explicit here so a caller that never successfully ran PrepareJobCheckout (e.g. dispatch failed before staging was ever attempted) can unconditionally defer this without a nil/empty check of its own.

func CloneBareRepo added in v0.1.0

func CloneBareRepo(ctx context.Context, rawURL, destPath string, creds *gitgateway.CredentialProvider, namespace string) error

CloneBareRepo clones rawURL into destPath as a `--mirror` bare repository (NOT plain `--bare`: a plain bare clone sets no fetch refspec on the `origin` remote at all, so a later `git fetch --all` populates FETCH_HEAD only and silently leaves every branch ref exactly as it was at clone time — useless as a daemon-managed fetch cache. `--mirror` configures `remote.origin.fetch = +refs/*:refs/*` (and mirror=true), which is what makes FetchBareRepo's `git fetch --all` actually update refs/heads/* in place; see docs/plans/volume-only-daemon.md §論点b's fetch 経路), injecting forge credentials from creds when rawURL's host is configured under gateway.forges. namespace scopes secret resolution the same way job dispatch does (the registering project's workspace slug — SecretNamespace's existing convention). A host creds has no opinion on (gitgateway.CredentialProvider.KnowsHost false, or creds itself nil) clones unauthenticated — correct for public repos and for SSH URLs, which this credential mechanism (HTTPS Basic auth) does not apply to at all.

func ContainerBackendBrokerTLS added in v0.1.0

func ContainerBackendBrokerTLS(be backend.SandboxBackend) (addr string, hasCA bool, ok bool)

ContainerBackendBrokerTLS returns whether be is a *containerBackend configured with a non-nil BrokerTLSCA, and the broker TLS address it would currently dereference (dereferencing the late-bound ContainerBackendOptions.BrokerTLSAddr pointer fresh, "" if the pointer itself is nil or points at an empty string). Same external-package introspection rationale as ContainerBackendUIDGID/ ContainerBackendHasDiagnosticsCollector — for internal/server/wire_backend_test.go's own pin that sandboxBackendForConfig actually wires the daemon's CA + late-binding address pointer into the containerBackend it constructs (docs/plans/phase6-cutover-followups.md §⓪).

func ContainerBackendDefaultImage added in v0.1.0

func ContainerBackendDefaultImage(be backend.SandboxBackend) (string, bool)

ContainerBackendDefaultImage returns the effective default image a containerBackend launches job containers from when a spec carries no ContainerImage override (after NewContainerBackend's own empty-falls-back-to-version.DefaultContainerImage() resolution has already run), and false if be is not a *containerBackend. Same external-package introspection rationale as IsContainerBackend's own doc comment — used by internal/server/wire_backend_test.go to pin that sandboxBackendForConfig threads BOID_IMAGE through (docs/plans/ release-onboarding.md 穴4/PR4 codex review: the daemon and the job containers it launches must agree on the same image ref, or a daemon that pulled its own GHCR image successfully can still fail every job dispatch trying to pull an unrelated, unqualified "boid-runner:latest" from docker.io).

func ContainerBackendHasDiagnosticsCollector added in v0.1.0

func ContainerBackendHasDiagnosticsCollector(be backend.SandboxBackend) bool

ContainerBackendHasDiagnosticsCollector reports whether be is a containerBackend constructed with a non-nil ContainerBackendOptions.DiagnosticsCollector. Exists solely as an external-package introspection helper — the same rationale as IsContainerBackend's own doc comment — for [Major 7, PR7 codex review]'s production wiring test (internal/server/wire_backend_test.go): that package can observe that sandboxBackendForConfig actually wired NewDefaultDiagnosticsCollector in without being able to name (or type-assert into) the unexported *containerBackend/diagnosticsCollector fields directly.

func ContainerBackendUIDGID added in v0.1.0

func ContainerBackendUIDGID(be backend.SandboxBackend) (uid, gid int, ok bool)

ContainerBackendUIDGID returns the effective uid/gid a containerBackend launches job containers under (after NewContainerBackend's own unset/partial/root-resolving-pair rejection has already run — see ContainerBackendOptions.UID's doc comment), and false if be is not a *containerBackend. Same external-package introspection rationale as ContainerBackendHasDiagnosticsCollector — for internal/server/wire_backend_test.go's own pin that sandboxBackendForConfig wires the daemon's actual os.Getuid()/os.Getgid() through (PR9, §決定4 — see sandboxBackendForConfig's own doc comment for why a mismatch here silently broke every job's access to its own workspace home directory).

func ContainerBackendUsesDockerAPI added in v0.1.0

func ContainerBackendUsesDockerAPI(be backend.SandboxBackend, api any) bool

ContainerBackendUsesDockerAPI reports whether be is a *containerBackend whose engine handle IS api — pointer identity, not merely "both are non-nil docker clients". Same external-package introspection rationale as ContainerBackendUIDGID/ContainerBackendBrokerTLS.

It exists because the wiring test for [round 2 Major 2, codex review 2026-07-26] could not state its own claim from internal/server [round 3 Minor 2]: buildRuntime must hand the container backend and the daemon-state-volume self-inspection (DetectDaemonStateVolumes) THE SAME client.New(client.FromEnv) result, and asserting only that each got some non-nil *client.Client passes just as happily on a regression that builds two — which is exactly the shape round 2 removed, and exactly the shape (a second synchronous DOCKER_CERT_PATH read on the startup path) whose cost is invisible until a wedged filesystem hangs `boid start`. A nil api never matches, so the helper cannot report a shared handle where neither side has one.

func CreateJob

func CreateJob(dbtx db.DBTX, j *Job) error

func FetchBareRepo added in v0.1.0

func FetchBareRepo(ctx context.Context, bareRepoPath string, creds *gitgateway.CredentialProvider, namespace string) error

FetchBareRepo runs `git fetch --all --prune` inside an existing daemon-managed bare (mirror) repo (`boid project fetch <id>`), re-resolving credentials against the repo's own remote.origin.url — which, per CloneBareRepo's doc comment, is always the plain (uncredentialed) URL the project was registered with. After a successful fetch, also refreshes bareRepoPath's symbolic HEAD to match the remote's current default branch (MAJOR 4, PR-2a codex round-1 review) — see refreshBareRepoHEAD's doc comment for why this needs its own step (a mirror clone's fetch refspec never touches HEAD on its own).

func FindDaemonShutdownAbortedTasks

func FindDaemonShutdownAbortedTasks(conn *sql.DB) ([]string, error)

FindDaemonShutdownAbortedTasks returns IDs of tasks currently in aborted status whose most recent aborted-transition action carries payload.code == "daemon_shutdown". Use this on daemon startup to auto-reopen tasks that were interrupted by the previous shutdown.

"Most recent" means the latest action with to_status='aborted' for that task (ordered by created_at desc). If a task was aborted by daemon_shutdown and then aborted again later for another reason, the later code wins and the task is NOT returned — matching the intuition that only freshly-shutdown tasks deserve auto-reopen.

func GenerateKey

func GenerateKey() []byte

GenerateKey creates a random 32-byte AES-256 key.

func GitOriginURL added in v0.0.9

func GitOriginURL(dir string) (string, error)

GitOriginURL returns the `git config --get remote.origin.url` value for dir, or an error if git is missing, dir is not a repo, or no origin is configured. It deliberately uses cmd.Dir rather than `git -C dir`: this repo's sandbox git wrapper rejects `-C`, and cmd.Dir works everywhere (production and sandboxed callers alike).

This is the production getOriginURL implementation passed to ResolveHostCommands; it is exported so callers outside this package (internal/server/api_store.go) can pass it too.

func IsContainerBackend added in v0.1.0

func IsContainerBackend(be backend.SandboxBackend) bool

IsContainerBackend reports whether be is a containerBackend constructed by NewContainerBackend. Exists solely as an external-package introspection helper for docs/plans/phase6-container-backend.md §PR7's config-driven backend-selection wiring (internal/server/wire.go's sandboxBackendForConfig) — that package cannot type-assert against the unexported *containerBackend type directly, and this is cheaper for a test to depend on than reflect-based %T string matching.

func LoadOrCreateKey

func LoadOrCreateKey(path string) ([]byte, error)

LoadOrCreateKey loads the master key from the given path, or atomically generates and persists a fresh one if it doesn't exist yet.

Publish uses atomicfile.PublishIfAbsent (docs/plans/volume-only-daemon.md §論点 d — the same write-temp + os.Link protocol internal/install. LoadOrCreate pioneered, Major 7 PR6 codex review) instead of a plain os.WriteFile: two daemon instances racing to boot against the same fresh, empty data dir (a named volume with nothing in it yet — the scenario this file and web_secret both share as callers of this same function) must agree on exactly one key instead of each generating its own and clobbering the other's write, with a window where a reader could observe a half-written (or, worse, zero-byte and therefore format-invalid per the length check below) file in between.

func MarkStaleAwaitingTasksAborted added in v0.0.7

func MarkStaleAwaitingTasksAborted(conn *sql.DB) (int, error)

MarkStaleAwaitingTasksAborted does the same for tasks left in "awaiting" status from a previous crash or restart. After a restart no agent is parked in the (purely in-memory) BlockingAskRegistry, so every awaiting task is a zombie with no live agent behind it — reclaim it. It carries the same daemon_shutdown code as the executing path, so the startup auto-reopen sweep (FindDaemonShutdownAbortedTasks) restarts it and the agent re-asks if needed.

func MarkStaleExecutingTasksAborted

func MarkStaleExecutingTasksAborted(conn *sql.DB) (int, error)

MarkStaleExecutingTasksAborted transitions all tasks in "executing" status to "aborted" and records a daemon_shutdown abort action for each. Call this on server startup after MarkStaleJobsFailed. Returns the number of tasks transitioned.

func MarkStaleJobsFailed

func MarkStaleJobsFailed(dbtx db.DBTX) error

MarkStaleJobsFailed marks all running jobs as failed. Call this on server startup to clean up jobs left in running state from a previous crash or restart.

func NewContainerBackend added in v0.1.0

func NewContainerBackend(api dockerAPI, opts ContainerBackendOptions) backend.SandboxBackend

NewContainerBackend constructs a containerBackend over api (typically a real *github.com/moby/moby/client.Client — see dockerAPI's doc comment for why the parameter is this narrower interface rather than that concrete type — or a fake for tests).

As of PR7 (docs/plans/phase6-container-backend.md §PR7 cutover), internal/server/wire.go's sandboxBackendForConfig calls this in production when config.yaml sets `sandbox.backend: container`, and assigns the result to Runner.Backend — the same DI seam (internal/dispatcher/runner.go, landed PR1) tests have exercised this backend through since PR5. Every pre-PR7 caller (and every test that doesn't opt in via that config key) is unaffected: Runner.Backend stays nil and Runner.sandboxBackend() keeps constructing the usernsBackend.

func NewDefaultDiagnosticsCollector added in v0.1.0

func NewDefaultDiagnosticsCollector(api dockerAPI, dir string) func(ctx context.Context, containerID string, exit backend.RuntimeExit)

NewDefaultDiagnosticsCollector returns a ContainerBackendOptions. DiagnosticsCollector implementation suitable for production wiring (internal/server/wire.go's sandboxBackendForConfig — [Major 7, PR7 codex review]).

Before this fix, ContainerBackendOptions.DiagnosticsCollector was never set outside of tests (NewContainerBackend's own doc comment on production wiring): containerSession.waitLoop's own §決定7/8 ordering contract ("診断回収 → job fallback 処理 → resource remove") had a real hook to run through, but nothing was ever plugged into it — an OOM-killed or setup-failure container was removed with NO diagnostic capture beyond whatever the (possibly-empty, possibly-truncated) attach-stream transcript spool happened to catch: exit code 137 and an empty log were often the only signal left.

The returned collector runs ONLY when exit.ExitCode != 0 (the common happy path already has its full output durable via the transcript spool — §決定8's distinction between "full persistence" and "silent-exit diagnosis" — so a clean exit does not pay the extra ContainerInspect/ ContainerLogs round trip; an engine-fault exit is always != 0 — waitLoop forces exitCode to 1 whenever it sets EngineError — so this scope covers it too). On an abnormal exit it captures ContainerInspect (exit code / status / OOMKilled / dockerd's own State.Error), a bounded tail of ContainerLogs (dockerd's own independently-retained log buffer — the attach-stream transcript spool can be empty or truncated for a SIGKILL'd container, but dockerd's own buffer isn't), and exit.EngineError verbatim when the exit was an engine fault rather than the job's own command failing (containerDiagnostics.EngineError's own doc comment) — and writes all of it to <dir>/<containerID>/diagnostics.json — the sibling of transcript.log under the same per-job directory (callers pass the same root as ContainerBackendOptions.TranscriptDir when set, else RuntimeDir — see TranscriptDir's own doc comment for why diagnostics.json, like transcript.log, does not need RuntimeDir's DooD host-visibility and can live on a persistent volume instead). Every step is best-effort: an inspect or logs failure is recorded in the diagnostics.json itself (CollectorError) rather than losing the whole artifact, and the collector NEVER returns an error to its caller (waitLoop's own contract — see ContainerBackendOptions.DiagnosticsCollector's doc comment: this runs strictly before ContainerRemove, so it must not block or fail container teardown).

dir empty (every pre-Major-7 test/caller, or a deploy that hasn't wired a transcript/runtime dir) makes the returned collector a no-op — there is no directory to write into (mirrors openTranscriptSpool's identical empty-dir degrade).

func NormalizeArch added in v0.1.0

func NormalizeArch(arch string) string

NormalizeArch is normalizeArch, exported for cmd/check.go (PR7, docs/plans/release-onboarding.md): `boid check` runs its own host-arch vs. image-arch preflight independently of resolveImage's launch-time fail-fast (both are required per 決定5 — this one is diagnostic, run before a job ever launches; resolveImage's is the actual gate), but needs the exact same docker/podman uname(1)-style-to-OCI-vocabulary translation resolveImage's check applies, or the two would disagree about what counts as a mismatch. Kept as a thin wrapper (rather than renaming the unexported original) so every existing call site inside this package keeps using the plain, private name.

func NormalizeOriginURL added in v0.0.10

func NormalizeOriginURL(raw string) (string, error)

NormalizeOriginURL converts a git remote origin URL into the HTTPS form used as a project's upstream_url (docs/plans/git-gateway-cutover.md PR2: "project → 上流 URL の明示マッピング"). HTTPS URLs are returned unchanged ("既に HTTPS URL ならそのまま"); scp-like SSH (`git@host:owner/repo.git`) and `ssh://` URLs are rewritten to `https://host/owner/repo.git` (`http://` is likewise upgraded to `https://`, reusing the same host/path extraction). Returns an error for an empty or unrecognized URL form.

This is a pure function so it can be unit tested without a real git repository; CaptureUpstreamURL below composes it with the actual `git config` read.

func PoliciesToSandbox

func PoliciesToSandbox(in map[string]orchestrator.BuiltinPolicy) map[string]sandbox.BuiltinPolicy

PoliciesToSandbox converts the orchestrator-owned neutral BuiltinPolicy representation into the sandbox-layer BuiltinPolicy the broker understands. dispatcher is the only layer allowed to bridge both sides.

func PrepareJobCheckout added in v0.1.0

func PrepareJobCheckout(ctx context.Context, bareRepoPath, branch, baseBranch, baseBranchForkPoint, remoteURL, stagingDir string) (err error)

PrepareJobCheckout materializes a fresh, per-job working checkout of branch at stagingDir, cloned from the daemon-managed bare repository at bareRepoPath (docs/plans/volume-only-daemon.md §論点b steps 2-3: "daemon が job 用 staging area を用意... bare repo から per-job clone... を staging area に配置").

Cloning is a plain `git clone file://<bareRepoPath>` — deliberately NOT `git clone --reference bareRepoPath` (codex round-1, PR834 Blocker 1): `--reference` records bareRepoPath itself in stagingDir's own `.git/objects/info/alternates`, which only ever resolves from a process that can see bareRepoPath on ITS OWN filesystem — true of the daemon process that runs this clone, but NOT true of the job container the staging area gets bind-mounted into (the job container mounts only stagingDir's own subtree, e.g. `checkouts/<jobID>/<project>/`, never the daemon's own data/runtime volume bareRepoPath lives under). A job container running `git status`/`git commit`/anything that touches HEAD's object graph would fail resolving objects through an alternates path it cannot see. The explicit `file://` scheme (rather than a bare local path, which git would otherwise still auto-hardlink against the source without an alternates entry) forces git's own transport-based clone machinery — a real, standalone copy of every object stagingDir needs, no alternates file, no shared inodes with bareRepoPath — so stagingDir is fully self-contained the moment this function returns and never depends on bareRepoPath's own continued existence or mount visibility (see also TestPrepareJobCheckout_NoAlternatesDependency).

Branch resolution (which ref to check stagingDir out to) is NOT a plain `git checkout -B <branch> origin/<branch>` — it shares sandbox.ResolveCloneBranchRef with internal/sandbox/runner/clone.go's resolveCloneBranch (PR834 PR-2b round-2 codex review Blocker: the two paths had drifted — this function's own pre-fix naive `origin/<branch>` construction neither stripped an "origin/" prefix baseBranch/branch might carry, e.g. a project.yaml `base_branch: origin/main`, which produced an unresolvable "origin/origin/main", nor created a missing base branch from baseBranchForkPoint the ClassifyBaseBranch case-3 way resolveCloneBranch already did). See ResolveCloneBranchRef's own doc comment for the exact algorithm; the net effect is the same idempotent-by-reclone contract the in-sandbox clone sequence already established (docs/plans/ branch-policy-simplification.md: reopen = re-running this exact sequence), forcing the local branch to exactly match the resolved ref, discarding any local drift a same-named branch might otherwise carry from `git clone`'s own default-branch checkout.

A prior stagingDir (a leftover from an earlier attempt, or a reopen of the same job) is wiped before cloning fresh — the daemon-side analogue of clearDirContents/performCloneSteps' own reopen contract. Unlike performCloneSteps (which must preserve TargetDir's own directory ENTRY because it is an active sandbox mount point the kernel refuses to rmdir), stagingDir here is plain daemon-local filesystem the daemon itself owns outright before any container ever mounts it, so a full os.RemoveAll (removing stagingDir itself, not just its contents) is safe and simpler.

remoteURL, when non-empty, is set as stagingDir's own `origin` remote after cloning (docs/plans/volume-only-daemon.md §論点b) — the gateway clone URL (dispatcher.buildGatewayCloneURL's "<gatewayURL>/j/<token>/..." form) a writable job's own in-sandbox `git push` needs, since a plain local clone from bareRepoPath would otherwise leave `remote.origin.url` pointing at a DAEMON-filesystem path meaningless (and unreachable) from inside the job container. Empty skips this step, leaving origin pointed at bareRepoPath — the correct behavior for a read-only/no-gateway dispatch (nothing inside the sandbox will ever `git push` in that case). remoteURL carries a live per-job gateway token exactly like sandbox.CloneSpec.URL does; any error this function returns has already been redacted (via runGit -> redactGitArgs, which also strips this specific /j/<token>/ shape — see bare_repo.go's gatewayJobTokenPathPattern).

On any failure ONCE stagingDir has actually started being populated (i.e. after the pre-clone RemoveAll below), stagingDir is removed before returning so a caller never inherits a half-populated staging area (codex round-1, PR834 Major 1: this previously only happened on the checkout/remote-url failure paths, not on `git clone` itself failing — the deferred cleanup below now covers every failure path uniformly, including clone failure, so a caller — runner.go's own trackCheckoutDir, which only starts tracking stagingDir on full success — can never be left responsible for cleaning up a staging dir it never learned about).

func ReadTranscript

func ReadTranscript(rootDir, runtimeID string) ([]byte, error)

ReadTranscript reads the transcript.log for the given runtimeID from rootDir. Returns os.ErrNotExist if the transcript file does not exist (e.g. runtime was gc'd).

func RepoSlugFromOriginURL added in v0.1.0

func RepoSlugFromOriginURL(url string) (string, error)

repoSlugFromOriginURL normalizes a git remote origin URL into a `host/owner/repo` slug. Supported forms:

https://github.com/owner/repo.git -> github.com/owner/repo
git@github.com:owner/repo.git     -> github.com/owner/repo
ssh://git@github.com/owner/repo.git -> github.com/owner/repo
ssh://git@github.com:2222/owner/repo.git -> github.com/owner/repo
git://github.com/owner/repo.git   -> github.com/owner/repo

Non-github hosts are kept as-is. Returns an error if the URL cannot be parsed into a host/owner/repo shape. RepoSlugFromOriginURL is the exported form of repoSlugFromOriginURL (docs/plans/workspace-default-project.md 決定3): the same normalization gitgateway.NewRepoKey applies to a request path's host/owner/repo components, used here as the hash input for a project.yaml-less project's derived id — see internal/api's deriveProjectIDFromURL. Exported specifically for that cross-package use; every existing in-package caller still calls the unexported form directly.

func ResolveHostCommands

func ResolveHostCommands(
	builtins []string,
	hostCommands map[string]orchestrator.CommandDef,
	projectDir string,
	lookPath func(string) (string, error),
	getOriginURL func(string) (string, error),
) (byPath map[string]orchestrator.CommandDef, byName map[string]orchestrator.CommandDef, err error)

ResolveHostCommands turns the orchestrator-side host command map (keyed by the user-declared name) into two views over the same resolved command data (docs/plans/phase5-shim-and-task-context.md, "5a: shim 固定ディレクトリ化" PR1):

  • byPath is keyed by the absolute host path each host command was resolved to (also written back into each entry's Path). It used to drive the shim's per-host-path bind mount and PATH parent entries; as of the 5a-3 cutover (PR3) that scheme is retired — shims are now symlinks under a fixed sandbox-internal directory (dispatcher.sandboxShimBinDir), so no dispatcher / broker / shim code paths key off the absolute host path any more. It is returned here as an inert byproduct of the pass (the map is already built for the dedup filter) and can be dropped once no downstream consumer needs the "no two host commands collide on the same host binary" invariant it happens to encode. No production caller still reads it.
  • byName is keyed by the short (user-declared) command name — the canonical view. Consumed by the broker's policy table (CommandBroker.RegisterCommands, BOID_HOST_COMMAND_RULES via buildHostCommandRulesEnv) and by the sandbox layout (hostCommandSymlinks, buildPATH). As of 5a-3 this is also the only shape the shim sends as ExecRequest.Command (sandbox.CommandFromArgv0 → the shim's bind-mount basename, which equals the declared short name by construction under sandboxShimBinDir); the broker's pre-5a-3 Path-scan fallback for the retired absolute-path shape was dropped in the same change.

Every entry appears in both maps under its own key with identical field values (byName[def.Name] == byPath[absPath]).

The names "boid", "git", and "fetch" are excluded, each for a different reason: "boid" has a dedicated bind mount + builtin policy elsewhere; "fetch" is a broker builtin (`FetchRequest`) without a host binary at all; "git" is neither a broker builtin nor a shim — it's a real binary reached via the base rbind of /usr, but the name is reserved here so a user `host_commands.git:` entry doesn't try to overlay a shim onto that path and break the sandbox-side git that the git gateway clone flow depends on. Neither map ever contains an entry for these three names.

`projectDir` is used to resolve relative paths declared in host_commands.<name>.path, and as the working directory for the origin URL lookup that expands `${boid:repo_slug}` in Env values (see docs/plans/host-command-contract.md item 3). `lookPath` and `getOriginURL` are parameterized for tests; production callers pass exec.LookPath and GitOriginURL. There are only two production call sites (runner.go, api_store.go), which is few enough that threading a parameter through them (matching the existing lookPath convention) is simpler than a package-level var seam.

func ResolveWorkspaceHomeSource added in v0.1.0

func ResolveWorkspaceHomeSource(root string) (string, error)

ResolveWorkspaceHomeSource validates root as a migration source and returns the path a walk of it has to actually run against.

Why this exists (codex review of PR8 round 3, Blocker 2)

Every pre-flight in this feature used os.Stat, which FOLLOWS a symlink and answers "yes, a directory" for `homes/team-a -> /mnt/backup/team-a`. The walk disagrees: filepath.WalkDir lstats its root, sees a symlink rather than a directory, does not descend, and hands the callback exactly one path — the root — which WriteWorkspaceHomeTar skips unconditionally. The result is a well-formed archive with ZERO entries and no error anywhere, and since the daemon destroys the workspace's HOME volume before it reads a byte of the body, that archive extracts cleanly over the wreckage and the CLI prints "imported".

Resolved rather than refused

Refusing a symlinked --from would also be safe, and it would be worse: a symlink is how an operator points at a home that lives on another disk, and "we followed the link you gave us" is what every other tool they use does. The cost of following it is bounded — this is a READ of a directory the operator named, and the archive it produces is the same one a --from of the target would produce.

Only the FINAL component is resolved, and only when it is itself a link. An intermediate symlink needs no special handling (WalkDir lstats the root, which is a directory, and descends normally), and resolving one would only make the path in the confirmation prompt less like the one the operator typed.

Links INSIDE the tree are untouched and still cross as links — see WriteWorkspaceHomeTar's contract for why that asymmetry is deliberate: the root is the thing the operator NAMED, while the links inside it are the structure of the home itself.

func SanitizeURLForLogging added in v0.1.0

func SanitizeURLForLogging(raw string) string

SanitizeURLForLogging returns a copy of raw with every recognized credential shape (userinfo anywhere in the string, and any known credential-carrying query parameter) replaced with a redacted placeholder — safe to embed in an error message, log line, or persisted StatusMessage even when raw itself might carry a secret (PR-2a codex round-2 Blocker 1 sibling sweep: every site that echoes a caller-supplied or not-yet-validated URL back into an error/log routes through this instead of interpolating the raw string directly). Deliberately over-redacts rather than under-redacts — e.g. a legitimate scp-like "git@host:path" login prefix reads as "REDACTED@host:path" when run through this on a raw, not-yet-normalized string — since this function's only job is "never let a real secret through," not "produce a pretty error message."

func StatTranscript

func StatTranscript(rootDir, runtimeID string) (os.FileInfo, error)

StatTranscript returns os.FileInfo for the transcript.log of the given runtimeID. Returns os.ErrNotExist if the file does not exist (e.g. runtime was gc'd).

func UpdateJob

func UpdateJob(dbtx db.DBTX, j *Job) error

func WorkspaceHomeSourceHasEntries added in v0.1.0

func WorkspaceHomeSourceHasEntries(root string) (bool, error)

WorkspaceHomeSourceHasEntries reports whether root holds anything WriteWorkspaceHomeTar would put in the archive.

Why a separate question (codex round 3, Blocker 2, second half)

The symlinked root was ONE way to produce an archive with no entries. It is not the only one: a --from with a typo in it, a backup directory that was never populated, a mount that is not mounted, all land in the same place — and that place is uniquely destructive, because the daemon removes the HOME volume before it reads the body. So the outcome is refused on its own terms rather than only its known causes, and it is refused on BOTH sides of the wire (see Runner.ImportWorkspaceHome's own check, which is the one that sits on the same side as the deletion).

Refusing an empty source costs nothing an operator needs: "make this workspace's home empty" is `boid workspace remove` plus a re-create, which says what it means and does not run through a migration command.

Cost

It stops at the first entry that would be carried (fs.SkipAll), so on a real home it is one readdir. The pathological input — a directory holding only sockets and FIFOs — is the only one that walks the whole tree, and it is exactly the input whose answer cannot be short-circuited.

func WorkspaceHomesDir added in v0.0.13

func WorkspaceHomesDir(runtimesDir string) (string, error)

WorkspaceHomesDir returns ~/.local/share/boid/homes, the directory under which every workspace's home USED to live (docs/plans/home-workspace-volume.md 「レイアウト」).

PR6 status: the dispatcher no longer writes here

As of PR6 of docs/plans/workspace-home-volume-persistence.md a workspace home is a docker named volume (dockerres.WorkspaceHomeVolumeName), so resolveWorkspaceHome neither creates nor reads anything under this directory. PR7 finished 論点 a-2's rewiring, so internal/api's size-reporting, orphan-detection and `workspace remove` handlers now go through the engine (dispatcher.WorkspaceHomeVolumeStore) rather than through this path, and the intermediate state PR6 documented here — silent no-op deletes, empty sizes, no orphans — is over.

This function is kept, and still exported, for the legacy root itself: it is where the pre-PR6 homes live, and PR8's migration CLI resolves them from here — `boid workspace import-home`'s --from default is <this>/<slug>, computed in cmd/workspace_import_home.go's defaultWorkspaceHomeSource with an EMPTY runtimesDir (a CLI has no way to know the daemon's, and the fallback branch below is exactly where a pre-PR6 install put them).

Existing directories under this root are NOT deleted by PR6, and PR8 does not delete them either: the migration only READS them, which is what makes it re-runnable and what makes a failed migration recoverable.

Prefers deriving from runtimesDir when non-empty. Deriving homes/ from whatever root the runtime dirs use means a daemon instance running against an isolated data dir (e.g. every test in this codebase that spins up a real server) gets its own isolated homes/ next to its own runtimes, instead of every such instance converging on one global ~/.local/share/boid/homes and leaking into the real developer machine's home directory during `go test`. Falls back to the $XDG_DATA_HOME / ~/.local/share/boid convention only when runtimesDir is empty (minimal test wiring that constructs a bare &Runner{}, or a daemon build that never wired RuntimesDir).

Note that root is NOT the daemon's persistent data root, despite what this comment claimed while the userns backend still existed (it named runtimesDirFor(cfg) — filepath.Dir(cfg.DBPath) + "/runtimes" — and called it "the same per-installation data root skills/ already lives under"; the daemon stopped writing a skills/ dir there at all in PR3 of docs/plans/workspace-home-volume-persistence.md). server/wire.go wires Runner.RuntimesDir from hostVisibleRuntimesDirFor(cfg) unconditionally, which resolves under cfg.SocketPath's dir = BOID_RUNTIME_DIR, typically tmpfs — see that function's own doc comment. That tmpfs is precisely the persistence regression PR6 repaired by moving the home off this root entirely.

Types

type CommandBroker

type CommandBroker interface {
	// RegisterCommands takes the short-name-keyed view of resolved host
	// commands (ResolveHostCommands' byName return value —
	// docs/plans/phase5-shim-and-task-context.md, "5a: shim
	// 固定ディレクトリ化" PR1). As of the 5a-3 cutover (PR3) this is the sole
	// broker key — the shim always sends the declared short name as
	// ExecRequest.Command (sandbox.CommandFromArgv0 — every shim's
	// bind-mount basename equals its declared name by construction under
	// sandboxShimBinDir), and the broker's pre-5a-3 absolute-path Path-scan
	// fallback was dropped in the same change.
	RegisterCommands(commands map[string]orchestrator.CommandDef, builtinPolicies map[string]sandbox.BuiltinPolicy, ctx sandbox.TokenContext, resolve SecretResolver) string
	UnregisterCommandToken(token string)
	SocketPath() string
}

CommandBroker is the dispatcher-owned behavior contract for host command brokering. The execution context is the canonical sandbox.TokenContext so adapters do not need to translate between dispatcher- and sandbox-side context shapes.

type ContainerBackendOptions added in v0.1.0

type ContainerBackendOptions struct {
	// DefaultImage is used when a spec carries no ContainerImage override.
	// Empty falls back to version.DefaultContainerImage() — see
	// NewContainerBackend's own assignment for why.
	DefaultImage string
	// PullPolicy controls image pulling (see ImagePullPolicy). Zero value
	// is ImagePullIfNotPresent.
	PullPolicy ImagePullPolicy
	// UID/GID select the `--user <uid>:<gid>` job containers run as (§決定
	// 4 — non-root; docs/plans/release-onboarding.md 決定1/PR2 — arbitrary-
	// uid, gid 0 + `g=u` group permissions, self-registered into
	// /etc/passwd at runtime rather than baked per-uid at image build
	// time). nil means "unset". A custom pair is only honored when BOTH
	// are provided (non-nil) AND uid resolves to non-zero — anything else
	// (both unset, only one set, or uid == 0) falls back to 1000:0 (the
	// non-root default — see defaultContainerGID's own doc comment for
	// why the fallback gid is 0, not 1000) rather than silently running
	// the job as root.
	//
	// gid == 0 is DELIBERATELY allowed through as a real value, not
	// rejected the way it was before PR2: compose's `user: "<uid>:0"`
	// (build/container/compose.yml) is the whole point of the gid-0
	// arbitrary-uid design, and internal/server/wire.go's
	// sandboxBackendForConfig passes the DAEMON's own os.Getuid()/
	// os.Getgid() straight through here — under that compose config
	// os.Getgid() legitimately IS 0. Only uid == 0 remains a hard reject
	// (決定 4 still requires non-root job containers; gid 0 is a *group*,
	// not "running as root").
	//
	// This is nullable (*int, not int) specifically so "unset" and
	// "explicitly 0" are distinguishable: an int-typed field couldn't
	// tell `UID: 0` (meant as "use the default") apart from a caller who
	// actually passed 0, which let a partial override like `UID: 0, GID:
	// 1000` slip through as a root container (fixed — see the PR5
	// review's Major 1). A real UID 0 override is never a use case this
	// backend supports (決定 4 requires non-root); GID 0 is (この doc
	// comment 自身、PR2 で「both resolve to non-zero」から更新).
	UID, GID *int
	// InstallID is the value stamped on every container's boid.install_id
	// label (§決定 6). Empty is valid — install_id generation lands in PR6
	// (~/.local/share/boid/install_id LoadOrCreate); PR5's ReapOrphans uses
	// a global (not install_id-scoped) label filter until then, per the
	// plan doc's PR5 TODO note.
	InstallID string
	// DiagnosticsCollector, when set, is called exactly once per exited
	// container — after containerSession.waitLoop finalizes exit state and
	// unblocks every Wait() caller, but strictly before the container (and
	// its volumes) are removed. This is the hook §決定 7's "診断回収 →
	// job fallback 処理 → resource remove" ordering contract requires: the
	// pre-fix waitLoop called close(s.done) and then immediately removed
	// the container in the same goroutine, racing ahead of any diagnostic
	// work a woken Wait() caller might still need to do against the live
	// container (e.g. a `docker inspect` for OOM/exit-reason before it's
	// gone — 決定 8's silent-exit classification, PR7's job). PR5 leaves
	// this nil (no consumer yet — see NewContainerBackend's doc comment on
	// production wiring); ContainerRemove is unconditionally sequenced
	// after it returns so a future collector can never lose its window.
	DiagnosticsCollector func(ctx context.Context, containerID string, exit backend.RuntimeExit)

	// DockerTLSCA, when non-nil, is the mTLS CA (internal/mtls.CA) Launch
	// uses to issue a short-lived per-job client certificate for any spec
	// launched with LaunchOptions.DockerEnabled — §決定5's "per-job 短命
	// client cert (mTLS) を... env で配送" (the plan's chosen delivery style;
	// a URL-path-embedded token was ruled out because DOCKER_HOST cannot
	// carry a path). nil (every pre-PR6 caller) disables this entirely: no
	// cert is issued, no DOCKER_* env is added, no bind mount is created —
	// byte-for-byte the same Launch behavior as before this field existed.
	// Real production wiring of a daemon-owned CA into this field, and of a
	// compose-reachable dockerproxy TCP listener behind DockerProxyAddr, is
	// PR6-residual/PR7 territory (see build/container/compose.yml's own
	// "NOT yet true of this file" note) — this option exists so the
	// materialize-cert / mount / env-delivery mechanics are real and
	// unit-tested ahead of that wiring landing.
	DockerTLSCA *mtls.CA
	// DockerProxyAddr is the compose-network `host:port` (typically a
	// compose service DNS name) job containers' DOCKER_HOST env should
	// point at. Ignored when DockerTLSCA is nil.
	DockerProxyAddr string
	// RuntimeDir, when non-empty, is the host-visible directory (typically
	// $BOID_RUNTIME_DIR, bind-mounted source == target into this daemon's
	// own container — build/container/compose.yml's "Persistence" header
	// comment) materializeDockerClientCert writes each job's per-job TLS
	// material (cert.pem/key.pem/ca.pem) under, as
	// <RuntimeDir>/tls/<jobID>/, instead of a fresh os.MkdirTemp("", ...)
	// directory (Major 11, PR6 codex review). This matters because Launch
	// is a DooD (docker-out-of-docker) backend: the container it creates
	// is a SIBLING via the HOST's own docker daemon, not nested inside
	// this daemon's own container, so a mount Source it hands that
	// daemon has to be a path the host filesystem actually has.
	// os.MkdirTemp's default (this daemon container's own, typically
	// unmounted, private /tmp) is not one — the sibling docker daemon
	// would either mount the wrong host directory or fail outright. Empty
	// (every pre-this-field caller/test) falls back to the prior
	// os.MkdirTemp("", ...) behavior unchanged — correct for any caller
	// NOT running under a compose deploy with BOID_RUNTIME_DIR bind
	// mounted (e.g. every existing unit test, which shares a real host
	// /tmp with its own test process either way).
	RuntimeDir string

	// TranscriptDir, when non-empty, is where openTranscriptSpool spools
	// transcript.log (and NewDefaultDiagnosticsCollector writes
	// diagnostics.json) INSTEAD of RuntimeDir — <TranscriptDir>/<containerID>/.
	// Unlike RuntimeDir, this directory does NOT need to be host-visible for
	// DooD: both files are written exclusively by the daemon process itself,
	// reading its own `docker attach`/`docker inspect`/`docker logs` calls —
	// never bind-mounted into a job container the way spec.json/state.json
	// are (writeContainerSpec's containerSpecPath/containerStatePath, which
	// DO require RuntimeDir's host-visibility). So TranscriptDir can point at
	// a real persistent volume (e.g. the daemon's own boid_state-backed data
	// home) instead of RuntimeDir's typical host tmpfs
	// (BOID_RUNTIME_DIR/XDG_RUNTIME_DIR) — fixing the "every job transcript
	// is lost on host reboot" gap hostVisibleRuntimesDirFor's own doc comment
	// (internal/server/wire.go) flags. Empty (every pre-this-field caller)
	// falls back to RuntimeDir, unchanged from before this field existed —
	// see openTranscriptSpool's own fallback.
	TranscriptDir string

	// SelfContainerID, when non-empty, is this daemon's OWN docker container
	// ID (or name) — typically `os.Getenv("HOSTNAME")`, which docker sets to
	// a container's own short ID unless overridden, inside the compose
	// daemon service itself (see sandboxBackendForConfig's wiring). PR9
	// (docs/plans/phase6-container-backend.md §決定5, §PR9): a job launched
	// with a non-empty LaunchOptions.Workspace is confined to an `Internal:
	// true` per-workspace network with no route out — the ONLY way it can
	// still reach the git gateway (mandatory: every project-visible
	// dispatch clones, see runner.go's Visibility.Clone comment), the
	// egress proxy, or the broker (docs/plans/phase6-cutover-followups.md
	// §⓪ — all three hosted in-process in this same daemon container,
	// §決定4/5) is if the daemon container ALSO joins that network, under
	// the same "boid-gateway"/"boid-egress"/"boid-broker" DNS aliases a job
	// resolves on the static `boid_internal` compose network. Empty (every
	// pre-PR9 caller, and any non-compose test/DI usage) skips the
	// self-connect step entirely — ensureWorkspaceNetwork still creates the
	// isolated network and attaches the job container to it, just without
	// also connecting the daemon, matching every unit test's expectations
	// unchanged.
	SelfContainerID string

	// BrokerTLSCA, when non-nil, is the mTLS CA (internal/mtls.CA) Launch
	// uses to issue a short-lived per-job client certificate for the
	// broker's TCP(mTLS) listener (docs/plans/phase6-cutover-followups.md
	// §⓪ "broker TCP wire completion") — the broker-side analogue of
	// DockerTLSCA above. Unlike DockerTLSCA (gated on
	// LaunchOptions.DockerEnabled — only a docker-capable job needs the
	// dockerproxy identity), Launch materializes a broker cert
	// unconditionally whenever this is non-nil: every non-foreground job
	// posts `boid job done` through the broker at minimum (the former
	// EXIT-trap replacement, internal/sandbox/runner.postJobDone), and most
	// hooks also call task-context/payload-patch RPCs, so "does this job
	// need broker RPC" is not a meaningful per-job gate the way
	// DockerEnabled is. nil (every pre-this-feature caller) disables the
	// whole feature: no cert is issued, no BOID_BROKER_TLS_* env is added,
	// no bind mount is created — byte-for-byte the same Launch behavior as
	// before this field existed. The design decision behind keeping mTLS
	// here (rather than downgrading to mtls.CA.ServerOnlyTLSConfig the way
	// the git gateway TLS fix — commit 577f9a8 — did) is documented on
	// mtls.CA.ServerOnlyTLSConfig's own doc comment and
	// docs/plans/phase6-cutover-followups.md §⓪: the broker is an
	// arbitrary-RPC endpoint (task update, job done, host-command exec),
	// not a single-purpose per-job-token-authorized clone endpoint like the
	// gateway, so per-connection client identity binding is worth keeping.
	BrokerTLSCA *mtls.CA
	// BrokerTLSAddr is a pointer to the compose-network `host:port`
	// (composeBrokerServiceName + the broker's actual bound TLS port, e.g.
	// "boid-broker:54321") job containers' BOID_BROKER_TLS_ADDR env should
	// point at. This is a POINTER, not a plain string like
	// DockerProxyAddr — unlike dockerproxy's fixed compose DNS name +
	// well-known port, the broker's TLS listener binds an OS-assigned
	// ephemeral port (internal/server/server.go's `s.broker.TLSAddr =
	// gatewayBindHost(...) + ":0"`) that is only known once Server.Start
	// has bound it, strictly AFTER sandboxBackendForConfig (internal/
	// server/wire.go) has already constructed this containerBackend inside
	// buildRuntime. internal/server.Server resolves this exact same
	// "value not known until Start runs" problem for GatewayURL via a
	// late-binding pointer (Runner.GatewayURL *string, dereferenced fresh
	// on every Dispatch) — this field mirrors that pattern one level
	// deeper: Server owns the string (brokerTLSSandboxAddr), hands
	// sandboxBackendForConfig a pointer to it at construction time, and
	// Start writes the real "boid-broker:<port>" value into it once
	// s.broker.Start has bound the listener. Launch dereferences this
	// pointer fresh on every call (not once at construction), so a job
	// launched even a long time after this backend was constructed still
	// observes the real address. nil (every non-server-wired test/caller,
	// and any deployment with BrokerTLSCA also nil) is treated the same as
	// a nil-pointing-at-empty-string — Launch adds no DOCKER_HOST-style env
	// pointing nowhere.
	BrokerTLSAddr *string
}

ContainerBackendOptions configures NewContainerBackend. Every field has a documented zero-value fallback so `ContainerBackendOptions{}` is a valid (if minimal) configuration for tests.

type DaemonStateVolumes added in v0.1.0

type DaemonStateVolumes struct {
	// StateVolumeExpected reports whether a named volume could be holding this
	// daemon's persistent state — i.e. whether an empty Names is an ANSWER or
	// a FAILURE. False is a positive finding ("the data root is an ordinary
	// directory on the root filesystem; there is no volume to reserve") and
	// callers must stay silent on it. True with a non-nil error is
	// "something is probably holding my state and I could not name it", which
	// callers must warn about.
	//
	// It is deliberately NOT "am I in a container". That question was the
	// first implementation and it was wrong in the dangerous direction: see
	// daemonStateMayLiveOnVolume.
	StateVolumeExpected bool

	// ContainerID is the daemon's own container, when it could be determined.
	// Recorded for the startup log line, so an operator can re-run the same
	// `docker inspect` by hand.
	ContainerID string

	// Names is every NAMED VOLUME mounted into this daemon's container,
	// sorted. See DetectDaemonStateVolumes for why it is all of them and not
	// only the one holding dataHome.
	Names []string

	// DataHomeCovered reports whether the daemon's own persistent data root
	// (server/wire.go's dataHomeFor(cfg) — where boid.db and secret.key live)
	// actually falls inside one of the volumes in Names. False with a
	// non-empty dataHome means name-based reservation is not covering the
	// crown jewels and the operator should be told, even though every
	// individual step succeeded.
	DataHomeCovered bool

	// DataHomeUnresolved carries why the data root could not be normalized
	// (made absolute and symlink-free) for comparison against the engine's
	// mount destinations. It is set whenever that step failed — including on
	// the error returns below, where the same reason is also folded into the
	// returned error, so a caller that reads both must not report it twice.
	// The path it exists for is the all-succeeded one, which has nowhere
	// else to report it.
	//
	// It exists because that failure has nowhere honest to go otherwise
	// [round 3 Minor 1, codex review]. It cannot be the returned error: a
	// non-nil error means "containment is INACTIVE" to the caller, and it is
	// not — the volumes were named and reserved. It cannot be silently
	// dropped either, which is what the first implementation did: with an
	// unresolvable data root and an otherwise healthy inspect, the run
	// returned a nil error and the operator was never told that
	// DataHomeCovered had been computed against a path the daemon could not
	// resolve. So it rides alongside, and the caller warns about it
	// separately from the INACTIVE case.
	//
	// DataHomeCovered is still computed (against the absolute-but-unresolved
	// spelling, the closest available approximation) rather than forced
	// false — a false there would claim the crown jewels are outside every
	// reserved volume, which is a different and equally unsupported claim.
	DataHomeUnresolved error
}

DaemonStateVolumes is what the startup self-inspection learned. It is returned even alongside a non-nil error, because StateVolumeExpected is meaningful in exactly that case: it is how the caller decides between logging nothing and logging a warning.

func DetectDaemonStateVolumes added in v0.1.0

func DetectDaemonStateVolumes(ctx context.Context, api SelfContainerInspector, dataHome string) (DaemonStateVolumes, error)

DetectDaemonStateVolumes identifies the daemon's own container and returns the named volumes mounted into it, for injection into the dockerproxy policy's reserved set (dockerproxy.Server.SetReservedVolumeNames).

Contract, by outcome

  • No volume can be holding the daemon's state (daemonStateMayLiveOnVolume says no): DaemonStateVolumes{} and a nil error, and api is never called. Bare `boid start` keeps its state in an ordinary directory on the root filesystem, where there is no volume to name — an empty result is the right answer, not a degraded one, and callers must not warn about it.
  • A volume might be holding it, and it was identified: Names populated, nil error.
  • A volume might be holding it and it was NOT identified (unknown id, ambiguous id, no docker client, inspect failed, inspect timed out): StateVolumeExpected true, Names empty, non-nil error. Callers warn once and continue. Refusing to start would be a much worse trade: it turns "a docker-capable job could read the daemon's secrets" — which is the status quo ante for every release so far — into "the daemon does not run at all" on any engine or runtime this detection does not understand.

The invariant those three outcomes rest on

EVERY non-nil error this function returns carries StateVolumeExpected=true, and StateVolumeExpected=false is returned by exactly one path — the positive finding, with a nil error. Callers therefore never have to guess which of the two a zero value meant, and "silent" is reachable only from an answer, never from a failure. It is upheld by ordering (the engine-independent classification runs before anything engine-shaped can fail) and pinned by TestDetectDaemonStateVolumes_everyErrorCarriesStateVolumeExpected. [round 2 Major 2, codex review 2026-07-26.]

Every path is bounded by selfInspectTimeout, with the two synchronous filesystem reads that no deadline can interrupt enumerated and justified in that variable's own doc comment.

Why EVERY named volume, not just the one holding dataHome

Deliberate, and the safer of the two readings the brief allowed:

  • The daemon's persistent state is not confined to dataHome. Under the compose deploy XDG_CONFIG_HOME=/home/boid/.config (config.yaml, host_commands.yaml, workspaces/<slug>/init.sh) sits OUTSIDE filepath.Dir(cfg.DBPath) and is only covered today because both happen to live under the same /home/boid mount. A dataHome-only rule would silently stop covering the config half the day someone splits it out.
  • A dataHome-containment test degrades badly when dataHome is empty, which dataHomeFor genuinely can return (see its own doc comment). "Every volume I hold" has no such degenerate case.
  • There is no legitimate reason for a sandboxed job to mount a volume the daemon itself has mounted. Over-reserving costs a job nothing it can articulate a use for; under-reserving costs secret.key.
  • It cannot drift. A second daemon-owned volume added to compose later is protected the day it is added, with no second PR and no shared constant for two packages to disagree about.

Bind mounts are excluded on purpose: their Source is a host path, not a volume name, so it is not the kind of thing the policy's name rules can match — and HostConfig.Binds / Mounts[].Type=bind are already denied wholesale by dockerproxy, which covers that shape completely.

type ImagePullPolicy added in v0.1.0

type ImagePullPolicy int

ImagePullPolicy controls when containerBackend.Launch pulls an image before creating a container from it (docs/plans/ phase6-container-backend.md §PR5's "default/pull policy").

const (
	// ImagePullIfNotPresent (the default) pulls only when the image is not
	// already present in the local docker image store.
	ImagePullIfNotPresent ImagePullPolicy = iota
	// ImagePullAlways pulls before every Launch, even when the image is
	// already present locally (picks up a moved tag).
	ImagePullAlways
	// ImagePullNever never pulls; Launch fails if the image is missing
	// locally.
	ImagePullNever
)

type Job

type Job struct {
	ID             string    `json:"id"`
	TaskID         string    `json:"task_id"`
	ProjectID      string    `json:"project_id"`
	HandlerID      string    `json:"handler_id"`
	DisplayName    string    `json:"display_name,omitempty"` // persisted via the jobs.display_name column (migration 0027)
	Role           string    `json:"role"`
	RuntimeID      string    `json:"runtime_id,omitempty"`
	Interactive    bool      `json:"interactive"`
	TTY            bool      `json:"tty"`
	Status         JobStatus `json:"status"`
	ExitCode       int       `json:"exit_code,omitempty"`
	Output         string    `json:"output,omitempty"`
	ExecutionState string    `json:"execution_state,omitempty"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
}

func GetJob

func GetJob(dbtx db.DBTX, id string) (*Job, error)

func ListJobsByTask

func ListJobsByTask(dbtx db.DBTX, taskID string) ([]*Job, error)

func ListJobsFiltered

func ListJobsFiltered(dbtx db.DBTX, filter JobFilter) ([]*Job, error)

ListJobsFiltered returns jobs across all tasks matching the given filter.

type JobCompletionResult

type JobCompletionResult struct {
	Output   string
	ExitCode int
}

JobCompletionResult is the result delivered via WaitForJobCtx/CompleteJob.

type JobContextSnapshot added in v0.0.13

type JobContextSnapshot struct {
	Instructions              []orchestrator.RoutedInstruction
	Env                       WorkspaceEnvView
	Payload                   json.RawMessage
	PayloadPatchAllowedTraits []orchestrator.TraitType
	WorkspacePeerAdvertise    map[string]PeerAdvertise
}

JobContextSnapshot captures the per-job data the Phase 5b PR1 task-context RPCs (`boid task instructions` / `boid task env` / `boid task payload`, docs/plans/phase5-shim-and-task-context.md) need but which has no standalone DB representation to re-derive live from:

  • Instructions: the job's own routed instruction (JobSpec.Instruction, see orchestrator.DispatchPlanner.PlanHook's selectInstruction). This is NOT the task's "active" instruction — orchestrator.Evaluator fires every agent-kind hook whose agent appears anywhere in the instruction history (extractInstructionAgents), not just the most recent entry, so a claude-code hook and a codex hook can both be dispatched from the same task even though only one of them matches the history's last entry. selectInstruction/FilterInstructions only route the *last* entry, so the other hook's job gets Instruction=nil — and `boid task instructions` correspondingly returns an empty list for that job (routedInstructionSlice below returns [] when inst==nil). Deriving "current instructions" from the task row instead of the job's own JobSpec.Instruction would hand a claude job the codex instruction (or vice versa) — a real regression codex review caught before merge; see wiring-seams.md #13. orchestrator.CurrentInstructions still exists for task-row-level callers that are NOT this RPC — see its own doc comment.
  • Env: the reduced environment view (allowed_domains + resolved host commands, both dispatch-time-only runtime facts).
  • Payload: the trait-filtered payload (depends on the firing hook's declared Traits.Consumes — plan-time-only data that JobSpec does not carry forward).
  • PayloadPatchAllowedTraits: the firing hook's own `traits.produces` list, captured at dispatch time (JobSpec.HookTraitsProduces — event.Hook.Traits.Produces, verbatim). Phase 5b PR7's `boid task update --payload-patch` RPC (docs/plans/phase5-shim-and-task-context.md) uses this to gate its merge exactly like a completing hook's own file-based payload_patch would be gated (HandlerResult.allowedTraits in coordinator.go) — never by re-resolving the hook against current (possibly since-edited) project meta, which is a TOCTOU staleness bug (codex review, wiring-seams.md #17's Major 1). nil means unrestricted (see JobSpec.HookTraitsProduces's own doc comment for when that applies).
  • WorkspacePeerAdvertise: the {name, clone URL, reference path, clone dir} view of this job's workspace peers, keyed by peer project ID (Runner.buildPeerAdvertise, gitgateway_wire.go — the same value fed into SandboxRuntimeInfo.WorkspacePeerAdvertise). nil when the gateway isn't wired, the job isn't in clone mode (spec.Visibility.Clone == nil), or no peer has a resolvable upstream_url. Feeds `boid project list`'s BoidOpProjectList response (internal/server/boid_executor.go) — the CLI replacement docs/plans/phase5-shim-and-task-context.md 決定事項4 left as a future item. Contains a raw git gateway token (embedded in CloneURL) scoped to THIS job's own permissions; the broker's BoidOpProjectList case MUST reject a request whose JobID doesn't match the calling token's own JobID, or a readonly job could read another job's writable-token clone URL and escalate.

Runner.Dispatch populates one per job; UnregisterJob discards it, mirroring the broker token's own lifecycle so nothing outlives the job it describes.

type JobEventSink

type JobEventSink interface {
	JobCreated(taskID, jobID string)
}

JobEventSink lets the runner report job lifecycle events to a subscriber (typically the web SSE hub) without taking a hard dependency on it. All methods are best-effort: implementations should not block or fail the caller — they exist to push UI refresh hints.

type JobFilter

type JobFilter struct {
	Status       string
	Interactive  *bool // nil = no filter
	TasklessOnly bool  // true = only jobs where task_id IS NULL
}

JobFilter specifies optional filters for listing jobs globally.

type JobRepository

type JobRepository struct {
	// contains filtered or unexported fields
}

func NewJobRepository

func NewJobRepository(db db.DBTX) *JobRepository

func (*JobRepository) CreateJob

func (r *JobRepository) CreateJob(job *Job) error

func (*JobRepository) GetJob

func (r *JobRepository) GetJob(id string) (*Job, error)

func (*JobRepository) ListJobsByTask

func (r *JobRepository) ListJobsByTask(taskID string) ([]*Job, error)

func (*JobRepository) ListJobsFiltered

func (r *JobRepository) ListJobsFiltered(filter JobFilter) ([]*Job, error)

func (*JobRepository) UpdateJob

func (r *JobRepository) UpdateJob(job *Job) error

type JobStatus

type JobStatus string
const (
	JobStatusRunning   JobStatus = "running"
	JobStatusCompleted JobStatus = "completed"
	JobStatusFailed    JobStatus = "failed"
)

type OrchestratorAdapter

type OrchestratorAdapter struct {
	// contains filtered or unexported fields
}

OrchestratorAdapter adapts dispatcher execution to orchestrator interfaces.

func NewOrchestratorAdapter

func NewOrchestratorAdapter(dispatcher dispatchBackend, planner *orchestrator.DispatchPlanner) *OrchestratorAdapter

func (*OrchestratorAdapter) ExecuteHook

func (a *OrchestratorAdapter) ExecuteHook(ctx context.Context, event *orchestrator.HookFireEvent) (string, error)

func (*OrchestratorAdapter) WaitForJob

type PeerAdvertise added in v0.0.10

type PeerAdvertise struct {
	// Name is the peer's repo name (the last segment of its upstream_url's
	// host/owner/repo form), used purely for display/discoverability.
	Name string
	// CloneURL is the full gateway clone URL for this peer, scoped fetch-only
	// to this job's gateway token (docs/plans/container-based-boid.md
	// 「workspace peer プロジェクト」: peers are fetch-only; writing to a peer
	// means a cross-project child task instead).
	CloneURL string
	// ReferencePath is the sandbox-internal RO bind-mount path of the peer's
	// `.git` (sandboxClonePeerReferenceDirFmt), usable as `git clone
	// --reference` when an agent does clone the peer.
	ReferencePath string
	// CloneDir is the suggested absolute sandbox-internal directory for this
	// peer, e.g. "/workspace/bm-next-lp" (workspace 親化リファクタリング,
	// nose 2026-07-13 decision). It is only a suggestion — nothing enforces
	// an agent actually clones the peer here — but using the same leaf name
	// projectDirName would resolve for the peer's own project (were it
	// dispatching as self) keeps the directory name stable regardless of
	// which project happens to be the one dispatching, and keeps it off
	// $HOME/tmp (both tmpfs, RAM-backed).
	CloneDir string
}

PeerAdvertise is the {name, clone URL, reference path} view of a workspace peer project (docs/plans/git-gateway-cutover.md PR6 cutover 「5. peer advertise の変更」). Built by Runner.buildPeerAdvertise from the peer's captured upstream_url + this job's gateway token; it intentionally carries no host filesystem path — clone-mode jobs have no host path visible for a peer project any more, only the sandbox-internal RO reference dir (ReferencePath) and the gateway clone URL an agent would `git clone` from if it wants to see the peer's working tree.

Exposed to the agent via `boid project list`'s clone_url/reference_path/ clone_dir fields (2026-08): this used to be advertised via environment.yaml's `workspace_projects` section, removed by the environment.yaml 縮退 (docs/plans/phase5-shim-and-task-context.md 決定事項 4, Phase 5b PR5). The replacement RPC carries this same struct through JobContextSnapshot.WorkspacePeerAdvertise (job_context.go), tracked by Runner.Dispatch and read by BoidOpProjectList (internal/server/boid_executor.go) — NOT through SandboxRuntimeInfo.WorkspacePeerAdvertise, which stays unused; see that field's own doc comment.

type ProjectLookup

type ProjectLookup interface {
	GetProject(id string) (*orchestrator.Project, error)
	ListProjects() ([]*orchestrator.Project, error)
}

ProjectLookup lets dispatcher resolve ProjectID → WorkspaceID and enumerate workspace peers, so workspace-peer authorization and peer-visibility concerns stay inside dispatcher instead of leaking into JobSpec.

type ProxyAllocator added in v0.0.8

type ProxyAllocator interface {
	GetOrCreate(workspaceID string, allowed []string) (int, error)
}

ProxyAllocator returns the loopback port of an HTTP(S) egress proxy bound to the given workspace, after applying allowed as its allowlist. The listener is long-lived: subsequent calls for the same workspace reuse the port and live-swap the allowlist. Satisfied by *sandbox.ProxyManager.

type Runner

type Runner struct {
	DB          *sql.DB
	Broker      CommandBroker
	SecretStore *SecretStore
	Projects    ProjectLookup
	// Backend is the SandboxBackend every sandbox launch/attach/resize/
	// signal call site routes through (sandboxBackend() below). Production
	// wiring (internal/server/wire.go's buildRuntime) always sets this to a
	// real containerBackend — container is the only sandbox backend since
	// PR-4 removed the userns backend (docs/plans/volume-only-daemon.md
	// §論点e) and the config-driven userns/container branch that used to
	// leave this nil for the userns default. Tests set it to a fake
	// backend.SandboxBackend directly (the same DI seam this field has
	// always been).
	Backend backend.SandboxBackend
	// InstallID mirrors ContainerBackendOptions.InstallID (§決定6): threaded
	// through separately here (not read back off Backend) so
	// startDockerProxy's per-job SetWorkspaceNetwork call (PR9, §決定5) can
	// compute the exact same containerWorkspaceNetworkName the container
	// backend's own Launch computed for this job's workspace, without a
	// type assertion back into *containerBackend. Empty (every pre-PR9
	// caller) is valid — containerWorkspaceNetworkName treats it as
	// "noinst", matching NewContainerBackend's own unset-InstallID default.
	InstallID string
	// Hydrator optionally resolves a project's workspace-hydrated
	// ProjectMeta (project.yaml `meta.name` plus workspace merge) by project
	// ID. It is used only for workspace-peer name resolution in
	// buildPeerAdvertise — the self project's name is already resolved at
	// JobSpec-build time via Visibility.ProjectName and does not need this.
	// nil (test wiring, or a daemon build that doesn't wire it) makes
	// buildPeerAdvertise degrade to the pre-existing basename fallback, same
	// as orchestrator.DispatchPlanner.Hydrator's nil behavior.
	Hydrator orchestrator.MetaHydrator
	// Workspaces resolves WorkspaceMeta at dispatch time for the workspace
	// the dispatched project is linked to. When nil (test wiring, missing
	// disk) the runner falls back to the global floor for proxy allowlist
	// resolution. Together with ProxyAllocator it implements the
	// workspace-scoped proxy egress allowlist (project-workspace-allowed-domains).
	Workspaces     WorkspaceLookup
	ProxyAllocator ProxyAllocator
	BoidBinary     string
	ServerSocket   string
	// ProxyPort is the default-workspace proxy port (back-compat fallback
	// when the per-workspace allocator path isn't wired or returns an
	// error). Workspaces with no overrides reuse this port via the
	// allocator's GetOrCreate("default", ...) entry.
	ProxyPort *int
	// NoWorkspaceProxyPort is the port of the dedicated egress proxy
	// listener internal/server's Server.Start binds once at daemon startup,
	// keyed by NoWorkspaceProxyKey, for jobs with no workspace at all
	// (workspaceID == "" — see resolveWorkspaceProxy's doc comment). Same
	// late-binding-via-pointer pattern as ProxyPort (Start fills in the int
	// this points at after the listener is actually bound). nil (test
	// wiring, or a daemon build that never calls Start) makes
	// resolveWorkspaceProxy's empty-workspaceID branch return port 0 —
	// deliberately NEVER ProxyPort's value: falling back to the real
	// default workspace's own (editable, live-widening) listener is exactly
	// the aliasing bug NoWorkspaceProxyKey's distinctness exists to
	// prevent, and a port-0 dispatch failing loudly is safer than a silent
	// isolation leak.
	NoWorkspaceProxyPort *int
	// AllowedDomains is the daemon-wide proxy egress allowlist floor
	// (built-in defaults ∪ config.yaml's sandbox.allowed_domains), captured
	// once when this Runner is built (internal/server/wire.go's
	// buildRuntime). Workspace overrides are added on top per-dispatch via
	// orchestrator.ResolveAllowedDomains.
	//
	// A plain []string, not a getter — sandbox.allowed_domains is
	// ReloadRestartRequired (PR #830 round-4 simplification, nose
	// directive; see ReloadDynamic's own doc comment in
	// internal/config/schema.go): `boid config set sandbox.allowed_domains
	// ...` persists to config.yaml immediately but only reaches this field
	// on the next daemon restart, when wire.go rebuilds the Runner from the
	// freshly-loaded config. nil is a valid, cheap-to-construct test
	// default meaning "no floor".
	AllowedDomains []string
	RuntimesDir    string
	// DataHomeDir is the daemon's OWN persistent data root —
	// server/wire.go's dataHomeFor(cfg), which in a real deployment is
	// filepath.Dir(cfg.DBPath): the directory boid.db / web_secret /
	// install_id / secret.key / tls/ / kits/ already live in, which
	// under the volume-only compose deploy is the `boid_state` named volume.
	// (dataHomeFor also has a socket-path fallback and an empty case that
	// only test wiring reaches — see its own doc comment.)
	//
	// Deliberately NOT derivable from RuntimesDir: since the volume-only
	// pivot those are two genuinely different roots (RuntimesDir resolves via
	// hostVisibleRuntimesDirFor(cfg) to BOID_RUNTIME_DIR, host-visible but
	// tmpfs). Currently consumed only by workspaceHomeMetaDir — the workspace
	// home init marker, the init lock, and the private temp copy of init.sh
	// (docs/plans/workspace-home-volume-persistence.md 論点b, PR2).
	//
	// Empty (minimal test wiring, or a daemon build that never wired it)
	// falls back to $XDG_DATA_HOME/boid; see workspaceHomeMetaDir's own doc
	// comment. That fallback resolves against the ambient environment, so any
	// package whose tests construct a bare &Runner{} and reach Dispatch must
	// install testutil/homeenv's TestMain isolation or it will operate on the
	// developer's real boid installation.
	DataHomeDir string
	// ReservedVolumeNames is the set of docker volume names startDockerProxy
	// injects into every per-job dockerproxy's policy, on top of the static
	// "boid-ws-" namespace that always applies
	// (dockerproxy.Server.SetReservedVolumeNames).
	//
	// Production wiring (internal/server/wire.go's buildRuntime) fills this
	// with the named volumes the daemon found mounted into its OWN container
	// at startup — under the compose deploy, `boid_boid_state`, which holds
	// boid.db / secret.key / tls/ca.key / web_secret / install_id. That name
	// is chosen by the compose project, not by boid, so it matches no prefix
	// rule and had to be discovered: see DetectDaemonStateVolumes.
	//
	// Captured once at Runner construction, exactly like AllowedDomains: the
	// answer cannot change without the daemon container itself being
	// recreated, at which point this process is gone too.
	//
	// nil is valid and is the correct value for every deployment where the
	// daemon is NOT in a container (bare `boid start` — no state volume
	// exists to name) as well as for test wiring. It leaves the policy
	// behaving exactly as it did before this field existed.
	ReservedVolumeNames []string
	JobEvents           JobEventSink // optional; nil disables job lifecycle broadcasts

	// GitGateway is the git gateway's job-token registry
	// (docs/plans/git-gateway-cutover.md PR4: gateway lifecycle + dispatch
	// wiring). nil disables gateway token registration entirely — Dispatch
	// and UnregisterJob treat that as a no-op rather than panicking (test
	// wiring, or a daemon build without the gateway constructed). PR4 is
	// inert: registration happens, but nothing inside the sandbox talks to
	// the gateway yet (that's PR5/PR6).
	GitGateway *gitgateway.Registry
	// GatewayURL points at the daemon's own gateway listener address string,
	// filled in by Server.Start once the gateway's TCP listener is bound —
	// the same late-binding-via-pointer pattern as ProxyPort, since the
	// gateway (like the default proxy listener) is only known once Start
	// has run. nil disables gateway URL propagation into SandboxRuntimeInfo.
	GatewayURL *string
	// GatewayCAPEM points at the daemon's internal CA's own PEM-encoded
	// certificate (mtls.CA.CertPEM), filled in by Server.Start alongside
	// GatewayURL. A container-backend clone-mode job needs this to trust
	// the git gateway's TLS server certificate (see
	// SandboxRuntimeInfo.GatewayCAPEM's own doc comment for why a client
	// certificate is not also needed). nil disables CA propagation.
	GatewayCAPEM *[]byte

	// GatewayCredentials resolves forge auth for the daemon's OWN direct
	// git operations against a bare repo (docs/plans/volume-only-daemon.md
	// §論点b, PR-2b) — the same gitgateway.CredentialProvider bare_repo.go's
	// CloneBareRepo/FetchBareRepo already consume (see those functions'
	// own doc comments for why this is a direct CredentialProvider.Resolve
	// call, not a round trip through the HTTP reverse proxy: there is no
	// job token or sandbox involved for this specific use — Dispatch calls
	// FetchBareRepo itself, from the daemon process, before staging a
	// per-job checkout via PrepareJobCheckout). nil (every pre-PR-2b
	// caller, and any test wiring that doesn't need per-job clone) skips
	// the FetchBareRepo refresh step entirely — matches CloneBareRepo/
	// FetchBareRepo's own "creds nil -> proceed unauthenticated" fail-open
	// convention, appropriate here too since a project's bare repo may
	// simply be public.
	GatewayCredentials *gitgateway.CredentialProvider

	// APIGateway is the API gateway's job-token registry (docs/plans/
	// api-gateway.md PR1). nil disables API gateway token registration
	// entirely — Dispatch and UnregisterJob treat that as a no-op rather
	// than panicking, mirroring GitGateway's own nil-disables convention.
	APIGateway *apigateway.Registry
	// APIGatewayServicesFloor is the daemon-wide set of API gateway service
	// names enabled for every workspace (config.yaml services_floor —
	// docs/plans/api-gateway.md §3), captured once when this Runner is
	// built, exactly like AllowedDomains is for the proxy egress allowlist.
	// A workspace's own WorkspaceMeta.Services list adds to this floor at
	// dispatch time via orchestrator.ResolveEnabledServices.
	APIGatewayServicesFloor []string

	// WithProjectLock, when set, runs a function while holding the daemon's
	// project lifecycle mutex — api.ProjectAppService.projectMu, via that
	// service's own exported WithProjectLock method — the same lock
	// CreateProject/CreateProjectFromGitURL/DeleteProject/FetchProject
	// already serialize their own create/delete/fetch critical sections
	// against each other (PR834 PR-2b round-2 codex review Major 1). The
	// entire project-registry-guarded dispatch section below — gateway-token
	// registration, the selfProject lookup, the gatewayCloneURL/
	// peerAdvertise snapshot, managed-bare-repo classification, AND the
	// FetchBareRepo + PrepareJobCheckout pair against selfProject.WorkDir —
	// runs as one closure inside this lock (round-3 codex review Major 1:
	// round-2 only wrapped the final fetch+clone call, leaving the lookup
	// and URL/token snapshot that feed it unguarded — see Dispatch's own
	// "project-registry-guarded dispatch section" comment for the mixed-
	// checkout race that left open), so a concurrent `project rm` + re-add
	// at the identical managed path cannot land ANYWHERE in that sequence
	// and produce a mixed checkout (this project's gateway URL/credentials
	// cloned against a DIFFERENT, just-re-registered project's bare-repo
	// content).
	//
	// internal/dispatcher cannot import internal/api directly to call
	// ProjectAppService.WithProjectLock itself — internal/api already
	// imports internal/dispatcher for wiring, so the reverse direction would
	// be an import cycle — so internal/server/wire.go closes over the same
	// ProjectAppService instance's WithProjectLock method and hands it here
	// as a plain function value instead (see wire.go's assignment, right
	// next to GatewayCredentials above, which is wired from the identical
	// gwCreds for the identical reason: no cross-package type dependency,
	// just a shared instance closed over once at startup).
	//
	// nil (any dispatcher unit test that does not wire an
	// api.ProjectAppService at all, and any pre-PR-2b caller) means "no
	// serialization" — the per-job-clone step below runs unguarded exactly
	// as it did before this field existed. Production wiring always sets it.
	WithProjectLock func(fn func() error) error

	// ConfirmWorkspaceExists reports whether a workspace row still exists,
	// returning the service's own error (an *api.StatusError, i.e. a 404) when it
	// does not. server/wire.go closes over api.ProjectAppService.GetWorkspace to
	// supply it — the same no-cross-package-dependency trick WithProjectLock
	// above uses, and for the same reason (internal/api already imports
	// internal/dispatcher, so the reverse direction would be an import cycle).
	//
	// ImportWorkspaceHome is the only caller, and it calls this while holding its
	// in-flight registration — which is the entire point (codex round 2, Major
	// 1). The API handler already checks the workspace before reading the body;
	// what that check cannot do is stay true, because `boid workspace remove`
	// deletes the row and then the volume, and a removal that completes between
	// the handler's check and the migration's first engine call leaves the
	// migration minting a HOME volume for a workspace that no longer exists —
	// full of harness credentials, unreachable by any dispatch, and no longer
	// deletable by `workspace remove` (it 404s on the missing row). Re-checking
	// under the registration is what makes the answer hold: from that point a
	// removal of this workspace is refused (workspaceHomeInFlight.beginRemoval).
	//
	// nil means "no confirmation", which is what every dispatcher unit test that
	// does not wire an api.ProjectAppService gets, and what the pre-PR8 behaviour
	// was. Production wiring always sets it. The consequence of leaving it nil is
	// narrow rather than open-ended: the API handler's own pre-check still runs,
	// so what is lost is only the re-check under the registration.
	ConfirmWorkspaceExists func(slug string) error
	// contains filtered or unexported fields
}

func Wire

func Wire(cfg WireConfig) *Runner

func (*Runner) BeginWorkspaceHomeRemoval added in v0.1.0

func (r *Runner) BeginWorkspaceHomeRemoval(workspaceID string) (done func(), err error)

BeginWorkspaceHomeRemoval excludes a migration of workspaceID's HOME volume for as long as the returned function has not been called, and is what api.WorkspaceHandler.Remove brackets its row-and-volume deletion with.

It lives on the Runner rather than on the volume store because the registry it consults is the Runner's, and it has to be THE SAME instance the dispatch and migration paths register in — two objects with two registries would exclude nothing while looking exactly like this. That is also why the API layer discovers it through the same interface value it calls ImportWorkspaceHome on (api.WorkspaceHomeImporter) rather than through a second field.

The only error it returns wraps ErrWorkspaceHomeBusy, so the caller has one thing to map (409). A workspaceID that cannot name a workspace home at all — normalizeWorkspaceSlug rejects it — gets a no-op release and a nil error instead: there is no home for it to exclude anybody from, and the caller's own next step (Service.RemoveWorkspace) is the authority on rejecting the argument. Returning an error there would make the caller distinguish two failures where only one is about exclusion.

func (*Runner) CanAttach added in v0.1.0

func (r *Runner) CanAttach(ctx context.Context, runtimeID string) bool

CanAttach reports whether runtimeID can currently be adopted by the configured SandboxBackend — i.e. whether an attach/resize/signal ingress against it should be allowed. Routes through Adopt so the backend answers with its own notion of session liveness (codex review Blocker 2 on PR #816) rather than internal/server/job_runtime_routes.go's resolveAttachableJob type-asserting onto a backend-specific capability directly.

sessionControlCallTimeout is layered on top of the caller's own ctx as a FLOOR, not a replacement (next-session-container-backend-followups.md #2, Opus review of PR #857): CanAttach's only caller (job_runtime_routes.go's resolveAttachableJob) passes req.Context(), which stays open for as long as the HTTP client stays connected — before this, that gave Adopt an effectively unbounded ctx. Adopt's in-flight-join wait already selects on ctx (Major 1 in session_control_call_deadline_test.go), so this did not itself hang — but an unbounded CanAttach caller could still sit as the in-flight attempt's "owner" against a wedged engine, and every bounded joiner for the SAME runtimeID (StopJobRuntime, SignalJobRuntime, ...) would then exhaust its own sessionControlCallTimeout budget waiting on that owner instead of the engine ever answering — `boid task stop` failing every time, not hanging, but never succeeding either. context.WithTimeout(ctx, ...) keeps whichever of the caller's own deadline (if shorter) and sessionControlCallTimeout fires first, and the caller's own cancellation (the HTTP client disconnecting) still propagates through unchanged, because the new ctx is derived FROM ctx rather than from context.Background().

The bool result here still can't distinguish "Adopt legitimately found nothing" from "ctx was done before Adopt could resolve" — both surface identically as job_runtime_routes.go's 409 "job runtime does not support attach" to the HTTP caller. That ambiguity predates this fix (it already existed whenever ctx itself expired before this change) and changing the HTTP-visible contract (status code / response shape) to fix it is left alone here; see this PR's description for why.

The boid.log side of that same ambiguity IS fixed (NB-1, Opus independent review of this PR): when ok is false because ctx.Err() != nil rather than a legitimate Adopt miss, this logs — the same distinction StopJobRuntime/SignalJobRuntime/ResizeRuntimeID/the four runtime_subscriber_export.go routes already make, so an operator grepping boid.log for "why did this attach/resize get rejected" is not stuck guessing between "no such runtime" and "the engine never answered". Unlike those five, ctx here is derived from the CALLER's own ctx (not context.Background()), so ctx.Err() at this point can be either DeadlineExceeded (the floor fired, or the caller's own deadline did) OR Canceled (the HTTP client disconnecting mid-request — job_runtime_routes.go passes req.Context()). The level differs between the two (nit, Opus independent review of this PR, round 2): DeadlineExceeded is Warn, the same actionable signal StopJobRuntime's own Warn is (the engine may be wedged); Canceled is only Debug — an ordinary, non-actionable client disconnect, not evidence of anything wrong with the engine, so it must not carry the same "something needs attention" weight as the deadline case. The message and the logged ctx.Err() value stay agnostic between the two rather than hardcoding "engine did not respond" for a cause that might just be a client giving up.

func (*Runner) CleanupTaskWindow

func (r *Runner) CleanupTaskWindow(taskID string)

CleanupTaskWindow stops all tracked runtimes associated with a task.

[Blocker 3, PR7 codex review]: routes through StopJobRuntime (itself SandboxBackend.Adopt → SandboxSession.Stop, see its doc comment) so aborting a task actually stops its job container, not just an in-memory bookkeeping entry.

func (*Runner) CloseInput added in v0.0.13

func (r *Runner) CloseInput(jobID string) error

CloseInput implements RuntimeInputWriter for Runner. It resolves jobID to a runtimeID via the jobs table, then adopts a SandboxSession and closes its input through it. Adopt is bounded — see Subscribe's doc comment above for why, including the ctx.Err()-gated Warn + wrapped error below, matching WriteInput/ResizeRuntime above (next-session-container-backend- followups.md #3, Opus review of PR #857).

func (*Runner) CompleteJob

func (r *Runner) CompleteJob(jobID string, result JobCompletionResult)

CompleteJob signals the waiting dispatcher that a job has completed.

func (*Runner) Dispatch

func (r *Runner) Dispatch(ctx context.Context, spec *orchestrator.JobSpec, cleanup orchestrator.CleanupFunc) (jobID string, dispatchErr error)

Dispatch launches a sandbox for the given JobSpec. The optional cleanup callback (typically provided by orchestrator's PlanHook for staging dir teardown) runs after the sandbox process has exited.

func (*Runner) ImportWorkspaceHome added in v0.1.0

func (r *Runner) ImportWorkspaceHome(ctx context.Context, workspaceID string, tarStream io.Reader) (WorkspaceHomeImportResult, error)

ImportWorkspaceHome replaces workspaceID's HOME volume with the contents of tarStream, and guarantees the next dispatch runs its init.sh once.

The guarantee, and why it takes two mechanisms (論点 f)

The skip condition (workspaceHomeInitialized) is five ANDs, and a migration changes NONE of them by itself: it copies contents, and the marker describes the script, the generation, the skeleton and the volume's IDENTITY — never its contents. A settled workspace would therefore keep skipping init and the host-era toolchain, with its host-era absolute paths, would live on forever. 論点 f calls that the hole and requires the migration to close it itself. Both of its options are taken, and the ORDER is what makes either one enough on its own:

  1. Remove the volume. This is also the in-use check (see below) and is the only step that can refuse WITHOUT side effects, so it goes first: an operator told "no" still has exactly the workspace they had.
  2. Delete the completion marker. From here the home is already gone, so nothing is being risked by trying; a failure is reported and not fatal.
  3. Create the volume again, with a fresh identity.
  4. Extract the tar into it.

After step 1 succeeds, every later outcome re-initializes:

  • all four succeed -> the marker is gone AND the identity is new.
  • step 2 fails, 3-4 succeed -> the marker survives but describes an identity that no longer exists (leg 1).
  • step 3 or 4 fails -> the marker is gone (leg 2). If step 3 failed there is no volume at all, and the next dispatch creates a fresh one, which is re-initialized on both counts.

The numbering skips half-steps that belong to the crash-recovery mechanism rather than to 論点 f — step 0 and 1.5 write the interrupted-migration record and open its destruction window, step 5 closes it and step 6 removes it. They are numbered in the body where they occur; see workspace_home_migration_sentinel.go for what each phase means and why 1.5 sits between the removal and the re-creation. The only one that can stop a migration whose steps 1-4 would have worked is 1.5, and it stops it in the same "the home is empty, the next dispatch rebuilds it" state step 3's own failure produces.

Every path that leaves before step 5 closes the window too, with the phase that matches where it stopped: "home-absent" once the volume is confirmed gone, and nothing at all while the record still says "recorded" (it already authorizes no destruction). The window is never left open across an unlink — see clearWorkspaceHomeMigrationRecordForAnAbsentHome for why the unlink cannot carry that job itself.

TestRunner_ImportWorkspaceHome_ReInitsWithTheMarkerRemovalUNDONE and its mirror pin the two legs INDEPENDENTLY, by undoing one and checking the other still fires.

Refusing a workspace with a job in it (D4)

The refusal is the engine's own 409 on the volume removal ("volume is being used by the following container(s)", measured against podman 4.9.3 in PR7, and not overridable by any force flag). That IS the pre-flight check: it is atomic with the removal, so a busy workspace is refused before anything has been destroyed. A separate ContainerList beforehand would be strictly worse — it could only be more stale than the removal it precedes, and it would suggest a guarantee ("we checked") that the window after it cannot support.

What a failure leaves behind (D4)

Once step 1 has succeeded the migration is not reversible: the old contents are gone and boid never had a copy of them (the source is read-only, and it is still on the host — this is why the CLI refuses to delete it). What a failure leaves is a workspace whose home is EMPTY (not partial — step 5 discards a half-extracted volume, see discardPartialWorkspaceHome) and whose init is armed, i.e. the state a brand-new workspace is in. The next dispatch prepares it from scratch; re-running the migration is also safe. That is the whole recovery story, and it is why the legacy directory must not be deleted by this command.

What a KILL leaves behind (codex review of PR8 round 2, Major 2)

Step 5 only runs when this function returns. A daemon that is SIGKILLed, OOM killed or powered off inside steps 1-4 runs no defer and no cleanup, and leaves precisely the half-extracted volume step 5 exists to prevent. Step 0 below writes a durable record of the migration before anything is destroyed, and Runner.SweepInterruptedWorkspaceHomeMigrations finishes the job at the next daemon start. See workspace_home_migration_sentinel.go for the ordering, for why every crash point lands on the "delete and re-initialize" side, and for why this cannot be a label on the volume.

Excluding a concurrent dispatch, and a concurrent remove

(codex review of PR8 round 1, Blocker 2; round 2, Major 1.)

The flock serializes this against another dispatch's INIT, and that is all it does: resolveWorkspaceHome's fast path (a satisfied marker) returns without taking it, so a settled workspace's dispatch holds nothing between resolving its home and asking the engine for a container. A migration landing in that gap removes the volume, re-creates it under the same name and starts extracting, and the dispatch's ContainerCreate then mounts the replacement BY NAME — the job's agent and the migration's tar writing into one volume.

PR6's identity re-check does not close that. It compares what containerBackend.ensureNamedVolumes' own VolumeCreate answered against the identity the dispatch resolved, which catches a replacement landing before that call and cannot catch one landing after it, because the comparison is not atomic with ContainerCreate. (This function's first version claimed the job side would 「大声で失敗する」 in every ordering; it fails loudly in one of them.)

So the exclusion is explicit: r.homeInFlight, registered at the top of this function, refuses a migration while any dispatch of the same workspace is between those two points, and parks a dispatch that arrives while a migration is running.

`boid workspace remove` is the third participant, and the one round 2 found. It deletes the workspace ROW and then the home VOLUME, so a migration that overlaps it re-creates the volume for a row that is gone: credentials in a volume no dispatch can mount and `workspace remove` can no longer target (it 404s on the missing row). Removals therefore register too, and a migration is refused while one is in flight. That covers the overlap and not the ordering where a removal FINISHES before this function registers, which is what r.ConfirmWorkspaceExists below is for — asked under the registration, so its answer cannot go stale.

See workspaceHomeInFlight for why the registry is in memory, why the three directions are not symmetric (a dispatch waits, a migration and a removal refuse), and which windows it deliberately leaves open (another process; the remaining delete-only paths, which the identity check really does cover).

func (*Runner) JobContext added in v0.0.13

func (r *Runner) JobContext(jobID string) (JobContextSnapshot, bool)

JobContext returns the tracked JobContextSnapshot for jobID, and whether one was found. false covers both "no such job" and "job existed but its context was already unregistered" (UnregisterJob clears the entry).

func (*Runner) ReapOrphans added in v0.1.0

func (r *Runner) ReapOrphans(ctx context.Context) (backend.ReapReport, error)

ReapOrphans reconciles sandbox resources a previous daemon instance left behind, via the configured SandboxBackend (docs/plans/ phase6-container-backend.md §PR7 / §決定 6). It is a thin delegation — r.sandboxBackend().ReapOrphans(ctx) — so callers (internal/server/wire.go's startup sequence) never need to know backend construction details; container is the only sandbox backend since PR-4, so this always does real reconciliation work now.

Callers MUST run this — and act on ReapReport.FailedJobIDs, e.g. by skipping auto-reopen for the corresponding tasks — strictly BEFORE resuming any daemon_shutdown-aborted task, per §決定 6: a docker container does not die when the daemon process restarts the way a userns child process (killed by MarkStaleJobsFailed's implicit process death) does, so auto-reopening before reap could dispatch a fresh agent against a task whose previous job container is still alive — two agents mutating the same $HOME/task RPC concurrently.

func (*Runner) ResizeRuntime

func (r *Runner) ResizeRuntime(jobID string, size TerminalSize) error

ResizeRuntime implements RuntimeInputWriter for Runner — the WS attach transport's "resize" frame ingress (docs/plans/phase6-container-backend.md §PR1's other resize seam is the HTTP route, see Runner.ResizeRuntimeID). It resolves jobID to a runtimeID via the jobs table, then adopts a SandboxSession and resizes through it. Adopt is bounded — see Subscribe's doc comment above for why (session.Resize itself is separately bounded, container_backend.go, since its interface signature takes no context to inherit one from), including the ctx.Err()-gated Warn + wrapped error below, matching WriteInput's just above (next-session-container-backend- followups.md #3, Opus review of PR #857).

func (*Runner) ResizeRuntimeID added in v0.1.0

func (r *Runner) ResizeRuntimeID(ctx context.Context, runtimeID string, size TerminalSize) error

ResizeRuntimeID resizes a sandbox session's terminal via the configured SandboxBackend, given a runtimeID directly. This is the collapse point for the HTTP resize ingress (POST /api/jobs/{id}/resize, internal/server/job_runtime_routes.go — the caller there has already resolved job.RuntimeID and doesn't go through the jobID-keyed RuntimeInputWriter path the WS transport uses; see ResizeRuntime for that one). docs/plans/phase6-container-backend.md §PR1 lists this as one of the two resize ingress routes that must route through SandboxSession.Resize.

sessionControlCallTimeout is layered on the caller's ctx as a FLOOR, the same as CanAttach just above (next-session-container-backend-followups.md #1 — the identical defect, left in this function when PR #862 fixed its neighbour). The caller is job_runtime_routes.go's POST /api/jobs/{id}/resize passing req.Context(), and the daemon's http.Server sets neither ReadTimeout nor WriteTimeout (internal/server/server.go), so without the floor a client that simply stays connected hands this an effectively unbounded ctx. Adopt's in-flight join selects on ctx (Major 1, PR #857), so that never hung this call itself — the cost lands on OTHER callers: an unbounded resize owning the in-flight Adopt attempt for a runtimeID starves every bounded joiner of that same runtimeID (StopJobRuntime, SignalJobRuntime) of its whole sessionControlCallTimeout budget, i.e. `boid task stop` fails every time for as long as the engine stays wedged.

Deriving FROM the caller's ctx (rather than replacing it) keeps a shorter caller deadline and a caller cancellation both governing. Shadowing ctx for the rest of the function is safe because SandboxSession.Resize takes no context at all — containerSession.Resize synthesizes its own bounded one from context.Background() — so the deferred cancel cannot cut short the Resize call below.

func (*Runner) SignalJobRuntime

func (r *Runner) SignalJobRuntime(runtimeID string, sig syscall.Signal)

SignalJobRuntime delivers a single signal to the runtime's process group without any SIGKILL follow-up. NotifyTask uses this for SIGUSR1 to ask the agent (run-agent.py) to stop the agent session gracefully — the go-native runner subcommands keep the signal SIG_IGN (inherited across execve), so they survive while run-agent.py acts on it and runner-inner-child still posts `boid job done` through the broker. Best-effort: errors at debug level only, with the same control-call-deadline exception as StopJobRuntime above (Moderate 4).

Routes through SandboxBackend.Adopt → SandboxSession.Signal (docs/plans/phase6-container-backend.md §PR1: this is the `boid agent stop` seam the plan calls out by name).

func (*Runner) StopJobRuntime

func (r *Runner) StopJobRuntime(runtimeID string)

StopJobRuntime stops the runtime identified by runtimeID. It is a best-effort operation: errors are logged at debug level only, EXCEPT when the control-call deadline itself was hit (see below), which is loud (Warn) because it means the container may still be running with no further mechanism in place to stop it.

[Blocker 3, PR7 codex review]: routes through SandboxBackend.Adopt → SandboxSession.Stop (the same seam SignalJobRuntime/ResizeRuntimeID/ CanAttach already use, docs/plans/phase6-container-backend.md §PR1) so a task abort/`boid task stop` reaches the actual container the job is running in via Adopt(runtimeID), not a backend-specific transport this function would otherwise have to know about directly.

func (*Runner) Subscribe

func (r *Runner) Subscribe(jobID string) (snapshot RuntimeSnapshot, ch <-chan []byte, cancel func(), ok bool, finished bool)

Subscribe implements RuntimeSubscriber for Runner. It resolves jobID to a runtimeID via the jobs table, then adopts a SandboxSession for it (docs/plans/phase6-container-backend.md §PR1 — this is the "stream 1 本" seam shared by WS attach and the Web UI's SSE follow endpoint, both of which call through this same method).

Adopt runs under sessionControlCallTimeout (runner.go — Opus review of PR #857, Major 2), not context.Background(): a cache-miss Adopt (fresh daemon restart, before anything has repopulated containerBackend's session cache — exactly the case Adopt's own doc comment names as its reason to exist) does a real `docker inspect` against the engine, and an unbounded context here would hang a WS attach or the Web UI's SSE follow request forever against a wedged engine.

When Adopt's !adopted is caused by that same deadline firing (ctx.Err() != nil) rather than a legitimate "no such runtime" result, this logs a Warn naming the cause (next-session-container-backend-followups.md #3, Opus review of PR #857) — before this, a wedged engine and an already-exited job were indistinguishable to an operator reading the logs, both surfacing as silent ok=false, turning a "terminal stayed blank" bug report into a guessing game between "nothing to attach to" and "the engine never answered".

Both early ok=false returns below also THINK ABOUT finished rather than hardcoding it (Opus review of PR #864, NB2 — a round after the #857 Warn-logging fix above: the first version of this method logged the Warn correctly but still left finished hardcoded at true on both branches, which reopened the exact false-positive class B2 had just closed for containerSession.Subscribe, just through two different doors here):

  • "no runtime_id yet": CreateJob (Dispatch's very first step) persists a job row — and fires r.JobEvents.JobCreated so the Web UI can already show it — well before launchSandbox's own `job.RuntimeID = handleID; UpdateJob(...)` call sets RuntimeID. Everything between those two points (BuildSandboxSpec, ResolveHostCommands, workspace- home resolution/init — PR #861 added a debug log specifically because that step can be slow) can take real wall-clock time, during which a job row exists but has no runtime_id yet. A caller landing here during that window is looking at a job that is ABOUT TO run, not one that is done — jobFinishedBeforeRuntime (below) reports finished=false for it. A job that instead failed BEFORE ever reaching Launch (Runner.failJob, 8 call sites) leaves the same "row exists, no runtime_id" shape behind, but permanently — the status column is what actually distinguishes "still might launch" from "already terminal", not mere row presence (Opus review of PR #864, NB3 — see jobFinishedBeforeRuntime's own doc comment for the concrete failure this closes). A jobID with NO row at all (mistyped, or old enough to have been GC'd) also reports finished=true: nothing will ever come either way.
  • Adopt itself returning ok=false: distinguishes "Adopt legitimately found nothing" (ctx still had budget left when Adopt returned — the backend has no notion of this container at all, already exited and reaped or never existed — finished=true) from "the sessionControlCallTimeout deadline fired before Adopt could resolve" (ctx.Err() != nil — the same condition the Warn above already logs — a wedged engine told us NOTHING about whether the container is still alive; the job could be very much still running, finished=true here would be exactly B2's false positive reached through the Adopt-itself-timed-out door instead of the adopted-session's-own- Subscribe door). The same ctx.Err() != nil pattern already distinguishes this in StopJobRuntime/SignalJobRuntime/ ResizeRuntimeID (this file's own sibling methods) — this is that same pattern applied to the one method that hadn't used it yet.

func (*Runner) SweepInterruptedWorkspaceHomeMigrations added in v0.1.0

func (r *Runner) SweepInterruptedWorkspaceHomeMigrations(ctx context.Context) (swept int, err error)

SweepInterruptedWorkspaceHomeMigrations resolves every leftover interrupted-migration record on this installation and reports how many it resolved.

Call it at daemon start, BEFORE anything can dispatch: it is the EAGER half of this file's acting mechanism, clearing wreckage while nothing is competing for it, including for workspaces no job will touch for days.

It is not the guarantee, though — a sweep whose volume removal fails logs and lets startup continue, so the invariant "no init and no job runs against a home with a record" is enforced where it can actually be enforced: on the dispatch path (Runner.recoverInterruptedWorkspaceHomeMigration, codex round 3 Blocker 1). The two share their discard so a workspace repaired by a boot and one repaired by a dispatch end up in the same state.

What it does per record

It registers the slug in the in-flight registry as a migration (so a dispatch that somehow reaches this workspace first waits rather than mounting a volume that is about to be removed) and takes the workspace's init flock (the same one an init and a migration take, so the sweep can never interleave with either). What happens under those two exclusions depends on the record's PHASE — see discardInterruptedWorkspaceHomeMigrationLocked, and this file's header for the table. A record that does not authorize a discard costs one unlink and no engine call at all.

The count

swept counts RECORDS RESOLVED, of both kinds, because the caller's only use for it is deciding whether to say anything at startup — and "the daemon cleared leftover migration state" is worth saying whichever kind it was. Which kind each one was is in the per-record log line, which is where an operator looking for "was my home destroyed" will actually be.

Errors

A per-record failure is logged, joined into the returned error and does not stop the sweep: one workspace whose volume the engine refuses to remove must not leave the others unswept. A non-nil error does not abort daemon startup — like the startup container reap it is scoped to resource reconciliation — but it does mean at least one workspace still holds a home nobody vouches for.

func (*Runner) UnregisterJob

func (r *Runner) UnregisterJob(jobID string)

UnregisterJob removes the broker token, the git gateway job token, and the API gateway job token associated with the given job.

func (*Runner) WaitForJob

func (r *Runner) WaitForJob(jobID string) <-chan JobCompletionResult

WaitForJob registers a channel that will receive the job completion result.

func (*Runner) WaitForJobCtx

func (r *Runner) WaitForJobCtx(ctx context.Context, jobID string) (JobCompletionResult, error)

WaitForJobCtx waits for job completion with context cancellation.

A non-zero exit is NOT reported as an error — the caller inspects result.ExitCode. Only true wait-machinery failures (ctx cancel) produce a non-nil error. This lets the orchestrator record `hook_fired` actions for failing hooks the same way as successful ones; prior behavior discarded the partial FiredEvents when any hook exited non-zero.

func (*Runner) WriteInput

func (r *Runner) WriteInput(jobID string, data []byte) error

WriteInput implements RuntimeInputWriter for Runner. It resolves jobID to a runtimeID via the jobs table, then adopts a SandboxSession and writes through it. Adopt is bounded — see Subscribe's doc comment just above for why, including the ctx.Err()-gated Warn below.

Unlike Subscribe, WriteInput has an error return, so an Adopt-deadline !adopted also gets a wrapped error distinguishing it from the ordinary ErrRuntimeUnsupported result (next-session-container-backend-followups.md #3, Opus review of PR #857) — the same "engine did not respond in time" phrasing ResizeRuntimeID (runner.go) already uses for session.Resize's own deadline error, so the two read as the same class of failure.

type RuntimeExit

type RuntimeExit = backend.RuntimeExit

RuntimeExit is an alias for backend.RuntimeExit (same rationale as TerminalSize above). ExitCode is the process exit code; TranscriptPath is the path to a file holding the child process's stdout/stderr full capture, so a silent exit_code!=0 (transcript が 0 byte) ケースを diag log で一発判別できる。サポートしない runtime は空文字。

type RuntimeInputWriter

type RuntimeInputWriter interface {
	WriteInput(jobID string, data []byte) error
	ResizeRuntime(jobID string, size TerminalSize) error
	// CloseInput signals that no more input is coming for jobID — the WS
	// attach transport's counterpart to the old raw-hijack transport's
	// implicit half-close (docs/plans/cli-remote-connection.md Phase 3 PR3;
	// see LocalRuntime.CloseInputRuntime's doc comment for the full
	// rationale). A no-op for jobs whose runtime has no notion of "closing"
	// input (interactive PTY sessions, or non-interactive sessions with no
	// StdinForward pipe).
	CloseInput(jobID string) error
}

RuntimeInputWriter provides write access to a running job's PTY input.

type RuntimeSnapshot added in v0.2.6

type RuntimeSnapshot = backend.RuntimeSnapshot

RuntimeSnapshot is an alias for backend.RuntimeSnapshot (same rationale as TerminalSize above), and additionally keeps internal/api — which consumes it through RuntimeSubscriber — free of a direct dependency on the sandbox backend package.

type RuntimeSubscriber

type RuntimeSubscriber interface {
	Subscribe(jobID string) (snapshot RuntimeSnapshot, ch <-chan []byte, cancel func(), ok bool, finished bool)
}

RuntimeSubscriber subscribes to live output of a running job identified by jobID. finished disambiguates ok=false the same way backend.SandboxSession.Subscribe's own finished return does (see its doc comment for the full rationale, Opus review of PR #864, B2): true means the job is actually done (safe to report as such); false means the job is still running but has no live stream to offer right now, which a caller MUST NOT collapse into "done" — see ws_attach.go/job_log_sse.go's own handling for what each ingress does with the distinction.

type SandboxRuntimeInfo

type SandboxRuntimeInfo struct {
	JobID        string
	BoidBinary   string
	ServerSocket string
	ProxyPort    int
	// ProxyHost [Blocker 2, PR7 codex review] is the host applyProxyEnv
	// points HTTP_PROXY/HTTPS_PROXY at. Empty (every pre-Blocker-2 caller)
	// falls back to hostGatewayIP ("10.0.2.2", the pasta/slirp userns
	// gateway IP) — applyProxyEnv's own doc comment. Runner.Dispatch sets
	// this to the compose egress service DNS name
	// (dispatcher-internal composeEgressServiceName, "boid-egress") when
	// the configured backend is the container backend
	// (IsContainerBackend(r.Backend)): a docker sibling container has no
	// 10.0.2.2 projection at all, so a container-backend job needs a
	// reachable compose-network address instead.
	ProxyHost string

	// WorkspaceNetworkCIDRs are the subnets of this job's OWN per-workspace
	// docker network, which applyProxyEnv adds to no_proxy/NO_PROXY so a
	// sibling container dialed by container IP is reached directly instead of
	// through the egress proxy — §決定5's "job → sibling の到達は container IP
	// + container port の直アクセス". Runner.Dispatch fills this in via the
	// backend's optional workspaceNetworkCIDRResolver; nil (every non-container
	// backend, and a container backend whose subnet lookup failed) leaves
	// no_proxy exactly as it was before this field existed.
	//
	// Only this workspace's own subnets belong here — see
	// containerBackend.WorkspaceNetworkCIDRs' doc comment for why widening it
	// would hand the job a route into other workspaces' networks.
	WorkspaceNetworkCIDRs []string

	// UsingContainerBackend (PR9, §決定2) is Runner.Dispatch's
	// IsContainerBackend(r.Backend) — the same signal ProxyHost's own doc
	// comment describes for the identical "computed once at the Dispatch
	// call site, threaded through because BuildSandboxSpec has no other
	// way to know the configured backend" reason. BuildSandboxSpec uses it
	// to skip binding rt.BoidBinary into the sandbox (see its own call
	// site below): the container backend's shared image already bakes
	// boid at the fixed shim path (build/container/Dockerfile), so
	// binding it AGAIN would try to bind-mount rt.BoidBinary
	// (os.Executable() — resolves to the DAEMON's own in-image path,
	// e.g. "/usr/local/bin/boid") as a docker-out-of-docker sibling
	// mount SOURCE, which the host's real docker daemon then rejects
	// outright ("bind source path does not exist") since that path only
	// exists inside the daemon's own container, never on the real host
	// filesystem a DooD sibling's bind sources are resolved against.
	// False (every pre-PR9 caller) preserves today's userns-only
	// behavior unchanged — the userns backend genuinely needs this bind
	// (its job process shares the host mount namespace before
	// pivot_root, so rt.BoidBinary is a real, bindable host path there).
	UsingContainerBackend bool

	BrokerSocket string
	BrokerToken  string

	// WorkspacePeers maps peer project IDs (same workspace, excluding self) to
	// host paths. Dispatcher resolves this from its ProjectLookup so peer
	// visibility/authorization does not leak into orchestrator.JobSpec.
	WorkspacePeers map[string]string

	// Foreground indicates whether the job runs in the foreground (user-facing
	// stdout/stderr, no trap-based completion callback). boid exec sets this
	// to true; hook/gate jobs leave it false so stdout is captured and a
	// `boid job done` trap posts completion back to the daemon.
	Foreground bool

	// ResolvedHostCommandsByName is the short-name-keyed view of the resolved
	// host command defs produced by ResolveHostCommands
	// (docs/plans/phase5-shim-and-task-context.md, "5a: shim 固定ディレクトリ化"
	// PR1). It is the single source of truth for host command wiring:
	//
	//   - the broker's policy table (CommandBroker.RegisterCommands) keys off
	//     it directly;
	//   - buildHostCommandRulesEnv turns the same map into
	//     BOID_HOST_COMMAND_RULES;
	//   - hostCommandSymlinks (5a-3) materializes one
	//     `/run/boid/bin/<name> -> boid` symlink per entry — so every
	//     host_command becomes a shim on PATH under its declared short name,
	//     even when host_commands.<name>.path aliases the source file to a
	//     different basename.
	//
	// The pre-5a-3 absolute-path-keyed sibling (ResolvedHostCommands / byPath)
	// was dropped: it existed only to key the retired hostCommandMounts /
	// buildHostCommandNamesEnv / per-command PATH parent, all replaced by the
	// fixed-directory scheme. Empty when the job declares no host commands.
	ResolvedHostCommandsByName map[string]orchestrator.CommandDef

	// ProxySocketPath, when non-empty, is the host-side Unix socket path of the
	// per-sandbox docker proxy. sandbox_builder bind-mounts it into the sandbox
	// at the fixed sandbox path (see dockerProxySandboxSocket) and injects
	// DOCKER_HOST / CONTAINER_HOST / TESTCONTAINERS_* env vars.
	// Set by the runner before BuildSandboxSpec when capabilities.docker is
	// declared in project.yaml.
	ProxySocketPath string

	// AllowedDomains is the proxy egress allowlist. It is purely informational
	// inside the sandbox (the proxy itself enforces it on the host), surfaced
	// to the agent via the `boid task env` broker RPC (Phase 5b PR1) so it
	// knows which hosts are reachable without burning a turn on a 403.
	AllowedDomains []string

	// GatewayURL is the git gateway's sandbox-facing base URL
	// (http://10.0.2.2:<port>), set by Runner from the daemon's own
	// gateway listener (docs/plans/git-gateway-cutover.md PR4: gateway
	// lifecycle + dispatch wiring). Empty when the gateway isn't wired.
	//
	// PR4 is inert: BuildSandboxSpec does not thread this into env or mounts
	// yet — nothing inside the sandbox reads it. The env var advertise
	// (e.g. GIT_HTTP_GATEWAY_URL) is explicitly deferred to the cutover PR
	// (PR6); the runner clone sequence that would consume it is PR5.
	GatewayURL string

	// GatewayCAPEM is the daemon's internal CA's own certificate
	// (mtls.CA.CertPEM), PEM-encoded, set by Runner from Server's
	// gatewayCAPEM (PR9 e2e-container fix). Non-secret — the CA's public
	// half, not a key — so it needs no per-job scoping or rotation, unlike
	// a client certificate would.
	//
	// Only meaningful for the container backend: the userns backend's
	// gateway URL is plain HTTP (http://10.0.2.2:<port>, the pasta/slirp
	// loopback projection — see GatewayURL's own doc comment), so there is
	// no TLS handshake to trust in the first place. BuildSandboxSpec only
	// writes this into the sandbox (as a file, with GIT_SSL_CAINFO pointed
	// at it) when UsingContainerBackend is true AND spec.Visibility.Clone
	// is set — see its own call site. Without it, every sandbox-internal
	// clone against the container backend's TLS-secured gateway
	// (https://boid-gateway:<port>) fails outright: "server certificate
	// verification failed. CAfile: none CRLfile: none" (the real-docker
	// e2e-container CI job's exact failure, PR9).
	GatewayCAPEM []byte

	// GatewayJobToken is this job's git gateway token, registered against
	// the gateway's Registry at dispatch time (self project fetch/fetch+push,
	// workspace peers and workspace extra_repos fetch-only) and unregistered
	// when the job completes (see Runner.registerGatewayToken /
	// Runner.UnregisterJob). Empty when the gateway isn't wired.
	//
	// Same PR4-is-inert caveat as GatewayURL: carried here for PR5/PR6 to
	// consume, not yet used by BuildSandboxSpec.
	GatewayJobToken string

	// GatewayCloneURL is the full gateway clone URL for spec's own project
	// (GatewayURL + "/j/" + GatewayJobToken + "/<host>/<owner>/<repo>.git"),
	// built by Runner.buildGatewayCloneURL (docs/plans/git-gateway-cutover.md
	// PR5). Empty unless spec.Visibility.Clone is non-nil (the opt-in
	// sandbox-clone path) — computing it is otherwise wasted work, since
	// nothing would consume it. BuildSandboxSpec only reads this when
	// spec.Visibility.Clone != nil.
	GatewayCloneURL string

	// APIGatewayBaseURL is the shared gateway listener's sandbox-facing base
	// URL (docs/plans/api-gateway.md 論点1: "同居 — path prefix /j/ と /api/
	// で分岐"). Byte-identical to GatewayURL above in every real deployment
	// — both gateways share the exact same TCP(mTLS) listener — but resolved
	// independently by Runner.registerAPIGatewayToken (which reads r.GatewayURL
	// directly rather than reusing GatewayURL's own local variable) so the
	// API gateway's env-var advertise does not depend on the git gateway
	// having registered anything for this job. Empty when the API gateway
	// isn't wired (r.APIGateway == nil).
	APIGatewayBaseURL string
	// APIGatewayJobToken is this job's API gateway token, registered against
	// apigateway.Registry at dispatch time (docs/plans/api-gateway.md §3:
	// floor ∪ workspace enabled-service set, task.readonly → Entry.ReadOnly)
	// and unregistered when the job completes (Runner.registerAPIGatewayToken
	// / Runner.UnregisterJob). Empty when the API gateway isn't wired.
	// BuildSandboxSpec combines this with APIGatewayBaseURL to set
	// BOID_API_BASE.
	APIGatewayJobToken string

	// WorkspacePeerAdvertise is the {name, clone URL, reference path} view of
	// WorkspacePeers, built by Runner.buildPeerAdvertise and keyed by peer
	// project ID (docs/plans/git-gateway-cutover.md PR6 cutover 「5. peer
	// advertise の変更」 — replaces the pre-cutover host path enumeration);
	// nil when the gateway isn't wired or no peer has a resolvable
	// upstream_url.
	//
	// Still unused by BuildSandboxSpec: environment.yaml's
	// `workspace_projects` section (its sole consumer) was removed by the
	// environment.yaml 縮退 (docs/plans/phase5-shim-and-task-context.md 決定
	// 事項 4, Phase 5b PR5). The CLI replacement this field was originally
	// kept for landed as `boid project list`'s clone_url/reference_path/
	// clone_dir fields (2026-08), but that path reads the SAME
	// buildPeerAdvertise output through a different carrier —
	// JobContextSnapshot.WorkspacePeerAdvertise (job_context.go), tracked by
	// Runner.Dispatch — not through this SandboxRuntimeInfo field. This
	// field remains genuinely dead; a future cleanup could remove it
	// entirely rather than keep two independent holders of the same
	// buildPeerAdvertise result.
	WorkspacePeerAdvertise map[string]PeerAdvertise

	// CloneWorkspaceDir is the host-side runtime dir path
	// (`<RuntimesDir>/<runtime_id>/workspace`) that BuildSandboxSpec bind-
	// mounts at the sandbox-internal clone target (/workspace/<name>) when
	// spec.Visibility.Clone is set (docs/plans/git-gateway-cutover.md PR6
	// cutover — 「一時領域の実体はホスト側 runtime dir の bind mount を既定と
	// する」, 2026-07-08 decision in container-based-boid.md). Allocated and
	// mkdir'd by Runner.Dispatch before BuildSandboxSpec runs, the same way
	// startDockerProxy pre-creates its runtime dir. Empty when RuntimesDir is
	// unset (e.g. minimal test wiring) — cloneMounts then skips the bind and
	// the clone lands on the sandbox's own tmpfs root instead, a safe but
	// non-default degrade (working tree + build artifacts in RAM).
	CloneWorkspaceDir string

	// WorkspaceHomeVolume is the NAME of the docker named volume holding this
	// workspace's persistent home, as resolved by
	// Runner.resolveWorkspaceHome: dockerres.WorkspaceHomeVolumeName(installID,
	// slug), guaranteed to exist — and to have had its bind-target skeleton
	// and, if the workspace declares one, its init.sh run against it — by the
	// time Dispatch reaches BuildSandboxSpec.
	//
	// It is a volume name, NOT a path, as of PR6 of
	// docs/plans/workspace-home-volume-persistence.md (論点 a/e). Through Phase
	// 4 and Phase 6 this field was called WorkspaceHomeDir and held
	// <runtimesRoot>/homes/<slug>; that root resolves under BOID_RUNTIME_DIR in
	// every real deployment, i.e. tmpfs, so a host reboot destroyed every
	// workspace's harness credentials and its ~1.5GB toolchain. The rename is
	// deliberate: the value now selects a completely different mount kind
	// (internal/sandbox/realization.classifySource treats any non-absolute
	// Source as a named volume), and a field still called ...Dir would invite
	// exactly the filepath.Join that silently produces a second, junk volume.
	//
	// The Clone / projectVisible / default HOME branches below (via homeMounts)
	// mount it read-write at HOME's sandbox-internal path instead of a plain
	// tmpfs. From Phase 4 PR2 through Phase 6 PR7, $HOME/.boid was
	// additionally layered with a job-scoped tmpfs overlay to isolate
	// $HOME/.boid/output/payload_patch.json between concurrent jobs sharing
	// the same workspace home; Phase 6 PR8 (docs/plans/
	// phase6-container-backend.md §決定 9) removed that overlay once the
	// payload-patch RPC (`boid task update --payload-patch`) became the sole
	// delivery path — see homeMounts' doc comment. env["HOME"] itself is
	// unchanged — it still comes from hostHomeDir(), the *target* path
	// inside the sandbox; only the *contents* now come from the
	// workspace home instead of starting empty every job.
	//
	// When empty (test wiring that never resolved a workspace — most of
	// sandbox_builder_test.go's minimal SandboxRuntimeInfo{} literals —
	// or any other caller that has not threaded a workspace home through
	// yet) the HOME branches gracefully degrade to the pre-PR2 behaviour: a
	// single fresh tmpfs. The ProfileInit branch never reads this field at
	// all — see its own doc comment for why bind-mounting HOME there would
	// defeat its host-tool-discovery purpose.
	WorkspaceHomeVolume string

	// WorkspaceSlug is the normalized workspace slug WorkspaceHomeVolume was
	// resolved for (docs/plans/home-workspace-volume.md Phase 4 PR3), taken
	// straight from resolveWorkspaceHome's second return value by
	// Runner.Dispatch.
	//
	// It used to be filepath.Base(<the home path>) instead. PR4 of
	// docs/plans/workspace-home-volume-persistence.md cut that dependency and
	// PR6 collected on it: the home is now a named volume called
	// boid-ws-home-<installID8>-<slug>, so that derivation would put a VOLUME
	// NAME into BOID_WORKSPACE_SLUG and into the adapter error message below —
	// naming a workspace that does not exist to an operator being told which
	// init.sh to edit. Nothing in this struct may re-derive it.
	//
	// BuildSandboxSpec threads it into env["BOID_WORKSPACE_SLUG"] so the
	// claude/codex/opencode adapters' fail-fast "harness CLI not found"
	// error (run.go, triggered when PR3's retired adapter bindings leave no
	// CLI on PATH) can name the exact workspace whose init.sh needs the
	// install step. Empty for test wiring that never resolved a workspace
	// (most of sandbox_builder_test.go's minimal SandboxRuntimeInfo{}
	// literals) — the env var is simply omitted in that case.
	WorkspaceSlug string

	// SkillsSourceDir is the host-visible directory Runner.Dispatch just
	// materialized the embedded skill set into — <RuntimesDir>/skills, see
	// embeddedSkillsDir / syncEmbeddedSkills (docs/plans/
	// workspace-home-volume-persistence.md 論点 e-2, PR3).
	//
	// homeMounts turns it into one READ-ONLY bind per embedded skill,
	// <SkillsSourceDir>/<name> → <HOME>/.claude/skills/<name>, layered on top
	// of the workspace home bind. Per skill rather than one bind of the whole
	// ~/.claude/skills directory on purpose: a directory-wide bind would hide
	// any non-embedded skill the workspace's init.sh copied into the home,
	// which internal/adapters/opencode/bindings.go documents as the supported
	// way to expose host skills (bitbucket, jira, google-*, ...) to a harness.
	// skills.EmbeddedSkillNames() enumerates the names, so the mount set
	// tracks the embed directive rather than a hard-coded list.
	//
	// Empty (test wiring that never threaded it, the same minimal
	// SandboxRuntimeInfo{} literals WorkspaceHomeVolume degrades for) means no
	// skill binds at all — the HOME layer is then byte-for-byte what it was
	// before PR3.
	SkillsSourceDir string

	// CloneHostBacked (docs/plans/volume-only-daemon.md §論点b, PR-2b "per-job
	// clone at dispatch time") signals that Runner.Dispatch has already
	// materialized CloneWorkspaceDir via dispatcher.PrepareJobCheckout
	// (`git clone file://<bare-repo>` from the project's daemon-managed
	// bare repository into a per-job staging dir under a host-visible
	// runtimes root), rather than leaving CloneWorkspaceDir as an empty
	// scratch directory for the SANDBOX's own in-container clone sequence
	// (buildCloneSpec/performCloneSteps) to populate at job start.
	//
	// Only ever true for a git-URL-registered project (orchestrator.
	// IsBareRepoDir(proj.WorkDir), PR-2a) dispatched under the container
	// backend with a resolvable host-visible runtimes root — every other
	// caller (legacy host-dir-registered projects, the userns backend,
	// r.RuntimesDir unset test wiring) leaves this false, the byte-for-byte
	// pre-PR-2b default: cloneMounts' /workspace bind stays
	// container-local (决定 4/10) and buildCloneSpec keeps declaring the
	// in-sandbox clone exactly as before.
	//
	// When true: cloneMounts sets sandbox.Mount.HostBacked on the
	// /workspace bind (realization.classifySource then treats it as a real
	// host-path bind, not container-local — see that field's own doc
	// comment) and buildCloneSpec returns CloneSpec{} (Enabled == false):
	// the sandbox has nothing left to clone, its /workspace/<name> already
	// IS the daemon-prepared checkout.
	CloneHostBacked bool

	// ContainerImage is the workspace's Phase 6 container image override
	// (`orchestrator.WorkspaceMeta.ContainerImage`, docs/plans/
	// phase6-container-backend.md §決定 2/11), resolved by
	// Runner.resolveContainerImage the same way resolveWorkspaceProxy
	// resolves AllowedDomains — an independent WorkspaceLookup.Load call
	// rather than a field threaded through orchestrator.JobSpec, following
	// that field's existing precedent for workspace-level (not
	// project/task-level) dispatch data. Copied verbatim into
	// sandbox.Spec.ContainerImage below; BuildSandboxSpec does not
	// interpret it — only a container backend does. Empty for every
	// workspace that doesn't set container_image (the common case) and for
	// test wiring that never resolved a workspace.
	ContainerImage string
}

SandboxRuntimeInfo carries the dispatcher-internal facts that are required to turn an orchestrator.JobSpec into a sandbox.Spec but that orchestrator never needs to know: job id, broker plumbing, proxy port, boid binary location, server socket path, staging dirs.

type SecretResolver

type SecretResolver func(key string) (string, error)

SecretResolver resolves a secret key into its plaintext value.

type SecretStore

type SecretStore struct {
	// contains filtered or unexported fields
}

SecretStore provides encrypted secret storage backed by SQLite.

func NewSecretStore

func NewSecretStore(d *sql.DB, key []byte) (*SecretStore, error)

NewSecretStore creates a store with the given database and encryption key.

func (*SecretStore) Delete

func (s *SecretStore) Delete(namespace, key string) error

func (*SecretStore) Get

func (s *SecretStore) Get(namespace, key string) (string, error)

func (*SecretStore) List

func (s *SecretStore) List(namespace string) ([]string, error)

func (*SecretStore) Set

func (s *SecretStore) Set(namespace, key, value string) error

type SelfContainerInspector added in v0.1.0

type SelfContainerInspector interface {
	ContainerInspect(ctx context.Context, containerID string, options client.ContainerInspectOptions) (client.ContainerInspectResult, error)
}

SelfContainerInspector is the one docker API call this feature needs. It is declared as its own narrow interface rather than reusing dockerAPI so internal/server can hand in a bare *client.Client without constructing a container backend, and so the test stub does not have to implement two dozen unrelated methods. dockerAPI satisfies it (pinned by a compile-time assertion in the test file).

type SessionJobInput added in v0.0.6

type SessionJobInput struct {
	// ProjectID and ProjectWorkDir locate the host filesystem the sandbox
	// will expose; ProjectWorkDir is the cwd seen by the agent.
	ProjectID      string
	ProjectWorkDir string

	// ProjectName is project.yaml's `meta.name` (see
	// orchestrator.Visibility.ProjectName's doc comment). The caller fills
	// this from the same workspace-hydrated ProjectMeta it already reads
	// Env/HostCommands/AdditionalBindings from.
	ProjectName string

	// HarnessType selects the agent adapter the runner-inner-child will
	// dispatch through. Must be one of "claude" / "codex" / "opencode" /
	// "shell" (validated by the caller; BuildSessionJobSpec does not police it).
	HarnessType string

	// Argv is the literal program + arguments the shell adapter consumes.
	// The claude / codex / opencode adapters ignore it (they build their
	// argv from CLI conventions). Required when HarnessType == "shell";
	// ignored otherwise.
	Argv []string

	// Instruction is the optional bootstrap prompt the agent should pick up
	// on launch (e.g. the `--instruction` flag of `boid agent`, or the
	// WebUI Session dialog's text field). When non-empty it is plumbed
	// through RunContext.UserAnswer so the adapter's existing "user reply"
	// path delivers it as the first turn of input. Empty leaves the adapter
	// to pick its default bootstrap (no positional for session mode on claude,
	// since the /boid-task skill is meaningless without a task.yaml).
	Instruction string

	// Readonly controls Visibility.Writable. Sessions default to writable
	// (interactive use prioritises developer ergonomics over fail-safety)
	// so callers must opt into a read-only session explicitly.
	Readonly bool

	// Model overrides the harness binary's default model selection.
	Model string

	// Project trait overlay (the session has no behavior to resolve from,
	// so the caller fills these directly from ProjectMeta).
	Env                map[string]string
	HostCommands       map[string]orchestrator.HostCommandSpec
	AdditionalBindings []orchestrator.BindMount
	SecretNamespace    string
	DockerEnabled      bool

	// DisplayName is the human-readable label persisted to jobs.display_name
	// (and shown in the TUI / Web UI). Empty falls back to "<harness>
	// session" downstream.
	DisplayName string
}

SessionJobInput carries the resolved data needed to build a Session (HarnessAdapter-backed, task-less) JobSpec. Phase 3-d (PR1) introduced it as the input shape for both the daemon API (POST /sessions) and the `boid agent` CLI.

session jobs inherit project-level traits only (env / host_commands / additional_bindings / secret_namespace). behavior-level traits are deliberately ignored — sessions are not driven by the task state machine and have no behavior context to resolve.

type TerminalSize

type TerminalSize = backend.TerminalSize

TerminalSize is an alias for backend.TerminalSize. The canonical definition lives in internal/sandbox/backend (docs/plans/ phase6-container-backend.md §PR1) so SandboxSession.Resize and every caller in this package share one type without an import cycle — backend has no dependency on dispatcher.

type WireConfig

type WireConfig struct {
	DB          *sql.DB
	Broker      CommandBroker
	SecretStore *SecretStore

	Projects ProjectLookup
	// Hydrator is optional workspace-hydrated ProjectMeta lookup, threaded
	// straight to Runner.Hydrator (see its doc comment). nil disables
	// workspace-peer meta.name resolution; buildPeerAdvertise falls back to
	// filepath.Base(WorkDir).
	Hydrator orchestrator.MetaHydrator

	// BoidBinary is the host path to the boid executable that should be
	// bind-mounted into sandboxes.
	BoidBinary string
	// ServerSocket is the host path to the daemon UNIX socket (for boid exec
	// jobs that talk to boid over HTTP from inside the sandbox).
	ServerSocket string
	// ProxyPort points at the default-workspace proxy port. Used as the
	// fallback when ProxyAllocator is not wired (or fails) for a NAMED
	// workspace's dispatch. Sandboxes linked to a workspace get a
	// per-workspace port via ProxyAllocator.
	ProxyPort *int
	// NoWorkspaceProxyPort points at the dedicated no-workspace proxy port
	// — see Runner.NoWorkspaceProxyPort's own doc comment. Deliberately
	// separate from ProxyPort: resolveWorkspaceProxy's empty-workspaceID
	// path must never be able to fall back to the real default workspace's
	// own (editable) listener.
	NoWorkspaceProxyPort *int
	// AllowedDomains is the daemon-wide proxy egress allowlist floor
	// (config.yaml sandbox.allowed_domains + boid built-in defaults),
	// captured once when Wire builds the Runner — see Runner.AllowedDomains's
	// own doc comment for why this is a plain []string, not a getter
	// (sandbox.allowed_domains is ReloadRestartRequired: PR #830 round-4
	// simplification, nose directive). Workspaces add entries on top via
	// workspace.yaml; they cannot remove floor entries
	// (orchestrator.ResolveAllowedDomains enforces this).
	AllowedDomains []string
	// Workspaces is the WorkspaceLookup used at dispatch time to discover
	// each workspace's AllowedDomains overrides. nil disables workspace
	// hydration and the runner stays on the floor only.
	Workspaces WorkspaceLookup
	// ProxyAllocator is the per-workspace proxy listener registry. nil
	// disables workspace-scoped proxy allocation and the runner serves
	// every sandbox via the default-workspace listener.
	ProxyAllocator ProxyAllocator
	// RuntimesDir is the root directory where per-sandbox runtime directories
	// are created. When non-empty and DockerEnabled, the runner pre-allocates a
	// runtime directory here to host the per-sandbox docker proxy socket and
	// resource ledger.
	RuntimesDir string
	// DataHomeDir is the daemon's own persistent data root, threaded
	// straight to Runner.DataHomeDir (see its doc comment). server/wire.go
	// passes dataHomeFor(cfg) — the same value it already gives
	// projectSvc.DataDir, the attachments root and the repos root, so
	// workspace home init bookkeeping lands in the `boid_state` volume with
	// the rest of the daemon's durable state rather than on tmpfs
	// (docs/plans/workspace-home-volume-persistence.md 論点b, PR2). Empty
	// falls back to $XDG_DATA_HOME/boid rather than disabling anything —
	// unlike dataHomeFor's other consumers, which do read "" as "feature
	// disabled".
	DataHomeDir string
	// ReservedVolumeNames is threaded straight to Runner.ReservedVolumeNames
	// (see its doc comment): the docker volume names a sandboxed docker
	// client may not create, delete or mount, discovered at daemon startup by
	// inspecting the daemon's own container. server/wire.go passes
	// dispatcher.DetectDaemonStateVolumes' result. nil — every non-container
	// deployment and all test wiring — leaves the dockerproxy policy exactly
	// as it was before this field existed.
	ReservedVolumeNames []string
	// GitGateway is the git gateway's job-token registry
	// (docs/plans/git-gateway-cutover.md PR4). nil disables gateway token
	// registration entirely.
	GitGateway *gitgateway.Registry
	// GatewayURL points at the daemon's own gateway listener address string,
	// filled in by Server.Start once the gateway's TCP listener is bound
	// (same late-binding pattern as ProxyPort). nil disables gateway URL
	// propagation into SandboxRuntimeInfo.
	GatewayURL *string
	// GatewayCAPEM points at the daemon's internal CA's own PEM-encoded
	// certificate, filled in by Server.Start alongside GatewayURL (same
	// late-binding-via-pointer pattern). A container-backend clone-mode
	// job needs this to verify the git gateway's TLS server certificate
	// (see SandboxRuntimeInfo.GatewayCAPEM's own doc comment). nil
	// disables CA propagation — the plaintext gateway URL of the (now
	// removed, PR-4) userns backend never needed it either way.
	GatewayCAPEM *[]byte
	// APIGateway is the API gateway's job-token registry (docs/plans/
	// api-gateway.md PR1). nil disables gateway token registration
	// entirely.
	APIGateway *apigateway.Registry
	// APIGatewayServicesFloor is the daemon-wide set of API gateway service
	// names enabled for every workspace (config.yaml services_floor),
	// captured once when Wire builds the Runner — see Runner.
	// APIGatewayServicesFloor's own doc comment.
	APIGatewayServicesFloor []string
}

type WorkspaceEnvHostCommand added in v0.0.13

type WorkspaceEnvHostCommand struct {
	Name   string                   `json:"name" yaml:"name"`
	Allow  []string                 `json:"allow,omitempty" yaml:"allow,omitempty"`
	Deny   []string                 `json:"deny,omitempty" yaml:"deny,omitempty"`
	Reject []WorkspaceEnvRejectRule `json:"reject,omitempty" yaml:"reject,omitempty"`
}

WorkspaceEnvHostCommand mirrors orchestrator.CommandDef's agent-relevant surface (the parts an agent cannot infer by trying the command and reading the error): its allow/deny argument policy and reject rules. Renamed and exported from the former environmentHostCommand (Phase 5b PR1) so buildEnvironmentYAML's host_commands section and `boid task env`'s RPC response share one conversion (convertHostCommands) instead of two independently-maintained shapes that could silently drift apart.

type WorkspaceEnvRejectRule added in v0.0.13

type WorkspaceEnvRejectRule struct {
	Match  string `json:"match" yaml:"match"`
	Reason string `json:"reason" yaml:"reason"`
}

WorkspaceEnvRejectRule mirrors orchestrator.RejectRule so agents can read, per host command, which arg shapes are rejected and what to do instead.

type WorkspaceEnvView added in v0.0.13

type WorkspaceEnvView struct {
	AllowedDomains []string                  `json:"allowed_domains,omitempty" yaml:"allowed_domains,omitempty"`
	HostCommands   []WorkspaceEnvHostCommand `json:"host_commands,omitempty" yaml:"host_commands,omitempty"`
}

WorkspaceEnvView is the reduced "environment" a Phase 5b `boid task env` call returns (docs/plans/phase5-shim-and-task-context.md 決定事項 4). Only the two properties an in-sandbox agent cannot observe on its own survive the 縮退 from the legacy environment.yaml: network egress allowlist and host-command policy. Every other section the legacy doc had (sandbox.*/filesystem.*/worktree/tools/session.*/network.restricted/notes) is either hard-coded scenery or directly observable from inside the container, so it is dropped rather than carried over.

JSON tags define the RPC's wire schema; per the plan doc's "broker RPC の スキーマ安定性契約" open question, treat field renames/removals here as a breaking change to the `boid task env` contract skills depend on.

func BuildWorkspaceEnvView added in v0.0.13

func BuildWorkspaceEnvView(allowedDomains []string, hostCommands map[string]orchestrator.CommandDef) WorkspaceEnvView

BuildWorkspaceEnvView derives the reduced env view from the dispatcher's resolved allowedDomains and hostCommands, via the shared convertHostCommands helper — the sole source of the `boid task env` RPC response as of the Phase 5b PR6 cutover (docs/plans/phase5-shim-and-task-context.md), which retired the parallel dispatch-time environment.yaml file this function used to also feed.

type WorkspaceHomeImportRequest added in v0.1.0

type WorkspaceHomeImportRequest struct {
	// Slug is the normalized workspace slug, used for the container name, its
	// label and every diagnostic.
	Slug string

	// HomeSource is the NAME of the workspace's docker named volume
	// (dockerres.WorkspaceHomeVolumeName) — never a path, for the reason
	// workspaceInitHomeMount spells out.
	HomeSource string

	// HomeTarget is where HomeSource is mounted inside the extraction
	// container, and therefore what the archive's relative paths resolve
	// against. It is hostHomeDir(), the same path a JOB sees its own $HOME at,
	// which is what makes an absolute path baked into a migrated wrapper script
	// or shebang land where the harness will later look for it.
	HomeTarget string

	// HomeID is the identity the (freshly re-created) volume carries on its
	// dockerres.LabelWorkspaceHomeID label. The executor re-checks its own
	// VolumeCreate's answer against it before mounting anything, for the reason
	// verifyWorkspaceHomeIdentity gives.
	HomeID string

	// Tar is the archive to extract, streamed rather than buffered: the
	// measured homes on the machine this was written for run to 4.3GB, and the
	// daemon must not hold one of those in memory.
	Tar io.Reader
}

WorkspaceHomeImportRequest is one extraction run, fully resolved.

type WorkspaceHomeImportResult added in v0.1.0

type WorkspaceHomeImportResult struct {
	// Slug is the normalized workspace slug the migration ran against — not
	// necessarily the string the caller passed (an empty workspace id
	// normalizes to the default workspace).
	Slug string

	// Volume is the home volume that was replaced,
	// dockerres.WorkspaceHomeVolumeName(installID, slug).
	Volume string

	// HomeID is the identity the NEW incarnation carries. It differs from
	// whatever the old one had, which is 論点 f's leg 1.
	HomeID string

	// PreviousExisted reports whether there was a HOME VOLUME to replace — the
	// engine's answer, not an inference from the completion marker (the two can
	// disagree: an operator can delete either one independently, which is the
	// whole reason workspaceHomeMarker.HomeID exists). false means the
	// workspace had never been dispatched into, which is not an error and is
	// the case a fresh install restoring from a backup lands in.
	PreviousExisted bool

	// MarkerRemoved / MarkerRemoveError report 論点 f's leg 2. A failure here
	// is not fatal (leg 1 has already re-armed the init on its own) but it IS
	// reported, because the two legs exist so that either one alone suffices
	// and an operator should be told when they are down to one.
	MarkerRemoved     bool
	MarkerRemoveError string

	// MigrationRecordRemoveError is non-empty when the migration SUCCEEDED but
	// its in-progress record could not be deleted afterwards
	// (workspace_home_migration_sentinel.go).
	//
	// Not fatal — the home is correct and complete — and reported anyway,
	// because leftover daemon state is worth saying out loud. What it COSTS
	// depends on MigrationRecordDiscardsHome.
	MigrationRecordRemoveError string

	// MigrationRecordDiscardsHome says whether that leftover record still
	// authorizes the next daemon start to DESTROY this home (codex round 4,
	// Blocker 1). Meaningful only alongside MigrationRecordRemoveError.
	//
	// false — the ordinary case — means the migration managed to move the record
	// into its "the home was rebuilt" phase before failing to delete it, so
	// recovery will do nothing but the unlink this daemon could not do. The
	// operator's home is safe and no action is required.
	//
	// true means it could not do even that, so the record is still in the phase
	// that says this home is wreckage. The consequence arrives later and looks
	// unrelated when it does: the next daemon start discards this workspace's
	// freshly imported home and re-initializes it from scratch. Deleting the
	// named file before restarting saves re-doing a multi-GB migration, and that
	// difference is the whole reason this is a separate field rather than
	// something the CLI could infer.
	MigrationRecordDiscardsHome bool
}

WorkspaceHomeImportResult describes a completed migration.

type WorkspaceHomeImporter added in v0.1.0

type WorkspaceHomeImporter interface {
	// RemoveWorkspaceHomeVolume deletes volumeName and reports whether there
	// was one to delete. A volume that is not there is NOT an error (a
	// workspace can be migrated into before it has ever been dispatched into),
	// which is why "existed" is a separate return rather than inferred from a
	// nil error. A volume held by a running container comes back as an error
	// wrapping ErrWorkspaceHomeInUse, with nothing removed.
	RemoveWorkspaceHomeVolume(ctx context.Context, volumeName string) (existed bool, err error)

	// ImportWorkspaceHome extracts req.Tar into req.HomeSource, mounted at
	// req.HomeTarget.
	ImportWorkspaceHome(ctx context.Context, req WorkspaceHomeImportRequest) error
}

WorkspaceHomeImporter is the capability Runner.ImportWorkspaceHome needs from a sandbox backend, on top of WorkspaceInitExecutor.

A separate interface, discovered by type assertion, for the same three reasons WorkspaceInitExecutor is (see its §D10 note) — and separate from WorkspaceInitExecutor rather than folded into it because that interface is on the DISPATCH path: every backend has to satisfy it for jobs to run at all, and a backend that can run jobs but cannot serve a one-off migration should fail the migration, not every dispatch.

type WorkspaceHomeTarStats added in v0.1.0

type WorkspaceHomeTarStats struct {
	// Files is the number of regular-file entries written, hard-linked
	// duplicates included.
	Files int64
	// Dirs is the number of directory entries written, excluding the root.
	Dirs int64
	// Symlinks is the number of symlink entries written.
	Symlinks int64
	// HardLinks is how many entries were written as a link to a name already in
	// the archive rather than as another copy of the payload.
	HardLinks int64
	// Bytes is the total file content written — a hard-linked file's payload
	// counted ONCE, matching how the engine's own `docker system df` sizes a
	// volume (see WorkspaceHomeVolumeStore's doc comment). It is the number to
	// compare against a `boid workspace show` size, not the archive's length.
	Bytes int64
	// Skipped names every entry the walk deliberately left out, with the reason
	// — see the irregular-file branch in writeWorkspaceHomeEntry. Reported
	// rather than logged because a migration that silently dropped part of a
	// home is indistinguishable from one that copied all of it.
	Skipped []string
}

WorkspaceHomeTarStats is what a walk produced (and, while it is running, how far it has got). Reported both incrementally through WriteWorkspaceHomeTar's progress callback and once at the end as its return value.

func WriteWorkspaceHomeTar added in v0.1.0

func WriteWorkspaceHomeTar(w io.Writer, root string, progress func(WorkspaceHomeTarStats)) (WorkspaceHomeTarStats, error)

WriteWorkspaceHomeTar writes root's contents to w as an uncompressed tar stream, and reports what it wrote.

progress, when non-nil, is called at most every workspaceHomeTarProgressInterval with the stats so far, and once more is NOT implied at the end — the return value is the final figure.

What crosses, and what deliberately does not

  • Modes cross exactly (D3: 「`0600` などの mode は維持すること」). The extraction side is what makes that stick; see workspaceHomeImportArgv.
  • Ownership does NOT cross. Every entry is written uid/gid 0 with no user/group names, because the extraction discards ownership anyway (--no-same-owner) and recording the host account into an artifact whose whole purpose is to cross a uid-mapping boundary is noise at best.
  • Symlinks INSIDE the tree cross as symlinks, targets verbatim — absolute ones included. Following them would duplicate payloads and flatten a toolchain's internal structure; rewriting them would be boid inventing a target the workspace never had. An absolute symlink into the host filesystem is already broken inside the sandbox and stays broken, which is the honest outcome (memory: 「workspace HOME 配下の symlink は relative 必須」).
  • The ROOT is the one exception: a root that is itself a symlink is RESOLVED and its target walked. The asymmetry is deliberate — the root is the directory the operator named on the command line, while the links inside it are the home's own structure. See ResolveWorkspaceHomeSource for the empty-archive bug that made this explicit.
  • Hard links cross as links. A node/volta toolchain hard-links aggressively, and writing each name's content again would inflate a multi-GB transfer for nothing.
  • Sockets, FIFOs and device nodes are SKIPPED and named in Skipped. None of them is state a workspace home needs restored (an agent's IPC socket is re-created on demand), and a FIFO in particular would make the extraction block or fail.
  • Sparse files are read densely: a 100MiB sparse file crosses as 100MiB. archive/tar has no portable sparse encoding worth relying on, and the alternative — dropping the file — loses data.

It never writes to root. That is D4's first rule (「source は絶対に削除・変更 しない。読むだけ」) and the reason the migration is safe to re-run.

type WorkspaceHomeVolume added in v0.1.0

type WorkspaceHomeVolume struct {
	// Slug is the workspace this volume belongs to. For Get/Remove it is the
	// slug that was asked about; for List it is read off the volume's
	// dockerres.LabelWorkspaceHome LABEL — see List's doc comment for why the
	// name cannot supply it.
	Slug string

	// Volume is the engine-side volume name,
	// dockerres.WorkspaceHomeVolumeName(installID, slug) — the same name
	// resolveWorkspaceHome hands the job container as its $HOME mount.
	// Always set, whether or not the volume currently exists.
	Volume string

	// Exists reports whether the engine currently has this volume. false
	// means the workspace has never been dispatched into — the
	// init-on-first-dispatch contract, not an error.
	Exists bool

	// Bytes is the volume's size as GET /system/df reports it, meaningful
	// only when Exists is true and SizeError is empty.
	Bytes int64

	// SizeError is non-empty when the size could not be determined. Bytes is
	// 0 and must not be trusted when it is set; callers render "?" instead.
	// It never implies the volume is gone or undeletable — Remove treats
	// sizing as best-effort and attempts the deletion regardless.
	SizeError string
}

WorkspaceHomeVolume is one workspace HOME volume as the engine describes it. Plain data on purpose: internal/api renders it into the wire types (api.WorkspaceHomeSize, api.WorkspaceRemoveResponse) and this package never learns about those.

type WorkspaceHomeVolumeAPI added in v0.1.0

type WorkspaceHomeVolumeAPI interface {
	VolumeInspect(ctx context.Context, volumeID string, options client.VolumeInspectOptions) (client.VolumeInspectResult, error)
	VolumeList(ctx context.Context, options client.VolumeListOptions) (client.VolumeListResult, error)
	VolumeRemove(ctx context.Context, volumeID string, options client.VolumeRemoveOptions) (client.VolumeRemoveResult, error)
	DiskUsage(ctx context.Context, options client.DiskUsageOptions) (client.DiskUsageResult, error)
}

WorkspaceHomeVolumeAPI is the engine surface workspace HOME reporting and deletion needs, declared as its own narrow interface for the same two reasons SelfContainerInspector is: internal/server can hand in the bare *client.Client it already built without constructing a container backend, and a test stub does not have to implement two dozen unrelated methods.

DiskUsage is on it, rather than VolumeInspect alone, because of a fact that is easy to get wrong and expensive to get wrong silently: Volume.UsageData is populated ONLY by GET /system/df. Measured against rootless podman 4.9.3 (2026-07-27), GET /volumes/<name> and GET /volumes both return the volume with no UsageData field at all, exactly as the moby type's own comment says ("This information is used by the `GET /system/df` endpoint, and omitted in other endpoints"). A sizing implementation built on VolumeInspect would compile, run, and report every workspace as 0 B.

type WorkspaceHomeVolumeRequest added in v0.1.0

type WorkspaceHomeVolumeRequest struct {
	// Slug is the normalized workspace slug; it becomes the value of the
	// dockerres.LabelWorkspaceHome label on a newly created volume.
	Slug string

	// Name is the volume name, computed by the caller
	// (dockerres.WorkspaceHomeVolumeName). Executors must use it verbatim
	// rather than recomputing it: this same string becomes the job container's
	// HOME mount source, and two independent computations of a deterministic
	// name are two things that can disagree.
	Name string

	// CandidateID is the identity to stamp on the volume IF this call is the
	// one that creates it. For a volume that already exists it is discarded by
	// the engine, and the executor reports the incumbent identity instead —
	// which is exactly how a deleted-and-recreated volume becomes detectable.
	CandidateID string
}

WorkspaceHomeVolumeRequest asks an executor to make sure one workspace's HOME volume exists, and to report the identity it carries.

The two halves are one request, and one engine call, on purpose: VolumeCreate is idempotent and returns an ALREADY-EXISTING volume together with its own labels, so "ensure" and "read the identity" are the same operation. Splitting them into ensure-then-inspect would double the per-dispatch engine round trips on the hot path and open a window between them. See dockerres.LabelWorkspaceHomeID for the measurement this rests on.

type WorkspaceHomeVolumeStore added in v0.1.0

type WorkspaceHomeVolumeStore struct {
	// API is the engine handle, the very *client.Client server/wire.go built
	// for the container backend. nil means no engine was available, which
	// every method degrades gracefully on rather than panicking.
	API WorkspaceHomeVolumeAPI

	// InstallID scopes the volume names this store generates and recognizes,
	// matching Runner.InstallID / ContainerBackendOptions.InstallID.
	InstallID string
}

WorkspaceHomeVolumeStore answers the three questions 論点 a-2 needs about workspace HOME volumes: how big is this one, what ones exist, and delete this one.

Sizing goes through GET /system/df, and why that was the choice

Measured against rootless podman 4.9.3 (2026-07-27), read-only:

  • GET /volumes/<name> (VolumeInspect) and GET /volumes (VolumeList), with and without a label filter, return NO UsageData at all. Sizing cannot be built on them.
  • GET /system/df returns UsageData{Size,RefCount} for every volume. Its Size is du --apparent-size semantics: a probe volume holding a 1MiB regular file, a 100MiB sparse file, a hardlink to the regular file, a symlink and a small file reported 105906193 bytes, byte-identical to `du -sb` on the mountpoint.
  • podman 4.9.3 IGNORES both the `type=volume` and the `verbose` query parameters: all three responses (no params, type=volume, verbose=1) were byte-identical at 151995 bytes, and per-volume UsageData was populated in each. Both options are still passed, because a real docker engine honours them and one of them is load-bearing there — see DiskUsageOptions below.

The alternative 論点 a-2 asked to compare — running `du` inside a throwaway container — was rejected: it needs a container start per volume (against one df call for the whole listing), an image to run, and a second init-container-shaped failure surface, in exchange for a number in the SAME units df already reports. Its one advantage would have been not walking unrelated volumes, which matters only if these calls were hot, and they are not (see workspaceHomeVolumeTimeout).

What changes for users: df's Size is real `du` semantics, so a hardlinked file is counted ONCE (the previous host-path implementation, humanize.ApparentSize, summed every name and counted it twice) and a humanize.ApparentSize, summed every name and counted it twice). Sparse files stay logical in both, and symlinks are counted the same way by both (ApparentSize sums FileInfo.Size() for every non-directory entry, which for a symlink is its target string's length — an earlier revision of this comment claimed ApparentSize skipped them, which is not what internal/humanize does). docs/{ja,en}/guide/workspace-home.md is updated accordingly.

func (*WorkspaceHomeVolumeStore) Get added in v0.1.0

Get reports on slug's workspace HOME volume.

It never returns an error: every failure mode (no engine handle, an inspect that failed for a reason other than "no such volume", an unavailable size) is reflected in the returned value's Exists/SizeError fields instead. That is the same "never block the rest of the response on a size lookup failure" contract the host-path computeWorkspaceHomeSize had, carried across the mechanism change.

func (*WorkspaceHomeVolumeStore) List added in v0.1.0

List enumerates every workspace HOME volume belonging to this install.

The slug comes off the LABEL, not the name (論点 a-2, D7)

dockerres.WorkspaceHomeVolumeName runs the slug through SanitizeNamePart, which is not invertible — "team/a" and "team-a" produce the same volume name — so there is no way back from a name to the workspace it belongs to. dockerres.LabelWorkspaceHome carries the slug verbatim, and PR6 made both volume-creating paths (resolveWorkspaceHome's EnsureWorkspaceHomeVolume and containerBackend.ensureNamedVolumes) attach it with the already-normalized slug, so the label is the authority here.

Enumerating on presence, and scoping by name reconstruction

The engine query filters on the mere PRESENCE of dockerres. LabelWorkspaceHome. It deliberately does NOT filter on dockerres.LabelWorkspaceHomeInstallID the way internal/reap.unionResources does, because that label is only attached when the install HAS an id (see ensureNamedVolumes) — an install-id-scoped query lists NOTHING on an install without one, which is a fine fail-safe for reap (it destroys) and exactly backwards for a listing (it reports). Verified against podman 4.9.3 (2026-07-27): a bare `label=<key>` term matches on presence.

Install scoping is then done by reconstructing the name — dockerres.WorkspaceHomeVolumeName(s.InstallID, labelSlug) == v.Name — which is both stricter and independent of the optional label: two boid installs sharing one engine never list each other's homes, and the rule reads the same whether or not the install-id label happens to be there. The one case it degrades on is a volume this install created BEFORE it had an install id (named ...-noinst-<slug>): the daemon no longer mounts that volume either, so leaving it out of "this install's homes" keeps the listing consistent with what dispatch actually uses. It is still visible to `docker volume ls`, which the user-facing doc points at for manual cleanup.

A sizing failure does not fail the call: the listing is what drives orphan detection, and losing it because df was busy would be a much worse trade than an entry rendering "?" for its size.

func (*WorkspaceHomeVolumeStore) Remove added in v0.1.0

Remove deletes slug's workspace HOME volume, reporting what was there beforehand.

deleted is true only when the volume existed AND the removal succeeded — mirroring the host-path implementation, where os.RemoveAll returning nil on a path that was never there did not count as a deletion.

In-use volumes surface as an error (論点 a-2, D6)

Force is set, but only one of its two meanings is being relied on. Measured against rootless podman 4.9.3 (2026-07-27): with a running container holding the volume, DELETE /volumes/<name> and DELETE /volumes/<name>? force=1 BOTH return 409 ("volume is being used by the following container(s): <id>"); against a name that does not exist, force=1 returns 204 where the unforced call returns 404. So force buys tolerance of a volume that vanished between the inspect and the remove — os.RemoveAll's tolerance, which the host-path version had — and buys nothing at all against a job that is currently running in that workspace. That 409 is returned to the caller rather than swallowed: `workspace remove` reports it as a part-completed remove (the row is gone, the volume is not), which is the honest answer. Silently reporting success would tell an operator their credentials were destroyed when they are still sitting on the engine.

Sizing stays best-effort and never gates the delete attempt (PR #791 review, Should-fix #2, carried across the mechanism change): neither an unavailable size nor an inspect that could not establish existence skips the VolumeRemove call.

type WorkspaceInitExecutor added in v0.1.0

type WorkspaceInitExecutor interface {
	// EnsureWorkspaceHomeVolume creates req.Name if it does not exist (with
	// req.CandidateID as its identity) and returns the identity the volume
	// carries afterwards. An empty return means the volume exists but was not
	// created by boid; the caller decides what to do about that.
	EnsureWorkspaceHomeVolume(ctx context.Context, req WorkspaceHomeVolumeRequest) (string, error)

	RunWorkspaceInit(ctx context.Context, req WorkspaceInitRequest) error
}

WorkspaceInitExecutor is the capability resolveWorkspaceHome needs from a sandbox backend: bring a workspace's HOME volume into existence, report its identity, and run one WorkspaceInitRequest to completion.

Both methods live on one interface because after PR6 they are inseparable: a backend that cannot create a named volume cannot host a workspace home at all, and a backend that cannot start a container cannot prepare one. Two interfaces would let a backend satisfy half the contract and fail the other half at run time, which is precisely what the assertion in workspaceInitExecutorFor exists to turn into a startup-time answer.

§D10 — why this is a separate, assertion-discovered interface rather than a method on backend.SandboxBackend:

  • backend.SandboxBackend is the JOB lifecycle contract (Launch → session → Wait/Stop/Signal → ReapOrphans). A workspace-home init has no job row, no session, no transcript, no attach ingress and no place in ReapReport's job accounting — adding it there would force every implementation, including that package's own test doubles, to carry a method that means nothing to them.
  • The request type lives here, in internal/dispatcher, and internal/dispatcher imports internal/sandbox/backend. Putting the method on that interface would mean moving the request type down into it, i.e. putting workspace-home vocabulary into the generic backend package.
  • This package already discovers container-only capabilities by assertion rather than by growing the interface: IsContainerBackend, ContainerBackendUIDGID, ContainerBackendBrokerTLS, ContainerBackendUsesDockerAPI. This is the same shape, and — because both the interface and *containerBackend live in this package — needs no exported helper at all.

type WorkspaceInitRequest added in v0.1.0

type WorkspaceInitRequest struct {
	// Slug is the normalized workspace slug, used for the container name,
	// its label, BOID_WORKSPACE_SLUG and every diagnostic.
	Slug string

	// HomeSource is what the executor mounts: as of PR6 the NAME of this
	// workspace's docker named volume (dockerres.WorkspaceHomeVolumeName), not
	// a path. Through PR5 it was an absolute host path — the homes/<slug>
	// directory, host-visible only because it derived from RuntimesDir =
	// BOID_RUNTIME_DIR, i.e. tmpfs, which is the persistence regression PR6
	// closed. workspaceInitHomeMount rejects an absolute value outright rather
	// than binding it, so the two eras cannot be confused silently.
	HomeSource string

	// HomeTarget is where HomeSource is mounted INSIDE the container, and
	// therefore the value of HOME and BOID_WORKSPACE_HOME. It is the same
	// path a job container sees its own $HOME at (hostHomeDir(), what
	// BuildSandboxSpec uses), which is the point: a toolchain init.sh installs
	// records absolute paths in wrapper scripts, .pth files, shebangs and
	// symlinks, so the path it installs under has to be the path the harness
	// later runs under. Before PR5 those two differed and every absolute
	// symlink an init.sh created dangled inside the sandbox.
	HomeTarget string

	// Env is the complete environment for the run — see buildWorkspaceInitEnv
	// for what is in it and, more to the point, what is deliberately not.
	Env map[string]string

	// Script is the assembled wrapper (builtin prelude + user script),
	// fed to `bash -s` on the container's stdin. Never a path: the daemon's
	// own filesystem is not visible to the sibling engine that has to start
	// the container (build/container/compose.yml's KNOWN GAP note), so a
	// temp file the daemon writes cannot be a bind source.
	Script string

	// SkeletonDirs are the bind-target directories the prelude creates,
	// relative to the home (workspaceHomeSkeletonDirs). Carried on the request
	// rather than recomputed by the executor so that the set the init actually
	// created and the set resolveWorkspaceHome records in the completion
	// marker are the same value, not two evaluations of one function.
	SkeletonDirs []string

	// HomeID is the identity the workspace home volume carries on its
	// dockerres.LabelWorkspaceHomeID label (論点 b). resolveWorkspaceHome
	// records the same value in the completion marker's home_id and compares
	// the two on every later dispatch.
	//
	// The executor needs it because it has to guarantee the volume exists
	// before creating a container that mounts it, and a volume that vanished
	// between resolveWorkspaceHome's check and this run must come back with
	// THIS identity — otherwise the marker written afterwards would describe
	// an incarnation that no longer exists and every subsequent dispatch would
	// re-init.
	HomeID string
}

WorkspaceInitRequest is one workspace-home preparation run, fully resolved: which home to mount where, what environment to run under, and the complete shell program to feed the container's stdin.

Exported, together with WorkspaceInitExecutor, for one reason: the executor is discovered by type assertion on Runner.Backend (see §D10 on workspaceInitExecutorFor), and a test in another package that wires its own backend.SandboxBackend into internal/server's Config.Backend has to be able to satisfy that interface. An unexported request type would make the interface unimplementable outside this package, which would turn "this fake backend cannot prepare workspace homes" from a compile error into a runtime one.

type WorkspaceInitScriptStore added in v0.1.0

type WorkspaceInitScriptStore struct{}

WorkspaceInitScriptStore reads, writes and removes a workspace's init.sh at the path resolveWorkspaceHome reads it from.

It is a struct with no fields on purpose. An injectable root would be the usual way to make a filesystem store testable, and it would break the one property this type exists for: the reader takes its root from the ambient environment (os.UserConfigDir), so a writer with its own configurable root could be pointed somewhere the reader never looks. Tests isolate the environment instead (testutil/homeenv), which is the same thing production does and therefore cannot drift from it.

func (WorkspaceInitScriptStore) Path added in v0.1.0

Path returns the absolute path of slug's init.sh on the DAEMON's filesystem, or an error when slug is not a valid workspace slug.

Exposed (rather than kept internal to the store's own methods) because it is worth showing an operator: under the container deploy the answer is a path inside the daemon's volume, and saying so is how a message stops implying that editing a file on the host would do anything. See the adapters' missingCLIError for the message that used to imply exactly that.

func (WorkspaceInitScriptStore) Read added in v0.1.0

func (s WorkspaceInitScriptStore) Read(slug string) (data []byte, exists bool, err error)

Read returns slug's init.sh, reporting exists=false (with no error) when the workspace has none — the pass-through class of docs/plans/home-workspace-volume.md 「script が無い workspace は素通し」, not a fault.

func (WorkspaceInitScriptStore) Remove added in v0.1.0

func (s WorkspaceInitScriptStore) Remove(slug string) (removed bool, err error)

Remove deletes slug's init.sh, reporting whether there was one to delete.

The per-workspace directory is left in place: it is cheap, and removing it would race a concurrent Write that has already created it.

func (WorkspaceInitScriptStore) Write added in v0.1.0

func (s WorkspaceInitScriptStore) Write(slug string, data []byte) error

Write publishes data as slug's init.sh, creating the per-workspace config directory if needed.

The file is 0600 and the directory 0700 — the daemon is the only reader, and the content is operator-authored shell that runs with the workspace's full (unrestricted, see the guide) network access.

The directory's mode is SET on every write, not merely requested at creation (PR9 codex round 2, Minor 4). os.MkdirAll applies its mode only to directories it creates, so an install that already had ~/.config/boid/workspaces/<slug>/ kept whatever mode the pre-PR9 hand-managed workflow left — 0775, group-writable, on the install this plan doc migrates. The file's own 0600 is not an answer to that: it protects the content, while a group-writable directory lets anyone in the group unlink init.sh and leave their own in its place, to be run by the workspace's init container with that workspace's network access and credentials. A chmod failure fails the write rather than being logged past — this tree is the daemon's own $XDG_CONFIG_HOME, so being unable to set the mode on it is a fault the operator needs told, and publishing the script anyway would leave it sitting somewhere this function just established it cannot vouch for.

It is deliberately NOT executable. boid never execs the configured file: it reads the bytes, hashes them into the completion marker, and streams them into the init container inside a quoted heredoc for `bash` to run (buildWorkspaceInitScript). An executable bit would advertise a way of running this file that does not exist, and a shebang in it is ignored for the same reason.

The publish is atomic (temp file in the same directory, chmod, fsync, rename) so a concurrent resolveWorkspaceHome — which reads this path with no lock on the fast path — can never observe a half-written script and hash it into a marker.

type WorkspaceLookup added in v0.0.8

type WorkspaceLookup interface {
	Load(slug string) (*orchestrator.WorkspaceMeta, error)
}

WorkspaceLookup reads a WorkspaceMeta for a given slug. Satisfied by *orchestrator.WorkspaceStore; kept as an interface so tests can stub it without touching disk. Load is expected to return os.ErrNotExist-wrapped errors when the workspace file is missing — Runner treats that as the "degraded window" and falls back to the global floor.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL