# Design traceability Automatic project snapshots and explicit result application accompany native one-command planning, primary-agent-selected budgets, the docked sidebar and durable collaboration runtime. Plan editing and mission controls call the same runtime that authenticates model tools by session identity; the browser transport uses modern Harness native browser credentials, cookies and trusted-host checks. | Agreed design property | Implementation | Evidence | | --- | --- | --- | | Workstreams outlive agent turns | `types.ts`, `store.ts`, `runtime.ts` | Full host restart without live owner in `harness-composition.mjs` | | Peer initiative within one mission | `propose`, `workstream`, `message`, `subscribeTopics` | Worker proposes review and contacts its peer through real model-visible tools | | Conversation differs from verified knowledge | Typed `Delivery` and `Evidence` records | Unverified findings, negative outcomes, challenges and host tool-run references | | Runtime owns coordination authority and capacity | Actor resolution, scoped tool guards, shared budget; Harness sandbox owns workspace confinement | Cross-session rejection, alternate delegation denial, shared-step tests | | Enforced exclusive work ownership | Atomic attempts, epochs, leases, quiescent handoff | Concurrent claims, stale result rejection, transfer and cancellation tests | | Durable partial work | Per-task workspace checkpoint metadata, retained Git refs and durable stop-transition markers | Dirty restart, interrupted handoff, cross-owner and round-trip handoff tests | | Immutable artifacts and independent verification | `captureArtifact`, exact candidate reviewer checkout, fresh host check checkout; evidence status changes remain recorded | Source branch preservation, scope and failed-check tests | | Challenges affect dependent decisions | Transitive dependency and `reviewOf` invalidation | Delayed preparation/verification race regressions | | Repair can converge | `replaces`, acceptance obligation preservation, verified evidence supersession | Runtime repair/acceptance tests | | Controlled coding integration | Accepted dependency artifacts merged only in owned integration worktree | Real Loader composition and merge conflict tests | | Durable coordination and selective wakeups | SQLite transactional state/event/outbox, stable inbox IDs and enforced parking at pre-step | Restart, duplicate delivery, offline owner and concurrent parking/wake tests | | Peer context is visible to the actual model | Host-derived identity prompt and mission IDs in rendered delivery text | First-peer-before-assignment regression through native model input | | Resumable bounded workers | Harness factory handles, saved composition, cumulative usage reconciliation | Adapter cold resume and usage replay tests | | Editable planning before execution | `swarm_stage`, `PlanInput`, revisioned `DraftPlan`, `plans.ts`, `DraftEditor.tsx` | Plan validation, ownership, revision-conflict and draft HTTP tests; CLI Web/browser workflow in `test:web` | | Complete topology before dispatch | Staged mission assembly, stable topology IDs, `launchDraft`; saved-plan workspace and exact-model admission | Launch retry, interrupted assembly recovery and model-validation-before-effects tests | | Live inspectable mission state | `ActivityPanel.tsx`, selected-session `SwarmMonitor`, native state/watch RPC, summary and disclosed technical views | Watch cancellation, cursor replay, owner isolation, HTTP and actual Web-profile browser tests | | Sidebar remains usable beside chat | Optional Better Sidebar tab, independent dock fallback, retained draft state on collapse | Real service contract tests and browser geometry/draft interactions | | Owner-only mission management | Verified native session IDs, `visibleSnapshots`, durable worker identity checks and runtime control methods | Owner/member isolation, historical-worker readonly, pause/stop and cold-owner HTTP cases | | Independent worker conversations and persisted transcripts | Listed workers use `sessions.open(workerSessionId)`; missing/disposed workers use owner-authorized `worker-history` RPC backed by native `sessionController.inspect`, through `WorkerHistory` and `WorkerTranscript` | Native navigation and history pagination/projection tests; browser workflow checks live navigation and cold history without model activation | | Conversation history stays reconstructable | Durable `tool/result.meta.swarmSnapshot` conversation projections, separate from live watches | Real client registry mount/dispose and conversation render tests | | No agent-loop fork | `ctx.agents`, `agent.send`, scoped guards and lifecycle events | Packaged artifact loaded with unmodified target Harness | The runtime uses one SQLite owner and a local worker adapter. Task selection is deterministic priority/readiness scheduling; temporary coordinators advise through the same tools as other members. The primary chooses the initial team and task graph. Runtime scheduling does not perform separate model-based task valuation or distributed consensus. An owner can stage a plan through the model tool or create one manually in **New mission**. The plan records the mission's scope, budget and acceptance criteria, worker provider/model/reasoning choices, workstreams, and tasks with dependencies and independent review targets. Saving performs no worker or worktree creation. Browser saves and launch validate the canonical workspace against the selected native session. Provider catalogs are advisory; the exact route and requested reasoning effort are validated through the public Harness LLM service before launch effects. Launch requires a saved revision and a live owner composition. All workers and task references are materialized while the mission remains staged; only the final activation permits dispatch. A failed launch retains its draft and partially prepared mission for retry using stable IDs. The same completed launch returns the same mission on retry. To change a failed plan, discard it and stage a new one; retained artifacts are not silently deleted. The browser bridge is optional and registered through native Connection under `/agent-swarm`, with native browser authentication and Host/Origin/Fetch-Metadata checks, native RPC envelopes and an additional decoded-payload bound. Headless use does not depend on a web server. The sidebar reads only its viewed session's authorized drafts and missions, watches commits without model requests, cancels obsolete session reads, and fences late plan/control responses after selection changes. Draft editing and owner controls are disabled for worker sessions, including stopped historical workers. Worker links use ordinary `sessions.open` while the independent worker session is listed. The native composer may remain writable; mission management authority is enforced separately. When a disposed worker is absent from that list, a read-only transcript opens inside the sidebar using the plugin’s `worker-history` RPC. The host checks mission/member ownership, then reads attached or persisted events through native `sessionController.inspect` without resuming or publishing an agent. `WorkerHistory` fetches pages of 30 append-origin messages, merges by event sequence, and ignores responses after a view closes or changes. The viewer displays input, assistant messages, tool calls/results and an event index, with earlier-page loading. It is a text-oriented history view, not a recreated native chat session; media is represented by type and individual entry display is explicitly capped at 40,000 characters. Both live sidebar cards and historical conversation cards share this navigation path. Conversation snapshot cards preserve the state recorded by explicit observations. The sidebar summary and disclosed work board, dependency graph, evidence and activity views reflect later durable state through the watch protocol. The advanced draft editor includes native model/reasoning selectors, priorities, experiment flags, scope, budgets and independent review targets; verification rows display their source task's actual check commands. Principal labels use the native English/Chinese locale setting, and CSS follows Harness's light/dark theme marker. Hiding a tab or collapsing the dock cancels monitor requests while retaining editor state; workers continue within runtime budgets. Watch updates describe committed collaboration state, not individual model tokens or distributed synchronization. Deterministic composition tests script provider responses while Harness loading, tools, sessions, worktrees, sandboxes and filesystem outcomes are real. `npm run test:web` additionally exercises the actual CLI Web composition and browser controls; its artifacts and current outcome are reported separately from synthetic UI previews. Current tested versions, the scripted-provider boundary and frontend evidence are summarized in [validation.md](validation.md). These tests do not establish comparative swarm performance. Remaining authority, lease and storage limits are documented in [known-limitations.md](known-limitations.md). ## v0.2.1 sidebar presentation The client registers one `agent-swarm` tab through the optional public Better Sidebar service. Each tab receives its supplied session scope and visibility, owns a separate state monitor and history viewer, and never substitutes the globally selected session for a pinned tab. Hidden tabs suspend monitor requests. Registration and service replacement follow Cordis disposal. Without Better Sidebar, the additive shell contribution renders a right-edge dock and explicitly reserves its width from the DSH root. A narrow viewport uses a bottom row. Width changes, collapse and reopen affect layout, not runtime authority. The floating rectangle, title-bar dragging, corner resize and free-position preferences were removed. The native conversation and tool-details slot owners remain installed. ## Native command and primary-agent decisions (v0.3.0) The command descriptor is registered in native `commands`; native `ui-commands` supplies autocomplete and arbitrary text input. A client commandview renders the original goal and acknowledgment, and a successful native command event opens the sidebar. No duplicate client-only command or custom composer parser is used. `planner.ts` checks the live owner, canonical Git workspace and current model before creating a durable automatic request. Before delivering the typed `swarm-start` follow-up through that owner's native inbox, it freezes one project baseline and supplies a detached planning checkout. That turn inspects the frozen repository and invokes `swarm_launch`; no secondary provider loop or hardcoded task decomposition is used. All members use the same durable baseline, including retries and restarts. The runtime checks the generated topology, assembles it with dispatch fenced, and activates it atomically. Completion is driven by accepted artifacts, independent review and coverage, not a model's claimed success. The primary agent decides token/step budgets, team capacity and membership, task/experiment limits, mission duration, task graph, scope, acceptance, check commands, priorities, optional model routes, per-member output-token allowances, per-task recovery attempts and verification timeouts. `swarm_budget` permits owner-only revisions based on progress, with a durable reason; it never resets usage. Paused/blocked missions remain under explicit owner control. Database/worktree locations, heartbeat/tick intervals, output/payload bounds, identity, artifact checks and review requirements remain runtime policy. The journal is separate from manual drafts. The frontend displays planning/errors directly and hides the internal auto-generated draft editor. Manual advanced staging remains available when explicitly requested. Host restarts and retries preserve request/draft/mission identities. Peer messages cannot launch another swarm, expand budgets, change owner authority or waive verification. Automatic topology size is constrained by the primary-selected worker/task budgets and the transport payload bound; no separate 200-entry team/task ceiling remains. Acceptance commands run in clean committed artifact checkouts, with changed paths checked separately by the host. Budget resume waits for actual worker quiescence and wakes the same attempt immediately, preserving evidence. ## Admission repair (v0.3.1) Both complete plans and incremental create/propose calls share admission normalization and diagnostics. Only equivalent path aliases (`./src/`, `src/**`) become canonical relative scopes; arbitrary globs, root guesses, traversal and descriptive prose are never expanded to broader permissions. Legal filenames may contain spaces, so admission cannot reliably detect every prose sentence; the model contract explicitly separates path scope from objective and acceptance. For verification, `reviewOf` already gates the source's submitted artifact. A duplicate ordinary dependency is removed on a detached input copy to avoid waiting for acceptance of the source being reviewed. Other dependencies remain mandatory, and the source author still cannot accept their own work. Canonical fields are retained in the durable plan/task; caller inputs are unchanged. Field diagnostics for paths and code checks are returned together before complete-plan admission. Missing, empty and whitespace-only shell checks remain rejected. The primary uses ordinary tools to inspect the repository and corrects the same request, preserving identity, acceptance and its selected budget. Read-only analysis and report consolidation use research tasks and may depend on accepted research; code integration continues to require immutable artifacts and host commands. The runtime never silently changes a task kind or supplies an always-passing command. ## Live state and visible activity The default mission view leads with the goal, observed operation, accepted-task count and recent progress. Native disclosures hold the team, technical tabs/resources and manual configuration form. Completion exposes the existing result inspection and application controls. Disclosure state changes presentation only; ownership, budget decisions, verification and result application still use the same host runtime. SQLite records a monotonically increasing revision and changed scopes in the same transaction as each mutation. Subscribers wake only after commit; rollback produces no revision or notification. A bounded change history supports catch-up without using coordination event counts as a state cursor. Schema 1 upgrades to schema 2 add this bookkeeping without replacing mission records; an older binary requires the pre-upgrade database for rollback. The client first reads `/agent-swarm/state`, then waits on `/agent-swarm/watch` with its owner and cursor. The host returns changed mission snapshots, authoritative mission membership, and current owner drafts/automatic requests. The client merges unchanged missions and fences late responses by selected owner and request identity. Native agent creation/disposal also wakes a watch because owner liveness can change without a SQLite mutation; keepalives reconcile that metadata as well. Missing history or an invalid future cursor requires a complete snapshot. Disposal, hiding or changing owner cancels the wait. Native HTTP authentication and session ownership checks also apply to watches. Network failure retains the last data, displays a reconnecting state and retries with bounded backoff. Worker activity originates in native model-stream, tool-execution, verification and retry lifecycles. Each in-process operation has an identity; ending one operation cannot erase a newer overlapping operation. The persisted member projection records the observed kind and timestamps for display. Stream chunks can update an observation timestamp, while lease bookkeeping does not fabricate progress. Cancellation and completion clear current activity, and startup discards persisted liveness before recovering work. Lease renewal checks the current attempt identity against the adapter's still-owned, uncancelled operation. A stored activity record alone is insufficient. Renewal remains bounded by the mission deadline; an operation that is merely waiting may still consume its provider/tool timeout. This prevents a healthy long operation from losing ownership solely because no step boundary occurred, without treating liveness as proof of a useful result. Acceptance continues to require the independent artifact/check path. ## Token efficiency and stall handling Model-visible context is scoped by role. Every session still registers the same global tool set, and the host's scoped restriction hides what a role cannot use: ordinary sessions keep the entry set and a short prompt, a session that owns an automatic request or mission is promoted to the owner protocol and management tools on the next assembly, workers see member tools and the member protocol, and subagent sessions see no swarm tools. Planning rules appear once in the owner prompt; the planning message carries only request facts. The runtime guard is unchanged and remains the authority boundary. `swarm_observe` returns focused views instead of the whole board: a member sees its current task, effective prerequisites (following replacement lineage), the review source with its evidence, references to its own tool runs, and events after a cursor; the owner sees a compact board, usage buckets, in-flight estimate and unschedulable work. Full records are read by id (`taskId`, `runId` paged by `offset`, `evidenceId`). The complete snapshot travels only in UI presentation metadata. Each worker tool result is recorded through the host post-execute waterfall before the model sees it and ends with its durable run id, so evidence can be cited without an observation round trip. Owner notices are reserved for decisions: rejection, challenge, worker failure, budget exhaustion, a stalled board and completion. Submission, acceptance and launch are durable events for the panel. Dependencies follow repair lineage. A reference to a blocked or cancelled task resolves to its live replacement (recursively), so an integration planned before a rejection becomes ready when the accepted repair lands, is prepared with the repair's artifact, and is invalidated when that repair is challenged. Two accepted replacements for one obligation are ambiguous and fail closed. After a verdict, other pending reviews of the same source are cancelled; a review cannot be assigned to its source author or target finished work. Replacement admission errors name the failing condition. ## Owner withdrawal, lineage and worker close-out (round 2) The owner withdraws admitted-but-mistaken work with `swarm_cancel(taskId, reason)`. The tool is owner-only and the worker guard refuses it. A pending task becomes `cancelled` immediately; a running attempt is fenced, its lease released, its member freed and the worker stopped; a `submitted` task may also be withdrawn — the owner keeps authority to stop work under review, the captured artifact remains durable and its pending reviews are retired — and accepted work is immutable. Every withdrawal writes one durable `task/cancelled` event carrying the previous status, attempt and owner, and cancelling a source also retires its pending, running and quiescence-parked reviews so a review of cancelled work cannot re-pend after lease expiry. Replaying the same cancel is idempotent. Replacement admission resolves live replacements before the status check, so a blocked task admits exactly one live replacement and a second proposal is rejected by name; lineage resolves deterministically to the oldest live replacement for imported history, and two accepted replacements still fail closed. This keeps `swarm_cancel` the owner's only way to withdraw a live duplicate instead of letting it run to acceptance. A worker that ends its turn with an open attempt is not stranded. The runtime nudges it a bounded number of times (`maxIdleCloseouts`, default 2, not yet exposed in the plugin `Config`), then captures the workspace as a durable checkpoint and re-pends the task to the same member with one recovery credit, so uncommitted work survives and reassignment does not silently start from the mission base. If the checkpoint itself fails, the task blocks and the owner is woken rather than the dirty workspace being reassigned. The lease-expiry checkpoint re-reads the task after the capture await and continues only if the epoch, status and attempt are unchanged, so an owner cancel committed while the capture is in flight is never overwritten by recovery; a failed lease-expiry checkpoint emits `task/checkpoint-failed` and notifies the owner. Workers cannot write git metadata: the worktree index and refs live under the shared git common directory outside the worker-writable path, so a worker-side `git commit` fails with `index.lock: Operation not permitted`. Artifact publication is host-side and does not depend on a worker commit; the assignment instructions state the constraint and a denied write returns a typed error naming `swarm_submit`. Completion recognizes dead work. Tasks that can never be dispatched (dead prerequisites, unreachable review sources, blocked work without repair, stopped assignees) are reported in the owner view and in a single stall notice per distinct state. The owner's complete, and automatic completion once the board is stalled, cancel those leftovers when every acceptance criterion is independently covered and the deliverable exists; evidence of dead work no longer blocks completion while live disputes do. One reviewed implementation is a complete code plan and its artifact is the delivery target when no integration task exists. Accounting keeps disjoint buckets (uncached input, cache read, cache write, output including reasoning, physical requests) per worker and per mission, attributes owner usage by time window to the newest live mission or planning request, estimates in-flight requests from each worker's average before admitting a step, and offers an optional boundary compaction through the host engine after a verdict for idle workers over a prompt-pressure threshold. Verification checkouts link the source project's ignored dependency directories so declared checks find their toolchain, and exit 127 is annotated as an environment failure.