# AirCoding V1.0.0 Alpha System Overview Design

Date: 2026-05-29
Status: FROZEN — no further edits permitted. This document is the authoritative overview for detailed design and implementation.
Scope: Architecture-level design. No implementation code.

## 1. Purpose

This document turns the repaired AirCoding V1.0.0 Alpha architecture baseline into a system-level overview design. It is the bridge between the formal architecture baselines and the later detailed design / class diagram freeze.

Frozen source documents:

1. `AirPlan/docs/analysis/requirements.md`
2. `AirPlan/docs/architecture/baselineV1.md`
3. `AirPlan/docs/architecture/solution-architecture.md`
4. `AirPlan/docs/architecture/interface-contracts-v1.md`
5. `AirPlan/docs/architecture/db-schema-v1.md`
6. `AirPlan/docs/architecture/event-registry-v1.md`
7. `AirPlan/docs/architecture/runtime-semantics-v1.md`
8. `AirPlan/docs/architecture/c4/module.md`
9. `AirPlan/docs/architecture/c4/code-view.md`
10. `AirPlan/docs/architecture/main-agent-state-machine.md`
11. `AirPlan/docs/architecture/scheduler-state-machine-v1.md`
12. `AirPlan/docs/architecture/scope-escalation-v1.md`
13. `AirPlan/docs/architecture/security-model-v1.md`
14. `AirPlan/docs/architecture/capability-trust-v1.md`
15. `AirPlan/docs/architecture/provider-capability-matrix-v1.md`
16. `AirPlan/docs/architecture/prompt-layering-v1.md`
17. `AirPlan/docs/architecture/artifact-naming-v1.md`
18. `AirPlan/docs/architecture/error-taxonomy-v1.md`
19. `AirPlan/docs/architecture/tool-registry-v1.md`
20. `AirPlan/docs/architecture/cross-platform-matrix-v1.md`
21. `AirPlan/docs/architecture/decisions-round-1.md`
22. `AirPlan/docs/architecture/decisions-round-2.md`
23. `AirPlan/docs/architecture/decisions-round-3.md`
24. `idea.md`

Current-stage review inputs:

1. `AirPlan/docs/architecture/gpt5概要设计审查.md`
2. `AirPlan/docs/architecture/mimo2.5概要设计审查.md`
3. `AirPlan/docs/architecture/Opus4.7概要设计审查.md`
4. `AirPlan/docs/architecture/DeepSeek概要设计审查.md`
5. `AirPlan/docs/architecture/多模型三视角审查联合评估.md`
6. `AirPlan/plan.md`
7. `AirPlan/todo.md`

Baseline precedence: frozen source documents are authoritative. This overview may add design-stage alignment decisions and cross-document summaries, but it does not change frozen requirements or baselines.

## 2. System Goal

AirCoding V1.0.0 Alpha is a self-owned, Linux-first, local AI coding runtime. It is not a Claude Code plugin, wrapper, or thin shell around another coding agent. It owns its runtime state, event log, task scheduler, tool permission layer, artifact/evidence lifecycle, and UI projection.

Canonical V1 coding loop:

```text
requirement
  → architecture/interface design
  → code reading
  → implementation planning
  → scoped implementation
  → build
  → static analysis
  → test
  → run/debug
  → crash/log/network/GUI evidence analysis
  → fix
  → review
  → change summary
  → experience mining
```

V1.0.0 Alpha must deliver a usable developer loop with:

- global `~/.air` user state and project-local `.air` state;
- stable `project_id` UUID per initialized project;
- SQLite-backed session persistence and recovery;
- event-driven runtime behavior;
- isolated Bun child-process workers;
- ToolRegistry + PermissionEngine for all side effects;
- Anthropic-canonical provider boundary;
- OpenTUI/Solid terminal UI and HUD;
- complete zero-config-oriented C++ configure/build/test/static-analysis/debug/fix/review workflow;
- capability/plugin foundation;
- evidence-backed completion and release gates.

Core architecture decisions inherited from `solution-architecture.md`:

1. Event-driven runtime with SQLite recovery.
2. ToolRegistry + PermissionEngine for all side effects.
3. Anthropic canonical internal message format with provider adapter boundary.
4. Bun child-process workers over NDJSON IPC.

Reference influences and reuse boundaries:

| Reference | Used for | Not reused for |
|---|---|---|
| Claude Code | Execution-layer quality benchmark: read-before-edit, exact conservative edits, small patches, no unrelated refactors, verification-before-completion, evidence-backed closure | Runtime ownership or state model |
| OpenCode | UI visual patterns and OpenTUI primitives | SDK, sync, session, or business-state logic |
| Hermes Agent | Experience mining, Nudge triggers, Curator daemon, self-patch ideas, `SKILL.md` format | Runtime process model |
| OpenAI Codex | Shell/patch/test loop and tool orchestration ideas | Provider/runtime lock-in |
| Claude Skills | Skill directory layout and trigger descriptions | Untrusted side-effect bypass |
| asciinema / Atuin / claude-hud | PTY capture, command history indexing, HUD/statusline layout | Source of truth for runtime recovery |

Technology baseline:

- Runtime language: TypeScript on Bun.
- Monorepo: Bun workspaces + Turborepo.
- TUI: `@opentui/solid`, `@opentui/core`, `@opentui/keymap`.
- Storage: SQLite per session, project-local by default.
- IPC: NDJSON over stdio.
- Python: subprocess-only helper layer for existing scripts/libraries, not core runtime.
- Distribution: binary tarball before public package channels.

Non-goals for V1.0.0 Alpha:

- third-party plugin registry/signing;
- container sandboxing;
- multi-machine scheduling;
- Windows-native deep support;
- advanced semantic merge;
- production bitmap image generation provider integration.

## 3. System Context

```text
Developer
  │
  ▼
AirCoding CLI/TUI
  │
  ├─ global ~/.air user state
  ├─ local project files
  ├─ project-local .air state
  ├─ local shell/toolchains/debug tools
  ├─ configured LLM providers
  └─ optional display/network evidence tools
```

External dependencies:

| External system | Role | Boundary rule |
|---|---|---|
| Global `~/.air` | User config, provider config, project index, global skills/cache/logs | User-local state; not project source of truth |
| Local project | Source files, build outputs, tests | All writes go through tools and permissions |
| `.air/shared` | Git-shareable project config/rules/plans | May be committed by user/project |
| `.air/local` | Private local DBs/artifacts/workspaces/backups | Gitignored by default |
| LLM providers | Model completions | Provider adapters convert at boundary |
| OS shell/toolchain | Build/test/debug/static analysis | ToolRegistry + PermissionEngine only |
| Git | Diff, status, worktree, merge, backup repo | Permissioned tools only |
| Display/network subsystems | GUI screenshots, pcaps | Explicit evidence tools, no automatic upload |

## 4. Container Overview

```text
packages/contracts
  ▲          ▲          ▲              ▲              ▲
  │          │          │              │              │
packages/cli ───▶ packages/runtime ───▶ packages/llm  │
  │                 │        │                         │
  ▼                 │        └── provider adapters     │
packages/tui        │                                  │
                    ├── packages/toolchain-cpp via capability/tools
                    ├── child worker processes over NDJSON IPC
                    ├── SQLite session/project DBs
                    └── project filesystem/artifacts/backups
```

Canonical dependency direction from C4 module view:

```text
contracts ← cli
contracts ← runtime
contracts ← llm
contracts ← tui
contracts ← toolchain-cpp
runtime   ← cli
runtime   ← workers over IPC, not direct imports
llm       ← runtime through ProviderManager facade
tui       ← cli bootstrap and ProjectionClient contracts only
toolchain-cpp ← runtime through capability/tool boundary
```

| Container | Responsibility | Key outputs |
|---|---|---|
| `packages/contracts` | Shared TypeScript public contracts | RuntimeEvent, TaskSpec, WorkerResult, ToolDefinition, IPC, provider, UI, DB-facing types |
| `packages/cli` | Entry point, command routing, init/open project, Doctor, TUI bootstrap | CLI commands and startup lifecycle |
| `packages/tui` | OpenTUI/Solid views and HUD | User conversation, progress, evidence, permission prompts |
| `packages/runtime` | Main Agent, Architecture Designer, Scheduler, EventStore, ToolRegistry, PermissionEngine, context, artifacts, projection | Core orchestration and state ownership |
| `packages/llm` | Provider config, startup/session selection, adapters, conversion reports | ProviderManager facade and stream events |
| `packages/toolchain-cpp` | C++ capability/tools | `cpp.*` tools, deterministic diagnostics, evidence |
| worker processes | Executor/Reviewer/Debugger/Compactor/ExperienceMiner roles | WorkerResult, RuntimeEvents, tool calls |

Future language packages may add `packages/toolchain-python`, `packages/toolchain-rust`, and `packages/toolchain-js`; V1.0.0 Alpha only requires `packages/toolchain-cpp`.

Expected `packages/contracts/src/` public file set from code view:

```text
index.ts
types.ts
errors.ts
events.ts
storage.ts
project.ts
scheduler.ts
workers.ts
tools.ts
permissions.ts
artifacts.ts
providers.ts
context.ts
projection.ts
capabilities.ts
doctor.ts
knowledge.ts
diagnostics.ts
```

## 5. Dependency Rules

```text
contracts → no implementation dependencies
cli → runtime, tui, llm, toolchain-cpp
tui → contracts only for projection/UI contracts
runtime → contracts, llm facade, toolchain-* through capability boundary
llm → contracts
toolchain-cpp → contracts
workers → contracts and WorkerRuntime IPC surface
```

Forbidden paths:

- TUI → SQLite direct query;
- TUI → runtime private service import;
- worker → SQLite direct write;
- worker → filesystem/shell/network side effect outside tool IPC;
- tool → side effect without PermissionEngine;
- capability → dependency install outside Doctor;
- provider adapter → silent semantic prompt loss;
- repository → scheduling policy;
- EventBus → recovery source of truth;
- runtime → TUI import;
- LLM output → direct file/shell side effect.

## 6. Runtime Component Overview

| Component | Owns | Calls | Emits / persists |
|---|---|---|---|
| Main Agent | User interaction, request classification, direct mode | ContextAssembler, ProviderManager, Scheduler, Architecture Designer | messages, `requirement.changed`, progress summaries |
| Architecture Designer | Architecture impact and plan/doc sync | ContextAssembler, ProviderManager, document stores | `architecture.plan.updated`, `architecture.impact.completed` |
| Scheduler | TaskGraph, wave planning, retries, workspaces, worker lifecycle | SessionStore, WorkerManager, ContextAssembler, EventIngestor | `task.*`, `agent.*`, `workspace.*` |
| WorkerManager | Child process spawn/monitor, IPC lifecycle | OS process APIs, WorkerProtocol | `agent.started/lost/completed/failed` |
| EventIngestor | Event intake boundary | EventStore, EventBus, EventSchemaRegistry | routes durable/ephemeral events |
| EventStore | Durable event validation and domain projection transaction | SQLite, EventSchemaRegistry | `events` + domain table rows |
| EventBus | Live pub/sub | subscribers only | ephemeral delivery and post-commit durable delivery |
| SessionStore | Repositories over session DB | SQLite | domain records |
| ToolRegistry | Tool registration and dispatch | PermissionEngine, ArtifactStore, EventIngestor | `tool.*`, ToolResultEnvelope |
| PermissionEngine | Action/risk decisions | PathClassifier, CommandRiskAnalyzer, EventIngestor | `permission.*` |
| CapabilityRegistry | Manifest discovery/validation/enable | ToolRegistry, DoctorService | capability config and registered tools |
| ContextAssembler | Prompt layering and context budget | SessionStore, ArtifactStore, PromptLayerLoader, CompactionPolicy | AssembledContext, compaction requests |
| ArtifactStore | Artifacts temp-write/rename/hash/read | filesystem, EventIngestor, SessionStore | artifacts table, `artifact.created` |
| EvidenceStore | Evidence refs and claim links | ArtifactStore, diagnostics | evidence_refs table |
| ProjectionStore | TUI/HUD view model | SessionStore, EventBus | derived ProjectionSnapshot |
| ProviderManager | Startup/session provider/model validation and streaming | provider adapters | ProviderStreamEvent, conversion reports |
| DoctorService | Environment/capability checks/fixes/bundles | CapabilityRegistry, PermissionEngine, tools | doctor events/artifacts |
| DebugKnowledgeStore | debug-records.db | project-level DB | DebugRecord rows |
| LearnedMemoryStore | learned-memory.db | project-level DB | LearnedMemory rows |
| Logger | user and developer logs | redaction/encryption policy | `air.log`, encrypted developer log |
| ProjectScanner | directory tree metadata scan | filesystem metadata only | project scan artifacts/warnings |
| MigrationManager | schema/version checks and migrations | SQLite, backup repo, PermissionEngine | migration plan/evidence |

Main Agent must remain idle-ready and responsive. It never performs long-running background work itself; Scheduler dispatches background tasks to workers.

Scheduler owns TaskGraph loading, dependency resolution, write-area conflict handling, wave planning, retry budgets, child worker dispatch, heartbeat monitoring, workspace merge coordination, and restart recovery.

Capability lifecycle:

```text
discovered
  → validated
  → doctor_checked
  → enabled
  → registered
  → active
  → disabled | failed | updated
```

Trust levels:

```text
built_in | project_local | user_installed | verified_publisher | untrusted
```

Built-in and local manifests still pass schema validation and permission checks. Trust affects default enablement and prompt posture; it never bypasses ToolRegistry or PermissionEngine.

## 7. Runtime Agent Overview

| Agent/role | Process model | Writes project code? | Key inputs | Key outputs |
|---|---|---:|---|---|
| Main Agent | in runtime process | only in direct mode | user messages, projections, context | messages, routing decisions, summaries |
| Architecture Designer | in runtime process / LLM role | planning docs only | requirement changes, current architecture | impact assessment, plan/doc updates |
| Scheduler | in runtime process | no code writes | TaskGraph, events, worker results | wave plans, worker dispatch, task outcomes |
| Executor | child process | yes, scoped | TaskSpec, ContextPack, WorkerRuntime | ExecutorResult, diffs, artifacts, evidence |
| Reviewer | child process | no | diffs, evidence, architecture context | findings, verdict, follow-up tasks |
| Debugger | child process | yes if assigned | failure evidence, diagnostics, logs | diagnosis, fix/blocker, debug record |
| Compactor | child process | no project code | message snapshot, compaction rules | summary row/artifact |
| ExperienceMiner | child process | rules/skills only if assigned | verified patterns/evidence | memory/rule/skill candidates |

Worker loops are independent role implementations, not one generic shared loop.

## 8. State and Data Overview

### 8.1 Filesystem layout

Global user directory:

```text
~/.air/
  config.yaml
  models.yaml
  permissions.yaml
  compaction-rules.md
  project-index.db
  cache/
    plugins/
    providers/
    lsp/
    downloads/
  resources/versions/<version>/
  skills/
  logs/
    air.log
    air.developer.log
```

Project-local directory:

```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/
```

`project_id` is a stable UUID generated at project initialization and stored in `.air/shared/project.json`. It is not derived from the absolute path. `.air/local/` is gitignored by default.

### 8.2 Session DB

`session.db` lives at `.air/local/sessions/<session-id>/session.db` and owns recoverable per-session state:

- sessions;
- messages;
- message_drafts;
- events;
- tasks;
- task_dependencies;
- task_attempts;
- agents;
- tool_runs;
- command_runs;
- artifacts;
- diagnostics;
- evidence_refs;
- workspaces;
- summaries;
- ui_state.

Rules:

1. Durable event insert and corresponding domain update occur in one SQLite transaction.
2. EventBus is never recovery source of truth.
3. `foreign_keys = OFF` is compensated by repository-level invariant checks and startup orphan scans.
4. Artifact files use temp-write → hash/size → atomic rename → DB record.
5. `ui_state` is not source of truth for runtime state.
6. Messages store Anthropic canonical JSON in `content_json` with `canonical_format = "anthropic"`.
7. `assistant.message.started` writes/updates `message_drafts`; `assistant.message.created` inserts the final `messages` row and deletes the draft.
8. V1 does not use a separate `message_parts` source-of-truth table.
9. Closed enum values are controlled by `db-schema-v1.md` and require migration review when changed.

FK-off application invariants:

1. `tasks.session_id` must reference an existing `sessions.id`.
2. `task_attempts.task_id` must reference an existing `tasks.id`.
3. `agents.task_id` must reference an existing `tasks.id` when not null.
4. `tool_runs.task_id` and `tool_runs.agent_id` must reference existing rows when not null.
5. `command_runs.task_id`, `command_runs.agent_id`, and `command_runs.tool_run_id` must reference existing rows when not null.
6. `workspaces.task_id` and `workspaces.agent_id` must reference existing rows when not null.
7. `diagnostics.command_run_id` and `diagnostics.artifact_id` must reference existing rows when not null.
8. `evidence_refs` foreign columns must reference existing rows when not null.

`command_runs` status is derived, not stored as a physical V1 status column:

| Row state | Derived status |
|---|---|
| `completed_at` is null | `running` |
| `exit_code = 0` | `ok` |
| `exit_code` non-zero | `error` |
| cancellation metadata present | `cancelled` |
| inconsistent row | `unknown` |

### 8.3 Project-level DBs

| DB | Purpose | Owner |
|---|---|---|
| `.air/local/debug-records.db` | verified failure/debug knowledge records | DebugKnowledgeStore |
| `.air/local/learned-memory.db` | candidates, promoted memories, archived/rejected entries | LearnedMemoryStore |

Cross-DB and file writes use outbox/compensation semantics:

```text
1. Insert durable session event recording intent/request.
2. Insert or update session domain row with pending/external status where applicable.
3. Perform external DB/file operation through owning service.
4. Emit durable completed/failed event with evidence.
5. On restart, recovery scans pending external intents and reconciles.
```

### 8.4 Artifact and evidence naming

Artifacts use the canonical naming model from `artifact-naming-v1.md`:

```text
artifact://project/<project-id>/session/<session-id>/<artifact-id>
art_<ulid>
<timestamp>-<artifact-id>-<slug><extension>
```

Artifact type maps to a session artifact subdirectory. Evidence refs link claims to artifacts, diagnostics, command runs, tool runs, messages, agents, or tasks. Worker results embed full `EvidenceRef[]` when evidence is part of the conclusion; lightweight events may carry evidence IDs.

## 9. Event, Error, and Projection Overview

### 9.1 Event flow

```text
Producer
  → EventIngestor
  → validate envelope, schema, and version
  → durable? EventStore transaction + domain projection + EventBus post-commit publish
  → ephemeral? EventBus publish/coalescing only
  → ProjectionStore applies event
  → TUI/HUD renders ProjectionSnapshot
```

RuntimeEvent envelope:

```text
id
type
version
timestamp
session_id
project_id?
source
route[]
payload
```

Rules:

1. `route` is append-only. Forwarders append their segment and never rewrite earlier entries.
2. `route_text` in SQLite is derived from `route.join("/")` for indexing.
3. EventStore decides durable vs ephemeral persistence by event type; producers do not decide ad hoc.
4. Payload schema changes require incrementing the event `version` for that event type.
5. Durable event insert and same-session domain projection happen in one SQLite transaction.
6. Durable events are published to EventBus only after commit.
7. EventBus handler errors are caught, logged to developer log, and do not propagate to the publisher; the subscription remains active.

Durable events include session/message/task/agent/tool/command/artifact/diagnostic/evidence/context/summary/permission/doctor/requirement/architecture/workspace/memory/debug events.

Ephemeral events include heartbeat, task progress, assistant delta, tool progress, command stdout/stderr deltas, HUD frame rendered.

### 9.2 Error taxonomy

All tool, event, worker, provider, and command failures use `AirError` rather than parallel ad hoc error shapes.

`AirError` carries:

```text
error_id
kind
severity
message
detail?
retryability
semantic_signature
cause_ref?
cause_refs?
user_action?
metadata?
```

Error kinds:

```text
user_error
project_error
env_error
dependency_error
permission_error
tool_error
command_error
build_error
test_error
static_analysis_error
debug_error
provider_error
model_capability_error
context_error
agent_error
scheduler_error
workspace_error
merge_error
architecture_error
policy_error
system_error
unknown_error
```

Severity:

```text
info | warning | error | fatal
```

Retryability:

```text
retryable | retryable_after_change | not_retryable | unknown
```

`semantic_signature` is the stable grouping key for repeated failure detection, debug knowledge lookup, and Scheduler retry/debug/escalation routing. Scheduler decisions use error kind, retryability, severity, task scope, permission result, architecture impact, verification evidence, and repetition count.

### 9.3 ProjectionStore

ProjectionStore rules:

- hydrate from DB on startup/resume;
- apply durable and key ephemeral events;
- coalesce noisy deltas;
- ignore unknown event types;
- never become scheduling/recovery source of truth.

## 10. Execution Flow Overview

### 10.1 Startup / open session

```text
CLI
  → load global config/resources
  → locate or initialize project
  → Doctor self-bootstrap and read-only startup check
  → open session.db
  → run schema/recovery checks
  → hydrate ProjectionStore
  → start TUI/HUD
  → Main Agent ready
```

Doctor fix mode on first startup always asks before applying fixes, even in high-permission mode.

### 10.2 Main Agent state machine

Main Agent lifecycle:

```text
IDLE
  → CLASSIFYING
  → ANSWERING | DELEGATING | DIRECT_MODE
  → SCHEDULING | ARCHITECTURE_DESIGNING
  → CONFIRMING when user confirmation is needed
  → EXECUTING
  → INTERRUPTING when requirements change mid-execution
  → ARCHITECTURE_REVISING when design-level changes are required
  → SUMMARIZING
  → IDLE
```

Main Agent state rules:

- IDLE/CLASSIFYING/ANSWERING/CONFIRMING/SUMMARIZING perform no task execution.
- DIRECT_MODE uses `permission_template = "main_direct"` and writes only to the main workspace.
- EXECUTING is Scheduler-owned; Main Agent reports progress and decisions.
- Requirement changes emit `requirement.changed` and route to Scheduler/Architecture Designer according to impact.

### 10.3 Scheduler state machine

Scheduler states:

```text
IDLE
  → LOADING_GRAPH
  → PLANNING_WAVE
  → DISPATCHING
  → MONITORING
  → MERGING
  → REVIEWING
  → RETRYING | DEBUGGING | ESCALATING | BLOCKED | COMPLETED | CANCELLED
  → RECOVERING on restart/lost worker
```

Scheduler owns:

- runnable task discovery;
- dependency and write-area serialization;
- wave planning;
- workspace assignment;
- model assignment according to constraints;
- worker dispatch;
- heartbeat timeout and lost-worker recovery;
- retry budget enforcement;
- review/debug routing;
- workspace merge and conflict handling;
- architecture/user escalation routing;
- recovery after restart.

### 10.4 Normal user request

```text
TUI/CLI user message
  → Main Agent records message
  → classify intent
  → answer directly OR route work
  → Architecture Designer if architecture/interface/product impact
  → Scheduler creates TaskSpec records
  → Scheduler computes runnable wave
  → ContextAssembler builds ContextPack
  → WorkerManager starts child worker
  → worker uses WorkerRuntime for events/tools/checkpoints
  → Scheduler collects WorkerResult
  → review/debug/merge/retry/escalate as needed
  → Main Agent reports result with evidence
```

### 10.5 Direct mode

```text
/direct
  → Main Agent enters DIRECT_MODE
  → permission_template = main_direct
  → direct ToolRegistry calls, main workspace only
  → events recorded with source.kind = main
/done
  → evidence collection
  → summary
  → IDLE
```

### 10.6 Tool call

```text
Agent/worker
  → ToolRegistry.call or IPC tool.call
  → schema validation
  → PermissionEngine.evaluate
  → permission prompt if needed
  → tool.started
  → side effect / command / artifact
  → tool.completed | tool.failed | tool.cancelled
  → ToolResultEnvelope
```

Tool rules:

- `ToolDefinition` includes input/output schemas, category, permissions, and streaming flag.
- `shell.run` is the AirCoding runtime equivalent of a controlled Bash execution primitive.
- `call()` consumes streaming internally and returns the final `ToolResultEnvelope`.
- `call_streaming()` exposes progress events and ends with exactly one final result envelope.

### 10.7 Review and architecture gate

Ordinary implementation tasks use the normal review path:

```text
WorkerResult
  → Reviewer
  → Scheduler completes/retries/blocks based on ReviewerResult and evidence
```

Architecture-sensitive work adds an Architecture Designer gate:

```text
WorkerResult
  → Reviewer
  → if architecture-sensitive: Architecture Designer impact/review gate
  → Scheduler combines gates
  → complete | retry | block | replan | ask user
```

Architecture Designer does not replace Reviewer. Reviewer owns implementation quality, correctness, security, tests, and evidence sufficiency. Architecture Designer owns interface/schema/event/package-boundary/security/runtime-semantics/ADR/C4/plan consistency.

Trigger Architecture Designer gate when any are true:

1. public function/class/module interface changes;
2. DB schema or persisted data shape changes;
3. IPC/event/tool/provider contract changes;
4. package dependency direction or component responsibility changes;
5. runtime semantics, security model, capability trust, or permission boundary changes;
6. ADR/C4/plan/todo architecture artifacts must change;
7. Reviewer emits `category = "architecture"`;
8. worker returns architecture/interface blocker;
9. phase completion requires architecture consistency review;
10. release/final completion requires full architecture consistency review.

Scope impact levels:

```text
implementation
interface
architecture
product
permission
environment
policy
```

Gate result rule:

```text
Reviewer approved + Architecture gate approved/not_required = may complete
Reviewer changes_requested = retry/debug
Architecture requires_replan = route to Architecture Designer planning
Architecture requires_user_confirmation = Main Agent asks user
Architecture reject_or_escalate = block until explicit decision
```

### 10.8 C++ workflow

```text
cpp.detect
  → cpp.cmake.configure
  → cpp.build
  → deterministic DiagnosticParser
  → cpp.test
  → cpp.static.cppcheck
  → cpp.clangd.query when needed
  → Debugger for build/test/debug failures
  → scoped fix loop
  → Reviewer
  → Architecture Designer gate if contracts/schema/events/boundaries changed
  → evidence-backed verification
```

C++ toolchain rules:

- CMake + Ninja is preferred when available.
- Make fallback is supported.
- `compile_commands.json` is generated or located when clangd/static analysis requires it.
- clangd is used in CLI/query mode for V1, not hidden inside a language-server UI integration.
- DiagnosticParser in `toolchain-cpp` performs deterministic extraction and semantic signature generation only.
- LLM-based diagnostic interpretation happens in runtime Debugger/Reviewer context, not inside `toolchain-cpp`.
- The user experience target is zero-config C++ onboarding where feasible: detect existing project shape before requiring manual `.air` configuration.

### 10.9 Claude Code execution discipline

All code-changing execution paths must preserve these runtime-level constraints:

1. Read before edit: `fs.edit`/`fs.patch` require a recent read observation or expected file hash.
2. Exact edit: `old_string` must match exactly; non-unique matches fail unless replace-all is explicit.
3. Conservative patching: changes stay inside TaskSpec scope and write area.
4. No unrelated refactors: workers must not broaden scope to improve nearby code opportunistically.
5. Verification before completion: code-changing WorkerResult cannot be `completed` unless required verification passed, or skipped verification is explicitly allowed with evidence/risk.
6. Evidence-backed closure: diffs, command outputs, diagnostics, artifacts, or screenshots are linked through evidence refs.
7. Block instead of improvising when product, interface, architecture, permission, environment, or policy decisions are missing.

### 10.10 TaskSpec and WorkerResult overview

TaskSpec field families:

```text
identity: id, type, title, description
acceptance: acceptance_criteria
scope: write_area, expected_files, allowed_paths, denied_paths
dependencies: hard, soft, conflict, serialization
verification: commands, required, fallback_allowed
constraints: max_turns, soft_timeout_ms, hard_timeout_ms, retry_budget, model_policy, model ids
context_refs: plan_ref, arc_ref, parent results, artifacts
output_contract: ExecutorResult | ReviewerResult | DebuggerResult | CompactorResult | ExperienceMinerResult
```

WorkerResult field families:

```text
identity: task_id, agent_id, agent_type
status: completed | failed | blocked | cancelled
summary
changed_files
diff_ref
artifacts
verification
risks
follow_up_tasks
evidence_refs
result
```

Status semantics:

| Status | Meaning | Scheduler behavior |
|---|---|---|
| `completed` | Acceptance met and verification policy satisfied | review/merge/complete |
| `failed` | Attempt failed due to error and may be retried/debugged according to retryability | retry/debug/fail |
| `blocked` | Cannot safely proceed without decision, environment fix, permission, dependency, or architecture assessment | escalate/block |
| `cancelled` | Task intentionally stopped | preserve evidence/workspace state |

`summary` is user-facing and scheduler-readable; it must not hide unresolved risks or skipped verification.

## 11. IPC and Worker Overview

V1 uses NDJSON over stdio between runtime parent and child workers.

IPC envelope fields:

```text
id
direction
kind
timestamp
session_id
agent_id
correlation_id?
protocol_version
payload
```

Handshake:

1. parent spawns worker process;
2. parent sends `agent.start` after spawn;
3. worker responds with `worker.ready` including `protocol_version`;
4. parent validates protocol version;
5. worker executes role loop;
6. worker returns `worker.result`, checkpoints, logs, events, and tool calls.

Message categories:

| Direction | Kinds |
|---|---|
| parent → worker | `control`, `tool.result`, `tool.stream` |
| worker → parent | `event`, `log`, `tool.call`, `worker.result`, `worker.checkpoint`, `protocol.error` |

Stdout is NDJSON protocol only. Stderr is for fatal fallback/logging and must not carry protocol messages.

Worker exit codes:

| Code | Meaning |
|---:|---|
| 0 | protocol-level completion (including task failed/blocked via WorkerResult) |
| 1 | uncaught exception |
| 2 | startup/protocol error |
| 3 | permission error |
| 4 | parent cancelled |
| 5 | hard timeout killed |

Note: Task success/failure is communicated through `WorkerResult.status`, not exit codes. Exit code 0 means the worker completed the IPC protocol correctly; the actual task outcome is in the result payload.

Workers never write SQLite directly and never perform side effects outside parent-mediated tools.

## 12. Permission and Security Overview

Permission evaluation order:

1. tool capability declaration;
2. permission profile;
3. TaskSpec scope allowed/denied paths;
4. path/command/network risk classification;
5. credential/system-sensitive override;
6. user prompt workflow.

Permission actions:

```text
allow | deny | ask_user | block | refuse | announce_then_run
```

Grant scopes:

```text
none | once | session | project | global
```

Path risk categories:

```text
project_source
project_build_output
project_air_shared
project_air_local
project_git_internal
outside_project
credential_or_secret
system_sensitive
```

Command risk categories:

```text
read_only
build
test
static_analysis
git_read
git_write
destructive
network
system_sensitive
credential_sensitive
```

Boundary rules:

1. Path policy uses realpath normalization before allow/deny checks; symlink escapes are not allowed by string-prefix checks.
2. `.git/` internals are protected from arbitrary write tools; Git operations go through git tools.
3. Build output directories are lower risk than source but still remain scoped by TaskSpec and destructive-command analysis.
4. Runtime-owned writes inside `.air/local/` are internal service operations, but user-visible or destructive access still follows permission policy.
5. `sudo` does not automatically become high risk by string alone; command intent, target path, and system sensitivity determine risk, with safe prompts when uncertain.
6. Static high-risk command patterns are deny/ask by default, with LLM escape hatch only through explicit PermissionEngine reasoning and prompt flow.
7. Project-outside writes require backup where policy says `backup_required`, usually through `.air/local/backups/`.
8. Credentials and system-sensitive actions override broad session/project/global allows.
9. Project-level allow does not override TaskSpec scope.
10. Migration, destructive, shared-state, credential, and policy-sensitive operations require explicit user confirmation or block/refuse.

Security invariants:

- LLM output is untrusted until validated by runtime/tool schemas and PermissionEngine;
- provider output cannot directly modify files or run commands;
- credentials are referenced by `auth_ref` and not copied into events/artifacts;
- no automatic upload of source, logs, screenshots, bundles, pcaps, or artifacts;
- destructive/system-sensitive actions require confirmation or policy block.

## 13. Context, Memory, and Compaction Overview

Context assembly uses ordered PromptLayers L0-L9 (per `prompt-layering-v1.md`):

| Layer | Name |
|---|---|
| L0 | Runtime invariant |
| L1 | Role / agent mode |
| L2 | Safety and permission policy |
| L3 | Project rules and user preferences |
| L4 | Architecture baseline and current plan |
| L5 | Task specification and acceptance criteria |
| L6 | Relevant code / artifacts / evidence |
| L7 | Recent conversation and decision context |
| L8 | Tool result history / diagnostics |
| L9 | Immediate instruction |

Compaction rules:

1. ContextAssembler may request compaction but does not compact itself.
2. Scheduler creates `compact` task.
3. Compactor snapshots immutable message range.
4. `summary.created` inserts the summaries row.
5. `context.compaction.completed` references the created summary.
6. Original messages are preserved for backtracking.

ExperienceMiner triggers:

- debug record created;
- session end;
- N-turn/tool-call interval (default 10);
- stale rule/skill discovered during execution.

Scheduler owns trigger creation. ExperienceMiner never self-triggers. Curator dedup/archive runs as a scheduled `mine_experience` task.

Experience lifecycle:

```text
candidate.created
  → evidence threshold check
  → user/project policy approval
  → promotion write through owning store
  → memory.promoted or promotion failed
  → rollback/archive if stale or harmful
```

## 14. UI/HUD and Provider Overview

TUI is in-process with runtime for V1.0.0 Alpha.

Rules:

- TUI consumes only `ProjectionClient` and projection contracts;
- UI commands flow through a narrow UiCommandChannel;
- TUI never imports runtime private services;
- TUI never queries SQLite/EventBus directly;
- permission prompts, blockers, evidence, artifacts, and HUD are rendered from ProjectionSnapshot/evidence refs.

OpenCode reuse boundary:

- Reuse visual/component patterns: theme, dialog, modal, toast, keymap, layout, spinner, border, error, markdown, code, diff.
- Do not reuse SDK, sync, session, or business-state logic.

V1.0.0 Alpha UI surfaces:

- conversation;
- task/agent/tool/command progress;
- permission prompt UX with `announce_then_run` visualization;
- blocker reports;
- evidence display;
- HUD presets: Full / Essential / Minimal;
- read-only provider/model status display;
- CLI command catalog: `resume`, `compact`, `history`, `session list`, read-only `provider list/current`, `restore`.

UI design evidence capability:

- ASCII/wireframe layout sketches for terminal UI planning;
- SVG/textual diagram artifacts where useful;
- screenshot capture and analysis for GUI evidence;
- no automatic upload of screenshots or generated design artifacts.

Provider capability matrix concepts:

```text
provider_kind
quality_tier: frontier | strong | standard | cheap | local | unknown
cost_tier: high | medium | low | free | unknown
context_window_tokens
max_output_tokens
supports
conversion
```

Provider adapters expose `list_models()`, `validate_model()`, optional `count_tokens()`, and streaming `complete()`. Provider adapters convert external formats to/from AirCoding's Anthropic canonical internal format and must not silently drop semantic prompt/tool information.

Model/provider rule: runtime provider/model selection is fixed for a running session and must not be changed through TUI shortcuts or CLI commands. Users may inspect current provider/model state, but switching requires starting a new session or editing config before startup. This is a design-stage decision accepted during overview review and should be captured in ADR/detailed design when provider UI is specified.

## 15. Doctor, Restore, Recovery, and Operations Overview

Doctor self-bootstrap:

1. verify Bun runtime;
2. verify SQLite availability;
3. verify basic shell access;
4. verify `.air/` writability;
5. run platform/provider/toolchain/capability/display/network checks.

Doctor modes:

- read-only startup/manual check;
- fix mode under PermissionEngine;
- bundle export with local artifact, no automatic upload.

Restore:

- `air restore file <path>`;
- `air restore time <timestamp>`;
- `air restore session <session-id>`.

Restore uses the git-backed backup repository under `.air/local/backups/` and preserves history with a restore commit.

Recovery:

- DB recovery rebuilds scheduler queues from tasks/agents/task_attempts/workspaces;
- lost worker detection emits durable `agent.lost`;
- orphan artifact scan registers or quarantines files;
- FK-off orphan scan logs and repairs/archive references;
- workspace GC preserves active/conflicted states and cleans merged/abandoned states by retention policy.

Workspace GC policy:

| Workspace status | Retention |
|---|---|
| active | preserve until merge or explicit cancel |
| merged | preserve 7 days after `merged_at`, then clean |
| conflicted | preserve until decision, then move to abandoned |
| abandoned | preserve 3 days, then clean |
| cleaned | filesystem artifacts removed; DB row retained |

Logging:

- `air.log` is user-facing and contains redacted operational errors and recovery summaries.
- `air.developer.log` is encrypted, more detailed, and retained according to policy.
- Logs must redact secrets, auth refs, provider keys, and credential-like values.
- Tool/command failures link log artifacts through evidence refs rather than copying sensitive content into user summaries.

Migration:

1. Detect `schema_meta.schema_version` on session/project DB open.
2. If migration is needed, build a migration plan and risk summary.
3. Create backup through `.air/local/backups/` before migration when required.
4. Ask user for destructive or non-trivial migration confirmation.
5. Apply migration transactionally when SQLite scope allows.
6. Emit migration evidence and recovery instructions.
7. On failure, restore or leave explicit repair state.

Project scanner:

- collects full directory tree metadata with no directory exclusion and no depth limit;
- does not recurse through symlinks by default;
- records permission errors as entries with error metadata;
- does not read file contents during tree scan;
- records special file types without opening them;
- provides progress and cancellation hooks;
- records cycle/mount anomalies as scanner warnings.

Distribution:

```text
binary tarball
  bin/air
  resources/
  LICENSE
```

Tier-1 Linux x86_64 is release-blocking. Linux arm64 and WSL2 are best-effort/tier-2 according to the cross-platform matrix. Windows-native deep support is not V1.0.0 Alpha release-blocking.

## 16. Implementation Phase Mapping

| Phase | System overview scope |
|---|---|
| Phase 0 | Monorepo skeleton + `packages/contracts` |
| Phase 1 | `.air` project/session storage, SQLite, EventStore, ArtifactStore |
| Phase 2 | ToolRegistry, PermissionEngine, built-in tools, CapabilityRegistry |
| Phase 3 | Provider layer, ContextAssembler, prompt resources |
| Phase 4 | Worker IPC, WorkerManager, Scheduler |
| Phase 5 | Complete C++ workflow |
| Phase 6 | ProjectionStore, TUI/HUD, UX surfaces |
| Phase 7 | Main Agent / Architecture Designer / worker role integration |
| Phase 8 | Release gates, Doctor bundle, packaging |

Critical serialization:

1. `packages/contracts` before implementation packages.
2. DB schema before storage/EventStore tests.
3. ToolRegistry + PermissionEngine before side-effect tools/workers.
4. Provider/context contracts before agent prompts.
5. IPC before real worker E2E.
6. Projection contracts before TUI implementation.

ADR alignment checkpoints:

- Monorepo/package boundaries align with the package and C4 decisions.
- IPC/worker process choices align with NDJSON child-process ADRs.
- Permission template and tool trust decisions align with security/capability ADRs.
- Doctor fix/bundle and restore behavior align with decisions-round-2/3.

## 17. Validation Overview

Minimum release-level validation:

```bash
bun install
bun run typecheck
bun test
bun run lint
bun run air -- doctor --read-only
bun run air -- e2e worker-fixture
bun run air -- fixture cpp-build-test
bun run air -- e2e cpp-fix-fixture
bun run air -- e2e cpp-debug-review-fixture
bun run air -- capability validate --all
bun run release:check
```

Validation categories:

| Category | Purpose | Examples |
|---|---|---|
| Unit | contract/schema/repository/tool logic | contracts, EventSchemaRegistry, PermissionEngine, path classifier |
| Integration fixture | deterministic local runtime flows | storage, EventStore, Scheduler graph, IPC fixture, C++ fixture |
| E2E real LLM | release-level agent behavior | simple edit, C++ debug/fix/review, architecture review gate |
| UI smoke | TUI/HUD responsiveness and projection rendering | tui startup, permission prompt, evidence view, HUD presets |
| Release gate | combined Linux tier-1 release readiness | `bun run release:check` |

Additional Alpha UX gates:

```bash
bun run air -- e2e direct-mode-fixture
bun test packages/runtime --filter restore
bun run air -- doctor --fix --dry-run
bun run air -- doctor --bundle
bun run air -- tui-smoke --project <fixture>
```

Skipped gates must record:

- why skipped;
- evidence available;
- risk;
- follow-up task.

## 18. Open Items for Detailed Design

The following are intentionally left for detailed design and class diagram freeze:

1. exact TypeScript file/module layout per package;
2. final class method signatures beyond public contracts;
3. repository implementation classes and query helpers;
4. EventStore domain projection handler table;
5. WorkerProtocol implementation state machine;
6. CLI command parser structure;
7. TUI component tree and state subscriptions;
8. fixture definitions and test harness layout;
9. release package resource manifest;
10. concrete ProviderAdapter implementation sequence;
11. ADR numbering for design-stage provider/model immutability;
12. exact UI mockups for permission, blocker, evidence, and HUD surfaces.

## 19. Readiness Decision

The system overview design is complete enough to proceed to detailed design / class diagram freeze after this multi-model audit repair.

Readiness basis:

- P0/P1/P2 overview audit gaps that do not require user decisions are resolved in this document;
- architecture source precedence is stable and all 24 frozen baselines are listed;
- contracts/schema/runtime semantics/error taxonomy/security/capability/artifact models are aligned at overview level;
- system containers and runtime components have clear responsibilities and dependency rules;
- Main Agent, Scheduler, worker, IPC, tool, permission, event, context, and recovery flows have implementation-facing overview semantics;
- implementation phases and serialization points are identified;
- validation gates are explicit.
