# Solution Architecture

Date: 2026-05-27
Status: Formal V1 architecture derived from AirCoding Architecture Baseline V1

## 1. Overview

AirCoding is a self-owned local AI coding agent/runtime. It is not a Claude Code plugin wrapper. The product provides a Claude Code-quality execution layer, OpenCode/OpenTUI-inspired terminal UI, project-local session persistence, multi-agent orchestration, and language/toolchain capability packages.

The V1 architecture is Linux-first, TypeScript/Bun-based, event-driven, and project-local by default. C++ is the first deep language profile, while the runtime remains language-agnostic through `toolchain-*` capability packages.

Core value path:

```text
User requirement
  → Main Agent clarification and routing
  → Architecture Designer for design/interface decisions
  → Scheduler task graph and wave planning
  → Executor/Reviewer/Debugger/Compactor/ExperienceMiner workers
  → ToolRegistry + PermissionEngine + EventStore
  → project-local DB/artifacts/evidence
  → TUI/HUD ProjectionStore
```

## 2. Architecture Sources of Truth

This document summarizes the formal architecture. Detailed V1 baselines remain authoritative for implementation contracts.

Precedence rule:

1. `interface-contracts-v1.md` wins for TypeScript public interface shape.
2. `db-schema-v1.md` wins for SQLite persistence shape.
3. `event-registry-v1.md` wins for event names and payloads.
4. `tool-registry-v1.md` wins for tool names and tool I/O schemas.
5. `runtime-semantics-v1.md` wins for cross-cutting runtime behavior.
6. `c4/module.md` and `c4/code-view.md` win for package/component boundaries.
7. ADR files win for accepted design decisions they explicitly cover.
8. `baselineV1.md` remains the narrative baseline and decision index.

| Area | Source |
|---|---|
| Overall baseline | `AirPlan/docs/architecture/baselineV1.md` |
| Interface contracts | `AirPlan/docs/architecture/interface-contracts-v1.md` |
| Runtime semantics | `AirPlan/docs/architecture/runtime-semantics-v1.md` |
| C4/module/code view | `AirPlan/docs/architecture/c4/module.md`, `AirPlan/docs/architecture/c4/code-view.md` |
| DB schema | `AirPlan/docs/architecture/db-schema-v1.md` |
| Event registry | `AirPlan/docs/architecture/event-registry-v1.md` |
| Tool registry | `AirPlan/docs/architecture/tool-registry-v1.md` |
| Scheduler state machine | `AirPlan/docs/architecture/scheduler-state-machine-v1.md` |
| Prompt layering | `AirPlan/docs/architecture/prompt-layering-v1.md` |
| Provider matrix | `AirPlan/docs/architecture/provider-capability-matrix-v1.md` |
| Error taxonomy | `AirPlan/docs/architecture/error-taxonomy-v1.md` |
| Artifact naming | `AirPlan/docs/architecture/artifact-naming-v1.md` |
| Scope escalation | `AirPlan/docs/architecture/scope-escalation-v1.md` |
| Security model | `AirPlan/docs/architecture/security-model-v1.md` |
| Capability trust | `AirPlan/docs/architecture/capability-trust-v1.md` |
| Platform matrix | `AirPlan/docs/architecture/cross-platform-matrix-v1.md` |

## 3. Architectural Principles

1. **Execution quality follows Claude Code.** File edits are read-before-edit, exact, conservative, small, and verified before completion.
2. **OpenCode is a UI/runtime reference, not a business-state dependency.** Reuse visual patterns and OpenTUI/Solid primitives, not OpenCode's session/sync state model.
3. **Project-local source of truth.** Session state, artifacts, backups, and project rules live under project `.air/`.
4. **Events drive live behavior; SQLite drives recovery.** EventBus is live transport; domain tables and durable events are the source of truth.
5. **Workers are isolated child processes.** Executor, Reviewer, Debugger, Compactor, and ExperienceMiner run as independent Bun processes over NDJSON IPC.
6. **Main Agent remains responsive.** Long-running background work is delegated to Scheduler/workers.
7. **Architecture changes are explicit.** Implementation-only changes may continue silently; interface/architecture/product changes route through Architecture Designer and/or user confirmation.
8. **Tool/capability boundaries are permissioned.** Built-in and future plugin tools all pass through ToolRegistry and PermissionEngine.
9. **Provider boundary is isolated.** Internal messages are Anthropic canonical; adapters convert at provider boundary.
10. **Evidence is first-class.** Build/test/debug/review outputs become artifacts and evidence refs before completion claims.

## 4. Major Containers

### CLI Container

Package: `packages/cli`

Responsibilities:

- command entrypoint
- startup and first-run initialization
- Doctor invocation
- project discovery and `.air` initialization
- resource loading
- TUI/runtime bootstrap

Interfaces:

- CLI commands
- local filesystem
- runtime service initialization

### TUI/HUD Container

Package: `packages/tui`

Responsibilities:

- OpenTUI/Solid user interface
- Main Agent conversation surface
- progress, task, agent, diff, and evidence display
- permission prompts and blocker reports
- HUD/statusline projection

Interfaces:

- ProjectionStore read API
- Main Agent UI channel
- Permission prompt UI

Constraints:

- TUI consumes ProjectionStore only.
- TUI does not query SQLite or EventBus directly.
- TUI does not own scheduling state.

### Runtime Container

Package: `packages/runtime`

Responsibilities:

- Main Agent orchestration shell
- Architecture Designer integration
- Scheduler
- child process management
- EventBus and EventStore
- SessionStore/domain repositories
- ToolRegistry
- PermissionEngine
- CapabilityRegistry
- ContextAssembler
- ArtifactStore and EvidenceStore
- ProjectionStore producer side

Interfaces:

- `packages/contracts`
- `packages/llm`
- `packages/toolchain-*`
- SQLite
- project filesystem
- child process stdio IPC

### LLM Container

Package: `packages/llm`

Responsibilities:

- provider configuration
- provider adapters
- Anthropic canonical message handling
- OpenAI/OpenRouter/ollama/custom endpoint conversion
- capability matrix validation
- streaming/tool-use conversion
- token counting hooks where available

Interfaces:

- ProviderAdapter API
- ProviderCapabilityMatrix
- runtime LLM request API

### Toolchain C++ Container

Package: `packages/toolchain-cpp`

Responsibilities:

- C++ project detection
- CMake configure/build orchestration
- Ninja-first, Make fallback strategy
- CTest/GoogleTest execution
- cppcheck static analysis
- clangd CLI queries
- compiler/linker diagnostic parsing
- build/test/debug evidence production

Interfaces:

- Capability manifest
- ToolRegistry tools under `cpp.*`
- shell command runner
- diagnostics/artifacts/evidence stores

### Contracts Container

Package: `packages/contracts`

Responsibilities:

- compileable shared TypeScript interfaces
- RuntimeEvent, TaskSpec, WorkerResult, ToolDefinition, ArtifactRef, EvidenceRef
- error, provider, project, IPC, UI types

Dependency rule:

- All packages may depend on `contracts`.
- `contracts` must not depend on domain implementation packages.

## 5. Runtime Agents

### Main Agent

User-facing coordinator. It handles conversation, progress summaries, requirement changes, direct foreground tasks, and escalation presentation. It does not perform long-running background work.

### Architecture Designer

Owns architecture planning, impact assessment, ADR/C4/plan/todo alignment, and design/interface change review. It may edit planning/architecture documents, not implementation code.

### Scheduler

Owns TaskGraph loading, wave planning, dependency handling, write-area conflict handling, retry strategy, child worker dispatch, heartbeat monitoring, merge coordination, and restart recovery.

### Executor

Performs scoped implementation/build/test tasks with Claude Code-style execution discipline and structured WorkerResult output.

### Reviewer

Read-only reviewer for correctness, security, scope control, architecture compliance, and evidence sufficiency. It produces review reports and follow-up tasks.

### Debugger

Diagnoses failures using logs, diagnostics, artifacts, command output, GUI/network evidence, and may fix only within assigned write scope.

### Compactor

Performs copy-on-write context compaction. It produces summaries while preserving original messages for explicit backtracking.

### ExperienceMiner

Extracts project rules, skill candidates, and debug knowledge from verified repeated patterns and evidence.

## 6. Data Architecture

Project layout:

```text
<project>/.air/
  shared/
    project.json
    permissions.yaml
    compaction-rules.md
    rules/
    plan/
  local/
    sessions/<session-id>/
      session.db
      artifacts/
    backups/
    debug-records.db
    learned-memory.db
    workspaces/
    tmp/
    locks/
```

Session DB path:

```text
<project>/.air/local/sessions/<session-id>/session.db
```

Core data groups:

| Group | Tables |
|---|---|
| session/conversation | `sessions`, `messages`, `message_drafts`, `summaries` |
| orchestration | `events`, `tasks`, `task_dependencies`, `task_attempts`, `agents`, `workspaces` |
| execution evidence | `tool_runs`, `command_runs`, `artifacts`, `diagnostics`, `evidence_refs` |
| UI recovery | `ui_state` |
| schema | `schema_meta` |

SQLite V1 settings:

```sql
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA foreign_keys = OFF;
```

Durable event insert and corresponding domain table update must be in the same transaction.

## 7. Control Flow Architecture

### Startup Flow

```text
CLI starts
  → detect platform and config
  → load resources/prompts/capabilities
  → open or initialize project .air
  → run read-only Doctor
  → open session DB
  → hydrate ProjectionStore from DB
  → start TUI/Main Agent/runtime services
```

### Normal Execution Flow

```text
User request
  → Main Agent classifies intent
  → direct answer or architecture/task planning
  → Scheduler creates/loads TaskGraph
  → ContextAssembler builds agent context
  → Scheduler dispatches child worker over NDJSON IPC
  → worker uses ToolRegistry
  → ToolRegistry enforces PermissionEngine
  → tools emit events/artifacts/evidence
  → worker returns WorkerResult
  → Scheduler retries/merges/reviews/continues
  → Main Agent reports outcome
```

### Requirement Change Flow

```text
User changes requirement
  → requirement.changed event
  → Scheduler pauses affected work
  → Architecture Designer assesses if needed
  → implementation-level change continues silently
  → architecture/product-level change routes to user confirmation/replan
```

### Recovery Flow

```text
Process/session restarts
  → open session DB
  → load running/interrupted tasks and agents
  → inspect child process liveness when possible
  → emit agent.lost/task.failed or reconnect/resume
  → preserve unmerged workspaces
  → rebuild Scheduler queues
  → hydrate ProjectionStore
```

## 8. Tool and Capability Architecture

ToolRegistry provides stable schema-validated built-ins:

```text
fs.*, shell.*, git.*, project.*, cpp.*, debug.*,
gui.*, network.*, artifact.*, context.*, permission.*, doctor.*
```

CapabilityRegistry adds built-in and future plugin capabilities through manifests. Capability dependencies are declared in manifests but installed/fixed by Doctor, never by arbitrary plugin scripts.

Every tool call follows:

```text
model/agent request
  → schema validation
  → PermissionEngine evaluation
  → tool execution
  → tool/command/artifact/evidence events
  → structured ToolResult
```

## 9. Prompt and Provider Architecture

ContextAssembler emits Anthropic canonical messages with L0-L9 layers:

```text
runtime invariant
role/mode
safety and permission policy
project rules/user preferences
architecture baseline/current plan
task spec/acceptance criteria
relevant code/artifacts/evidence
recent conversation/decision context
tool result history/diagnostics
immediate instruction
```

Provider adapters convert canonical messages at the LLM boundary. Conversion omissions are recorded. Required unsupported capabilities block before model call.

Model selection is capability-based and can be Scheduler-forced or agent-selected within allowed constraints.

## 10. Security Architecture

Security boundary summary:

- LLM output is untrusted until validated.
- Tools are the only path to filesystem/shell/network effects.
- PermissionEngine evaluates all writes, execution, network, system-sensitive, and credential access.
- Symlinks are resolved by realpath before risk classification.
- `.git/` is protected by default.
- Build directories are allowed project write areas.
- Project-outside writes require backup.
- Credentials and system-sensitive operations require explicit confirmation.
- No automatic upload of logs, artifacts, debug knowledge, or doctor bundles.

## 11. Platform Architecture

V1.0.0 Alpha is Linux-first:

| Platform | Support |
|---|---|
| Linux x86_64 | tier 1 |
| Linux arm64 | tier 2 |
| WSL2 | tier 2 |
| macOS | experimental |
| Windows native | experimental/post-MVP |

Shell/process/C++ tooling in V1.0.0 Alpha targets POSIX-like Linux behavior.

## 12. Quality and Validation Architecture

Validation layers:

```text
unit tests → integration fixture replay → real LLM E2E release gate
```

Execution completion requires evidence appropriate to the task:

- build command result
- test command result
- static analysis result where configured
- debug evidence where failures occur
- review report for significant changes
- artifact/evidence refs for claims

Release gate for tier-1 Linux must cover startup, project init, child IPC, session DB, artifacts/events, C++ configure/build/test, TUI startup, and real LLM E2E behavior.

## 13. Key Risks and Mitigations

| Risk | Mitigation |
|---|---|
| Execution quality below Claude Code | Align edit primitives, tool lifecycle, read-before-edit, verification discipline |
| Context explosion | copy-on-write compaction, ContextAssembler budgets, artifact refs |
| Scheduler complexity | V1 state machine and V1.0.0 Alpha cut line; advanced optimization deferred |
| Tool/plugin safety | ToolRegistry + PermissionEngine + capability trust model |
| Provider feature mismatch | Provider capability matrix and conversion report |
| Lost worker/process | heartbeat, task attempts, restart recovery |
| Merge conflicts across parallel workers | write-area planning, worktrees, merge events, repair/escalation |
| Debug evidence too large/noisy | artifact naming/layout, evidence refs, summaries |
| Platform drift | Linux tier-1 release matrix and Doctor platform report |

## 14. V1.0.0 Alpha Architecture Boundaries

In scope for V1.0.0 Alpha:

```text
Bun monorepo
contracts package
runtime services
project-local SQLite/artifacts
EventStore/EventBus/ProjectionStore
Main Agent shell
Scheduler/worker IPC
ToolRegistry/PermissionEngine
complete C++ development workflow
local/built-in plugin and capability foundation
TUI/HUD startup and projections
provider adapters
Doctor read-only/fix framework
GUI/network evidence tools
release gate and binary tarball packaging
```

Deferred beyond V1.0.0 Alpha:

```text
third-party plugin registry/signing
container sandboxing
advanced semantic merge
multi-machine scheduling
Windows-native deep support
production-grade bitmap image generation providers
browser/computer-use automation
learned retry optimizer
```
