- system-overview-design.md: repaired with P0/P1/P2 gaps resolved, all 24 frozen baselines listed, error taxonomy, global ~/.air, IPC, TaskSpec/WorkerResult, PromptLayer, PermissionEngine, RuntimeEvent, state machines, capability trust, artifact naming, operations - Four cross-verification audit reports (GPT-5, MIMO 2.5, Opus 4.7, DeepSeek V4 Pro) - Three regression reviews (R1: initial repair closure, R2: second pass with PromptLayer L9 wording found, R3: full PromptLayer alignment verified) - AGENTS.md, plan.md, todo.md synchronized Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
44 KiB
AirCoding V1.0.0 Alpha System Overview Design
Date: 2026-05-29 Status: System overview design for V1.0.0 Alpha after multi-model audit repair 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:
AirPlan/docs/analysis/requirements.mdAirPlan/docs/architecture/baselineV1.mdAirPlan/docs/architecture/solution-architecture.mdAirPlan/docs/architecture/interface-contracts-v1.mdAirPlan/docs/architecture/db-schema-v1.mdAirPlan/docs/architecture/event-registry-v1.mdAirPlan/docs/architecture/runtime-semantics-v1.mdAirPlan/docs/architecture/c4/module.mdAirPlan/docs/architecture/c4/code-view.mdAirPlan/docs/architecture/main-agent-state-machine.mdAirPlan/docs/architecture/scheduler-state-machine-v1.mdAirPlan/docs/architecture/scope-escalation-v1.mdAirPlan/docs/architecture/security-model-v1.mdAirPlan/docs/architecture/capability-trust-v1.mdAirPlan/docs/architecture/provider-capability-matrix-v1.mdAirPlan/docs/architecture/prompt-layering-v1.mdAirPlan/docs/architecture/artifact-naming-v1.mdAirPlan/docs/architecture/error-taxonomy-v1.mdAirPlan/docs/architecture/tool-registry-v1.mdAirPlan/docs/architecture/cross-platform-matrix-v1.mdAirPlan/docs/architecture/decisions-round-1.mdAirPlan/docs/architecture/decisions-round-2.mdAirPlan/docs/architecture/decisions-round-3.mdidea.md
Current-stage review inputs:
AirPlan/docs/architecture/gpt5概要设计审查.mdAirPlan/docs/architecture/mimo2.5概要设计审查.mdAirPlan/docs/architecture/Opus4.7概要设计审查.mdAirPlan/docs/architecture/DeepSeek概要设计审查.mdAirPlan/docs/architecture/多模型三视角审查联合评估.mdAirPlan/plan.mdAirPlan/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:
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
~/.airuser state and project-local.airstate; - stable
project_idUUID 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:
- Event-driven runtime with SQLite recovery.
- ToolRegistry + PermissionEngine for all side effects.
- Anthropic canonical internal message format with provider adapter boundary.
- 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
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
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:
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:
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
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:
discovered
→ validated
→ doctor_checked
→ enabled
→ registered
→ active
→ disabled | failed | updated
Trust levels:
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:
~/.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:
<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:
- Durable event insert and corresponding domain update occur in one SQLite transaction.
- EventBus is never recovery source of truth.
foreign_keys = OFFis compensated by repository-level invariant checks and startup orphan scans.- Artifact files use temp-write → hash/size → atomic rename → DB record.
ui_stateis not source of truth for runtime state.- Messages store Anthropic canonical JSON in
content_jsonwithcanonical_format = "anthropic". assistant.message.startedwrites/updatesmessage_drafts;assistant.message.createdinserts the finalmessagesrow and deletes the draft.- V1 does not use a separate
message_partssource-of-truth table. - Closed enum values are controlled by
db-schema-v1.mdand require migration review when changed.
FK-off application invariants:
tasks.session_idmust reference an existingsessions.id.task_attempts.task_idmust reference an existingtasks.id.agents.task_idmust reference an existingtasks.idwhen not null.tool_runs.task_idandtool_runs.agent_idmust reference existing rows when not null.command_runs.task_id,command_runs.agent_id, andcommand_runs.tool_run_idmust reference existing rows when not null.workspaces.task_idandworkspaces.agent_idmust reference existing rows when not null.diagnostics.command_run_idanddiagnostics.artifact_idmust reference existing rows when not null.evidence_refsforeign 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:
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:
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
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:
id
type
version
timestamp
session_id
project_id?
source
route[]
payload
Rules:
routeis append-only. Forwarders append their segment and never rewrite earlier entries.route_textin SQLite is derived fromroute.join("/")for indexing.- EventStore decides durable vs ephemeral persistence by event type; producers do not decide ad hoc.
- Payload schema changes require incrementing the event
versionfor that event type. - Durable event insert and same-session domain projection happen in one SQLite transaction.
- Durable events are published to EventBus only after commit.
- 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:
error_id
kind
severity
message
detail?
retryability
semantic_signature
cause_ref?
cause_refs?
user_action?
metadata?
Error kinds:
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:
info | warning | error | fatal
Retryability:
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
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:
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.changedand route to Scheduler/Architecture Designer according to impact.
10.3 Scheduler state machine
Scheduler states:
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
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
/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
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:
ToolDefinitionincludes input/output schemas, category, permissions, and streaming flag.shell.runis the AirCoding runtime equivalent of a controlled Bash execution primitive.call()consumes streaming internally and returns the finalToolResultEnvelope.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:
WorkerResult
→ Reviewer
→ Scheduler completes/retries/blocks based on ReviewerResult and evidence
Architecture-sensitive work adds an Architecture Designer gate:
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:
- public function/class/module interface changes;
- DB schema or persisted data shape changes;
- IPC/event/tool/provider contract changes;
- package dependency direction or component responsibility changes;
- runtime semantics, security model, capability trust, or permission boundary changes;
- ADR/C4/plan/todo architecture artifacts must change;
- Reviewer emits
category = "architecture"; - worker returns architecture/interface blocker;
- phase completion requires architecture consistency review;
- release/final completion requires full architecture consistency review.
Scope impact levels:
implementation
interface
architecture
product
permission
environment
policy
Gate result rule:
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
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.jsonis 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-cppperforms 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
.airconfiguration.
10.9 Claude Code execution discipline
All code-changing execution paths must preserve these runtime-level constraints:
- Read before edit:
fs.edit/fs.patchrequire a recent read observation or expected file hash. - Exact edit:
old_stringmust match exactly; non-unique matches fail unless replace-all is explicit. - Conservative patching: changes stay inside TaskSpec scope and write area.
- No unrelated refactors: workers must not broaden scope to improve nearby code opportunistically.
- Verification before completion: code-changing WorkerResult cannot be
completedunless required verification passed, or skipped verification is explicitly allowed with evidence/risk. - Evidence-backed closure: diffs, command outputs, diagnostics, artifacts, or screenshots are linked through evidence refs.
- Block instead of improvising when product, interface, architecture, permission, environment, or policy decisions are missing.
10.10 TaskSpec and WorkerResult overview
TaskSpec field families:
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:
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:
id
direction
kind
timestamp
session_id
agent_id
correlation_id?
protocol_version
payload
Handshake:
- parent spawns worker process;
- parent sends
agent.startafter spawn; - worker responds with
worker.readyincludingprotocol_version; - parent validates protocol version;
- worker executes role loop;
- 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 | success |
| 1 | task failed |
| 2 | worker crashed |
| 3 | protocol error |
| 4 | cancelled |
| 5 | permission/policy blocked |
Workers never write SQLite directly and never perform side effects outside parent-mediated tools.
12. Permission and Security Overview
Permission evaluation order:
- tool capability declaration;
- permission profile;
- TaskSpec scope allowed/denied paths;
- path/command/network risk classification;
- credential/system-sensitive override;
- user prompt workflow.
Permission actions:
allow | deny | ask_user | block | refuse | announce_then_run
Grant scopes:
none | once | session | project | global
Path risk categories:
project_source
project_build_output
project_air_shared
project_air_local
project_git_internal
outside_project
credential_or_secret
system_sensitive
Command risk categories:
read_only
build
test
static_analysis
git_read
git_write
destructive
network
system_sensitive
credential_sensitive
Boundary rules:
- Path policy uses realpath normalization before allow/deny checks; symlink escapes are not allowed by string-prefix checks.
.git/internals are protected from arbitrary write tools; Git operations go through git tools.- Build output directories are lower risk than source but still remain scoped by TaskSpec and destructive-command analysis.
- Runtime-owned writes inside
.air/local/are internal service operations, but user-visible or destructive access still follows permission policy. sudodoes not automatically become high risk by string alone; command intent, target path, and system sensitivity determine risk, with safe prompts when uncertain.- Static high-risk command patterns are deny/ask by default, with LLM escape hatch only through explicit PermissionEngine reasoning and prompt flow.
- Project-outside writes require backup where policy says
backup_required, usually through.air/local/backups/. - Credentials and system-sensitive actions override broad session/project/global allows.
- Project-level allow does not override TaskSpec scope.
- 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_refand 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:
- ContextAssembler may request compaction but does not compact itself.
- Scheduler creates
compacttask. - Compactor snapshots immutable message range.
summary.createdinserts the summaries row.context.compaction.completedreferences the created summary.- 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:
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
ProjectionClientand 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_runvisualization; - blocker reports;
- evidence display;
- HUD presets: Full / Essential / Minimal;
- read-only provider/model status display;
- CLI command catalog:
resume,compact,history,session list, read-onlyprovider 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:
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:
- verify Bun runtime;
- verify SQLite availability;
- verify basic shell access;
- verify
.air/writability; - 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.logis user-facing and contains redacted operational errors and recovery summaries.air.developer.logis 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:
- Detect
schema_meta.schema_versionon session/project DB open. - If migration is needed, build a migration plan and risk summary.
- Create backup through
.air/local/backups/before migration when required. - Ask user for destructive or non-trivial migration confirmation.
- Apply migration transactionally when SQLite scope allows.
- Emit migration evidence and recovery instructions.
- 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:
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:
packages/contractsbefore implementation packages.- DB schema before storage/EventStore tests.
- ToolRegistry + PermissionEngine before side-effect tools/workers.
- Provider/context contracts before agent prompts.
- IPC before real worker E2E.
- 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:
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:
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:
- exact TypeScript file/module layout per package;
- final class method signatures beyond public contracts;
- repository implementation classes and query helpers;
- EventStore domain projection handler table;
- WorkerProtocol implementation state machine;
- CLI command parser structure;
- TUI component tree and state subscriptions;
- fixture definitions and test harness layout;
- release package resource manifest;
- concrete ProviderAdapter implementation sequence;
- ADR numbering for design-stage provider/model immutability;
- 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.