# C4 Module

Date: 2026-05-27
Status: Formal C4/module view for AirCoding V1 architecture

Detailed C4 code view and UML class model are defined in `AirPlan/docs/architecture/c4/code-view.md`.

## 1. System Context

AirCoding is a local AI coding agent/runtime operated by a developer in a project workspace.

```text
Developer
  → AirCoding CLI/TUI
  → local project files and .air state
  → configured LLM providers
  → local toolchains/build systems/test runners
```

External actors/systems:

| Actor/System | Relationship |
|---|---|
| Developer | gives requirements, approves decisions, reviews progress/results |
| Local project | source files, build/test outputs, `.air` state |
| LLM providers | Anthropic/OpenAI-compatible model calls through adapters |
| OS shell/toolchain | build, test, static analysis, debug, doctor fixes |
| Git | status/diff/worktree/merge/backup repository |
| Display/network subsystems | optional GUI/network evidence collection |

## 2. Container View

```text
+-------------------+
| Developer         |
+---------+---------+
          |
          v
+-------------------+       +-------------------+
| packages/cli      | ----> | packages/tui      |
| startup/doctor    |       | OpenTUI/Solid UI  |
+---------+---------+       +---------+---------+
          |                           ^
          v                           |
+------------------------------------------------+
| packages/runtime                               |
| Main Agent, Architecture Designer, Scheduler,  |
| EventStore, ToolRegistry, PermissionEngine,    |
| ContextAssembler, ArtifactStore, Projection    |
+----+-------------+-------------+---------------+
     |             |             |
     v             v             v
+-----------+ +-------------+ +-------------------+
| packages/ | | packages/   | | child worker      |
| llm       | | toolchain-  | | Bun processes     |
| providers | | cpp         | | NDJSON IPC        |
+-----+-----+ +------+------+ +---------+---------+
      |              |                  |
      v              v                  v
+-----------+ +-------------+ +-------------------+
| LLM APIs  | | OS tools    | | project .air DB   |
|           | | CMake/etc   | | artifacts/files   |
+-----------+ +-------------+ +-------------------+
```

## 3. Package Dependency View

```text
packages/contracts
  ↑
  ├── packages/runtime
  ├── packages/tui
  ├── packages/llm
  └── packages/toolchain-cpp

packages/cli
  ├── runtime
  ├── tui
  ├── llm
  └── toolchain-cpp

packages/runtime
  ├── contracts
  ├── llm interfaces/adapters
  └── toolchain-* via registry/capability boundary

packages/tui
  ├── contracts
  └── ProjectionStore client/view-models
```

Rules:

1. `contracts` has no dependency on implementation packages.
2. `runtime` does not depend on `tui`.
3. `tui` consumes `ProjectionClient`/projection contracts, not runtime internals, DB, or EventBus directly.
4. `toolchain-*` registers capabilities/tools; runtime invokes through ToolRegistry.
5. `llm` owns ProviderManager, provider adapters, model config, and provider conversion; runtime owns prompt assembly semantics and calls LLM through the provider facade.
6. `Scheduler → WorkerManager`, `EventIngestor → EventStore/EventBus`, `ProjectionStore → EventBus`, `DoctorService → CapabilityRegistry`, and `CapabilityRegistry → ToolRegistry` are one-way dependencies.

## 4. Runtime Component View

| Component | Responsibility | Public Interfaces | Dependencies | Data Ownership | Quality Notes |
|---|---|---|---|---|---|
| CLI Bootstrap | command entrypoint, config/resource loading, project open/init | CLI commands, startup API | runtime, tui, llm, toolchain-cpp | none long-term | startup smoke and doctor tests |
| Main Agent Shell | user-facing conversation/routing/escalation | MainAgent API, UI channel | ContextAssembler, Scheduler, Architecture Designer, LLM | messages via SessionStore | must remain responsive |
| Architecture Designer | architecture planning, impact assessment, ADR/C4/plan sync | architecture assessment/update API | ContextAssembler, LLM, plan docs | architecture docs | no implementation code edits |
| Scheduler | TaskGraph, waves, retries, workspaces, child dispatch | scheduler service API | EventIngestor, SessionStore, ContextAssembler, WorkerManager | tasks/agents/workspaces/attempts | restart recovery tests required |
| WorkerManager | spawn/monitor child Bun processes over NDJSON | process lifecycle API | Scheduler-owned API, OS process APIs | agents runtime metadata | heartbeat/timeout tests |
| EventIngestor | runtime event intake and durable/ephemeral routing | ingest / ingest_ephemeral | EventStore, EventBus, schema registry | none directly | ingestion tests required |
| EventBus | live event pub/sub | subscribe/publish | none; services publish through EventIngestor/EventStore | ephemeral only | no recovery source-of-truth |
| EventStore | durable event validation and transactional projection | append event, query event | SQLite, schema validators | `events` and domain updates | transaction tests required |
| SessionStore | domain repositories for session DB | repository APIs | SQLite | messages/tasks/tool runs/etc | schema migration tests |
| ToolRegistry | schema-validated tool dispatch | register/call/list tools | PermissionEngine, EventIngestor, ArtifactStore | tool run lifecycle | tool contract tests |
| PermissionEngine | path/command/network/credential decisions | evaluate/request/record | security config, realpath, command analyzer, EventIngestor | permission decisions/events | policy tests required |
| CapabilityRegistry | load/validate/enable capabilities | register capability/tools | ToolRegistry | capability config/cache refs | manifest validation tests |
| ContextAssembler | layered prompt/context construction | assemble context | SessionStore, ArtifactStore, rules, summaries | context artifacts/summaries | omission/conflict tests |
| ArtifactStore | temp-write, rename, hash, DB row/event request, URI | create/read artifact | filesystem, EventIngestor, SessionStore | artifacts tree/table | crash/orphan tests |
| EvidenceStore | claim-linked evidence references | create/query evidence | ArtifactStore, diagnostics | evidence_refs | report traceability tests |
| ProjectionStore | TUI/HUD view model from DB + live events | hydrate/subscribe/query projections | SessionStore, EventBus | derived UI state | not source-of-truth |
| ProviderManager | provider/model config, selection, adapter dispatch | complete/list/select model | llm adapters, capability matrix | provider metadata only | lives in `packages/llm`; runtime calls facade |
| DoctorService | environment/capability/dependency checks/fixes | doctor.run tool/API | CapabilityRegistry, PermissionEngine, shell tools | doctor artifacts/events | read-only startup test |

## 5. Worker Component View

Each worker runs in an independent Bun child process.

```text
Parent Scheduler
  → agent.start control message
  → Worker runtime bootstrap
  → role-specific loop
  → tool calls through parent/runtime protocol
  → RuntimeEvents and WorkerResult
```

| Worker | Writes code? | Primary input | Primary output |
|---|---:|---|---|
| Executor | yes, scoped | TaskSpec, ContextPack | Executor WorkerResult, diff/artifacts/evidence |
| Reviewer | no | diff/artifacts/plan/evidence | review report, risks, follow-up tasks |
| Debugger | yes if assigned | failure evidence, logs, diagnostics | diagnosis, fix or blocker, debug record |
| Compactor | no project code | message range snapshot, rules | summary artifact and `summary.created` |
| ExperienceMiner | rules/skills only if assigned | verified evidence/patterns | memory/skill/rule candidate |

## 6. Data Store View

```text
session.db
  schema_meta
  sessions
  messages
  message_drafts
  events
  tasks
  task_dependencies
  task_attempts
  agents
  tool_runs
  command_runs
  artifacts
  diagnostics
  evidence_refs
  workspaces
  summaries
  ui_state
```

Project-level DBs:

```text
<project>/.air/local/debug-records.db
<project>/.air/local/learned-memory.db
```

File-backed stores:

```text
<project>/.air/shared/project.json
<project>/.air/shared/rules/*.md
<project>/.air/shared/plan/*
<project>/.air/local/sessions/<session-id>/artifacts/*
<project>/.air/local/backups/*
```

## 7. Key Runtime Sequences

### 7.1 Startup / Resume

```text
CLI
  → PlatformDetector
  → ConfigLoader
  → ProjectStore.openOrInit
  → DoctorService.run(read_only)
  → SessionStore.open
  → EventStore.recover
  → ProjectionStore.hydrate
  → TUI.start
  → MainAgent.ready
```

### 7.2 User Request to Worker Execution

```text
TUI
  → MainAgent receives user message
  → SessionStore inserts message
  → MainAgent classifies intent
  → Architecture Designer if design needed
  → Scheduler loads/creates tasks
  → Scheduler plans wave
  → ContextAssembler assembles ContextPack
  → WorkerManager spawns Executor/Reviewer/Debugger
  → Worker emits IPC tool.call / event / worker.result messages
  → parent runtime routes tool.call to ToolRegistry
  → ToolRegistry validates and executes tools through PermissionEngine
  → EventIngestor routes events to EventStore or EventBus
  → EventStore persists durable events/domain rows
  → ProjectionStore updates TUI/HUD
  → WorkerResult returned
  → Scheduler merge/retry/review/complete
  → MainAgent reports result
```

### 7.3 Tool Call

```text
Worker/Agent
  → IPC tool.call when running in child process, or ToolRegistry.call for in-process runtime tools
  → ToolRegistry schema validation
  → PermissionEngine.evaluate
  → permission prompt if needed
  → tool.started event
  → command/tool/artifact operations
  → tool.completed or tool.failed
  → structured ToolResult
```

### 7.4 Context Compaction

```text
ContextAssembler detects budget pressure
  → context.compaction.requested
  → Scheduler creates compact task
  → Compactor receives immutable message range snapshot
  → summary artifact and summaries row
  → context.compaction.completed
  → future contexts use summary + backtracking refs
```

### 7.5 Parallel Workspace Merge

```text
Scheduler plans non-conflicting wave
  → git.worktree.create per write task
  → workers complete
  → workspace.merge.started
  → git merge/patch apply
  → workspace.merge.completed or workspace.merge.conflicted
  → conflict repair/debug/escalation if needed
```

## 8. Interface Inventory

| Interface | Owner | Consumers |
|---|---|---|
| `RuntimeEvent<T>` | contracts/runtime | EventStore, EventBus, workers, ProjectionStore |
| `TaskSpec` | contracts/runtime | Scheduler, workers, ContextAssembler |
| `WorkerResult<T>` | contracts/runtime | workers, Scheduler, Main Agent |
| `ToolDefinition<I,O>` | contracts/runtime | ToolRegistry, capabilities |
| `ProviderAdapter` | llm | ProviderManager/runtime |
| `ProviderCapabilityMatrix` | contracts/llm | Scheduler, ProviderManager, Doctor |
| `PermissionDecision` | runtime/security | ToolRegistry, Main Agent, EventStore |
| `ArtifactRef` | contracts/runtime | Tool results, WorkerResult, EvidenceStore |
| `EvidenceRef` | contracts/runtime | reports, reviews, debug records |
| `IpcMessage` | contracts/ipc | WorkerManager, child agents |
| `ProjectionSnapshot` | contracts/ui | TUI/HUD |

## 9. Capability View

Built-in capability groups:

| Capability | Tools |
|---|---|
| core-filesystem | `fs.list`, `fs.read`, `fs.write`, `fs.edit`, `fs.patch`, `fs.stat` |
| core-shell | `shell.run`, `process.kill` |
| core-git | `git.status`, `git.diff`, `git.worktree.create`, `git.merge_workspace` |
| core-project | `project.scan`, `project.profile.write` |
| core-artifacts | `artifact.create` |
| core-context | `context.assemble` |
| core-permission | `permission.request` |
| core-doctor | `doctor.run` |
| toolchain-cpp | `cpp.detect`, `cpp.cmake.configure`, `cpp.build`, `cpp.test`, `cpp.static.cppcheck`, `cpp.clangd.query` |
| debug-basic | `debug.run`, `debug.parse_logs` |
| gui-evidence-basic | `gui.screenshot` |
| network-evidence-basic | `network.capture` |

## 10. Deployment View

Local single-machine deployment:

```text
AirCoding binary tarball
  bin/air
  resources/
    prompts/
    themes/
    capabilities/
    scripts/

Runtime process tree
  air parent process
    child worker process N
    child shell/tool processes
```

State:

```text
~/.air/                       # global config/cache/logs
<project>/.air/shared/        # project-shareable configuration/plans/rules
<project>/.air/local/         # private sessions/artifacts/workspaces/backups
```

## 11. Architecture Decision Boundaries

Implementation may proceed silently when confined to accepted TaskSpec scope and architecture contracts.

Escalate when changing:

```text
public interfaces
DB schema
event/tool/provider contracts
component responsibilities
permission/security assumptions
product behavior/acceptance criteria
platform support promises
```

## 12. MVP Skeleton Module Cut

Initial implementation order should minimize dependency cycles:

1. `packages/contracts`
2. workspace/build/test harness
3. `runtime` storage/event/artifact foundations
4. `runtime` ToolRegistry/PermissionEngine foundations
5. `llm` provider adapter interface and one provider path
6. child worker IPC skeleton
7. Scheduler minimal state machine
8. filesystem/shell/git/project/artifact/context/doctor tools
9. `toolchain-cpp` MVP tools
10. ProjectionStore and basic TUI/HUD
11. Main Agent/Architecture Designer prompt integration
12. E2E release gate
