# Source ownership

[Contributing](../CONTRIBUTING.md) · [Interactive architecture map](architecture.html)

Every production file under `src/` belongs to exactly one of twelve owners. An owner is a top-level
directory with one responsibility and a fixed list of other owners it may import.
`npm run lint:dependencies` enforces that list; reviewers judge whether a concept sits with the
right owner.

## Owners

| Owner              | Responsibility                                                                                      |
| ------------------ | --------------------------------------------------------------------------------------------------- |
| `src/domain/`      | Run and slice state, business rules and transitions, metrics data and business failures.            |
| `src/failures/`    | Failure messages, panic unwrapping and retry of `Result`s.                                          |
| `src/ports/`       | Contracts for external capabilities, their portable data and their failures.                        |
| `src/config/`      | Configuration and environment schemas, defaults, provider and model policy, presets and precedence. |
| `src/flow/`        | Flow contracts, the engine that runs a supplied flow, and the step retry policy.                    |
| `src/prompts/`     | The text jig sends to its agents.                                                                   |
| `src/steps/`       | Individual workflow steps, which act through ports.                                                 |
| `src/observers/`   | Event subscriptions: logging, tracing and metric records.                                           |
| `src/adapters/`    | Git, GitHub, sandbox containers, images, storage, config files, terminals, logging and telemetry.   |
| `src/app/`         | The public operations, their preparation, resource lifetimes and the assembly of jig's workflow.    |
| `src/cli/`         | Command declarations, input parsing, result formatting and exit codes.                              |
| `src/composition/` | The `jig` executable: chooses implementations, builds them, connects observers and starts the CLI.  |

Which owners each owner may import is `allowedOwners` in
[`.dependency-cruiser.mjs`](../.dependency-cruiser.mjs), checked by one
`<owner>-imports-only-allowed-owners` rule per owner; read it there. A file under any other
directory of `src/` fails as unowned.

## What dependency lint enforces

- Every production file is scanned, disconnected files included. Value, type-only, re-export and
  literal dynamic imports all count, through nested paths.
- Owners form no cycle, including cycles through erased type imports. Files form no runtime cycle;
  a cycle within one owner that only a type import closes passes.
- Only composition imports CLI. Only CLI and composition import app.
- Outside app and composition, specs included, app is reached only through `src/app/api.ts`.
  App specs may import adapters and composition wiring. Specs and tooling outside `src/` may import
  CLI helpers, and tooling outside `src/` may import any app module.
- Production config imports no package but `better-result` and `zod`: files, paths, processes, the
  home directory and the environment belong to adapters and the process edge. Config specs are
  exempt.
- Production app imports no package but `better-result`, `zod` and `node:crypto`: it reaches Git,
  files, processes, containers and the terminal through a capability an adapter implements, so no
  type of an infrastructure package reaches `src/app/api.ts`. App specs are exempt.
- Production failures imports no package but `better-result` and Node built-ins.
- Only adapters, observers and composition import Pino or OpenTelemetry; every other owner reports
  through the logs and telemetry ports.
- Production code imports no spec, no development dependency and nothing unresolvable.

Specs are checked in a separate pass against the public-entry rule only. Run the check alone with
`npm run validate -- lint:dependencies`.

## Composition and the CLI

`src/composition/main.ts` is the executable. `buildJigCli()` adds the GitHub commands to the core
CLI, bound to the same operations, and the module parses arguments only when it is the invoked
script, compared by real path so an installed symlink works. Importing it starts nothing. Every
operation releases what it built before its command resolves; only then is the output flushed and
the process ended.

Composition only wires. It captures the process environment, working directory and home directory
for every command, chooses implementations, builds them with explicit factories and attaches
observers. jig uses no dependency-injection container. Policy — retry counts, which failures are
transient, resume, locking, required stores, credential consent, publication — belongs to app,
domain, config or a port contract, even when composition installs the implementation.

A command handler in `src/cli/commands/` receives the bound operations as `JigOperations`, parses
its input once, calls one operation, formats the result and sets the exit code. It never receives a
runtime factory, builds adapters, loads config, probes Git or opens a scope. Help and version start
no application resources.

## Application operations

`src/app/api.ts` is the application's public entry. Its operations check the repository and read
the settings they need themselves, so a caller other than the CLI repeats nothing.
Reviewers check that every operation it exposes takes and returns only domain types, portable port
types and the configuration types a caller needs, such as a preset and its name schema — no runtime
factory, concrete store, Pino logger, OpenTelemetry tracer, Commander command, Node process or
environment object, or terminal adapter — including types reached through an alias or inferred from
a concrete factory. Dependency lint keeps app off adapters, observers, the CLI and infrastructure
packages; which configuration types the entry exposes is the reviewer's call. The CLI reaches
configuration types only through this entry, never by importing `src/config/`.
`prepareRepository` in `src/app/repository-preparation.ts` decides the order: repository root,
environment, saved credentials, config, preset directories.

- **Status and presets.** `readRunStatus` and `listPresets` take the context composition captured
  and narrow capabilities. Status reads metrics and documents through `RunRecords` in
  `src/ports/run-records.ts`, implemented by `src/adapters/local-store/local-run-records.ts`.
- **Run.** The handler in `src/cli/commands/run.ts` reads the request file or standard input
  through the `RequestInputs` it is given, so unusable input calls no operation. `startOrResumeRun`
  prepares the repository, applies the preset (nobody picking refuses the run) and only then asks
  the supplied `openRuntime` for the run's capabilities. `runJig` in `src/app/run-jig.ts` owns the
  run policy: the lock, which stores to open (`openRunStore` in `src/app/run-stores.ts` adds
  required stores to the configured ones), start or resume by id, the ended-run report, credentials
  and image before any sandbox, and the invocation's records. `src/app/run-flow.ts` assembles the
  workflow the engine in `src/flow/engine.ts` runs.
- **Init and build.** `initRepository` and `buildSandboxImage` prepare the repository first
  (`build` then applies the preset; cancelling the pick builds nothing) and only then ask the
  supplied `openSandboxRuntime` for a `SandboxRuntime`. Init decides when to ask for agents, for a
  missing credential and whether to save it, through the `InitInteraction` composition supplies
  from `src/adapters/terminal/`; the starter files sit behind `StarterFiles` in
  `src/ports/starter-files.ts`, and agent credentials and the owner-only `.jig/.env` behind
  `AgentCredentials`. Agents run only on a session `withThrowawaySandbox` opens on its
  own branch, closes and removes. `ensureSandboxImage` in `src/app/sandbox-image.ts` decides what to
  rebuild over the `SandboxImageRecipe` and `SandboxImages` ports in `src/ports/sandbox-images.ts`;
  `src/adapters/sandbox-image/repository-image-recipe.ts` reads the Dockerfile, the host user, the
  agents' packages, the image names and the labels. `sandboxRuntimeFactory` in
  `src/composition/sandbox-runtime.ts` builds the runtime.
- **GitHub issues.** `implementGithubIssue` in `src/app/implement-issue.ts` validates the token and
  repository through `src/config/github-settings.ts` before the origin is read or anything is
  prepared. It then gets its run through `withPreparedRun` in `src/app/run-operation.ts`, the same
  preparation, preset selection, runtime and release `jig run` uses, runs the accepted issue through
  `runJig` with the remote store required and its code held back, and publishes the outcome. Its
  GitHub API (`src/ports/github.ts`) and guarded run branches (`src/ports/run-branches.ts`) arrive
  as capabilities, and `src/adapters/git/github-origin.ts` reads the repository name from the
  origin. Composition supplies them lazily so help needs no token or repository.

### Resource lifetimes

`withResource`, `releaseInOrder` and `releasingOnPanic` in `src/app/lifecycle.ts` acquire, use and
release. Every release is attempted; a partial acquisition releases what it already holds, even
when it panics. A cleanup failure after successful work is the result; after failed work it is
logged and the work's failure is kept (`reportCleanup` in `src/app/report-cleanup.ts`). The first
panic propagates as thrown.

A run releases its sandbox session, then its scope, then telemetry, then the lock.
`runRuntimeFactory` in `src/composition/run-runtime.ts` constructs the adapters; opening a runtime
opens no sandbox, image or run log. `acquireRunScope` in `src/app/run-scope.ts` decides the order
over the parts composition supplies: the run's reporting (wired in
`src/composition/observed-events.ts`), the sandbox start retried under `transientRetryPolicy`, the
workspace, and the `EngineDependencies` built from them. Each run gets its own events, metrics and
workspace; the console log is shared, and a run's log file stays open for the life of the process.

Stores are built by `src/adapters/run-store/repository-run-stores.ts` behind `RunStoreCatalog` in
`src/ports/run-store.ts`, which also loads and checks a custom store module.

### GitHub publication

Publication keeps its shared receipts and leases in `refs/jig/_orchestration`. Domain owns their
state, schema and transitions (`src/domain/orchestration.ts`) and the repository identity
(`src/domain/repository-identity.ts`). `src/ports/publication-receipts.ts` declares the receipt
store, publication ownership and their failures; `src/adapters/git/orchestration-ref.ts` persists
them. `withPublicationOwnership` in `src/app/publication-ownership.ts` claims the lease, renews it
before each outward effect and releases it however the work ends. The run-branch adapter
`src/adapters/git/run-branches.ts` enforces the protected-path refusal from
`src/domain/protected-paths.ts`.

## Configuration and defaults

Config owns configurable defaults; domain owns business rules. Settings cross the `ConfigSource`
contract in `src/config/config-source.ts`: config decides absence, schema, defaults and update
merging, and `src/adapters/filesystem/config-source.ts` resolves the file and moves its raw JSON.
Presets cross `PresetSource` in `src/config/preset-source.ts`:
`src/adapters/filesystem/preset-source.ts` orders the preset directories and yields candidates
lazily, while config skips invalid names, lets the first candidate of a name win, validates it and
merges whole roles. Presets override role configurations only.

The step retry count and delay are config defaults in `src/config/load-config.ts`, which
`runSettingsFrom` resolves into `RunSettings`. Domain owns `RunSettings` and the rules that read it,
such as `reviewCapReached`, and genuine safety caps such as `HOOK_FAILURE_CAP` in
`src/domain/settings.ts`. A numeric constant is not by itself a setting.

## Failures

Each failure class lives with the owner of what it means to callers:

| Failure                                              | Owner                                                                                                                           |
| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| Business conditions, `FailureKind` and `isTransient` | `src/domain/errors.ts`                                                                                                          |
| Capability failures                                  | the port that declares them, such as `src/ports/github.ts`, `src/ports/run-branches.ts` and `src/ports/publication-receipts.ts` |
| Shared Git, run-state and local-state failures       | `src/ports/git-failures.ts`, `src/ports/run-state-failures.ts`, `src/ports/local-state.ts`                                      |
| Configuration validation                             | `src/config/errors.ts`                                                                                                          |
| Use-case failures                                    | `src/app/`, reached through `src/app/api.ts` outside app and composition                                                        |
| Command input failures                               | `src/cli/`                                                                                                                      |

Import a class from its owner; no module re-exports another's and there is no union of every class.
A class a step or a sandbox start can fail with carries a literal `kind`; no other class does.

`src/failures/` holds no failure class. It presents a failure (`messageOf`), unwraps a panic to its
original cause (`rootCause`) and retries an operation that returns a `Result` (`retryResult` and its
`RetryPolicy`). Callers import these functions directly. Flow makes the step retry decision, so
`transientRetryPolicy` in `src/flow/retry-policy.ts` builds the step `RetryPolicy` from the resolved
`RunSettings` and `isTransient`.

## Placing new code

Put a concept with the owner whose responsibility it is, even when another owner calls it most.
When a placement is borderline, decide from what the concept means to its callers:

- **domain** keeps what a run, a slice or a publication is and the rules over them, including a
  cap that stops a run such as `HOOK_FAILURE_CAP` and identity several capabilities share such as
  `RepositoryIdentity`. A value an operator could choose is a config default, and a failure many
  modules return still belongs to the port whose capability fails.
- **failures** keeps presenting, unwrapping and retrying failures and nothing else. It is not a
  home for shared utilities: a new helper goes with the rule it expresses, and a failure class
  goes with its owner.
- **ports** keeps what jig asks of the outside world: the contract, its portable data and its
  failures, without raw library details. Plain report data an operation returns belongs in a port
  contract, so app does not import an observer to expose it. A type only one adapter uses stays in
  that adapter.
- **config** keeps schemas, defaults, provider and model policy, precedence and preset selection.
  Reading a file, a directory, the environment or the home directory belongs to an adapter or the
  process edge; config receives raw values. Its failures are configuration-validation failures
  unless a capability contract shares them, in which case they belong to that port.
- **flow** keeps how any supplied flow runs and when a step is retried. Anything that names a
  concrete step or the order of jig's steps belongs to `src/app/run-flow.ts` or `src/steps/`.
- **prompts** keeps the text an agent reads, built from domain data. When a prompt is sent and how
  its reply is parsed belong to the step that sends it; an issue comment or other text for a
  person belongs to app, such as `src/app/publication-content.ts`.
- **steps** keeps one workflow operation that acts through ports and returns its outcome. Choosing
  between steps belongs to app's workflow assembly, and a library call belongs to an adapter behind
  a port.
- **observers** keeps reactions to events: logs, traces and metric records. An observer never
  decides a run's outcome; an ordinary observer exception is reported and the other observers are
  still notified, while a panic propagates.
- **adapters** implements a port over a library, file, process or container and turns its throws
  into the port's failures. Where to look belongs here — the order of preset directories, the
  settings file path — while what counts as valid, required or retried belongs to config, app or
  domain.
- **app** keeps use cases: what an operation requires and in which order it prepares, acquires and
  releases, use-case failures and the assembly of jig's workflow. When it needs Git, a file or a
  container, it asks through a port.
- **cli** keeps parsing input once, formatting results, setting exit codes and command input
  failures. A check every caller of an operation needs belongs inside that operation, not in the
  handler.
- **composition** chooses implementations, builds them and connects observers. Retry, resume,
  locking, required stores, credential consent and publication are decided by app, domain, config
  or a port contract, even when composition installs the implementation.

A new owner, or a new edge between owners, changes `allowedOwners` and this guide together. A pull
request that decides where something lives names the owner in one line and links the issue that
carries the reasoning.
