# Architecture and package ownership

zelk is a library with a durable reducer and replaceable I/O adapters. Packages
group behavior by responsibility. A file split alone does not establish an
ownership boundary: a reusable subsystem receives explicit facts and capabilities,
not a pointer to the whole agent or reducer state.

## Implemented structure

The repository is a Go workspace (`go.work`) of separate modules. The library
is the `core` module, `github.com/barevoidco/zelk/core`, whose root package is
named `zelk`. Package paths in the rest of this document are relative to
`core/`.

```text
go.work                      The workspace: every module below
core/                        Module github.com/barevoidco/zelk/core: the library
cmd/zelk/                    Separate module: the zelk command (terminal UI, print mode, subcommands)
adapters/otel/               Separate module: the OpenTelemetry observer adapter
examples/                    Separate module for embedding examples
eval/                        Separate module for evaluation tooling
tools/                       Pinned lint and vulnerability tools (outside the workspace)
```

Inside `core/`:

```text
zelk                         Public API: the agent, sessions and executions
  agent.go                   Construction and resource ownership
  config.go                  Configuration validation and defaults
  options.go                 Host options
  tools.go                   Ordered tool composition and tool ceiling
  session.go                 Session startup, lease lifetime and Send-or-Start
  session_config.go          Recorded session configuration
  execution.go               Execution handles and results
  lifecycle.go               Agent shutdown and active execution ownership
  commands.go                Command construction and acknowledgments
  subscribe.go               Durable subscription notifications
  updates.go                 Live updates: deltas, child updates and lag markers
  read.go                    Read-only session events, status and history
  cost.go                    Pricing the usage Status reports
  processes.go               Host access to background processes
  model.go                   Model switches and listing
  output.go                  Structured output contract and records
  typed.go                   Typed structured output: RunSchema, RunTyped, WaitTyped
  mcp.go                     MCP server connections and their tools
  observe.go                 Observer option
  subagents.go               Child-session composition and forwarding
  acp.go                     Adapter from Agent to the ACP server's interface
  run.go                     Zero-config entry point; sole environment reader
  example_test.go            Runnable public examples

Public, externally importable components, beside the root package:
event/                       Durable records and commands
history/                     Portable conversation envelope
loop/                        State, event ordering, effects and replay
driver/                      Authority, dispatch, recovery and persistence
tool/                        Custom tool definitions and execution contracts
provider/                    Provider contract, adapters and private SSE framing
env/                         Workspace/process contract, local implementation and launchers
store/                       Log/blob contract, implementations and conformance kit
lease/                       Authority contract, implementations and conformance kit
secret/                      Credential documents in a locked file or a host's keychain, and a vault kit
permission/ hook/ preset/    Host-facing permission, hook and preset definitions
mcp/                         MCP client: stdio through an environment, streamable HTTP
observe/                     Neutral observer seam for spans and metrics
acp/                         ACP server over any io.ReadWriteCloser
present/                     Calls and approval choices described for people (shared by hosts)
transcript/                  A session's log read as the conversation a person sees (reader view)
skill/ subagent/             Host-facing feature definitions
fetch/ search/ blob/         Host-facing capability contracts
memory/                      Cross-conversation memory: notes, Store contract, file and mem stores, conformance kit
uuid/                        Version 7 UUIDs (RFC 9562) for new session IDs
testkit/                     Shared scripted servers and crash checkers (tests only)

internal/
  completion/                Pure evidence freshness and completion decisions
  compact/                   Context sizing, retention and compaction planning
  accounting/                Reservation, settlement and allocation arithmetic
  delegation/                Child lifecycle, collection and report rendering
  process/                   Foreground command execution and output presentation
  instructions/              Scoped project guidance discovery
  workspace/                 Model-facing lexical path mapping
  textbound/                 UTF-8 byte bounds shared by output producers
  bashparse/                 Advisory shell segmentation and read-only command allowlist
  classifier/                Auto-mode classifier: policy, prompt framing, strict verdicts
  pathjail/                  openat2/os.Root path resolution beneath the workspace
  jsonrpc/                   JSON-RPC 2.0 over newline-delimited streams (ACP, MCP)
  permission/                The deterministic action decision algorithm
  hook/                      Registered hook execution and wire-result validation
  preset/                    Validation of the guarantees host presets make
  requirements/              Requirement ownership transitions, folded without I/O
  toolcall/                  Driver-created call state and durable tool observations
  gitinput/                  A workspace's git layout and the inputs git runs with
  glob/ ignore/              Path globbing, and which paths a workspace walk skips
  frontmatter/               The YAML subset of skill and subagent definitions
  contract/                  Checks of the source against the embedding contract (tests)
  builtin/
    files/                   Workspace tools, media and diffs
    shell/                   Bash and background process ownership
    verify/                  Check execution and evidence capture
    web/                     Fetch/search adapters and private HTML conversion
    skills/                  Skill loading and bundle capture
    control/                 Input, outcome and todo tools
    output/                  StructuredOutput tool and host validators
  prompt/                    Prompt assets and assembly
  schema/                    Tool schema generation and validation
```

The agent, its sessions and executions are declared in the root package itself,
so `go doc` and pkg.go.dev show their methods and fields. Hosts import the root
package as `zelk "github.com/barevoidco/zelk/core"` and components as
`github.com/barevoidco/zelk/core/<component>`.
This document describes existing code.

## Dependency direction

```mermaid
flowchart TD
    agent[zelk: agent, sessions, executions] --> driver
    agent --> tools[Built-in tool adapters]
    driver --> loop
    loop --> completion[Pure completion policy]
    loop --> compact[Pure compaction policy]
    loop --> accounting[Pure accounting policy]
    agent --> delegation[Child lifecycle and reports]
    tools --> process[Command execution]
    tools --> instructions[Scoped instructions]
    tools --> workspace[Workspace paths]
    verify[Verify adapter] --> completion
    driver --> ports[Provider, environment, store and lease contracts]
    process --> ports
```

- `loop` owns durable state, event ordering, version compatibility and effects.
  Pure policies return decisions; the reducer records and applies them.
- `driver` owns supervised log adoption, lazy initialization, I/O sequencing, cancellation, fencing, concurrency and append
  outcomes. It does not recreate completion policy.
- The root package's configuration and composition translate host options into explicit
  dependencies. They preserve tool descriptor order and recorded configuration.
- Tool families never import one another in production. Shared behavior gets a
  narrowly named capability package. Tool-specific options stay in their family.
- Private capabilities never import the root package, `loop`, `driver` or tool
  adapters. Completion, compaction and accounting policies have explicit pure
  dependency allowlists.
- `blob`, `history` and `event` form the durable data layer; local imports stay
  within their own/lower data layers rather than acquiring runtime services.
- Provider and environment implementations remain independent of one another.

`internal/contract` checks the tool/capability boundaries across production source,
including platform-specific files. Existing contract checks enforce process,
environment, approved-dependency and adapter import rules. Tests may integrate
multiple adapters without making those dependencies part of production code.

## Where changes belong

| Change | Owner |
|---|---|
| New host option | Root package: option, validation and composition |
| New persisted fact or command | `event`, then its fold in `loop` |
| Child limits, ownership, collection and report rendering | `internal/delegation` |
| Budget limits, settlement and allocation arithmetic | `internal/accounting` |
| Context sizing, retention, cuts and summary acceptance | `internal/compact` |
| Completion verdict or evidence freshness | `internal/completion` |
| Ordering a completion check with its causal records | `loop` |
| Dispatch, cancellation or append handling | `driver` |
| Command wrapper, cleanup or bounded output presentation | `internal/process` |
| Bash argument handling or background process handles | `internal/builtin/shell` |
| Check selection or evidence construction | `internal/builtin/verify` |
| Instruction fallback, ancestry or reload rules | `internal/instructions` |
| Path mapping shared by tools | `internal/workspace` |
| Provider wire-format behavior | Corresponding `provider` adapter |

## Verification

`make check` runs formatting, vet across supported tags, pinned lint, race tests
with the integration tag (which hold every test: no file is built only without
it), no-cgo builds and vulnerability checks in every source
module. Generated evaluation results are artifacts and are excluded from source
discovery. Targeted unit tests and existing replay fixtures establish behavior
before extraction; full checks validate each completed increment.

## Private ownership and test infrastructure

Provider streaming framing lives in `provider/internal/sse`, accessible only
within provider packages. HTML conversion belongs to the WebFetch adapter in
`internal/builtin/web/internal/htmlmd`; it is not part of the fetch port.
Shared scripted servers and crash checkers live in `testkit/` and are
used only by tests. Shared production capabilities stay in `internal/` when
multiple independent callers need them.

## Runtime source organization

Agent startup, shutdown, configuration, commands and subscriptions have distinct
files in the root package. Driver construction, driving, log loading, atomic
recording, dispatch, provider attempts and recovery likewise have distinct files
within `driver`. Reducer sequencing stays in `step.go`; command folds, attempt
transitions, model turns, tool waves, run endings and copy isolation each have
named files in `loop`. These splits preserve declaration tokens and ownership;
they do not introduce new package boundaries or alter the durable protocol.

## Agent–driver boundary

The agent supplies the resolved configuration and owns host-facing execution
handles, child/process cleanup and lease release. `Driver.Ensure` owns supervised
adoption and lazy initialization; existing logs do not resolve configuration
again. `Begin` remains the explicit initialization primitive for custom hosts.
Startup failure closes the tracked execution and releases its authority; the
driver preserves persistence and authority errors rather than the agent rebuilding
them. Provider capability discovery stays in host configuration/model resolution.
Executions receive only log reading for subscriptions; the driver's log adapter
receives only its log port and a notification callback. The agent's execution
registry owns session lookup, so neither adapter retains a whole-agent reference.

Agent result projection and the read-only wake query deliberately use reducer
state. They do not schedule effects or append derived records. Moving them behind
another forwarding API would not reduce state ownership or improve that boundary.

## Public extension boundaries

[Embedding and extension boundaries](/internals/embedding/) records the public API
audit. Public components remain independently usable: they cannot import the
root package or private tool composition. Shared private policies and codecs
remain valid dependencies. Core import checks exercise allowed and forbidden
edges; the testkit source check additionally covers nested eval/examples modules.


## Pre-polish harness features

The root facade's `Catalog` composes a `store.LogStore` and `lease.Lease` for
provider-free metadata mutations. Tags and deletion tombstones are commands
in the original log; `store.Catalog` supplies summaries and omits tombstones.
A deleted session is then removed whole, and `Catalog.Cleanup` removes
sessions idle too long ([retention](/internals/retention/)).

The reducer resolves deferred `CallTool` wrappers before target authorization;
its `ToolSearch` reads recorded specifications. The provider-visible schema
selection remains fixed. The driver persists opaque workspace baselines and
calls the optional `env.Differ`; `env/local` implements bounded hash captures,
and `transcript` renders observed changes separately from tool attribution.

`env/egress` owns destination checks, DNS pinning and HTTP/CONNECT forwarding.
`env/launcher` owns the Linux namespace relay and command seccomp profile.
`cmd/zelk/internal/host` owns broker listeners, helper dispatch and lifecycle, and
wires explicit MCP configuration for both hosts. The core broker never discovers
host settings or starts its own server. macOS allowlists remain rejected until
an equivalent confinement proof exists.
