# Architecture ## Pinned integration `0.3.54` targets DeepSeek Harness `0.1.1-rc.2` at `b150a551b8d465e31e418e1b2eaf5e79bbb7d28e`. It is an external Cordis bundle (`dsh.bundle.patch`) and does not patch `agent-loop`, the Web client, or any upstream package. The command plugin consumes `ctx.commands`, `ctx.tools`, `ctx.jobs`, `ctx.agentDefaultModel`, `ctx.llm`, `ctx.credentials`, and `ctx.skills`. It globally registers the simple `/leppy-loop` human surface, the durable `leppy_loop_control` tool, and the model-only, non-user-invocable `leppy-loop-operator` lifecycle skill. The `/leppy-loop` name is reserved exclusively for the Host command, so one `/leppy-loop` invocation mints a lifecycle permit before queuing one plugin-authored resolver turn. The permit is stored in Host memory until binding; each admitted transition appends an HMAC-chained immutable receipt under `git-common-dir` before `ctx.jobs.start`, then advances an HMAC-authenticated append-only per-run high-water anchor under Host-owned `DSH_HOME`, so a restarted Host can rehydrate same-session authority without trusting mutable `run.json`, coordinated local prefix rollback, or replaying a crash-consumed transition. The permit is bound to exact Agent identity and canonical repository, binds to its first run atomically, permits only one transition in flight, expires after 24 hours and carries one cumulative sixteen-transition budget epoch plus fixed iteration/repair bounds. Only a new direct-human command may append the next zero-consumption epoch after exact exhaustion; it holds the repository lock, proves no owner-fenced Host job is live, settles the signed worker lease, and persists the epoch before committing staged Host memory. It survives sequential controller jobs and, after run binding, Host restarts without crossing session/repository/run identity. Explicit local-only language permanently removes publication authority; otherwise the lifecycle may let the AI choose controller-owned branch/PR delivery from conversation context, never merge/deploy/scope widening. After a recoverable background result the Host can queue the next exact-state resolver turn without another slash command. Every existing-run resolver turn first calls read-only status; status returns the authenticated checklist/base and continue derives them when omitted; only absence of a live owner-fenced job permits one transition from those exact facts. The tool validates technical facts against the live authenticated controller, transfers each transition to `ctx.jobs`, and returns its job ID without waiting. Relative paths resolve from the receiving agent session's absolute `cwd`. The read-only `preflight` operation returns dry-run diagnostics before start or worktree creation. Canonical lint rejects extension fragments, brace/glob syntax, ambiguous inferred basenames, and required tests without test-capable write scope. The parser retains the canonical pipe grammar while folding indented legacy Markdown rows and role tags into the same typed representation; human checkpoints stall controller-side without a worker. A bounded tracked `.leppy-loop.json` instruction string is prepended to discovered repository instruction files. Cancellation reaches fetch, worker, and gate process trees; worktree creation and controller commits finish their short persistence-critical sections before cancellation is observed, so every mutation remains recoverable. The runner's optional `onProgress` sink emits a typed start and terminal update for each selected row, measuring elapsed milliseconds from that task attempt's start. A general `leppy-loop` background record is owned by the same Agent through the Harness job registry, which supplies status projection and cancellation; status selects that exact owner/repository-fenced live job first, reports durable `running` without such a job as `orphaned`, and otherwise selects the newest authenticated durable controller, while terminal stalls retain bounded diagnostic detail; the client adds a dedicated Stop action that submits the direct human `/leppy-loop stop` intent. Web composition maps each pair to one synthetic `command/run`/`command/done` lifecycle under a deterministic per-attempt ID. The package root also declares a browser bundle that registers the keyed `leppy-loop-task` command row; it combines the durable zero baseline with the command event time and ticks locally once per second until the terminal update arrives. `Running`, per-task attempt and elapsed duration are fixed-width siblings; only the task description elides. The durable global attempt remains the identity for leases, worker artifacts, receipts, events and command pairing. A separately persisted counter keyed by the checklist row index/phase/kind/raw digest supplies the human ordinal: sequential or durably split replacement rows begin at one, explicit recovery of the same row advances it, and an internal no-commit retry retains the same card and ordinal. Command lifecycle events are durable but model-invisible, preserving provider tool-call/result adjacency and avoiding per-tick Session writes or progress-token overhead. The default bundle is Host command/control plus one immutable packaged model-only skill whose name is distinct from every human command; workers keep skills disabled and receive their bounded protocol directly. The separately exported startup module remains available to explicit custom CLI compositions and claims process argv only when `--tasks` is present. Both entry points validate catalog membership through `ctx.llm.listModels(provider)` and exact reasoning capabilities through `ctx.llm.resolveModelInfo(provider, model)`. Each worker uses `@deepseek-ai/dsh-sdk-client` to launch the official stdio JSON-RPC runtime. Because the SDK may resolve `run()` after the underlying Agent emitted a terminal error, the adapter independently inspects terminal `turn/end` and streaming `finish` notifications and maps their failure into the typed worker outcome before commit validation. For verification/publication it requires one strict structured `LEPPY_OUTCOME`; ordinary task/closure reports degrade to advisory prose unless they explicitly declare `implementation-impossible`. Tool notifications feed a per-turn backpressure circuit (three identical failures or eight total) before the runner reconciles safe work or starts a fresh bounded worker. The private runtime mounts both the native DeepSeek adapter and the Harness `llm-pi-ai` multi-provider adapter; it receives the selected provider profile and reuses the Harness credential store, so the current default model route is preserved instead of forcing `DEEPSEEK_API_KEY`. Cordis and `dsh-tools` remain Host-shared peers so registrations and the parallel-call scheduler use the same service symbols inside an installed profile. Ordinary workers own ignored and generated state inside their isolated worktree. The controller neither snapshots nor quarantines worker ignored paths, and legacy `ActiveTaskAttempt` ignored-artifact fields are tolerated but ignored during recovery. Svelte validation caches are disposable and removed automatically, while other ignored files remain available across worker retries without lifecycle receipts. Legacy ignored-baseline admission remains readable only to upgrade already-persisted runs; it does not constrain worker recovery. The command prepares a digest of the normalized exact terminal plus full attempt identity in repository-locked HMAC state before lifecycle receipt and controller-job admission. Preparation binds the normalized request digest and target lifecycle epoch/transition and is idempotent across pre-job failures; an already-persisted target receipt is reused for job registration without a new transition, including at exhaustion. The runner requires the same option and prepared marker, then atomically promotes it to consumed before reconciliation. Only consumed state closes replay. The predecessor's exact terminal no-match detail proves `n <= 39`, where one capability transition can exhaust four removals in 92,170 candidates. Its canonical terminal admits one further promotion-aware transition: only paths added since the authenticated active-attempt base that remain ignored can augment the exact digest candidate set. That terminal admits one base-ignore transition for current ordinary untracked paths matched by byte-exact regular ignore blobs and strict binary path protocols from the authenticated base. After tracked and untracked base-ignore inference is exhausted, one final transition may use all current ordinary untracked paths only to reprove the exact baseline subset; unproven ordinary paths never enter quarantine and remain to fail the clean-tree gate. Base classification runs in a fresh Git dir with empty repository/global/system excludes, and one shared 512 MiB budget spans all proof classes per initial or stable collection. The base-ignore terminal admits one final transition that also classifies newly tracked paths under those base rules with rename detection disabled, covering an exact promotion that is no longer currently ignored; nonregular rules, checkout transforms and noncanonical path encodings reject. Wider state stays at three removals/10,000 candidates. UTF-8 fingerprint input is capped at 128 KiB, cumulative candidate serialization/hashing at 512 MiB, and file content at an independent streamed 512 MiB per discovery, reconciliation, move or retry phase. A missing receipt referenced by modern state fails closed. Recovery never terminates by reusable PID: the worker host must sign a real tri-state OS identity before spawning its child, and recovery advances only after definitive absence or a positively different identity. For `openai-codex`, the default adaptive policy chooses Terra/high for a fresh ordinary task and Sol/low for closures and recovery. Runtime outcomes without a model disposition receive up to three fresh workers in the same job, with the replacement global attempt persisted before spawn; direct interruption never retries. Before an ordinary task worker is admitted, embedded HMAC state binds task/checklist/base/attempt plus the ignored-path byte digest. After a turn, controller-observed Git invariants dominate report/validation/commit ceremony: repository-wide WIP is adopted regardless of declared paths, multiple or nonconventional commits are consolidated, ignored/generated state is non-blocking, and clean no-op work closes with a checklist-only commit. Authenticated legacy pending or interrupted commits are adopted directly without detached ordinary verification. Per-line metadata and explicit command options override policy fields independently. Other providers retain the Harness selection. Worker transcripts default to 8 MiB so OpenAI streaming chunks do not prematurely terminate recoverable work. Recovery receipts carry the authenticated run ID. Before adoption, exact recovery authenticates state and ownership, verifies the preserved branch/worktree, and parses the controller from that worktree rather than the receiving source checkout; the source branch may therefore have removed the checklist or contain unrelated dirty changes without weakening fresh-run source validation. A local phase gate may trigger up to three controller-owned repair cycles through the immediately preceding scoped closure. If it remains nonzero, the controller binds its receipt to the run/task/fingerprint/HEAD/checklist, commits it as advisory, and advances locally; ordinary recovery adopts matching HMAC-bound evidence without another execution, while pre-evidence legacy stalls rerun the unchanged gate exactly once with repair disabled. Before local or publication gates, pre-existing Svelte validation caches move through an HMAC-bound same-device transaction and the complete post-quarantine ignored baseline is signed before execution; an opaque gate remains behind a private permit until its PID/start identity is HMAC-bound, pre-spawn reservations are non-executable and recoverable, and Windows Job/Linux subreaper containment settles detached descendants before identity clearance or filesystem mutation, while other gate-host platforms fail closed before WIP movement or spawn; only attempt-generated replacements are discarded, and the original byte digest is restored in `finally` or at crash recovery. Every gate transaction additionally HMAC-binds its pre-gate HEAD, so restart recovery reattaches the authenticated branch, reverts Git, and discards attempt-generated ignored artifacts before restoring WIP; publication also binds and aborts its effective target rebase. Identity-only legacy migration strips both gate evidence and cache transactions rather than authenticating injected capabilities. Explicit `retry gate` and `repair gate` arguments still require direct exact-run capability. Dirty or moved worktrees, malformed evidence, branch/checklist drift, commits created by a gate, and unmerged state fail closed. One capability may repeat this transition only up to its controller-side repair-cycle bound (three), with a new worker/session/attempt and latest receipt each cycle; success exits immediately and all non-gate worker failures still settle normally. Direct `--repair-path` values may extend that one repair worker's commit scope to existing authenticated-worktree paths omitted by the original closure; they are canonicalized, persisted in repair state/events/instructions, carried into later resume receipts, and absent from the model tool. `leppy_exec` normalizes omitted or explicit-dot cwd to the repository root so generation and validation scripts can run there, while `leppy_commit` still validates every changed path against the effective scope. Every gate attempt increments the persisted count and creates a new receipt. When no selector is supplied, a sole stalled/interrupted run takes precedence over older failed artifacts. A completed run remains excluded from implicit recovery but can be continued explicitly by ID when a selective invocation left open rows in its preserved checklist. After selection returns no open row, the lifecycle resolver decides from the human conversation whether to remain local or use publication authority retained by the lifecycle permit; an explicit local-only permit rejects the private `publish` transition bit. The publisher first resolves matching fetch/push GitHub identity and reconciles one exact same-owner OPEN/MERGED PR at the current authenticated head without remote mutation. Otherwise it prunes and queries live remote refs, freezes exact target/head OIDs, and rebases onto the target OID rather than a tracking ref. A removed base is never guessed: `publicationTarget` is a private lifecycle argument and retarget succeeds only when a durable prior target commit is an ancestor of that live replacement. A newly granted retry authenticates and aborts any prior interrupted rebase before parsing the controller, so partial/manual resolutions never cross jobs. During one live job, each conflict exposes only Git's exact unmerged file paths to at most the grant-bound number of fresh Sol recovery workers. Conflict workers receive exact-path read/write/delete only: commit and exec tools are absent, while the controller freezes HEAD, authenticated rebase identity and the complete staged index. After an edit-only worker returns, the controller requires the same HEAD/index/unmerged set, rejects every out-of-scope or untracked edit, stages only the exact conflict paths, and continues the sequencer itself. Clean paths already staged by Git remain outside worker authority and are preserved in the replayed commit; an index-empty replay step is skipped controller-side, and every failed repair verifies rebase abort restored the authenticated branch, HEAD and clean tree. The final checklist gate returns its validated HEAD and receipt; the publisher then rechecks clean tree, unchanged HEAD, exact live base OID and unchanged remote branch OID. It updates an absent or previously controller-owned branch only with an exact expected-OID `force-with-lease`, verifies the remote result, re-lists PRs to absorb races, and creates through explicit `gh --repo` only if an exact PR still does not exist. Publication failure stalls only an explicitly requested publication with a deterministic recovery command; success persists the URL before the final completed event. The worker runtime never receives these capabilities. ## Control flow ```text source checkout (clean, tracked checklist) | v single fetch -> authoritative ref -> run branch + sibling worktree | v select first open literal match | task/closure | gate v v worker-host + fresh SDK session controller platform shell, once | | read-wide + write-scoped search/edit/argv/commit tools receipt + checklist commit | validate branch/commit/tree/checklist | controller marks checkbox and amends/commits ``` The worker-host is the process-tree ownership boundary. It writes a signed lease and launches the JSON-RPC runtime through `@deepseek-ai/dsh-subprocess-local`, whose handle terminates the complete child tree. SDK stdin/stdout are proxied without interpreting JSON-RPC. ## State and recovery Run state is atomically replaced and stored under `/leppy-loop/runs/` unless overridden. Ownership is HMAC-bound to run, repository, checklist, branch, and worktree. Lifecycle authority is separate: an immutable HMAC required-marker distinguishes modern authority from genuine legacy state; numbered receipts HMAC-bind the complete authority, prior digest, run and sequence; and an atomically replaced HMAC head anchors the required tail. Admission advances head+receipt before a job ID, local-only reauthorization persists a same-transition one-way downgrade before followup/ack, and direct-human Stop persists revocation before kill/ack. Missing or corrupt modern marker, head, or chain quarantines the controller. Worker leases additionally bind PID, process-start identity, task, attempt, and heartbeat. Recovery requires a unique valid ownership proof and matching Git facts. Human continuation additionally freezes an authority digest over controller bytes, source/base/worktree identity, current task/global-attempt state, per-row attempt map, gate attempts, lifecycle authority, and failure-circuit state. The global tool re-inspects exact facts before consuming a grant; only same-session persisted authority may hydrate after restart. State must remain outside the worktree. Otherwise leases, sessions, and transcripts would pollute the worker tree and correctly fail the scoped commit validator. ## Git transaction Ordinary task/closure reports, validation, and commit ceremony are advisory. The controller checks complete porcelain state, expected branch, unchanged checklist, exact scope, and absence of unmerged entries; it restores out-of-scope side effects, adopts in-scope WIP, and consolidates commits before writing `[x]`. Only explicit `implementation-impossible` grants worker prose stop authority. Gates and publication paths retain strict receipts and validation. The official sandbox has one writable root. A Git linked worktree stores commit metadata in a separate `git-common-dir`, so a normal sandboxed `git commit` cannot work without widening the writable root beyond the worktree. `leppy_commit` remains an optional narrow bridge: it inspects changed names, rejects anything outside allowed real paths, stages only allowed scopes, and runs exact Git argv with a scrubbed environment. Omission or noncanonical commit ceremony is normalized by the controller after the worker turn. Ordinary reads may inspect the worktree except the controller; writes remain scoped. `leppy_search` and `leppy_edit` avoid shell/patch dependence, worker Git verbs use a positive read-only allowlist, and PowerShell is permitted only as repo-local `-File` execution. ## Public API - `runLeppyLoop(options, dependencies)` - `executeLeppyLoopCommand(ctx, invocation, runtime)` - `executeLeppyLoopControl(ctx, runtime, agent, args)` - `inspectAuthenticatedControllers(cwd)` and `selectControllerForHumanIntent(runs)` - `HumanGrantStore` - `parseLeppyLoopCommandInput(input)` - `parseChecklist(sourceOrPath, path?)` - `lintChecklist(parsed, options?)` - `HarnessWorkerAdapter` - `LeppyLoopOptions`, `RunResult`, `RunPreview`, `RunEvent` The dependency seam permits deterministic fake-worker tests without weakening the production adapter.