Initial commit: AirCoding V1.0.0 Alpha architecture baseline
Complete architecture document set with multi-model review remediation: - Frozen interface contracts, runtime semantics, DB schemas - Event/tool/error/provider registries - Scheduler and main agent state machines - C4 module/code views, solution architecture, baseline V1 - Multi-model review reports and joint assessment - Phase-gate remediation complete (P0/P1/P2/UX resolved) - Implementation plan with T-000A through T-045 - Reference folders kept as placeholders only
This commit is contained in:
365
AirPlan/docs/architecture/DeepSeekV4Pro三视角审查.md
Normal file
365
AirPlan/docs/architecture/DeepSeekV4Pro三视角审查.md
Normal file
@@ -0,0 +1,365 @@
|
||||
# DeepSeek V4 Pro 三角度架构审查报告
|
||||
|
||||
Date: 2026-05-28
|
||||
Status: Third-round architecture review using DeepSeek V4-Pro model
|
||||
Reviewer: DeepSeek V4-Pro (1M context)
|
||||
Scope: All architecture documents under `AirPlan/docs/architecture/`
|
||||
|
||||
## 审查背景
|
||||
|
||||
当前架构文档集(26 个文件)是第二轮 MIMO2.5 审查后的修正版本。第二轮审查发现 6 项阻塞级和 10 项应修复问题,本文件已独立输出为 `MIMO2.5三视角审查.md`。
|
||||
|
||||
本轮审查旨在用新模型独立评估架构质量,覆盖三个视角:
|
||||
1. 架构设计师 — 概念完整性、设计一致性和边界清晰性
|
||||
2. 软件开发工程师 — 可编译性、类型完整性和实现可行性
|
||||
3. 用户 — 与原始需求的对齐程度
|
||||
|
||||
---
|
||||
|
||||
## 1. 架构设计师视角
|
||||
|
||||
### 1.1 概念完整性
|
||||
|
||||
AirCoding V1.0.0 Alpha 架构展示了良好的概念完整性。核心原则(项目本地状态、事件驱动 + SQLite 恢复、ToolRegistry/PermissionEngine 作为统一副作用边界、独立子进程 worker)在所有文档中保持连贯。
|
||||
|
||||
**核心架构决策评价:**
|
||||
|
||||
| 决策 | 质量 | 理由 |
|
||||
|---|---|---|
|
||||
| EventIngestor 作为事件摄入边界 | 优秀 | 解决了 EventStore 职责过宽问题,EventStore 不再隐式触发业务动作 |
|
||||
| 边列表任务依赖模型 | 优秀 | 完整表达 hard/soft/conflict/serialization,Scheduler 可动态追加持久化冲突边 |
|
||||
| IPC 协议含 tool.call/result | 优秀 | 使独立 worker 进程能通过父进程 ToolRegistry/PermissionEngine 安全调用工具 |
|
||||
| TUI 只依赖 ProjectionClient | 优秀 | TUI 不导入 runtime 内部,边界清晰 |
|
||||
| ProviderManager 在 packages/llm | 清晰 | runtime 通过 facade 调用 LLM,不耦合 provider 实现 |
|
||||
| snake_case 命名统一 | 务实 | 避免序列化层,DB/event/tool/contract 一致 |
|
||||
|
||||
### 1.2 依赖方向分析
|
||||
|
||||
包级依赖方向已收敛为单向无循环图:
|
||||
|
||||
```text
|
||||
contracts
|
||||
↑
|
||||
cli → runtime → llm (ProviderManager facade)
|
||||
cli → tui → contracts (ProjectionClient only)
|
||||
cli → toolchain-cpp
|
||||
runtime → contracts
|
||||
tui → contracts
|
||||
llm → contracts
|
||||
toolchain-cpp → contracts
|
||||
|
||||
runtime 不依赖 tui
|
||||
tui 不依赖 DB/EventBus/runtime 内部
|
||||
toolchain-cpp 不直接依赖 runtime 或 llm
|
||||
```
|
||||
|
||||
服务级依赖方向也已澄清:
|
||||
|
||||
- Scheduler → WorkerManager(单向)
|
||||
- EventIngestor → EventStore/EventBus(单向)
|
||||
- DoctorService → CapabilityRegistry → ToolRegistry(单向)
|
||||
- CapabilityRegistry 不依赖 DoctorService(已修正)
|
||||
|
||||
### 1.3 跨文档一致性评估
|
||||
|
||||
当前文档集存在两类跨文档问题:
|
||||
|
||||
#### 1.3.1 已收敛的领域
|
||||
|
||||
- IPC 协议:interface-contracts 已定义完整 envelope 类型,baseline 引用之
|
||||
- Permission 模型:interface-contracts、security-model、scope-escalation、event-registry 使用一致 action+grant_scope
|
||||
- Error 模型:interface-contracts、tool-registry、event-registry 统一使用 AirError
|
||||
- Task 依赖:interface-contracts、scheduler-state-machine、event-registry、baseline 统一使用边列表
|
||||
- 文档优先级:solution-architecture §2 已定义 8 级 precedence rule
|
||||
|
||||
#### 1.3.2 仍有不一致的领域
|
||||
|
||||
| 问题 | 涉及文档 | 严重度 |
|
||||
|---|---|---|
|
||||
| error-taxonomy 中 cause_ref 为扁平字段对象,interface-contracts 中为 EntityRef | error-taxonomy-v1 vs interface-contracts-v1 | 高 |
|
||||
| event-registry 中 EntityRef 内联定义(10 个值),interface-contracts 定义 12 个值 | event-registry-v1 vs interface-contracts-v1 | 高 |
|
||||
| ToolCategory 和 ToolResultEnvelope 在 interface-contracts 和 tool-registry 重复定义 | interface-contracts-v1 vs tool-registry-v1 | 中 |
|
||||
| DebugKnowledgeStore 和 LearnedMemoryStore 接口缺失 | runtime-semantics-v1 引用但未定义 | 中 |
|
||||
|
||||
这些已在 MIMO2.5 审查中详细记录,此处不再逐项展开。
|
||||
|
||||
### 1.4 架构风险矩阵
|
||||
|
||||
| 风险 | 概率 | 影响 | 现有缓解措施 | 剩余风险 |
|
||||
|---|---|---|---|---|
|
||||
| 跨 DB/文件事务原子性不足 | 中 | 中 | outbox/compensation 模型 | 低 — 已定义恢复扫描 |
|
||||
| worker 工具调用链路过长 | 低 | 中 | NDJSON IPC + correlation_id | 低 — 协议完整性好 |
|
||||
| Compaction 策略过于复杂 | 中 | 低 | copy-on-write + 显式回退引用 | 低 — 设计清晰 |
|
||||
| C++ 工具链覆盖不够 | 中 | 中 | cppcheck+clangd+CMake+Ninja/Make | 中 — 需要真实项目验证 |
|
||||
| 插件权限绕过 | 低 | 高 | capability trust model + PermissionEngine | 低 — 边界充分 |
|
||||
|
||||
### 1.5 架构师结论
|
||||
|
||||
**可以进入概要设计阶段**。架构方向正确,依赖方向已收敛,包边界清晰。剩余 4 项跨文档不一致问题应在进入概要设计前修复,但都属于工程一致性层面,不影响设计方向。
|
||||
|
||||
---
|
||||
|
||||
## 2. 软件工程师视角
|
||||
|
||||
### 2.1 可编译性评估
|
||||
|
||||
`packages/contracts` 在修复以下问题后可编译:
|
||||
|
||||
#### 2.1.1 类型定义问题
|
||||
|
||||
**E1. `TaskInsert = TaskRecord` 类型不安全**
|
||||
|
||||
`interface-contracts-v1.md` 第 240 行:`export type TaskInsert = TaskRecord`。这意味着调用方创建任务时必须提供所有 Record 字段,包括服务器生成的 `created_at`、`retry_count`、`status`。正确做法是定义子集类型。
|
||||
|
||||
**建议修复:**
|
||||
```ts
|
||||
export type TaskInsert = Omit<TaskRecord, "created_at" | "retry_count"> & {
|
||||
status?: TaskStatus // defaults to "pending"
|
||||
retry_count?: number // defaults to 0
|
||||
}
|
||||
```
|
||||
|
||||
**E2. `JsonSchema<T>` 泛型参数 T 未使用**
|
||||
|
||||
第 41 行:`export type JsonSchema<T = unknown> = JsonObject`。T 在类型体中从未引用,是 phantom type,不提供任何编译时安全检查。要么移除泛型参数,要么定义品牌化类型。
|
||||
|
||||
**建议修复:**
|
||||
```ts
|
||||
declare const JsonSchemaBrand: unique symbol
|
||||
export type JsonSchema<T = unknown> = JsonObject & { [JsonSchemaBrand]: T }
|
||||
|
||||
// 用于测试/类型推导
|
||||
export type InferSchemaType<T extends JsonSchema<unknown>> =
|
||||
T extends JsonSchema<infer U> ? U : never
|
||||
```
|
||||
|
||||
**E3. `FollowUpTask.type` 引用不存在的 `TaskType` 成员**
|
||||
|
||||
`FollowUpTask.type` 定义为 `TaskType | "docs"`,但 `TaskType` 不含 `"docs"`。`"docs"` 作为类型字符串存在于类型标注中,但 Scheduler 收到 `type: "docs"` 时无法创建合法的 `TaskSpec.type`(它是 `TaskType`,不含 `"docs"`)。
|
||||
|
||||
**建议修复:** 将 `"docs"` 加入 `TaskType`:`TaskType = ... | "docs"`
|
||||
|
||||
#### 2.1.2 缺失接口
|
||||
|
||||
**E4. `DebugKnowledgeStore` 和 `LearnedMemoryStore` 无任何接口定义**
|
||||
|
||||
`runtime-semantics-v1.md` §6.3-6.4 引用了这两个关键服务,但 `interface-contracts-v1.md` 中没有任何对应接口。开发者实现 §6 的跨 DB 事务语义时没有契约参照。
|
||||
|
||||
**E5. `CompactionPolicy`、`PromptLayer`、`PromptLayerLoader` 无任何接口定义**
|
||||
|
||||
`c4/code-view.md` §4 列出了 `CompactionPolicy.ts` 和 `PromptLayerLoader.ts`,`prompt-layering-v1.md` 详细描述了 L0-L9 分层逻辑。但 `interface-contracts-v1.md` §16 只定义了极简的 `ContextAssembler` 输入输出,`PromptLayer` 和 `CompactionPolicy` 的类型形状完全空白。
|
||||
|
||||
#### 2.1.3 语义不完整
|
||||
|
||||
**E6. `PathPolicy` 类型仅有 `allow/deny`,缺失 `source` 元数据**
|
||||
|
||||
`interface-contracts-v1.md` 中 `PathPolicy` 定义为 `{ allow?: string[], deny?: string[] }`,但 `security-model-v1.md` 和 `runtime-semantics-v1.md` 要求路径评估考虑 "从哪个角色/配置文件来的"。`PathPolicy` 需要 `source` 元数据来表达这个语义。
|
||||
|
||||
**E7. `PermissionEngine.record` 返回 `Promise<void>` 无失败路径**
|
||||
|
||||
如果记录权限决策失败(磁盘满、DB 锁),调用方无法得知。这违反 "证据优先" 架构原则。
|
||||
|
||||
**建议修复:** 返回 `Promise<Result<void, AirError>>` 或指定抛出的类型化错误。
|
||||
|
||||
**E8. `ProjectionStore.apply` 接受 `RuntimeEvent<unknown>` — 无类型窄化**
|
||||
|
||||
实现者需要猜测哪些事件触发投影更新。当前设计依赖运行时类型检查,而 contracts 包应该为关键投影提供编译时保证。
|
||||
|
||||
**E9. `EventBus.subscribe` handler 异常行为未定义**
|
||||
|
||||
如果订阅 handler 抛出异常:EventBus 吞掉错误?传播给发布者?终止订阅?contracts 未定义。
|
||||
|
||||
**建议:** 明确 "handler 异常被 EventBus 吞掉并记录到 developer log,不传播给发布者,不终止订阅"。
|
||||
|
||||
#### 2.1.4 类型别名一致性
|
||||
|
||||
**E10. 多处缺少 branded ID 类型**
|
||||
|
||||
`SchedulerWavePlan.wave_id` 是 `string`,而非 `WaveID`。其他标识符都用了品牌化类型(`TaskID`、`AgentID` 等),`wave_id` 应该一致。
|
||||
|
||||
### 2.2 可测试性评估
|
||||
|
||||
**优点:**
|
||||
- `Clock` 和 `IdGenerator` 接口设计良好,支持时间/ID 确定性测试
|
||||
- `TransactionHandle` 接口允许测试事务边界
|
||||
- Repository 接口支持 mock/stub
|
||||
- EventBus/EventStore/EventIngestor 边界清晰,可独立测试
|
||||
|
||||
**不足:**
|
||||
- `ToolExecutor.execute` 返回 `AsyncIterable | Promise` 未品牌化联合,测试需 duck-type
|
||||
- `ProviderAdapter.complete` 返回值相同问题
|
||||
- 无契约定义 IPC mock/stub 边界
|
||||
|
||||
### 2.3 可部署性评估
|
||||
|
||||
**优点:**
|
||||
- `Clock` 抽象使时间可控
|
||||
- `IdGenerator` 抽象使 ID 可预测
|
||||
- `TransactionManager` 抽象使事务边界可测试
|
||||
- binary tarball 分发策略清晰
|
||||
|
||||
**不足:**
|
||||
- 无环境变量/配置文件 schema 定义(除 `~/.air/models.yaml` 外)
|
||||
- 无 Docker/容器化分发方案
|
||||
|
||||
### 2.4 工程师结论
|
||||
|
||||
**必须修复(阻塞实现):E1、E3、E4、E5**
|
||||
|
||||
**应在实现前修复:E2、E6、E7、E8、E9、E10**
|
||||
|
||||
其余问题可在实现过程中逐步处理。interface-contracts-v1.md 是最大的单一阻塞文件 — 一旦它稳定,package 边界就稳定了。
|
||||
|
||||
---
|
||||
|
||||
## 3. 用户视角
|
||||
|
||||
### 3.1 核心需求对齐表
|
||||
|
||||
按 AirCoding 原始概念文件 (`idea.md`)、讨论中确立的决策和 VibeBox 衍生分支重新评估:
|
||||
|
||||
| # | 原始需求 | 当前架构状态 | 对齐度 |
|
||||
|---|---|---|---|
|
||||
| 1 | 自有 AI coding agent/runtime,非 Claude Code 插件包装 | 独立架构,自有运行时/调度器/工具系统/权限引擎 | 完全 |
|
||||
| 2 | Claude Code 级执行层代码质量 | D-059 + runtime-semantics §9(read-before-edit token、exact edit、completion gate) | 完全 |
|
||||
| 3 | OpenCode TUI 复用(UI 风格,非业务状态) | `@opentui/solid`,TUI 只消费 ProjectionClient,不导入 runtime 内部 | 完全 |
|
||||
| 4 | Hermes-style 经验挖掘/技能/Curator | ExperienceMiner 角色、candidate→promotion→rollback 生命周期、Skill/SKILL.md 格式 | 充分 |
|
||||
| 5 | 事件驱动 + SQLite 恢复 | EventBus 实时 + EventStore 持久化 + ProjectionStore 投影 + restart recovery | 完全 |
|
||||
| 6 | 独立子进程 worker + NDJSON IPC | Bun child processes + 完整 IPC envelope(control/event/log/tool.call/result/stream/worker.result/checkpoint/error) | 完全 |
|
||||
| 7 | C++ 为第一个深度语言 | `toolchain-cpp` 完整工作流(detect/configure/build/static-analysis/test/debug/fix/review/verify) | 完全 |
|
||||
| 8 | 项目本地状态可携带 | `.air/shared`(git-shareable)+ `.air/local`(project-local) | 完全 |
|
||||
| 9 | 多 agent 调度(Scheduler + TaskGraph) | Scheduler state machine + 边列表依赖 + write-area 冲突 + wave dispatch + merge coordination | 完全 |
|
||||
| 10 | 权限模型(分层确认、高权限 announce_then_run) | PermissionEngine + action + grant_scope + layered checks + 凭据/系统敏感边界 | 完全 |
|
||||
| 11 | AirConsole 模块化工作流 | AirPlan/AGENTS.md 入口 + AirArc/AirEng/AirDo 工作流 + AirDbg/AirNDB/AirSDB/AirXDB 调试插件 | 完全 |
|
||||
| 12 | VibeBox 下位分支(ARM Linux appliance) | `branchvibebox/` 独立 baseline + feasibility plan + Electron 模板 | 完全 |
|
||||
| 13 | 不可半成品 MVP,目标 V1.0.0 Alpha | 范围含完整 C++ 开发闭环 + 插件/能力基础 + 发布验证 | 完全 |
|
||||
| 14 | 参考 Codex 工具/OpenAI 工具 | `reference/openai-codex/`,tool-registry 含 Codex 风格 tool breadth | 充分 |
|
||||
| 15 | 参考 Anthropic Claude Skills | `reference/anthropic-skills/`,SKILL.md 格式在 ExperienceMiner 中引用 | 充分 |
|
||||
|
||||
### 3.2 设计质量评估
|
||||
|
||||
**满足/超越需求的领域:**
|
||||
|
||||
1. **EventIngestor 引入**:比原始需求更清晰地分离了事件摄入与持久化,是超出原始讨论的架构改进
|
||||
2. **边列表任务依赖**:从原始讨论的 "hard/soft 数组" 演进到 `(hard|soft|conflict|serialization)` 边列表,表达能力更强
|
||||
3. **IPC 协议**:从原始讨论的 "event/control/log" 三个 kind 扩展到 9 个 kind,覆盖了 worker 的完整通信需求
|
||||
4. **跨 DB 事务语义**:主动定义了 debug-records.db、learned-memory.db 的 outbox/compensation 模型
|
||||
5. **执行原语强化**:从 "原则" 级别提升到 "read observation token required for edit" 的强制契约级别
|
||||
|
||||
**与用户意图一致的权衡:**
|
||||
|
||||
| 权衡 | 用户意图 | 架构决策 | 一致性 |
|
||||
|---|---|---|---|
|
||||
| 进度优先 vs 完美 | 用户多次表示 "先确定再完善" | 定义清晰的文档优先级,允许渐进式完善 | 一致 |
|
||||
| 复用 vs 自研 | "能复用就复用,不能就 AI 生成" | TUI 复用 OpenTUI,核心运行时自研 | 一致 |
|
||||
| 权限 vs 自动化 | "高权限模式 auto-run,凭据必须确认" | action + grant_scope 模型 | 一致 |
|
||||
| 复杂度 vs 可用性 | "V1.0.0 Alpha 不是半成品" | 完整 C++ 工作流 + 插件基础在范围内 | 一致 |
|
||||
|
||||
### 3.3 用户体验路径
|
||||
|
||||
最终开发者体验路径:
|
||||
|
||||
```text
|
||||
$ air init # 一键初始化项目
|
||||
$ air # 启动 TUI/HUD
|
||||
> 帮我修复 src/core/parser.cpp 的编译错误
|
||||
→ Main Agent 分类 → Scheduler 创建 Executor 任务
|
||||
→ Executor 读取文件 → 精确编辑 → 构建 → 测试
|
||||
→ Reviewer 审查 → 通过 → 合并 workspace
|
||||
→ 展示 diff + 构建/测试证据
|
||||
```
|
||||
|
||||
这个路径在架构中完全支持,从 CLI 到 TUI 到 Scheduler 到 tools 到 workspace merge 到 evidence 展示都有覆盖。
|
||||
|
||||
### 3.4 用户视角结论
|
||||
|
||||
**架构完全对齐原始需求,无方向性偏差。** 每一个关键决策都可以追溯到讨论中明确的选择。
|
||||
|
||||
---
|
||||
|
||||
## 4. 三视角综合结论
|
||||
|
||||
### 4.1 阻塞实现的问题(6 项)
|
||||
|
||||
这些必须在进入 `packages/contracts` 编码前解决:
|
||||
|
||||
| ID | 问题 | 涉及文档 | 修复方向 |
|
||||
|---|---|---|---|
|
||||
| E1 | `TaskInsert = TaskRecord` 不安全 | interface-contracts-v1 | 定义 Omit 子集类型 |
|
||||
| E3 | `FollowUpTask.type` 含 `"docs"` 但 `TaskType` 无 | interface-contracts-v1 | 将 docs 加入 TaskType |
|
||||
| E4 | `DebugKnowledgeStore` / `LearnedMemoryStore` 缺失 | interface-contracts-v1 | 添加对应接口 |
|
||||
| E5 | `PromptLayer` / `CompactionPolicy` / `PromptLayerLoader` 缺失 | interface-contracts-v1 | 添加对应接口 |
|
||||
| E9 | `EventBus.subscribe` handler 异常行为未定义 | interface-contracts-v1 | 明确吞掉+记录 |
|
||||
| B3* | `debug-records.db` / `learned-memory.db` 无 DDL | db-schema-v1 | 补充 DDL |
|
||||
|
||||
> *B3 来自上一轮审查,本节确认仍然有效。
|
||||
|
||||
### 4.2 应在实现前修复的问题(6 项)
|
||||
|
||||
| ID | 问题 | 涉及文档 | 修复方向 |
|
||||
|---|---|---|---|
|
||||
| E2 | `JsonSchema<T>` phantom generic | interface-contracts-v1 | 品牌化或移除 |
|
||||
| E6 | `PathPolicy` 缺少 source 元数据 | interface-contracts-v1 | 添加 source 字段 |
|
||||
| E7 | `PermissionEngine.record` 无错误路径 | interface-contracts-v1 | 返回 Result 类型 |
|
||||
| E8 | `ProjectionStore.apply` 无类型窄化 | interface-contracts-v1 | 添加事件类型文档 |
|
||||
| E10 | `wave_id` 非品牌化 ID | interface-contracts-v1 | 添加 WaveID 类型 |
|
||||
| B1* | error-taxonomy cause_ref 冲突 | error-taxonomy-v1 | 统一为 EntityRef |
|
||||
|
||||
> *B1 来自上一轮审查,本节确认仍然有效。
|
||||
|
||||
### 4.3 可接受延迟的问题(4 项)
|
||||
|
||||
| 问题 | 理由 |
|
||||
|---|---|
|
||||
| error-taxonomy 和 event-registry 中的 EntityRef 内联定义 | 编译时可通过 import 解决,不影响核心架构 |
|
||||
| ToolCategory/ToolResultEnvelope 重复定义 | 编译时结构兼容,仅需一次 import 修复 |
|
||||
| 无 Docker 分发方案 | V1.0.0 Alpha 仅需 binary tarball |
|
||||
| 无环境变量 schema | 实现时可后期补充 |
|
||||
|
||||
### 4.4 架构质量评分
|
||||
|
||||
| 维度 | 评分 | 说明 |
|
||||
|---|---|---|
|
||||
| 概念完整性 | 9/10 | 核心原则一致,包边界清晰 |
|
||||
| 跨文档一致性 | 7/10 | 大部分已收敛,6 项不一致待修复 |
|
||||
| 可编译性 | 7/10 | 修复 E1/E3 后可编译,修复 E4/E5 后完整 |
|
||||
| 可测试性 | 8/10 | Clock/IdGenerator 抽象好,ToolExecutor 返回值待改进 |
|
||||
| 可部署性 | 7/10 | binary tarball 清晰,Docker 可选 |
|
||||
| 需求对齐度 | 10/10 | 所有原始需求在架构中均有对应设计 |
|
||||
| 平均 | **8.0/10** | 充分进入概要设计阶段 |
|
||||
|
||||
### 4.5 与 MIMO2.5 审查的比较
|
||||
|
||||
| 维度 | MIMO2.5 | DeepSeek V4 Pro |
|
||||
|---|---|---|
|
||||
| 发现问题数 | 16 (6B+10S) | 16 (6E-critical + 6E-should + 4E-ok) |
|
||||
| 关键分歧 | — | `ForeignKeys` 问题(MIMO2.5 视为 S8),本审查认为已有合理工程解释 |
|
||||
| 新发现 | — | E6 (PathPolicy 缺少 source)、E9 (EventBus 异常行为) |
|
||||
| 共识 | B1-B3/B5/B6/S1-S7 相同 | 一致 |
|
||||
| 总体评分 | — | 8.0/10 |
|
||||
|
||||
DeepSeek V4 Pro 与 MIMO2.5 两个独立模型在阻塞问题识别上高度一致,增加了审查结论的置信度。
|
||||
|
||||
---
|
||||
|
||||
## 5. 下一步行动
|
||||
|
||||
### 立即行动(进入概要设计前)
|
||||
|
||||
1. 修复 E1:`TaskInsert` 改为 Omit 子集
|
||||
2. 修复 E3:`TaskType` 加入 `"docs"`
|
||||
3. 修复 E4/E5:补充 `DebugKnowledgeStore`、`LearnedMemoryStore`、`PromptLayer`、`CompactionPolicy` 接口
|
||||
4. 修复 E9:明确 `EventBus.subscribe` handler 异常行为
|
||||
5. 修复 B3:补充 `debug-records.db` / `learned-memory.db` DDL
|
||||
6. 修复 B1:`error-taxonomy` 中 `cause_ref` 统一为 `EntityRef`
|
||||
|
||||
### 概要设计中同步
|
||||
|
||||
7. 修复 E2/E6/E7/E8/E10
|
||||
8. 修复跨文档的 EntityRef 和 ToolCategory 重复定义问题
|
||||
9. 产出 `系统概要设计.md`
|
||||
10. 产出 `系统详细设计.md`
|
||||
|
||||
### 总体建议
|
||||
|
||||
**进入概要设计阶段**,先修 6 项立即行动问题,再产出概要设计文档。
|
||||
329
AirPlan/docs/architecture/MIMO2.5三视角审查.md
Normal file
329
AirPlan/docs/architecture/MIMO2.5三视角审查.md
Normal file
@@ -0,0 +1,329 @@
|
||||
# MIMO2.5 三角度架构审查报告
|
||||
|
||||
Date: 2026-05-28
|
||||
Status: Second-round architecture review after major corrections
|
||||
Model: MIMO v2.5 (1M context)
|
||||
Reviewer scope: All architecture documents under `AirPlan/docs/architecture/`
|
||||
|
||||
## 审查背景
|
||||
|
||||
本轮审查基于第一轮审查后的修正结果,包括:
|
||||
|
||||
- 接口契约统一为 `snake_case` 并重写为可实现版本
|
||||
- Permission 统一为 `action + grant_scope` 模型
|
||||
- Error 统一为 `AirError` 嵌入式结构
|
||||
- Task 依赖统一为边列表模型(含 `hard/soft/conflict/serialization`)
|
||||
- IPC 补齐 `tool.call/tool.result/tool.stream/worker.result/worker.checkpoint/protocol.error`
|
||||
- C4/UML 修正 TUI、ProviderManager、EventIngestor、Scheduler/WorkerManager、Capability/Doctor 依赖方向
|
||||
- 新增 `runtime-semantics-v1.md` 明确跨 DB 事务、heartbeat、执行原语等
|
||||
- 目标从半成品 MVP 升级为 V1.0.0 Alpha(含完整 C++ 工作流和插件基础)
|
||||
- 明确 source-of-truth precedence
|
||||
- 消除 VibeBox 双 baseline 歧义
|
||||
|
||||
---
|
||||
|
||||
## 1. 架构师视角
|
||||
|
||||
### 1.1 总体评价
|
||||
|
||||
架构方向正确,修正后的 IPC 协议、依赖方向、EventIngestor、权限模型、任务依赖边列表均已收敛。剩余问题主要是**跨文档一致性**,不是设计方向问题。
|
||||
|
||||
V1.0.0 Alpha 范围合理:完整 C++ 开发闭环、插件/能力基础、TUI/HUD、验证与打包都在范围内。推迟容器沙箱、第三方插件签名、Windows 原生支持等是正确的取舍。
|
||||
|
||||
### 1.2 可接受的取舍
|
||||
|
||||
| 取舍 | 理由 |
|
||||
|---|---|
|
||||
| 项目本地 `.air` 作为状态源 | 本地 coding agent 的合理选择,避免云端耦合 |
|
||||
| Anthropic canonical 内部消息格式 | 简化多 Provider 支持,转换在 adapter 边界 |
|
||||
| EventBus 用于实时、SQLite 用于恢复 | 正确的职责分离,已通过 EventIngestor 澄清 |
|
||||
| 独立 Bun 子进程 + NDJSON IPC | 良好的隔离边界,协议已补齐 |
|
||||
| C++ 作为第一个深度工具链 | 对架构有高验证价值,同时保持 `toolchain-*` 可扩展性 |
|
||||
| Architecture Designer 作为显式升级路径 | 多 agent 编码运行时的合理治理模型 |
|
||||
| `foreign_keys = OFF` | 降低迁移/恢复复杂度,但需要应用层一致性契约(见 S8) |
|
||||
|
||||
### 1.3 已修正的关键问题
|
||||
|
||||
1. **IPC 协议**:已补齐 tool.call/result/stream、worker.result/checkpoint、protocol.error
|
||||
2. **依赖方向**:已消除 Scheduler↔WorkerManager、EventStore↔EventBus、CapabilityRegistry↔DoctorService 循环
|
||||
3. **TUI 边界**:已明确 TUI 只依赖 `ProjectionClient`,不导入 runtime 内部
|
||||
4. **ProviderManager 归属**:已明确在 `packages/llm`,runtime 通过 facade 调用
|
||||
5. **EventIngestor**:已引入作为事件摄入边界,EventStore 不再隐式触发业务动作
|
||||
6. **Permission 模型**:已统一为 `action + grant_scope`
|
||||
7. **Task 依赖**:已改为边列表模型,Scheduler 可动态追加持久化冲突边
|
||||
8. **执行原语**:已通过 `runtime-semantics-v1.md` 定义 read-before-edit token、exact edit、completion gate
|
||||
|
||||
### 1.4 剩余架构关注点
|
||||
|
||||
1. **跨 DB/文件事务**:`runtime-semantics-v1.md` 已定义 outbox/compensation 模型,但 `DebugKnowledgeStore` 和 `learned-memory` 服务接口尚未定义
|
||||
2. **学习/技能生命周期**:`candidate → approval → promotion → rollback` 流程已有文档描述,但缺少形式化状态机
|
||||
3. **项目扫描**:已确认无限递归无排除原则,安全边界(symlink 环、挂载异常)已补充
|
||||
|
||||
---
|
||||
|
||||
## 2. 工程师视角
|
||||
|
||||
### 2.1 阻塞级问题(B1-B6)
|
||||
|
||||
这些问题会阻止 `packages/contracts` 编译为可用 TypeScript 包,或导致运行时失败。
|
||||
|
||||
#### B1. `AirError.cause_ref` 类型冲突
|
||||
|
||||
**位置**:`interface-contracts-v1.md` §3 vs `error-taxonomy-v1.md` §2
|
||||
|
||||
**问题**:
|
||||
- `interface-contracts-v1.md` 中 `cause_ref` 类型为 `EntityRef`(`{ type: EntityType, id: string }` 结构)
|
||||
- `error-taxonomy-v1.md` 中 `cause_ref` 为内联扁平字段对象:`{ event_id?, task_id?, agent_id?, tool_run_id?, command_run_id?, artifact_id?, diagnostic_id? }`
|
||||
- 两个结构体不兼容,消费者期望其中一种格式会与另一种冲突
|
||||
|
||||
**修复方向**:以 `interface-contracts-v1.md` 的 `EntityRef` 为准,更新 `error-taxonomy-v1.md`
|
||||
|
||||
---
|
||||
|
||||
#### B2. `DebugKnowledgeStore` 和 learned-memory 服务接口缺失
|
||||
|
||||
**位置**:`runtime-semantics-v1.md` §6.3, §6.4
|
||||
|
||||
**问题**:
|
||||
- `runtime-semantics-v1.md` 引用 `DebugKnowledgeStore` 作为写入 `debug-records.db` 的服务
|
||||
- 引用未命名的 "ExperienceMiner/Curator service" 写入 `learned-memory.db`
|
||||
- 两个服务在 `interface-contracts-v1.md` 中均无接口契约
|
||||
- `c4/code-view.md` 中也未列出这些运行时类
|
||||
- 开发者实现 §6 的跨 DB 事务语义时没有可实现的契约
|
||||
|
||||
**修复方向**:在 `interface-contracts-v1.md` 中添加 `DebugKnowledgeStore` 和 `LearnedMemoryStore` 接口
|
||||
|
||||
---
|
||||
|
||||
#### B3. `debug-records.db` 和 `learned-memory.db` 无 schema 定义
|
||||
|
||||
**位置**:`db-schema-v1.md`
|
||||
|
||||
**问题**:
|
||||
- `db-schema-v1.md` 只覆盖 `session.db`
|
||||
- 这两个项目级数据库在至少 4 个文档中被引用,但无 DDL、无表定义、无列规范
|
||||
- `debug.record.created` 事件载荷暗示了 `debug_record_id`、`failure_signature`、`summary` 等列,但目标表结构未定义
|
||||
|
||||
**修复方向**:在 `db-schema-v1.md` 中补充 `debug-records.db` 和 `learned-memory.db` 的 schema
|
||||
|
||||
---
|
||||
|
||||
#### B4. `PermissionProfile` 命名冲突
|
||||
|
||||
**位置**:`security-model-v1.md` §3 vs `interface-contracts-v1.md` §10
|
||||
|
||||
**问题**:
|
||||
- `security-model-v1.md` 定义 `PermissionProfile` 为 `"low" | "normal" | "high" | "developer"`(安全态势)
|
||||
- `interface-contracts-v1.md` 定义 `AgentRuntimeContext.permission_profile` 为 `"main_direct" | "executor" | "reviewer" | "debugger" | "system"`(角色权限模板)
|
||||
- 两个不同概念使用相同名称 `permission_profile`,实现者可能混淆
|
||||
|
||||
**修复方向**:将 `AgentRuntimeContext.permission_profile` 重命名为 `permission_template` 或 `role_permission`
|
||||
|
||||
---
|
||||
|
||||
#### B5. `EntityType` 集合不一致
|
||||
|
||||
**位置**:`interface-contracts-v1.md` §4 vs `event-registry-v1.md` §1
|
||||
|
||||
**问题**:
|
||||
- `interface-contracts-v1.md` 定义 `EntityType` 含 12 个值,包括 `"capability"` 和 `"provider"`
|
||||
- `event-registry-v1.md` 内联定义自己的 `EntityRef` 只有 10 个值,缺失 `"capability"` 和 `"provider"`
|
||||
- 如果两者编译到同一包,会有两个冲突的 `EntityRef` 定义
|
||||
|
||||
**修复方向**:以 `interface-contracts-v1.md` 为准,event-registry 引用该定义而非内联
|
||||
|
||||
---
|
||||
|
||||
#### B6. `CompactionPolicy`、`PromptLayer`、`PromptLayerLoader` 无契约
|
||||
|
||||
**位置**:`c4/code-view.md` §4 vs `interface-contracts-v1.md` §16
|
||||
|
||||
**问题**:
|
||||
- `c4/code-view.md` 列出 `CompactionPolicy.ts`、`PromptLayerLoader.ts` 并引用 `PromptLayer` 类型
|
||||
- `interface-contracts-v1.md` §16 只定义了最小 `ContextAssembler` 接口
|
||||
- `ContextAssembleInput.refs` 是 `string[]` 无结构,而 code-view 的 `ContextPack.refs` 有结构化形状
|
||||
- 没有 `PromptLayer` 定义,`ContextAssembler` 无法实现
|
||||
|
||||
**修复方向**:在 `interface-contracts-v1.md` 中补充 `PromptLayer`、`CompactionPolicy`、`PromptLayerLoader` 接口
|
||||
|
||||
---
|
||||
|
||||
### 2.2 应修复问题(S1-S10)
|
||||
|
||||
这些问题不会阻止编译,但会造成混淆、重复或测试困难。
|
||||
|
||||
#### S1. `ToolCategory` 和 `ToolResultEnvelope` 重复定义
|
||||
|
||||
**位置**:`interface-contracts-v1.md` §12 和 `tool-registry-v1.md` §2
|
||||
|
||||
**问题**:两者定义了相同的 `ToolCategory` 和 `ToolResultEnvelope`。编译到同一包时 TypeScript 会报重复标识符。
|
||||
|
||||
**修复方向**:`tool-registry-v1.md` 引用 `interface-contracts-v1.md`,不重复定义。
|
||||
|
||||
---
|
||||
|
||||
#### S2. `TaskInsert = TaskRecord` 强制调用方传服务器生成字段
|
||||
|
||||
**位置**:`interface-contracts-v1.md` §6
|
||||
|
||||
**问题**:`TaskInsert` 等于 `TaskRecord`,意味着调用方必须提供 `created_at`、`retry_count`、`status`。通常 insert 应使用子集类型,服务器默认值由存储层填充。`PersistedEventRecord` 有同样问题。
|
||||
|
||||
**修复方向**:定义 `TaskInsert` 和 `EventInsert` 为省略服务器生成字段的子集类型。
|
||||
|
||||
---
|
||||
|
||||
#### S3. `ToolExecutor.execute` 返回未区分联合类型
|
||||
|
||||
**位置**:`interface-contracts-v1.md` §12
|
||||
|
||||
**问题**:返回 `AsyncIterable<ToolEvent> | Promise<ToolResultEnvelope<O>>`,调用方需 duck-type 或 `Symbol.asyncIterator` 检查来区分流式与非流式。`streaming: boolean` 字段存在但未在类型层面强制。
|
||||
|
||||
**修复方向**:使用判别联合或品牌化返回类型。
|
||||
|
||||
---
|
||||
|
||||
#### S4. `EventBus.subscribe` handler 抛错行为未定义
|
||||
|
||||
**位置**:`interface-contracts-v1.md` §7
|
||||
|
||||
**问题**:如果订阅 handler 抛出异常,契约未说明:(a) 错误被吞掉,(b) 传播给发布者,(c) 订阅被终止。
|
||||
|
||||
**修复方向**:明确 handler 错误不影响发布者,错误被记录但不传播。
|
||||
|
||||
---
|
||||
|
||||
#### S5. `JsonSchema<T>` 泛型参数 `T` 未使用
|
||||
|
||||
**位置**:`interface-contracts-v1.md` §2
|
||||
|
||||
**问题**:`type JsonSchema<T = unknown> = JsonObject` 中 `T` 从未在类型体中引用,是幽灵类型,不提供编译时安全。
|
||||
|
||||
**修复方向**:移除泛型参数或定义品牌化类型。
|
||||
|
||||
---
|
||||
|
||||
#### S6. `SchedulerWavePlan.wave_id` 是 `string` 而非品牌化 ID
|
||||
|
||||
**位置**:`interface-contracts-v1.md` §9
|
||||
|
||||
**问题**:系统中其他标识符都用品牌化类型别名(`TaskID`、`AgentID` 等),`wave_id` 是普通 `string`,不一致且无法防止 ID 类型混淆。
|
||||
|
||||
**修复方向**:添加 `WaveID` 品牌化类型。
|
||||
|
||||
---
|
||||
|
||||
#### S7. `FollowUpTask.type` 允许 `"docs"` 但 `TaskType` 不含 `"docs"`
|
||||
|
||||
**位置**:`interface-contracts-v1.md` §11
|
||||
|
||||
**问题**:`FollowUpTask.type` 为 `TaskType | "docs"`,但 `TaskType` 不含 `"docs"`。Scheduler 收到 `type: "docs"` 的 follow-up 时无法调度。
|
||||
|
||||
**修复方向**:将 `"docs"` 加入 `TaskType`,或从 `FollowUpTask.type` 中移除。
|
||||
|
||||
---
|
||||
|
||||
#### S8. `foreign_keys = OFF` 无应用层一致性契约
|
||||
|
||||
**位置**:`db-schema-v1.md` §1
|
||||
|
||||
**问题**:禁用外键并声明"应用层一致性检查处理引用",但无文档定义这些检查是什么、何时运行、孤立行如何处理。
|
||||
|
||||
**修复方向**:在 Repository 接口中明确 insert 是否验证外键存在,或在 `runtime-semantics-v1.md` 中补充孤儿清理规则。
|
||||
|
||||
---
|
||||
|
||||
#### S9. `PermissionEngine.record` 返回 `Promise<void>` 无错误指示
|
||||
|
||||
**位置**:`interface-contracts-v1.md` §10
|
||||
|
||||
**问题**:如果记录权限决策失败(磁盘满、DB 锁),调用方无法得知。
|
||||
|
||||
**修复方向**:返回结果类型或指定抛出的类型化错误。
|
||||
|
||||
---
|
||||
|
||||
#### S10. `ProjectionStore.apply` 接受任意事件无过滤规范
|
||||
|
||||
**位置**:`interface-contracts-v1.md` §14
|
||||
|
||||
**问题**:`apply(event: RuntimeEvent): void` 未指定哪些事件类型会触发投影更新,实现者需猜测。
|
||||
|
||||
**修复方向**:添加文档说明预期的事件集,或使用类型窄化联合。
|
||||
|
||||
---
|
||||
|
||||
### 2.3 可接受的缺口
|
||||
|
||||
| 缺口 | 理由 |
|
||||
|---|---|
|
||||
| 无 monorepo 工具配置 | 实现选择 |
|
||||
| 无具体 SQLite 迁移策略 | 单版本 V1.0.0 Alpha 可接受 |
|
||||
| 无 Provider 重试/退避细节 | adapter 实现细节 |
|
||||
| 无 TUI 组件细节 | TUI 仅消费投影,实现自由度高 |
|
||||
| 无具体 token 计数实现 | Provider adapter 处理 |
|
||||
| `ProviderCapabilityMatrix.supports/.conversion` 为 `JsonObject` | 故意保留 provider 特定形状灵活性 |
|
||||
| 无具体 `semantic_signature` 算法 | 格式已定义,哈希函数为实现选择 |
|
||||
| 无 IPC 传输层契约 | 信封格式已定义,传输为实现细节 |
|
||||
| 无 EventStore schema 验证失败的具体错误形状 | 次要缺口 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 用户视角(原始需求对齐)
|
||||
|
||||
### 3.1 需求对齐检查
|
||||
|
||||
| 原始需求 | 当前状态 | 评价 |
|
||||
|---|---|---|
|
||||
| 自有 AI coding agent/runtime,非 Claude Code 插件包装 | 独立架构,自有运行时、调度器、工具系统 | 已满足 |
|
||||
| Claude Code 级执行层质量 | D-059 + runtime-semantics 定义了 read-before-edit、exact edit、completion gate | 已满足 |
|
||||
| OpenCode TUI 风格复用 | `@opentui/solid`,投影消费模式,不复用业务状态 | 已满足 |
|
||||
| 项目本地 `.air` 状态 | `.air/shared` + `.air/local`,session DB 项目本地 | 已满足 |
|
||||
| 事件驱动 + SQLite 恢复 | EventBus 实时 + EventStore 持久化 + ProjectionStore 投影 | 已满足 |
|
||||
| 独立子进程 worker + NDJSON IPC | 已定义完整 IPC 协议含 tool 调用 | 已满足 |
|
||||
| C++ 作为第一个深度工具链 | `toolchain-cpp` 包含完整工作流 | 已满足 |
|
||||
| 多 agent 调度 | Scheduler + TaskGraph + 边列表依赖 + 波次规划 | 已满足 |
|
||||
| 权限模型 | `action + grant_scope`,路径/命令/网络/凭据分类 | 已满足 |
|
||||
| VibeBox 下游分支 | `branchvibebox/` 独立 baseline + feasibility plan | 已满足 |
|
||||
| 非半成品 MVP,目标 V1.0.0 Alpha | 范围已升级,含完整 C++ 工作流和插件基础 | 已满足 |
|
||||
|
||||
### 3.2 无方向性冲突
|
||||
|
||||
用户视角下无设计方向性冲突。所有 B/S 级问题都是工程实现一致性问题,不影响产品定位和架构决策。
|
||||
|
||||
---
|
||||
|
||||
## 4. 优先级建议
|
||||
|
||||
### 必须在系统概要设计前修复(B1-B6)
|
||||
|
||||
| 优先级 | ID | 修复内容 |
|
||||
|---|---|---|
|
||||
| 1 | B1 | 统一 `AirError.cause_ref` 为 `EntityRef`,更新 error-taxonomy |
|
||||
| 2 | B4 | 重命名 `AgentRuntimeContext.permission_profile` 为 `permission_template` |
|
||||
| 3 | B5 | event-registry 引用 interface-contracts 的 `EntityRef`,不内联 |
|
||||
| 4 | B2 | 在 interface-contracts 补充 `DebugKnowledgeStore` 和 `LearnedMemoryStore` 接口 |
|
||||
| 5 | B3 | 在 db-schema-v1 补充 `debug-records.db` 和 `learned-memory.db` DDL |
|
||||
| 6 | B6 | 在 interface-contracts 补充 `PromptLayer`、`CompactionPolicy`、`PromptLayerLoader` |
|
||||
|
||||
### 可在概要设计中同步修复(S1-S10)
|
||||
|
||||
| 优先级 | ID | 修复内容 |
|
||||
|---|---|---|
|
||||
| 1 | S7 | 将 `"docs"` 加入 `TaskType` 或从 `FollowUpTask.type` 移除 |
|
||||
| 2 | S2 | 定义 `TaskInsert`/`EventInsert` 子集类型 |
|
||||
| 3 | S1 | tool-registry 引用 interface-contracts,不重复定义 |
|
||||
| 4 | S6 | 添加 `WaveID` 品牌化类型 |
|
||||
| 5 | S4 | 定义 EventBus handler 错误行为 |
|
||||
| 6 | S8 | 补充 FK 一致性契约或孤儿清理规则 |
|
||||
| 7 | S9 | `PermissionEngine.record` 返回结果类型 |
|
||||
| 8 | S10 | `ProjectionStore.apply` 添加事件过滤文档 |
|
||||
| 9 | S3 | `ToolExecutor` 返回判别联合 |
|
||||
| 10 | S5 | 移除 `JsonSchema<T>` 泛型参数 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 审查结论
|
||||
|
||||
**可以进入系统概要设计阶段**,前提是 B1-B6 先修复。S1-S10 可在概要设计过程中同步处理。
|
||||
|
||||
架构文档集整体质量高,V1.0.0 Alpha 范围明确,接口契约基本可编译,运行时语义已澄清。本轮修正解决了第一轮审查发现的所有关键问题,剩余问题都是工程一致性层面的细节。
|
||||
15
AirPlan/docs/architecture/adr/ADR-0001-use-airplan-as-the-workflow-root.md
Executable file
15
AirPlan/docs/architecture/adr/ADR-0001-use-airplan-as-the-workflow-root.md
Executable file
@@ -0,0 +1,15 @@
|
||||
# ADR-0001: Use AirPlan As The Workflow Root
|
||||
|
||||
- Status: Accepted
|
||||
- Date: YYYY-MM-DD
|
||||
|
||||
## Context
|
||||
This project needs a durable workflow root for planning, execution state, architecture context, validation evidence, and resumable AI sessions.
|
||||
|
||||
## Decision
|
||||
Store project workflow artifacts under `AirPlan/`, use the repo-root `AGENTS.md` only as a bootstrap shim, and let `aireng` plus `airdo` maintain plan, todo, ADR, and C4 context there.
|
||||
|
||||
## Consequences
|
||||
- Planning and execution context stay resumable across sessions.
|
||||
- Global workflow docs live in one predictable location.
|
||||
- Plugin runtime state does not clutter the main project tree.
|
||||
@@ -0,0 +1,28 @@
|
||||
# ADR-0002: Use Bun TypeScript Monorepo For AirCoding Runtime
|
||||
|
||||
- Status: Accepted
|
||||
- Date: 2026-05-27
|
||||
|
||||
## Context
|
||||
|
||||
AirCoding needs a self-owned runtime that can support CLI, TUI, agent orchestration, provider adapters, contracts, and toolchain packages without becoming a wrapper around an existing coding agent.
|
||||
|
||||
## Decision
|
||||
|
||||
Use TypeScript on Bun with Bun workspaces and Turborepo. Organize MVP packages as:
|
||||
|
||||
```text
|
||||
packages/cli
|
||||
packages/tui
|
||||
packages/runtime
|
||||
packages/llm
|
||||
packages/toolchain-cpp
|
||||
packages/contracts
|
||||
```
|
||||
|
||||
## Consequences
|
||||
|
||||
- Runtime, UI, providers, and toolchains share compileable contracts.
|
||||
- Worker agents can run as independent Bun child processes.
|
||||
- Python remains subprocess-only for existing scripts/libraries, not the core runtime.
|
||||
- Future language support is added through `toolchain-*` packages.
|
||||
@@ -0,0 +1,30 @@
|
||||
# ADR-0003: Use Project-Local `.air` State
|
||||
|
||||
- Status: Accepted
|
||||
- Date: 2026-05-27
|
||||
|
||||
## Context
|
||||
|
||||
AirCoding sessions, artifacts, rules, plans, backups, and debug evidence must be resumable and portable with the project where possible, while still keeping private/local state out of normal source sharing.
|
||||
|
||||
## Decision
|
||||
|
||||
Use project-local `.air/` as the source of truth:
|
||||
|
||||
```text
|
||||
<project>/.air/shared/ # git-shareable project config, rules, plan docs
|
||||
<project>/.air/local/ # private sessions, artifacts, backups, workspaces, local DBs
|
||||
```
|
||||
|
||||
Session DBs live at:
|
||||
|
||||
```text
|
||||
<project>/.air/local/sessions/<session-id>/session.db
|
||||
```
|
||||
|
||||
## Consequences
|
||||
|
||||
- Project state can move with the project directory.
|
||||
- `.air/shared/` can be versioned; `.air/local/` is gitignored by default.
|
||||
- Runtime recovery uses project-local SQLite and artifacts.
|
||||
- Global `~/.air/` remains config/cache/log/index state, not session source of truth.
|
||||
@@ -0,0 +1,28 @@
|
||||
# ADR-0004: Use EventStore, Domain Tables, And ProjectionStore
|
||||
|
||||
- Status: Accepted
|
||||
- Date: 2026-05-27
|
||||
|
||||
## Context
|
||||
|
||||
AirCoding needs live TUI/HUD updates, crash recovery, scheduling queries, tool/run evidence, and resumable session state. Raw message storage alone is insufficient for scheduling and recovery.
|
||||
|
||||
## Decision
|
||||
|
||||
Use an event-driven runtime with:
|
||||
|
||||
```text
|
||||
EventBus # live ephemeral/durable event publication
|
||||
EventStore # durable event validation and transactional persistence
|
||||
Domain tables # scheduling/recovery/query source of truth
|
||||
ProjectionStore # derived TUI/HUD view model
|
||||
```
|
||||
|
||||
Canonical messages are stored as Anthropic content JSON. Domain tables store tasks, agents, tool runs, command runs, artifacts, diagnostics, evidence, workspaces, summaries, and UI state.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Scheduler and recovery query domain tables instead of parsing message history.
|
||||
- TUI/HUD consumes ProjectionStore, not DB/EventBus directly.
|
||||
- Durable event insert and corresponding domain table update happen in one SQLite transaction.
|
||||
- Event payloads and persistence policy are governed by `event-registry-v1.md`.
|
||||
@@ -0,0 +1,30 @@
|
||||
# ADR-0005: Use Independent Worker Processes And NDJSON IPC
|
||||
|
||||
- Status: Accepted
|
||||
- Date: 2026-05-27
|
||||
|
||||
## Context
|
||||
|
||||
A single agent process doing all work would cause context explosion, reduce responsiveness, and make parallel execution fragile. AirCoding needs workers that can be monitored, retried, cancelled, and recovered independently.
|
||||
|
||||
## Decision
|
||||
|
||||
Run Executor, Reviewer, Debugger, Compactor, and ExperienceMiner as independent Bun child processes. Use NDJSON over stdio for IPC.
|
||||
|
||||
IPC messages use:
|
||||
|
||||
```text
|
||||
kind: event
|
||||
kind: control
|
||||
kind: log
|
||||
```
|
||||
|
||||
The Scheduler owns process lifecycle, heartbeat monitoring, timeout handling, and WorkerResult collection.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Main Agent remains responsive.
|
||||
- Workers have bounded task context.
|
||||
- Scheduler can detect lost workers through heartbeat/process state.
|
||||
- stdout is reserved for protocol; stderr is crash/fatal fallback.
|
||||
- Worker loops may be role-specific rather than one generic shared loop.
|
||||
@@ -0,0 +1,30 @@
|
||||
# ADR-0006: Align Execution Layer With Claude Code Quality Discipline
|
||||
|
||||
- Status: Accepted
|
||||
- Date: 2026-05-27
|
||||
|
||||
## Context
|
||||
|
||||
AirCoding's usefulness depends heavily on safe, correct code modifications. The user explicitly prioritized Claude Code-level execution quality over broad but loose tool behavior.
|
||||
|
||||
## Decision
|
||||
|
||||
Align execution-layer primitives with Claude Code as much as possible:
|
||||
|
||||
- read before edit
|
||||
- exact conservative replacements
|
||||
- small patches
|
||||
- no unrelated refactors
|
||||
- no premature abstractions
|
||||
- schema-validated tool use
|
||||
- permission checks before side effects
|
||||
- verification before completion
|
||||
- build/test/debug evidence collection
|
||||
- root-cause failure diagnosis
|
||||
- explicit blocker escalation for architecture/interface conflicts
|
||||
|
||||
## Consequences
|
||||
|
||||
- `fs.edit`, `fs.patch`, `shell.run`, WorkerResult, and review gates must preserve this discipline.
|
||||
- Codex/OpenCode may inform tool breadth/UI/runtime ideas, but not at the cost of execution quality.
|
||||
- Workers should fail or block rather than guessing unsafe edits.
|
||||
@@ -0,0 +1,21 @@
|
||||
# ADR-0007: Use ToolRegistry, PermissionEngine, And Capability Manifests
|
||||
|
||||
- Status: Accepted
|
||||
- Date: 2026-05-27
|
||||
|
||||
## Context
|
||||
|
||||
AirCoding needs a growing tool surface across filesystem, shell, git, build, debug, GUI, network, memory, and future plugins. Tools must be extensible without bypassing safety boundaries.
|
||||
|
||||
## Decision
|
||||
|
||||
Use ToolRegistry for schema-validated tool execution, PermissionEngine for all side-effect decisions, and CapabilityRegistry for built-in/future tool bundles.
|
||||
|
||||
Capabilities declare dependencies and permissions. Doctor/setup detects and installs/fixes dependencies according to permission policy. Capability tools are not privileged above built-ins.
|
||||
|
||||
## Consequences
|
||||
|
||||
- All tool calls share lifecycle events, artifacts, errors, and evidence behavior.
|
||||
- Plugin/capability extension is possible without opening a permission bypass.
|
||||
- Doctor owns dependency installation rather than arbitrary plugin scripts.
|
||||
- MVP tool names and schemas are frozen in `tool-registry-v1.md`.
|
||||
@@ -0,0 +1,21 @@
|
||||
# ADR-0008: Use Anthropic Canonical Messages With Provider Adapters
|
||||
|
||||
- Status: Accepted
|
||||
- Date: 2026-05-27
|
||||
|
||||
## Context
|
||||
|
||||
AirCoding needs provider flexibility while preserving a stable internal representation for prompts, tools, messages, context compaction, and session persistence.
|
||||
|
||||
## Decision
|
||||
|
||||
Use Anthropic canonical content blocks internally. ContextAssembler emits Anthropic canonical messages. Provider adapters convert at the LLM boundary to Anthropic, OpenAI, OpenRouter, ollama, or compatible endpoints.
|
||||
|
||||
Provider capability matrix controls whether a model can satisfy the task and whether conversion is lossless, lossy, or unsupported.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Same-provider model switching has low conversion cost.
|
||||
- Cross-provider differences are localized to adapters.
|
||||
- Unsupported required features block before model call.
|
||||
- Tool/result/message persistence remains stable across providers.
|
||||
@@ -0,0 +1,21 @@
|
||||
# ADR-0009: Target Linux First With Tiered Platform Support
|
||||
|
||||
- Status: Accepted
|
||||
- Date: 2026-05-27
|
||||
|
||||
## Context
|
||||
|
||||
AirCoding's first deep workflow targets C++ development and local agent execution, which depend heavily on POSIX shell/process/filesystem semantics and local toolchains.
|
||||
|
||||
## Decision
|
||||
|
||||
Use Linux x86_64 as tier-1 MVP platform, Linux arm64 and WSL2 as tier-2, macOS as experimental, and Windows native as experimental/post-MVP.
|
||||
|
||||
MVP shell/process/C++ workflows target POSIX-like Linux behavior.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Release gates block on tier-1 Linux.
|
||||
- Platform detection and path classification must be platform-aware.
|
||||
- Windows native deep support and MSVC workflows are deferred.
|
||||
- VibeBox ARM Linux remains compatible as a downstream branch but does not define mainline MVP release blockers.
|
||||
303
AirPlan/docs/architecture/artifact-naming-v1.md
Normal file
303
AirPlan/docs/architecture/artifact-naming-v1.md
Normal file
@@ -0,0 +1,303 @@
|
||||
# AirCoding Artifact Naming and Layout V1
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Canonical artifact naming/layout standard for V1.0.0 Alpha skeleton
|
||||
|
||||
This document defines artifact URI format, directory layout, naming conventions, metadata requirements, compression rules, and evidence linkage.
|
||||
|
||||
## 1. Goals
|
||||
|
||||
Artifact storage must be:
|
||||
|
||||
1. Project-local and session-local.
|
||||
2. Stable across project moves when using artifact URI and DB records.
|
||||
3. Queryable through SQLite domain tables.
|
||||
4. Safe for large logs/binaries/screenshots/pcaps/core dumps.
|
||||
5. Linked to tool/command/task/agent/evidence records.
|
||||
6. Compatible with crash recovery and final reports.
|
||||
|
||||
## 2. Root Layout
|
||||
|
||||
Session artifact root:
|
||||
|
||||
```text
|
||||
<project>/.air/local/sessions/<session-id>/artifacts/
|
||||
```
|
||||
|
||||
Canonical subdirectories:
|
||||
|
||||
```text
|
||||
artifacts/
|
||||
messages/
|
||||
context/
|
||||
command-runs/
|
||||
tool-runs/
|
||||
builds/
|
||||
tests/
|
||||
static-analysis/
|
||||
debug/
|
||||
screenshots/
|
||||
pcaps/
|
||||
core-dumps/
|
||||
diffs/
|
||||
reports/
|
||||
doctor/
|
||||
permissions/
|
||||
workspaces/
|
||||
ui-assets/
|
||||
tmp/
|
||||
```
|
||||
|
||||
`tmp/` is not referenced by `artifacts` table until a file is atomically renamed into a canonical directory.
|
||||
|
||||
## 3. Artifact URI
|
||||
|
||||
Canonical URI:
|
||||
|
||||
```text
|
||||
artifact://project/<project-id>/session/<session-id>/<artifact-id>
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. URI is stable and stored in `artifacts.uri`.
|
||||
2. Filesystem path is stored in `artifacts.path`.
|
||||
3. Consumers should prefer URI + DB lookup over reconstructing paths.
|
||||
4. Artifact IDs are opaque stable IDs, not semantic filenames.
|
||||
|
||||
## 4. Artifact ID
|
||||
|
||||
V1 artifact ID format:
|
||||
|
||||
```text
|
||||
art_<ulid>
|
||||
```
|
||||
|
||||
Examples:
|
||||
|
||||
```text
|
||||
art_01JZ7QX4D4N9Y6QZ3C9QH4SX2A
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. IDs are generated before writing temp files.
|
||||
2. IDs must be unique within session DB.
|
||||
3. IDs are not reused after failed writes.
|
||||
4. Human-readable meaning belongs in filename and metadata, not ID.
|
||||
|
||||
## 5. Filename Format
|
||||
|
||||
Canonical filename:
|
||||
|
||||
```text
|
||||
<timestamp>-<artifact-id>-<slug><extension>
|
||||
```
|
||||
|
||||
Timestamp format:
|
||||
|
||||
```text
|
||||
YYYYMMDDTHHMMSSmmmZ
|
||||
```
|
||||
|
||||
Examples:
|
||||
|
||||
```text
|
||||
20260527T142233120Z-art_01JZ7QX4D4N9Y6QZ3C9QH4SX2A-build-log.txt.gz
|
||||
20260527T142240992Z-art_01JZ7QXXM8WAPVTA5Y4F4P5NTQ-screenshot.png
|
||||
20260527T142251002Z-art_01JZ7QY8P6PR3G2T5BXE91D6KD-diff.patch
|
||||
```
|
||||
|
||||
Slug rules:
|
||||
|
||||
```text
|
||||
lowercase
|
||||
ascii letters/numbers/hyphen only
|
||||
collapse repeated hyphens
|
||||
max 64 chars
|
||||
no secrets, usernames, absolute paths, tokens, or raw command strings
|
||||
```
|
||||
|
||||
## 6. Type to Directory Mapping
|
||||
|
||||
| Artifact type | Directory | Default extension |
|
||||
|---|---|---|
|
||||
| `message_snapshot` | `messages/` | `.json.gz` |
|
||||
| `context_pack` | `context/` | `.json.gz` |
|
||||
| `stdout` | `command-runs/<command-run-id>/` | `.stdout.txt.gz` |
|
||||
| `stderr` | `command-runs/<command-run-id>/` | `.stderr.txt.gz` |
|
||||
| `combined_output` | `command-runs/<command-run-id>/` | `.combined.txt.gz` |
|
||||
| `tool_output` | `tool-runs/<tool-run-id>/` | `.json.gz` |
|
||||
| `build_log` | `builds/` | `.txt.gz` |
|
||||
| `test_report` | `tests/` | `.json` or `.xml` |
|
||||
| `static_analysis_report` | `static-analysis/` | `.json` |
|
||||
| `debug_report` | `debug/` | `.md` |
|
||||
| `backtrace` | `debug/` | `.txt` |
|
||||
| `screenshot` | `screenshots/` | `.png` |
|
||||
| `pcap` | `pcaps/` | `.pcap` |
|
||||
| `core_dump` | `core-dumps/` | `.core` |
|
||||
| `diff` | `diffs/` | `.patch` |
|
||||
| `review_report` | `reports/` | `.md` |
|
||||
| `doctor_report` | `doctor/` | `.json` |
|
||||
| `permission_report` | `permissions/` | `.json` |
|
||||
| `workspace_diff` | `workspaces/<workspace-id>/` | `.patch` |
|
||||
| `ui_asset` | `ui-assets/` | `.svg` / `.png` / `.json` |
|
||||
|
||||
## 7. Command and Tool Run Layout
|
||||
|
||||
Command run artifacts:
|
||||
|
||||
```text
|
||||
command-runs/<command-run-id>/
|
||||
<timestamp>-<artifact-id>-stdout.txt.gz
|
||||
<timestamp>-<artifact-id>-stderr.txt.gz
|
||||
<timestamp>-<artifact-id>-combined.txt.gz
|
||||
<timestamp>-<artifact-id>-diagnostics.json
|
||||
```
|
||||
|
||||
Tool run artifacts:
|
||||
|
||||
```text
|
||||
tool-runs/<tool-run-id>/
|
||||
<timestamp>-<artifact-id>-input.json.gz
|
||||
<timestamp>-<artifact-id>-output.json.gz
|
||||
<timestamp>-<artifact-id>-report.md
|
||||
```
|
||||
|
||||
Only store tool input as artifact when needed for audit/debug; secrets must be redacted or omitted according to tool policy.
|
||||
|
||||
## 8. Write Protocol
|
||||
|
||||
Artifact file write protocol:
|
||||
|
||||
```text
|
||||
1. generate artifact_id
|
||||
2. write to artifacts/tmp/<artifact-id>.tmp
|
||||
3. fsync/close where supported and appropriate
|
||||
4. compute sha256 and size
|
||||
5. atomic rename into canonical directory
|
||||
6. insert artifacts row and emit artifact.created in same logical operation
|
||||
7. link evidence_refs if applicable
|
||||
```
|
||||
|
||||
If DB insert fails after rename, recovery scans orphaned files and either registers or quarantines them under `tmp/orphans/`.
|
||||
|
||||
## 9. Compression Rules
|
||||
|
||||
Default compression:
|
||||
|
||||
| Content | Rule |
|
||||
|---|---|
|
||||
| text logs over threshold | gzip |
|
||||
| JSON context/message snapshots | gzip |
|
||||
| screenshots PNG/JPEG | no double compression |
|
||||
| pcap | no compression by default |
|
||||
| core dumps | no compression by default in MVP |
|
||||
| small markdown reports | no compression |
|
||||
| patches | no compression unless very large |
|
||||
|
||||
Default threshold:
|
||||
|
||||
```text
|
||||
compress text/json artifacts >= 64 KiB
|
||||
```
|
||||
|
||||
## 10. Metadata Requirements
|
||||
|
||||
Minimum artifact row:
|
||||
|
||||
```ts
|
||||
interface ArtifactMetadataV1 {
|
||||
schema_version: 1
|
||||
producer: "tool" | "command" | "agent" | "scheduler" | "main" | "system"
|
||||
content_type?: string
|
||||
compression?: "gzip" | "none"
|
||||
redaction?: "none" | "partial" | "full" | "not_applicable"
|
||||
preview_available?: boolean
|
||||
original_path?: string
|
||||
command_run_id?: string
|
||||
tool_run_id?: string
|
||||
task_id?: string
|
||||
agent_id?: string
|
||||
related_event_ids?: string[]
|
||||
notes?: string[]
|
||||
}
|
||||
```
|
||||
|
||||
DB columns store common query fields separately; metadata is for extra detail.
|
||||
|
||||
## 11. Evidence Linking
|
||||
|
||||
Artifacts are facts only when linked by `evidence_refs`.
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
artifact: command combined output
|
||||
claim: "cpp.build failed with undefined reference in linker stage"
|
||||
evidence_ref.kind: command_output
|
||||
evidence_ref.ref: artifact://...
|
||||
location_json: { "line_start": 120, "line_end": 148 }
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. A report may cite many evidence refs.
|
||||
2. A single artifact may support multiple claims.
|
||||
3. Evidence claims should be concise and testable.
|
||||
4. Do not treat artifact existence as proof without a claim.
|
||||
|
||||
## 12. Redaction and Sensitive Data
|
||||
|
||||
Default local artifacts are not automatically redacted because they are project-local debug evidence.
|
||||
|
||||
Before export/share/upload:
|
||||
|
||||
```text
|
||||
preview
|
||||
redact secrets/credentials/private paths where policy requires
|
||||
record redaction status
|
||||
require explicit user authorization
|
||||
```
|
||||
|
||||
Doctor bundles may include full diagnostics and are encrypted for the development team when exported through that channel.
|
||||
|
||||
## 13. Retention
|
||||
|
||||
Session artifacts are retained with the session by default.
|
||||
|
||||
Cleanup candidates:
|
||||
|
||||
```text
|
||||
tmp files
|
||||
orphaned failed writes
|
||||
duplicate large command stream chunks after combined artifact exists
|
||||
old developer logs outside project session artifacts
|
||||
```
|
||||
|
||||
No automatic deletion of evidence-bearing artifacts in MVP unless user explicitly runs cleanup and confirms the policy.
|
||||
|
||||
## 14. V1.0.0 Alpha Cut Line
|
||||
|
||||
V1.0.0 Alpha skeleton must implement:
|
||||
|
||||
1. Artifact ID generation.
|
||||
2. Canonical URI creation.
|
||||
3. Directory mapping by artifact type.
|
||||
4. Temp-write then atomic rename.
|
||||
5. sha256 and size recording.
|
||||
6. gzip compression for large text/json.
|
||||
7. `artifacts` table insertion.
|
||||
8. `artifact.created` event emission.
|
||||
9. Evidence ref linking.
|
||||
10. Orphan scan/quarantine on startup.
|
||||
|
||||
Post-MVP:
|
||||
|
||||
```text
|
||||
content-addressed deduplication
|
||||
artifact browser UI
|
||||
automatic retention policies
|
||||
export bundle redaction profiles
|
||||
remote artifact storage adapters
|
||||
```
|
||||
884
AirPlan/docs/architecture/baselineV1.md
Normal file
884
AirPlan/docs/architecture/baselineV1.md
Normal file
@@ -0,0 +1,884 @@
|
||||
# AirCoding Architecture Baseline V1
|
||||
|
||||
Date: 2026-05-26
|
||||
Status: Canonical baseline for formal C4 / ADR / plan / todo work
|
||||
|
||||
This document supersedes earlier exploratory wording in `idea.md` and decision rounds where conflicts exist. Round files remain historical records; this baseline is the implementation-facing source of truth until V2.
|
||||
|
||||
## 1. Product Positioning
|
||||
|
||||
AirCoding is a self-owned AI coding agent/runtime, not a Claude Code plugin wrapper.
|
||||
|
||||
The runtime is language-agnostic. C++ is the first deep language profile, with later expansion through `toolchain-<lang>` packages.
|
||||
|
||||
Core loop:
|
||||
|
||||
```text
|
||||
Requirement understanding
|
||||
→ architecture/interface design
|
||||
→ code reading
|
||||
→ implementation planning
|
||||
→ build
|
||||
→ static analysis
|
||||
→ test
|
||||
→ run/debug
|
||||
→ crash/log/network/GUI evidence analysis
|
||||
→ fix
|
||||
→ change summary
|
||||
→ experience mining
|
||||
```
|
||||
|
||||
## 2. Reference Projects and Roles
|
||||
|
||||
### OpenCode
|
||||
|
||||
Reference for:
|
||||
|
||||
- Runtime layering
|
||||
- TUI visual style and interaction layout
|
||||
- Session/event/sync concepts
|
||||
- Provider/model abstraction
|
||||
- Plugin/SDK extension ideas
|
||||
|
||||
AirCoding reuses OpenCode-style UI primitives and OpenTUI patterns, but does **not** reuse OpenCode SDK/sync/session business state.
|
||||
|
||||
### Claude Code CLI
|
||||
|
||||
Primary reference for execution-layer quality.
|
||||
|
||||
AirCoding execution-layer primitives should align with Claude Code as much as possible to maximize code quality, correctness, safe modification behavior, and verification discipline.
|
||||
|
||||
Reference areas:
|
||||
|
||||
- File read/edit/write safety boundaries
|
||||
- Exact and conservative diff/update application behavior
|
||||
- Patch granularity and conflict handling
|
||||
- Tool lifecycle and schema style
|
||||
- Permission checks around filesystem and shell
|
||||
- Read-before-edit discipline
|
||||
- Small-step edits
|
||||
- Avoiding unrelated refactors and premature abstractions during task execution
|
||||
- Verification-before-completion discipline
|
||||
- Build/test/debug evidence collection before declaring completion
|
||||
- Project Rules / memory adherence during edits
|
||||
- Root-cause-oriented failure handling rather than random retries
|
||||
- Explicit blocker escalation when implementation discovers architecture/interface conflicts
|
||||
- TAOR / TORI execution feedback loops
|
||||
|
||||
Claude Code is the quality benchmark because it productizes coding execution discipline: conservative edits, strong tool boundaries, persistent project rules, contextual memory, and verified build/test/debug closure.
|
||||
|
||||
### Hermes Agent
|
||||
|
||||
Reference for:
|
||||
|
||||
- Experience mining
|
||||
- Nudge Engine interval-triggered learning
|
||||
- Curator daemon
|
||||
- Skill self-patching
|
||||
- SKILL.md format and FTS retrieval
|
||||
|
||||
### OpenAI Codex
|
||||
|
||||
Reference for:
|
||||
|
||||
- Shell / patch / test direct execution loop
|
||||
- Coding sandbox and tool orchestration
|
||||
- Tool/plugin/core-plugin/MCP implementation ideas
|
||||
- Wider tool surface including image generation/editing/vision capabilities
|
||||
|
||||
Local reference path: `reference/openai-codex/`.
|
||||
|
||||
### Anthropic Claude Skills
|
||||
|
||||
Reference for:
|
||||
|
||||
- `SKILL.md` structure and frontmatter conventions
|
||||
- Skill directory layout (`scripts/`, `references/`, `assets/`)
|
||||
- Reusable workflow packaging
|
||||
- Skill trigger/retrieval descriptions
|
||||
- Skill/Project Rules/MCP/Capability boundary
|
||||
|
||||
Local reference path: `reference/anthropic-skills/`.
|
||||
|
||||
### asciinema / Atuin / claude-hud
|
||||
|
||||
Reference for:
|
||||
|
||||
- PTY capture and terminal replay
|
||||
- Command metadata/history indexing
|
||||
- HUD/statusline layout and activity display
|
||||
|
||||
## 3. Technology Baseline
|
||||
|
||||
- Runtime: TypeScript on Bun
|
||||
- Monorepo: Bun workspaces + Turborepo
|
||||
- TUI: `@opentui/solid`, `@opentui/core`, `@opentui/keymap`
|
||||
- Storage: SQLite per session, project-local
|
||||
- IPC: NDJSON over stdio
|
||||
- Python: subprocess-only helper layer for existing scripts/libraries, not core runtime
|
||||
- Distribution: binary tarball before public package channels
|
||||
|
||||
## 4. Monorepo Packages
|
||||
|
||||
Canonical V1.0.0 Alpha package set:
|
||||
|
||||
```text
|
||||
packages/
|
||||
contracts/ # shared TypeScript interfaces (no implementation deps)
|
||||
cli/ # command entrypoint, resource loading, startup/doctor/init
|
||||
tui/ # OpenTUI/Solid UI, ProjectionStore consumers, HUD
|
||||
runtime/ # EventBus, Scheduler, Agent process mgmt, ToolRegistry, PermissionEngine, SessionStore, ContextAssembler
|
||||
llm/ # provider/model adapters, Anthropic canonical format, cross-provider conversion
|
||||
toolchain-cpp/ # C++ detector, build/test/static-analysis/debug tools
|
||||
```
|
||||
|
||||
Future language packages:
|
||||
|
||||
```text
|
||||
packages/toolchain-python/
|
||||
packages/toolchain-rust/
|
||||
packages/toolchain-js/
|
||||
```
|
||||
|
||||
Dependency direction:
|
||||
|
||||
```text
|
||||
contracts → (no implementation deps)
|
||||
cli → tui/runtime/llm/toolchain-cpp
|
||||
runtime → contracts, llm (interfaces/adapters), toolchain-* via registry
|
||||
tui → contracts (ProjectionClient only)
|
||||
llm → contracts
|
||||
toolchain-cpp → contracts
|
||||
runtime must not depend on tui
|
||||
tui must consume ProjectionStore, not raw DB/EventBus directly
|
||||
```
|
||||
|
||||
## 5. Project and Global Filesystem Layout
|
||||
|
||||
### Global User Directory
|
||||
|
||||
`~/.air/` stores user-global configuration, caches, global skills, logs, and project index only. It is not the source of truth for project sessions.
|
||||
|
||||
```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 Directory
|
||||
|
||||
Project source of truth lives under the project.
|
||||
|
||||
```text
|
||||
<project>/.air/
|
||||
├── shared/
|
||||
│ ├── project.json
|
||||
│ ├── permissions.yaml
|
||||
│ ├── compaction-rules.md
|
||||
│ ├── rules/
|
||||
│ │ ├── project-rules.md
|
||||
│ │ └── toolchain-rules.md
|
||||
│ └── plan/
|
||||
│ ├── AGENTS.md
|
||||
│ ├── plan.md
|
||||
│ ├── todo.md
|
||||
│ └── docs/
|
||||
└── local/
|
||||
├── sessions/<session-id>/
|
||||
│ ├── session.db
|
||||
│ └── artifacts/
|
||||
├── state/
|
||||
├── backups/
|
||||
├── debug-records.db
|
||||
├── learned-memory.db
|
||||
├── workspaces/
|
||||
├── tmp/
|
||||
└── locks/
|
||||
```
|
||||
|
||||
Recommended `.gitignore`:
|
||||
|
||||
```gitignore
|
||||
.air/local/
|
||||
```
|
||||
|
||||
`.air/shared/` is git-shareable. `.air/local/` is portable with the project directory but private/local by default.
|
||||
|
||||
`project_id` is a stable UUID generated at initialization and stored in `.air/shared/project.json`. It is not derived from the absolute path.
|
||||
|
||||
## 6. Runtime Architecture
|
||||
|
||||
AirCoding is event-driven.
|
||||
|
||||
```text
|
||||
Main Agent
|
||||
→ Architecture Designer
|
||||
→ Scheduler
|
||||
→ Executor
|
||||
→ Reviewer
|
||||
→ Debugger
|
||||
→ Compactor
|
||||
→ ExperienceMiner
|
||||
```
|
||||
|
||||
### Main Agent
|
||||
|
||||
- Only user-facing agent
|
||||
- Handles conversation, decisions, progress summaries, requirement changes
|
||||
- Must remain responsive and idle-ready
|
||||
- Does not perform background work itself
|
||||
- Direct mode is a foreground execution lane, not a long-running Main Agent blockage
|
||||
|
||||
Canonical Main Agent state machine is defined in `AirPlan/docs/architecture/main-agent-state-machine.md`.
|
||||
|
||||
### Architecture Designer
|
||||
|
||||
- Architecture planning and impact assessment
|
||||
- Requirement-change assessment for design/interface/goal changes
|
||||
- C4/ADR/plan/todo alignment
|
||||
- Full-cycle architecture review
|
||||
|
||||
Canonical implementation/interface/architecture/product escalation rules are defined in `AirPlan/docs/architecture/scope-escalation-v1.md`.
|
||||
|
||||
### Scheduler
|
||||
|
||||
- Reads TaskGraph
|
||||
- Computes dependency order, write-area conflicts, waves, retries, workspaces
|
||||
- Spawns child agents as independent Bun processes
|
||||
- Monitors heartbeat and progress
|
||||
- Handles merge coordination
|
||||
|
||||
Canonical Scheduler task graph, wave, retry, heartbeat, workspace merge, and recovery state machine is defined in `AirPlan/docs/architecture/scheduler-state-machine-v1.md`.
|
||||
|
||||
### Worker Agents
|
||||
|
||||
- Executor: implementation/build/test verification
|
||||
- Reviewer: read-only code/static-analysis review
|
||||
- Debugger: evidence gathering, diagnosis, instrumentation, fix, verification
|
||||
- Compactor: copy-on-write context compaction
|
||||
- ExperienceMiner: memory/skill extraction, patching, promotion suggestions
|
||||
|
||||
Worker loops are independent implementations, not one generic shared loop.
|
||||
|
||||
## 7. RuntimeEvent and EventStore
|
||||
|
||||
Cross-cutting runtime semantics for EventIngestor, heartbeat coalescing, cross-DB/file side effects, compaction ownership, execution primitives, scanner behavior, and learning/skills lifecycle are defined in `AirPlan/docs/architecture/runtime-semantics-v1.md`.
|
||||
|
||||
Event envelope:
|
||||
|
||||
```ts
|
||||
interface RuntimeEvent<T = unknown> {
|
||||
id: string
|
||||
type: string
|
||||
version: number
|
||||
timestamp: string
|
||||
session_id: string
|
||||
project_id?: string
|
||||
source: EventSource
|
||||
route: string[]
|
||||
payload: T
|
||||
}
|
||||
```
|
||||
|
||||
`route` is an append-only structured route chain. Event durability is determined by EventStore based on event type, not by the event producer.
|
||||
|
||||
Canonical event names, payload schemas, persistence policy, and producer/consumer rules are defined in `AirPlan/docs/architecture/event-registry-v1.md`.
|
||||
|
||||
Persistence rules:
|
||||
|
||||
1. Event producers emit valid envelopes but do not decide storage ad hoc.
|
||||
2. EventStore owns persistence policy by event type.
|
||||
3. Durable event insert and matching domain table update happen in one SQLite transaction.
|
||||
4. Ephemeral stream/progress events may be throttled or coalesced by EventBus/ProjectionStore.
|
||||
5. Event payload schema changes increment that event type's `version`.
|
||||
|
||||
V1 durable event families:
|
||||
|
||||
```text
|
||||
session, message, agent, task, tool, command,
|
||||
artifact, diagnostic, evidence,
|
||||
context, summary, permission, doctor,
|
||||
requirement, architecture, workspace, memory, debug
|
||||
```
|
||||
|
||||
V1 ephemeral event families:
|
||||
|
||||
```text
|
||||
agent heartbeat, task progress, assistant message delta,
|
||||
tool progress, command stdout/stderr delta, HUD frame render
|
||||
```
|
||||
|
||||
## 8. IPC Protocol
|
||||
|
||||
Child agents are independent Bun processes.
|
||||
|
||||
IPC uses NDJSON over stdio.
|
||||
|
||||
Canonical IPC envelopes are defined in `AirPlan/docs/architecture/interface-contracts-v1.md`.
|
||||
|
||||
Required V1.0.0 Alpha IPC kinds:
|
||||
|
||||
```text
|
||||
control
|
||||
event
|
||||
log
|
||||
tool.call
|
||||
tool.result
|
||||
tool.stream
|
||||
worker.result
|
||||
worker.checkpoint
|
||||
protocol.error
|
||||
```
|
||||
|
||||
All request/response IPC messages include `id`, `direction`, `timestamp`, `session_id`, `agent_id`, and optional `correlation_id`.
|
||||
|
||||
- stdout: protocol only
|
||||
- stderr: crash fallback and fatal diagnostics
|
||||
|
||||
Exit codes:
|
||||
|
||||
```text
|
||||
0 protocol-level completion, including task failed/blocked
|
||||
1 uncaught exception
|
||||
2 startup/protocol error
|
||||
3 permission error
|
||||
4 parent cancelled
|
||||
5 hard timeout killed
|
||||
```
|
||||
|
||||
## 9. TaskSpec and WorkerResult
|
||||
|
||||
### TaskSpec
|
||||
|
||||
```ts
|
||||
interface TaskSpec {
|
||||
id: string
|
||||
type: "execute" | "review" | "debug" | "compact" | "mine_experience"
|
||||
title: string
|
||||
description: string
|
||||
acceptance_criteria: string[]
|
||||
scope: {
|
||||
write_area?: string
|
||||
expected_files?: string[]
|
||||
allowed_paths?: string[]
|
||||
denied_paths?: string[]
|
||||
}
|
||||
dependencies: Array<{
|
||||
depends_on_task_id: string
|
||||
dependency_type: "hard" | "soft" | "conflict" | "serialization"
|
||||
reason?: string
|
||||
source?: "architecture" | "scheduler" | "worker" | "user" | "system"
|
||||
}>
|
||||
verification: {
|
||||
commands?: string[]
|
||||
required: boolean
|
||||
fallback_allowed: boolean
|
||||
}
|
||||
constraints: {
|
||||
max_turns: number
|
||||
soft_timeout_ms: number
|
||||
hard_timeout_ms: number
|
||||
retry_budget: number
|
||||
model_policy: "scheduler_forced" | "agent_select"
|
||||
model_id?: string
|
||||
}
|
||||
context_refs: {
|
||||
plan_ref?: string
|
||||
arc_ref?: string
|
||||
parent_task_results?: string[]
|
||||
artifacts?: string[]
|
||||
}
|
||||
output_contract: "ExecutorResult" | "ReviewerResult" | "DebuggerResult" | "CompactorResult" | "ExperienceMinerResult"
|
||||
}
|
||||
```
|
||||
|
||||
### WorkerResult
|
||||
|
||||
```ts
|
||||
interface WorkerResult<T = unknown> {
|
||||
task_id: string
|
||||
agent_id: string
|
||||
agent_type: "executor" | "reviewer" | "debugger" | "compactor" | "experience_miner"
|
||||
status: "completed" | "failed" | "blocked" | "cancelled"
|
||||
summary: string
|
||||
changed_files: string[]
|
||||
diff_ref?: string
|
||||
artifacts: ArtifactRef[]
|
||||
verification: VerificationResult[]
|
||||
risks: Risk[]
|
||||
follow_up_tasks: FollowUpTask[]
|
||||
evidence_refs: EvidenceRef[]
|
||||
result: T
|
||||
}
|
||||
```
|
||||
|
||||
`failed` means the task goal was not achieved and Scheduler may retry/skip. `blocked` means upper-level decision is needed.
|
||||
|
||||
`summary` is a 3–6 sentence human-readable summary covering what was done, evidence, conclusion, and risk. It is not used for scheduling decisions.
|
||||
|
||||
## 10. Tool and Capability System
|
||||
|
||||
### ToolDefinition
|
||||
|
||||
```ts
|
||||
interface ToolDefinition<I = unknown, O = unknown> {
|
||||
name: string
|
||||
version: number
|
||||
description: string
|
||||
input_schema: JsonSchema<I>
|
||||
output_schema: JsonSchema<O>
|
||||
category: "filesystem" | "shell" | "build" | "test" | "debug" | "static_analysis" | "gui" | "network" | "memory" | "project" | "internal"
|
||||
permissions: {
|
||||
read_paths?: PathPolicy
|
||||
write_paths?: PathPolicy
|
||||
execute?: boolean
|
||||
network?: boolean
|
||||
system_sensitive?: boolean
|
||||
}
|
||||
streaming: boolean
|
||||
execute(input: I, context: ToolExecutionContext): AsyncIterable<ToolEvent> | Promise<ToolResult<O>>
|
||||
}
|
||||
```
|
||||
|
||||
Inputs and outputs are schema-validated. Streaming tools emit a final `tool.result`.
|
||||
|
||||
Canonical V1.0.0 Alpha built-in tool names, input/output schemas, and cut lines are defined in `AirPlan/docs/architecture/tool-registry-v1.md`.
|
||||
|
||||
Bash is implemented as `shell.run`, a normal shell tool with extra PermissionEngine risk analysis.
|
||||
|
||||
### Capability
|
||||
|
||||
Capabilities are runtime-registered tool bundles with dependencies, triggers, evidence types, and config schema.
|
||||
|
||||
Canonical capability manifest, source trust, dependency declaration, permission declaration, lifecycle, event namespace, and enable/update rules are defined in `AirPlan/docs/architecture/capability-trust-v1.md`.
|
||||
|
||||
Capability manifests declare dependencies; they do not install them directly.
|
||||
|
||||
Doctor/setup manages detection and installation.
|
||||
|
||||
## 11. Doctor and Dependency Policy
|
||||
|
||||
- First startup runs read-only doctor automatically.
|
||||
- If issues exist, user is prompted to run fix.
|
||||
- High-permission mode may `announce_then_run` dependency installation after first startup.
|
||||
- First startup always asks before `doctor --fix`, even in high-permission mode.
|
||||
- `credentials` and `system_sensitive` dependencies always require explicit confirmation.
|
||||
|
||||
## 12. Permission and Security Model
|
||||
|
||||
Canonical local security boundaries, permission profiles, path classification, command risk analysis, network policy, credential handling, logs/export rules, and refusal/block conditions are defined in `AirPlan/docs/architecture/security-model-v1.md`.
|
||||
|
||||
Core principles:
|
||||
|
||||
```text
|
||||
read → allow
|
||||
project directory → allow
|
||||
project-outside non-system → backup then allow
|
||||
system-sensitive → explicit confirmation
|
||||
credentials → explicit confirmation
|
||||
```
|
||||
|
||||
Project-outside backups are stored as a git repo at:
|
||||
|
||||
```text
|
||||
<project>/.air/local/backups/
|
||||
```
|
||||
|
||||
## 13. Session DB and Domain State
|
||||
|
||||
Session DB path:
|
||||
|
||||
```text
|
||||
<project>/.air/local/sessions/<session-id>/session.db
|
||||
```
|
||||
|
||||
Canonical schema details are defined in `AirPlan/docs/architecture/db-schema-v1.md`.
|
||||
|
||||
Canonical message storage:
|
||||
|
||||
- `messages` stores complete Anthropic canonical content JSON.
|
||||
- `message_drafts` stores streaming assistant intermediate state and is deleted after final completion.
|
||||
- `message_parts` is not a source-of-truth MVP table.
|
||||
|
||||
Domain state tables are the source of truth for scheduling/recovery/query:
|
||||
|
||||
```text
|
||||
tasks
|
||||
task_dependencies
|
||||
task_attempts
|
||||
agents
|
||||
tool_runs
|
||||
command_runs
|
||||
artifacts
|
||||
diagnostics
|
||||
evidence_refs
|
||||
workspaces
|
||||
events
|
||||
ui_state
|
||||
```
|
||||
|
||||
Query-friendly columns are preferred over parsing JSON. Examples:
|
||||
|
||||
- `tool_runs.origin_message_id`
|
||||
- `command_runs.origin_message_id`
|
||||
- common artifact foreign keys (`task_id`, `agent_id`, `tool_run_id`, `command_run_id`)
|
||||
- event source/task/agent/tool/command IDs
|
||||
- `route_json` plus `route_text`
|
||||
|
||||
`ui_state` stores only UI recovery state and is flushed periodically plus on normal exit.
|
||||
|
||||
## 14. Contract V1 Type Baseline
|
||||
|
||||
Canonical implementation-facing service/interface contracts are defined in `AirPlan/docs/architecture/interface-contracts-v1.md`.
|
||||
|
||||
Shared implementation contracts live in a dedicated package:
|
||||
|
||||
```text
|
||||
packages/contracts/
|
||||
runtime.ts
|
||||
event.ts
|
||||
ipc.ts
|
||||
task.ts
|
||||
worker-result.ts
|
||||
tool.ts
|
||||
artifact.ts
|
||||
project.ts
|
||||
provider.ts
|
||||
ui.ts
|
||||
error.ts
|
||||
```
|
||||
|
||||
Principles:
|
||||
|
||||
1. Contracts must be compileable and shared by runtime, TUI, LLM, and toolchain packages.
|
||||
2. Shape stability matters more than perfect detail in V1.
|
||||
3. Schema-heavy fields may start as `unknown` and tighten later.
|
||||
4. ContextPack stays lightweight and reference-based; large context bodies are stored as artifacts/summaries and loaded through ContextAssembler.
|
||||
5. Domain packages depend on `packages/contracts`; they must not import each other's private types.
|
||||
|
||||
Core identity aliases:
|
||||
|
||||
```ts
|
||||
type ISOTimeString = string
|
||||
type UUID = string
|
||||
type ProjectID = string
|
||||
type SessionID = string
|
||||
type TaskID = string
|
||||
type AgentID = string
|
||||
type ToolRunID = string
|
||||
type CommandRunID = string
|
||||
type ArtifactID = string
|
||||
type MessageID = string
|
||||
```
|
||||
|
||||
Core event source:
|
||||
|
||||
```ts
|
||||
interface EventSource {
|
||||
kind: "main" | "architecture_designer" | "scheduler" | "agent" | "tool" | "system"
|
||||
id?: string
|
||||
agent_type?: "executor" | "reviewer" | "debugger" | "compactor" | "experience_miner"
|
||||
}
|
||||
```
|
||||
|
||||
Control messages:
|
||||
|
||||
```ts
|
||||
type ControlMessage =
|
||||
| {
|
||||
type: "agent.start"
|
||||
version: 1
|
||||
task_spec: TaskSpec
|
||||
context_pack: ContextPack
|
||||
runtime: AgentRuntimeContext
|
||||
}
|
||||
| { type: "agent.cancel"; reason: string }
|
||||
| { type: "agent.pause"; reason: string }
|
||||
| { type: "agent.resume" }
|
||||
| { type: "agent.extend_timeout"; extra_ms: number; reason: string }
|
||||
|
||||
interface AgentRuntimeContext {
|
||||
session_id: SessionID
|
||||
project_id: ProjectID
|
||||
agent_id: AgentID
|
||||
worktree_path?: string
|
||||
permission_template: "main_direct" | "executor" | "reviewer" | "debugger" | "system"
|
||||
}
|
||||
```
|
||||
|
||||
ContextPack:
|
||||
|
||||
```ts
|
||||
interface ContextPack {
|
||||
refs: {
|
||||
plan_ref?: string
|
||||
arc_ref?: string
|
||||
task_refs?: string[]
|
||||
artifact_refs?: string[]
|
||||
rule_refs?: string[]
|
||||
}
|
||||
assembled_context_ref?: string
|
||||
notes?: string[]
|
||||
}
|
||||
```
|
||||
|
||||
Common result helpers:
|
||||
|
||||
```ts
|
||||
interface VerificationResult {
|
||||
name: string
|
||||
status: "passed" | "failed" | "skipped" | "unknown"
|
||||
evidence_refs?: string[]
|
||||
notes?: string
|
||||
}
|
||||
|
||||
interface Risk {
|
||||
severity: "low" | "medium" | "high"
|
||||
summary: string
|
||||
}
|
||||
|
||||
interface FollowUpTask {
|
||||
title: string
|
||||
description: string
|
||||
type?: "execute" | "review" | "debug" | "docs"
|
||||
}
|
||||
```
|
||||
|
||||
Provider capability matrix, model assignment, adapter conversion, fallback policy, and doctor checks are defined in `AirPlan/docs/architecture/provider-capability-matrix-v1.md`.
|
||||
|
||||
Canonical error kinds, severity, retryability, failure signatures, user-facing formatting, and Scheduler routing are defined in `AirPlan/docs/architecture/error-taxonomy-v1.md`.
|
||||
|
||||
`TaskSpec`, `WorkerResult`, `RuntimeEvent`, `ToolDefinition`, `ArtifactRef`, and `EvidenceRef` are defined by earlier sections of this baseline and must be exported from `packages/contracts`.
|
||||
|
||||
## 15. Artifact Layout
|
||||
|
||||
Artifacts live under:
|
||||
|
||||
```text
|
||||
<project>/.air/local/sessions/<session-id>/artifacts/
|
||||
```
|
||||
|
||||
Canonical URI format, artifact ID format, filename conventions, directory mapping, compression, metadata, write protocol, and evidence linking are defined in `AirPlan/docs/architecture/artifact-naming-v1.md`.
|
||||
|
||||
## 15. Context and Compaction
|
||||
|
||||
ContextAssembler outputs Anthropic canonical messages. Provider conversion happens only at the LLM adapter boundary.
|
||||
|
||||
Canonical prompt/context layer order, agent-specific context profiles, conflict handling, and prompt asset locations are defined in `AirPlan/docs/architecture/prompt-layering-v1.md`.
|
||||
|
||||
ContextAssembler records omissions and publishes `context.compaction.requested` when compaction is needed; it does not compact itself.
|
||||
|
||||
Compaction rules use Markdown + YAML frontmatter.
|
||||
|
||||
Rule locations:
|
||||
|
||||
```text
|
||||
built-in default
|
||||
~/.air/compaction-rules.md
|
||||
<project>/.air/shared/compaction-rules.md
|
||||
```
|
||||
|
||||
Compaction uses copy-on-write:
|
||||
|
||||
```text
|
||||
snapshot messages 1-N
|
||||
→ async Compactor subagent
|
||||
→ new messages keep appending
|
||||
→ compaction marker inserted when done
|
||||
→ original messages preserved for explicit backtracking
|
||||
```
|
||||
|
||||
## 16. Memory, Skills, and Debug Knowledge
|
||||
|
||||
Project Rules:
|
||||
|
||||
```text
|
||||
<project>/.air/shared/rules/project-rules.md
|
||||
```
|
||||
|
||||
Skills:
|
||||
|
||||
```text
|
||||
~/.air/skills/<skill-name>/SKILL.md
|
||||
```
|
||||
|
||||
ExperienceMiner triggers:
|
||||
|
||||
- DebugRecord produced
|
||||
- session end
|
||||
- N turns/tool calls interval
|
||||
- existing skill/rule discovered outdated during execution
|
||||
|
||||
Non-debug experiences promote after repeated occurrence and user confirmation. Debug experience confidence comes from evidence and verification, not numeric scoring.
|
||||
|
||||
Debug Knowledge is local-first. Sharing/upload is a separate explicit flow and must be redacted/previewed.
|
||||
|
||||
## 17. Provider and Model Layer
|
||||
|
||||
- Native providers: Anthropic and OpenAI
|
||||
- Compatibility: OpenRouter, ollama, custom Anthropic/OpenAI-compatible endpoints
|
||||
- Internal canonical message format: Anthropic content blocks
|
||||
- Cross-provider conversion happens at the adapter boundary
|
||||
- Same-provider model switching has no format conversion cost
|
||||
- Canonical provider/model capability contract is defined in `AirPlan/docs/architecture/provider-capability-matrix-v1.md`
|
||||
|
||||
## 18. TUI and HUD
|
||||
|
||||
TUI uses OpenTUI/Solid.
|
||||
|
||||
Reuse from OpenCode:
|
||||
|
||||
- theme system
|
||||
- dialog/modal/toast patterns
|
||||
- keymap wrapper
|
||||
- layout style
|
||||
- spinner/border/error components
|
||||
- markdown/code/diff rendering patterns
|
||||
|
||||
Do not reuse OpenCode SDK/sync/session business layer.
|
||||
|
||||
HUD/TUI consumes ProjectionStore only.
|
||||
|
||||
```text
|
||||
DB persistent state + EventBus live events
|
||||
→ ProjectionStore
|
||||
→ TUI/HUD
|
||||
```
|
||||
|
||||
HUD never directly queries SQLite.
|
||||
|
||||
## 19. UI Design Asset Capability
|
||||
|
||||
AirCoding supports optional `ui-design-assets` capability.
|
||||
|
||||
MVP supports:
|
||||
|
||||
- ASCII/wireframe mockups
|
||||
- design specs
|
||||
- SVG icons
|
||||
- screenshot design analysis
|
||||
- prompts for external image generators
|
||||
|
||||
Post-MVP supports bitmap image generation/editing via providers.
|
||||
|
||||
Generated UI/design assets are artifacts first and must be shown to the user before being written into project files.
|
||||
|
||||
## 20. C++ Toolchain V1.0.0 Alpha
|
||||
|
||||
`toolchain-cpp` provides:
|
||||
|
||||
- BuildTool: CMake built-in, Ninja first then Make fallback
|
||||
- DiagnosticParser: deterministic compiler/linker output extraction and semantic signatures (LLM-based interpretation belongs to runtime Debugger/Reviewer, not toolchain)
|
||||
- TestRunner: CTest + GoogleTest first
|
||||
- StaticAnalysis: cppcheck built-in, clang-tidy later
|
||||
- CodeIntelligence: clangd CLI mode first
|
||||
- `compile_commands.json`: generated on demand, not persisted as cache
|
||||
|
||||
Build-system conflicts are shown to the user.
|
||||
|
||||
BuildTool attempts built-in repair first; unresolved failures route to Debugger.
|
||||
|
||||
## 21. Project Initialization
|
||||
|
||||
Scanner collects filesystem metadata only:
|
||||
|
||||
- full directory tree
|
||||
- file extension statistics
|
||||
- special files
|
||||
- git summary
|
||||
|
||||
No directory exclusions and no depth limit.
|
||||
|
||||
LLM proposes ProjectProfile; user confirms/corrects.
|
||||
|
||||
Project schema lives at:
|
||||
|
||||
```text
|
||||
<project>/.air/shared/project.json
|
||||
```
|
||||
|
||||
Old schema detection triggers migration plan and user confirmation.
|
||||
|
||||
## 22. Migration
|
||||
|
||||
- Opening a project detects `.air` schema versions.
|
||||
- Old schema shows a migration plan.
|
||||
- User confirmation is always required, even in high-permission mode.
|
||||
- `.air` is backed up first.
|
||||
- Failure rolls back.
|
||||
|
||||
Migration backups should be stored under project-local backup state, e.g.:
|
||||
|
||||
```text
|
||||
<project>/.air/local/backups/migrations/<timestamp>/
|
||||
```
|
||||
|
||||
## 23. Logging and Doctor Bundles
|
||||
|
||||
`air.log` is user-readable and contains startup failures, exceptions, and environment configuration issues.
|
||||
|
||||
`air.developer.log` is full debug/performance log encrypted with the development team's public key.
|
||||
|
||||
Doctor bundles may include full diagnostics and are not automatically redacted. They are never automatically uploaded; user must explicitly export/send them.
|
||||
|
||||
Doctor bundles and Debug Knowledge sharing are separate channels:
|
||||
|
||||
- doctor bundle: development-team diagnostic channel
|
||||
- Debug Knowledge: shareable knowledge channel that requires redaction, preview, and explicit authorization
|
||||
|
||||
## 24. Testing
|
||||
|
||||
- Unit tests: `bun test`, CI, deterministic, no LLM
|
||||
- Integration tests: CI, recorded LLM fixture replay
|
||||
- E2E tests: release gate, real LLM, must pass before release
|
||||
- Platform support levels and release validation matrix are defined in `AirPlan/docs/architecture/cross-platform-matrix-v1.md`
|
||||
|
||||
## 25. Distribution
|
||||
|
||||
Canonical platform support levels, distribution targets, and release gates are defined in `AirPlan/docs/architecture/cross-platform-matrix-v1.md`.
|
||||
|
||||
Early distribution uses binary tarball:
|
||||
|
||||
```text
|
||||
bin/air
|
||||
resources/
|
||||
LICENSE
|
||||
```
|
||||
|
||||
Resources include templates, prompts, themes, HUD presets, Python scripts, and toolchain resources.
|
||||
|
||||
No public npm/brew/apt/winget channel until stable.
|
||||
|
||||
## 26. V1.0.0 Alpha Prerequisite Baselines
|
||||
|
||||
This baseline is sufficient for formal architecture design and V1.0.0 Alpha implementation planning. The following prerequisite baselines are frozen for V1:
|
||||
|
||||
1. Interface contracts: `AirPlan/docs/architecture/interface-contracts-v1.md`.
|
||||
2. SQLite schema: `AirPlan/docs/architecture/db-schema-v1.md`.
|
||||
3. Event payload registry: `AirPlan/docs/architecture/event-registry-v1.md`.
|
||||
4. Tool registry: `AirPlan/docs/architecture/tool-registry-v1.md`.
|
||||
5. Scheduler state machine: `AirPlan/docs/architecture/scheduler-state-machine-v1.md`.
|
||||
6. Prompt layering model: `AirPlan/docs/architecture/prompt-layering-v1.md`.
|
||||
7. Provider capability matrix: `AirPlan/docs/architecture/provider-capability-matrix-v1.md`.
|
||||
8. Error taxonomy: `AirPlan/docs/architecture/error-taxonomy-v1.md`.
|
||||
9. Artifact naming/layout: `AirPlan/docs/architecture/artifact-naming-v1.md`.
|
||||
10. Scope escalation model: `AirPlan/docs/architecture/scope-escalation-v1.md`.
|
||||
11. Security model: `AirPlan/docs/architecture/security-model-v1.md`.
|
||||
12. Capability trust model: `AirPlan/docs/architecture/capability-trust-v1.md`.
|
||||
13. Cross-platform matrix: `AirPlan/docs/architecture/cross-platform-matrix-v1.md`.
|
||||
14. Runtime semantics: `AirPlan/docs/architecture/runtime-semantics-v1.md`.
|
||||
|
||||
V1.0.0 Alpha scope includes a complete C++ development workflow and local/built-in plugin capability foundation.
|
||||
36
AirPlan/docs/architecture/branch-deepcode-cli/README.md
Normal file
36
AirPlan/docs/architecture/branch-deepcode-cli/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# DeepCode CLI Branch
|
||||
|
||||
Date: 2026-05-28
|
||||
Status: AirCoding mainline branch, pre-design research phase
|
||||
|
||||
DeepCode CLI is a mainline AirCoding branch (not a downstream simplification like VibeBox). It explores integrating DeepSeek's model architecture innovations and research capabilities into the AirCoding agent runtime.
|
||||
|
||||
## Reference Documents
|
||||
|
||||
- [DeepSeek Research Survey](deepseek-research-survey.md) — Complete inventory of DeepSeek papers, models, architectures, and technical innovations (36 repos, ~395K stars)
|
||||
|
||||
## Key DeepSeek Innovations Relevant to DeepCode CLI
|
||||
|
||||
1. **Multi-head Latent Attention (MLA)** — 93% KV cache reduction for long code contexts
|
||||
2. **DeepSeekMoE** — Fine-grained experts + shared experts, 37B activated from 671B total
|
||||
3. **GRPO** — RL without critic model, applicable to code/debug agent training
|
||||
4. **DeepSeek Sparse Attention** — Efficient long-context processing
|
||||
5. **DeepSeek-Coder/V2** — Fill-in-Middle, SWE-bench, Codeforces competitive
|
||||
6. **DeepSeek-R1** — Emergent chain-of-thought reasoning via pure RL
|
||||
7. **DeepSeek-Prover-V2** — Formal Lean 4 theorem proving
|
||||
8. **DeepSeek-Math-V2** — Self-verifiable reasoning, IMO 2025 gold
|
||||
9. **Engram** — Conditional memory sparsity as new axis beyond MoE
|
||||
10. **DeepSeek-OCR/OCR-2** — Visual understanding for GUI evidence
|
||||
11. **3FS/FlashMLA/DeepGEMM/DeepEP/DualPipe** — Full inference infrastructure stack
|
||||
|
||||
## Open Design Questions
|
||||
|
||||
1. How does DeepCode CLI relate to AirCoding mainline — does it add DeepSeek as a provider, or fork architecture?
|
||||
2. Which DeepSeek innovations should DeepCode CLI adopt at the runtime level vs. treat as provider capabilities?
|
||||
3. Does DeepCode CLI target DeepSeek models as primary, or remain provider-agnostic with DeepSeek optimizations?
|
||||
4. Should MLA/MoE-aware context assembly be part of the runtime, or handled by provider adapter?
|
||||
5. How should formal proving (Prover-V2) integrate with the existing review/debug workflow?
|
||||
6. Should self-verifiable reasoning (Math-V2 style) influence the verification architecture?
|
||||
7. Does DeepCode CLI need its own GRPO-trained code agent, or reuse general DeepSeek models?
|
||||
8. How does the Engram conditional memory concept map to AirCoding's memory/skills system?
|
||||
9. Should infrastructure tools (3FS, smallpond) be optional capabilities for large-codebase workflows?
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,689 @@
|
||||
# DeepSeek Research Survey
|
||||
|
||||
Date: 2026-05-28
|
||||
Status: Reference survey for DeepCode CLI branch
|
||||
|
||||
Source: GitHub deepseek-ai organization API + README fetches, arXiv references, training data.
|
||||
Note: Some 2025-2026 details may need further verification against latest arXiv publications.
|
||||
|
||||
## 1. DeepSeek Company Overview
|
||||
|
||||
DeepSeek is a Chinese AI research company backed by High-Flyer quantitative fund. They have been remarkably prolific, publishing 15+ significant open-source papers and model releases across MoE architecture, reasoning, code, math, vision, multimodal, and infrastructure — all with open-source weights and MIT/Apache 2.0 licenses.
|
||||
|
||||
Key architectural innovations:
|
||||
|
||||
- **Multi-head Latent Attention (MLA)**: KV cache compression via low-rank latent representation, ~93% cache reduction
|
||||
- **DeepSeekMoE**: Fine-grained expert segmentation + shared experts + topology-aware routing
|
||||
- **GRPO (Group Relative Policy Optimization)**: RL without separate critic model
|
||||
- **DeepSeek Sparse Attention (DSA)**: Fine-grained sparse attention for long-context efficiency
|
||||
- **Engram**: Conditional memory via N-gram embeddings as a new sparsity axis complementary to MoE
|
||||
|
||||
## 2. Complete Model/Repository Inventory
|
||||
|
||||
### 2.1 Foundation Language Models
|
||||
|
||||
| Repository | Description | Stars | Key Features |
|
||||
|---|---|---|---|
|
||||
| `DeepSeek-LLM` | Base LLM series (7B/67B) | 6,954 | First foundation model, Llama-style architecture |
|
||||
| `DeepSeek-V2` | MoE with MLA | 5,009 | 236B total/21B activated, MLA, DeepSeekMoE |
|
||||
| `DeepSeek-V3` | Large MoE | 103,641 | 671B total/37B activated, FP8 training, ~$5.5M cost |
|
||||
| `DeepSeek-V3.1-Exp` | Experimental model | 1,594 | Benchmark improvements over V3 |
|
||||
| `DeepSeek-V3.2-Exp` | Experimental sparse attention | 1,593 | DeepSeek Sparse Attention (DSA), long-context optimization |
|
||||
| `DeepSeek-V3.2-Exp-Dense` | Dense attention variant | 1,593 supplement | Matches V3.1-Terminus benchmarks |
|
||||
| `DeepSeek-V4-Pro` | Latest flagship MoE | — | 1.6T total/49B activated, CSA+HCA hybrid attention, MIT license, Apr 23 2026 |
|
||||
| `DeepSeek-R1` | Reasoning model | 92,019 | Pure RL reasoning (GRPO), competes with OpenAI o1 |
|
||||
| `DeepSeek-R1-Lite` | Lightweight reasoning | — | Lighter R1 variant |
|
||||
| `DeepSeek-MoE` | MoE research | 1,934 | Fine-grained expert specialization paper |
|
||||
|
||||
### 2.2 Code Models
|
||||
|
||||
| Repository | Description | Stars | Key Features |
|
||||
|---|---|---|---|
|
||||
| `DeepSeek-Coder` | Code LLM (1.3B-33B) | 23,509 | Code-focused training, Fill-in-Middle |
|
||||
| `DeepSeek-Coder-V2` | MoE code model | 6,791 | 236B MoE, breaks closed-source barrier in code intelligence |
|
||||
|
||||
### 2.3 Math and Formal Reasoning
|
||||
|
||||
| Repository | Description | Stars | Key Features |
|
||||
|---|---|---|---|
|
||||
| `DeepSeek-Math` | Math reasoning (7B) | 3,298 | GRPO introduced, mathematical reasoning |
|
||||
| `DeepSeek-Math-V2` | Self-verifiable math reasoning | 1,589 | IMO 2025 gold, Putnam 2024 118/120, verifier-generator loop |
|
||||
| `DeepSeek-Prover-V1.5` | Formal theorem prover | 574 | Lean 4, RL + MCTS for proof search |
|
||||
| `DeepSeek-Prover-V2` | Advanced formal prover | 1,267 | Recursive subgoal decomposition, DeepSeek-V3 powered |
|
||||
|
||||
### 2.4 Vision and Multimodal
|
||||
|
||||
| Repository | Description | Stars | Key Features |
|
||||
|---|---|---|---|
|
||||
| `DeepSeek-VL` | Vision-Language | 4,116 | Real-world vision-language understanding |
|
||||
| `DeepSeek-VL2` | MoE Vision-Language | 5,291 | MoE-based multimodal understanding |
|
||||
| `Janus` | Unified multimodal | 17,733 | Decoupled visual encoding for understanding + generation |
|
||||
| `DeepSeek-OCR` | OCR/context compression | 23,186 | Context optical compression |
|
||||
| `DeepSeek-OCR-2` | Visual Causal Flow | 2,889 | arXiv: 2601.20552, next-gen OCR |
|
||||
|
||||
### 2.5 Training/Inference Infrastructure
|
||||
|
||||
| Repository | Description | Stars | Key Features |
|
||||
|---|---|---|---|
|
||||
| `DualPipe` | Bidirectional pipeline parallelism | 2,955 | Computation-communication overlap for V3/R1 training |
|
||||
| `DeepGEMM` | FP8 GEMM kernels | 7,308 | Clean, efficient FP8 with fine-grained scaling |
|
||||
| `FlashMLA` | Efficient MLA kernels | 12,670 | Optimized Multi-head Latent Attention GPU kernels |
|
||||
| `DeepEP` | Expert-parallel communication | 9,679 | Efficient expert-parallel communication library |
|
||||
| `EPLB` | Expert Parallelism Load Balancer | 1,380 | Production MoE load balancing |
|
||||
| `LPLB` | Linear programming load balancer | 505 | Research-stage LP-based expert load balancing |
|
||||
| `TileKernels` | Tilelang kernel library | 1,559 | Kernel library written in tilelang |
|
||||
| `3FS` | Distributed file system | 9,931 | High-performance FS for AI training/inference |
|
||||
| `smallpond` | Data processing framework | 4,961 | Lightweight, built on DuckDB and 3FS |
|
||||
| `profile-data` | Overlap analysis | 1,158 | Analyze computation-communication overlap in V3/R1 |
|
||||
| `open-infra-index` | Infrastructure index | 8,001 | Production-tested AI infrastructure tools |
|
||||
|
||||
### 2.6 Research/Training Innovations
|
||||
|
||||
| Repository | Description | Stars | Key Features |
|
||||
|---|---|---|---|
|
||||
| `Engram` | Conditional memory sparsity | 4,427 | N-gram lookup as new sparsity axis beyond MoE |
|
||||
| `ESFT` | Expert-Specialized Fine-Tuning | 735 | EMNLP 2024, tune only task-relevant MoE experts |
|
||||
|
||||
### 2.7 Agent/Ecosystem
|
||||
|
||||
| Repository | Description | Stars |
|
||||
|---|---|---|
|
||||
| `awesome-deepseek-agent` | Agent project curation | 2,582 |
|
||||
| `awesome-deepseek-integration` | API integration examples | 37,621 |
|
||||
| `awesome-deepseek-coder` | Code project curation | 788 |
|
||||
|
||||
## 3. Key Papers (Chronological)
|
||||
|
||||
### 2024
|
||||
|
||||
| Paper | arXiv | Key Contribution |
|
||||
|---|---|---|
|
||||
| DeepSeekMoE | 2401.06066 | Fine-grained MoE with shared experts |
|
||||
| DeepSeek-Coder | 2401.14196 | Code-focused LLM with Fill-in-Middle |
|
||||
| DeepSeekMath | 2402.03300 | GRPO algorithm, mathematical reasoning |
|
||||
| DeepSeek-VL | 2403.05525 | Real-world vision-language understanding |
|
||||
| DeepSeek-V2 | 2405.04434 | Multi-head Latent Attention (MLA) + DeepSeekMoE |
|
||||
| DeepSeek-Coder-V2 | 2406.11931 | MoE code model breaking closed-source barrier |
|
||||
| ESFT | 2407.01906 | Expert-Specialized Fine-Tuning for MoE |
|
||||
| Fire-Flyer AI-HPC | 2408.14158 | Cost-effective software-hardware co-design |
|
||||
| DeepSeek-Prover-V1.5 | 2408.08152 | RL + MCTS for formal theorem proving |
|
||||
| Janus | 2410.13848 | Decoupled visual encoding for unified multimodal |
|
||||
| JanusFlow | 2411.05820 | Autoregression + Rectified Flow for multimodal |
|
||||
| DeepSeek-VL2 | 2412.10302 | MoE vision-language models |
|
||||
| DeepSeek-V3 | 2412.19437 | 671B MoE, FP8 training, $5.5M cost |
|
||||
|
||||
### 2025
|
||||
|
||||
| Paper | arXiv | Key Contribution |
|
||||
|---|---|---|
|
||||
| DeepSeek-R1 | 2501.12948 | Pure RL reasoning, GRPO, emergent CoT |
|
||||
| Native Sparse Attention | 2502.11089 | Hardware-aligned trainable sparse attention |
|
||||
| DeepSeek-V3.2 | 2512.02556 | DSA + Scalable RL + Agentic Task Synthesis Pipeline |
|
||||
| DeepSeek-OCR-2 | 2601.20552 | Visual Causal Flow |
|
||||
|
||||
### 2026
|
||||
|
||||
| Paper | arXiv | Key Contribution |
|
||||
|---|---|---|
|
||||
| DeepSeek-Prover-V2 | — | Recursive subgoal decomposition for Lean 4 |
|
||||
| DeepSeek-Math-V2 | — | Self-verifiable math reasoning, IMO gold |
|
||||
| DeepSeek-V4 | DeepSeek_V4.pdf (HF) | V4-Pro (1.6T/49B) + V4-Flash (284B/13B), CSA+HCA, mHC, Muon, MIT |
|
||||
|
||||
### Undated / In Repo
|
||||
|
||||
| Paper | Source | Key Contribution |
|
||||
|---|---|---|
|
||||
| Engram | Repo | Conditional memory via scalable lookup |
|
||||
| DualPipe | Repo | Bidirectional pipeline parallelism |
|
||||
|
||||
## 4. Agent Optimization Guide (针对 DeepCode CLI Agent 优化)
|
||||
|
||||
### 4.1 Model Selection by Task
|
||||
|
||||
| Task | Recommended Model | Reasoning |
|
||||
|---|---|---|
|
||||
| Code generation (complex) | V4-Pro / V4-Pro-Max | 80.6% SWE-bench, 93.5 LiveCodeBench |
|
||||
| Code gen (simple/high volume) | V4-Flash | 13B active, $0.14/M in, 74% cheaper than GPT-4o |
|
||||
| Architecture design / Refactoring | V4-Pro + R1 hybrid | R1 for reasoning plan, V4-Pro for execution |
|
||||
| Debugging / Root cause analysis | R1 / V4-Pro reasoning mode | Internal CoT, self-verification, reflection |
|
||||
| Code review | V3.2 / V4-Pro | Strong Codeforces + Aider scores |
|
||||
| Formal verification | DeepSeek-Prover-V2 | Lean 4 theorem proving |
|
||||
| Documentation / Explanations | V4-Flash | Cost-effective, fast |
|
||||
| Long-context analysis (1M tokens) | V4-Pro | CSA+HCA, 10% KV cache of V3.2 |
|
||||
| Chat / Interactive | V4-Flash | Low latency, fast TTFT |
|
||||
| Math-heavy reasoning | V3.2-Speciale / R1 | IMO 2025 gold, Putnam 118/120 |
|
||||
|
||||
### 4.2 Prompting Strategies for Coding Agents
|
||||
|
||||
#### V4 Pro / Flash (Chat Models — Non-Thinking)
|
||||
```text
|
||||
Effective patterns:
|
||||
- ✅ Use system prompts with explicit persona and constraints
|
||||
- ✅ Provide XML/fenced output format instructions
|
||||
- ✅ Use few-shot examples in user messages
|
||||
- ⚠️ Temperature: 0.3-0.6 (coding = 0.3, creative = 0.6)
|
||||
- ✅ Structured outputs via JSON schema in system prompt
|
||||
- ✅ Function calling / tool use natively supported
|
||||
|
||||
Example system prompt for coding agent:
|
||||
You are an expert software engineer. Write production-ready, well-typed code.
|
||||
Follow the project conventions. Use concise explanations.
|
||||
Output code blocks with language tags.
|
||||
```
|
||||
|
||||
#### R1 / Reasoning Models (Thinking Mode)
|
||||
```text
|
||||
Critical differences from chat models:
|
||||
- ❌ System prompts are WEAK — R1 deprioritizes them during thinking
|
||||
- ✅ Put ALL instructions in the USER prompt
|
||||
- ✅ Explicit output format MUST come LAST (after reasoning completes)
|
||||
- ✅ Temperature: 0.5-0.7 (0.6 recommended)
|
||||
- ✅ Use <think> tags for internal reasoning naturally
|
||||
- ⚠️ Vague prompts → excessively long thinking (waste tokens)
|
||||
- ✅ Precise, well-scoped questions → concise, accurate answers
|
||||
- ✅ For coding: provide exact file path, language, constraints
|
||||
|
||||
Example prompt for R1:
|
||||
Write a Python function that [specific task].
|
||||
Constraints: [list].
|
||||
File: [path/to/file.py].
|
||||
Output ONLY valid JSON: {"code": "...", "explanation": "..."}
|
||||
```
|
||||
|
||||
#### Hybrid Strategy (Recommended for DeepCode CLI)
|
||||
```text
|
||||
Step 1: Problem Analysis (R1)
|
||||
- Use R1 to reason about architecture, debug root cause, plan refactoring
|
||||
- Let it think freely, capture the plan
|
||||
|
||||
Step 2: Code Generation (V4-Pro / V4-Flash)
|
||||
- Feed R1's plan as context to V4-Pro with explicit system prompt
|
||||
- Generate actual code with tool use
|
||||
|
||||
Step 3: Verification (V4-Pro / Prover-V2)
|
||||
- Code review, test generation, formal verification
|
||||
```
|
||||
|
||||
### 4.3 API Configuration for Agent Use
|
||||
|
||||
| Parameter | V4-Pro | V4-Flash | R1 |
|
||||
|---|---|---|---|
|
||||
| Model name | `deepseek-v4-pro` | `deepseek-v4-flash` | `deepseek-reasoner` |
|
||||
| Input price /1M | $1.74 | $0.14 | $0.50 (V3.2 pricing) |
|
||||
| Output price /1M | $3.48 | $0.28 | $2.18 |
|
||||
| Context window | 1,000,000 | 1,000,000 | 164K |
|
||||
| Max output | 384K | 384K | 8K |
|
||||
| Function calling | ✓ | ✓ | limited |
|
||||
| Streaming | ✓ | ✓ | ✓ |
|
||||
| Prompt caching | ✓ | ✓ | — |
|
||||
| Assistant prefill | ✓ | ✓ | — |
|
||||
| Vision (PDF/Image) | ✓ | ✓ | — |
|
||||
|
||||
#### Cost Optimization for Agent Loops
|
||||
```text
|
||||
V4-Flash for high-volume agentic tasks:
|
||||
- Triage, classification, simple edits: V4-Flash ($0.14/$0.28)
|
||||
- Complex reasoning, multi-step: V4-Pro ($1.74/$3.48)
|
||||
- Planning/pre-analysis: R1 ($0.50/$2.18)
|
||||
|
||||
Prompt caching strategy:
|
||||
- Long system prompt + repeated context → cached (cache hit ≈ 10% cost)
|
||||
- Prefix-aware: keep consistent prefix for repetitive agent tasks
|
||||
- 90% cache hit rate → effective cost ~$0.17/M for V4-Pro
|
||||
|
||||
Typical agent cost estimates:
|
||||
- V4-Flash per agent step: ~$0.001-0.005 (assuming 2K in/1K out)
|
||||
- V4-Pro per agent step: ~$0.01-0.05
|
||||
- 100-step agentic workflow with V4-Flash: ~$0.10-0.50
|
||||
```
|
||||
|
||||
### 4.4 Context Window Strategy for Agents
|
||||
|
||||
#### V4-Pro 1M Context: Tiered Access
|
||||
```text
|
||||
Sliding window (128 tokens): Immediate local context (always dense)
|
||||
CSA (4x compression, top-1024): Project-level context (selected)
|
||||
HCA (128x compression, dense): Full repository context (compressed)
|
||||
|
||||
For DeepCode CLI:
|
||||
- Active file: sliding window (always precise)
|
||||
- Related files (imports, types): CSA tier (selective)
|
||||
- Full project map: HCA tier (compressed summary)
|
||||
- Git history, conventions, README: HCA tier
|
||||
```
|
||||
|
||||
#### Context Budget Allocation
|
||||
```text
|
||||
System prompt / Agent rules: 4K (stable, cached)
|
||||
Project conventions / AGENTS.md: 4K (stable, cached)
|
||||
Current file context: 16K (sliding window)
|
||||
Related files: 32K (CSA-selected)
|
||||
Open files / tabs: ~8K
|
||||
Tool call history: 16K (last N interactions)
|
||||
Agent scratchpad: 4K
|
||||
Total: ~84K (well within 1M limit)
|
||||
```
|
||||
|
||||
### 4.5 Function Calling / Tool Use
|
||||
|
||||
V4-Pro natively supports function calling and structured outputs.
|
||||
|
||||
For DeepCode CLI tools (read, edit, grep, bash, etc.):
|
||||
```text
|
||||
Recommended: native OpenAI-compatible function calling
|
||||
- Define tools as JSON schema in API call
|
||||
- V4-Pro routes to appropriate experts for tool selection
|
||||
- Parallel function calling supported
|
||||
|
||||
Fallback: structured output mode (JSON schema)
|
||||
- Force model to output valid JSON matching a schema
|
||||
- Useful for orchestrator pattern
|
||||
- Combine with assistant prefill for guided output start
|
||||
```
|
||||
|
||||
### 4.6 Evaluation Benchmarks Relevant to Coding Agents
|
||||
|
||||
| Benchmark | V4-Pro-Max | V4-Pro-High | V4-Flash-Max | V3.2 | R1 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| SWE-bench Verified | **80.6%** | 79.4% | 79.0% | ~50% | — |
|
||||
| LiveCodeBench | **93.5** | 89.8 | 91.6 | 74.1 | — |
|
||||
| Codeforces | **3206** | 2919 | 3052 | 2121 | — |
|
||||
| Aider-Polyglot | **~80** | ~76 | ~68 | 74.5 | — |
|
||||
| HLE (Pass@1) | 37.7 | 34.5 | 34.8 | — | — |
|
||||
| GPQA Diamond | 90.1 | 89.1 | 88.1 | 79.9 | 71.5 |
|
||||
| MMLU-Pro | 87.5 | 87.1 | 86.2 | 85.0 | 84.0 |
|
||||
| SimpleQA-Verified | **57.9** | 46.2 | 34.1 | — | — |
|
||||
| Terminal Bench 2.0 | 67.9 | 63.3 | 56.9 | — | — |
|
||||
| SWE-Pro | 55.4 | 54.4 | 52.6 | — | — |
|
||||
| MRCR 1M | 83.5 | 83.3 | 78.7 | — | — |
|
||||
| CorpusQA 1M | 62.0 | 56.5 | 60.5 | — | — |
|
||||
| BrowseComp | 83.4 | 80.4 | 73.2 | 40.1 | — |
|
||||
| MCPAtlas Public | 73.6 | 74.2 | 69.0 | — | — |
|
||||
| Toolathlon (Pass@1) | 51.8 | 49.0 | 47.8 | — | — |
|
||||
|
||||
*V4-Pro matches Claude Opus 4.6 on SWE-bench (80.6 vs 80.8) at 2% of the cost.
|
||||
|
||||
### 4.7 Key Takeaways for Agent Optimization
|
||||
|
||||
1. **V4-Pro is the best coding model as of May 2026** — $3.48/M output is unmatched value
|
||||
2. **V4-Flash for agentic loops** — $0.14/$0.28 enables cheap multi-step workflows
|
||||
3. **R1 for planning/reasoning** — but feed its output to V4-Pro for code generation
|
||||
4. **1M context is real** — with CSA+HCA tiered access, full-repo context is practical
|
||||
5. **OpenAI-compatible API** — drop-in replacement for existing agent frameworks
|
||||
6. **MIT license** — no restrictions on commercial use or fine-tuning
|
||||
7. **No system prompt for R1** — all instructions in user message
|
||||
8. **Temperature 0.3 for V4 coding, 0.6 for R1 reasoning**
|
||||
|
||||
---
|
||||
|
||||
## 5. Key Technical Innovations Deep Dive
|
||||
|
||||
### 4.1 Multi-head Latent Attention (MLA)
|
||||
|
||||
Introduced in DeepSeek-V2. Solves KV cache memory bottleneck.
|
||||
|
||||
```text
|
||||
Standard MHA: cache full K and V matrices per layer per token
|
||||
MLA: compress KV to low-rank latent vector c_kv, reconstruct K/V on-the-fly
|
||||
|
||||
c_kv = W_DKV · h_t (compress to latent, dimension d_c << n_h · d_h)
|
||||
k = W_UK · c_kv (upsample K)
|
||||
v = W_UV · c_kv (upsample V)
|
||||
|
||||
Result: ~93% KV cache reduction, comparable or better performance
|
||||
```
|
||||
|
||||
### 4.2 DeepSeekMoE
|
||||
|
||||
Introduced in DeepSeek-MoE, refined in V2/V3.
|
||||
|
||||
```text
|
||||
Standard MoE: few large experts, top-k routing
|
||||
DeepSeekMoE:
|
||||
- Fine-grained segmentation: many smaller experts (e.g., 256)
|
||||
- Shared experts: always activated, capture common knowledge
|
||||
- Routed experts: specialized knowledge per token
|
||||
- Auxiliary-loss-free load balancing (V3)
|
||||
```
|
||||
|
||||
### 4.3 GRPO (Group Relative Policy Optimization)
|
||||
|
||||
Introduced in DeepSeek-R1. Eliminates need for separate critic model.
|
||||
|
||||
```text
|
||||
Standard PPO: policy model + critic/value model
|
||||
GRPO:
|
||||
- Sample group of responses per prompt
|
||||
- Compute rewards for each response
|
||||
- Group mean as baseline
|
||||
- Advantages = (reward - group_mean) / group_std
|
||||
- No separate critic model needed
|
||||
- Significantly lower memory/computation cost
|
||||
```
|
||||
|
||||
Key result: R1-Zero trained with pure RL (no SFT) developed emergent reasoning behaviors — chain-of-thought, self-verification, reflection — and spontaneously learned to allocate more "thinking time" to harder problems.
|
||||
|
||||
### 4.4 DeepSeek Sparse Attention (DSA)
|
||||
|
||||
Introduced in DeepSeek-V3.2-Exp. Fine-grained sparse attention for long-context.
|
||||
|
||||
```text
|
||||
Dense attention: O(n²) for all token pairs
|
||||
DSA: fine-grained sparse pattern maintaining output quality
|
||||
- First fine-grained sparse attention achieving parity with dense
|
||||
- Substantial long-context training/inference efficiency improvement
|
||||
- V3.2-Exp matches V3.1-Terminus on public benchmarks
|
||||
```
|
||||
|
||||
### 5.5 DeepSeek V4-Pro / V4-Flash (Hybrid CSA + HCA Attention)
|
||||
|
||||
Released April 24, 2026. Full technical report: DeepSeek_V4.pdf (43 pages, 4.3MB, from HuggingFace).
|
||||
|
||||
```text
|
||||
V4-Pro:
|
||||
- Total parameters: 1.6T
|
||||
- Activated per token: 49B
|
||||
- Layers: 61 transformer layers, hidden dim: 7168
|
||||
- MoE: 1 shared expert + 384 routed experts, 6 active per token (Hash routing for first 3 layers)
|
||||
- Attention: interleaved CSA+HCA (first 2 layers HCA only)
|
||||
- CSA: m=4 compression, top-k=1024, n_h^I=64 indexer heads, c_I=128, n_h=128 query heads, c=512 head dim, d_c=1536
|
||||
- HCA: m'=128 compression
|
||||
- SWA: n_win=128 sliding window, grouped output: g=16, d_g=1024
|
||||
- mHC: n_hc=4 expansion, Sinkhorn-Knopp 20 iterations
|
||||
- Context: 1,000,000 tokens
|
||||
- Training: 33T tokens, Muon (μ=0.95, wd=0.1, γ=0.18), AdamW for embed/prediction head/RMSNorm
|
||||
- LR: 2.0e-4 → 2.0e-5, max batch: 94.4M, 4K→16K→64K→1M sequence ramp
|
||||
- Precision: FP4 (routed expert weights + indexer QK path) + FP8 (other weights)
|
||||
- Download size: ~865 GB, License: MIT
|
||||
- Optimizer: Muon (hybrid Newton-Schulz: 8 fast + 2 stable iterations)
|
||||
|
||||
V4-Flash:
|
||||
- Total parameters: 284B
|
||||
- Activated per token: 13B
|
||||
- Layers: 43 transformer layers, hidden dim: 4096
|
||||
- MoE: 1 shared expert + 256 routed experts, 6 active per token (Hash routing for first 3 layers)
|
||||
- Attention: interleaved CSA+HCA (first 2 layers pure SWA)
|
||||
- CSA: m=4 compression, top-k=512, n_h^I=64, c_I=128, n_h=64, c=512, d_c=1024
|
||||
- HCA: m'=128 compression
|
||||
- SWA: n_win=128, grouped output: g=8, d_g=1024
|
||||
- mHC: n_hc=4 expansion, Sinkhorn-Knopp 20 iterations
|
||||
- Context: 1,000,000 tokens
|
||||
- Training: 32T tokens, Muon (μ=0.95, wd=0.1, γ=0.18)
|
||||
- LR: 2.7e-4 → 2.7e-5, max batch: 75.5M
|
||||
- Download size: ~160 GB, License: MIT
|
||||
|
||||
Key architectural innovations (paper-grounded):
|
||||
|
||||
1. Compressed Sparse Attention (CSA):
|
||||
- Dual-stream KV compression (C^a, C^b with overlapping windows), m=4
|
||||
- Lightning Indexer: low-rank queries (W^DQ + W^IUQ), ReLU scoring, per-head weights
|
||||
- Shared KV MQA: compressed entries serve as both K and V
|
||||
- Grouped Output Projection: g groups reduce n_h·c → d overhead
|
||||
|
||||
2. Heavily Compressed Attention (HCA):
|
||||
- Single-stream compression, m'=128 (no overlap)
|
||||
- Dense attention on heavily compressed representation
|
||||
- No sparse selection — pure global summary
|
||||
|
||||
3. Combined CSA + HCA at 1M context:
|
||||
- V4-Pro: 27% FLOPs, 10% KV cache of V3.2
|
||||
- V4-Flash: 10% FLOPs, 7% KV cache of V3.2
|
||||
- vs BF16 GQA8 baseline: ~2% KV cache
|
||||
- Mixed KV precision: BF16 (RoPE 64 dims) + FP8 (remaining)
|
||||
|
||||
4. Manifold-Constrained Hyper-Connections (mHC):
|
||||
- Residual mapping B_l constrained to doubly stochastic manifold (Birkhoff polytope)
|
||||
- Sinkhorn-Knopp projection (20 iters, exp→row norm→col norm)
|
||||
- Dynamic parameterization: input-dependent + static components
|
||||
- A_l, C_l bounded via Sigmoid, ∥B_l∥₂ ≤ 1 ensures stability
|
||||
- Engineering overhead: only 6.7% of 1F1B pipeline stage
|
||||
|
||||
5. Muon Optimizer:
|
||||
- Hybrid Newton-Schulz: 8 steps (3.4445, -4.7750, 2.0315) + 2 steps (2, -1.5, 0.5)
|
||||
- Nesterov momentum (μ=0.95), BF16 Newton-Schulz stable
|
||||
- Mixed ZeRO: knapsack for dense params, per-expert for MoE
|
||||
- MoE gradients: stochastic rounding to BF16, all-to-all + FP32 local sum
|
||||
|
||||
Infrastructure innovations:
|
||||
|
||||
6. MegaMoE (Fused EP Kernel):
|
||||
- Wave-based expert scheduling (1.5-1.96× speedup)
|
||||
- Computation-communication ratio: C/B ≤ 6144 FLOPs/Byte hides communication
|
||||
- Open-sourced in DeepGEMM
|
||||
|
||||
7. TileLang DSL:
|
||||
- Host Codegen: Python checks → C++ (<1μs per invocation)
|
||||
- Z3 SMT solver for formal integer analysis
|
||||
- IEEE-754 + bitwise reproducibility
|
||||
|
||||
8. Batch-Invariant & Deterministic Kernels:
|
||||
- Dual-kernel attention (single SM + multi SM for wave-quantization)
|
||||
- DeepGEMM replaces cuBLAS end-to-end
|
||||
- Deterministic MoE backward: token order preprocessing + buffer isolation
|
||||
|
||||
9. KV Cache Management:
|
||||
- Heterogeneous: State Cache (SWA + uncompressed tail) + Classical Cache (CSA/HCA blocks)
|
||||
- Block size: lcm(4, 128) = 128 original tokens per block
|
||||
- On-disk storage: Full SWA / Periodic Checkpointing / Zero SWA Caching
|
||||
|
||||
Post-training innovations:
|
||||
|
||||
10. FP4 Quantization-Aware Training:
|
||||
- MoE expert weights: FP32 master→FP4→FP8 (lossless dequant)
|
||||
- Indexer QK path: full FP4
|
||||
- Index scores: FP32→BF16 (2× speedup, 99.7% recall)
|
||||
|
||||
11. On-Policy Distillation (OPD):
|
||||
- 10+ teacher models → single student
|
||||
- Full-vocabulary reverse KL (D_KL(π_θ ∥ π_Ei))
|
||||
- Teachers offloaded to distributed storage, ZeRO-like sharding
|
||||
- Cached last-layer hidden states → on-the-fly logits reconstruction
|
||||
|
||||
12. Quick Instruction:
|
||||
- Special tokens (<|action|>, <|query|>, <|domain|>, etc.)
|
||||
- Reuses existing KV cache, zero redundant prefill
|
||||
- Parallel execution of auxiliary tasks
|
||||
|
||||
13. Interleaved Thinking:
|
||||
- Tool-calling: full reasoning history preserved across rounds
|
||||
- General conversation: previous reasoning discarded per turn
|
||||
|
||||
14. DSec Sandbox (Rust):
|
||||
- 4 substrates: Function Call / Container / microVM (Firecracker) / fullVM (QEMU)
|
||||
- 3FS-backed layered storage, preemption-safe trajectory logging
|
||||
- Hundreds of thousands of concurrent instances
|
||||
|
||||
Training stability:
|
||||
|
||||
15. Anticipatory Routing:
|
||||
- Step t uses θ_t for features, θ_{t-Δt} routing indices
|
||||
- Auto-detection: loss spike → short rollback → activate → revert
|
||||
- ~20% overhead when active (negligible overall)
|
||||
|
||||
16. SwiGLU Clamping:
|
||||
- Linear component: clamp [-10, 10]
|
||||
- Gate component: upper bound 10
|
||||
|
||||
V4-Pro-Max benchmarks (selected):
|
||||
- SimpleQA: 57.9% (vs Gemini 3.1 Pro 75.6%)
|
||||
- HLE: 37.7% (vs Opus 4.6 40.0%)
|
||||
- LiveCodeBench: 93.5 (highest, vs GPT-5.4 91.7%)
|
||||
- Codeforces: 3206 (23rd human, vs GPT-5.4 3168)
|
||||
- SWE-Verified: 80.6% (vs Opus 4.6 80.8%)
|
||||
- TerminalBench 2.0: 67.9% (vs GPT-5.4 75.1%)
|
||||
- MRCR 1M: 83.5 MMR (vs Opus 4.6 92.9%)
|
||||
- CorpusQA 1M: 62.0% (vs Opus 4.6 71.7%)
|
||||
- Formal Putnam 2025: 120/120
|
||||
|
||||
Pricing:
|
||||
- V4-Pro: $1.74/M in, $3.48/M out
|
||||
- V4-Flash: $0.14/M in, $0.28/M out
|
||||
- V4-Pro (Max reasoning): $3.48/M in, $6.96/M out
|
||||
- vs GPT-5.5: ~$0.55-0.75/M in, ~$2-3/M out (~25-30x cheaper)
|
||||
- vs Claude Opus 4.6: ~$15/M in, ~$75/M out (~20x cheaper)
|
||||
```
|
||||
|
||||
### 5.6 DeepSeek V3.2: DSA + Scalable RL + Agent Pipeline
|
||||
|
||||
arXiv: 2512.02556 (Dec 2, 2025). Not an experimental — full V3.2 release.
|
||||
|
||||
```text
|
||||
Three key innovations:
|
||||
|
||||
1. DeepSeek Sparse Attention (DSA):
|
||||
- Lightning indexer: small, multi-head scorer (FP8 efficient)
|
||||
- Fine-grained token selection: top-k KV retrieval per query
|
||||
- Implemented under MLA framework
|
||||
- Dense warm-up (1K steps, 2.1B tokens) trains indexer via KL-divergence
|
||||
- Full sparse training adapts all params to sparse pattern
|
||||
- Result: first fine-grained sparse attention matching dense quality
|
||||
|
||||
2. Scalable RL Framework:
|
||||
- Post-training compute scaled substantially (larger than typical)
|
||||
- V3.2-Speciale: higher compute variant
|
||||
- Achieves IMO 2025 gold + IOI gold
|
||||
- Matches GPT-5 on reasoning, Gemini-3.0-Pro on complex reasoning
|
||||
|
||||
3. Agentic Task Synthesis Pipeline:
|
||||
- Novel pipeline for generating training data for tool-use scenarios
|
||||
- Scalable agentic post-training
|
||||
- Improved generalization and instruction-following in interactive envs
|
||||
|
||||
Benchmarks:
|
||||
- Codeforces: 2121 (V3.2-Exp), higher in full V3.2
|
||||
- LiveCodeBench: 74.1 (Exp)
|
||||
- Aider-Polyglot: 74.5 (Exp)
|
||||
- MMLU-Pro: 85.0
|
||||
- GPQA-Diamond: 79.9
|
||||
- AIME 2025: 89.3
|
||||
- SWE-bench Verified: ~50 (via V3.2)
|
||||
- BrowseComp: 40.1 / BrowseComp-zh: 47.9
|
||||
```
|
||||
|
||||
### 5.7 Engram (Conditional Memory)
|
||||
|
||||
Introduced as a new sparsity axis complementary to MoE.
|
||||
|
||||
```text
|
||||
MoE: scales capacity via conditional computation (routing)
|
||||
Engram: scales knowledge via conditional memory (lookup)
|
||||
|
||||
Key idea: N-gram embedding lookup as O(1) knowledge primitive
|
||||
- Deterministic addressing
|
||||
- Offloadable to host memory with minimal inference overhead
|
||||
- Relieves early layers from static pattern reconstruction
|
||||
- U-shaped scaling law for optimal MoE vs Engram allocation
|
||||
- Engram-27B improves over MoE baselines on knowledge/reasoning/code/math
|
||||
```
|
||||
|
||||
## 6. DeepSeek Model Evolution Timeline
|
||||
|
||||
```text
|
||||
DeepSeek-LLM (base)
|
||||
↓
|
||||
DeepSeekMoE (fine-grained experts)
|
||||
↓
|
||||
DeepSeek-V2 (MLA + DeepSeekMoE, 236B)
|
||||
↓
|
||||
DeepSeek-Coder / Coder-V2 (code focus)
|
||||
↓
|
||||
DeepSeek-Math / Math-V2 (GRPO, IMO gold)
|
||||
↓
|
||||
DeepSeek-V3 (671B MoE, FP8, $5.5M, 128K context)
|
||||
↓
|
||||
DeepSeek-R1 / R1-Zero (pure RL reasoning, emergent CoT)
|
||||
↓
|
||||
DeepSeek-VL / VL2 / Janus (multimodal)
|
||||
↓
|
||||
DeepSeek-Prover-V1.5 / V2 (Lean 4 formal reasoning)
|
||||
↓
|
||||
DeepSeek-OCR / OCR-2 (visual understanding)
|
||||
↓
|
||||
DeepSeek-V3.1-Terminus (128K context extension)
|
||||
↓
|
||||
DeepSeek-V3.2-Exp / V3.2 (DSA sparse attention + agent pipeline)
|
||||
↓
|
||||
Engram (conditional memory sparsity)
|
||||
↓
|
||||
DeepSeek-V4-Pro / V4-Flash (CSA+HCA hybrid attention, mHC, Muon, 1M context)
|
||||
```
|
||||
|
||||
The V4 series (Apr 2026) represents the current frontier — CSA+HCA attention enabling practical 1M-token context at 27% FLOPs and 10% KV cache of V3.2.
|
||||
|
||||
## 7. Infrastructure Innovation Timeline
|
||||
|
||||
```text
|
||||
Fire-Flyer AI-HPC (hardware-software co-design)
|
||||
↓
|
||||
FlashMLA (efficient MLA GPU kernels)
|
||||
↓
|
||||
DeepGEMM (FP8 GEMM with fine-grained scaling)
|
||||
↓
|
||||
DeepEP (expert-parallel communication)
|
||||
↓
|
||||
DualPipe (bidirectional pipeline parallelism)
|
||||
↓
|
||||
EPLB / LPLB (expert load balancing)
|
||||
↓
|
||||
3FS (distributed file system for AI)
|
||||
↓
|
||||
smallpond (data processing on DuckDB + 3FS)
|
||||
↓
|
||||
TileKernels / TileLang (DSL kernel library with Host Codegen + Z3 SMT)
|
||||
↓
|
||||
MegaMoE (fused EP kernel with wave scheduling, 1.5-1.96× speedup)
|
||||
↓
|
||||
DSec Sandbox (Firecracker microVM + 3FS, 100K+ concurrent agent sandboxes)
|
||||
```
|
||||
|
||||
## 8. Relevance to DeepCode CLI
|
||||
|
||||
DeepSeek's research is directly relevant to DeepCode CLI architecture:
|
||||
|
||||
### 8.1 Code Intelligence
|
||||
|
||||
- DeepSeek-Coder/Coder-V2: Fill-in-Middle, long-context code understanding
|
||||
- DeepSeek-V3.2-Exp: Codeforces 2121, LiveCodeBench 74.1, Aider-Polyglot 74.5
|
||||
- SWE-bench Verified 67.8, SWE-bench Multilingual 57.9
|
||||
|
||||
### 8.2 Reasoning for Debugging/Architecture
|
||||
|
||||
- DeepSeek-R1: emergent chain-of-thought, self-verification, reflection
|
||||
- GRPO: efficient RL without critic model
|
||||
- Applicable to training code-review/debug agents
|
||||
|
||||
### 8.3 Formal Verification
|
||||
|
||||
- DeepSeek-Prover-V2: Lean 4 theorem proving
|
||||
- Applicable to formal verification of generated code
|
||||
|
||||
### 8.4 Efficient Inference
|
||||
|
||||
- MLA: 93% KV cache reduction for long code contexts
|
||||
- DSA: efficient long-context processing
|
||||
- MoE: 37B activated from 671B total parameters
|
||||
- Engram: O(1) knowledge lookup
|
||||
|
||||
### 8.5 Multimodal Evidence
|
||||
|
||||
- DeepSeek-OCR/OCR-2: visual understanding for GUI evidence
|
||||
- Janus: unified multimodal for screenshot/code understanding
|
||||
|
||||
### 8.6 Infrastructure
|
||||
|
||||
- 3FS: distributed file system for large codebase training
|
||||
- DualPipe: efficient distributed training
|
||||
- DeepGEMM/FlashMLA: optimized inference kernels
|
||||
|
||||
## 9. Total GitHub Stats Summary
|
||||
|
||||
| Category | Repos | Total Stars |
|
||||
|---|---|---|
|
||||
| Foundation Models | 6 | ~209,000 |
|
||||
| Code Models | 2 | ~30,000 |
|
||||
| Math/Proving | 4 | ~6,700 |
|
||||
| Vision/Multimodal | 5 | ~53,000 |
|
||||
| Infrastructure | 11 | ~50,000 |
|
||||
| Research | 2 | ~5,200 |
|
||||
| Ecosystem | 3 | ~41,000 |
|
||||
| **Total** | **36** | **~395,000** |
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
AirPlan/docs/architecture/branch-deepcode-cli/papers/Engram.pdf
Normal file
BIN
AirPlan/docs/architecture/branch-deepcode-cli/papers/Engram.pdf
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
738
AirPlan/docs/architecture/branchvibebox/feasibility-plan.md
Normal file
738
AirPlan/docs/architecture/branchvibebox/feasibility-plan.md
Normal file
@@ -0,0 +1,738 @@
|
||||
# VibeBox Feasibility and Implementation Plan
|
||||
|
||||
Date: 2026-05-26
|
||||
Status: Practical implementation plan for the VibeBox downstream branch
|
||||
|
||||
## 1. Feasibility Verdict
|
||||
|
||||
VibeBox is feasible if scoped as an appliance that generates small, local Electron utilities from templates.
|
||||
|
||||
It is not feasible as an unrestricted “any software from any prompt” agent. The product must enforce a constrained scope:
|
||||
|
||||
```text
|
||||
small local Electron app
|
||||
+ template-based generation
|
||||
+ default high-permission appliance setup
|
||||
+ frontend-design and image-gen capabilities
|
||||
+ full automated workflow testing
|
||||
+ review gates
|
||||
+ ARM Linux packaging/delivery
|
||||
```
|
||||
|
||||
Expected timelines:
|
||||
|
||||
| Stage | Estimate | Outcome |
|
||||
|---|---:|---|
|
||||
| Prototype | 3–5 weeks | Generates and packages simple Electron tools |
|
||||
| Partner trial | 6–8 weeks | Background setup/dev/test/review/package on ARM Linux box |
|
||||
| Stable appliance version | 10–12 weeks | Hardened testing, packaging fallback, diagnostics, user-friendly failure handling |
|
||||
|
||||
## 2. Product Contract
|
||||
|
||||
VibeBox should provide this user experience:
|
||||
|
||||
```text
|
||||
User: “I want a tool that renames photos by date and lets me preview the result.”
|
||||
|
||||
VibeBox:
|
||||
1. asks only blocking product questions, if any
|
||||
2. configures the environment silently where allowed
|
||||
3. generates a small Electron app
|
||||
4. designs the UI and required assets
|
||||
5. writes code
|
||||
6. runs full automated tests
|
||||
7. reviews security/functionality/packaging
|
||||
8. packages for ARM Linux
|
||||
9. gives the user a runnable app and a simple report
|
||||
```
|
||||
|
||||
The user should not supervise implementation. The user may lack computer expertise.
|
||||
|
||||
## 3. Scope Boundaries
|
||||
|
||||
### Accepted by default
|
||||
|
||||
- Small desktop utility
|
||||
- Local-first app
|
||||
- Simple filesystem workflows
|
||||
- Form/data-entry tools
|
||||
- CSV/JSON/image batch helpers
|
||||
- Clipboard/notes/todo utilities
|
||||
- Single-window dashboards
|
||||
- Simple API client if network access is declared
|
||||
|
||||
### Requires narrowing question
|
||||
|
||||
- vague app idea
|
||||
- multiple unrelated features
|
||||
- unclear input/output data
|
||||
- network access or credentials
|
||||
- destructive filesystem operations
|
||||
- system integration beyond app sandbox
|
||||
|
||||
### Refuse or escalate
|
||||
|
||||
- malware, credential theft, stealth, evasion
|
||||
- destructive system modification
|
||||
- kernel/driver changes
|
||||
- large Excel/Photoshop/IDE-like apps
|
||||
- multi-service cloud systems
|
||||
- unbounded automation over arbitrary shell commands
|
||||
|
||||
## 4. Architecture Cut from AirCoding
|
||||
|
||||
VibeBox keeps only the minimum needed path.
|
||||
|
||||
```text
|
||||
Orchestrator
|
||||
→ Executor
|
||||
→ Reviewer/Tester
|
||||
→ Packager
|
||||
→ Delivery Reporter
|
||||
```
|
||||
|
||||
No V1 support for:
|
||||
|
||||
- Architecture Designer as a separate agent
|
||||
- complex TaskGraph / Scheduler
|
||||
- parallel write workers
|
||||
- worktree merging
|
||||
- C++ toolchain
|
||||
- ExperienceMiner / Curator
|
||||
- Debug Knowledge Network
|
||||
- plugin marketplace
|
||||
- broad multi-language runtime
|
||||
|
||||
## 5. Default Permission Model
|
||||
|
||||
VibeBox is an appliance product and should default to highest-permission automation.
|
||||
|
||||
However, highest permission is bounded by appliance policy:
|
||||
|
||||
```text
|
||||
Allowed automatically:
|
||||
- installing approved runtime dependencies
|
||||
- creating/modifying generated app projects
|
||||
- running tests/build/package commands
|
||||
- writing artifacts/reports
|
||||
- using configured image-gen provider
|
||||
|
||||
Requires explicit user/operator confirmation:
|
||||
- credentials entry
|
||||
- network access not implied by the user request
|
||||
- destructive file operations outside the app workspace
|
||||
- system-sensitive paths
|
||||
- shell execution exposed inside generated app
|
||||
```
|
||||
|
||||
System dependency installation should use an allowlist controlled by the appliance vendor/operator.
|
||||
|
||||
## 6. Recommended Technology Stack
|
||||
|
||||
### Runtime
|
||||
|
||||
Preferred for V1:
|
||||
|
||||
```text
|
||||
Node.js runtime for generated apps
|
||||
Bun or Node.js for the VibeBox agent runtime
|
||||
```
|
||||
|
||||
Choose Node for maximum Electron ecosystem compatibility if uncertain.
|
||||
|
||||
### Generated app stack
|
||||
|
||||
```text
|
||||
Electron
|
||||
Vite
|
||||
TypeScript
|
||||
React
|
||||
CSS modules or simple Tailwind-like design tokens
|
||||
Playwright/Electron tests
|
||||
Electron Builder or Electron Forge
|
||||
```
|
||||
|
||||
### Test stack
|
||||
|
||||
```text
|
||||
Vitest for unit tests
|
||||
Playwright + Electron for E2E tests
|
||||
Xvfb or configured display backend for ARM Linux UI automation
|
||||
```
|
||||
|
||||
### Packaging
|
||||
|
||||
Primary:
|
||||
|
||||
```text
|
||||
AppImage arm64 if stable on target box
|
||||
```
|
||||
|
||||
Fallback:
|
||||
|
||||
```text
|
||||
unpacked Electron app + launcher script
|
||||
```
|
||||
|
||||
The fallback is important. Packaging should not block delivery if an unpacked app runs reliably.
|
||||
|
||||
## 7. Template Strategy
|
||||
|
||||
VibeBox must be template-first.
|
||||
|
||||
Suggested V1 templates:
|
||||
|
||||
```text
|
||||
templates/
|
||||
file-batch-tool/
|
||||
data-table-tool/
|
||||
form-entry-tool/
|
||||
clipboard-tool/
|
||||
notes-todo-tool/
|
||||
image-batch-tool/
|
||||
api-dashboard-tool/
|
||||
single-panel-utility/
|
||||
```
|
||||
|
||||
Each template includes:
|
||||
|
||||
- Electron secure main/preload/renderer structure
|
||||
- React component skeleton
|
||||
- local storage helper
|
||||
- design tokens
|
||||
- test harness
|
||||
- Playwright fixtures
|
||||
- packaging config
|
||||
- README/report template
|
||||
|
||||
AI should select and fill templates, not build projects from scratch.
|
||||
|
||||
## 8. Built-in Capabilities
|
||||
|
||||
### 8.1 frontend-design
|
||||
|
||||
First-class built-in capability.
|
||||
|
||||
Inputs:
|
||||
|
||||
- user requirement
|
||||
- selected template
|
||||
- display size constraints
|
||||
- novice-user profile
|
||||
|
||||
Outputs:
|
||||
|
||||
- UI layout plan
|
||||
- component hierarchy
|
||||
- design tokens
|
||||
- copywriting
|
||||
- empty/loading/error states
|
||||
- screenshot review checklist
|
||||
|
||||
Default design priorities:
|
||||
|
||||
1. clarity over aesthetics
|
||||
2. large readable controls
|
||||
3. obvious next action
|
||||
4. safe defaults
|
||||
5. clear error messages
|
||||
6. local-first expectations
|
||||
|
||||
### 8.2 image-gen
|
||||
|
||||
First-class built-in capability.
|
||||
|
||||
V1 should support:
|
||||
|
||||
- app icon generation
|
||||
- empty-state / placeholder illustration generation
|
||||
- simple decorative assets
|
||||
- SVG fallback when bitmap generation is unavailable
|
||||
- multiple candidate generation if provider supports it
|
||||
|
||||
Provider strategy:
|
||||
|
||||
```text
|
||||
preferred: configured cloud image provider
|
||||
fallback: SVG/simple generated asset
|
||||
deferred: heavy local image model on ARM unless hardware supports it
|
||||
```
|
||||
|
||||
Generated assets are artifacts first. They are copied into the app only after internal selection/review.
|
||||
|
||||
### 8.3 electron-test
|
||||
|
||||
First-class built-in capability.
|
||||
|
||||
Required functions:
|
||||
|
||||
- launch generated Electron app in test mode
|
||||
- interact with UI through Playwright
|
||||
- test core workflows
|
||||
- test edge cases
|
||||
- test persistence/restart when applicable
|
||||
- capture screenshot/trace artifacts
|
||||
- launch packaged app or unpacked delivery
|
||||
|
||||
Smoke test alone is insufficient.
|
||||
|
||||
## 9. Testing Policy
|
||||
|
||||
VibeBox users may not be able to diagnose software failures. Therefore, delivery requires full workflow validation.
|
||||
|
||||
Minimum delivery gates:
|
||||
|
||||
1. environment setup passed
|
||||
2. dependencies installed
|
||||
3. build passed
|
||||
4. typecheck passed when TypeScript is used
|
||||
5. lint passed when configured
|
||||
6. unit tests passed or skipped with reason
|
||||
7. integration tests passed for data/file flows
|
||||
8. E2E tests cover all core user workflows
|
||||
9. edge cases tested where relevant
|
||||
10. persistence/restart tested if local data is stored
|
||||
11. packaged or delivered app launches
|
||||
12. screenshot evidence captured when display backend exists
|
||||
13. review report approves delivery
|
||||
|
||||
Core workflow coverage definition:
|
||||
|
||||
```text
|
||||
For every user-visible requirement, at least one automated test exercises the path.
|
||||
For every input type, normal / empty / invalid / large input cases are tested where practical.
|
||||
For storage features, restart recovery is tested.
|
||||
For delivery, the packaged or unpacked app launch is tested.
|
||||
```
|
||||
|
||||
## 10. Review Policy
|
||||
|
||||
Reviewer/Tester pass should use a fixed checklist.
|
||||
|
||||
### Functional review
|
||||
|
||||
- Does the app implement the user request?
|
||||
- Are any requested features missing?
|
||||
- Are assumptions clearly reported?
|
||||
|
||||
### UX/design review
|
||||
|
||||
- Is the UI understandable to a novice?
|
||||
- Are controls readable on the target display?
|
||||
- Are error states visible and actionable?
|
||||
- Does screenshot match design intent?
|
||||
|
||||
### Asset review
|
||||
|
||||
- Are generated icons/images appropriate?
|
||||
- Are assets bundled locally?
|
||||
- Are missing provider fallbacks acceptable?
|
||||
|
||||
### Security review
|
||||
|
||||
- `contextIsolation: true`
|
||||
- `nodeIntegration: false`
|
||||
- preload API is minimal
|
||||
- no arbitrary shell exposure
|
||||
- filesystem access scoped to the app's purpose
|
||||
- network access declared if used
|
||||
|
||||
### Test review
|
||||
|
||||
- Do tests cover all core workflows?
|
||||
- Are skipped tests justified?
|
||||
- Are failure artifacts available?
|
||||
|
||||
### Packaging review
|
||||
|
||||
- Does the delivered app launch on the ARM Linux box?
|
||||
- Is there a fallback launcher if AppImage fails?
|
||||
|
||||
## 11. Doctor / Setup
|
||||
|
||||
Doctor runs at first boot and before generation.
|
||||
|
||||
Checks:
|
||||
|
||||
- ARM Linux architecture
|
||||
- Node/Bun availability
|
||||
- npm/pnpm availability
|
||||
- Electron install ability
|
||||
- native npm build tools
|
||||
- frontend-design capability availability
|
||||
- image-gen provider or fallback availability
|
||||
- Playwright/Electron automation support
|
||||
- Xvfb/display backend
|
||||
- disk space
|
||||
- workspace write permission
|
||||
- package cache availability
|
||||
|
||||
Modes:
|
||||
|
||||
```text
|
||||
prepared appliance:
|
||||
pre-authorized high-permission setup
|
||||
run fixes automatically with brief visible status
|
||||
|
||||
unprepared/manual mode:
|
||||
show fix plan and ask operator before fixing
|
||||
```
|
||||
|
||||
## 12. State Layout
|
||||
|
||||
Each generated app is self-contained.
|
||||
|
||||
```text
|
||||
<workspace>/<app-name>/
|
||||
├── package.json
|
||||
├── src/
|
||||
├── tests/
|
||||
├── dist/
|
||||
├── release/
|
||||
└── .vibebox/
|
||||
├── project.json
|
||||
├── session.db
|
||||
├── artifacts/
|
||||
├── reports/
|
||||
└── state.json
|
||||
```
|
||||
|
||||
Minimum DB tables:
|
||||
|
||||
- `messages`
|
||||
- `message_drafts`
|
||||
- `steps`
|
||||
- `tool_runs`
|
||||
- `command_runs`
|
||||
- `artifacts`
|
||||
- `reports`
|
||||
|
||||
Pipeline steps:
|
||||
|
||||
```text
|
||||
understand
|
||||
setup
|
||||
plan
|
||||
scaffold
|
||||
design
|
||||
asset_generate
|
||||
implement
|
||||
test
|
||||
review
|
||||
fix
|
||||
package
|
||||
deliver
|
||||
```
|
||||
|
||||
## 13. Delivery Contract
|
||||
|
||||
Delivery directory:
|
||||
|
||||
```text
|
||||
<app>/release/
|
||||
├── <app-name>-arm64.AppImage # if available
|
||||
├── unpacked/ # fallback if needed
|
||||
├── launch.sh # fallback launcher
|
||||
├── README.md
|
||||
└── vibebox-report.md
|
||||
```
|
||||
|
||||
Final report must be non-technical and include:
|
||||
|
||||
- what was built
|
||||
- how to launch it
|
||||
- what it can do
|
||||
- where its data is stored
|
||||
- tests that passed
|
||||
- known limitations
|
||||
- package path
|
||||
- what VibeBox automatically configured
|
||||
|
||||
## 14. Failure Handling
|
||||
|
||||
If generation fails, VibeBox should not dump raw logs to the user.
|
||||
|
||||
It should provide:
|
||||
|
||||
```text
|
||||
- simple explanation
|
||||
- what was attempted
|
||||
- what failed
|
||||
- whether retry is possible
|
||||
- what the user/operator can do next
|
||||
- diagnostic artifact bundle path
|
||||
```
|
||||
|
||||
Automatic retry limits:
|
||||
|
||||
- implementation/test fix cycle: max 2–3 rounds
|
||||
- dependency setup: max 1 automatic fix attempt per issue
|
||||
- package fallback: AppImage → unpacked app + launcher
|
||||
|
||||
If still failing, deliver a failure report and preserve artifacts.
|
||||
|
||||
## 15. Implementation Phases
|
||||
|
||||
### Phase 0 — Feasibility spike (3–5 days)
|
||||
|
||||
Goal: prove Electron generation/testing/package path on the ARM box.
|
||||
|
||||
Tasks:
|
||||
|
||||
- choose runtime/package manager
|
||||
- scaffold one fixed Electron template
|
||||
- run build/typecheck
|
||||
- run Playwright/Electron E2E on box
|
||||
- package AppImage or produce unpacked app
|
||||
- document environment dependencies
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- a hand-coded sample app can be built, tested, and launched on the target box
|
||||
|
||||
### Phase 1 — Prototype generator (1–2 weeks)
|
||||
|
||||
Tasks:
|
||||
|
||||
- implement Orchestrator linear pipeline
|
||||
- implement filesystem/shell/template tools
|
||||
- implement session/artifact logging
|
||||
- implement one template family
|
||||
- generate simple app from natural language
|
||||
- generate tests for golden path
|
||||
- produce final report
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- user prompt → generated runnable app for 2–3 simple examples
|
||||
|
||||
### Phase 2 — Strong testing/review (1–2 weeks)
|
||||
|
||||
Tasks:
|
||||
|
||||
- add electron-test capability
|
||||
- add edge-case test generation
|
||||
- add restart/persistence test
|
||||
- add reviewer checklist
|
||||
- add screenshot evidence
|
||||
- add fix loop
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- generated apps pass workflow tests and review gates before delivery
|
||||
|
||||
### Phase 3 — frontend-design + image-gen (1–2 weeks)
|
||||
|
||||
Tasks:
|
||||
|
||||
- implement frontend-design spec generation
|
||||
- add design tokens/templates
|
||||
- add image-gen provider interface
|
||||
- add SVG fallback
|
||||
- add asset review
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- generated app includes coherent UI design and usable assets
|
||||
|
||||
### Phase 4 — appliance hardening (2–4 weeks)
|
||||
|
||||
Tasks:
|
||||
|
||||
- doctor/setup automatic fixes
|
||||
- high-permission appliance policy
|
||||
- package fallback
|
||||
- non-technical failure reports
|
||||
- more templates
|
||||
- partner trial scenarios
|
||||
|
||||
Exit criteria:
|
||||
|
||||
- partner can use VibeBox on the ARM box with minimal operator intervention
|
||||
|
||||
## 16. Recommended V1 Cut Line
|
||||
|
||||
V1 should include:
|
||||
|
||||
- high-permission appliance setup
|
||||
- Electron + Vite + TS + React template
|
||||
- 5–8 templates
|
||||
- frontend-design
|
||||
- image-gen provider with SVG fallback
|
||||
- full workflow Playwright/Electron tests
|
||||
- review gate
|
||||
- AppImage or unpacked delivery fallback
|
||||
- final non-technical report
|
||||
|
||||
V1 should not include:
|
||||
|
||||
- arbitrary app complexity
|
||||
- local heavy image model unless hardware supports it
|
||||
- plugin marketplace
|
||||
- long-term memory/curator
|
||||
- multi-agent scheduler
|
||||
- cloud/backend deployment
|
||||
- unrestricted shell apps
|
||||
|
||||
## 17. Top Risks and Mitigations
|
||||
|
||||
| Risk | Mitigation |
|
||||
|---|---|
|
||||
| User asks for too-large app | scope classifier + propose smaller MVP |
|
||||
| Electron packaging fails on ARM | unpacked app + launcher fallback |
|
||||
| UI tests flaky on display backend | fixed appliance environment + Xvfb/Wayland profile |
|
||||
| image-gen unavailable | SVG fallback + design prompt artifact |
|
||||
| generated app unsafe | fixed Electron security template + security review gate |
|
||||
| novice user cannot debug failure | non-technical report + preserved diagnostics |
|
||||
| dependency setup breaks system | allowlisted high-permission setup only |
|
||||
|
||||
## 18. Implementation Decisions
|
||||
|
||||
The following decisions are fixed for VibeBox V1 to avoid delaying implementation.
|
||||
|
||||
### 18.1 Agent Runtime
|
||||
|
||||
**Decision: Bun for the VibeBox agent runtime.**
|
||||
|
||||
Reasons:
|
||||
|
||||
- aligns with AirCoding baseline
|
||||
- fast startup on appliance
|
||||
- good TypeScript support
|
||||
- easy subprocess management
|
||||
- can still generate Node/Electron apps normally
|
||||
|
||||
The generated Electron apps use Node/Electron runtime as usual; Bun is only the agent/runtime implementation choice.
|
||||
|
||||
### 18.2 Generated App Package Manager
|
||||
|
||||
**Decision: bundled pnpm for generated apps.**
|
||||
|
||||
Reasons:
|
||||
|
||||
- deterministic dependency resolution
|
||||
- faster installs than npm
|
||||
- better workspace/cache behavior
|
||||
- avoids relying on user-installed package manager
|
||||
|
||||
VibeBox should ship or bootstrap a known pnpm version into its appliance cache.
|
||||
|
||||
Fallback: npm may be used only if pnpm bootstrap fails and doctor records the fallback.
|
||||
|
||||
### 18.3 Electron Template Stack
|
||||
|
||||
**Decision: Electron + Vite + TypeScript + React.**
|
||||
|
||||
Reasons:
|
||||
|
||||
- mature Electron template ecosystem
|
||||
- React is easier for AI-generated UI composition
|
||||
- TypeScript improves generated-code validation
|
||||
- Vite gives fast build/dev loop
|
||||
- Playwright/Electron testing works well with this stack
|
||||
|
||||
Default security posture:
|
||||
|
||||
- `contextIsolation: true`
|
||||
- `nodeIntegration: false`
|
||||
- explicit preload bridge
|
||||
- no arbitrary shell exposure to renderer
|
||||
- local-first storage
|
||||
|
||||
### 18.4 Image Generation Provider
|
||||
|
||||
**Decision: cloud image provider first, SVG fallback always available.**
|
||||
|
||||
V1 includes a provider interface and default cloud-provider adapter selected by deployment configuration.
|
||||
|
||||
If image provider is unavailable:
|
||||
|
||||
- generate SVG icon/assets
|
||||
- generate design prompt artifact
|
||||
- use template placeholder assets
|
||||
- continue delivery if app functionality is not blocked
|
||||
|
||||
Heavy local image models are not V1 unless the appliance hardware is explicitly provisioned for them.
|
||||
|
||||
### 18.5 Display / UI Test Backend
|
||||
|
||||
**Decision: Xvfb-first controlled display backend for automated tests.**
|
||||
|
||||
Reasons:
|
||||
|
||||
- predictable CI/appliance behavior
|
||||
- mature with Electron and Playwright
|
||||
- easier to run headless than Wayland-first automation
|
||||
|
||||
If the target appliance is Wayland-only, provide a configured compatibility path, but V1 test automation assumes Xvfb availability.
|
||||
|
||||
### 18.6 Packaging Default
|
||||
|
||||
**Decision: unpacked app + launcher is the reliability baseline; AppImage is a preferred artifact when available.**
|
||||
|
||||
Delivery order:
|
||||
|
||||
1. Build unpacked Electron app directory.
|
||||
2. Generate `launch.sh` and verify it starts.
|
||||
3. Attempt AppImage arm64 packaging.
|
||||
4. If AppImage fails but unpacked app passes full tests, deliver unpacked app + launcher and report AppImage failure as non-blocking.
|
||||
|
||||
Rationale: delivery of a working tool matters more than a single-file package.
|
||||
|
||||
### 18.7 High-Permission Dependency Installation Allowlist
|
||||
|
||||
**Decision: high-permission setup may automatically install only allowlisted dependencies.**
|
||||
|
||||
Initial ARM Linux allowlist:
|
||||
|
||||
```text
|
||||
runtime:
|
||||
- nodejs
|
||||
- npm
|
||||
- pnpm bootstrap into VibeBox cache
|
||||
|
||||
build/electron:
|
||||
- python3
|
||||
- make
|
||||
- gcc/g++ or build-essential equivalent
|
||||
- git
|
||||
- unzip
|
||||
- tar
|
||||
- xz-utils
|
||||
- ca-certificates
|
||||
|
||||
ui-test/display:
|
||||
- xvfb
|
||||
- libgtk-3 / gtk runtime package
|
||||
- libnss3
|
||||
- libxss1
|
||||
- libasound2 or platform equivalent
|
||||
- libx11-xcb1
|
||||
- libxcomposite1
|
||||
- libxdamage1
|
||||
- libxrandr2
|
||||
- libgbm1
|
||||
|
||||
packaging:
|
||||
- fuse or fuse3 when AppImage requires it
|
||||
- desktop-file-utils when available
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- Dependency names are normalized per OS/package manager by Doctor.
|
||||
- Commands are shown in status, but appliance high-permission mode runs them unless interrupted.
|
||||
- Credentials, destructive system changes, kernel/driver changes, and non-allowlisted packages require operator confirmation.
|
||||
- All setup actions are recorded in `.vibebox/reports/setup-report.md` and command artifacts.
|
||||
|
||||
### 18.8 Network Default
|
||||
|
||||
**Decision: generated apps are local-only by default.**
|
||||
|
||||
Network access is allowed only when:
|
||||
|
||||
- the user's request clearly requires it, or
|
||||
- VibeBox asks and receives product-level approval, or
|
||||
- the template explicitly declares a safe local-only loopback service.
|
||||
|
||||
Final report must state whether the generated app uses network access.
|
||||
545
AirPlan/docs/architecture/branchvibebox/vibeboxbaseline.md
Normal file
545
AirPlan/docs/architecture/branchvibebox/vibeboxbaseline.md
Normal file
@@ -0,0 +1,545 @@
|
||||
# VibeBox Baseline V1
|
||||
|
||||
Date: 2026-05-26
|
||||
Status: Downstream simplified branch of AirCoding Baseline V1
|
||||
|
||||
VibeBox is a highly simplified AirCoding derivative for an ARM Linux appliance. Its goal is to let non-technical users describe a small desktop utility in natural language, then run environment setup, development, testing, review, packaging, and delivery mostly silently in the background, finally handing the user a usable Electron application.
|
||||
|
||||
This baseline intentionally cuts most of AirCoding's general-purpose architecture to minimize implementation cost, runtime risk, and support burden.
|
||||
|
||||
## 1. Product Goal
|
||||
|
||||
VibeBox should behave like an appliance:
|
||||
|
||||
```text
|
||||
User describes desired small tool in natural language
|
||||
→ VibeBox asks only blocking product questions, if any
|
||||
→ Runs doctor/setup silently where allowed
|
||||
→ Generates Electron app from approved template
|
||||
→ Implements UI and local logic in the background
|
||||
→ Runs lint/typecheck/test/smoke test
|
||||
→ Reviews generated code
|
||||
→ Fixes issues automatically when possible
|
||||
→ Packages app for ARM Linux
|
||||
→ Delivers runnable app to user with report
|
||||
```
|
||||
|
||||
Primary experience target: after the user states the requirement, VibeBox should work in the background and only return when a usable tool is ready, unless a truly blocking product or safety decision is required.
|
||||
|
||||
Target user: non-programmer / beginner.
|
||||
|
||||
Target output: small Electron-based desktop utilities for ARM Linux.
|
||||
|
||||
Typical examples:
|
||||
|
||||
- simple file renamer
|
||||
- local note/todo app
|
||||
- clipboard helper
|
||||
- small form/data-entry utility
|
||||
- image batch resizer wrapper
|
||||
- CSV viewer/editor
|
||||
- local dashboard around simple APIs
|
||||
- single-purpose internal workflow helper
|
||||
|
||||
Non-goals:
|
||||
|
||||
- large software projects
|
||||
- multi-language deep toolchains
|
||||
- C++ build/debug loop
|
||||
- complex distributed agents
|
||||
- long-running enterprise workflow automation
|
||||
- arbitrary system administration
|
||||
- production SaaS/backend deployment
|
||||
|
||||
## 2. Relationship to AirCoding
|
||||
|
||||
VibeBox reuses AirCoding principles selectively.
|
||||
|
||||
Keep:
|
||||
|
||||
- Claude Code style execution-layer discipline
|
||||
- Anthropic canonical message format internally
|
||||
- conservative file edit/diff/update primitives
|
||||
- local session persistence
|
||||
- artifact/evidence records
|
||||
- doctor/setup environment checks
|
||||
- TUI/HUD or simple appliance UI status display
|
||||
- review/test before delivery
|
||||
|
||||
Cut or defer:
|
||||
|
||||
- Architecture Designer as a separate agent
|
||||
- complex Scheduler / TaskGraph / worktree parallelism
|
||||
- C++ toolchain profile
|
||||
- multi-language toolchain packages
|
||||
- network/GUI/static-analysis Air plugin family as first-class components
|
||||
- ExperienceMiner / Curator
|
||||
- Debug Knowledge Network
|
||||
- project migration complexity beyond simple schema versioning
|
||||
- multi-provider complexity beyond one configured provider
|
||||
- OpenCode-compatible advanced TUI
|
||||
|
||||
## 3. Core Design Principle
|
||||
|
||||
VibeBox should optimize for appliance reliability over architectural generality.
|
||||
|
||||
Key rule:
|
||||
|
||||
> One user request should produce one small app project through a linear setup → generate → test → review → package → deliver pipeline, with background silent execution as the default.
|
||||
|
||||
The system should not require the user to supervise intermediate development steps. Progress can be visible in status/HUD, but VibeBox should not ask for implementation choices unless the task is blocked.
|
||||
|
||||
No parallel write workers in V1.
|
||||
|
||||
No complex agent hierarchy in V1.
|
||||
|
||||
No automatic architecture replanning loop in V1.
|
||||
|
||||
## 4. Agent Model
|
||||
|
||||
### 4.1 Single Orchestrator
|
||||
|
||||
VibeBox has one main Orchestrator agent.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Understand user's natural language request
|
||||
- Ask only truly blocking product/safety questions
|
||||
- Choose an app template
|
||||
- Produce an internal implementation plan without requiring user approval for implementation details
|
||||
- Run environment setup through doctor/setup according to appliance permission policy
|
||||
- Drive Executor and Reviewer steps sequentially in the background
|
||||
- Present final package and usage instructions
|
||||
|
||||
### 4.2 Executor
|
||||
|
||||
Executor can be implemented as a mode of Orchestrator or a simple child process.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Scaffold Electron project from template
|
||||
- Edit files using Claude Code-like execution primitives
|
||||
- Run npm/pnpm commands
|
||||
- Run tests and smoke checks
|
||||
- Produce structured result
|
||||
|
||||
### 4.3 Reviewer/Tester
|
||||
|
||||
Reviewer/Tester can be a separate pass, not a long-lived agent.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Inspect generated diff
|
||||
- Check for obvious security issues
|
||||
- Verify app matches user request
|
||||
- Verify tests/smoke test passed
|
||||
- Produce a concise approval or requested-change report
|
||||
|
||||
V1 pipeline:
|
||||
|
||||
```text
|
||||
Orchestrator
|
||||
→ Executor
|
||||
→ Reviewer/Tester
|
||||
→ Executor fix pass if needed
|
||||
→ Package
|
||||
→ Deliver
|
||||
```
|
||||
|
||||
Maximum retry cycles: 2.
|
||||
|
||||
If still failing, show clear failure report and ask user whether to continue.
|
||||
|
||||
## 5. Execution-Layer Quality Standard
|
||||
|
||||
VibeBox follows AirCoding D-059: execution-layer primitives align with Claude Code for code quality.
|
||||
|
||||
Required behaviors:
|
||||
|
||||
- read before edit
|
||||
- small exact edits
|
||||
- no broad rewrites unless scaffolding from template
|
||||
- no unrelated refactors
|
||||
- run verification before declaring success
|
||||
- collect evidence for build/test/package results
|
||||
- diagnose root cause on failure, not random retries
|
||||
- explicitly escalate if the requested app is outside supported scope
|
||||
|
||||
This is the most important reuse point from AirCoding.
|
||||
|
||||
## 6. Technology Stack
|
||||
|
||||
Recommended V1 stack:
|
||||
|
||||
```text
|
||||
Runtime: TypeScript + Bun or Node.js
|
||||
App target: Electron
|
||||
Frontend: React + Vite or plain HTML/TS template
|
||||
Package manager: pnpm or npm
|
||||
Testing: vitest + Playwright/Electron smoke test
|
||||
Packaging: electron-builder or electron-forge
|
||||
Target OS: ARM Linux
|
||||
```
|
||||
|
||||
Default app template:
|
||||
|
||||
```text
|
||||
Electron + Vite + TypeScript
|
||||
├── main process
|
||||
├── preload bridge
|
||||
├── renderer UI
|
||||
├── local storage helper
|
||||
├── test harness
|
||||
└── packaging config for ARM Linux
|
||||
```
|
||||
|
||||
Security defaults:
|
||||
|
||||
- `contextIsolation: true`
|
||||
- `nodeIntegration: false`
|
||||
- explicit preload API
|
||||
- no remote code execution
|
||||
- no arbitrary shell command from generated app unless user explicitly requested and approved
|
||||
- local-first storage by default
|
||||
|
||||
## 7. Project Layout
|
||||
|
||||
Each generated app is self-contained.
|
||||
|
||||
```text
|
||||
<workspace>/<app-name>/
|
||||
├── package.json
|
||||
├── src/
|
||||
│ ├── main/
|
||||
│ ├── preload/
|
||||
│ └── renderer/
|
||||
├── tests/
|
||||
├── dist/
|
||||
├── release/
|
||||
└── .vibebox/
|
||||
├── project.json
|
||||
├── session.db
|
||||
├── artifacts/
|
||||
├── reports/
|
||||
└── state.json
|
||||
```
|
||||
|
||||
VibeBox may later converge with AirCoding `.air/shared` + `.air/local`, but V1 uses `.vibebox/` for product clarity and isolation.
|
||||
|
||||
## 8. Session and State
|
||||
|
||||
V1 uses one SQLite database per generated project:
|
||||
|
||||
```text
|
||||
<app>/.vibebox/session.db
|
||||
```
|
||||
|
||||
Minimum tables:
|
||||
|
||||
- `messages`
|
||||
- `message_drafts`
|
||||
- `steps`
|
||||
- `tool_runs`
|
||||
- `command_runs`
|
||||
- `artifacts`
|
||||
- `reports`
|
||||
|
||||
No complex TaskGraph tables in V1.
|
||||
|
||||
Pipeline steps are linear:
|
||||
|
||||
```text
|
||||
clarify
|
||||
plan
|
||||
scaffold
|
||||
implement
|
||||
test
|
||||
review
|
||||
fix
|
||||
package
|
||||
deliver
|
||||
```
|
||||
|
||||
Artifacts:
|
||||
|
||||
```text
|
||||
.vibebox/artifacts/
|
||||
├── command-runs/
|
||||
├── screenshots/
|
||||
├── build-logs/
|
||||
├── test-logs/
|
||||
├── review-reports/
|
||||
└── packages/
|
||||
```
|
||||
|
||||
## 9. Tool Set
|
||||
|
||||
Minimum built-in tools include frontend design and image generation as first-class VibeBox capabilities, because the target output is a user-facing Electron app and the user may not be able to provide UI/assets manually.
|
||||
|
||||
### Filesystem
|
||||
|
||||
- list files
|
||||
- read file
|
||||
- write file
|
||||
- edit file with exact replacement
|
||||
- apply patch
|
||||
- create project from template
|
||||
|
||||
### Shell
|
||||
|
||||
- run command with timeout
|
||||
- capture stdout/stderr artifacts
|
||||
- enforce output limits
|
||||
|
||||
### Electron workflow
|
||||
|
||||
- install dependencies
|
||||
- run dev build
|
||||
- run typecheck
|
||||
- run unit tests
|
||||
- run smoke test
|
||||
- package app
|
||||
|
||||
### Frontend design
|
||||
|
||||
- generate layout plan from natural language requirement
|
||||
- choose sensible UI pattern from templates (form, dashboard, list/detail, wizard, utility panel)
|
||||
- generate component structure and styling tokens
|
||||
- generate CSS/theme defaults suitable for appliance users
|
||||
- generate responsive layout for common small displays
|
||||
- review screenshot against requested UX
|
||||
|
||||
### Image generation / assets
|
||||
|
||||
- generate app icon
|
||||
- generate placeholder illustrations / empty-state images
|
||||
- generate simple background or decorative assets when useful
|
||||
- generate SVG assets when bitmap generation is unavailable
|
||||
- edit/regenerate assets from user feedback
|
||||
- store generated assets as artifacts before copying into the app
|
||||
|
||||
### Electron automated testing
|
||||
|
||||
- generate Playwright/Electron tests for all core user workflows
|
||||
- launch Electron app in controlled test mode
|
||||
- interact with UI elements, forms, menus, file pickers, and local storage paths where applicable
|
||||
- test invalid/empty/large input cases relevant to the generated tool
|
||||
- test restart/persistence behavior when the app stores local data
|
||||
- capture screenshots and traces for failed UI tests
|
||||
- run packaged-app launch test after packaging
|
||||
|
||||
### UI evidence
|
||||
|
||||
- launch app under Xvfb/Wayland-compatible mode if available
|
||||
- capture screenshot
|
||||
- compare screenshot against generated design intent
|
||||
- use automated UI test evidence, not only smoke-test evidence
|
||||
|
||||
### Delivery
|
||||
|
||||
- collect release artifact
|
||||
- generate README / usage instructions
|
||||
- generate final report
|
||||
|
||||
## 10. Doctor / Setup
|
||||
|
||||
First startup runs read-only doctor.
|
||||
|
||||
Checks:
|
||||
|
||||
- Node.js or Bun availability
|
||||
- npm/pnpm availability
|
||||
- Electron install ability
|
||||
- frontend-design capability availability
|
||||
- image generation provider availability or local image model availability
|
||||
- build tools required by native npm modules
|
||||
- display/Xvfb availability for automated Electron UI tests
|
||||
- Playwright/Electron automation support
|
||||
- disk space
|
||||
- write permissions to workspace
|
||||
- ARM Linux architecture
|
||||
- package manager cache availability
|
||||
|
||||
If issues exist:
|
||||
|
||||
- Low-permission mode: ask user before fix
|
||||
- High-permission appliance mode: run fix automatically after showing a brief visible plan, unless the user interrupts
|
||||
- First startup on a prepared appliance may be pre-authorized by the vendor/operator; otherwise it shows the fix plan before proceeding
|
||||
|
||||
VibeBox's default appliance deployment should be high-permission and background-oriented. Environment setup is part of the product promise: the user should not need to manually install Node/Electron/build dependencies.
|
||||
|
||||
## 11. User Interaction Model
|
||||
|
||||
VibeBox should minimize technical language and assume the user lacks computer expertise. Default mode is highest-permission appliance automation with strong test/review gates, not an interactive developer workflow.
|
||||
|
||||
User sees:
|
||||
|
||||
```text
|
||||
1. Understanding your app idea
|
||||
2. Creating the app
|
||||
3. Testing the app
|
||||
4. Reviewing quality
|
||||
5. Packaging for this box
|
||||
6. Ready to use
|
||||
```
|
||||
|
||||
Clarifying questions should be limited to product choices, for example:
|
||||
|
||||
- app name
|
||||
- input/output file types
|
||||
- desired UI layout
|
||||
- whether data stays local
|
||||
- whether app may access network
|
||||
|
||||
Do not ask users about implementation details unless necessary. If a decision can be safely inferred from the user's requirement and appliance defaults, VibeBox should choose automatically and report the choice in the final summary.
|
||||
|
||||
## 12. Review and Test Gate
|
||||
|
||||
VibeBox must maximize testing and review strength because the user may not be able to diagnose failures manually.
|
||||
|
||||
Before delivery, VibeBox must have:
|
||||
|
||||
- environment setup result
|
||||
- dependency install result
|
||||
- install/build command result
|
||||
- typecheck result where TypeScript is used
|
||||
- lint result when configured
|
||||
- unit test result when tests exist
|
||||
- integration test result for file/data flows when applicable
|
||||
- end-to-end UI test result covering the main user workflows
|
||||
- edge-case test result for invalid/empty/large inputs relevant to the app
|
||||
- persistence/restart test result when the app stores local data
|
||||
- frontend design review result
|
||||
- generated asset review result when image-gen is used
|
||||
- packaged-app launch test result
|
||||
- screenshot evidence when a display backend is available
|
||||
- reviewer report
|
||||
- final package artifact
|
||||
|
||||
Recommended review passes:
|
||||
|
||||
1. Functional review: does the app match the user's request?
|
||||
2. Runtime review: does it start and perform the golden path?
|
||||
3. Full workflow test review: are all core user workflows covered by automated tests?
|
||||
4. Edge-case review: are invalid/empty/large-input paths tested where relevant?
|
||||
5. Frontend/design review: does the UI match the generated design intent and stay usable for a novice?
|
||||
6. Asset review: are generated icons/images appropriate, local, and correctly bundled?
|
||||
7. Security review: does it avoid dangerous filesystem/network/shell behavior?
|
||||
8. Packaging review: can the delivered app run on the ARM Linux box?
|
||||
|
||||
If a gate is skipped, final report must say why. Delivery should be blocked if the app cannot be launched, packaged, or validated through all core workflows. Smoke testing alone is insufficient for delivery.
|
||||
|
||||
Delivery is blocked if:
|
||||
|
||||
- app fails to start
|
||||
- package build fails
|
||||
- generated app requests unsafe permissions not approved by user
|
||||
- reviewer finds high-severity issue
|
||||
|
||||
## 13. Packaging and Delivery
|
||||
|
||||
Default package output:
|
||||
|
||||
```text
|
||||
<app>/release/
|
||||
├── <app-name>-arm64.AppImage or unpacked Linux directory
|
||||
├── README.md
|
||||
└── vibebox-report.md
|
||||
```
|
||||
|
||||
If AppImage is not feasible on the target box, deliver an unpacked Electron app directory plus launcher script.
|
||||
|
||||
Final report includes:
|
||||
|
||||
- what was built
|
||||
- how to launch
|
||||
- where files are stored
|
||||
- tests run
|
||||
- known limitations
|
||||
- package path
|
||||
|
||||
## 14. Scope Guards
|
||||
|
||||
VibeBox should refuse or ask for escalation when user asks for:
|
||||
|
||||
- malware, credential stealing, persistence, stealth, evasion
|
||||
- destructive system modification
|
||||
- unsupported drivers/kernel changes
|
||||
- large multi-service systems
|
||||
- cloud deployment requiring secrets
|
||||
- apps that require unapproved network or filesystem access
|
||||
|
||||
## 15. Reuse Strategy
|
||||
|
||||
Reuse strongly from AirCoding:
|
||||
|
||||
- execution-primitives aligned with Claude Code
|
||||
- Anthropic canonical message handling
|
||||
- ToolResult / ArtifactRef / EvidenceRef style
|
||||
- doctor/dependency concepts
|
||||
- basic session/artifact persistence
|
||||
|
||||
Reuse from OpenCode:
|
||||
|
||||
- optional TUI style if VibeBox has an operator console
|
||||
- theme/dialog/status patterns
|
||||
|
||||
Reuse from Codex:
|
||||
|
||||
- shell/patch/test direct loop
|
||||
- broad tool/capability examples
|
||||
|
||||
Reuse from Claude Skills:
|
||||
|
||||
- packaged workflow templates
|
||||
- app-generation skill format
|
||||
|
||||
Do not carry over:
|
||||
|
||||
- AirCoding multi-agent scheduler complexity
|
||||
- C++-specific toolchain
|
||||
- long-term memory/curator in V1
|
||||
- OpenCode business state model
|
||||
|
||||
## 16. MVP Acceptance Criteria
|
||||
|
||||
A VibeBox V1 prototype is acceptable when it can:
|
||||
|
||||
1. Run doctor on the ARM Linux box.
|
||||
2. Accept a novice user's natural-language app request.
|
||||
3. Ask at most 3 clarifying questions for a simple app.
|
||||
4. Scaffold an Electron template.
|
||||
5. Implement requested UI and local behavior.
|
||||
6. Run build/typecheck/test or explain skipped gates.
|
||||
7. Launch the app for a smoke test and capture evidence.
|
||||
8. Run a review pass and fix at least one round of issues.
|
||||
9. Package the app for ARM Linux or deliver a runnable unpacked app.
|
||||
10. Produce a final user-friendly report.
|
||||
|
||||
## 17. Explicit Differences from AirCoding Baseline V1
|
||||
|
||||
| Area | AirCoding | VibeBox |
|
||||
|---|---|---|
|
||||
| Target | General coding agent, C++ first | Appliance for small Electron apps |
|
||||
| User | Developer | Beginner/non-programmer |
|
||||
| Agent model | Main + Architect + Scheduler + Workers | Linear Orchestrator + Executor + Reviewer |
|
||||
| State layout | `.air/shared` + `.air/local` | `.vibebox/` per generated app |
|
||||
| Toolchain | multi-language, C++ deep first | Electron/Node only |
|
||||
| Parallelism | write-area/worktree capable | none in V1 |
|
||||
| Memory | Project Rules + ExperienceMiner + Curator | minimal session memory only |
|
||||
| Debug knowledge | structured local DB | not in V1 |
|
||||
| UI assets | optional capability | useful for app UI generation |
|
||||
|
||||
## 18. Fixed V1 Implementation Decisions
|
||||
|
||||
Detailed rationale lives in `feasibility-plan.md`.
|
||||
|
||||
1. **Agent runtime**: Bun.
|
||||
2. **Generated app stack**: Electron + Vite + TypeScript + React.
|
||||
3. **Package manager**: bundled pnpm, npm fallback only if doctor records the fallback.
|
||||
4. **Image generation**: cloud image provider first, SVG/design-prompt fallback always available.
|
||||
5. **Display/test backend**: Xvfb-first controlled backend for automated Electron UI tests.
|
||||
6. **Packaging**: unpacked app + launcher is the reliability baseline; AppImage arm64 is preferred when available.
|
||||
7. **Permissions/setup**: default high-permission appliance mode with an allowlisted dependency installation set.
|
||||
8. **Network**: generated apps are local-only by default unless the user request clearly requires network access or the user approves it.
|
||||
9. **Testing**: smoke test alone is insufficient; V1 requires full workflow E2E tests for core user requirements.
|
||||
858
AirPlan/docs/architecture/c4/code-view.md
Normal file
858
AirPlan/docs/architecture/c4/code-view.md
Normal file
@@ -0,0 +1,858 @@
|
||||
# C4 Code View and UML Class Model
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Formal V1 code-view design for AirCoding V1.0.0 Alpha skeleton
|
||||
|
||||
This document refines `AirPlan/docs/architecture/c4/module.md` from container/module view into package-level code structure, class/service responsibilities, UML class diagrams, and implementation boundaries.
|
||||
|
||||
Canonical TypeScript interface contracts are defined in `AirPlan/docs/architecture/interface-contracts-v1.md`.
|
||||
|
||||
## 1. Code View Scope
|
||||
|
||||
The V1.0.0 Alpha code view covers these packages:
|
||||
|
||||
```text
|
||||
packages/contracts
|
||||
packages/cli
|
||||
packages/runtime
|
||||
packages/llm
|
||||
packages/toolchain-cpp
|
||||
packages/tui
|
||||
```
|
||||
|
||||
The code view is implementation-facing but remains architecture-only. It defines expected classes/interfaces and relationships; exact file names may be adjusted during implementation if contracts and dependencies remain stable.
|
||||
|
||||
## 2. Package Dependency Diagram
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
skinparam componentStyle rectangle
|
||||
|
||||
package "packages/contracts" as contracts
|
||||
package "packages/cli" as cli
|
||||
package "packages/runtime" as runtime
|
||||
package "packages/llm" as llm
|
||||
package "packages/toolchain-cpp" as cpp
|
||||
package "packages/tui" as tui
|
||||
|
||||
cli --> runtime
|
||||
cli --> tui
|
||||
cli --> llm
|
||||
cli --> cpp
|
||||
|
||||
runtime --> contracts
|
||||
runtime --> llm : adapter interfaces
|
||||
runtime ..> cpp : capability registration boundary
|
||||
|
||||
llm --> contracts
|
||||
cpp --> contracts
|
||||
tui --> contracts
|
||||
runtime --> llm : ProviderManager facade/API
|
||||
|
||||
@enduml
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. `contracts` must have no implementation-package dependencies.
|
||||
2. `runtime` must not import `tui`.
|
||||
3. `tui` must depend only on `contracts` and a narrow `ProjectionClient`/UI API boundary; it must not import runtime private services, query SQLite, or subscribe to EventBus directly.
|
||||
4. `toolchain-cpp` exposes tools through capability registration, not direct runtime coupling.
|
||||
5. `llm` owns provider adapters, model config, provider conversion, and ProviderManager implementation; `runtime` owns prompt assembly and calls LLM through the provider facade/API.
|
||||
|
||||
## 3. Contracts Package Code View
|
||||
|
||||
Expected directory:
|
||||
|
||||
```text
|
||||
packages/contracts/src/
|
||||
index.ts
|
||||
ids.ts
|
||||
runtime.ts
|
||||
event.ts
|
||||
ipc.ts
|
||||
task.ts
|
||||
worker-result.ts
|
||||
tool.ts
|
||||
artifact.ts
|
||||
evidence.ts
|
||||
project.ts
|
||||
provider.ts
|
||||
permission.ts
|
||||
ui.ts
|
||||
error.ts
|
||||
capability.ts
|
||||
platform.ts
|
||||
```
|
||||
|
||||
### UML
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
interface RuntimeEvent<T> {
|
||||
id: UUID
|
||||
type: string
|
||||
version: number
|
||||
timestamp: ISOTimeString
|
||||
session_id: SessionID
|
||||
project_id?: ProjectID
|
||||
source: EventSource
|
||||
route: string[]
|
||||
payload: T
|
||||
}
|
||||
|
||||
interface TaskSpec {
|
||||
id: TaskID
|
||||
type: TaskType
|
||||
title: string
|
||||
description: string
|
||||
acceptance_criteria: string[]
|
||||
scope: TaskScope
|
||||
dependencies: TaskDependencySpec[]
|
||||
verification: VerificationPolicy
|
||||
constraints: TaskConstraints
|
||||
context_refs: TaskContextRefs
|
||||
output_contract: WorkerOutputContract
|
||||
}
|
||||
|
||||
interface WorkerResult<T> {
|
||||
task_id: TaskID
|
||||
agent_id: AgentID
|
||||
agent_type: AgentType
|
||||
status: WorkerStatus
|
||||
summary: string
|
||||
changed_files: string[]
|
||||
artifacts: ArtifactRef[]
|
||||
verification: VerificationResult[]
|
||||
risks: Risk[]
|
||||
follow_up_tasks: FollowUpTask[]
|
||||
evidence_refs: EvidenceRef[]
|
||||
result: T
|
||||
}
|
||||
|
||||
interface ToolDefinition<I, O> {
|
||||
name: string
|
||||
version: number
|
||||
description: string
|
||||
input_schema: JsonSchema<I>
|
||||
output_schema: JsonSchema<O>
|
||||
category: ToolCategory
|
||||
permissions: ToolPermissionSpec
|
||||
streaming: boolean
|
||||
}
|
||||
|
||||
interface ProviderCapabilityMatrix
|
||||
interface AirError
|
||||
interface ArtifactRef
|
||||
interface EvidenceRef
|
||||
interface PermissionDecision
|
||||
interface ProjectionSnapshot
|
||||
interface CapabilityManifestV1
|
||||
|
||||
RuntimeEvent --> EventSource
|
||||
TaskSpec --> WorkerResult : output contract
|
||||
WorkerResult --> ArtifactRef
|
||||
WorkerResult --> EvidenceRef
|
||||
ToolDefinition --> PermissionDecision
|
||||
AirError --> EvidenceRef
|
||||
@enduml
|
||||
```
|
||||
|
||||
### Contract Ownership
|
||||
|
||||
| Contract | File | Primary consumers |
|
||||
|---|---|---|
|
||||
| IDs and aliases | `ids.ts` | all packages |
|
||||
| RuntimeEvent/EventSource | `event.ts` | EventStore, EventBus, IPC, ProjectionStore |
|
||||
| TaskSpec | `task.ts` | Scheduler, workers, ContextAssembler |
|
||||
| WorkerResult | `worker-result.ts` | workers, Scheduler, Main Agent |
|
||||
| ToolDefinition/ToolResult | `tool.ts` | ToolRegistry, capabilities, workers |
|
||||
| ArtifactRef/EvidenceRef | `artifact.ts`, `evidence.ts` | ArtifactStore, EvidenceStore, reports |
|
||||
| ProviderCapabilityMatrix | `provider.ts` | ProviderManager, Scheduler, Doctor |
|
||||
| AirError/ErrorKind | `error.ts` | tools, Scheduler, agents, UI |
|
||||
| IpcMessage/ControlMessage | `ipc.ts` | WorkerManager, child workers |
|
||||
| PermissionDecision | `permission.ts` | PermissionEngine, ToolRegistry, UI |
|
||||
| ProjectionSnapshot | `ui.ts` | ProjectionStore, TUI/HUD |
|
||||
| CapabilityManifestV1 | `capability.ts` | CapabilityRegistry, Doctor |
|
||||
|
||||
## 4. Runtime Package Code View
|
||||
|
||||
Expected directory:
|
||||
|
||||
```text
|
||||
packages/runtime/src/
|
||||
index.ts
|
||||
app/
|
||||
RuntimeApp.ts
|
||||
ServiceRegistry.ts
|
||||
config/
|
||||
ConfigLoader.ts
|
||||
ResourceLoader.ts
|
||||
project/
|
||||
ProjectLocator.ts
|
||||
ProjectInitializer.ts
|
||||
ProjectStore.ts
|
||||
storage/
|
||||
DatabaseManager.ts
|
||||
MigrationRunner.ts
|
||||
repositories/
|
||||
events/
|
||||
EventBus.ts
|
||||
EventStore.ts
|
||||
EventIngestor.ts
|
||||
EventSchemaRegistry.ts
|
||||
sessions/
|
||||
SessionManager.ts
|
||||
SessionStore.ts
|
||||
scheduler/
|
||||
Scheduler.ts
|
||||
TaskGraph.ts
|
||||
WavePlanner.ts
|
||||
RetryPlanner.ts
|
||||
WorkspaceManager.ts
|
||||
AgentMonitor.ts
|
||||
workers/
|
||||
WorkerManager.ts
|
||||
WorkerProcess.ts
|
||||
WorkerProtocol.ts
|
||||
roles/
|
||||
tools/
|
||||
ToolRegistry.ts
|
||||
BuiltInToolRegistrar.ts
|
||||
fs/
|
||||
shell/
|
||||
git/
|
||||
project/
|
||||
artifact/
|
||||
context/
|
||||
permission/
|
||||
doctor/
|
||||
security/
|
||||
PermissionEngine.ts
|
||||
PathClassifier.ts
|
||||
CommandRiskAnalyzer.ts
|
||||
SecretRedactor.ts
|
||||
capabilities/
|
||||
CapabilityRegistry.ts
|
||||
CapabilityManifestValidator.ts
|
||||
context/
|
||||
ContextAssembler.ts
|
||||
PromptLayerLoader.ts
|
||||
CompactionPolicy.ts
|
||||
artifacts/
|
||||
ArtifactStore.ts
|
||||
EvidenceStore.ts
|
||||
knowledge/
|
||||
DebugKnowledgeStore.ts
|
||||
LearnedMemoryStore.ts
|
||||
projection/
|
||||
ProjectionStore.ts
|
||||
projections/
|
||||
doctor/
|
||||
DoctorService.ts
|
||||
checks/
|
||||
logging/
|
||||
Logger.ts
|
||||
DeveloperLogEncryptor.ts
|
||||
agents/
|
||||
main/
|
||||
architecture/
|
||||
```
|
||||
|
||||
### Runtime Service UML
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
class RuntimeApp {
|
||||
+start(options): Promise<void>
|
||||
+shutdown(): Promise<void>
|
||||
}
|
||||
|
||||
class ServiceRegistry {
|
||||
+get<T>(token): T
|
||||
+register(token, service): void
|
||||
}
|
||||
|
||||
class ProjectStore {
|
||||
+open(root): Promise<ProjectContext>
|
||||
+initialize(root): Promise<ProjectContext>
|
||||
}
|
||||
|
||||
class SessionManager {
|
||||
+openSession(project, options): Promise<SessionContext>
|
||||
+closeSession(sessionId): Promise<void>
|
||||
}
|
||||
|
||||
class DatabaseManager {
|
||||
+open(path): DatabaseHandle
|
||||
+transaction(fn): Promise<T>
|
||||
}
|
||||
|
||||
class MigrationRunner {
|
||||
+migrate(db): Promise<void>
|
||||
}
|
||||
|
||||
class EventStore {
|
||||
+append(event): Promise<void>
|
||||
+query(filter): Promise<RuntimeEvent[]>
|
||||
}
|
||||
|
||||
class EventIngestor {
|
||||
+ingest(event): Promise<void>
|
||||
+ingest_ephemeral(event): Promise<void>
|
||||
}
|
||||
|
||||
class EventBus {
|
||||
+publish(event): void
|
||||
+subscribe(filter, handler): Subscription
|
||||
}
|
||||
|
||||
class ProjectionStore {
|
||||
+hydrate(sessionId): Promise<void>
|
||||
+apply(event): void
|
||||
+snapshot(): ProjectionSnapshot
|
||||
}
|
||||
|
||||
RuntimeApp --> ServiceRegistry
|
||||
RuntimeApp --> ProjectStore
|
||||
RuntimeApp --> SessionManager
|
||||
SessionManager --> DatabaseManager
|
||||
DatabaseManager --> MigrationRunner
|
||||
EventIngestor --> EventStore : durable events
|
||||
EventIngestor --> EventBus : ephemeral events
|
||||
EventStore --> DatabaseManager
|
||||
EventStore --> EventBus : publishes after commit
|
||||
ProjectionStore --> SessionStore : hydrate via repositories
|
||||
ProjectionStore --> EventBus : subscribes to live events
|
||||
@enduml
|
||||
```
|
||||
|
||||
### Scheduler UML
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
class Scheduler {
|
||||
+create_tasks(session_id, specs): Promise<void>
|
||||
+add_dependency(session_id, task_id, dependency): Promise<void>
|
||||
+load_graph(session_id): Promise<TaskGraph>
|
||||
+run_until_idle(session_id): Promise<SchedulerRunResult>
|
||||
+cancel_task(task_id, reason): Promise<void>
|
||||
-plan_wave(graph): SchedulerWavePlan
|
||||
-dispatch(wave): Promise<void>
|
||||
-collect_results(): Promise<void>
|
||||
}
|
||||
|
||||
class TaskGraph {
|
||||
+tasks: Map<TaskID, TaskNode>
|
||||
+dependencies: TaskDependencyRecord[]
|
||||
+getRunnableTasks(): TaskNode[]
|
||||
+markTerminal(taskId, status): void
|
||||
}
|
||||
|
||||
class WavePlanner {
|
||||
+plan(graph, resources): SchedulerWavePlan
|
||||
}
|
||||
|
||||
class RetryPlanner {
|
||||
+decide(task, attempts, error): RetryDecision
|
||||
}
|
||||
|
||||
class WorkspaceManager {
|
||||
+createWorkspace(plan): Promise<WorkspaceRef>
|
||||
+mergeWorkspace(workspaceId): Promise<MergeResult>
|
||||
+cleanupWorkspace(workspaceId): Promise<void>
|
||||
}
|
||||
|
||||
class AgentMonitor {
|
||||
+recordHeartbeat(event): void
|
||||
+detectLostAgents(): Promise<AgentLost[]>
|
||||
+enforceTimeouts(): Promise<void>
|
||||
}
|
||||
|
||||
class WorkerManager {
|
||||
+spawn(taskSpec, contextPack): Promise<WorkerProcess>
|
||||
+cancel(agentId, reason): Promise<void>
|
||||
}
|
||||
|
||||
class WorkerProcess {
|
||||
+agent_id: AgentID
|
||||
+pid?: number
|
||||
+send(envelope): void
|
||||
+on_message(handler): void
|
||||
}
|
||||
|
||||
Scheduler --> TaskGraph
|
||||
Scheduler --> WavePlanner
|
||||
Scheduler --> RetryPlanner
|
||||
Scheduler --> WorkspaceManager
|
||||
Scheduler --> AgentMonitor
|
||||
Scheduler --> WorkerManager
|
||||
Scheduler --> EventStore
|
||||
Scheduler --> ContextAssembler
|
||||
WorkerManager --> WorkerProcess
|
||||
@enduml
|
||||
```
|
||||
|
||||
### Tool/Permission UML
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
class ToolRegistry {
|
||||
+register(definition, executor): void
|
||||
+call(name, input, context): Promise<ToolResultEnvelope>
|
||||
+list(): ToolDefinition[]
|
||||
}
|
||||
|
||||
class PermissionEngine {
|
||||
+evaluate(request): Promise<PermissionDecision>
|
||||
+record(decision, context): Promise<void>
|
||||
}
|
||||
|
||||
class PathClassifier {
|
||||
+classify(path, projectRoot): PathRiskClassification
|
||||
}
|
||||
|
||||
class CommandRiskAnalyzer {
|
||||
+analyze(command, cwd): CommandRiskAnalysis
|
||||
}
|
||||
|
||||
class CapabilityRegistry {
|
||||
+discover(): Promise<CapabilityManifestV1[]>
|
||||
+validate(manifest): Promise<ValidationResult>
|
||||
+enable(capability_id): Promise<void>
|
||||
+disable(capability_id): Promise<void>
|
||||
+register_tools(tool_registry): Promise<void>
|
||||
}
|
||||
|
||||
class DoctorService {
|
||||
+run(input): Promise<DoctorRunOutput>
|
||||
+checkCapability(capability): Promise<DoctorIssue[]>
|
||||
}
|
||||
|
||||
ToolRegistry --> PermissionEngine
|
||||
ToolRegistry --> EventIngestor
|
||||
ToolRegistry --> ArtifactStore
|
||||
PermissionEngine --> PathClassifier
|
||||
PermissionEngine --> CommandRiskAnalyzer
|
||||
PermissionEngine --> EventIngestor
|
||||
CapabilityRegistry --> ToolRegistry : registers enabled tools
|
||||
DoctorService --> CapabilityRegistry : reads manifests/checks dependencies
|
||||
@enduml
|
||||
```
|
||||
|
||||
### Context/Agent UML
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
class ContextAssembler {
|
||||
+assemble(input): Promise<AssembledContext>
|
||||
-loadLayers(profile): Promise<PromptLayer[]>
|
||||
-fitBudget(context): BudgetFitResult
|
||||
}
|
||||
|
||||
class PromptLayerLoader {
|
||||
+loadRuntimeInvariant(): PromptLayer
|
||||
+loadRole(role): PromptLayer
|
||||
+loadProjectRules(project): PromptLayer[]
|
||||
}
|
||||
|
||||
class MainAgent {
|
||||
+handleUserMessage(message): Promise<void>
|
||||
+presentProgress(): Promise<void>
|
||||
+presentBlocker(blocker): Promise<void>
|
||||
}
|
||||
|
||||
class ArchitectureDesigner {
|
||||
+assessImpact(change): Promise<ArchitectureImpact>
|
||||
+updateArchitectureDocs(update): Promise<DocumentUpdate>
|
||||
}
|
||||
|
||||
interface ProviderManager {
|
||||
+select_model(requirement): Promise<ModelAssignment>
|
||||
+complete(request): AsyncIterable<ProviderStreamEvent>
|
||||
}
|
||||
|
||||
ContextAssembler --> PromptLayerLoader
|
||||
MainAgent --> ContextAssembler
|
||||
MainAgent --> ProviderManager : LLM facade from packages/llm
|
||||
MainAgent --> Scheduler
|
||||
ArchitectureDesigner --> ContextAssembler
|
||||
ArchitectureDesigner --> ProviderManager : LLM facade from packages/llm
|
||||
ArchitectureDesigner --> EventIngestor
|
||||
|
||||
class DebugKnowledgeStore {
|
||||
+insert(record): Promise<void>
|
||||
+lookup_by_signature(sig): Promise<DebugRecord[]>
|
||||
+lookup_by_task(task_id): Promise<DebugRecord[]>
|
||||
+update(id, patch): Promise<void>
|
||||
}
|
||||
|
||||
class LearnedMemoryStore {
|
||||
+insert(memory): Promise<void>
|
||||
+lookup_by_type(type): Promise<LearnedMemory[]>
|
||||
+update_status(id, status): Promise<void>
|
||||
+scan_stale(): Promise<LearnedMemory[]>
|
||||
}
|
||||
|
||||
class CompactionPolicy {
|
||||
+should_compact(messages, budget): boolean
|
||||
+compact(messages, target): Promise<CompactionResult>
|
||||
}
|
||||
|
||||
ExperienceMinerRole --> LearnedMemoryStore
|
||||
DebuggerRole --> DebugKnowledgeStore
|
||||
ContextAssembler --> CompactionPolicy
|
||||
@enduml
|
||||
```
|
||||
|
||||
## 5. LLM Package Code View
|
||||
|
||||
Expected directory:
|
||||
|
||||
```text
|
||||
packages/llm/src/
|
||||
index.ts
|
||||
ProviderManager.ts
|
||||
ModelConfigLoader.ts
|
||||
CapabilityMatrix.ts
|
||||
ConversionReport.ts
|
||||
adapters/
|
||||
AnthropicAdapter.ts
|
||||
OpenAICompatibleAdapter.ts
|
||||
canonical/
|
||||
AnthropicCanonical.ts
|
||||
ToolUseConverter.ts
|
||||
StreamNormalizer.ts
|
||||
```
|
||||
|
||||
### UML
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
interface ProviderAdapter {
|
||||
+provider_id: string
|
||||
+list_models(): Promise<ProviderCapabilityMatrix[]>
|
||||
+validate_model(model_id): Promise<ProviderCapabilityMatrix>
|
||||
+complete(input): AsyncIterable<ProviderStreamEvent>
|
||||
+count_tokens?(input): Promise<number>
|
||||
}
|
||||
|
||||
class ProviderManager {
|
||||
+load_config(): Promise<void>
|
||||
+select_model(requirement): Promise<ModelAssignment>
|
||||
+complete(input): AsyncIterable<ProviderStreamEvent>
|
||||
}
|
||||
|
||||
class ModelConfigLoader
|
||||
class CapabilityMatrixRegistry
|
||||
class AnthropicAdapter
|
||||
class OpenAICompatibleAdapter
|
||||
class AnthropicCanonicalConverter
|
||||
class StreamNormalizer
|
||||
|
||||
ProviderManager --> ProviderAdapter
|
||||
ProviderManager --> ModelConfigLoader
|
||||
ProviderManager --> CapabilityMatrixRegistry
|
||||
AnthropicAdapter ..|> ProviderAdapter
|
||||
OpenAICompatibleAdapter ..|> ProviderAdapter
|
||||
OpenAICompatibleAdapter --> AnthropicCanonicalConverter
|
||||
ProviderAdapter --> StreamNormalizer
|
||||
@enduml
|
||||
```
|
||||
|
||||
## 6. Toolchain C++ Package Code View
|
||||
|
||||
Expected directory:
|
||||
|
||||
```text
|
||||
packages/toolchain-cpp/src/
|
||||
index.ts
|
||||
capability.ts
|
||||
CppToolRegistrar.ts
|
||||
detect/
|
||||
CppProjectDetector.ts
|
||||
build/
|
||||
CMakeConfigurator.ts
|
||||
CppBuilder.ts
|
||||
test/
|
||||
CppTestRunner.ts
|
||||
analysis/
|
||||
CppcheckRunner.ts
|
||||
ClangdClient.ts
|
||||
DiagnosticParser.ts
|
||||
```
|
||||
|
||||
### UML
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
class CppToolRegistrar {
|
||||
+register(toolRegistry): void
|
||||
}
|
||||
|
||||
class CppProjectDetector {
|
||||
+detect(projectRoot): Promise<CppDetectOutput>
|
||||
}
|
||||
|
||||
class CMakeConfigurator {
|
||||
+configure(input): Promise<CppCmakeConfigureOutput>
|
||||
}
|
||||
|
||||
class CppBuilder {
|
||||
+build(input): Promise<CppBuildOutput>
|
||||
}
|
||||
|
||||
class CppTestRunner {
|
||||
+runTests(input): Promise<CppTestOutput>
|
||||
}
|
||||
|
||||
class CppcheckRunner {
|
||||
+run(input): Promise<CppcheckOutput>
|
||||
}
|
||||
|
||||
class ClangdClient {
|
||||
+query(input): Promise<ClangdQueryOutput>
|
||||
}
|
||||
|
||||
class DiagnosticParser {
|
||||
+parse_compiler_output(output): Diagnostic[]
|
||||
+semantic_signature(diagnostic): string
|
||||
}
|
||||
|
||||
CppToolRegistrar --> CppProjectDetector
|
||||
CppToolRegistrar --> CMakeConfigurator
|
||||
CppToolRegistrar --> CppBuilder
|
||||
CppToolRegistrar --> CppTestRunner
|
||||
CppToolRegistrar --> CppcheckRunner
|
||||
CppToolRegistrar --> ClangdClient
|
||||
CMakeConfigurator --> DiagnosticParser
|
||||
CppBuilder --> DiagnosticParser
|
||||
CppTestRunner --> DiagnosticParser
|
||||
CppcheckRunner --> DiagnosticParser
|
||||
@enduml
|
||||
```
|
||||
|
||||
## 7. TUI Package Code View
|
||||
|
||||
Expected directory:
|
||||
|
||||
```text
|
||||
packages/tui/src/
|
||||
index.ts
|
||||
TuiApp.tsx
|
||||
ProjectionClient.ts
|
||||
components/
|
||||
SessionView.tsx
|
||||
TaskListView.tsx
|
||||
AgentStatusView.tsx
|
||||
ToolRunView.tsx
|
||||
DiffView.tsx
|
||||
EvidenceView.tsx
|
||||
PermissionPrompt.tsx
|
||||
BlockerReport.tsx
|
||||
HudView.tsx
|
||||
theme/
|
||||
theme.ts
|
||||
keymap/
|
||||
keymap.ts
|
||||
```
|
||||
|
||||
### UML
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
class TuiApp {
|
||||
+start(): void
|
||||
+stop(): void
|
||||
}
|
||||
|
||||
class ProjectionClient {
|
||||
+subscribe(handler): Subscription
|
||||
+snapshot(): ProjectionSnapshot
|
||||
}
|
||||
|
||||
class SessionView
|
||||
class TaskListView
|
||||
class AgentStatusView
|
||||
class ToolRunView
|
||||
class EvidenceView
|
||||
class PermissionPrompt
|
||||
class BlockerReport
|
||||
class HudView
|
||||
|
||||
TuiApp --> ProjectionClient
|
||||
TuiApp --> SessionView
|
||||
TuiApp --> TaskListView
|
||||
TuiApp --> AgentStatusView
|
||||
TuiApp --> ToolRunView
|
||||
TuiApp --> EvidenceView
|
||||
TuiApp --> PermissionPrompt
|
||||
TuiApp --> BlockerReport
|
||||
TuiApp --> HudView
|
||||
@enduml
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. UI components render projections only.
|
||||
2. Permission prompts emit user decisions through the narrow runtime UI command API, not private runtime services.
|
||||
3. UI never mutates domain tables directly.
|
||||
4. UI never imports `packages/runtime/src/*` private implementation modules.
|
||||
5. Diff/evidence views must link back to artifact/evidence refs.
|
||||
|
||||
## 8. CLI Package Code View
|
||||
|
||||
Expected directory:
|
||||
|
||||
```text
|
||||
packages/cli/src/
|
||||
index.ts
|
||||
commands/
|
||||
run.ts
|
||||
init.ts
|
||||
doctor.ts
|
||||
provider.ts
|
||||
e2e.ts
|
||||
release.ts
|
||||
bootstrap/
|
||||
createRuntime.ts
|
||||
loadConfig.ts
|
||||
```
|
||||
|
||||
### UML
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
class CliEntrypoint {
|
||||
+main(argv): Promise<number>
|
||||
}
|
||||
|
||||
class RunCommand
|
||||
class InitCommand
|
||||
class DoctorCommand
|
||||
class ProviderCommand
|
||||
class E2ECommand
|
||||
class ReleaseCommand
|
||||
class RuntimeFactory {
|
||||
+create(options): Promise<RuntimeApp>
|
||||
}
|
||||
|
||||
CliEntrypoint --> RunCommand
|
||||
CliEntrypoint --> InitCommand
|
||||
CliEntrypoint --> DoctorCommand
|
||||
CliEntrypoint --> ProviderCommand
|
||||
CliEntrypoint --> E2ECommand
|
||||
CliEntrypoint --> ReleaseCommand
|
||||
RunCommand --> RuntimeFactory
|
||||
InitCommand --> RuntimeFactory
|
||||
DoctorCommand --> RuntimeFactory
|
||||
@enduml
|
||||
```
|
||||
|
||||
## 9. Repository Interface Code View
|
||||
|
||||
Domain repositories live under `packages/runtime/src/storage/repositories/`.
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
interface SessionRepository
|
||||
interface MessageRepository
|
||||
interface EventRepository
|
||||
interface TaskRepository
|
||||
interface AgentRepository
|
||||
interface ToolRunRepository
|
||||
interface CommandRunRepository
|
||||
interface ArtifactRepository
|
||||
interface DiagnosticRepository
|
||||
interface EvidenceRepository
|
||||
interface WorkspaceRepository
|
||||
interface SummaryRepository
|
||||
interface UiStateRepository
|
||||
|
||||
class SessionStore {
|
||||
+sessions: SessionRepository
|
||||
+messages: MessageRepository
|
||||
+events: EventRepository
|
||||
+tasks: TaskRepository
|
||||
+agents: AgentRepository
|
||||
+toolRuns: ToolRunRepository
|
||||
+commandRuns: CommandRunRepository
|
||||
+artifacts: ArtifactRepository
|
||||
+diagnostics: DiagnosticRepository
|
||||
+evidence: EvidenceRepository
|
||||
+workspaces: WorkspaceRepository
|
||||
+summaries: SummaryRepository
|
||||
+uiState: UiStateRepository
|
||||
}
|
||||
@enduml
|
||||
```
|
||||
|
||||
Repositories must be thin persistence adapters. Scheduling, permission, and projection logic must not be hidden inside repositories.
|
||||
|
||||
## 10. Worker Role Code View
|
||||
|
||||
```plantuml
|
||||
@startuml
|
||||
interface WorkerRole {
|
||||
+run(taskSpec, contextPack, runtime): Promise<WorkerResult>
|
||||
}
|
||||
|
||||
class WorkerRuntime {
|
||||
+emit(event): void
|
||||
+callTool(name, input): Promise<ToolResultEnvelope>
|
||||
+checkpoint(data): Promise<void>
|
||||
}
|
||||
|
||||
class ExecutorRole
|
||||
class ReviewerRole
|
||||
class DebuggerRole
|
||||
class CompactorRole
|
||||
class ExperienceMinerRole
|
||||
|
||||
ExecutorRole ..|> WorkerRole
|
||||
ReviewerRole ..|> WorkerRole
|
||||
DebuggerRole ..|> WorkerRole
|
||||
CompactorRole ..|> WorkerRole
|
||||
ExperienceMinerRole ..|> WorkerRole
|
||||
WorkerRole --> WorkerRuntime
|
||||
@enduml
|
||||
```
|
||||
|
||||
Role constraints:
|
||||
|
||||
| Role | Write access | Required output |
|
||||
|---|---|---|
|
||||
| Executor | scoped project writes | ExecutorResult in WorkerResult |
|
||||
| Reviewer | read-only | ReviewerResult |
|
||||
| Debugger | scoped writes only when assigned | DebuggerResult |
|
||||
| Compactor | summaries/artifacts only | CompactorResult |
|
||||
| ExperienceMiner | candidates/rules/skills only when assigned | ExperienceMinerResult |
|
||||
|
||||
## 11. State Ownership Rules
|
||||
|
||||
| State | Owner | Access rule |
|
||||
|---|---|---|
|
||||
| session DB | SessionStore/EventStore | runtime services only |
|
||||
| live events | EventBus | runtime services publish/subscribe |
|
||||
| UI projections | ProjectionStore | TUI read only |
|
||||
| artifacts | ArtifactStore | tools/workers via runtime API |
|
||||
| evidence refs | EvidenceStore | reports/reviews/debug via runtime API |
|
||||
| tasks/agents | Scheduler | repositories are storage only |
|
||||
| permission decisions | PermissionEngine | ToolRegistry requests decisions |
|
||||
| model config | ProviderManager | runtime/Doctor read through API |
|
||||
| project rules | ContextAssembler/ProjectStore | workers receive context excerpts |
|
||||
|
||||
## 12. Implementation Cut Lines
|
||||
|
||||
V1.0.0 Alpha implementation must create public interfaces matching `interface-contracts-v1.md`. Classes may be implemented as functions/modules where idiomatic TypeScript is simpler, but module ownership, dependency direction, and service boundaries must remain intact.
|
||||
|
||||
Do not implement:
|
||||
|
||||
```text
|
||||
TUI direct DB access
|
||||
worker direct SQLite writes
|
||||
capability direct dependency install
|
||||
provider adapter changing prompt semantics silently
|
||||
tool execution without PermissionEngine
|
||||
repositories containing scheduling policy
|
||||
```
|
||||
356
AirPlan/docs/architecture/c4/module.md
Executable file
356
AirPlan/docs/architecture/c4/module.md
Executable file
@@ -0,0 +1,356 @@
|
||||
# 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
|
||||
352
AirPlan/docs/architecture/capability-trust-v1.md
Normal file
352
AirPlan/docs/architecture/capability-trust-v1.md
Normal file
@@ -0,0 +1,352 @@
|
||||
# AirCoding Capability Trust Model V1
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Canonical capability/plugin trust model for V1.0.0 Alpha skeleton
|
||||
|
||||
This document defines how AirCoding trusts, installs, enables, validates, and runs capabilities and plugins.
|
||||
|
||||
Capabilities are tool bundles with dependencies, triggers, evidence types, and configuration schema. They extend ToolRegistry but do not bypass runtime security.
|
||||
|
||||
## 1. Goals
|
||||
|
||||
Capability trust must:
|
||||
|
||||
1. Allow built-in and future third-party capabilities.
|
||||
2. Keep dependency installation under Doctor/setup policy.
|
||||
3. Prevent plugins from bypassing PermissionEngine.
|
||||
4. Make capability source and permissions visible.
|
||||
5. Support project-local reproducibility.
|
||||
6. Keep MVP simple while leaving a path to signed plugins later.
|
||||
|
||||
## 2. Capability Manifest
|
||||
|
||||
Manifest path:
|
||||
|
||||
```text
|
||||
CAPABILITY.md or capability.json
|
||||
```
|
||||
|
||||
V1 canonical JSON shape:
|
||||
|
||||
```ts
|
||||
interface CapabilityManifestV1 {
|
||||
schema_version: 1
|
||||
capability_id: string
|
||||
display_name: string
|
||||
version: string
|
||||
description: string
|
||||
publisher?: string
|
||||
source: CapabilitySource
|
||||
trust_level: CapabilityTrustLevel
|
||||
tools: CapabilityToolDeclaration[]
|
||||
dependencies?: CapabilityDependency[]
|
||||
permissions: CapabilityPermissionDeclaration
|
||||
events?: {
|
||||
produced?: string[]
|
||||
consumed?: string[]
|
||||
}
|
||||
artifact_types?: string[]
|
||||
config_schema?: unknown
|
||||
entrypoint?: CapabilityEntrypoint
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
type CapabilitySource =
|
||||
| { kind: "built_in" }
|
||||
| { kind: "local_path"; path: string }
|
||||
| { kind: "git"; url: string; ref?: string }
|
||||
| { kind: "registry"; registry_id: string; package: string; version: string }
|
||||
|
||||
type CapabilityTrustLevel =
|
||||
| "built_in"
|
||||
| "project_local"
|
||||
| "user_installed"
|
||||
| "verified_publisher"
|
||||
| "untrusted"
|
||||
```
|
||||
|
||||
## 3. Tool Declaration
|
||||
|
||||
```ts
|
||||
interface CapabilityToolDeclaration {
|
||||
name: string
|
||||
version: number
|
||||
category: ToolCategory
|
||||
description: string
|
||||
input_schema: unknown
|
||||
output_schema: unknown
|
||||
streaming?: boolean
|
||||
permissions: {
|
||||
read_paths?: boolean
|
||||
write_paths?: boolean
|
||||
execute?: boolean
|
||||
network?: boolean
|
||||
system_sensitive?: boolean
|
||||
credentials?: boolean
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Tool names must be namespaced unless built-in:
|
||||
|
||||
```text
|
||||
<capability-id>.<tool-name>
|
||||
```
|
||||
|
||||
Built-in tools reserve short namespaces:
|
||||
|
||||
```text
|
||||
fs.*
|
||||
shell.*
|
||||
git.*
|
||||
project.*
|
||||
cpp.*
|
||||
debug.*
|
||||
gui.*
|
||||
network.*
|
||||
artifact.*
|
||||
context.*
|
||||
permission.*
|
||||
doctor.*
|
||||
```
|
||||
|
||||
## 4. Dependency Declaration
|
||||
|
||||
```ts
|
||||
interface CapabilityDependency {
|
||||
dependency_id: string
|
||||
kind: "system_package" | "binary" | "language_package" | "service" | "model" | "provider" | "display_backend"
|
||||
required: boolean
|
||||
detector: string
|
||||
installer?: {
|
||||
strategy: "doctor_allowlisted" | "manual" | "unsupported"
|
||||
commands?: string[]
|
||||
package_names?: string[]
|
||||
}
|
||||
permission_notes?: string
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Capability manifests declare dependencies; they do not install directly.
|
||||
2. Doctor detects and installs/fixes dependencies according to permission profile.
|
||||
3. Credentials/system-sensitive dependencies always require explicit confirmation.
|
||||
4. Install commands must be visible in Doctor plan.
|
||||
|
||||
## 5. Permission Declaration
|
||||
|
||||
```ts
|
||||
interface CapabilityPermissionDeclaration {
|
||||
read_project?: boolean
|
||||
write_project?: boolean
|
||||
execute_commands?: boolean
|
||||
network?: boolean
|
||||
system_sensitive?: boolean
|
||||
credentials?: boolean
|
||||
project_outside_write?: boolean
|
||||
generated_artifacts?: string[]
|
||||
notes?: string[]
|
||||
}
|
||||
```
|
||||
|
||||
Permission declarations are maximum requested permissions, not grants. Runtime PermissionEngine still evaluates every tool call.
|
||||
|
||||
## 6. Trust Levels
|
||||
|
||||
| Trust level | Meaning | Enable behavior |
|
||||
|---|---|---|
|
||||
| `built_in` | shipped with AirCoding release | enabled by default if required |
|
||||
| `project_local` | stored in project and reviewed by user/team | ask on first enable |
|
||||
| `user_installed` | installed by user into global AirCoding config | ask on install/enable |
|
||||
| `verified_publisher` | future signed/verified source | ask with higher confidence |
|
||||
| `untrusted` | unknown source or modified package | disabled until explicit user approval |
|
||||
|
||||
Trust level affects prompts and defaults; it does not bypass PermissionEngine.
|
||||
|
||||
## 7. Capability Lifecycle
|
||||
|
||||
```text
|
||||
discovered
|
||||
→ validated
|
||||
→ doctor_checked
|
||||
→ enabled
|
||||
→ registered
|
||||
→ active
|
||||
→ disabled | failed | updated
|
||||
```
|
||||
|
||||
### `discovered`
|
||||
|
||||
Runtime finds capability manifests in configured locations.
|
||||
|
||||
### `validated`
|
||||
|
||||
Manifest schema, tool schemas, namespacing, and declared permissions are validated.
|
||||
|
||||
### `doctor_checked`
|
||||
|
||||
Doctor checks dependencies and reports missing/incompatible items.
|
||||
|
||||
### `enabled`
|
||||
|
||||
User/project policy enables the capability.
|
||||
|
||||
### `registered`
|
||||
|
||||
Tools are added to ToolRegistry with permission metadata.
|
||||
|
||||
### `active`
|
||||
|
||||
Tools may be invoked through normal ToolRegistry path.
|
||||
|
||||
## 8. Capability Locations
|
||||
|
||||
Built-in:
|
||||
|
||||
```text
|
||||
resources/capabilities/
|
||||
```
|
||||
|
||||
Global user-installed:
|
||||
|
||||
```text
|
||||
~/.air/capabilities/
|
||||
```
|
||||
|
||||
Project-local:
|
||||
|
||||
```text
|
||||
<project>/.air/shared/capabilities/
|
||||
```
|
||||
|
||||
Cached downloads:
|
||||
|
||||
```text
|
||||
~/.air/cache/plugins/
|
||||
```
|
||||
|
||||
Project-local capability config:
|
||||
|
||||
```text
|
||||
<project>/.air/shared/capabilities.yaml
|
||||
```
|
||||
|
||||
## 9. Runtime Isolation
|
||||
|
||||
MVP isolation:
|
||||
|
||||
1. Capability tools run as normal runtime tools or child processes under ToolRegistry control.
|
||||
2. Every filesystem/shell/network action goes through PermissionEngine.
|
||||
3. Capability code cannot write EventStore directly; it emits tool results/events through runtime APIs.
|
||||
4. Capability-generated artifacts use ArtifactStore.
|
||||
5. Capability config is schema-validated.
|
||||
6. Capability logs go through runtime logging with redaction rules.
|
||||
|
||||
Post-MVP may add process/container sandboxing.
|
||||
|
||||
## 10. Event Namespace Rules
|
||||
|
||||
Built-in event types are defined in `event-registry-v1.md`.
|
||||
|
||||
Capability custom events must be namespaced:
|
||||
|
||||
```text
|
||||
capability.<capability-id>.<event-name>
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Custom capability events are ephemeral by default.
|
||||
2. Durable custom events require registration and schema approval.
|
||||
3. Capability events must not spoof built-in event names.
|
||||
4. EventStore rejects unknown durable events unless development-mode config explicitly allows them.
|
||||
|
||||
## 11. Update and Integrity Rules
|
||||
|
||||
MVP:
|
||||
|
||||
```text
|
||||
record source kind/path/ref/version
|
||||
record manifest hash
|
||||
ask before updating user-installed or project-local capability
|
||||
Doctor rechecks dependencies after update
|
||||
```
|
||||
|
||||
Post-MVP:
|
||||
|
||||
```text
|
||||
signature verification
|
||||
publisher trust store
|
||||
lockfile with hashes
|
||||
reproducible capability bundle format
|
||||
```
|
||||
|
||||
Project lockfile candidate:
|
||||
|
||||
```text
|
||||
<project>/.air/shared/capability-lock.json
|
||||
```
|
||||
|
||||
## 12. Built-in MVP Capabilities
|
||||
|
||||
Built-in capabilities are part of runtime packages:
|
||||
|
||||
```text
|
||||
core-filesystem
|
||||
core-shell
|
||||
core-git
|
||||
core-project
|
||||
core-artifacts
|
||||
core-context
|
||||
core-permission
|
||||
core-doctor
|
||||
toolchain-cpp
|
||||
debug-basic
|
||||
gui-evidence-basic
|
||||
network-evidence-basic
|
||||
ui-design-assets-basic
|
||||
```
|
||||
|
||||
Only the tools in `tool-registry-v1.md` are required for MVP implementation. Other capability names may exist as placeholders if their tools are not registered yet.
|
||||
|
||||
## 13. Refusal and Disable Conditions
|
||||
|
||||
Disable/block a capability when:
|
||||
|
||||
```text
|
||||
manifest invalid
|
||||
tool schema invalid
|
||||
requested permissions exceed user/project policy
|
||||
source is untrusted and not approved
|
||||
dependency install requires disallowed action
|
||||
capability attempts to bypass ToolRegistry/PermissionEngine
|
||||
capability emits spoofed built-in events
|
||||
capability output contains malicious prompt-injection instructions targeting runtime policy
|
||||
```
|
||||
|
||||
## 14. V1.0.0 Alpha Cut Line
|
||||
|
||||
V1.0.0 Alpha skeleton must implement:
|
||||
|
||||
1. Capability manifest schema.
|
||||
2. Built-in capability registration.
|
||||
3. Namespaced tool validation.
|
||||
4. Dependency declaration and Doctor check path.
|
||||
5. Enable/disable config.
|
||||
6. Permission declaration display.
|
||||
7. ToolRegistry enforcement for capability tools.
|
||||
8. Manifest hash/source recording.
|
||||
9. Rejection of unknown durable capability events.
|
||||
|
||||
Post-MVP:
|
||||
|
||||
```text
|
||||
signed capability packages
|
||||
registry publishing
|
||||
containerized capability execution
|
||||
capability lockfile enforcement
|
||||
capability review UI
|
||||
automatic vulnerability checks
|
||||
```
|
||||
217
AirPlan/docs/architecture/cross-platform-matrix-v1.md
Normal file
217
AirPlan/docs/architecture/cross-platform-matrix-v1.md
Normal file
@@ -0,0 +1,217 @@
|
||||
# AirCoding Cross-Platform Matrix V1
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Canonical platform support matrix for V1.0.0 Alpha skeleton
|
||||
|
||||
This document defines MVP platform targets, feature support levels, toolchain assumptions, and release validation requirements.
|
||||
|
||||
## 1. Support Levels
|
||||
|
||||
```ts
|
||||
type PlatformSupportLevel =
|
||||
| "tier_1"
|
||||
| "tier_2"
|
||||
| "experimental"
|
||||
| "unsupported"
|
||||
```
|
||||
|
||||
| Level | Meaning |
|
||||
|---|---|
|
||||
| `tier_1` | release-blocking support; tested before release |
|
||||
| `tier_2` | intended support; best-effort validation; not always release-blocking |
|
||||
| `experimental` | may work; no compatibility promise |
|
||||
| `unsupported` | explicit non-target |
|
||||
|
||||
## 2. MVP Platform Targets
|
||||
|
||||
| Platform | Support level | Notes |
|
||||
|---|---|---|
|
||||
| Linux x86_64 | tier_1 | primary development and CI target |
|
||||
| Linux arm64 | tier_2 | important for appliance/VibeBox lineage and embedded-style testing |
|
||||
| macOS arm64 | experimental | CLI/runtime likely portable; C++/debug tooling varies |
|
||||
| macOS x86_64 | experimental | lower priority |
|
||||
| Windows native | experimental/post-MVP | path/shell/process/debug semantics need dedicated work |
|
||||
| WSL2 Linux | tier_2 | treated as Linux with Windows filesystem caveats |
|
||||
|
||||
MVP implementation should be Linux-first and avoid hardcoding Linux-only assumptions where simple abstractions are cheap.
|
||||
|
||||
## 3. Runtime Feature Matrix
|
||||
|
||||
| Feature | Linux x86_64 | Linux arm64 | macOS | Windows native | WSL2 |
|
||||
|---|---|---|---|---|---|
|
||||
| Bun runtime | tier_1 | tier_2 | experimental | experimental | tier_2 |
|
||||
| CLI | tier_1 | tier_2 | experimental | experimental | tier_2 |
|
||||
| OpenTUI/Solid TUI | tier_1 | tier_2 | experimental | experimental | tier_2 |
|
||||
| SQLite session DB | tier_1 | tier_2 | experimental | experimental | tier_2 |
|
||||
| NDJSON child processes | tier_1 | tier_2 | experimental | experimental | tier_2 |
|
||||
| ToolRegistry | tier_1 | tier_2 | experimental | experimental | tier_2 |
|
||||
| PermissionEngine path policy | tier_1 | tier_2 | partial | partial | tier_2 |
|
||||
| Doctor read-only | tier_1 | tier_2 | partial | partial | tier_2 |
|
||||
| Doctor fix | tier_1 | tier_2 | limited | limited | tier_2 |
|
||||
|
||||
## 4. Filesystem and Path Matrix
|
||||
|
||||
| Capability | Linux | macOS | Windows native | WSL2 |
|
||||
|---|---|---|---|---|
|
||||
| POSIX paths | yes | yes | no | yes |
|
||||
| symlink realpath | yes | yes | different semantics | yes |
|
||||
| chmod/exec bits | yes | yes | partial | yes |
|
||||
| case sensitivity | usually yes | often no | usually no | depends mount |
|
||||
| project-local `.air` | yes | yes | yes | yes |
|
||||
| git worktree | yes | yes | yes with caveats | yes |
|
||||
| project-outside backup repo | yes | yes | yes with path handling | yes |
|
||||
|
||||
V1 path classifier must be platform-aware and must not rely on string prefix checks before realpath normalization.
|
||||
|
||||
## 5. Shell and Command Matrix
|
||||
|
||||
| Shell behavior | Linux | macOS | Windows native | WSL2 |
|
||||
|---|---|---|---|---|
|
||||
| bash/sh commands | tier_1 | partial | unsupported by default | tier_2 |
|
||||
| process signals | POSIX | POSIX-ish | different | POSIX |
|
||||
| sudo | yes | yes | no | yes |
|
||||
| package manager commands | apt/dnf/pacman/etc | brew optional | winget/choco optional | Linux package mgr |
|
||||
| timeout/kill | tier_1 | partial | different | tier_2 |
|
||||
|
||||
MVP shell tools target non-interactive POSIX shell. Windows native command support is post-MVP.
|
||||
|
||||
## 6. C++ Toolchain Matrix
|
||||
|
||||
| Tool | Linux x86_64 | Linux arm64 | macOS | Windows native | WSL2 |
|
||||
|---|---|---|---|---|---|
|
||||
| CMake | tier_1 | tier_2 | experimental | experimental | tier_2 |
|
||||
| Ninja | tier_1 | tier_2 | experimental | experimental | tier_2 |
|
||||
| Make fallback | tier_1 | tier_2 | experimental | partial | tier_2 |
|
||||
| gcc/clang | tier_1 | tier_2 | clang-focused | MSVC not MVP | tier_2 |
|
||||
| clangd CLI | tier_1 | tier_2 | experimental | experimental | tier_2 |
|
||||
| cppcheck | tier_1 | tier_2 | experimental | experimental | tier_2 |
|
||||
| CTest/GoogleTest | tier_1 | tier_2 | experimental | experimental | tier_2 |
|
||||
| core dumps/backtrace | tier_1 | partial | different | unsupported MVP | tier_2 |
|
||||
|
||||
Windows MSVC-specific workflows are not MVP.
|
||||
|
||||
## 7. GUI, Debug, and Network Evidence Matrix
|
||||
|
||||
| Evidence type | Linux | macOS | Windows native | WSL2 |
|
||||
|---|---|---|---|---|
|
||||
| screenshots | tier_1 with display backend | experimental | experimental | depends WSLg/X |
|
||||
| GUI automation | post-MVP/basic only | post-MVP | post-MVP | depends WSLg/X |
|
||||
| pcaps | requires permissions | requires permissions | different tooling | requires permissions |
|
||||
| core dumps | Linux-first | different | different | Linux-first |
|
||||
| debugger integration | Linux-first | experimental | post-MVP | Linux-first |
|
||||
|
||||
MVP only requires basic GUI screenshot evidence where display backend is available.
|
||||
|
||||
## 8. Provider/Network Matrix
|
||||
|
||||
Provider APIs are platform-independent except for:
|
||||
|
||||
```text
|
||||
TLS/certificate store differences
|
||||
proxy environment variables
|
||||
local model runtimes
|
||||
network firewall/proxy policy
|
||||
```
|
||||
|
||||
Doctor should validate provider reachability without exposing secrets.
|
||||
|
||||
## 9. Distribution Matrix
|
||||
|
||||
MVP distribution:
|
||||
|
||||
| Platform | Distribution |
|
||||
|---|---|
|
||||
| Linux x86_64 | binary tarball |
|
||||
| Linux arm64 | binary tarball, best-effort |
|
||||
| macOS | experimental tarball or manual run |
|
||||
| Windows native | no stable MVP distribution |
|
||||
| WSL2 | use Linux tarball inside WSL |
|
||||
|
||||
Binary tarball contains:
|
||||
|
||||
```text
|
||||
bin/air
|
||||
resources/
|
||||
LICENSE
|
||||
```
|
||||
|
||||
Resources include templates, prompts, themes, HUD presets, Python scripts, and toolchain resources.
|
||||
|
||||
## 10. Platform Detection Contract
|
||||
|
||||
```ts
|
||||
interface PlatformInfo {
|
||||
os: "linux" | "darwin" | "windows" | "unknown"
|
||||
arch: "x64" | "arm64" | "arm" | "unknown"
|
||||
libc?: "glibc" | "musl" | "unknown"
|
||||
shell?: string
|
||||
is_wsl?: boolean
|
||||
display?: {
|
||||
wayland?: boolean
|
||||
x11?: boolean
|
||||
xvfb?: boolean
|
||||
wslg?: boolean
|
||||
}
|
||||
package_managers?: string[]
|
||||
path_case_sensitive?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
Doctor records platform info in doctor report artifacts and session metadata.
|
||||
|
||||
## 11. Release Gate
|
||||
|
||||
Before an AirCoding MVP release:
|
||||
|
||||
Tier 1 Linux x86_64 must pass:
|
||||
|
||||
```text
|
||||
unit tests
|
||||
integration fixture tests
|
||||
real LLM E2E release test
|
||||
project init smoke
|
||||
C++ configure/build/test flow
|
||||
SQLite recovery smoke
|
||||
child agent IPC smoke
|
||||
TUI startup smoke
|
||||
artifact/event persistence smoke
|
||||
```
|
||||
|
||||
Linux arm64 best-effort gate:
|
||||
|
||||
```text
|
||||
runtime startup
|
||||
doctor read-only
|
||||
SQLite/session creation
|
||||
basic shell/tool execution
|
||||
C++ toolchain detection if available
|
||||
```
|
||||
|
||||
Experimental platforms may have smoke checks but do not block MVP release unless declared for a specific release.
|
||||
|
||||
## 12. VibeBox Relationship
|
||||
|
||||
VibeBox targets ARM Linux appliance behavior and has its own downstream baseline. AirCoding mainline should keep Linux arm64 viable, but VibeBox-specific Electron packaging/test requirements do not become AirCoding mainline MVP release blockers.
|
||||
|
||||
## 13. V1.0.0 Alpha Cut Line
|
||||
|
||||
V1.0.0 Alpha skeleton must implement:
|
||||
|
||||
1. Platform detection.
|
||||
2. Linux x86_64 tier-1 path/shell/process behavior.
|
||||
3. Linux arm64 best-effort packaging/runtime checks.
|
||||
4. WSL detection and warnings.
|
||||
5. Platform-aware path classifier.
|
||||
6. Doctor platform report.
|
||||
7. Release gate script definitions for tier 1.
|
||||
|
||||
Post-MVP:
|
||||
|
||||
```text
|
||||
Windows native shell/process support
|
||||
macOS notarized distribution
|
||||
containerized test matrix
|
||||
MSVC toolchain profile
|
||||
Wayland/X11/Windows/macOS GUI automation adapters
|
||||
platform-specific sandboxing
|
||||
```
|
||||
680
AirPlan/docs/architecture/db-schema-v1.md
Normal file
680
AirPlan/docs/architecture/db-schema-v1.md
Normal file
@@ -0,0 +1,680 @@
|
||||
# AirCoding Session DB Schema V1
|
||||
|
||||
Date: 2026-05-26
|
||||
Status: Canonical schema baseline for V1.0.0 Alpha skeleton
|
||||
|
||||
This document defines the first implementation-facing SQLite schema for per-session state.
|
||||
|
||||
Session DB path:
|
||||
|
||||
```text
|
||||
<project>/.air/local/sessions/<session-id>/session.db
|
||||
```
|
||||
|
||||
Project-level DBs remain outside this session schema:
|
||||
|
||||
```text
|
||||
<project>/.air/local/debug-records.db
|
||||
<project>/.air/local/learned-memory.db
|
||||
```
|
||||
|
||||
## 1. SQLite Runtime Settings
|
||||
|
||||
```sql
|
||||
PRAGMA journal_mode = WAL;
|
||||
PRAGMA synchronous = NORMAL;
|
||||
PRAGMA foreign_keys = OFF;
|
||||
```
|
||||
|
||||
Rationale:
|
||||
|
||||
- WAL supports concurrent read/write patterns needed by runtime and TUI projection.
|
||||
- `NORMAL` is sufficient for local session state and faster than `FULL`.
|
||||
- Foreign keys are disabled in MVP to reduce migration/recovery complexity. Application-level consistency checks handle references. This can be revisited after schema stabilizes.
|
||||
|
||||
Transaction rules:
|
||||
|
||||
- A durable event insert and its corresponding domain table update must be in the same transaction.
|
||||
- Artifact file writes use temp file → atomic rename → DB record.
|
||||
- `ui_state` is flushed periodically and on normal exit.
|
||||
|
||||
## 2. schema_meta
|
||||
|
||||
```sql
|
||||
CREATE TABLE schema_meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
Initial keys:
|
||||
|
||||
```text
|
||||
schema_version = 1
|
||||
created_by = aircoding
|
||||
created_at = <ISO time>
|
||||
aircoding_version_created = <version>
|
||||
aircoding_version_last_opened = <version>
|
||||
```
|
||||
|
||||
## 3. sessions
|
||||
|
||||
```sql
|
||||
CREATE TABLE sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
project_id TEXT NOT NULL,
|
||||
project_root TEXT NOT NULL,
|
||||
title TEXT,
|
||||
status TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
exited_at TEXT,
|
||||
model_provider_id TEXT,
|
||||
model_id TEXT,
|
||||
metadata_json TEXT
|
||||
);
|
||||
```
|
||||
|
||||
Status values:
|
||||
|
||||
```text
|
||||
active | archived | deleted
|
||||
```
|
||||
|
||||
## 4. messages
|
||||
|
||||
```sql
|
||||
CREATE TABLE messages (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
canonical_format TEXT NOT NULL,
|
||||
content_json TEXT NOT NULL,
|
||||
parent_message_id TEXT,
|
||||
route_json TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
token_estimate INTEGER,
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_messages_session_created
|
||||
ON messages(session_id, created_at);
|
||||
```
|
||||
|
||||
`canonical_format` is `anthropic` in V1.
|
||||
|
||||
## 5. message_drafts
|
||||
|
||||
```sql
|
||||
CREATE TABLE message_drafts (
|
||||
message_id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
canonical_format TEXT NOT NULL,
|
||||
partial_content_json TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_drafts_session_status
|
||||
ON message_drafts(session_id, status);
|
||||
```
|
||||
|
||||
Drafts are deleted after the completed message is written to `messages`.
|
||||
|
||||
Status values:
|
||||
|
||||
```text
|
||||
streaming | interrupted | error
|
||||
```
|
||||
|
||||
## 6. events
|
||||
|
||||
```sql
|
||||
CREATE TABLE events (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
timestamp TEXT NOT NULL,
|
||||
|
||||
source_kind TEXT NOT NULL,
|
||||
source_id TEXT,
|
||||
agent_type TEXT,
|
||||
|
||||
task_id TEXT,
|
||||
agent_id TEXT,
|
||||
tool_run_id TEXT,
|
||||
command_run_id TEXT,
|
||||
|
||||
route_json TEXT NOT NULL,
|
||||
route_text TEXT NOT NULL,
|
||||
|
||||
payload_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX idx_events_session_type_time
|
||||
ON events(session_id, type, timestamp);
|
||||
|
||||
CREATE INDEX idx_events_task_time
|
||||
ON events(task_id, timestamp);
|
||||
|
||||
CREATE INDEX idx_events_agent_time
|
||||
ON events(agent_id, timestamp);
|
||||
|
||||
CREATE INDEX idx_events_route_text
|
||||
ON events(route_text);
|
||||
```
|
||||
|
||||
## 7. tasks
|
||||
|
||||
```sql
|
||||
CREATE TABLE tasks (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
|
||||
task_spec_json TEXT NOT NULL,
|
||||
worker_result_json TEXT,
|
||||
|
||||
assigned_agent_id TEXT,
|
||||
workspace_id TEXT,
|
||||
|
||||
retry_count INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
created_at TEXT NOT NULL,
|
||||
started_at TEXT,
|
||||
completed_at TEXT,
|
||||
heartbeat_at TEXT,
|
||||
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_tasks_session_status
|
||||
ON tasks(session_id, status);
|
||||
```
|
||||
|
||||
Task status values:
|
||||
|
||||
```text
|
||||
pending | running | completed | failed | blocked | cancelled | interrupted
|
||||
```
|
||||
|
||||
## 8. task_dependencies
|
||||
|
||||
```sql
|
||||
CREATE TABLE task_dependencies (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
task_id TEXT NOT NULL,
|
||||
depends_on_task_id TEXT NOT NULL,
|
||||
dependency_type TEXT NOT NULL,
|
||||
reason TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX idx_task_deps_task
|
||||
ON task_dependencies(task_id);
|
||||
|
||||
CREATE INDEX idx_task_deps_depends_on
|
||||
ON task_dependencies(depends_on_task_id);
|
||||
|
||||
CREATE INDEX idx_task_deps_session_type
|
||||
ON task_dependencies(session_id, dependency_type);
|
||||
```
|
||||
|
||||
Dependency types:
|
||||
|
||||
```text
|
||||
hard | soft | conflict | serialization
|
||||
```
|
||||
|
||||
## 9. task_attempts
|
||||
|
||||
```sql
|
||||
CREATE TABLE task_attempts (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
task_id TEXT NOT NULL,
|
||||
attempt_index INTEGER NOT NULL,
|
||||
|
||||
agent_id TEXT,
|
||||
status TEXT NOT NULL,
|
||||
|
||||
failure_signature TEXT,
|
||||
failure_summary TEXT,
|
||||
|
||||
started_at TEXT NOT NULL,
|
||||
completed_at TEXT,
|
||||
|
||||
worker_result_json TEXT,
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_task_attempts_task
|
||||
ON task_attempts(task_id, attempt_index);
|
||||
|
||||
CREATE INDEX idx_task_attempts_failure_signature
|
||||
ON task_attempts(failure_signature);
|
||||
```
|
||||
|
||||
## 10. agents
|
||||
|
||||
```sql
|
||||
CREATE TABLE agents (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
|
||||
pid INTEGER,
|
||||
task_id TEXT,
|
||||
|
||||
model_provider_id TEXT,
|
||||
model_id TEXT,
|
||||
|
||||
started_at TEXT NOT NULL,
|
||||
completed_at TEXT,
|
||||
last_heartbeat_at TEXT,
|
||||
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_agents_session_status
|
||||
ON agents(session_id, status);
|
||||
|
||||
CREATE INDEX idx_agents_task
|
||||
ON agents(task_id);
|
||||
```
|
||||
|
||||
Agent status values:
|
||||
|
||||
```text
|
||||
starting | running | completed | failed | lost | cancelled
|
||||
```
|
||||
|
||||
## 11. tool_runs
|
||||
|
||||
```sql
|
||||
CREATE TABLE tool_runs (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
|
||||
task_id TEXT,
|
||||
agent_id TEXT,
|
||||
origin_message_id TEXT,
|
||||
|
||||
tool_name TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
|
||||
input_json TEXT NOT NULL,
|
||||
output_json TEXT,
|
||||
error_json TEXT,
|
||||
|
||||
started_at TEXT NOT NULL,
|
||||
completed_at TEXT,
|
||||
duration_ms INTEGER,
|
||||
|
||||
artifacts_json TEXT,
|
||||
evidence_refs_json TEXT,
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_tool_runs_origin_message
|
||||
ON tool_runs(origin_message_id);
|
||||
|
||||
CREATE INDEX idx_tool_runs_session_time
|
||||
ON tool_runs(session_id, started_at);
|
||||
|
||||
CREATE INDEX idx_tool_runs_task_time
|
||||
ON tool_runs(task_id, started_at);
|
||||
|
||||
CREATE INDEX idx_tool_runs_agent_time
|
||||
ON tool_runs(agent_id, started_at);
|
||||
```
|
||||
|
||||
Status values:
|
||||
|
||||
```text
|
||||
running | ok | error | cancelled
|
||||
```
|
||||
|
||||
## 12. command_runs
|
||||
|
||||
```sql
|
||||
CREATE TABLE command_runs (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
|
||||
task_id TEXT,
|
||||
agent_id TEXT,
|
||||
origin_message_id TEXT,
|
||||
tool_run_id TEXT,
|
||||
|
||||
command TEXT NOT NULL,
|
||||
cwd TEXT NOT NULL,
|
||||
|
||||
exit_code INTEGER,
|
||||
|
||||
stdout_artifact_id TEXT,
|
||||
stderr_artifact_id TEXT,
|
||||
combined_artifact_id TEXT,
|
||||
|
||||
started_at TEXT NOT NULL,
|
||||
completed_at TEXT,
|
||||
duration_ms INTEGER,
|
||||
|
||||
parsed_diagnostics_json TEXT,
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_command_runs_origin_message
|
||||
ON command_runs(origin_message_id);
|
||||
|
||||
CREATE INDEX idx_command_runs_session_time
|
||||
ON command_runs(session_id, started_at);
|
||||
|
||||
CREATE INDEX idx_command_runs_task_time
|
||||
ON command_runs(task_id, started_at);
|
||||
|
||||
CREATE INDEX idx_command_runs_agent_time
|
||||
ON command_runs(agent_id, started_at);
|
||||
```
|
||||
|
||||
## 13. artifacts
|
||||
|
||||
```sql
|
||||
CREATE TABLE artifacts (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
|
||||
uri TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
original_name TEXT,
|
||||
|
||||
size_bytes INTEGER,
|
||||
sha256 TEXT,
|
||||
|
||||
task_id TEXT,
|
||||
agent_id TEXT,
|
||||
tool_run_id TEXT,
|
||||
command_run_id TEXT,
|
||||
|
||||
associated_entity_type TEXT,
|
||||
associated_entity_id TEXT,
|
||||
|
||||
created_at TEXT NOT NULL,
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_artifacts_session_type_time
|
||||
ON artifacts(session_id, type, created_at);
|
||||
|
||||
CREATE INDEX idx_artifacts_task
|
||||
ON artifacts(task_id);
|
||||
|
||||
CREATE INDEX idx_artifacts_agent
|
||||
ON artifacts(agent_id);
|
||||
|
||||
CREATE INDEX idx_artifacts_tool_run
|
||||
ON artifacts(tool_run_id);
|
||||
|
||||
CREATE INDEX idx_artifacts_command_run
|
||||
ON artifacts(command_run_id);
|
||||
```
|
||||
|
||||
## 14. diagnostics
|
||||
|
||||
```sql
|
||||
CREATE TABLE diagnostics (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
|
||||
task_id TEXT,
|
||||
agent_id TEXT,
|
||||
command_run_id TEXT,
|
||||
artifact_id TEXT,
|
||||
|
||||
language TEXT,
|
||||
toolchain TEXT,
|
||||
severity TEXT,
|
||||
|
||||
file TEXT,
|
||||
line INTEGER,
|
||||
column INTEGER,
|
||||
code TEXT,
|
||||
|
||||
message TEXT NOT NULL,
|
||||
semantic_signature TEXT NOT NULL,
|
||||
|
||||
created_at TEXT NOT NULL,
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_diagnostics_signature
|
||||
ON diagnostics(semantic_signature);
|
||||
|
||||
CREATE INDEX idx_diagnostics_file
|
||||
ON diagnostics(file);
|
||||
|
||||
CREATE INDEX idx_diagnostics_command
|
||||
ON diagnostics(command_run_id);
|
||||
|
||||
CREATE INDEX idx_diagnostics_task
|
||||
ON diagnostics(task_id);
|
||||
```
|
||||
|
||||
## 15. evidence_refs
|
||||
|
||||
```sql
|
||||
CREATE TABLE evidence_refs (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
|
||||
task_id TEXT,
|
||||
agent_id TEXT,
|
||||
tool_run_id TEXT,
|
||||
command_run_id TEXT,
|
||||
artifact_id TEXT,
|
||||
diagnostic_id TEXT,
|
||||
message_id TEXT,
|
||||
|
||||
kind TEXT NOT NULL,
|
||||
ref TEXT NOT NULL,
|
||||
location_json TEXT,
|
||||
claim TEXT NOT NULL,
|
||||
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX idx_evidence_task
|
||||
ON evidence_refs(task_id);
|
||||
|
||||
CREATE INDEX idx_evidence_artifact
|
||||
ON evidence_refs(artifact_id);
|
||||
|
||||
CREATE INDEX idx_evidence_diagnostic
|
||||
ON evidence_refs(diagnostic_id);
|
||||
```
|
||||
|
||||
## 16. workspaces
|
||||
|
||||
```sql
|
||||
CREATE TABLE workspaces (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
|
||||
task_id TEXT,
|
||||
agent_id TEXT,
|
||||
|
||||
path TEXT NOT NULL,
|
||||
strategy TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
|
||||
base_ref TEXT,
|
||||
branch_name TEXT,
|
||||
|
||||
created_at TEXT NOT NULL,
|
||||
merged_at TEXT,
|
||||
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_workspaces_task
|
||||
ON workspaces(task_id);
|
||||
|
||||
CREATE INDEX idx_workspaces_status
|
||||
ON workspaces(session_id, status);
|
||||
```
|
||||
|
||||
Workspace strategy values:
|
||||
|
||||
```text
|
||||
main | worktree | isolated_copy
|
||||
```
|
||||
|
||||
Workspace status values:
|
||||
|
||||
```text
|
||||
active | merged | conflicted | abandoned | cleaned
|
||||
```
|
||||
|
||||
## 17. summaries
|
||||
|
||||
```sql
|
||||
CREATE TABLE summaries (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
|
||||
type TEXT NOT NULL,
|
||||
range_start_message_id TEXT,
|
||||
range_end_message_id TEXT,
|
||||
|
||||
content_json TEXT NOT NULL,
|
||||
|
||||
created_at TEXT NOT NULL,
|
||||
metadata_json TEXT
|
||||
);
|
||||
```
|
||||
|
||||
## 18. ui_state
|
||||
|
||||
```sql
|
||||
CREATE TABLE ui_state (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
value_json TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX idx_ui_state_session_scope_key
|
||||
ON ui_state(session_id, scope, key);
|
||||
```
|
||||
|
||||
`ui_state` is not a source of truth for runtime state. It stores route, active panel, layout, scroll, collapse state, selected tab, and HUD preset.
|
||||
|
||||
## 19. V1 Summary
|
||||
|
||||
Frozen decisions:
|
||||
|
||||
1. Session DB is project-local and per-session.
|
||||
2. WAL + synchronous NORMAL + foreign_keys OFF.
|
||||
3. No `message_parts` source-of-truth table in V1.0.0 Alpha.
|
||||
4. Canonical messages are Anthropic content JSON.
|
||||
5. Draft messages exist only during streaming/incomplete assistant output.
|
||||
6. Domain tables are scheduling/recovery/query source of truth.
|
||||
7. JSON columns preserve full object fidelity; frequently queried relationships are extracted into columns and indexes.
|
||||
8. Durable event + domain update must be transactional.
|
||||
9. Artifact files are written temp → rename → DB record.
|
||||
10. UI state is flushed periodically and on normal exit.
|
||||
|
||||
## 20. Project-Level DBs
|
||||
|
||||
Two project-level databases live under `<project>/.air/local/`:
|
||||
|
||||
### 20.1 debug-records.db
|
||||
|
||||
```sql
|
||||
PRAGMA journal_mode = WAL;
|
||||
PRAGMA synchronous = NORMAL;
|
||||
PRAGMA foreign_keys = OFF;
|
||||
|
||||
CREATE TABLE debug_records (
|
||||
id TEXT PRIMARY KEY,
|
||||
task_id TEXT,
|
||||
failure_signature TEXT NOT NULL,
|
||||
summary TEXT NOT NULL,
|
||||
root_cause TEXT,
|
||||
fix_ref TEXT,
|
||||
evidence_json TEXT,
|
||||
verification_json TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_debug_records_signature
|
||||
ON debug_records(failure_signature);
|
||||
|
||||
CREATE INDEX idx_debug_records_task
|
||||
ON debug_records(task_id);
|
||||
```
|
||||
|
||||
### 20.2 learned-memory.db
|
||||
|
||||
```sql
|
||||
PRAGMA journal_mode = WAL;
|
||||
PRAGMA synchronous = NORMAL;
|
||||
PRAGMA foreign_keys = OFF;
|
||||
|
||||
CREATE TABLE learned_memories (
|
||||
id TEXT PRIMARY KEY,
|
||||
memory_type TEXT NOT NULL,
|
||||
summary TEXT NOT NULL,
|
||||
content TEXT,
|
||||
source_entity_type TEXT,
|
||||
source_entity_id TEXT,
|
||||
status TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
metadata_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX idx_learned_memories_type
|
||||
ON learned_memories(memory_type);
|
||||
|
||||
CREATE INDEX idx_learned_memories_status
|
||||
ON learned_memories(status);
|
||||
```
|
||||
|
||||
## 21. Closed Enum Inventory
|
||||
|
||||
The following TEXT columns use closed value sets. Implementations must validate on insert/update.
|
||||
|
||||
| Table | Column | Valid values |
|
||||
|---|---|---|
|
||||
| `sessions` | `status` | `active`, `archived`, `deleted` |
|
||||
| `messages` | `role` | `user`, `assistant`, `system`, `tool` |
|
||||
| `messages` | `canonical_format` | `anthropic` |
|
||||
| `tasks` | `type` | `execute`, `review`, `debug`, `compact`, `mine_experience`, `docs` |
|
||||
| `tasks` | `status` | `pending`, `running`, `completed`, `failed`, `blocked`, `cancelled`, `interrupted` |
|
||||
| `task_dependencies` | `dependency_type` | `hard`, `soft`, `conflict`, `serialization` |
|
||||
| `task_attempts` | `status` | `pending`, `running`, `completed`, `failed`, `cancelled` |
|
||||
| `agents` | `status` | `starting`, `running`, `completed`, `failed`, `lost`, `cancelled` |
|
||||
| `tool_runs` | `status` | `running`, `ok`, `error`, `cancelled` |
|
||||
| `artifacts` | `type` | `log`, `diff`, `screenshot`, `pcap`, `report`, `diagnostic`, `bundle`, `other` |
|
||||
| `diagnostics` | `severity` | `error`, `warning`, `info`, `hint` |
|
||||
| `evidence_refs` | `kind` | `build_output`, `test_output`, `log`, `screenshot`, `diff`, `metric`, `other` |
|
||||
| `workspaces` | `strategy` | `main`, `worktree`, `isolated_copy` |
|
||||
| `workspaces` | `status` | `active`, `merged`, `conflicted`, `abandoned`, `cleaned` |
|
||||
| `summaries` | `type` | `compaction`, `checkpoint`, `review`, `other` |
|
||||
| `message_drafts` | `status` | `streaming`, `interrupted`, `error` |
|
||||
| `learned_memories` | `memory_type` | `project_rule`, `toolchain_rule`, `skill_update`, `debug_experience` |
|
||||
| `learned_memories` | `status` | `candidate`, `promoted`, `archived`, `rejected` |
|
||||
134
AirPlan/docs/architecture/decisions-round-1.md
Normal file
134
AirPlan/docs/architecture/decisions-round-1.md
Normal file
@@ -0,0 +1,134 @@
|
||||
# Architecture Decisions — Round 1
|
||||
|
||||
Date: 2026-05-25
|
||||
Source: idea.md discussion, questions 1–18
|
||||
|
||||
## D-001: Bun as JS Runtime
|
||||
|
||||
- **Decision**: Bun.
|
||||
- **Why**: Both OpenCode and Claude Code use Bun; built-in SQLite removes native addon dependency; native TSX support simplifies build config; C++ modules communicate via subprocess, not native addons.
|
||||
- **Distribution**: Bundle Bun runtime with AirCoding.
|
||||
|
||||
## D-002: @opentui/solid as TUI Framework
|
||||
|
||||
- **Decision**: `@opentui/solid` (MIT licensed, standalone project, not coupled to OpenCode).
|
||||
- **Why**: OpenTUI is an independent library consumed by OpenCode as a regular npm dependency. The TUI rendering layer is cleanly separated from OpenCode's business logic. Reference OpenCode's TUI component patterns for interaction design.
|
||||
- **Reuse strategy**: Direct npm dependency on `@opentui/solid @opentui/core @opentui/keymap`. AirCoding TUI components reference OpenCode patterns but are independently implemented.
|
||||
|
||||
## D-003: Bun Monorepo
|
||||
|
||||
- **Decision**: Monorepo with Bun workspaces + Turborepo.
|
||||
- **MVP packages**:
|
||||
- `packages/tui` — AirCoding TUI components on top of `@opentui/solid`
|
||||
- `packages/runtime` — Agent Loop, Session, Scheduler, Tool Registry, EventBus
|
||||
- `packages/llm` — Provider/Model abstraction (reference `@opencode-ai/llm`, but may fork/adapt)
|
||||
- `packages/toolchain` — C++ BuildTool, DiagnosticParser, TestRunner
|
||||
- `packages/cli` — Entry point, assembles all packages
|
||||
- **Later**: Plugin SDK, debug knowledge, Python worker bridge.
|
||||
|
||||
## D-004: Python as Subprocess-Only Tooling
|
||||
|
||||
- **Decision**: Python workers are called via `Bun.spawn` with JSON-over-stdio. No long-lived Python server. No bundled Python environment.
|
||||
- **Scope**: Python only wraps existing C++ toolchain scripts and Python-specific libraries. Experience mining, context assembly, and memory management stay in TS runtime.
|
||||
- **Re-evaluated from idea.md**: idea.md assigned Python for Hermes-style learning and AirContext compression, but these are LLM + text + SQLite operations that Bun/TS handles natively. Keeping them in TS avoids unnecessary language bridging.
|
||||
|
||||
## D-005: Event-Driven Agent Architecture
|
||||
|
||||
- **Decision**: Event-driven. Main Agent subscribes to EventBus for agent/task/tool events and renders progress to TUI/HUD.
|
||||
- **Main Agent state machine** (see `AirPlan/docs/architecture/main-agent-state-machine.md`):
|
||||
- IDLE → CLASSIFYING → DELEGATING → CONFIRMING → EXECUTING → SUMMARIZING → IDLE
|
||||
- INTERRUPTING for mid-execution user requirement changes (classified via LLM)
|
||||
- Error handling: Main Agent handles what it can, escalates to user only when necessary
|
||||
- **Key constraint**: Main Agent must remain idle-ready for user intervention. Background tasks (ExperienceMiner, DebugKnowledge indexing) are dispatched to sub-agents.
|
||||
|
||||
## D-006: Sub-Agent Loops Are Independent
|
||||
|
||||
- **Decision**: Executor, Reviewer, and Debugger each have their own agent loop implementation. Not a shared generic loop engine.
|
||||
- **Executor loop**: LOADING → THINKING → ACTING → OBSERVING → (loop with debugging sub-loop on failure) → FINALIZING
|
||||
- **Reviewer loop**: LOADING → REVIEWING → DECIDING (approved / changes_requested / blocked)
|
||||
- **Debugger loop**: GATHERING → ANALYZING → FIXING → (RECORDING or ESCALATING)
|
||||
- **Sub-agent execution quality**: Claude Code is the behavioral benchmark (read-first, small edits, verify before return, follow Project Rules).
|
||||
|
||||
## D-007: Independent Processes for Sub-Agents
|
||||
|
||||
- **Decision**: Each Executor/Reviewer/Debugger is an independent Bun process spawned by Scheduler. IPC via stdio + JSON (same mechanism as Python workers).
|
||||
- **Why**: Crash isolation, context isolation, natural worktree support. Single-process approach excluded due to context explosion and lack of fault isolation.
|
||||
- **Communication**: Scheduler passes TaskSpec (worktree path, tool set, permission level) on spawn; sub-agent returns structured WorkerResult JSON on completion.
|
||||
|
||||
## D-008: Push Heartbeat + Soft/Hard Timeout
|
||||
|
||||
- **Decision**: Sub-agents push `AgentHeartbeat` events (status, turn count, tokens) every N seconds. Scheduler subscribes and detects stalls.
|
||||
- **Heartbeat**: Push model. Sub-agent proactively reports state.
|
||||
- **Timeout**: Hybrid. Hard timeout kills on expiration. Soft timeout warns and allows extension requests (sub-agent can justify need for more time). Scheduler decides per-task.
|
||||
- **Loop detection**: Same error signature appearing N+ times triggers escalation to Main Agent (not auto-kill).
|
||||
|
||||
## D-009: Per-Session SQLite with Anthropic-Native Storage
|
||||
|
||||
- **Decision**:
|
||||
- `~/.air/sessions/<session-id>/session.db` per session
|
||||
- `~/.air/projects/<project-id>/debug-records.db` cross-session
|
||||
- `~/.air/projects/<project-id>/learned-memory.db` cross-session
|
||||
- **Message format**: Anthropic-native content blocks (TextBlock, ThinkingBlock, ToolUseBlock, ToolResultBlock), following Claude Code's approach.
|
||||
- **Provider switching**: Same-provider switching (e.g., Opus → Sonnet) is zero-cost. Cross-provider switching converts at API boundary (Anthropic format → target provider format → response → back to Anthropic format for storage).
|
||||
- **Event persistence**:
|
||||
- High-frequency events (TokenDelta, StdoutChunk) → EventBus only, not persisted
|
||||
- Durable events (TaskCompleted, ToolRunCompleted) → SQLite, synchronous write on main thread
|
||||
- WAL mode for concurrent read/write
|
||||
|
||||
## D-010: Full Context Dump on Session Exit
|
||||
|
||||
- **Decision**: On session exit, dump complete context to session storage. On resume, load from full dump, not reconstruct from summaries.
|
||||
- **Recovery**:
|
||||
- Compaction is internal projection optimization, not data removal
|
||||
- Structured summaries serve as index for fast historical lookup
|
||||
- Scheduler rebuilds task queue from AgentTask table; running tasks judged by heartbeat timestamp
|
||||
- User sees full conversation history transparently
|
||||
|
||||
## D-011: Build System Auto-Detection
|
||||
|
||||
- **Priority**: CMake (built-in) > Meson/Bazel/XMake (capability plugin) > Makefile/.sln
|
||||
- **Conflict handling**: When multiple build system files exist (e.g., CMakeLists.txt + meson.build), ask user to choose.
|
||||
- **Generator**: Ninja first, fall back to Make if Ninja fails.
|
||||
- **Config failure**: BuildTool built-in logic attempts fix first (install missing deps, adjust CMake args); if unresolved, hand off to Debugger.
|
||||
|
||||
## D-012: compile_commands.json — On-Demand Generation, No Caching
|
||||
|
||||
- **Decision**: Detect and generate `compile_commands.json` on demand via `cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON`. No persistence/caching between sessions.
|
||||
|
||||
## D-013: clangd CLI Mode for MVP
|
||||
|
||||
- **Decision**: CLI mode (`clangd --check=<file>` or equivalent) for MVP. Spawn on tool call, exit on completion. LSP daemon mode deferred to later phase if CLI latency proves unacceptable.
|
||||
|
||||
## D-014: LLM-Based Diagnostic Parsing
|
||||
|
||||
- **Decision**: All compiler/linker output parsed via LLM (not regex). LLM extracts structured `Diagnostic` records and generates semantic error signatures.
|
||||
- **Error signature**: LLM computes semantic signature that normalizes across GCC/Clang/MSVC wording differences (e.g., "use of undeclared identifier" and "was not declared in this scope" map to same signature).
|
||||
- **Linker errors**: Separately categorized from compiler diagnostics.
|
||||
|
||||
## D-015: LLM-Driven Project Initialization — Loose Acceptance
|
||||
|
||||
- **Decision**: Scanner collects facts → LLM infers `ProjectProfile` → loose schema acceptance (missing fields marked as `unknown`, not rejected) → user confirms/corrects → incremental field update with "may affect related inferences" hint.
|
||||
- **No LLM retry loop** on schema mismatch. User correction is single-pass.
|
||||
|
||||
## D-016: Classification by LLM
|
||||
|
||||
- **Decision**: Main Agent uses LLM to classify user messages (chat, direct-mode, simple-task, needs-planning).
|
||||
|
||||
## D-017: Confirmation Gating
|
||||
|
||||
- **Decision**: Implementation-level changes that don't affect interfaces or architecture → silently proceed to EXECUTING. Architecture-level changes → Arc assessment required. Low permission: user confirms. High permission: auto-proceed with results displayed to user for immediate intervention.
|
||||
|
||||
## D-018: Interruption via LLM Intent Detection
|
||||
|
||||
- **Decision**: User interruption during execution detected via LLM intent classification, not Ctrl+C (ineffective with multi-process architecture).
|
||||
|
||||
## D-019: Scheduler — Full Dependency Handling
|
||||
|
||||
- **Decision**: Scheduler handles both hard dependencies (topological sort) and soft dependencies (optimization hints). Write-area conflict detection: different areas → parallel; same area but different code blocks → git worktree parallel then merge; same area, same code block → serial.
|
||||
- **Concurrency**: Dynamic, API-rate-limit-aware, machine-resource-aware.
|
||||
- **Failure**: Retry 3-5 times. Solvable failures block hard dependents only. Unsolvable failures (e.g., kernel limitation) go back to Architecture Designer. Repeated failures after max retries → Main Agent evaluates (silent resolution vs. user escalation).
|
||||
- **Model selection**: Scheduler decides whether to force a specific model per task or let Executor choose.
|
||||
|
||||
## D-020: Memory System — Claude Code Style
|
||||
|
||||
- **Decision**: Claude Code's persistent memory system (MEMORY.md + frontmatter + typed layers) is the primary reference for memory design, alongside Hermes-style experience mining as a candidate layer.
|
||||
96
AirPlan/docs/architecture/decisions-round-2.md
Normal file
96
AirPlan/docs/architecture/decisions-round-2.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# Architecture Decisions — Round 2
|
||||
|
||||
Date: 2026-05-26
|
||||
Source: idea.md discussion, questions 19–30
|
||||
|
||||
## D-021: Project Model Version Migration
|
||||
|
||||
- **Decision**: Backup before migrate, user confirmation required.
|
||||
- **Mechanism**: On opening a project with old-version `project.json`, auto-detect and prompt user. Backup to `~/.air/projects/<id>/backups/` before migration. Migration failure → rollback to backup, notify user.
|
||||
|
||||
## D-022: Scanner — Full Directory Tree, No Exclusions
|
||||
|
||||
- **Decision**: Scanner collects complete directory tree (file system metadata only — paths, extensions, file types), no recursion depth limit, no directory exclusions.
|
||||
- **Why**: Directory tree traversal is fast (kernel inode walk), and the full tree provides useful structural information (e.g., detecting referenced components). File content is NOT read during scanning.
|
||||
- **Timeout**: 15 seconds hard timeout as safety net. On timeout, return partial results with `incomplete` marker.
|
||||
- **Update strategy**: First scan is full. Subsequent scans are incremental (mtime diff). On re-open, load `project.json` + quick check for top-level directory changes; trigger incremental scan only if changes detected.
|
||||
- **Informed by**: Claude Code's zero-pre-scan approach (agentic search, no indexing), OpenCode's Tree-sitter AST + LLM hybrid.
|
||||
|
||||
## D-023: Project Rules Format — Markdown + Frontmatter
|
||||
|
||||
- **Decision**: Claude Code style — Markdown body with YAML frontmatter for structured metadata. Human-readable, git diff friendly, LLM natively understands.
|
||||
- **Storage**: `~/.air/projects/<id>/project-rules.md` (project-authoritative). Export via `air memory export --project-rules AIR.md`.
|
||||
- **Informed by**: Claude Code's CLAUDE.md format with frontmatter metadata.
|
||||
|
||||
## D-024: ExperienceMiner — Mid-Session Trigger + Curator + Self-Patch
|
||||
|
||||
- **Decision**:
|
||||
- **Triggers**: DebugRecord produced + session end + N-turn interval (Hermes-style Nudge Engine counter, ~10 turns or 10 tool calls). Background sub-agent, never blocks Main Agent.
|
||||
- **Scope**: Full extraction, no range limits. LLM decides what's worth saving.
|
||||
- **Validation**: Non-debug experiences use occurrence count (N=3) as threshold for promotion prompt. Debug experiences use evidence (build/test pass) as confidence; no numeric score needed.
|
||||
- **Deduplication**: Curator Daemon runs periodically (weekly), identifies overlapping skills, suggests merges, marks stale entries, archives unused ones.
|
||||
- **Self-patch**: When agent finds existing skill/rules wrong during execution, forwards to ExperienceMiner to patch.
|
||||
- **Data format**: SKILL.md (YAML frontmatter + Markdown body) under `~/.air/skills/`. Memories in `~/.air/projects/<id>/learned-memory.db`.
|
||||
- **Informed by**: Hermes Agent's Nudge Engine, Curator Daemon, self-patching mechanism, and SKILL.md format.
|
||||
|
||||
## D-025: Context Compaction — Rule-File Driven, Copy-on-Write, Async
|
||||
|
||||
- **Decision**:
|
||||
- **Trigger**: 70% of context window capacity.
|
||||
- **Strategy**: Rule-file driven with three-tier inheritance (system default → user template at `~/.air/compaction-rules.yaml` → project override at `.air/compaction-rules.yaml`). System default template ensures projects without custom rules work normally. Editing user template affects all future new projects.
|
||||
- **Mechanism**: Copy-on-Write. On trigger, snapshot current messages 1-N. Compression runs asynchronously (independent Compactor sub-agent). New messages continue appending to original chain. On completion, a compaction marker is inserted between the compressed summary and post-snapshot messages. LLM sees: summary + marker + new messages. Original messages preserved for explicit LLM backtracking.
|
||||
- **Executor**: Independent Compactor sub-agent (not ContextAssembler, not Main Agent).
|
||||
|
||||
## D-026: Permission — Symlink Physical Resolution
|
||||
|
||||
- **Decision**: Symlinks resolved to physical path (follow `realpath`). This prevents project escape via symlink chains.
|
||||
|
||||
## D-027: Permission — .git/ Write Protection
|
||||
|
||||
- **Decision**: `.git/` directory write-protected by default (requires user confirmation). Can be overridden in `.air/permissions.yaml` project settings.
|
||||
|
||||
## D-028: Permission — Build Directory Unrestricted
|
||||
|
||||
- **Decision**: Build directories (`build/`, `out/`, etc.) have no special restrictions. C++ packaging workflows require agent ability to manually organize runtime libraries (.so/.dll deployment, rpath, resource file organization), so build directory access must be unrestricted.
|
||||
|
||||
## D-029: Permission — `~/.air/` System-Managed
|
||||
|
||||
- **Decision**: `~/.air/` and all contents are managed by AirCoding internally. PermissionEngine does not check AirCoding's own internal operations.
|
||||
|
||||
## D-030: Backup — Git-Based Repo
|
||||
|
||||
- **Decision**: Project-external file backup is a git repository at `~/.air/projects/<id>/backups/`. Each external file modification: `cp` to backups/ → `git add && git commit` (commit message: session_id, agent_type, reason). Version history, diff, compression all provided by git natively. `air restore --list` → `git log`; `air restore --session <id>` → `git log --grep <id>`. User manually deletes backups; no automatic cleanup.
|
||||
|
||||
## D-031: High-Risk Action Detection — Static Path Whitelist + LLM Escape Hatch
|
||||
|
||||
- **Decision**: Static path whitelist covers clearly-system paths (`/etc/fstab`, `/boot/`, `/etc/default/grub`, Windows registry system hives). `sudo` is NOT treated as high-risk (development machines need it for routine operations). LLM judgment only used as escape hatch when path matching can't decide.
|
||||
|
||||
## D-032: Restore Granularity
|
||||
|
||||
- **Decision**: Three levels — single file (most recent backup), specified time point, entire session. Git-backed storage makes all three straightforward.
|
||||
|
||||
## D-033: Testing Strategy
|
||||
|
||||
- **Decision**: Three layers:
|
||||
- **Unit tests** (`bun test`, CI per push, <30s, no LLM): Tool schema validation, PermissionEngine, ContextAssembler token math, EventBus routing, build system detection, config loading priority.
|
||||
- **Integration tests** (CI per push, <1min, recorded LLM fixture replay): Agent Loop state machine, Scheduler dependency resolution, sub-agent spawn → IPC → WorkerResult, session persist/restore, compaction Copy-on-Write, worktree lifecycle.
|
||||
- **E2E tests** (Release gate, real LLM): Full C++ project scenarios — add function + test, fix build error, multi-task dependency order, session resume. Must pass before every release.
|
||||
|
||||
## D-034: Distribution — Binary Tarball
|
||||
|
||||
- **Decision**: Binary distribution (Bun compile standalone executable, bundled Bun runtime). Distribution package = binary executable + Python scripts + default resource files (compaction rule templates, HUD presets, etc.). No public npm/channel until stable. Language-specific toolchains are first-class plugins, not bundled special treatment.
|
||||
|
||||
## D-035: Logging — Dual-File, 7-Day Retention
|
||||
|
||||
- **Decision**:
|
||||
- `air.log` — User-readable. Records startup failures, exceptions, environment configuration issues. Helps users self-diagnose.
|
||||
- `air.developer.log` — Full debug log, encrypted (may contain user privacy data, only decryptable by development team). Performance metrics written here. 7-day retention, auto-rotated.
|
||||
- Crash diagnostics: `air doctor` command collects version info, system environment, recent logs, crash stack trace into diagnostic package. Auto-detect abnormal exit on next startup, prompt user.
|
||||
|
||||
## D-036: Multi-Language Extension — Per-Language toolchain-* Packages
|
||||
|
||||
- **Decision**: Runtime (Agent Loop, Session, Scheduler, ToolRegistry, PermissionEngine) is language-agnostic. Each language is a `toolchain-<lang>` package + a `LanguageDetector` plugin implementing a common interface. Adding a new language = adding a `toolchain-python`/`toolchain-rust` etc. package, no core changes required. MVP ships with `toolchain-cpp`.
|
||||
|
||||
## D-037: Compaction Rules — Three-Tier Inheritance
|
||||
|
||||
- **Decision**: System default (built-in, never deleted, always fallback) → User template (`~/.air/compaction-rules.yaml`, editable, affects all future new projects) → Project rules (`.air/compaction-rules.yaml`, project-specific, highest priority).
|
||||
425
AirPlan/docs/architecture/decisions-round-3.md
Normal file
425
AirPlan/docs/architecture/decisions-round-3.md
Normal file
@@ -0,0 +1,425 @@
|
||||
# Architecture Decisions — Round 3
|
||||
|
||||
Date: 2026-05-26
|
||||
Source: implementation-interface freeze discussion
|
||||
|
||||
## D-038: RuntimeEvent Envelope Uses Route Chain
|
||||
|
||||
- **Decision**: Runtime events use a structured `route: string[]` route chain instead of correlation/causation IDs.
|
||||
- **Reason**: Route chain is easier to display, append, and inspect across Main Agent → Architecture Designer → Scheduler → Worker → Tool flows.
|
||||
- **Envelope**:
|
||||
|
||||
```ts
|
||||
interface RuntimeEvent<T = unknown> {
|
||||
id: string
|
||||
type: string
|
||||
version: number
|
||||
timestamp: string
|
||||
session_id: string
|
||||
project_id?: string
|
||||
source: EventSource
|
||||
route: string[]
|
||||
payload: T
|
||||
}
|
||||
```
|
||||
|
||||
- **Durability**: Not declared by the event. EventStore decides durability by event type.
|
||||
|
||||
## D-039: IPC Uses NDJSON over stdio
|
||||
|
||||
- **Decision**: Parent Scheduler and child agents communicate via NDJSON over stdio.
|
||||
- **stdout**: Protocol only (`event`, `control`, `log` messages).
|
||||
- **stderr**: Crash fallback and non-structured fatal diagnostics only.
|
||||
- **Message union**:
|
||||
|
||||
```ts
|
||||
type IpcMessage =
|
||||
| { kind: "event"; event: RuntimeEvent }
|
||||
| { kind: "control"; control: ControlMessage }
|
||||
| { kind: "log"; level: "debug" | "info" | "warn" | "error"; message: string; data?: unknown }
|
||||
```
|
||||
|
||||
- **Exit codes**:
|
||||
- `0`: protocol-level completion, including task completed/blocked/failed
|
||||
- `1`: uncaught exception
|
||||
- `2`: startup/protocol error
|
||||
- `3`: permission error
|
||||
- `4`: parent cancelled
|
||||
- `5`: hard timeout killed
|
||||
|
||||
## D-040: Durable Event Type Set
|
||||
|
||||
- **Durable**:
|
||||
- `session.created`, `session.archived`, `session.deleted`
|
||||
- `user.message.created`, `assistant.message.created`
|
||||
- `agent.started`, `agent.completed`, `agent.failed`
|
||||
- `task.created`, `task.started`, `task.completed`, `task.blocked`, `task.failed`, `task.cancelled`
|
||||
- `tool.started`, `tool.completed`, `tool.failed`
|
||||
- `command.started`, `command.completed`, `command.failed`
|
||||
- `artifact.created`
|
||||
- `context.compaction.completed`, `summary.created`
|
||||
- `memory.candidate.created`, `memory.promoted`, `memory.archived`
|
||||
- `debug.record.created`
|
||||
- `permission.decision.recorded`
|
||||
- `requirement.changed`, `architecture.plan.updated`, `architecture.impact.completed`
|
||||
- **Ephemeral only**:
|
||||
- `agent.heartbeat`, `task.progress`, `token.delta`, `stdout.delta`, `stderr.delta`, `hud.frame.rendered`, `tool.progress`
|
||||
- **Rationale**: Persist tool/agent starts so crash recovery can detect half-finished operations; avoid persisting high-frequency stream deltas.
|
||||
|
||||
## D-041: TaskSpec Contract
|
||||
|
||||
```ts
|
||||
interface TaskSpec {
|
||||
id: string
|
||||
type: "execute" | "review" | "debug" | "compact" | "mine_experience"
|
||||
title: string
|
||||
description: string
|
||||
acceptance_criteria: string[]
|
||||
scope: {
|
||||
write_area?: string
|
||||
expected_files?: string[]
|
||||
allowed_paths?: string[]
|
||||
denied_paths?: string[]
|
||||
}
|
||||
dependencies: { hard: string[]; soft: string[] }
|
||||
verification: {
|
||||
commands?: string[]
|
||||
required: boolean
|
||||
fallback_allowed: boolean
|
||||
}
|
||||
constraints: {
|
||||
max_turns: number
|
||||
soft_timeout_ms: number
|
||||
hard_timeout_ms: number
|
||||
retry_budget: number
|
||||
model_policy: "scheduler_forced" | "agent_select"
|
||||
model_id?: string
|
||||
}
|
||||
context_refs: {
|
||||
plan_ref?: string
|
||||
arc_ref?: string
|
||||
parent_task_results?: string[]
|
||||
artifacts?: string[]
|
||||
}
|
||||
output_contract: "ExecutorResult" | "ReviewerResult" | "DebuggerResult" | "CompactorResult" | "ExperienceMinerResult"
|
||||
}
|
||||
```
|
||||
|
||||
- **allowed_paths/denied_paths** are task-level narrowing rules on top of global PermissionEngine.
|
||||
- **verification.commands** are Scheduler recommendations; agents may add more and must report actual commands run.
|
||||
- **retry_budget** is per task.
|
||||
|
||||
## D-042: WorkerResult Contract
|
||||
|
||||
```ts
|
||||
interface WorkerResult<T = unknown> {
|
||||
task_id: string
|
||||
agent_id: string
|
||||
agent_type: "executor" | "reviewer" | "debugger" | "compactor" | "experience_miner"
|
||||
status: "completed" | "failed" | "blocked" | "cancelled"
|
||||
summary: string
|
||||
changed_files: string[]
|
||||
diff_ref?: string
|
||||
artifacts: ArtifactRef[]
|
||||
verification: VerificationResult[]
|
||||
risks: Risk[]
|
||||
follow_up_tasks: FollowUpTask[]
|
||||
evidence_refs: EvidenceRef[]
|
||||
result: T
|
||||
}
|
||||
```
|
||||
|
||||
- **failed**: task goal not achieved; Scheduler may retry or skip.
|
||||
- **blocked**: upper-level decision needed; continued attempts are not useful.
|
||||
- **summary**: human-readable 3–6 sentence summary covering what was done, evidence, conclusion, and risk. It is for TUI/Main Agent display, not scheduling logic.
|
||||
- **changed_files** exists for all worker types and may be empty.
|
||||
|
||||
## D-043: ArtifactRef and EvidenceRef Separation
|
||||
|
||||
- **Artifact**: persistent file or large data object (build log, test log, screenshot, pcap, core dump, diff, terminal cast).
|
||||
- **Evidence**: a claim-supporting reference that may point to an artifact excerpt, structured result, message, tool run, command run, or diagnostic.
|
||||
|
||||
```ts
|
||||
interface ArtifactRef {
|
||||
id: string
|
||||
type: "build_log" | "test_log" | "screenshot" | "pcap" | "core_dump" | "terminal_cast" | "diff" | "report" | "other"
|
||||
uri: string
|
||||
size_bytes?: number
|
||||
sha256?: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
interface EvidenceRef {
|
||||
id: string
|
||||
kind: "artifact_excerpt" | "structured_result" | "message" | "tool_run" | "command_run" | "diagnostic"
|
||||
ref: string
|
||||
location?: { line_start?: number; line_end?: number; byte_start?: number; byte_end?: number }
|
||||
claim: string
|
||||
}
|
||||
```
|
||||
|
||||
## D-044: Tool API Contract
|
||||
|
||||
```ts
|
||||
interface ToolDefinition<I = unknown, O = unknown> {
|
||||
name: string
|
||||
version: number
|
||||
description: string
|
||||
input_schema: JsonSchema<I>
|
||||
output_schema: JsonSchema<O>
|
||||
category: "filesystem" | "shell" | "build" | "test" | "debug" | "static_analysis" | "gui" | "network" | "memory" | "project" | "internal"
|
||||
permissions: {
|
||||
read_paths?: PathPolicy
|
||||
write_paths?: PathPolicy
|
||||
execute?: boolean
|
||||
network?: boolean
|
||||
system_sensitive?: boolean
|
||||
}
|
||||
streaming: boolean
|
||||
execute(input: I, context: ToolExecutionContext): AsyncIterable<ToolEvent> | Promise<ToolResult<O>>
|
||||
}
|
||||
```
|
||||
|
||||
- Inputs and outputs are both JSON-schema validated.
|
||||
- Streaming tools must emit a final `tool.result` containing `ToolResult`.
|
||||
- Bash is a regular shell tool; PermissionEngine performs extra command risk analysis.
|
||||
|
||||
## D-045: Capability Dependencies Are Managed by Doctor/Setup
|
||||
|
||||
- Capability manifests declare dependencies but do not install them directly.
|
||||
- `air doctor` / `air setup` detect and repair missing dependencies.
|
||||
- First startup runs read-only doctor automatically.
|
||||
- If issues exist, user is prompted to run fix.
|
||||
- High-permission mode can use `announce_then_run` for dependency installation after the first startup; user not interrupting means allow.
|
||||
- First startup, even in high-permission mode, shows the report and asks before `doctor --fix`.
|
||||
- `credentials` and `system_sensitive` risks always require explicit confirmation.
|
||||
|
||||
```ts
|
||||
interface DependencySpec {
|
||||
id: string
|
||||
kind: "executable" | "system_package" | "npm_package" | "pip_package" | "lsp_server" | "formatter" | "mcp_server" | "env_var" | "permission" | "service" | "network_port"
|
||||
required_for: string[]
|
||||
severity: "required" | "optional" | "degraded"
|
||||
detect: DependencyDetectSpec
|
||||
install?: {
|
||||
low_permission: "never" | "prompt" | "safe_cache"
|
||||
high_permission: "never" | "announce_then_run" | "safe_cache" | "prompt"
|
||||
commands?: InstallCommandTemplate[]
|
||||
docs?: string
|
||||
}
|
||||
risk: "none" | "downloads_code" | "needs_root" | "network_capture" | "credentials" | "system_sensitive"
|
||||
}
|
||||
```
|
||||
|
||||
## D-046: ContextAssembler Contract
|
||||
|
||||
- ContextAssembler outputs Anthropic canonical messages. Provider-specific conversion happens only at the LLM adapter boundary.
|
||||
- ContextAssembler records omissions so agents know what was not included.
|
||||
- If usage passes compaction threshold, it publishes `context.compaction.requested` but does not compact itself.
|
||||
|
||||
```ts
|
||||
interface ContextRequest {
|
||||
session_id: string
|
||||
project_id: string
|
||||
requester: { kind: "main" | "architecture_designer" | "scheduler" | "agent"; agent_type?: string; task_id?: string }
|
||||
purpose: "user_response" | "architecture_planning" | "task_execution" | "review" | "debug" | "compaction" | "experience_mining"
|
||||
model: { provider_id: string; model_id: string; context_window_tokens: number; max_output_tokens: number }
|
||||
budget_policy: { reserved_output_tokens: number; safety_margin_tokens: number; target_usage_ratio: number }
|
||||
include: {
|
||||
project_rules: boolean
|
||||
project_profile: boolean
|
||||
task_graph: boolean
|
||||
recent_messages: number
|
||||
related_artifacts?: string[]
|
||||
related_tasks?: string[]
|
||||
related_files?: string[]
|
||||
}
|
||||
rule_set_ref?: string
|
||||
}
|
||||
|
||||
interface AssembledContext {
|
||||
request_id: string
|
||||
messages: AnthropicMessageParam[]
|
||||
included_refs: { messages: string[]; summaries: string[]; artifacts: string[]; rules: string[]; tasks: string[] }
|
||||
token_estimate: { total: number; by_section: Record<string, number>; model_id: string }
|
||||
compaction: { needed: boolean; reason?: string; requested_event_id?: string }
|
||||
omissions: { ref: string; reason: string }[]
|
||||
}
|
||||
```
|
||||
|
||||
## D-047: Compaction Rules Use Markdown + Frontmatter
|
||||
|
||||
- Rule files are Markdown with YAML frontmatter.
|
||||
- Paths:
|
||||
- Built-in system default
|
||||
- User template: `~/.air/compaction-rules.md`
|
||||
- Project override: `.air/shared/compaction-rules.md`
|
||||
- Three-tier inheritance: system default → user template → project override.
|
||||
- Message classification is done by ContextClassifier before compaction.
|
||||
- `drop_if_needed` is allowed because original messages are preserved.
|
||||
|
||||
## D-048: TUI Reuses OpenCode UI Primitives, Not Business State
|
||||
|
||||
- Use `@opentui/solid`, `@opentui/core`, and `@opentui/keymap`.
|
||||
- Copy/adapt OpenCode's generic theme, dialog, toast, keymap, layout, spinner, border, markdown/code/diff rendering patterns.
|
||||
- Do not reuse OpenCode's SDK/sync/session business layer.
|
||||
- AirCoding defines its own event store, session/message/task/agent/tool state model.
|
||||
- OpenCode session UI is used as a rendering reference only.
|
||||
|
||||
## D-049: Project State Lives in `.air/local`, Shared Knowledge in `.air/shared`
|
||||
|
||||
- Project source of truth moves into the project directory:
|
||||
|
||||
```text
|
||||
<project>/.air/
|
||||
shared/ # git-shareable project knowledge
|
||||
local/ # portable but gitignored runtime state
|
||||
```
|
||||
|
||||
- `.air/shared` contains project profile, permissions, compaction rules, project rules, and plan/docs.
|
||||
- `.air/local` contains sessions, artifacts, runtime state, backups, debug/learned DBs, locks, temp, and workspaces.
|
||||
- `~/.air` contains only user config, cache, global skills, global logs, and a project index.
|
||||
- `project_id` is a stable UUID generated at initialization, not an absolute-path hash.
|
||||
|
||||
## D-050: Developer Logs Use Development-Team Public Key Encryption
|
||||
|
||||
- `air.developer.log` is encrypted with the development team's public key.
|
||||
- No local user private key is required for decrypting developer logs.
|
||||
- `air doctor --bundle` may include full diagnostics and is not automatically redacted.
|
||||
- Rationale: redaction may remove information needed to debug real failures.
|
||||
- Diagnostic bundles are never auto-uploaded; user must explicitly export/send them.
|
||||
|
||||
## D-051: Session DB Uses Canonical Messages + Domain State Tables
|
||||
|
||||
- `messages` stores complete Anthropic canonical content JSON.
|
||||
- `message_drafts` stores streaming assistant intermediate state for crash recovery and is deleted after final message completion.
|
||||
- `message_parts` is not a source-of-truth table in MVP.
|
||||
- Domain tables are the source of truth for scheduling/recovery/query:
|
||||
- `tasks`, `task_dependencies`, `task_attempts`
|
||||
- `agents`, `tool_runs`, `command_runs`
|
||||
- `artifacts`, `diagnostics`, `evidence_refs`, `workspaces`, `events`
|
||||
- `ui_state` stores lightweight UI recovery state only.
|
||||
- ProjectionStore rebuilds TUI view models from DB + live EventBus.
|
||||
|
||||
## D-052: Query-Friendly Columns and Tables Are Preferred over Parsing JSON
|
||||
|
||||
- Canonical JSON preserves fidelity; frequently queried relations are extracted to columns/tables.
|
||||
- `tool_runs` and `command_runs` include `origin_message_id`.
|
||||
- `artifacts` include common foreign keys (`task_id`, `agent_id`, `tool_run_id`, `command_run_id`) while retaining generic associated entity fields.
|
||||
- `events` extract source/task/agent/tool/command IDs and store both `route_json` and `route_text`.
|
||||
- `task_dependencies`, `task_attempts`, `diagnostics`, `evidence_refs`, and `workspaces` are first-class tables.
|
||||
|
||||
## D-053: UI State Is Flushed Periodically and on Exit
|
||||
|
||||
- UI changes are held in memory during interaction.
|
||||
- `ui_state` flushes periodically (e.g. every 10 seconds) and on normal exit.
|
||||
- Crash/power loss may lose a few seconds of UI-only state, but never scheduling/message state.
|
||||
|
||||
## D-054: Artifact Layout Is Project-Local
|
||||
|
||||
- Artifacts live under:
|
||||
|
||||
```text
|
||||
<project>/.air/local/sessions/<session-id>/artifacts/
|
||||
```
|
||||
|
||||
- URI format:
|
||||
|
||||
```text
|
||||
artifact://project/<project-id>/session/<session-id>/<artifact-id>
|
||||
```
|
||||
|
||||
- Layout:
|
||||
|
||||
```text
|
||||
artifacts/
|
||||
command-runs/<command-run-id>/
|
||||
tool-runs/<tool-run-id>/
|
||||
builds/
|
||||
tests/
|
||||
screenshots/
|
||||
pcaps/
|
||||
core-dumps/
|
||||
diffs/
|
||||
reports/
|
||||
```
|
||||
|
||||
- Internal filenames may use artifact IDs or semantic names; DB preserves `original_name`.
|
||||
- Logs may be gzip-compressed; screenshots, pcaps, and core dumps are not double-compressed by default.
|
||||
- Session delete/purge deletes artifacts; archive keeps them.
|
||||
|
||||
## D-055: Schema Migration Requires User Confirmation
|
||||
|
||||
- Opening a project auto-detects `.air` schema versions.
|
||||
- Old schema triggers a migration plan display.
|
||||
- User confirmation is required even in high-permission mode.
|
||||
- Migration backs up `.air` first.
|
||||
- Migration failure must rollback.
|
||||
|
||||
## D-056: HUD/TUI Consumes ProjectionStore Only
|
||||
|
||||
- DB is persistent state source.
|
||||
- EventBus is real-time state source.
|
||||
- ProjectionStore is the only display projection consumed by TUI/HUD.
|
||||
- HUD does not query SQLite directly.
|
||||
- ProjectionStore hydrates from DB on startup and applies EventBus updates during runtime.
|
||||
- If EventBus disconnects/restarts, ProjectionStore rehydrates from DB.
|
||||
- HUD presets only control visible fields, not underlying state.
|
||||
|
||||
## D-057: UI Design Asset Capability Is Optional but Supported
|
||||
|
||||
- AirCoding is not a general creative-media agent, but software development often requires UI assets, icons, visual mockups, and design specs.
|
||||
- Runtime supports an optional `ui-design-assets` capability.
|
||||
- MVP includes text/SVG/design-spec oriented tools:
|
||||
- ASCII/wireframe mockup generation
|
||||
- design specification generation
|
||||
- SVG icon generation
|
||||
- screenshot design analysis
|
||||
- external image-generation prompt generation
|
||||
- Bitmap image generation/editing is provider-backed and post-MVP.
|
||||
- Generated design assets are artifacts first:
|
||||
- `ui_mockup`
|
||||
- `icon`
|
||||
- `illustration`
|
||||
- `svg_asset`
|
||||
- `design_spec`
|
||||
- `design_prompt`
|
||||
- Generated assets are shown to the user before being written into project files. UI/design choices are subjective and should not be silently finalized even in high-permission mode.
|
||||
|
||||
## D-058: Anthropic Claude Skills Are a Tool/Skill Reference Source
|
||||
|
||||
- Anthropic/Claude open-source Skills are included as a reference for AirCoding's skill and tool organization.
|
||||
- AirCoding should study and borrow:
|
||||
- `SKILL.md` structure and frontmatter conventions
|
||||
- skill directory layout (`scripts/`, `references/`, `assets/`)
|
||||
- how reusable workflows are packaged as discoverable skills
|
||||
- how skill descriptions guide trigger/retrieval behavior
|
||||
- how skills interact with project rules and tool/capability execution
|
||||
- Claude Skills are a reference for AirCoding's SkillGenerator, ExperienceMiner output format, and Capability documentation.
|
||||
- AirCoding still keeps Project Rules, Skills, MCP, and Capabilities as separate concepts:
|
||||
- Project Rules: authoritative project constraints
|
||||
- Skills: reusable procedural knowledge
|
||||
- MCP: external service/tool protocol
|
||||
- Capabilities: runtime-registered tool bundles with dependencies/triggers/evidence types
|
||||
|
||||
## D-059: Execution-Layer Primitives Align With Claude Code for Code Quality
|
||||
|
||||
- AirCoding should align execution-layer behavior with Claude Code as much as possible to maximize code quality, correctness, and safe modification behavior.
|
||||
- Claude Code is the primary behavioral reference for execution-layer primitives.
|
||||
- This includes:
|
||||
- file read/edit/write safety boundaries
|
||||
- exact and conservative diff/update application semantics
|
||||
- patch granularity and conflict handling
|
||||
- tool input/output schema style
|
||||
- permission checks around filesystem and shell operations
|
||||
- TAOR/TORI-style execution loops and result feedback patterns
|
||||
- read-before-edit discipline
|
||||
- small-step edits with verification before completion
|
||||
- avoiding unrelated refactors and premature abstractions during task execution
|
||||
- build/test/debug evidence collection before declaring completion
|
||||
- project-rule and memory adherence during edits
|
||||
- failure handling that diagnoses root cause instead of random retries
|
||||
- explicit blocker escalation when implementation discovers architecture/interface conflicts
|
||||
- OpenCode remains the runtime/TUI structure reference, but execution primitives must favor Claude Code semantics whenever there is a tradeoff.
|
||||
- Codex remains a reference for broad tool surface and shell/patch/test direct loops, but AirCoding should not sacrifice Claude Code-style edit discipline for tool breadth.
|
||||
- Rationale: Executor correctness, safe code modification, patch quality, verification discipline, project-rule adherence, and failure recovery matter more than matching OpenCode's internal execution implementation or Codex-style general tool breadth.
|
||||
300
AirPlan/docs/architecture/error-taxonomy-v1.md
Normal file
300
AirPlan/docs/architecture/error-taxonomy-v1.md
Normal file
@@ -0,0 +1,300 @@
|
||||
# AirCoding Error Taxonomy V1
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Canonical error taxonomy for V1.0.0 Alpha skeleton
|
||||
|
||||
This document defines error kinds, severity, retryability, failure signatures, user-facing presentation, and routing rules.
|
||||
|
||||
## 1. Goals
|
||||
|
||||
The error taxonomy must support:
|
||||
|
||||
1. Consistent ToolResult and WorkerResult failures.
|
||||
2. Scheduler retry/block/skip decisions.
|
||||
3. User-facing concise errors.
|
||||
4. Developer diagnostic detail.
|
||||
5. Stable semantic signatures for repeated failure detection.
|
||||
6. Safe distinction between implementation failure and architecture/product blockers.
|
||||
|
||||
## 2. Core Error Contract
|
||||
|
||||
```ts
|
||||
type ErrorKind =
|
||||
| "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"
|
||||
|
||||
type ErrorSeverity = "info" | "warning" | "error" | "fatal"
|
||||
|
||||
type Retryability = "retryable" | "retryable_after_change" | "not_retryable" | "unknown"
|
||||
|
||||
interface AirError {
|
||||
error_id: string
|
||||
kind: ErrorKind
|
||||
severity: ErrorSeverity
|
||||
message: string
|
||||
detail?: string
|
||||
retryability: Retryability
|
||||
semantic_signature: string
|
||||
cause_ref?: EntityRef
|
||||
cause_refs?: EntityRef[]
|
||||
user_action?: string
|
||||
metadata?: Record<string, unknown>
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Error Kind Semantics
|
||||
|
||||
| Kind | Meaning | Default route |
|
||||
|---|---|---|
|
||||
| `user_error` | invalid/contradictory user input or cancelled decision | Main Agent |
|
||||
| `project_error` | project structure/config issue | Main Agent or Doctor |
|
||||
| `env_error` | local environment missing/broken | Doctor |
|
||||
| `dependency_error` | missing or incompatible dependency | Doctor/PermissionEngine |
|
||||
| `permission_error` | action denied or needs confirmation | PermissionEngine/Main Agent |
|
||||
| `tool_error` | tool implementation or validation failure | Scheduler/Debugger |
|
||||
| `command_error` | shell process failed outside build/test classification | Scheduler/Debugger |
|
||||
| `build_error` | build/configure/compile/link failure | Executor/Debugger |
|
||||
| `test_error` | test command failed or assertion failed | Executor/Debugger |
|
||||
| `static_analysis_error` | static analysis found issue or tool failed | Reviewer/Debugger |
|
||||
| `debug_error` | debugger/instrumentation failed | Debugger/Scheduler |
|
||||
| `provider_error` | provider API/network/auth/rate failure | Provider layer/Main Agent |
|
||||
| `model_capability_error` | selected model lacks required feature | Scheduler/provider selector |
|
||||
| `context_error` | context assembly/compaction/retrieval failure | ContextAssembler/Compactor |
|
||||
| `agent_error` | worker protocol/crash/result validation issue | Scheduler |
|
||||
| `scheduler_error` | graph/dispatch/recovery internal issue | Main Agent/developer log |
|
||||
| `workspace_error` | worktree/copy/workspace setup failure | Scheduler |
|
||||
| `merge_error` | merge/patch conflict or copy-back failure | Scheduler/Debugger/Architecture Designer |
|
||||
| `architecture_error` | design/interface mismatch or invalid plan | Architecture Designer |
|
||||
| `policy_error` | safety/security/policy violation | Main Agent/PermissionEngine |
|
||||
| `system_error` | OS/resource/filesystem unexpected failure | Scheduler/Doctor |
|
||||
| `unknown_error` | insufficient classification evidence | Scheduler/Debugger |
|
||||
|
||||
## 4. Severity Semantics
|
||||
|
||||
| Severity | Meaning | User visibility |
|
||||
|---|---|---|
|
||||
| `info` | non-blocking note | usually hidden or progress detail |
|
||||
| `warning` | degraded path or skipped optional gate | shown in final report |
|
||||
| `error` | task/tool failed but system can continue/retry | shown when relevant |
|
||||
| `fatal` | session/graph cannot safely continue | immediately surfaced |
|
||||
|
||||
Severity does not imply retryability. A fatal provider outage may be retryable after user changes provider; a low-severity policy denial may be not retryable.
|
||||
|
||||
## 5. Retryability Rules
|
||||
|
||||
```text
|
||||
retryable → same strategy may succeed
|
||||
retryable_after_change → retry only after model/context/command/permission/env/workspace change
|
||||
not_retryable → route to block/skip/cancel
|
||||
unknown → first failure can be diagnosed, repeated unknown escalates
|
||||
```
|
||||
|
||||
Default retryability by kind:
|
||||
|
||||
| Kind | Default retryability |
|
||||
|---|---|
|
||||
| provider_error | retryable or retryable_after_change |
|
||||
| env_error | retryable_after_change |
|
||||
| dependency_error | retryable_after_change |
|
||||
| permission_error | retryable_after_change |
|
||||
| build_error | retryable_after_change |
|
||||
| test_error | retryable_after_change |
|
||||
| merge_error | retryable_after_change |
|
||||
| architecture_error | not_retryable until architecture decision |
|
||||
| policy_error | not_retryable unless policy changes |
|
||||
| agent_error | retryable_after_change |
|
||||
| scheduler_error | unknown/fatal depending on invariant |
|
||||
|
||||
## 6. Semantic Failure Signature
|
||||
|
||||
Failure signatures are used for retry-loop detection and debug knowledge.
|
||||
|
||||
Signature inputs:
|
||||
|
||||
```text
|
||||
kind
|
||||
normalized tool/command name
|
||||
normalized exit code or provider status
|
||||
primary diagnostic semantic_signature
|
||||
primary file/module path when relevant
|
||||
normalized error message class
|
||||
architecture/policy blocker class when relevant
|
||||
```
|
||||
|
||||
Signature format:
|
||||
|
||||
```text
|
||||
<kind>:<surface>:<class>:<location-or-none>:<hash>
|
||||
```
|
||||
|
||||
Examples:
|
||||
|
||||
```text
|
||||
build_error:cpp.build:undefined_reference:src/foo.cpp:ab12cd34
|
||||
provider_error:llm.complete:rate_limit:none:91fe2300
|
||||
merge_error:git.merge_workspace:patch_conflict:src/main.cpp:3344aa90
|
||||
permission_error:shell.run:system_sensitive:/usr/bin:bb12cc88
|
||||
```
|
||||
|
||||
Do not include volatile data such as timestamps, temp paths, PIDs, random IDs, full absolute home paths, or secret-like strings.
|
||||
|
||||
## 7. Mapping to Task Outcomes
|
||||
|
||||
| Error kind | Common task outcome |
|
||||
|---|---|
|
||||
| build/test/static_analysis | failed, then retry/debug |
|
||||
| permission | blocked unless policy auto-allows |
|
||||
| architecture | blocked and route to Architecture Designer |
|
||||
| provider/model capability | failed or blocked depending fallback availability |
|
||||
| merge/workspace | failed, retry serial/repair, or blocked |
|
||||
| env/dependency | blocked or doctor fix task |
|
||||
| policy | blocked/cancelled |
|
||||
| agent/scheduler/system | failed or fatal blocked |
|
||||
|
||||
WorkerResult status rules:
|
||||
|
||||
1. Use `failed` when the task goal was not achieved but Scheduler can decide retry/skip.
|
||||
2. Use `blocked` when a higher-level decision or external condition is required.
|
||||
3. Use `cancelled` when explicitly stopped.
|
||||
4. Do not label architecture/product impossibility as ordinary failure.
|
||||
|
||||
## 8. User-Facing Error Presentation
|
||||
|
||||
User-facing messages should include:
|
||||
|
||||
```text
|
||||
what failed
|
||||
why it matters
|
||||
what AirCoding tried or can try next
|
||||
whether user decision/action is needed
|
||||
where evidence/report is stored
|
||||
```
|
||||
|
||||
They should not include:
|
||||
|
||||
```text
|
||||
secrets
|
||||
raw huge logs
|
||||
stack traces unless the user asks
|
||||
irrelevant implementation detail
|
||||
```
|
||||
|
||||
Developer detail goes to `air.developer.log` and artifacts.
|
||||
|
||||
## 9. Tool and Command Error Mapping
|
||||
|
||||
ToolResult errors must map into `AirError`.
|
||||
|
||||
```ts
|
||||
interface ToolErrorOutput {
|
||||
error: AirError
|
||||
partial_output?: unknown
|
||||
artifact_ids?: string[]
|
||||
evidence_ref_ids?: string[]
|
||||
}
|
||||
```
|
||||
|
||||
Command failures are classified by purpose:
|
||||
|
||||
| Command purpose | Non-zero exit maps to |
|
||||
|---|---|
|
||||
| `build` | `build_error` |
|
||||
| `test` | `test_error` |
|
||||
| `doctor` | `env_error` or `dependency_error` |
|
||||
| `debug` | `debug_error` or diagnosed target error |
|
||||
| `general` | `command_error` |
|
||||
|
||||
## 10. Provider Error Mapping
|
||||
|
||||
Provider adapter maps provider-specific failures:
|
||||
|
||||
| Provider condition | Error kind |
|
||||
|---|---|
|
||||
| auth failure | `provider_error`, not retryable until config change |
|
||||
| rate limit | `provider_error`, retryable_after_change or retryable after delay |
|
||||
| model not found | `model_capability_error` or `provider_error` |
|
||||
| context too large | `context_error` or `model_capability_error` |
|
||||
| tool use unsupported | `model_capability_error` |
|
||||
| network timeout | `provider_error`, retryable |
|
||||
| malformed model output | `provider_error` or `agent_error` depending boundary |
|
||||
|
||||
## 11. Policy and Security Errors
|
||||
|
||||
Policy errors are not bypassed by retry. They require one of:
|
||||
|
||||
```text
|
||||
user approval within policy
|
||||
permission/profile change
|
||||
architecture/task redesign
|
||||
request refusal/cancellation
|
||||
```
|
||||
|
||||
Security-sensitive details may be summarized in user-facing text and preserved in encrypted developer logs/artifacts when needed.
|
||||
|
||||
## 12. Error Events and Persistence
|
||||
|
||||
Errors appear in:
|
||||
|
||||
```text
|
||||
tool.failed
|
||||
command.failed
|
||||
task.failed
|
||||
task.blocked
|
||||
agent.failed
|
||||
context.compaction.failed
|
||||
doctor.fix.failed
|
||||
```
|
||||
|
||||
Each failure payload should include canonical `AirError` plus evidence refs:
|
||||
|
||||
```text
|
||||
error.kind
|
||||
error.message
|
||||
error.detail when useful
|
||||
error.retryability
|
||||
error.semantic_signature
|
||||
evidence refs
|
||||
```
|
||||
|
||||
Diagnostics table uses `semantic_signature`; not every error is a diagnostic.
|
||||
|
||||
## 13. V1.0.0 Alpha Cut Line
|
||||
|
||||
V1.0.0 Alpha skeleton must implement:
|
||||
|
||||
1. `AirError`, `ErrorKind`, `ErrorSeverity`, `Retryability` contracts.
|
||||
2. Tool/command/provider error mapping.
|
||||
3. Semantic failure signature generation.
|
||||
4. Scheduler retry/block mapping from error kind.
|
||||
5. User-facing vs developer-detail formatting.
|
||||
6. Event payload integration for all failure events.
|
||||
|
||||
Post-MVP:
|
||||
|
||||
```text
|
||||
learned failure classifier
|
||||
cross-session duplicate failure clustering
|
||||
automatic debug knowledge promotion by signature
|
||||
localized user-facing error text
|
||||
provider-specific deep error parsers
|
||||
```
|
||||
1231
AirPlan/docs/architecture/event-registry-v1.md
Normal file
1231
AirPlan/docs/architecture/event-registry-v1.md
Normal file
File diff suppressed because it is too large
Load Diff
1334
AirPlan/docs/architecture/interface-contracts-v1.md
Normal file
1334
AirPlan/docs/architecture/interface-contracts-v1.md
Normal file
File diff suppressed because it is too large
Load Diff
148
AirPlan/docs/architecture/main-agent-state-machine.md
Normal file
148
AirPlan/docs/architecture/main-agent-state-machine.md
Normal file
@@ -0,0 +1,148 @@
|
||||
# Main Agent State Machine
|
||||
|
||||
Date: 2026-05-28
|
||||
Status: V1.0.0 Alpha canonical state machine
|
||||
|
||||
This document defines the Main Agent lifecycle for V1.0.0 Alpha. Event names align with `event-registry-v1.md`. Permission model aligns with `interface-contracts-v1.md` `permission_template`.
|
||||
|
||||
## States
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ IDLE │
|
||||
│ Waiting for user input │
|
||||
└──────┬───────────────────────────────────────┘
|
||||
│ user.message.created
|
||||
▼
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ CLASSIFYING │
|
||||
│ LLM classifies intent │
|
||||
└──┬──────────────────┬───────────────────────┘
|
||||
│ │
|
||||
Chat/Q&A │ Task request │ /direct command
|
||||
▼ ▼ ▼
|
||||
┌──────────┐ ┌──────────────────┐ ┌──────────────┐
|
||||
│ANSWERING │ │ DELEGATING │ │ DIRECT_MODE │
|
||||
│ Direct │ │ Needs arch check?│ │ Main Agent │
|
||||
│ reply │ └──┬───────────┬───┘ │ with executor│
|
||||
│ → IDLE │ │ │ │ permissions │
|
||||
└──────────┘ Simple│ Needs│ │ /done → IDLE │
|
||||
skip │ plan │ └──────────────┘
|
||||
plan │ │
|
||||
→ ▼ ▼
|
||||
Scheduler┌──────────┐ ┌──────────────────────┐
|
||||
│SCHEDULING│ │ARCHITECTURE_DESIGNING│
|
||||
│Create │ │ Architecture │
|
||||
│tasks │ │ Designer assesses │
|
||||
│→ AWAITING│ │ impact │
|
||||
└──────────┘ └──────┬───────────────┘
|
||||
│ architecture.plan.updated
|
||||
▼
|
||||
┌──────────────────┐
|
||||
│ CONFIRMING │
|
||||
│ Present plan to │
|
||||
│ user, await │
|
||||
│ confirm/modify/ │
|
||||
│ reject │
|
||||
└──┬───┬───┬──────┘
|
||||
│ │ │
|
||||
Confirm │ │Mod│ Reject
|
||||
▼ │ │ → IDLE
|
||||
┌──────────┐│
|
||||
│EXECUTING ││
|
||||
│ Scheduler││
|
||||
│ monitors ││
|
||||
│ progress ││
|
||||
└──┬───┬───┘│
|
||||
│ │ │
|
||||
task.progress event │ │ │
|
||||
→ summarize to user │ │ │
|
||||
│ │ │
|
||||
┌────────────────────┘ │ │
|
||||
│ User requirement change │ │
|
||||
▼ │ │
|
||||
┌──────────────┐ │ │
|
||||
│ INTERRUPTING │ │ │
|
||||
│ Classify │ │ │
|
||||
│ change level:│ │ │
|
||||
│ execution │ │ │
|
||||
│ → notify │ │ │
|
||||
│ Scheduler │ │ │
|
||||
│ design/ │ │ │
|
||||
│ interface │ │ │
|
||||
│ → Arch │ │ │
|
||||
│ Designer │ │ │
|
||||
│ full │ │ │
|
||||
│ assessment │ │ │
|
||||
└──┬───────┬───┘ │
|
||||
│ │ │
|
||||
Execution│ Design level │
|
||||
→ resume │ ▼ │
|
||||
EXECUTING│ ┌──────────────┐ │
|
||||
│ │ARCHITECTURE │ │
|
||||
│ │ REVISING │ │
|
||||
│ │ Update plan │ │
|
||||
│ │ → CONFIRMING │ │
|
||||
│ └──────────────┘ │
|
||||
│ │
|
||||
▼ ▼
|
||||
┌──────────────────────────────────────┐
|
||||
│ SUMMARIZING │
|
||||
│ All tasks complete, summarize to user│
|
||||
│ Trigger ExperienceMiner │
|
||||
│ → IDLE │
|
||||
└──────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Events (from event-registry-v1.md)
|
||||
|
||||
| Event | Emitter | Consumer | Notes |
|
||||
|---|---|---|---|
|
||||
| `user.message.created` | TUI/CLI | Main Agent | User input |
|
||||
| `requirement.changed` | Main Agent | Scheduler, Architecture Designer | When user changes scope mid-execution |
|
||||
| `architecture.plan.updated` | Architecture Designer | Main Agent | Plan produced or revised |
|
||||
| `architecture.impact.completed` | Architecture Designer | Main Agent | Impact assessment done |
|
||||
| `task.created` | Scheduler | Main Agent | Tasks created from plan |
|
||||
| `task.progress` | Scheduler/workers | Main Agent | Progress update |
|
||||
| `task.completed` | Scheduler | Main Agent | Task done |
|
||||
| `task.failed` | Scheduler | Main Agent | Task failed |
|
||||
| `task.blocked` | Scheduler | Main Agent | Task blocked |
|
||||
| `permission.prompt.requested` | PermissionEngine | Main Agent/TUI | Needs user decision |
|
||||
| `permission.prompt.resolved` | TUI | PermissionEngine | User decided |
|
||||
|
||||
## Key Internal Events
|
||||
|
||||
| Event | Meaning |
|
||||
|---|---|
|
||||
| `IntentClassified` | Main Agent internal: chat vs task vs direct |
|
||||
| `DirectModeEntered` | Main Agent entered `/direct` mode |
|
||||
| `DirectModeExited` | Main Agent exited `/done` mode |
|
||||
|
||||
## Confirmation Gating
|
||||
|
||||
| Change Level | Action |
|
||||
|---|---|
|
||||
| Implementation (no interface/architecture impact) | Silent → EXECUTING |
|
||||
| Architecture (interface/constraint/design change) | Architecture Designer assessment → low-permission: user confirm; high-permission: auto-proceed, results displayed |
|
||||
|
||||
## Main Agent Idle Principle
|
||||
|
||||
Main Agent must remain idle and responsive. Background tasks (ExperienceMiner, DebugKnowledge indexing) are dispatched to sub-agents via Scheduler, never run on Main Agent's thread/loop.
|
||||
|
||||
## Direct Mode Rules
|
||||
|
||||
1. `/direct` enters DIRECT_MODE with `permission_template: "main_direct"`.
|
||||
2. In DIRECT_MODE, Main Agent executes directly without Scheduler dispatch.
|
||||
3. Main Agent uses Executor-level permissions but remains user-facing.
|
||||
4. `/done` exits DIRECT_MODE, triggers evidence collection, returns to IDLE.
|
||||
5. DIRECT_MODE does not block Scheduler-owned background tasks.
|
||||
6. All DIRECT_MODE actions are logged with `source.kind = "main"`.
|
||||
|
||||
## State-to-AgentRuntimeContext Mapping
|
||||
|
||||
| State | permission_template |
|
||||
|---|---|
|
||||
| IDLE, CLASSIFYING, ANSWERING, CONFIRMING, SUMMARIZING | N/A (no task execution) |
|
||||
| DIRECT_MODE | `main_direct` |
|
||||
| EXECUTING | Determined by Scheduler per task |
|
||||
| INTERRUPTING, ARCHITECTURE_REVISING | N/A (delegation only) |
|
||||
528
AirPlan/docs/architecture/prompt-layering-v1.md
Normal file
528
AirPlan/docs/architecture/prompt-layering-v1.md
Normal file
@@ -0,0 +1,528 @@
|
||||
# AirCoding Prompt Layering Model V1
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Canonical prompt/context layering model for V1.0.0 Alpha skeleton
|
||||
|
||||
This document defines how AirCoding assembles prompts and context for Main Agent, Architecture Designer, Scheduler-facing planning, worker agents, Reviewer, Debugger, Compactor, and ExperienceMiner.
|
||||
|
||||
AirCoding stores and assembles Anthropic canonical messages internally. Provider adapters convert only at the LLM boundary.
|
||||
|
||||
## 1. Goals
|
||||
|
||||
Prompt layering must:
|
||||
|
||||
1. Preserve stable global behavior across providers.
|
||||
2. Keep project/user rules visible and ordered.
|
||||
3. Keep worker context bounded and task-specific.
|
||||
4. Make architecture decisions explicit and traceable.
|
||||
5. Prevent UI/progress/scheduling state from polluting coding instructions.
|
||||
6. Support copy-on-write compaction without losing backtracking ability.
|
||||
7. Keep Claude Code-like execution discipline at the execution layer.
|
||||
|
||||
## 2. Canonical Layer Order
|
||||
|
||||
ContextAssembler builds messages in this order:
|
||||
|
||||
```text
|
||||
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
|
||||
```
|
||||
|
||||
Higher layers may specialize lower layers but must not silently contradict runtime invariants or safety policy. If a conflict is detected, ContextAssembler records an omission/conflict note and routes to Main Agent or Architecture Designer.
|
||||
|
||||
## 3. Layer Definitions
|
||||
|
||||
### L0 Runtime invariant
|
||||
|
||||
Source:
|
||||
|
||||
```text
|
||||
built-in runtime prompts/resources
|
||||
packages/contracts
|
||||
baseline invariants
|
||||
```
|
||||
|
||||
Contents:
|
||||
|
||||
- internal message format is Anthropic canonical content blocks
|
||||
- tool use protocol and result expectations
|
||||
- read-before-edit discipline
|
||||
- exact/small edit discipline
|
||||
- no unrelated refactors
|
||||
- verify before declaring completion
|
||||
- escalate architecture/interface conflicts
|
||||
- respect PermissionEngine decisions
|
||||
|
||||
Mutable: no, except by AirCoding release.
|
||||
|
||||
### L1 Role / agent mode
|
||||
|
||||
Source:
|
||||
|
||||
```text
|
||||
built-in role prompt for main/architecture/scheduler/executor/reviewer/debugger/compactor/experience_miner
|
||||
```
|
||||
|
||||
Defines:
|
||||
|
||||
- responsibility boundary
|
||||
- allowed outputs
|
||||
- whether writing files is allowed
|
||||
- expected result schema
|
||||
- whether user-facing language is allowed
|
||||
|
||||
### L2 Safety and permission policy
|
||||
|
||||
Source:
|
||||
|
||||
```text
|
||||
~/.air/permissions.yaml
|
||||
<project>/.air/shared/permissions.yaml
|
||||
runtime PermissionEngine
|
||||
```
|
||||
|
||||
Contents:
|
||||
|
||||
- path policy
|
||||
- system-sensitive policy
|
||||
- credential policy
|
||||
- network policy
|
||||
- high-permission announce-then-run behavior
|
||||
- explicit-confirmation boundaries
|
||||
|
||||
### L3 Project rules and user preferences
|
||||
|
||||
Source order:
|
||||
|
||||
```text
|
||||
built-in default project rules template
|
||||
~/.air/rules or global profile
|
||||
<project>/.air/shared/rules/project-rules.md
|
||||
<project>/.air/shared/rules/toolchain-rules.md
|
||||
relevant promoted memories/skills
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Project-local rules override default templates.
|
||||
2. User-confirmed rules override inferred rules.
|
||||
3. Stale rules discovered during execution route to ExperienceMiner/Curator; workers do not silently rewrite rules unless assigned that task.
|
||||
|
||||
### L4 Architecture baseline and current plan
|
||||
|
||||
Source:
|
||||
|
||||
```text
|
||||
<project>/.air/shared/plan/AGENTS.md
|
||||
<project>/.air/shared/plan/plan.md
|
||||
<project>/.air/shared/plan/todo.md
|
||||
ADR/C4 docs
|
||||
current Architecture Designer output
|
||||
TaskGraph
|
||||
```
|
||||
|
||||
Contents:
|
||||
|
||||
- current architecture constraints
|
||||
- accepted ADR decisions
|
||||
- interfaces and module boundaries
|
||||
- active plan/todo
|
||||
- impact assessment summaries
|
||||
|
||||
Workers receive only relevant excerpts or references, not the entire architecture corpus by default.
|
||||
|
||||
### L5 Task specification and acceptance criteria
|
||||
|
||||
Source:
|
||||
|
||||
```text
|
||||
TaskSpec
|
||||
Scheduler wave plan
|
||||
Worker runtime context
|
||||
```
|
||||
|
||||
Contents:
|
||||
|
||||
- task title and description
|
||||
- scope/write area
|
||||
- allowed/denied paths
|
||||
- dependencies and parent results
|
||||
- acceptance criteria
|
||||
- verification requirements
|
||||
- retry/model policy
|
||||
|
||||
This is the primary steering layer for workers.
|
||||
|
||||
### L6 Relevant code/artifacts/evidence
|
||||
|
||||
Source:
|
||||
|
||||
```text
|
||||
fs.read outputs
|
||||
artifact refs
|
||||
command/tool reports
|
||||
diagnostics
|
||||
debug records
|
||||
review findings
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Prefer exact snippets with file paths and line ranges.
|
||||
2. Large content is passed by artifact reference.
|
||||
3. Binary/screenshot/pcap/core evidence is summarized plus referenced.
|
||||
4. Diagnostics include semantic signatures when available.
|
||||
|
||||
### L7 Recent conversation and decision context
|
||||
|
||||
Source:
|
||||
|
||||
```text
|
||||
messages
|
||||
summaries
|
||||
requirement.changed events
|
||||
architecture.impact.completed events
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Include recent user intent and decision changes.
|
||||
2. Include summary ranges when raw history is too large.
|
||||
3. Preserve raw message backtracking through copy-on-write compaction.
|
||||
|
||||
### L8 Tool result history / diagnostics
|
||||
|
||||
Source:
|
||||
|
||||
```text
|
||||
tool_runs
|
||||
command_runs
|
||||
diagnostics
|
||||
evidence_refs
|
||||
```
|
||||
|
||||
Contents:
|
||||
|
||||
- recent tool calls relevant to the task
|
||||
- build/test/debug evidence
|
||||
- failed command excerpts
|
||||
- previous retry attempts and failure signatures
|
||||
|
||||
### L9 Immediate instruction
|
||||
|
||||
Source:
|
||||
|
||||
```text
|
||||
Main Agent instruction
|
||||
Scheduler worker start message
|
||||
user's latest request
|
||||
```
|
||||
|
||||
This layer states what the model should do now and the required output format.
|
||||
|
||||
## 4. Agent-Specific Context Profiles
|
||||
|
||||
### Main Agent Profile
|
||||
|
||||
Purpose: user-facing coordination.
|
||||
|
||||
Includes:
|
||||
|
||||
```text
|
||||
L0 runtime invariant
|
||||
L1 main role
|
||||
L2 permission policy summary
|
||||
L3 user/project rules summary
|
||||
L4 current plan/task graph summary
|
||||
L7 recent conversation
|
||||
L8 high-level evidence summaries
|
||||
L9 latest user request
|
||||
```
|
||||
|
||||
Excludes by default:
|
||||
|
||||
```text
|
||||
large source files
|
||||
raw command logs
|
||||
worker-private scratch context
|
||||
```
|
||||
|
||||
Main Agent must remain responsive and should delegate background work.
|
||||
|
||||
### Architecture Designer Profile
|
||||
|
||||
Purpose: architecture/interface/impact decisions.
|
||||
|
||||
Includes:
|
||||
|
||||
```text
|
||||
L0
|
||||
L1 architecture role
|
||||
L3 project rules
|
||||
L4 full relevant baseline/ADR/C4/plan context
|
||||
L5 architecture task spec
|
||||
L6 code/interface excerpts when needed
|
||||
L7 requirement history
|
||||
L9 requested decision/output
|
||||
```
|
||||
|
||||
Allowed outputs:
|
||||
|
||||
```text
|
||||
architecture plan
|
||||
impact assessment
|
||||
ADR/C4/doc updates
|
||||
TaskGraph/todo updates
|
||||
```
|
||||
|
||||
It must not implement code directly.
|
||||
|
||||
### Scheduler Planning Profile
|
||||
|
||||
The Scheduler is mostly deterministic code, but may use LLM classification for complex planning decisions.
|
||||
|
||||
Includes:
|
||||
|
||||
```text
|
||||
TaskGraph summary
|
||||
write areas
|
||||
dependency graph
|
||||
resource snapshot
|
||||
failure/retry history
|
||||
architecture constraints
|
||||
```
|
||||
|
||||
Output must be structured:
|
||||
|
||||
```ts
|
||||
interface SchedulerLLMDecision {
|
||||
decision_type: "wave_plan" | "retry" | "escalation" | "model_assignment" | "merge_strategy"
|
||||
decision: unknown
|
||||
reason: string
|
||||
risks?: string[]
|
||||
}
|
||||
```
|
||||
|
||||
### Executor Profile
|
||||
|
||||
Purpose: implement/build/test within a bounded task.
|
||||
|
||||
Includes:
|
||||
|
||||
```text
|
||||
L0 execution discipline
|
||||
L1 executor role
|
||||
L2 scoped permissions
|
||||
L3 relevant project/toolchain rules
|
||||
L4 relevant architecture excerpts
|
||||
L5 full TaskSpec
|
||||
L6 relevant files/artifacts
|
||||
L8 prior failures for this task
|
||||
L9 required WorkerResult format
|
||||
```
|
||||
|
||||
Executor rules:
|
||||
|
||||
1. Read before edit.
|
||||
2. Use exact/small edits.
|
||||
3. Do not change architecture/interface unless TaskSpec or Architecture Designer authorizes it.
|
||||
4. Verify with required commands unless impossible; if impossible, return blocked/failed with evidence.
|
||||
5. Return structured WorkerResult.
|
||||
|
||||
### Reviewer Profile
|
||||
|
||||
Purpose: inspect and validate.
|
||||
|
||||
Includes:
|
||||
|
||||
```text
|
||||
L0 review discipline
|
||||
L1 reviewer role
|
||||
L3 project rules
|
||||
L4 architecture/acceptance constraints
|
||||
L5 review TaskSpec
|
||||
L6 diff/artifacts/evidence
|
||||
L8 verification results
|
||||
L9 review output schema
|
||||
```
|
||||
|
||||
Reviewer is read-only. It may propose follow-up tasks but must not edit files.
|
||||
|
||||
Review dimensions:
|
||||
|
||||
```text
|
||||
correctness
|
||||
security
|
||||
scope control
|
||||
architecture compliance
|
||||
test evidence
|
||||
regression risk
|
||||
```
|
||||
|
||||
### Debugger Profile
|
||||
|
||||
Purpose: diagnose failures and either fix within scope or produce blocker evidence.
|
||||
|
||||
Includes:
|
||||
|
||||
```text
|
||||
L0 debugging discipline
|
||||
L1 debugger role
|
||||
L2 permissions
|
||||
L3 toolchain rules
|
||||
L4 relevant architecture constraints
|
||||
L5 debug TaskSpec
|
||||
L6 failing logs/diagnostics/artifacts/code excerpts
|
||||
L8 retry/failure signatures
|
||||
L9 DebuggerResult schema
|
||||
```
|
||||
|
||||
Debugger may modify code only when assigned a debug/fix task with write scope.
|
||||
|
||||
### Compactor Profile
|
||||
|
||||
Purpose: summarize immutable message ranges.
|
||||
|
||||
Includes:
|
||||
|
||||
```text
|
||||
L0 compaction invariant
|
||||
L1 compactor role
|
||||
compaction rules
|
||||
message range snapshot
|
||||
existing summaries
|
||||
current plan/rules for terminology
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```text
|
||||
Markdown/frontmatter summary artifact
|
||||
summary.created / context.compaction.completed payload
|
||||
omissions and backtracking refs
|
||||
```
|
||||
|
||||
Compactor must preserve decisions, constraints, open questions, tool evidence, and user preferences.
|
||||
|
||||
### ExperienceMiner Profile
|
||||
|
||||
Purpose: extract durable rules/skills/debug knowledge candidates.
|
||||
|
||||
Includes:
|
||||
|
||||
```text
|
||||
L0 memory policy
|
||||
L1 experience_miner role
|
||||
project rules and skill docs
|
||||
verified debug records
|
||||
repeated patterns
|
||||
user confirmations
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```text
|
||||
memory candidate
|
||||
rule patch proposal
|
||||
skill patch proposal
|
||||
debug record promotion
|
||||
```
|
||||
|
||||
Non-debug experience promotion requires user confirmation unless project policy says otherwise.
|
||||
|
||||
## 5. Conflict Handling
|
||||
|
||||
Prompt/context conflicts are classified:
|
||||
|
||||
| Conflict | Example | Action |
|
||||
|---|---|---|
|
||||
| policy conflict | project rule asks to bypass permission | Permission policy wins; report conflict |
|
||||
| architecture conflict | task asks to change public interface without ADR | block or Architecture Designer assessment |
|
||||
| user-rule conflict | old rule contradicts latest explicit user instruction | latest explicit user instruction wins for session; ExperienceMiner may update rule |
|
||||
| evidence conflict | stale summary contradicts current file | current file/evidence wins; update summary/rule if needed |
|
||||
| provider conflict | target model lacks required capability | route to provider/model selection or block |
|
||||
|
||||
## 6. Context Assembly Algorithm
|
||||
|
||||
```text
|
||||
1. Resolve context profile from agent/task purpose.
|
||||
2. Load immutable L0/L1 templates.
|
||||
3. Load permission/project rules with precedence.
|
||||
4. Load current architecture/plan refs.
|
||||
5. Load TaskSpec and dependency results.
|
||||
6. Retrieve relevant files/artifacts/evidence.
|
||||
7. Add recent messages/summaries and requirement changes.
|
||||
8. Add relevant tool/command/diagnostic history.
|
||||
9. Fit to token budget using compaction rules.
|
||||
10. Emit Anthropic canonical messages and omissions list.
|
||||
11. If required context cannot fit, emit context.compaction.requested or block.
|
||||
```
|
||||
|
||||
## 7. Prompt Asset Locations
|
||||
|
||||
Built-in prompt resources ship with binary distribution:
|
||||
|
||||
```text
|
||||
resources/prompts/
|
||||
runtime-invariant.md
|
||||
roles/
|
||||
main.md
|
||||
architecture-designer.md
|
||||
scheduler-decision.md
|
||||
executor.md
|
||||
reviewer.md
|
||||
debugger.md
|
||||
compactor.md
|
||||
experience-miner.md
|
||||
output-schemas/
|
||||
```
|
||||
|
||||
Project overrides are not allowed for L0 runtime invariants. Project rules belong in `.air/shared/rules/`, not in prompt resource replacement.
|
||||
|
||||
## 8. Provider Boundary
|
||||
|
||||
ContextAssembler always returns Anthropic canonical messages:
|
||||
|
||||
```ts
|
||||
interface AssembledContext {
|
||||
canonical_format: "anthropic"
|
||||
messages: unknown[]
|
||||
omissions: string[]
|
||||
refs: string[]
|
||||
token_estimate?: number
|
||||
}
|
||||
```
|
||||
|
||||
Provider adapters may convert to OpenAI/OpenRouter/ollama formats after assembly. Provider conversion must not change task semantics or drop tool contract requirements without recording an omission/blocker.
|
||||
|
||||
## 9. V1.0.0 Alpha Cut Line
|
||||
|
||||
V1.0.0 Alpha skeleton must implement:
|
||||
|
||||
1. Built-in role prompt assets.
|
||||
2. Context profile selection by agent/task type.
|
||||
3. Layered assembly order L0-L9.
|
||||
4. Project/global rule loading with precedence.
|
||||
5. Architecture/plan/task/evidence reference loading.
|
||||
6. Token-budget fitting with omission reporting.
|
||||
7. Anthropic canonical output.
|
||||
8. Provider-boundary conversion hook.
|
||||
9. Conflict detection for policy, architecture, stale evidence, and provider capability.
|
||||
|
||||
Post-MVP:
|
||||
|
||||
```text
|
||||
learned retrieval ranking
|
||||
semantic code retrieval
|
||||
skill auto-selection
|
||||
multi-provider prompt optimization
|
||||
UI prompt visualization/debugger
|
||||
```
|
||||
347
AirPlan/docs/architecture/provider-capability-matrix-v1.md
Normal file
347
AirPlan/docs/architecture/provider-capability-matrix-v1.md
Normal file
@@ -0,0 +1,347 @@
|
||||
# AirCoding Provider Capability Matrix V1
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Canonical provider/model capability contract for V1.0.0 Alpha skeleton
|
||||
|
||||
This document defines how AirCoding represents provider/model capabilities, selects models, handles conversion limits, and records fallback behavior.
|
||||
|
||||
AirCoding's internal canonical message format is Anthropic content blocks. Provider adapters own conversion.
|
||||
|
||||
## 1. Goals
|
||||
|
||||
The provider capability matrix must answer:
|
||||
|
||||
1. Can this model/tool path execute the requested task?
|
||||
2. Which capabilities are native vs emulated?
|
||||
3. What quality/risk tier is acceptable for the task?
|
||||
4. What conversion or feature loss must be recorded?
|
||||
5. When should Scheduler force a model vs let an agent choose?
|
||||
|
||||
## 2. Provider Identity
|
||||
|
||||
```ts
|
||||
type ProviderKind =
|
||||
| "anthropic"
|
||||
| "openai"
|
||||
| "openrouter"
|
||||
| "ollama"
|
||||
| "anthropic_compatible"
|
||||
| "openai_compatible"
|
||||
| "custom"
|
||||
|
||||
interface ProviderIdentity {
|
||||
provider_id: string
|
||||
provider_kind: ProviderKind
|
||||
display_name: string
|
||||
base_url?: string
|
||||
auth_ref?: string
|
||||
local: boolean
|
||||
}
|
||||
```
|
||||
|
||||
Secrets are referenced by `auth_ref`; they are never embedded in session DB events or artifacts.
|
||||
|
||||
## 3. Model Capability Matrix
|
||||
|
||||
```ts
|
||||
interface ProviderCapabilityMatrix {
|
||||
provider_id: string
|
||||
provider_kind: ProviderKind
|
||||
model_id: string
|
||||
display_name?: string
|
||||
enabled: boolean
|
||||
quality_tier: "frontier" | "strong" | "standard" | "cheap" | "local" | "unknown"
|
||||
cost_tier: "high" | "medium" | "low" | "free" | "unknown"
|
||||
context_window_tokens?: number
|
||||
max_output_tokens?: number
|
||||
supports: {
|
||||
text_input: boolean
|
||||
text_output: boolean
|
||||
streaming: boolean
|
||||
tool_use: boolean
|
||||
parallel_tool_use: boolean
|
||||
structured_output: boolean
|
||||
json_mode: boolean
|
||||
thinking: boolean
|
||||
prompt_cache: boolean
|
||||
system_prompt: boolean
|
||||
image_input: boolean
|
||||
image_output: boolean
|
||||
audio_input: boolean
|
||||
audio_output: boolean
|
||||
file_input: boolean
|
||||
computer_use: boolean
|
||||
long_context: boolean
|
||||
batch: boolean
|
||||
}
|
||||
conversion: {
|
||||
from_anthropic_canonical: "lossless" | "lossy" | "unsupported"
|
||||
tool_schema: "native" | "converted" | "emulated" | "unsupported"
|
||||
image_input: "native" | "artifact_link" | "unsupported"
|
||||
thinking: "native" | "stripped" | "unsupported"
|
||||
cache_control: "native" | "ignored" | "unsupported"
|
||||
}
|
||||
limits?: {
|
||||
requests_per_minute?: number
|
||||
tokens_per_minute?: number
|
||||
concurrent_requests?: number
|
||||
max_tool_schema_bytes?: number
|
||||
max_image_count?: number
|
||||
max_file_bytes?: number
|
||||
}
|
||||
default_use?: {
|
||||
main?: boolean
|
||||
architecture?: boolean
|
||||
execute?: boolean
|
||||
review?: boolean
|
||||
debug?: boolean
|
||||
compact?: boolean
|
||||
mine_experience?: boolean
|
||||
}
|
||||
notes?: string[]
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Capability Semantics
|
||||
|
||||
### `tool_use`
|
||||
|
||||
Native model-driven tool invocation.
|
||||
|
||||
If false, agents may still call deterministic internal tools outside model tool-use, but the model cannot choose tool calls directly in a single turn. This is lower quality for coding execution.
|
||||
|
||||
### `parallel_tool_use`
|
||||
|
||||
Model can request multiple tool calls in one turn. Scheduler/ToolRegistry may still serialize unsafe tools.
|
||||
|
||||
### `structured_output` / `json_mode`
|
||||
|
||||
Used for WorkerResult, review reports, scheduler decisions, and impact assessments. If unavailable, runtime validates best-effort parsed JSON and may retry with stricter prompt.
|
||||
|
||||
### `thinking`
|
||||
|
||||
Model supports a distinct reasoning/thinking channel or equivalent. If converted/stripped, the adapter must ensure hidden reasoning is not persisted as user-visible content.
|
||||
|
||||
### `prompt_cache`
|
||||
|
||||
Provider supports cache-control or equivalent prompt reuse. If unsupported, ContextAssembler still works but cost may be higher.
|
||||
|
||||
### `image_input`
|
||||
|
||||
Required for screenshot/UI analysis, diagram analysis, and image-based debugging.
|
||||
|
||||
### `image_output`
|
||||
|
||||
Required for first-class image generation. If unavailable, `ui-design-assets` falls back to SVG/assets/prompts.
|
||||
|
||||
### `computer_use`
|
||||
|
||||
Post-MVP. V1 uses explicit tools for GUI/screenshot/network rather than opaque computer-use loops.
|
||||
|
||||
## 5. Task Capability Requirements
|
||||
|
||||
```ts
|
||||
interface ModelRequirement {
|
||||
required: Partial<ProviderCapabilityMatrix["supports"]>
|
||||
preferred?: Partial<ProviderCapabilityMatrix["supports"]>
|
||||
min_quality_tier?: "frontier" | "strong" | "standard" | "cheap" | "local"
|
||||
max_cost_tier?: "high" | "medium" | "low" | "free"
|
||||
min_context_window_tokens?: number
|
||||
allow_lossy_conversion?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
Default requirements by task type:
|
||||
|
||||
| Task type | Required | Preferred | Quality floor |
|
||||
|---|---|---|---|
|
||||
| Main conversation | streaming, tool_use | prompt_cache, long_context | strong |
|
||||
| Architecture Designer | structured_output, long_context | thinking, prompt_cache | frontier/strong |
|
||||
| Executor | tool_use, structured_output | thinking, long_context | frontier/strong |
|
||||
| Reviewer | structured_output | image_input for UI artifacts | strong |
|
||||
| Debugger | tool_use, structured_output | long_context, image_input | strong |
|
||||
| Compactor | long_context or large enough context | prompt_cache | standard |
|
||||
| ExperienceMiner | structured_output | long_context | standard |
|
||||
| UI screenshot analysis | image_input | structured_output | strong |
|
||||
| Image generation | image_output | image editing | provider-specific |
|
||||
|
||||
## 6. Scheduler Model Assignment
|
||||
|
||||
Scheduler chooses one of:
|
||||
|
||||
```ts
|
||||
type ModelAssignmentMode = "scheduler_forced" | "agent_select"
|
||||
|
||||
interface ModelAssignment {
|
||||
mode: ModelAssignmentMode
|
||||
provider_id?: string
|
||||
model_id?: string
|
||||
allowed_models?: Array<{ provider_id: string; model_id: string }>
|
||||
requirement: ModelRequirement
|
||||
reason: string
|
||||
}
|
||||
```
|
||||
|
||||
Guidelines:
|
||||
|
||||
1. Use `scheduler_forced` for cross-model review, high-risk tasks, repeated failures, and deterministic comparisons.
|
||||
2. Use `agent_select` for normal implementation/debug tasks when multiple acceptable models exist.
|
||||
3. Use strong/frontier models for code-changing tasks where hidden complexity may exist.
|
||||
4. Use cheaper models for summarization, indexing, and low-risk classification when evidence can be validated.
|
||||
5. Escalate if no model satisfies required capabilities.
|
||||
|
||||
## 7. Provider Adapter Contract
|
||||
|
||||
```ts
|
||||
interface ProviderAdapter {
|
||||
provider_id: string
|
||||
list_models(): Promise<ProviderCapabilityMatrix[]>
|
||||
validate_model(model_id: string): Promise<ProviderCapabilityMatrix>
|
||||
complete(input: ProviderCompletionInput): AsyncIterable<ProviderStreamEvent>
|
||||
count_tokens?(input: unknown): Promise<number>
|
||||
}
|
||||
|
||||
interface ProviderCompletionInput {
|
||||
model_id: string
|
||||
canonical_format: "anthropic"
|
||||
messages: unknown[]
|
||||
tools?: unknown[]
|
||||
tool_choice?: unknown
|
||||
system?: unknown
|
||||
max_output_tokens?: number
|
||||
temperature?: number
|
||||
metadata?: Record<string, unknown>
|
||||
}
|
||||
```
|
||||
|
||||
Adapter responsibilities:
|
||||
|
||||
1. Convert Anthropic canonical messages to provider format.
|
||||
2. Convert provider output back to Anthropic canonical content blocks or RuntimeEvents.
|
||||
3. Validate tool-call and structured-output compatibility.
|
||||
4. Record conversion omissions/losses.
|
||||
5. Never leak credentials into logs, events, artifacts, or model-visible messages.
|
||||
|
||||
## 8. Conversion Loss Handling
|
||||
|
||||
Conversion result:
|
||||
|
||||
```ts
|
||||
interface ProviderConversionReport {
|
||||
status: "lossless" | "lossy" | "unsupported"
|
||||
omissions: string[]
|
||||
warnings: string[]
|
||||
required_confirmation?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Lossless conversion continues silently.
|
||||
2. Lossy conversion may continue only if `allow_lossy_conversion` is true and omitted features are not required.
|
||||
3. Unsupported required feature blocks before model call.
|
||||
4. Thinking/cache-control stripping is allowed only when not required by task policy.
|
||||
5. Tool schema truncation or unsupported required tool use blocks.
|
||||
|
||||
## 9. Configuration Locations
|
||||
|
||||
Global provider/model config:
|
||||
|
||||
```text
|
||||
~/.air/models.yaml
|
||||
```
|
||||
|
||||
Project override:
|
||||
|
||||
```text
|
||||
<project>/.air/shared/models.yaml
|
||||
```
|
||||
|
||||
Session records store selected `model_provider_id` and `model_id`, but not secrets.
|
||||
|
||||
Example config shape:
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- provider_id: anthropic-main
|
||||
provider_kind: anthropic
|
||||
display_name: Anthropic
|
||||
auth_ref: env:ANTHROPIC_API_KEY
|
||||
enabled: true
|
||||
models:
|
||||
- model_id: claude-opus-4-7
|
||||
quality_tier: frontier
|
||||
cost_tier: high
|
||||
default_use:
|
||||
architecture: true
|
||||
execute: true
|
||||
review: true
|
||||
- model_id: claude-sonnet-4-6
|
||||
quality_tier: strong
|
||||
cost_tier: medium
|
||||
default_use:
|
||||
main: true
|
||||
debug: true
|
||||
compact: true
|
||||
```
|
||||
|
||||
## 10. Doctor Checks
|
||||
|
||||
Doctor validates:
|
||||
|
||||
```text
|
||||
provider config parseability
|
||||
auth_ref existence without printing secret values
|
||||
base_url reachability when allowed
|
||||
model list/validation where provider supports it
|
||||
required default model coverage by role
|
||||
capability mismatch warnings
|
||||
rate-limit metadata if configured
|
||||
```
|
||||
|
||||
Doctor must not persist or print API keys.
|
||||
|
||||
## 11. Fallback Policy
|
||||
|
||||
Fallback order:
|
||||
|
||||
1. Same provider, same quality tier, compatible model.
|
||||
2. Same provider, higher quality tier if allowed.
|
||||
3. Different provider with lossless/acceptable conversion.
|
||||
4. Lower quality tier only for non-code-changing or explicitly allowed tasks.
|
||||
5. Block and ask Main Agent/user if no safe fallback exists.
|
||||
|
||||
Fallback must record:
|
||||
|
||||
```text
|
||||
original provider/model
|
||||
selected provider/model
|
||||
reason
|
||||
capability differences
|
||||
conversion report
|
||||
```
|
||||
|
||||
## 12. V1.0.0 Alpha Cut Line
|
||||
|
||||
V1.0.0 Alpha skeleton must implement:
|
||||
|
||||
1. `ProviderCapabilityMatrix` contract.
|
||||
2. Global/project model config loading.
|
||||
3. Anthropic and OpenAI-compatible adapter interfaces.
|
||||
4. Capability-based model selection.
|
||||
5. Conversion report and omission handling.
|
||||
6. Scheduler model assignment integration.
|
||||
7. Doctor provider checks.
|
||||
8. Session persistence of chosen provider/model IDs.
|
||||
|
||||
Post-MVP:
|
||||
|
||||
```text
|
||||
automatic provider benchmarking
|
||||
cost optimizer
|
||||
multi-provider speculative review
|
||||
batch processing
|
||||
computer-use models
|
||||
native image-generation providers
|
||||
local model quality calibration
|
||||
```
|
||||
435
AirPlan/docs/architecture/runtime-semantics-v1.md
Normal file
435
AirPlan/docs/architecture/runtime-semantics-v1.md
Normal file
@@ -0,0 +1,435 @@
|
||||
# AirCoding Runtime Semantics V1
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Canonical runtime semantics corrections for V1.0.0 Alpha
|
||||
|
||||
This document resolves implementation-critical semantics that cut across the event registry, DB schema, Scheduler, ArtifactStore, PermissionEngine, ContextAssembler, and ExperienceMiner.
|
||||
|
||||
## 1. Source of Truth
|
||||
|
||||
This document refines, not replaces:
|
||||
|
||||
- `interface-contracts-v1.md`
|
||||
- `event-registry-v1.md`
|
||||
- `db-schema-v1.md`
|
||||
- `scheduler-state-machine-v1.md`
|
||||
- `artifact-naming-v1.md`
|
||||
- `security-model-v1.md`
|
||||
|
||||
If a runtime behavior conflicts with older wording, this document is authoritative for V1.0.0 Alpha runtime semantics.
|
||||
|
||||
## 2. Event Ingestion Boundary
|
||||
|
||||
All runtime events from workers, tools, agents, and internal services enter through `EventIngestor`.
|
||||
|
||||
```text
|
||||
producer
|
||||
→ EventIngestor.ingest(event)
|
||||
→ schema/version validation
|
||||
→ persistence policy lookup
|
||||
→ durable: EventStore transaction + domain projection + post-commit EventBus publish
|
||||
→ ephemeral: EventBus publish/coalescing only
|
||||
```
|
||||
|
||||
Responsibilities:
|
||||
|
||||
| Component | Responsibility |
|
||||
|---|---|
|
||||
| EventIngestor | accepts events, validates routing, chooses durable vs ephemeral path |
|
||||
| EventStore | validates durable event payload, inserts event, applies domain projection transactionally |
|
||||
| EventBus | live publish/subscribe only |
|
||||
| Domain services | emit follow-up events; do not hide policy inside EventStore |
|
||||
|
||||
EventStore must not create scheduler tasks, permission decisions, memory promotions, or doctor fixes by policy. Those are follow-up actions emitted by the owning services.
|
||||
|
||||
## 3. Durable Projection Rule
|
||||
|
||||
For same-session DB domain updates:
|
||||
|
||||
```text
|
||||
BEGIN
|
||||
insert events row
|
||||
apply domain table projection
|
||||
COMMIT
|
||||
publish committed event to EventBus
|
||||
```
|
||||
|
||||
For external DB/file side effects, use the cross-store semantics in section 6.
|
||||
|
||||
## 4. Heartbeat Semantics
|
||||
|
||||
`agent.heartbeat` remains an ephemeral event for live UI updates, but Scheduler must coalesce heartbeat timestamps into domain rows.
|
||||
|
||||
Rule:
|
||||
|
||||
```text
|
||||
agent.heartbeat event
|
||||
→ EventBus live publish
|
||||
→ Scheduler/AgentMonitor updates agents.last_heartbeat_at and tasks.heartbeat_at at a throttled interval
|
||||
```
|
||||
|
||||
Default coalescing interval:
|
||||
|
||||
```text
|
||||
5 seconds or meaningful status change, whichever comes first
|
||||
```
|
||||
|
||||
Recovery uses `agents.last_heartbeat_at`, `tasks.heartbeat_at`, process liveness, and task attempt state. It does not require replaying ephemeral heartbeat events.
|
||||
|
||||
## 5. Command Run Status Semantics
|
||||
|
||||
`command_runs` V1 schema has no explicit `status` column. Runtime derives status:
|
||||
|
||||
| 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` |
|
||||
|
||||
ProjectionStore may expose derived command status. A later schema version may add a physical `status` column if needed.
|
||||
|
||||
## 6. Cross-DB and File Transaction Semantics
|
||||
|
||||
Some durable events refer to project-level DBs or files outside the session DB:
|
||||
|
||||
```text
|
||||
debug-records.db
|
||||
learned-memory.db
|
||||
.air/shared/rules/*.md
|
||||
skills
|
||||
artifact files
|
||||
workspace files
|
||||
```
|
||||
|
||||
SQLite cannot provide one transaction across arbitrary files and DBs. V1.0.0 Alpha uses an outbox/compensation model.
|
||||
|
||||
### 6.1 Session DB First For Intent
|
||||
|
||||
For external side effects:
|
||||
|
||||
```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.
|
||||
```
|
||||
|
||||
### 6.2 Artifact Files
|
||||
|
||||
Artifact files use:
|
||||
|
||||
```text
|
||||
write temp file
|
||||
compute hash/size
|
||||
atomic rename
|
||||
insert artifact row + artifact.created event
|
||||
```
|
||||
|
||||
If the DB insert fails after rename, startup recovery scans orphaned files and either registers or quarantines them.
|
||||
|
||||
### 6.3 Debug Records
|
||||
|
||||
`debug.record.created` means:
|
||||
|
||||
```text
|
||||
session DB records debug-record intent/completion event
|
||||
DebugKnowledgeStore writes debug-records.db
|
||||
if debug-records.db write fails, emit debug.record.failed or task.failed with AirError
|
||||
```
|
||||
|
||||
### 6.4 Memory and Rule Promotion
|
||||
|
||||
`memory.promoted` means:
|
||||
|
||||
```text
|
||||
candidate was approved/promoted by owning service
|
||||
rule/skill/learned-memory write is performed by ExperienceMiner/Curator service
|
||||
session event records completed promotion and target ref
|
||||
```
|
||||
|
||||
If the file/DB write fails, emit a failure event and leave the candidate unpromoted or pending repair.
|
||||
|
||||
## 7. Summary and Compaction Ownership
|
||||
|
||||
Only `summary.created` inserts a `summaries` row.
|
||||
|
||||
`context.compaction.completed` records compaction task completion and references the created summary:
|
||||
|
||||
```ts
|
||||
interface ContextCompactionCompletedPayload {
|
||||
task_id?: string
|
||||
agent_id?: string
|
||||
summary_id: string
|
||||
range_start_message_id?: string
|
||||
range_end_message_id?: string
|
||||
token_estimate_before?: number
|
||||
token_estimate_after?: number
|
||||
}
|
||||
```
|
||||
|
||||
Sequence:
|
||||
|
||||
```text
|
||||
context.compaction.requested
|
||||
context.compaction.started
|
||||
summary.created
|
||||
context.compaction.completed
|
||||
```
|
||||
|
||||
This avoids duplicate summary rows.
|
||||
|
||||
## 8. Permission Layering
|
||||
|
||||
Permission evaluation order:
|
||||
|
||||
```text
|
||||
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 if required
|
||||
```
|
||||
|
||||
Project-level allow does not override task scope. Credential and system-sensitive boundaries override broad project/local allow.
|
||||
|
||||
Canonical decision:
|
||||
|
||||
```ts
|
||||
action: allow | deny | ask_user | block | refuse | announce_then_run
|
||||
grant_scope: none | once | session | project | global
|
||||
```
|
||||
|
||||
## 9. Execution Primitive Semantics
|
||||
|
||||
Claude Code-quality execution is enforced through tool contracts, not only prompts.
|
||||
|
||||
### 9.1 Read-Before-Edit Token
|
||||
|
||||
`fs.read` returns or records a read observation:
|
||||
|
||||
```ts
|
||||
interface FileReadObservation {
|
||||
path: string
|
||||
sha256?: string
|
||||
observed_at: ISOTimeString
|
||||
task_id?: TaskID
|
||||
agent_id?: AgentID
|
||||
}
|
||||
```
|
||||
|
||||
`fs.edit` and `fs.patch` require either:
|
||||
|
||||
```text
|
||||
active task read observation for the target file
|
||||
or explicit expected_existing_sha256
|
||||
```
|
||||
|
||||
### 9.2 Exact Edit Behavior
|
||||
|
||||
`fs.edit` rules:
|
||||
|
||||
1. `old_string` must match exactly.
|
||||
2. If `replace_all` is false, `old_string` must occur exactly once.
|
||||
3. If no match or ambiguous match, fail with `tool_error` and no file write.
|
||||
4. The tool does not guess indentation or nearby replacements.
|
||||
5. Successful edit emits a diff artifact.
|
||||
|
||||
### 9.3 Patch Behavior
|
||||
|
||||
`fs.patch` rules:
|
||||
|
||||
1. Patch paths must be within task scope and permission policy.
|
||||
2. Rejected hunks become artifacts.
|
||||
3. Partial patch application is allowed only if the patch tool can prove unchanged rejected paths were not written; otherwise fail atomically.
|
||||
4. Successful patch emits a diff artifact.
|
||||
|
||||
### 9.4 Completion Gate
|
||||
|
||||
A code-changing WorkerResult cannot be `completed` unless:
|
||||
|
||||
```text
|
||||
required verification passed, or
|
||||
verification is explicitly skipped with reason/evidence/risk, and fallback_allowed is true
|
||||
```
|
||||
|
||||
## 10. Project Scanner Semantics
|
||||
|
||||
Project initialization scanner collects full directory tree metadata with no directory exclusion and no depth limit.
|
||||
|
||||
Rationale: the user wants complete project shape visibility, and directory tree metadata alone is not comparable to reading file contents.
|
||||
|
||||
Safety boundaries:
|
||||
|
||||
1. Do not recurse through symlinks by default; record symlink target metadata instead.
|
||||
2. Handle permission errors as entries with error metadata, not fatal scanner failure.
|
||||
3. Avoid reading file contents during tree scan.
|
||||
4. Record special file types without opening them.
|
||||
5. Provide progress and cancellation hooks for UI responsiveness.
|
||||
6. Detect obvious filesystem cycles or mount anomalies and record them as scanner warnings.
|
||||
|
||||
No directories such as `.git`, `node_modules`, build directories, or vendor directories are excluded from the directory tree.
|
||||
|
||||
## 11. Learning, Skills, and Experience Lifecycle
|
||||
|
||||
ExperienceMiner produces candidates; it does not silently rewrite durable project rules or skills unless assigned an explicit promotion task.
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
Candidate types:
|
||||
|
||||
```text
|
||||
project_rule
|
||||
toolchain_rule
|
||||
skill_update
|
||||
debug_experience
|
||||
```
|
||||
|
||||
Promotion requirements:
|
||||
|
||||
| Candidate | Promotion requirement |
|
||||
|---|---|
|
||||
| debug_experience | verified failure + fix evidence |
|
||||
| project_rule | repeated pattern or explicit user confirmation |
|
||||
| toolchain_rule | verified toolchain evidence or explicit user confirmation |
|
||||
| skill_update | reviewed patch and trust policy approval |
|
||||
|
||||
Skills use Claude Skills-style directory structure where applicable:
|
||||
|
||||
```text
|
||||
SKILL.md
|
||||
scripts/
|
||||
references/
|
||||
assets/
|
||||
```
|
||||
|
||||
Skill invocation must pass through capability/tool trust rules when it causes side effects.
|
||||
|
||||
## 12. C++ Diagnostic Ownership
|
||||
|
||||
`toolchain-cpp` owns deterministic extraction of compiler/test/static-analysis diagnostics and semantic signatures.
|
||||
|
||||
LLM-based interpretation belongs to runtime Debugger/Reviewer context, not hidden inside low-level toolchain code, unless a future injected diagnostic interpretation service is explicitly added.
|
||||
|
||||
This preserves package direction:
|
||||
|
||||
```text
|
||||
toolchain-cpp → contracts
|
||||
runtime/debugger → llm/provider facade
|
||||
```
|
||||
|
||||
## 13. V1.0.0 Alpha Cut Line
|
||||
|
||||
V1.0.0 Alpha includes:
|
||||
|
||||
```text
|
||||
complete C++ configure/build/test/static-analysis/debug/fix/review workflow
|
||||
local and built-in capability manifests
|
||||
GUI/network evidence tools
|
||||
TUI/HUD projection
|
||||
release gates for Linux tier 1
|
||||
```
|
||||
|
||||
V1.0.0 Alpha may defer:
|
||||
|
||||
```text
|
||||
third-party plugin registry/signing
|
||||
container sandboxing
|
||||
multi-machine scheduling
|
||||
Windows-native deep support
|
||||
advanced semantic merge
|
||||
production bitmap image generation providers
|
||||
```
|
||||
|
||||
## 14. FK-Off Application Invariants
|
||||
|
||||
With `foreign_keys = OFF`, the runtime must enforce referential consistency in application code.
|
||||
|
||||
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`, `tool_runs.agent_id` must reference existing rows when not null.
|
||||
5. `command_runs.task_id`, `command_runs.agent_id`, `command_runs.tool_run_id` must reference existing rows when not null.
|
||||
6. `workspaces.task_id`, `workspaces.agent_id` must reference existing rows when not null.
|
||||
7. `diagnostics.command_run_id`, `diagnostics.artifact_id` must reference existing rows when not null.
|
||||
8. `evidence_refs` foreign columns must reference existing rows when not null.
|
||||
|
||||
Enforcement:
|
||||
|
||||
- Repository insert methods validate foreign key existence before insert.
|
||||
- On session startup recovery, run orphan scan: rows referencing deleted parents are logged and either re-parented or archived.
|
||||
- Release gate includes orphan scan validation.
|
||||
|
||||
## 15. Workspace GC Policy
|
||||
|
||||
`<project>/.air/local/workspaces/` and the `workspaces` table grow over time.
|
||||
|
||||
Retention rules:
|
||||
|
||||
1. Active workspaces (`status = active`) are preserved until merge or explicit cancel.
|
||||
2. Merged workspaces (`status = merged`) are preserved for 7 days after `merged_at`, then cleaned.
|
||||
3. Conflicted workspaces (`status = conflicted`) are preserved until user/system decision, then moved to `abandoned`.
|
||||
4. Abandoned workspaces are preserved for 3 days, then cleaned.
|
||||
5. `cleaned` status means filesystem artifacts removed; DB row retained with metadata.
|
||||
|
||||
Cleanup runs on session startup and periodically during idle.
|
||||
|
||||
## 16. Direct Mode Semantics
|
||||
|
||||
`/direct` enters a foreground execution lane where Main Agent acts with Executor-level permissions without dispatching to Scheduler.
|
||||
|
||||
Rules:
|
||||
|
||||
1. Direct mode is a Main Agent state, not a separate agent type.
|
||||
2. Direct mode uses `permission_template: "main_direct"`.
|
||||
3. Direct mode tasks write to the main workspace only; no worktree creation.
|
||||
4. Direct mode does not block Scheduler-owned background tasks from running concurrently.
|
||||
5. `/done` exits direct mode, triggers evidence collection, and returns to IDLE.
|
||||
6. Direct mode changes are recorded in the event log with `source.kind = "main"` and metadata indicating direct mode.
|
||||
|
||||
## 17. ExperienceMiner Trigger Ownership
|
||||
|
||||
ExperienceMiner is triggered by:
|
||||
|
||||
1. `debug.record.created` event → Scheduler creates `mine_experience` task.
|
||||
2. Session end → Scheduler creates final `mine_experience` task.
|
||||
3. N-turn/tool-call interval (configurable, default 10) → Scheduler creates periodic `mine_experience` task.
|
||||
4. Stale rule/skill discovered during execution → worker emits `memory.candidate.created` with `memory_type = skill_update`, Scheduler creates `mine_experience` task.
|
||||
|
||||
The Scheduler owns trigger creation; ExperienceMiner never self-triggers. Curator periodic dedup runs as a scheduled `mine_experience` task with `memory_type = "curator_dedup"`.
|
||||
|
||||
## 18. Doctor Self-Bootstrap
|
||||
|
||||
Doctor validates its own prerequisites before running capability checks:
|
||||
|
||||
1. Verify Bun runtime version.
|
||||
2. Verify SQLite availability.
|
||||
3. Verify basic shell access.
|
||||
4. Verify `.air/` directory writability.
|
||||
5. Then proceed to capability/dependency checks.
|
||||
|
||||
If self-bootstrap fails, Doctor reports a `blocking` issue and skips remaining checks.
|
||||
|
||||
## 19. air restore Semantics
|
||||
|
||||
`air restore` supports three granularities:
|
||||
|
||||
1. `air restore file <path>` — restore most recent backup of a single file.
|
||||
2. `air restore time <timestamp>` — restore all files backed up since a given timestamp.
|
||||
3. `air restore session <session-id>` — restore all files backed up during a specific session.
|
||||
|
||||
All restore operations use the git-backed backup repository at `<project>/.air/local/backups/`. Restore creates a new commit with the restored content, preserving full history.
|
||||
485
AirPlan/docs/architecture/scheduler-state-machine-v1.md
Normal file
485
AirPlan/docs/architecture/scheduler-state-machine-v1.md
Normal file
@@ -0,0 +1,485 @@
|
||||
# AirCoding Scheduler State Machine V1
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Canonical Scheduler state machine for V1.0.0 Alpha skeleton
|
||||
|
||||
This document defines the MVP Scheduler lifecycle, task states, retry policy, workspace/merge flow, heartbeat handling, and escalation rules.
|
||||
|
||||
The Scheduler is not a coding agent. It is the orchestration service that reads TaskGraph state, launches worker agents, monitors progress, persists transitions, and escalates when architecture or user decisions are required.
|
||||
|
||||
## 1. Inputs and Outputs
|
||||
|
||||
Primary inputs:
|
||||
|
||||
```text
|
||||
TaskSpec records
|
||||
task_dependencies
|
||||
RuntimeEvents
|
||||
Architecture impact assessments
|
||||
Permission decisions
|
||||
WorkerResult records
|
||||
Heartbeat/progress events
|
||||
Resource availability snapshot
|
||||
```
|
||||
|
||||
Primary outputs:
|
||||
|
||||
```text
|
||||
task/agent/workspace events
|
||||
child agent processes
|
||||
workspace creation/merge requests
|
||||
retry attempts
|
||||
blocked/escalation reports
|
||||
ProjectionStore updates via EventBus
|
||||
```
|
||||
|
||||
The Scheduler persists all durable state through EventStore and domain tables. In-memory queues are rebuildable from SQLite.
|
||||
|
||||
Task dependencies use one edge model across TaskSpec, events, DB, and Scheduler memory:
|
||||
|
||||
```ts
|
||||
interface TaskDependencySpec {
|
||||
depends_on_task_id: TaskID
|
||||
dependency_type: "hard" | "soft" | "conflict" | "serialization"
|
||||
reason?: string
|
||||
source?: "architecture" | "scheduler" | "worker" | "user" | "system"
|
||||
}
|
||||
```
|
||||
|
||||
Architecture Designer may create planned `hard`/`soft`/`serialization` edges. Scheduler may dynamically add `conflict` or `serialization` edges after write-area/resource analysis, but those inferred edges must be persisted through `task_dependencies` and durable events so restart recovery does not need to rediscover them.
|
||||
|
||||
## 2. Task Status Model
|
||||
|
||||
Task table status values:
|
||||
|
||||
```text
|
||||
pending | running | completed | failed | blocked | cancelled | interrupted
|
||||
```
|
||||
|
||||
State meaning:
|
||||
|
||||
| Status | Meaning | Scheduler action |
|
||||
|---|---|---|
|
||||
| `pending` | task exists but is not active | wait for dependencies/resources/write-set availability |
|
||||
| `running` | task has an assigned agent/attempt | monitor heartbeat, events, timeout, result |
|
||||
| `completed` | task met acceptance and produced WorkerResult | unblock dependents and consider merge/review |
|
||||
| `failed` | task attempted and did not meet goal | retry, skip if allowed, or escalate |
|
||||
| `blocked` | task cannot continue without higher-level decision | route to Main/Architecture Designer/user as needed |
|
||||
| `cancelled` | task intentionally stopped | cancel dependents or replan |
|
||||
| `interrupted` | task stopped but can be resumed or requeued | resume/requeue after requirement/control decision |
|
||||
|
||||
## 3. Task Attempt Model
|
||||
|
||||
Each run creates a `task_attempts` row.
|
||||
|
||||
```text
|
||||
task.created
|
||||
→ task.started + task_attempts.insert(attempt_index=N)
|
||||
→ agent.started
|
||||
→ terminal event:
|
||||
task.completed
|
||||
task.failed
|
||||
task.blocked
|
||||
task.cancelled
|
||||
task.interrupted
|
||||
```
|
||||
|
||||
Attempt indexes are monotonically increasing per task.
|
||||
|
||||
Failure signature is normalized from:
|
||||
|
||||
```text
|
||||
error_kind + tool/command name + semantic diagnostic signature + failure location + concise failure summary
|
||||
```
|
||||
|
||||
Repeated identical failure signatures consume retry budget faster than new failure signatures.
|
||||
|
||||
## 4. Scheduler Lifecycle
|
||||
|
||||
Top-level Scheduler states:
|
||||
|
||||
```text
|
||||
IDLE
|
||||
→ LOADING_GRAPH
|
||||
→ PLANNING_WAVE
|
||||
→ DISPATCHING
|
||||
→ MONITORING
|
||||
→ COLLECTING_RESULTS
|
||||
→ MERGING
|
||||
→ REVIEWING_WAVE
|
||||
→ REPAIRING_OR_CONTINUING
|
||||
→ COMPLETED | BLOCKED | CANCELLED
|
||||
```
|
||||
|
||||
### `IDLE`
|
||||
|
||||
Scheduler has no active graph or all graphs are terminal.
|
||||
|
||||
Transitions:
|
||||
|
||||
- `task.created` / execution request → `LOADING_GRAPH`
|
||||
- requirement change affecting active work → `LOADING_GRAPH`
|
||||
|
||||
### `LOADING_GRAPH`
|
||||
|
||||
Reads tasks, dependencies, attempts, agents, workspaces, and recent architecture/permission events from DB.
|
||||
|
||||
Actions:
|
||||
|
||||
1. Reconstruct TaskGraph.
|
||||
2. Detect orphaned running tasks/agents.
|
||||
3. Convert missing heartbeat/process to `agent.lost` and then `task.failed` or `task.interrupted`.
|
||||
4. Validate dependency references.
|
||||
5. Compute blocked/unblocked sets.
|
||||
|
||||
Transitions:
|
||||
|
||||
- valid runnable graph → `PLANNING_WAVE`
|
||||
- no runnable tasks and blocked tasks exist → `BLOCKED`
|
||||
- all terminal success → `COMPLETED`
|
||||
- graph invalid beyond scheduler repair → `BLOCKED`
|
||||
|
||||
### `PLANNING_WAVE`
|
||||
|
||||
Computes next wave of tasks.
|
||||
|
||||
Inputs:
|
||||
|
||||
```text
|
||||
hard dependencies
|
||||
soft dependencies
|
||||
conflict/serialization dependencies
|
||||
write_area and expected_files
|
||||
resource snapshot
|
||||
model policy
|
||||
permission profile
|
||||
workspace strategy
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Hard dependencies must be completed before dispatch.
|
||||
2. Soft dependencies influence priority/context but may run concurrently if Scheduler decides it is safe.
|
||||
3. Tasks with different write areas may run concurrently.
|
||||
4. Tasks with same file but provably different regions may run concurrently in separate worktrees.
|
||||
5. Same write area with uncertain conflict serializes by default.
|
||||
6. Reviewer tasks are read-only and may run concurrently with each other, but not against unstable unmerged write outputs unless they target a workspace snapshot.
|
||||
7. Debugger tasks may serialize with tasks touching the same failure surface.
|
||||
8. Machine resources constrain concurrency.
|
||||
|
||||
Wave output:
|
||||
|
||||
```ts
|
||||
interface SchedulerWavePlan {
|
||||
wave_id: string
|
||||
runnable_task_ids: string[]
|
||||
serialized_task_ids: string[]
|
||||
workspace_assignments: Record<string, WorkspacePlan>
|
||||
model_assignments: Record<string, ModelAssignment>
|
||||
reason: string
|
||||
}
|
||||
```
|
||||
|
||||
Transitions:
|
||||
|
||||
- runnable wave exists → `DISPATCHING`
|
||||
- no runnable wave but graph not terminal → `BLOCKED`
|
||||
|
||||
### `DISPATCHING`
|
||||
|
||||
Creates workspaces if needed, assembles context, and starts child agents.
|
||||
|
||||
Actions per task:
|
||||
|
||||
1. Create workspace (`main`, `worktree`, or `isolated_copy`).
|
||||
2. Create `task.started` and `agent.started` events.
|
||||
3. Write `agent.start` control message containing `TaskSpec`, `ContextPack`, and runtime context.
|
||||
4. Record attempt row.
|
||||
|
||||
Dispatch failures:
|
||||
|
||||
- permission denied → `task.blocked`
|
||||
- workspace create failure → retry if recoverable, otherwise `task.failed`
|
||||
- context assembly failure → `task.failed` or `task.blocked` depending on reason
|
||||
- process start failure → `task.failed`
|
||||
|
||||
Transition: `MONITORING`.
|
||||
|
||||
### `MONITORING`
|
||||
|
||||
Tracks active agents.
|
||||
|
||||
Inputs:
|
||||
|
||||
```text
|
||||
agent.heartbeat
|
||||
task.progress
|
||||
tool/command events
|
||||
process exit
|
||||
soft timeout
|
||||
hard timeout
|
||||
user interruption
|
||||
requirement.changed
|
||||
```
|
||||
|
||||
Heartbeat policy:
|
||||
|
||||
```text
|
||||
agent emits heartbeat periodically
|
||||
Scheduler updates agents.last_heartbeat_at and tasks.heartbeat_at
|
||||
missing heartbeat past threshold → inspect process
|
||||
process alive but silent → send status ping or soft cancel depending on timeout
|
||||
process gone without result → agent.lost
|
||||
```
|
||||
|
||||
Timeout policy:
|
||||
|
||||
| Timeout | Action |
|
||||
|---|---|
|
||||
| soft timeout | ask agent for checkpoint/status; Scheduler may extend if progress is credible |
|
||||
| hard timeout | cancel/kill worker; emit `agent.lost` or `agent.cancelled`; mark task failed/interrupted |
|
||||
|
||||
Requirement change policy:
|
||||
|
||||
1. Main Agent records `requirement.changed`.
|
||||
2. Scheduler pauses affected dispatch decisions.
|
||||
3. Architecture Designer assesses impact when change may affect interface/architecture/product goals.
|
||||
4. Implementation-only non-conflicting change may be silently absorbed.
|
||||
5. Architecture-level impact uses `architecture.impact.completed` and may require user confirmation or replan.
|
||||
|
||||
Transitions:
|
||||
|
||||
- all active agents terminal → `COLLECTING_RESULTS`
|
||||
- user/global cancellation → `CANCELLED`
|
||||
- architecture/user blocker → `BLOCKED`
|
||||
|
||||
### `COLLECTING_RESULTS`
|
||||
|
||||
Consumes WorkerResult and terminal task events.
|
||||
|
||||
Actions:
|
||||
|
||||
1. Validate WorkerResult against output contract.
|
||||
2. Persist artifacts/evidence references.
|
||||
3. Mark attempt terminal.
|
||||
4. Classify task terminal status.
|
||||
5. Compute dependency unblocks.
|
||||
|
||||
Status mapping:
|
||||
|
||||
| WorkerResult status | Task status |
|
||||
|---|---|
|
||||
| `completed` | `completed` |
|
||||
| `failed` | `failed` pending retry/skip decision |
|
||||
| `blocked` | `blocked` |
|
||||
| `cancelled` | `cancelled` or `interrupted` depending on resumability |
|
||||
|
||||
Transition:
|
||||
|
||||
- write workspaces need merge → `MERGING`
|
||||
- no merge needed but review required → `REVIEWING_WAVE`
|
||||
- more work remains → `REPAIRING_OR_CONTINUING`
|
||||
- all done → `COMPLETED`
|
||||
|
||||
### `MERGING`
|
||||
|
||||
Merges completed workspace outputs back into the target workspace.
|
||||
|
||||
Strategies:
|
||||
|
||||
```text
|
||||
main → no merge
|
||||
worktree → git merge or patch apply
|
||||
isolated_copy → copy-back or patch apply
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Merge only tasks with successful WorkerResult unless explicitly recovering artifacts.
|
||||
2. Serialize merges touching overlapping write areas.
|
||||
3. Persist `workspace.merge.started` and terminal merge event.
|
||||
4. Conflict creates `workspace.merge.conflicted` and either schedules Debugger/repair or blocks.
|
||||
|
||||
Conflict handling:
|
||||
|
||||
| Conflict | Scheduler action |
|
||||
|---|---|
|
||||
| trivial patch conflict | schedule repair/debugger or retry serially |
|
||||
| semantic conflict | route to Reviewer/Architecture Designer |
|
||||
| architecture/interface conflict | block and request Architecture impact assessment |
|
||||
| user requirement conflict | block and ask Main Agent/user |
|
||||
|
||||
Transition:
|
||||
|
||||
- merge success and review needed → `REVIEWING_WAVE`
|
||||
- merge success and more tasks → `REPAIRING_OR_CONTINUING`
|
||||
- merge conflict recoverable → `REPAIRING_OR_CONTINUING`
|
||||
- unrecoverable conflict → `BLOCKED`
|
||||
|
||||
### `REVIEWING_WAVE`
|
||||
|
||||
Schedules review tasks after implementation/debug waves when required by plan or risk.
|
||||
|
||||
Reviewers are read-only unless a follow-up execute/debug task is created.
|
||||
|
||||
Review result handling:
|
||||
|
||||
```text
|
||||
approved → continue
|
||||
minor issue with clear fix → create execute repair task
|
||||
high-severity/security/architecture issue → block or Architecture Designer assessment
|
||||
insufficient evidence → create verification task
|
||||
```
|
||||
|
||||
Transition: `REPAIRING_OR_CONTINUING`.
|
||||
|
||||
### `REPAIRING_OR_CONTINUING`
|
||||
|
||||
Decides next action after a wave.
|
||||
|
||||
Actions:
|
||||
|
||||
1. Retry failed tasks within budget.
|
||||
2. Create repair tasks from review/debug output.
|
||||
3. Skip allowed failed tasks only when acceptance criteria permit fallback.
|
||||
4. Recompute graph and continue.
|
||||
5. Escalate if architecture/user decision is required.
|
||||
|
||||
Transition:
|
||||
|
||||
- more runnable tasks → `PLANNING_WAVE`
|
||||
- blocked → `BLOCKED`
|
||||
- all acceptance criteria met → `COMPLETED`
|
||||
- cancelled → `CANCELLED`
|
||||
|
||||
## 5. Retry Policy
|
||||
|
||||
Default retry budget: task-specific `TaskSpec.constraints.retry_budget`, usually 3–5.
|
||||
|
||||
Retry rules:
|
||||
|
||||
1. Retry only when failure is plausibly recoverable.
|
||||
2. First retry may use same agent strategy with corrected context.
|
||||
3. Later retries should change one dimension: model, context, command strategy, serialization, or Debugger involvement.
|
||||
4. Identical failure signature after multiple attempts triggers escalation faster.
|
||||
5. Environment/kernel/toolchain impossibility becomes `blocked`, not infinite retry.
|
||||
6. Architecture/interface mismatch routes to Architecture Designer.
|
||||
7. If fallback is allowed and the failed task is non-critical, Scheduler may skip after recording evidence and risk.
|
||||
|
||||
Retry decision shape:
|
||||
|
||||
```ts
|
||||
interface RetryDecision {
|
||||
action: "retry" | "retry_serial" | "debug" | "skip" | "block" | "cancel"
|
||||
reason: string
|
||||
next_model_policy?: "scheduler_forced" | "agent_select"
|
||||
required_context_refs?: string[]
|
||||
}
|
||||
```
|
||||
|
||||
## 6. Model Assignment Policy
|
||||
|
||||
Scheduler chooses per task:
|
||||
|
||||
```text
|
||||
scheduler_forced → exact model assigned by Scheduler
|
||||
agent_select → agent may choose within allowed model/capability constraints
|
||||
```
|
||||
|
||||
Guidelines:
|
||||
|
||||
- Implementation tasks with hidden complexity should use strong coding-capable model assignment or constrained agent choice.
|
||||
- Cross-model review should be scheduler-forced.
|
||||
- Debug tasks may switch models after repeated failures.
|
||||
- Cheap/simple tasks may use lower-cost models when quality risk is low.
|
||||
|
||||
## 7. Resource-Aware Concurrency
|
||||
|
||||
Scheduler considers:
|
||||
|
||||
```text
|
||||
CPU cores
|
||||
RAM pressure
|
||||
disk space
|
||||
active command count
|
||||
LLM provider rate limits
|
||||
toolchain locks
|
||||
workspace write conflicts
|
||||
user-configured max concurrency
|
||||
```
|
||||
|
||||
Concurrency can shrink or expand dynamically. Running tasks are not killed solely because resources become tighter unless the system is at risk; new dispatch is paused first.
|
||||
|
||||
## 8. Escalation Model Hooks
|
||||
|
||||
Scheduler does not ask the user directly except through Main Agent/PermissionEngine.
|
||||
|
||||
Escalation routes:
|
||||
|
||||
| Trigger | Route |
|
||||
|---|---|
|
||||
| product/user choice needed | Main Agent |
|
||||
| architecture/interface change | Architecture Designer → Main Agent/user if needed |
|
||||
| permission decision | PermissionEngine → Main Agent/UI |
|
||||
| environment impossible | Main Agent with Doctor/Debugger evidence |
|
||||
| repeated implementation failure | Debugger or Main Agent based on recoverability |
|
||||
| high-severity review finding | Main Agent + Architecture Designer if design-level |
|
||||
|
||||
## 9. Recovery on Restart
|
||||
|
||||
On startup/resume:
|
||||
|
||||
1. Load `tasks` where status is `running` or `interrupted`.
|
||||
2. Load active `agents` and `workspaces`.
|
||||
3. Check process liveness where PID is known.
|
||||
4. If process is alive and IPC can reconnect, resume monitoring.
|
||||
5. If process is gone, emit `agent.lost`; mark task failed/interrupted based on resumability.
|
||||
6. Preserve workspaces until merge/cleanup decision is recorded.
|
||||
7. Rebuild queue from pending/failed-with-retry tasks.
|
||||
|
||||
## 10. Terminal Graph States
|
||||
|
||||
### `COMPLETED`
|
||||
|
||||
All required tasks completed and required review/verification gates passed or documented as skipped by policy.
|
||||
|
||||
### `BLOCKED`
|
||||
|
||||
No runnable work remains because a decision or external condition is required. Scheduler must produce a concise blocker report with:
|
||||
|
||||
```text
|
||||
blocked task IDs
|
||||
reason
|
||||
required decision
|
||||
available evidence
|
||||
safe suggested next step
|
||||
```
|
||||
|
||||
### `CANCELLED`
|
||||
|
||||
User/system cancellation propagated to running agents, task statuses terminalized, and workspaces left in a recoverable state.
|
||||
|
||||
## 11. V1.0.0 Alpha Cut Line
|
||||
|
||||
The V1.0.0 Alpha skeleton must implement:
|
||||
|
||||
1. DB-backed TaskGraph loading.
|
||||
2. Hard/soft dependency handling.
|
||||
3. Write-area serialization and basic worktree workspace strategy.
|
||||
4. Child process dispatch via NDJSON IPC.
|
||||
5. Heartbeat timeout detection.
|
||||
6. Retry budget and failure signature tracking.
|
||||
7. Workspace merge success/conflict events.
|
||||
8. Review wave support.
|
||||
9. Restart recovery for running/lost agents.
|
||||
10. Escalation report generation.
|
||||
|
||||
Advanced optimization can wait:
|
||||
|
||||
```text
|
||||
fine-grained AST write-set prediction
|
||||
multi-machine scheduling
|
||||
provider rate-limit optimization
|
||||
automatic semantic merge resolution
|
||||
learning-based retry strategy
|
||||
```
|
||||
283
AirPlan/docs/architecture/scope-escalation-v1.md
Normal file
283
AirPlan/docs/architecture/scope-escalation-v1.md
Normal file
@@ -0,0 +1,283 @@
|
||||
# AirCoding Scope Escalation Model V1
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Canonical scope escalation model for V1.0.0 Alpha skeleton
|
||||
|
||||
This document defines when agents may continue silently, when Scheduler must route to Architecture Designer, and when Main Agent/user confirmation is required.
|
||||
|
||||
## 1. Core Principle
|
||||
|
||||
Implementation-level changes that do not conflict with existing requirements, interfaces, architecture, or permissions may continue silently.
|
||||
|
||||
Architecture-level, product-level, safety-sensitive, or user-visible requirement changes require assessment and may require user confirmation depending on permission mode and impact.
|
||||
|
||||
## 2. Escalation Levels
|
||||
|
||||
```ts
|
||||
type ScopeImpactLevel =
|
||||
| "implementation"
|
||||
| "interface"
|
||||
| "architecture"
|
||||
| "product"
|
||||
| "permission"
|
||||
| "environment"
|
||||
| "policy"
|
||||
```
|
||||
|
||||
| Level | Meaning | Default action |
|
||||
|---|---|---|
|
||||
| `implementation` | internal code details within accepted scope | silent continue |
|
||||
| `interface` | public API/schema/module boundary changes | Architecture Designer assessment |
|
||||
| `architecture` | component responsibility/data flow/runtime model changes | Architecture Designer + likely user-visible summary |
|
||||
| `product` | changes user-facing goal, behavior, UX, or acceptance criteria | Main Agent/user confirmation |
|
||||
| `permission` | action exceeds current permission grant | PermissionEngine/Main Agent |
|
||||
| `environment` | dependency/toolchain/platform blocker | Doctor/Debugger, then Main Agent if unresolved |
|
||||
| `policy` | safety/security/legal/project policy issue | block until explicit decision or refuse |
|
||||
|
||||
## 3. Silent Continue Criteria
|
||||
|
||||
An agent may continue without escalation when all are true:
|
||||
|
||||
1. Change is inside TaskSpec scope/write area.
|
||||
2. Acceptance criteria remain unchanged.
|
||||
3. Public interfaces and architecture decisions remain unchanged.
|
||||
4. No denied path, credential, system-sensitive, or unapproved network access is needed.
|
||||
5. Verification plan remains valid.
|
||||
6. Change does not contradict project rules or latest user instructions.
|
||||
7. Risk is low or normal for the task type.
|
||||
|
||||
Examples:
|
||||
|
||||
```text
|
||||
rename local variable
|
||||
adjust private helper implementation
|
||||
fix compile error without API change
|
||||
add missing test for accepted behavior
|
||||
change internal algorithm with same contract
|
||||
```
|
||||
|
||||
## 4. Architecture Designer Assessment Criteria
|
||||
|
||||
Route to Architecture Designer when any are true:
|
||||
|
||||
1. Public function/class/module interface must change.
|
||||
2. DB schema or persisted data shape must change.
|
||||
3. IPC/event/tool contract must change.
|
||||
4. Dependency graph or component responsibility changes.
|
||||
5. Task requires new subsystem/capability not in plan.
|
||||
6. Multiple tasks conflict semantically, not just textually.
|
||||
7. A user requirement change may affect architecture.
|
||||
8. Repeated failures indicate the plan itself is wrong.
|
||||
|
||||
Architecture Designer outputs `architecture.impact.completed`:
|
||||
|
||||
```ts
|
||||
interface ArchitectureImpactCompletedPayload {
|
||||
assessment_id: string
|
||||
requirement_change_id?: string
|
||||
impact_level: "implementation" | "interface" | "architecture" | "product"
|
||||
decision: "silent_continue" | "requires_user_confirmation" | "requires_replan" | "reject_or_escalate"
|
||||
summary: string
|
||||
affected_task_ids?: string[]
|
||||
evidence_refs?: EvidenceLink[]
|
||||
}
|
||||
```
|
||||
|
||||
## 5. User Confirmation Criteria
|
||||
|
||||
Main Agent asks the user when any are true:
|
||||
|
||||
1. Product behavior or acceptance criteria changes.
|
||||
2. Architecture Designer marks `requires_user_confirmation`.
|
||||
3. Low-permission mode requires approval for the planned action.
|
||||
4. Credentials or system-sensitive operations are involved.
|
||||
5. Migration or destructive/shared-state operation is involved.
|
||||
6. Safety/policy boundary requires explicit authorization.
|
||||
7. Failure cannot be resolved without user preference or external input.
|
||||
|
||||
High-permission mode may auto-execute many actions after visible `announce_then_run`, but cannot bypass:
|
||||
|
||||
```text
|
||||
credentials
|
||||
system_sensitive
|
||||
migration confirmation
|
||||
policy refusal boundary
|
||||
destructive/shared-state actions requiring explicit confirmation
|
||||
```
|
||||
|
||||
## 6. Environment Escalation
|
||||
|
||||
Environment/toolchain issues follow:
|
||||
|
||||
```text
|
||||
worker detects issue
|
||||
→ Doctor/Debugger evidence
|
||||
→ if fix is allowlisted and permission mode allows: announce_then_run or ask
|
||||
→ if fix fails or unsupported platform: Main Agent blocker report
|
||||
→ if architecture assumptions invalid: Architecture Designer assessment
|
||||
```
|
||||
|
||||
Examples requiring environment escalation:
|
||||
|
||||
```text
|
||||
missing compiler/toolchain
|
||||
kernel feature unavailable
|
||||
package manager unavailable
|
||||
insufficient disk space
|
||||
X/display backend missing for GUI evidence
|
||||
```
|
||||
|
||||
## 7. Permission Escalation
|
||||
|
||||
PermissionEngine returns an action plus a grant scope:
|
||||
|
||||
```text
|
||||
action: allow | deny | ask_user | block | refuse | announce_then_run
|
||||
grant_scope: none | once | session | project | global
|
||||
```
|
||||
|
||||
Routes:
|
||||
|
||||
| Action | Route |
|
||||
|---|---|
|
||||
| `allow` | execute according to `grant_scope`; create backup first when `backup_required` is true |
|
||||
| `announce_then_run` | visible notice, auto-execute if not interrupted; grant is bounded by `grant_scope` |
|
||||
| `ask_user` | Main Agent/UI prompt |
|
||||
| `deny` | do not execute this request; caller may choose another safe path |
|
||||
| `block` | task.blocked |
|
||||
| `refuse` | policy_error and cancellation/blocker |
|
||||
|
||||
## 8. Requirement Change Handling
|
||||
|
||||
When the user changes requirements during execution:
|
||||
|
||||
```text
|
||||
Main Agent records requirement.changed
|
||||
Scheduler pauses affected dispatch/merge decisions
|
||||
Architecture Designer assesses if needed
|
||||
Scheduler cancels, interrupts, replans, or continues affected tasks
|
||||
Main Agent reports visible impact summary
|
||||
```
|
||||
|
||||
Classification:
|
||||
|
||||
| Change | Handling |
|
||||
|---|---|
|
||||
| clarification only | update context; continue |
|
||||
| implementation detail | Scheduler updates pending tasks; running tasks may continue if unaffected |
|
||||
| scope change | interrupt affected tasks and replan |
|
||||
| architecture change | Architecture Designer assessment |
|
||||
| cancellation | cancel affected tasks and preserve workspaces/artifacts |
|
||||
|
||||
## 9. Worker Self-Escalation Contract
|
||||
|
||||
Workers return `blocked` instead of improvising when they detect:
|
||||
|
||||
```text
|
||||
architecture/interface mismatch
|
||||
permission denial
|
||||
missing product decision
|
||||
unsupported environment condition
|
||||
unsafe requested behavior
|
||||
verification cannot be run and acceptance depends on it
|
||||
TaskSpec scope insufficient for necessary change
|
||||
```
|
||||
|
||||
WorkerResult blocker fields:
|
||||
|
||||
```ts
|
||||
interface BlockerReport {
|
||||
impact_level: ScopeImpactLevel
|
||||
reason: string
|
||||
required_decision: string
|
||||
options?: Array<{ label: string; tradeoff: string }>
|
||||
evidence_refs?: EvidenceLink[]
|
||||
suggested_default?: string
|
||||
}
|
||||
```
|
||||
|
||||
## 10. Scheduler Escalation Decision
|
||||
|
||||
Scheduler maps task/agent/tool events to one of:
|
||||
|
||||
```text
|
||||
continue
|
||||
retry
|
||||
retry_serial
|
||||
debug
|
||||
ask_permission
|
||||
architecture_assessment
|
||||
ask_user
|
||||
cancel
|
||||
refuse
|
||||
```
|
||||
|
||||
Decision inputs:
|
||||
|
||||
```text
|
||||
error kind
|
||||
failure signature repetition
|
||||
TaskSpec scope
|
||||
permission result
|
||||
architecture impact
|
||||
verification evidence
|
||||
resource/environment state
|
||||
user permission mode
|
||||
```
|
||||
|
||||
## 11. User-Facing Reports
|
||||
|
||||
Escalation reports should be short and actionable:
|
||||
|
||||
```text
|
||||
What changed or failed
|
||||
Why AirCoding cannot safely continue silently
|
||||
Evidence summary
|
||||
Recommended default action
|
||||
Alternatives if meaningful
|
||||
```
|
||||
|
||||
Do not show implementation noise when the decision is product-level. Do show precise evidence when the decision affects architecture, data loss, security, or environment setup.
|
||||
|
||||
## 12. Examples
|
||||
|
||||
### Silent implementation fix
|
||||
|
||||
A C++ build fails because a private helper has a mismatched parameter type. Executor edits the helper and reruns build/tests. No escalation.
|
||||
|
||||
### Interface-level escalation
|
||||
|
||||
A task discovers the accepted API cannot support required streaming. Executor returns blocked. Architecture Designer assesses interface change and updates plan/ADR before Scheduler continues.
|
||||
|
||||
### Product-level escalation
|
||||
|
||||
User asked for local-only storage, but implementation requires cloud sync to meet a new requirement. Main Agent asks user; no silent change.
|
||||
|
||||
### Environment escalation
|
||||
|
||||
Build requires a missing compiler. Doctor can install it. In high-permission mode this may be announced and run if allowlisted; credentials/system-sensitive steps still ask.
|
||||
|
||||
### Policy escalation
|
||||
|
||||
Requested behavior would steal credentials or hide persistence. AirCoding refuses; no architecture workaround.
|
||||
|
||||
## 13. V1.0.0 Alpha Cut Line
|
||||
|
||||
V1.0.0 Alpha skeleton must implement:
|
||||
|
||||
1. ScopeImpactLevel contract.
|
||||
2. Silent continue checks for workers.
|
||||
3. Worker blocked report schema.
|
||||
4. Architecture impact event route.
|
||||
5. PermissionEngine route integration.
|
||||
6. Scheduler escalation decision table.
|
||||
7. Main Agent blocker/confirmation presentation.
|
||||
|
||||
Post-MVP:
|
||||
|
||||
```text
|
||||
learned escalation classifier
|
||||
risk scoring by code ownership/history
|
||||
interactive impact visualization
|
||||
automated ADR draft generation from repeated escalations
|
||||
```
|
||||
334
AirPlan/docs/architecture/security-model-v1.md
Normal file
334
AirPlan/docs/architecture/security-model-v1.md
Normal file
@@ -0,0 +1,334 @@
|
||||
# AirCoding Security Model V1
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Canonical security model for V1.0.0 Alpha skeleton
|
||||
|
||||
This document defines AirCoding's MVP security boundaries for local coding-agent operation.
|
||||
|
||||
## 1. Security Goals
|
||||
|
||||
AirCoding should:
|
||||
|
||||
1. Protect user code, credentials, system-sensitive files, and git history.
|
||||
2. Allow productive local development, including C++ build directories and `sudo` when appropriate.
|
||||
3. Make risky actions visible and confirmable.
|
||||
4. Keep local evidence useful for debugging without automatic upload.
|
||||
5. Prevent tool/provider/plugin boundaries from bypassing permissions.
|
||||
6. Preserve recoverability through backups, artifacts, and event history.
|
||||
|
||||
## 2. Trust Boundaries
|
||||
|
||||
```text
|
||||
User
|
||||
→ Main Agent/UI
|
||||
→ Runtime services
|
||||
→ ToolRegistry/PermissionEngine
|
||||
→ OS/filesystem/shell/network/provider
|
||||
```
|
||||
|
||||
Boundary rules:
|
||||
|
||||
1. User instructions are intent, not permission bypass.
|
||||
2. LLM output is untrusted until validated by runtime/tool schemas and PermissionEngine.
|
||||
3. Tool inputs are validated before execution.
|
||||
4. Provider responses cannot directly modify files or run commands.
|
||||
5. Plugins/capabilities use the same ToolRegistry and PermissionEngine path as built-ins.
|
||||
6. Session DB/artifacts are local state, not remote telemetry.
|
||||
|
||||
## 3. Permission Profiles
|
||||
|
||||
```ts
|
||||
type PermissionProfile =
|
||||
| "low"
|
||||
| "normal"
|
||||
| "high"
|
||||
| "developer"
|
||||
```
|
||||
|
||||
Profile behavior:
|
||||
|
||||
| Profile | Behavior |
|
||||
|---|---|
|
||||
| `low` | ask for writes/exec/network beyond read-only inspection |
|
||||
| `normal` | allow project-local work; ask for project-outside/system-sensitive/credentials |
|
||||
| `high` | announce-then-run many allowlisted actions; still ask for credentials/system-sensitive/migrations/destructive shared actions |
|
||||
| `developer` | for AirCoding developers; may emit full encrypted diagnostics; still cannot bypass credential/policy rules |
|
||||
|
||||
## 4. Path Security
|
||||
|
||||
Path categories:
|
||||
|
||||
```ts
|
||||
type PathRiskCategory =
|
||||
| "project"
|
||||
| "project_air_shared"
|
||||
| "project_air_local"
|
||||
| "project_build"
|
||||
| "project_git"
|
||||
| "project_outside_user"
|
||||
| "system_sensitive"
|
||||
| "credential_store"
|
||||
| "unknown"
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Resolve symlinks with realpath before deciding risk.
|
||||
2. Project directory reads are allowed by default.
|
||||
3. Project directory writes are allowed by default except protected paths.
|
||||
4. `.git/` is write-protected by default.
|
||||
5. Build directories are unrestricted project paths because C++ workflows need them.
|
||||
6. Project-outside non-system writes require backup then allow/ask depending profile.
|
||||
7. System-sensitive and credential-store paths require explicit confirmation or are blocked.
|
||||
8. Unknown paths are treated conservatively.
|
||||
|
||||
System-sensitive examples:
|
||||
|
||||
```text
|
||||
/etc
|
||||
/usr
|
||||
/bin
|
||||
/sbin
|
||||
/boot
|
||||
/dev
|
||||
/proc
|
||||
/sys
|
||||
system service directories
|
||||
package manager global state
|
||||
```
|
||||
|
||||
Credential-store examples:
|
||||
|
||||
```text
|
||||
~/.ssh
|
||||
~/.gnupg
|
||||
password manager stores
|
||||
cloud credential directories
|
||||
.env files when classified as secret-bearing
|
||||
API key config files
|
||||
```
|
||||
|
||||
## 5. Command Security
|
||||
|
||||
Command risk categories:
|
||||
|
||||
```ts
|
||||
type CommandRisk =
|
||||
| "read_only"
|
||||
| "project_write"
|
||||
| "build_or_test"
|
||||
| "network"
|
||||
| "dependency_install"
|
||||
| "destructive"
|
||||
| "system_sensitive"
|
||||
| "credential_access"
|
||||
| "privilege_escalation"
|
||||
| "unknown"
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. `sudo` alone is not automatically forbidden.
|
||||
2. `sudo` touching system-sensitive paths still requires explicit confirmation.
|
||||
3. Destructive commands are never run silently unless narrowly allowlisted and recoverable.
|
||||
4. Interactive commands are not supported in MVP except through dedicated tools.
|
||||
5. Commands must have cwd and timeout.
|
||||
6. stdout/stderr are captured as artifacts when needed for evidence.
|
||||
7. Shell execution is non-interactive and does not inherit secrets except allowlisted environment variables.
|
||||
|
||||
Destructive examples:
|
||||
|
||||
```text
|
||||
rm -rf
|
||||
reset --hard
|
||||
clean -fd
|
||||
force push
|
||||
dropping databases
|
||||
overwriting user files outside scoped paths
|
||||
killing unrelated processes
|
||||
```
|
||||
|
||||
## 6. Network Security
|
||||
|
||||
Network categories:
|
||||
|
||||
```text
|
||||
provider API calls
|
||||
dependency downloads
|
||||
project-requested network behavior
|
||||
analysis/debug network capture
|
||||
unknown outbound network
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Provider API calls use configured providers only.
|
||||
2. Dependency downloads are managed through Doctor/setup and permission policy.
|
||||
3. Generated/project code network access must match user request or be approved.
|
||||
4. Network capture may require elevated permissions and explicit reason.
|
||||
5. No automatic upload of doctor bundles, debug knowledge, artifacts, screenshots, logs, pcaps, or source code.
|
||||
|
||||
## 7. Credential Handling
|
||||
|
||||
Credential rules:
|
||||
|
||||
1. Secrets are referenced by `auth_ref`, never copied into session DB/events/artifacts.
|
||||
2. Tools must declare whether input/output may contain secrets.
|
||||
3. Provider adapters redact auth headers and API keys from logs.
|
||||
4. Doctor checks existence/shape of credentials without printing values.
|
||||
5. Credential access always requires explicit confirmation unless already granted by a scoped secure config reference.
|
||||
6. LLM-visible context must not include secrets unless the user explicitly requests and the policy allows it.
|
||||
|
||||
## 8. Provider and Prompt Injection Security
|
||||
|
||||
External content includes:
|
||||
|
||||
```text
|
||||
web pages
|
||||
dependency logs
|
||||
compiler output
|
||||
repo files
|
||||
tool output
|
||||
provider responses
|
||||
MCP/plugin output
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. External content is data, not instruction.
|
||||
2. Tool results cannot override runtime policy or project rules.
|
||||
3. Prompt injection suspicion is surfaced to the user/developer log when relevant.
|
||||
4. ContextAssembler separates instruction layers from evidence/tool output layers.
|
||||
5. Provider output must pass tool schema validation before tool execution.
|
||||
|
||||
## 9. Plugin and Capability Security
|
||||
|
||||
Capabilities declare:
|
||||
|
||||
```text
|
||||
tools provided
|
||||
dependencies
|
||||
permissions requested
|
||||
network access
|
||||
artifact types
|
||||
config schema
|
||||
trust level
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Capability install/enable is a permissioned action.
|
||||
2. Capability tools are not privileged above built-ins.
|
||||
3. Capability dependencies are detected/installed by Doctor, not by arbitrary plugin scripts.
|
||||
4. Unknown plugin events cannot be durable unless registered or namespaced and approved.
|
||||
5. Capability updates require the same package/source trust policy as install.
|
||||
|
||||
## 10. Logs, Artifacts, and Export
|
||||
|
||||
Local logs:
|
||||
|
||||
```text
|
||||
~/.air/logs/air.log
|
||||
~/.air/logs/air.developer.log
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. `air.log` is user-readable and contains startup failures, exceptions, and environment configuration issues.
|
||||
2. `air.developer.log` is full debug/performance log encrypted with development-team public key.
|
||||
3. Logs retain seven days by default.
|
||||
4. Session artifacts are project-local and not automatically redacted.
|
||||
5. Export/share/upload requires explicit user action.
|
||||
6. Debug Knowledge sharing requires redaction, preview, and authorization.
|
||||
7. Doctor bundles may include full diagnostics and are encrypted for development-team channel.
|
||||
|
||||
## 11. Backup and Recovery
|
||||
|
||||
Project-outside writes:
|
||||
|
||||
```text
|
||||
backup to <project>/.air/local/backups/ before write
|
||||
```
|
||||
|
||||
Migration:
|
||||
|
||||
```text
|
||||
always ask user
|
||||
backup .air first
|
||||
rollback on failure
|
||||
```
|
||||
|
||||
Workspace merges preserve conflict artifacts and do not discard user work silently.
|
||||
|
||||
## 12. Refusal and Block Conditions
|
||||
|
||||
AirCoding refuses or blocks:
|
||||
|
||||
```text
|
||||
malware, credential theft, stealth, evasion, destructive abuse
|
||||
unauthorized access or exploitation
|
||||
mass targeting or DoS
|
||||
supply-chain compromise
|
||||
unapproved credential access
|
||||
unapproved destructive shared-state actions
|
||||
policy-bypassing requests
|
||||
```
|
||||
|
||||
Defensive security, authorized testing, CTF, and educational work are allowed when authorization context is clear.
|
||||
|
||||
## 13. PermissionEngine API
|
||||
|
||||
```ts
|
||||
interface PermissionRequestContext {
|
||||
session_id: string
|
||||
task_id?: string
|
||||
agent_id?: string
|
||||
tool_name?: string
|
||||
command?: string
|
||||
paths?: string[]
|
||||
network?: boolean
|
||||
requested_action: string
|
||||
reason: string
|
||||
}
|
||||
|
||||
type PermissionAction = "allow" | "deny" | "ask_user" | "block" | "refuse" | "announce_then_run"
|
||||
type PermissionGrantScope = "none" | "once" | "session" | "project" | "global"
|
||||
|
||||
interface PermissionDecision {
|
||||
action: PermissionAction
|
||||
grant_scope: PermissionGrantScope
|
||||
risk_level: "low" | "medium" | "high" | "critical"
|
||||
reason: string
|
||||
required_confirmation?: boolean
|
||||
backup_required?: boolean
|
||||
evidence_refs?: string[]
|
||||
}
|
||||
```
|
||||
|
||||
Permission decisions are recorded with `permission.decision.recorded` when durable.
|
||||
|
||||
## 14. V1.0.0 Alpha Cut Line
|
||||
|
||||
V1.0.0 Alpha skeleton must implement:
|
||||
|
||||
1. Realpath-based path classifier.
|
||||
2. Command risk analyzer.
|
||||
3. Permission profiles.
|
||||
4. Explicit credential/system-sensitive confirmation gates.
|
||||
5. Project-outside backup-before-write path.
|
||||
6. ToolRegistry permission enforcement.
|
||||
7. Provider secret redaction.
|
||||
8. Export/share no-auto-upload rule.
|
||||
9. Security refusal/block handling.
|
||||
10. Permission decision events.
|
||||
|
||||
Post-MVP:
|
||||
|
||||
```text
|
||||
sandboxed command runner
|
||||
seccomp/container profiles
|
||||
plugin signature verification
|
||||
secret scanner integration
|
||||
advanced prompt-injection classifier
|
||||
policy-as-code engine
|
||||
```
|
||||
479
AirPlan/docs/architecture/solution-architecture.md
Executable file
479
AirPlan/docs/architecture/solution-architecture.md
Executable file
@@ -0,0 +1,479 @@
|
||||
# Solution Architecture
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Formal V1 architecture derived from AirCoding Architecture Baseline V1
|
||||
|
||||
## 1. Overview
|
||||
|
||||
AirCoding is a self-owned local AI coding agent/runtime. It is not a Claude Code plugin wrapper. The product provides a Claude Code-quality execution layer, OpenCode/OpenTUI-inspired terminal UI, project-local session persistence, multi-agent orchestration, and language/toolchain capability packages.
|
||||
|
||||
The V1 architecture is Linux-first, TypeScript/Bun-based, event-driven, and project-local by default. C++ is the first deep language profile, while the runtime remains language-agnostic through `toolchain-*` capability packages.
|
||||
|
||||
Core value path:
|
||||
|
||||
```text
|
||||
User requirement
|
||||
→ Main Agent clarification and routing
|
||||
→ Architecture Designer for design/interface decisions
|
||||
→ Scheduler task graph and wave planning
|
||||
→ Executor/Reviewer/Debugger/Compactor/ExperienceMiner workers
|
||||
→ ToolRegistry + PermissionEngine + EventStore
|
||||
→ project-local DB/artifacts/evidence
|
||||
→ TUI/HUD ProjectionStore
|
||||
```
|
||||
|
||||
## 2. Architecture Sources of Truth
|
||||
|
||||
This document summarizes the formal architecture. Detailed V1 baselines remain authoritative for implementation contracts.
|
||||
|
||||
Precedence rule:
|
||||
|
||||
1. `interface-contracts-v1.md` wins for TypeScript public interface shape.
|
||||
2. `db-schema-v1.md` wins for SQLite persistence shape.
|
||||
3. `event-registry-v1.md` wins for event names and payloads.
|
||||
4. `tool-registry-v1.md` wins for tool names and tool I/O schemas.
|
||||
5. `runtime-semantics-v1.md` wins for cross-cutting runtime behavior.
|
||||
6. `c4/module.md` and `c4/code-view.md` win for package/component boundaries.
|
||||
7. ADR files win for accepted design decisions they explicitly cover.
|
||||
8. `baselineV1.md` remains the narrative baseline and decision index.
|
||||
|
||||
| Area | Source |
|
||||
|---|---|
|
||||
| Overall baseline | `AirPlan/docs/architecture/baselineV1.md` |
|
||||
| Interface contracts | `AirPlan/docs/architecture/interface-contracts-v1.md` |
|
||||
| Runtime semantics | `AirPlan/docs/architecture/runtime-semantics-v1.md` |
|
||||
| C4/module/code view | `AirPlan/docs/architecture/c4/module.md`, `AirPlan/docs/architecture/c4/code-view.md` |
|
||||
| DB schema | `AirPlan/docs/architecture/db-schema-v1.md` |
|
||||
| Event registry | `AirPlan/docs/architecture/event-registry-v1.md` |
|
||||
| Tool registry | `AirPlan/docs/architecture/tool-registry-v1.md` |
|
||||
| Scheduler state machine | `AirPlan/docs/architecture/scheduler-state-machine-v1.md` |
|
||||
| Prompt layering | `AirPlan/docs/architecture/prompt-layering-v1.md` |
|
||||
| Provider matrix | `AirPlan/docs/architecture/provider-capability-matrix-v1.md` |
|
||||
| Error taxonomy | `AirPlan/docs/architecture/error-taxonomy-v1.md` |
|
||||
| Artifact naming | `AirPlan/docs/architecture/artifact-naming-v1.md` |
|
||||
| Scope escalation | `AirPlan/docs/architecture/scope-escalation-v1.md` |
|
||||
| Security model | `AirPlan/docs/architecture/security-model-v1.md` |
|
||||
| Capability trust | `AirPlan/docs/architecture/capability-trust-v1.md` |
|
||||
| Platform matrix | `AirPlan/docs/architecture/cross-platform-matrix-v1.md` |
|
||||
|
||||
## 3. Architectural Principles
|
||||
|
||||
1. **Execution quality follows Claude Code.** File edits are read-before-edit, exact, conservative, small, and verified before completion.
|
||||
2. **OpenCode is a UI/runtime reference, not a business-state dependency.** Reuse visual patterns and OpenTUI/Solid primitives, not OpenCode's session/sync state model.
|
||||
3. **Project-local source of truth.** Session state, artifacts, backups, and project rules live under project `.air/`.
|
||||
4. **Events drive live behavior; SQLite drives recovery.** EventBus is live transport; domain tables and durable events are the source of truth.
|
||||
5. **Workers are isolated child processes.** Executor, Reviewer, Debugger, Compactor, and ExperienceMiner run as independent Bun processes over NDJSON IPC.
|
||||
6. **Main Agent remains responsive.** Long-running background work is delegated to Scheduler/workers.
|
||||
7. **Architecture changes are explicit.** Implementation-only changes may continue silently; interface/architecture/product changes route through Architecture Designer and/or user confirmation.
|
||||
8. **Tool/capability boundaries are permissioned.** Built-in and future plugin tools all pass through ToolRegistry and PermissionEngine.
|
||||
9. **Provider boundary is isolated.** Internal messages are Anthropic canonical; adapters convert at provider boundary.
|
||||
10. **Evidence is first-class.** Build/test/debug/review outputs become artifacts and evidence refs before completion claims.
|
||||
|
||||
## 4. Major Containers
|
||||
|
||||
### CLI Container
|
||||
|
||||
Package: `packages/cli`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- command entrypoint
|
||||
- startup and first-run initialization
|
||||
- Doctor invocation
|
||||
- project discovery and `.air` initialization
|
||||
- resource loading
|
||||
- TUI/runtime bootstrap
|
||||
|
||||
Interfaces:
|
||||
|
||||
- CLI commands
|
||||
- local filesystem
|
||||
- runtime service initialization
|
||||
|
||||
### TUI/HUD Container
|
||||
|
||||
Package: `packages/tui`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- OpenTUI/Solid user interface
|
||||
- Main Agent conversation surface
|
||||
- progress, task, agent, diff, and evidence display
|
||||
- permission prompts and blocker reports
|
||||
- HUD/statusline projection
|
||||
|
||||
Interfaces:
|
||||
|
||||
- ProjectionStore read API
|
||||
- Main Agent UI channel
|
||||
- Permission prompt UI
|
||||
|
||||
Constraints:
|
||||
|
||||
- TUI consumes ProjectionStore only.
|
||||
- TUI does not query SQLite or EventBus directly.
|
||||
- TUI does not own scheduling state.
|
||||
|
||||
### Runtime Container
|
||||
|
||||
Package: `packages/runtime`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Main Agent orchestration shell
|
||||
- Architecture Designer integration
|
||||
- Scheduler
|
||||
- child process management
|
||||
- EventBus and EventStore
|
||||
- SessionStore/domain repositories
|
||||
- ToolRegistry
|
||||
- PermissionEngine
|
||||
- CapabilityRegistry
|
||||
- ContextAssembler
|
||||
- ArtifactStore and EvidenceStore
|
||||
- ProjectionStore producer side
|
||||
|
||||
Interfaces:
|
||||
|
||||
- `packages/contracts`
|
||||
- `packages/llm`
|
||||
- `packages/toolchain-*`
|
||||
- SQLite
|
||||
- project filesystem
|
||||
- child process stdio IPC
|
||||
|
||||
### LLM Container
|
||||
|
||||
Package: `packages/llm`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- provider configuration
|
||||
- provider adapters
|
||||
- Anthropic canonical message handling
|
||||
- OpenAI/OpenRouter/ollama/custom endpoint conversion
|
||||
- capability matrix validation
|
||||
- streaming/tool-use conversion
|
||||
- token counting hooks where available
|
||||
|
||||
Interfaces:
|
||||
|
||||
- ProviderAdapter API
|
||||
- ProviderCapabilityMatrix
|
||||
- runtime LLM request API
|
||||
|
||||
### Toolchain C++ Container
|
||||
|
||||
Package: `packages/toolchain-cpp`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- C++ project detection
|
||||
- CMake configure/build orchestration
|
||||
- Ninja-first, Make fallback strategy
|
||||
- CTest/GoogleTest execution
|
||||
- cppcheck static analysis
|
||||
- clangd CLI queries
|
||||
- compiler/linker diagnostic parsing
|
||||
- build/test/debug evidence production
|
||||
|
||||
Interfaces:
|
||||
|
||||
- Capability manifest
|
||||
- ToolRegistry tools under `cpp.*`
|
||||
- shell command runner
|
||||
- diagnostics/artifacts/evidence stores
|
||||
|
||||
### Contracts Container
|
||||
|
||||
Package: `packages/contracts`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- compileable shared TypeScript interfaces
|
||||
- RuntimeEvent, TaskSpec, WorkerResult, ToolDefinition, ArtifactRef, EvidenceRef
|
||||
- error, provider, project, IPC, UI types
|
||||
|
||||
Dependency rule:
|
||||
|
||||
- All packages may depend on `contracts`.
|
||||
- `contracts` must not depend on domain implementation packages.
|
||||
|
||||
## 5. Runtime Agents
|
||||
|
||||
### Main Agent
|
||||
|
||||
User-facing coordinator. It handles conversation, progress summaries, requirement changes, direct foreground tasks, and escalation presentation. It does not perform long-running background work.
|
||||
|
||||
### Architecture Designer
|
||||
|
||||
Owns architecture planning, impact assessment, ADR/C4/plan/todo alignment, and design/interface change review. It may edit planning/architecture documents, not implementation code.
|
||||
|
||||
### Scheduler
|
||||
|
||||
Owns TaskGraph loading, wave planning, dependency handling, write-area conflict handling, retry strategy, child worker dispatch, heartbeat monitoring, merge coordination, and restart recovery.
|
||||
|
||||
### Executor
|
||||
|
||||
Performs scoped implementation/build/test tasks with Claude Code-style execution discipline and structured WorkerResult output.
|
||||
|
||||
### Reviewer
|
||||
|
||||
Read-only reviewer for correctness, security, scope control, architecture compliance, and evidence sufficiency. It produces review reports and follow-up tasks.
|
||||
|
||||
### Debugger
|
||||
|
||||
Diagnoses failures using logs, diagnostics, artifacts, command output, GUI/network evidence, and may fix only within assigned write scope.
|
||||
|
||||
### Compactor
|
||||
|
||||
Performs copy-on-write context compaction. It produces summaries while preserving original messages for explicit backtracking.
|
||||
|
||||
### ExperienceMiner
|
||||
|
||||
Extracts project rules, skill candidates, and debug knowledge from verified repeated patterns and evidence.
|
||||
|
||||
## 6. Data Architecture
|
||||
|
||||
Project layout:
|
||||
|
||||
```text
|
||||
<project>/.air/
|
||||
shared/
|
||||
project.json
|
||||
permissions.yaml
|
||||
compaction-rules.md
|
||||
rules/
|
||||
plan/
|
||||
local/
|
||||
sessions/<session-id>/
|
||||
session.db
|
||||
artifacts/
|
||||
backups/
|
||||
debug-records.db
|
||||
learned-memory.db
|
||||
workspaces/
|
||||
tmp/
|
||||
locks/
|
||||
```
|
||||
|
||||
Session DB path:
|
||||
|
||||
```text
|
||||
<project>/.air/local/sessions/<session-id>/session.db
|
||||
```
|
||||
|
||||
Core data groups:
|
||||
|
||||
| Group | Tables |
|
||||
|---|---|
|
||||
| session/conversation | `sessions`, `messages`, `message_drafts`, `summaries` |
|
||||
| orchestration | `events`, `tasks`, `task_dependencies`, `task_attempts`, `agents`, `workspaces` |
|
||||
| execution evidence | `tool_runs`, `command_runs`, `artifacts`, `diagnostics`, `evidence_refs` |
|
||||
| UI recovery | `ui_state` |
|
||||
| schema | `schema_meta` |
|
||||
|
||||
SQLite V1 settings:
|
||||
|
||||
```sql
|
||||
PRAGMA journal_mode = WAL;
|
||||
PRAGMA synchronous = NORMAL;
|
||||
PRAGMA foreign_keys = OFF;
|
||||
```
|
||||
|
||||
Durable event insert and corresponding domain table update must be in the same transaction.
|
||||
|
||||
## 7. Control Flow Architecture
|
||||
|
||||
### Startup Flow
|
||||
|
||||
```text
|
||||
CLI starts
|
||||
→ detect platform and config
|
||||
→ load resources/prompts/capabilities
|
||||
→ open or initialize project .air
|
||||
→ run read-only Doctor
|
||||
→ open session DB
|
||||
→ hydrate ProjectionStore from DB
|
||||
→ start TUI/Main Agent/runtime services
|
||||
```
|
||||
|
||||
### Normal Execution Flow
|
||||
|
||||
```text
|
||||
User request
|
||||
→ Main Agent classifies intent
|
||||
→ direct answer or architecture/task planning
|
||||
→ Scheduler creates/loads TaskGraph
|
||||
→ ContextAssembler builds agent context
|
||||
→ Scheduler dispatches child worker over NDJSON IPC
|
||||
→ worker uses ToolRegistry
|
||||
→ ToolRegistry enforces PermissionEngine
|
||||
→ tools emit events/artifacts/evidence
|
||||
→ worker returns WorkerResult
|
||||
→ Scheduler retries/merges/reviews/continues
|
||||
→ Main Agent reports outcome
|
||||
```
|
||||
|
||||
### Requirement Change Flow
|
||||
|
||||
```text
|
||||
User changes requirement
|
||||
→ requirement.changed event
|
||||
→ Scheduler pauses affected work
|
||||
→ Architecture Designer assesses if needed
|
||||
→ implementation-level change continues silently
|
||||
→ architecture/product-level change routes to user confirmation/replan
|
||||
```
|
||||
|
||||
### Recovery Flow
|
||||
|
||||
```text
|
||||
Process/session restarts
|
||||
→ open session DB
|
||||
→ load running/interrupted tasks and agents
|
||||
→ inspect child process liveness when possible
|
||||
→ emit agent.lost/task.failed or reconnect/resume
|
||||
→ preserve unmerged workspaces
|
||||
→ rebuild Scheduler queues
|
||||
→ hydrate ProjectionStore
|
||||
```
|
||||
|
||||
## 8. Tool and Capability Architecture
|
||||
|
||||
ToolRegistry provides stable schema-validated built-ins:
|
||||
|
||||
```text
|
||||
fs.*, shell.*, git.*, project.*, cpp.*, debug.*,
|
||||
gui.*, network.*, artifact.*, context.*, permission.*, doctor.*
|
||||
```
|
||||
|
||||
CapabilityRegistry adds built-in and future plugin capabilities through manifests. Capability dependencies are declared in manifests but installed/fixed by Doctor, never by arbitrary plugin scripts.
|
||||
|
||||
Every tool call follows:
|
||||
|
||||
```text
|
||||
model/agent request
|
||||
→ schema validation
|
||||
→ PermissionEngine evaluation
|
||||
→ tool execution
|
||||
→ tool/command/artifact/evidence events
|
||||
→ structured ToolResult
|
||||
```
|
||||
|
||||
## 9. Prompt and Provider Architecture
|
||||
|
||||
ContextAssembler emits Anthropic canonical messages with L0-L9 layers:
|
||||
|
||||
```text
|
||||
runtime invariant
|
||||
role/mode
|
||||
safety and permission policy
|
||||
project rules/user preferences
|
||||
architecture baseline/current plan
|
||||
task spec/acceptance criteria
|
||||
relevant code/artifacts/evidence
|
||||
recent conversation/decision context
|
||||
tool result history/diagnostics
|
||||
immediate instruction
|
||||
```
|
||||
|
||||
Provider adapters convert canonical messages at the LLM boundary. Conversion omissions are recorded. Required unsupported capabilities block before model call.
|
||||
|
||||
Model selection is capability-based and can be Scheduler-forced or agent-selected within allowed constraints.
|
||||
|
||||
## 10. Security Architecture
|
||||
|
||||
Security boundary summary:
|
||||
|
||||
- LLM output is untrusted until validated.
|
||||
- Tools are the only path to filesystem/shell/network effects.
|
||||
- PermissionEngine evaluates all writes, execution, network, system-sensitive, and credential access.
|
||||
- Symlinks are resolved by realpath before risk classification.
|
||||
- `.git/` is protected by default.
|
||||
- Build directories are allowed project write areas.
|
||||
- Project-outside writes require backup.
|
||||
- Credentials and system-sensitive operations require explicit confirmation.
|
||||
- No automatic upload of logs, artifacts, debug knowledge, or doctor bundles.
|
||||
|
||||
## 11. Platform Architecture
|
||||
|
||||
V1.0.0 Alpha is Linux-first:
|
||||
|
||||
| Platform | Support |
|
||||
|---|---|
|
||||
| Linux x86_64 | tier 1 |
|
||||
| Linux arm64 | tier 2 |
|
||||
| WSL2 | tier 2 |
|
||||
| macOS | experimental |
|
||||
| Windows native | experimental/post-MVP |
|
||||
|
||||
Shell/process/C++ tooling in V1.0.0 Alpha targets POSIX-like Linux behavior.
|
||||
|
||||
## 12. Quality and Validation Architecture
|
||||
|
||||
Validation layers:
|
||||
|
||||
```text
|
||||
unit tests → integration fixture replay → real LLM E2E release gate
|
||||
```
|
||||
|
||||
Execution completion requires evidence appropriate to the task:
|
||||
|
||||
- build command result
|
||||
- test command result
|
||||
- static analysis result where configured
|
||||
- debug evidence where failures occur
|
||||
- review report for significant changes
|
||||
- artifact/evidence refs for claims
|
||||
|
||||
Release gate for tier-1 Linux must cover startup, project init, child IPC, session DB, artifacts/events, C++ configure/build/test, TUI startup, and real LLM E2E behavior.
|
||||
|
||||
## 13. Key Risks and Mitigations
|
||||
|
||||
| Risk | Mitigation |
|
||||
|---|---|
|
||||
| Execution quality below Claude Code | Align edit primitives, tool lifecycle, read-before-edit, verification discipline |
|
||||
| Context explosion | copy-on-write compaction, ContextAssembler budgets, artifact refs |
|
||||
| Scheduler complexity | V1 state machine and V1.0.0 Alpha cut line; advanced optimization deferred |
|
||||
| Tool/plugin safety | ToolRegistry + PermissionEngine + capability trust model |
|
||||
| Provider feature mismatch | Provider capability matrix and conversion report |
|
||||
| Lost worker/process | heartbeat, task attempts, restart recovery |
|
||||
| Merge conflicts across parallel workers | write-area planning, worktrees, merge events, repair/escalation |
|
||||
| Debug evidence too large/noisy | artifact naming/layout, evidence refs, summaries |
|
||||
| Platform drift | Linux tier-1 release matrix and Doctor platform report |
|
||||
|
||||
## 14. V1.0.0 Alpha Architecture Boundaries
|
||||
|
||||
In scope for V1.0.0 Alpha:
|
||||
|
||||
```text
|
||||
Bun monorepo
|
||||
contracts package
|
||||
runtime services
|
||||
project-local SQLite/artifacts
|
||||
EventStore/EventBus/ProjectionStore
|
||||
Main Agent shell
|
||||
Scheduler/worker IPC
|
||||
ToolRegistry/PermissionEngine
|
||||
complete C++ development workflow
|
||||
local/built-in plugin and capability foundation
|
||||
TUI/HUD startup and projections
|
||||
provider adapters
|
||||
Doctor read-only/fix framework
|
||||
GUI/network evidence tools
|
||||
release gate and binary tarball packaging
|
||||
```
|
||||
|
||||
Deferred beyond V1.0.0 Alpha:
|
||||
|
||||
```text
|
||||
third-party plugin registry/signing
|
||||
container sandboxing
|
||||
advanced semantic merge
|
||||
multi-machine scheduling
|
||||
Windows-native deep support
|
||||
production-grade bitmap image generation providers
|
||||
browser/computer-use automation
|
||||
learned retry optimizer
|
||||
```
|
||||
761
AirPlan/docs/architecture/tool-registry-v1.md
Normal file
761
AirPlan/docs/architecture/tool-registry-v1.md
Normal file
@@ -0,0 +1,761 @@
|
||||
# AirCoding V1.0.0 Alpha Tool Registry V1
|
||||
|
||||
Date: 2026-05-27
|
||||
Status: Canonical V1.0.0 Alpha built-in tool registry
|
||||
|
||||
This document freezes the built-in tools required for the V1.0.0 Alpha skeleton. Additional tools may be added by capabilities/plugins later, but the tools here define the minimum stable execution surface.
|
||||
|
||||
Tool contract is defined in `interface-contracts-v1.md` §12 and exported from `packages/contracts/tool.ts`.
|
||||
|
||||
## 1. Registry Principles
|
||||
|
||||
1. Tools are schema-validated at input and output boundaries.
|
||||
2. Tools emit lifecycle events from `event-registry-v1.md`: `tool.started`, `tool.progress`, `tool.completed`, `tool.failed`, `tool.cancelled`.
|
||||
3. Tools must go through PermissionEngine before filesystem writes, command execution, network access, or system-sensitive operations.
|
||||
4. File edit tools follow Claude Code style discipline: read-before-edit, exact replacement, small edits, no broad rewrite unless the tool is explicitly `fs.write` or template scaffolding.
|
||||
5. Shell tools capture stdout/stderr as artifacts when output exceeds inline limits or when the command participates in verification evidence.
|
||||
6. Tool implementations return structured outputs; human-readable summaries are presentation data, not the source of truth.
|
||||
7. Tool names are stable API identifiers and use dotted namespaces.
|
||||
|
||||
## 2. Common Tool Types
|
||||
|
||||
`ToolCategory`, `ToolResultEnvelope`, `ToolDefinition`, `ToolExecutor`, `StreamingToolExecutor`, and `ToolRegistry` are defined in `interface-contracts-v1.md` §12. This document references those contracts; it does not re-define them.
|
||||
|
||||
Inline output limits are implementation config, but V1 defaults should be conservative:
|
||||
|
||||
```text
|
||||
stdout/stderr inline preview: 16 KiB each
|
||||
file read inline default: 2000 lines
|
||||
single tool event payload target: < 256 KiB
|
||||
larger content: artifact reference
|
||||
```
|
||||
|
||||
## 3. Filesystem Tools
|
||||
|
||||
### `fs.list` v1
|
||||
|
||||
Category: filesystem. Permission: read paths.
|
||||
|
||||
Purpose: list directory entries with metadata.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface FsListInput {
|
||||
path: string
|
||||
recursive?: boolean
|
||||
max_depth?: number
|
||||
include_hidden?: boolean
|
||||
glob?: string
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface FsListOutput {
|
||||
entries: Array<{
|
||||
path: string
|
||||
type: "file" | "directory" | "symlink" | "other"
|
||||
size_bytes?: number
|
||||
modified_at?: string
|
||||
target_path?: string
|
||||
}>
|
||||
truncated: boolean
|
||||
}
|
||||
```
|
||||
|
||||
### `fs.read` v1
|
||||
|
||||
Category: filesystem. Permission: read paths.
|
||||
|
||||
Purpose: read text, binary metadata, images, PDFs, or notebooks through typed adapters.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface FsReadInput {
|
||||
path: string
|
||||
offset_lines?: number
|
||||
limit_lines?: number
|
||||
pages?: string
|
||||
encoding?: "utf8" | "base64" | "auto"
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface FsReadOutput {
|
||||
path: string
|
||||
content?: string
|
||||
content_type: "text" | "binary" | "image" | "pdf" | "notebook" | "empty"
|
||||
line_count?: number
|
||||
truncated: boolean
|
||||
artifact_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
### `fs.write` v1
|
||||
|
||||
Category: filesystem. Permission: write paths.
|
||||
|
||||
Purpose: create new files or overwrite files only when explicitly authorized by the caller policy.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface FsWriteInput {
|
||||
path: string
|
||||
content: string
|
||||
create_parent_dirs?: boolean
|
||||
expected_existing_sha256?: string
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface FsWriteOutput {
|
||||
path: string
|
||||
bytes_written: number
|
||||
sha256: string
|
||||
backup_artifact_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
### `fs.edit` v1
|
||||
|
||||
Category: filesystem. Permission: read/write paths.
|
||||
|
||||
Purpose: exact string replacement in an existing file.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface FsEditInput {
|
||||
path: string
|
||||
old_string: string
|
||||
new_string: string
|
||||
replace_all?: boolean
|
||||
expected_existing_sha256?: string
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface FsEditOutput {
|
||||
path: string
|
||||
replacements: number
|
||||
sha256: string
|
||||
diff_artifact_id: string
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- The file must have been read in the active task before edit.
|
||||
- `old_string` must be unique unless `replace_all = true`.
|
||||
- The tool fails rather than guessing indentation or nearby replacements.
|
||||
|
||||
### `fs.patch` v1
|
||||
|
||||
Category: filesystem. Permission: read/write paths.
|
||||
|
||||
Purpose: apply a unified patch generated by the execution layer.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface FsPatchInput {
|
||||
patch: string
|
||||
strip?: number
|
||||
expected_paths?: string[]
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface FsPatchOutput {
|
||||
changed_files: string[]
|
||||
diff_artifact_id: string
|
||||
rejected_hunks_artifact_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
### `fs.stat` v1
|
||||
|
||||
Category: filesystem. Permission: read paths.
|
||||
|
||||
Purpose: inspect path metadata and realpath for permission decisions.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface FsStatInput { path: string }
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface FsStatOutput {
|
||||
path: string
|
||||
realpath?: string
|
||||
exists: boolean
|
||||
type?: "file" | "directory" | "symlink" | "other"
|
||||
size_bytes?: number
|
||||
modified_at?: string
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Shell and Process Tools
|
||||
|
||||
### `shell.run` v1
|
||||
|
||||
Category: shell. Permission: execute plus command risk analysis.
|
||||
|
||||
Purpose: run a bounded non-interactive command.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface ShellRunInput {
|
||||
command: string
|
||||
cwd: string
|
||||
timeout_ms?: number
|
||||
env?: Record<string, string>
|
||||
stdin?: string
|
||||
capture_mode?: "inline" | "artifact" | "both"
|
||||
purpose?: "build" | "test" | "debug" | "doctor" | "general"
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface ShellRunOutput {
|
||||
command_run_id: string
|
||||
exit_code: number
|
||||
duration_ms: number
|
||||
stdout_preview?: string
|
||||
stderr_preview?: string
|
||||
stdout_artifact_id?: string
|
||||
stderr_artifact_id?: string
|
||||
combined_artifact_id?: string
|
||||
parsed_diagnostics_json?: unknown
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- No interactive commands in V1 unless a dedicated tool owns the interaction model.
|
||||
- Destructive commands require PermissionEngine approval based on command risk analysis.
|
||||
- The command runner emits `command.started`, command stream deltas, and terminal command events.
|
||||
|
||||
### `process.kill` v1
|
||||
|
||||
Category: shell/debug. Permission: execute; system-sensitive when target is outside AirCoding process tree.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface ProcessKillInput {
|
||||
pid: number
|
||||
signal?: "SIGTERM" | "SIGKILL" | "SIGINT"
|
||||
reason: string
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface ProcessKillOutput {
|
||||
pid: number
|
||||
signal: string
|
||||
delivered: boolean
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Git Tools
|
||||
|
||||
### `git.status` v1
|
||||
|
||||
Category: git. Permission: read paths.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface GitStatusInput { cwd: string }
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface GitStatusOutput {
|
||||
branch?: string
|
||||
clean: boolean
|
||||
staged: string[]
|
||||
modified: string[]
|
||||
untracked: string[]
|
||||
conflicted: string[]
|
||||
}
|
||||
```
|
||||
|
||||
### `git.diff` v1
|
||||
|
||||
Category: git. Permission: read paths.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface GitDiffInput {
|
||||
cwd: string
|
||||
base_ref?: string
|
||||
pathspecs?: string[]
|
||||
staged?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface GitDiffOutput {
|
||||
diff: string
|
||||
diff_artifact_id?: string
|
||||
truncated: boolean
|
||||
}
|
||||
```
|
||||
|
||||
### `git.worktree.create` v1
|
||||
|
||||
Category: git. Permission: write project-local paths.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface GitWorktreeCreateInput {
|
||||
cwd: string
|
||||
path: string
|
||||
branch_name: string
|
||||
base_ref?: string
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface GitWorktreeCreateOutput {
|
||||
workspace_id: string
|
||||
path: string
|
||||
branch_name: string
|
||||
base_ref?: string
|
||||
}
|
||||
```
|
||||
|
||||
### `git.merge_workspace` v1
|
||||
|
||||
Category: git. Permission: write project paths.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface GitMergeWorkspaceInput {
|
||||
workspace_id: string
|
||||
strategy: "fast_forward" | "patch_apply" | "manual_merge"
|
||||
target_ref?: string
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface GitMergeWorkspaceOutput {
|
||||
status: "merged" | "conflicted" | "failed"
|
||||
changed_files: string[]
|
||||
diff_artifact_id?: string
|
||||
conflict_artifact_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
## 6. Project Tools
|
||||
|
||||
### `project.scan` v1
|
||||
|
||||
Category: project. Permission: read project paths.
|
||||
|
||||
Purpose: collect project metadata for initialization and profile updates.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface ProjectScanInput {
|
||||
project_root: string
|
||||
include_directory_tree: true
|
||||
include_git_summary?: boolean
|
||||
include_extension_stats?: boolean
|
||||
include_special_files?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface ProjectScanOutput {
|
||||
project_root: string
|
||||
directory_tree_artifact_id: string
|
||||
extension_stats: Record<string, number>
|
||||
special_files: string[]
|
||||
git_summary?: unknown
|
||||
}
|
||||
```
|
||||
|
||||
### `project.profile.write` v1
|
||||
|
||||
Category: project. Permission: write `.air/shared/project.json`.
|
||||
|
||||
Input:
|
||||
|
||||
```ts
|
||||
interface ProjectProfileWriteInput {
|
||||
project_root: string
|
||||
profile_json: unknown
|
||||
expected_schema_version?: number
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```ts
|
||||
interface ProjectProfileWriteOutput {
|
||||
path: string
|
||||
schema_version: number
|
||||
sha256: string
|
||||
}
|
||||
```
|
||||
|
||||
## 7. C++ Toolchain MVP Tools
|
||||
|
||||
### `cpp.detect` v1
|
||||
|
||||
Category: build. Permission: read project paths.
|
||||
|
||||
Output includes detected build systems, compiler hints, test frameworks, and confidence notes.
|
||||
|
||||
```ts
|
||||
interface CppDetectInput { project_root: string }
|
||||
interface CppDetectOutput {
|
||||
build_systems: Array<"cmake" | "make" | "ninja" | "custom" | "unknown">
|
||||
preferred_build_system?: string
|
||||
source_roots: string[]
|
||||
test_roots: string[]
|
||||
notes: string[]
|
||||
}
|
||||
```
|
||||
|
||||
### `cpp.cmake.configure` v1
|
||||
|
||||
Category: build. Permission: execute and write build directory.
|
||||
|
||||
```ts
|
||||
interface CppCmakeConfigureInput {
|
||||
project_root: string
|
||||
build_dir: string
|
||||
generator_preference?: "ninja_then_make" | "ninja" | "make"
|
||||
cmake_args?: string[]
|
||||
}
|
||||
interface CppCmakeConfigureOutput {
|
||||
command_run_id: string
|
||||
compile_commands_path?: string
|
||||
diagnostics?: unknown
|
||||
}
|
||||
```
|
||||
|
||||
### `cpp.build` v1
|
||||
|
||||
Category: build. Permission: execute and write build directory.
|
||||
|
||||
```ts
|
||||
interface CppBuildInput {
|
||||
project_root: string
|
||||
build_dir?: string
|
||||
target?: string
|
||||
clean_first?: boolean
|
||||
}
|
||||
interface CppBuildOutput {
|
||||
command_run_id: string
|
||||
status: "passed" | "failed"
|
||||
diagnostics?: unknown
|
||||
}
|
||||
```
|
||||
|
||||
### `cpp.test` v1
|
||||
|
||||
Category: test. Permission: execute project/build outputs.
|
||||
|
||||
```ts
|
||||
interface CppTestInput {
|
||||
project_root: string
|
||||
build_dir?: string
|
||||
framework?: "ctest" | "gtest" | "custom"
|
||||
filter?: string
|
||||
}
|
||||
interface CppTestOutput {
|
||||
command_run_id: string
|
||||
status: "passed" | "failed"
|
||||
test_count?: number
|
||||
failed_tests?: string[]
|
||||
report_artifact_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
### `cpp.static.cppcheck` v1
|
||||
|
||||
Category: static_analysis. Permission: execute/read project paths.
|
||||
|
||||
```ts
|
||||
interface CppcheckInput {
|
||||
project_root: string
|
||||
paths?: string[]
|
||||
compile_commands_path?: string
|
||||
}
|
||||
interface CppcheckOutput {
|
||||
command_run_id: string
|
||||
diagnostic_ids: string[]
|
||||
report_artifact_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
### `cpp.clangd.query` v1
|
||||
|
||||
Category: static_analysis. Permission: read project paths and execute clangd helper.
|
||||
|
||||
```ts
|
||||
interface ClangdQueryInput {
|
||||
project_root: string
|
||||
compile_commands_path?: string
|
||||
query: "definition" | "references" | "symbols" | "diagnostics"
|
||||
file?: string
|
||||
line?: number
|
||||
column?: number
|
||||
symbol?: string
|
||||
}
|
||||
interface ClangdQueryOutput {
|
||||
results: unknown
|
||||
artifact_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
## 8. Debug and Evidence Tools
|
||||
|
||||
### `debug.run` v1
|
||||
|
||||
Category: debug. Permission: execute project/build outputs.
|
||||
|
||||
```ts
|
||||
interface DebugRunInput {
|
||||
command: string
|
||||
cwd: string
|
||||
timeout_ms?: number
|
||||
collect_core_dump?: boolean
|
||||
collect_backtrace?: boolean
|
||||
}
|
||||
interface DebugRunOutput {
|
||||
command_run_id: string
|
||||
exit_code?: number
|
||||
crash_detected: boolean
|
||||
backtrace_artifact_id?: string
|
||||
core_dump_artifact_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
### `debug.parse_logs` v1
|
||||
|
||||
Category: debug. Permission: read paths.
|
||||
|
||||
```ts
|
||||
interface DebugParseLogsInput {
|
||||
paths: string[]
|
||||
task_id?: string
|
||||
hint?: string
|
||||
}
|
||||
interface DebugParseLogsOutput {
|
||||
diagnostic_ids: string[]
|
||||
summary: string
|
||||
report_artifact_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
## 9. GUI and Network Evidence Tools
|
||||
|
||||
### `gui.screenshot` v1
|
||||
|
||||
Category: gui. Permission: read display/session state; system-sensitive if outside controlled test display.
|
||||
|
||||
```ts
|
||||
interface GuiScreenshotInput {
|
||||
target: "active_window" | "display" | "window_title" | "pid"
|
||||
value?: string
|
||||
}
|
||||
interface GuiScreenshotOutput {
|
||||
screenshot_artifact_id: string
|
||||
width?: number
|
||||
height?: number
|
||||
}
|
||||
```
|
||||
|
||||
### `network.capture` v1
|
||||
|
||||
Category: network. Permission: network and system-sensitive when packet capture requires elevated permissions.
|
||||
|
||||
```ts
|
||||
interface NetworkCaptureInput {
|
||||
interface?: string
|
||||
duration_ms: number
|
||||
filter?: string
|
||||
reason: string
|
||||
}
|
||||
interface NetworkCaptureOutput {
|
||||
pcap_artifact_id?: string
|
||||
summary_artifact_id?: string
|
||||
packet_count?: number
|
||||
}
|
||||
```
|
||||
|
||||
## 10. Context, Artifact, Permission, and Doctor Tools
|
||||
|
||||
### `artifact.create` v1
|
||||
|
||||
Category: artifact. Permission: write session artifact path.
|
||||
|
||||
```ts
|
||||
interface ArtifactCreateInput {
|
||||
type: string
|
||||
original_name?: string
|
||||
content?: string
|
||||
source_path?: string
|
||||
associated_entity_type?: string
|
||||
associated_entity_id?: string
|
||||
metadata?: Record<string, unknown>
|
||||
}
|
||||
interface ArtifactCreateOutput {
|
||||
artifact_id: string
|
||||
uri: string
|
||||
path: string
|
||||
sha256?: string
|
||||
size_bytes?: number
|
||||
}
|
||||
```
|
||||
|
||||
### `context.assemble` v1
|
||||
|
||||
Category: context. Permission: read DB/artifacts/rules.
|
||||
|
||||
```ts
|
||||
interface ContextAssembleInput {
|
||||
task_id?: string
|
||||
purpose: "main" | "execute" | "review" | "debug" | "compact" | "mine_experience"
|
||||
refs?: string[]
|
||||
token_budget?: number
|
||||
}
|
||||
interface ContextAssembleOutput {
|
||||
canonical_format: "anthropic"
|
||||
messages_artifact_id: string
|
||||
omissions: string[]
|
||||
token_estimate?: number
|
||||
compaction_requested?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
### `permission.request` v1
|
||||
|
||||
Category: permission. Permission: internal.
|
||||
|
||||
```ts
|
||||
interface PermissionRequestInput {
|
||||
subject: string
|
||||
risk_level: "low" | "medium" | "high" | "critical"
|
||||
reason: string
|
||||
options: string[]
|
||||
default_option?: string
|
||||
request_ref?: unknown
|
||||
}
|
||||
interface PermissionRequestOutput {
|
||||
prompt_id: string
|
||||
selected_option?: string
|
||||
decision_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
### `doctor.run` v1
|
||||
|
||||
Category: doctor. Permission: read system/project state; fix mode may require execute/write.
|
||||
|
||||
```ts
|
||||
interface DoctorRunInput {
|
||||
mode: "read_only" | "fix"
|
||||
scope?: "startup" | "project" | "toolchain" | "release_gate"
|
||||
capabilities?: string[]
|
||||
}
|
||||
interface DoctorRunOutput {
|
||||
run_id: string
|
||||
status: "passed" | "issues_found" | "fixed" | "failed"
|
||||
issue_count: number
|
||||
blocking_issue_count: number
|
||||
report_artifact_id?: string
|
||||
}
|
||||
```
|
||||
|
||||
## 11. MVP Required Tool Index
|
||||
|
||||
```text
|
||||
fs.list
|
||||
fs.read
|
||||
fs.write
|
||||
fs.edit
|
||||
fs.patch
|
||||
fs.stat
|
||||
shell.run
|
||||
process.kill
|
||||
git.status
|
||||
git.diff
|
||||
git.worktree.create
|
||||
git.merge_workspace
|
||||
project.scan
|
||||
project.profile.write
|
||||
cpp.detect
|
||||
cpp.cmake.configure
|
||||
cpp.build
|
||||
cpp.test
|
||||
cpp.static.cppcheck
|
||||
cpp.clangd.query
|
||||
debug.run
|
||||
debug.parse_logs
|
||||
gui.screenshot
|
||||
network.capture
|
||||
artifact.create
|
||||
context.assemble
|
||||
permission.request
|
||||
doctor.run
|
||||
```
|
||||
|
||||
## 12. Post-MVP Tool Candidates
|
||||
|
||||
These are intentionally not required for the V1.0.0 Alpha skeleton:
|
||||
|
||||
```text
|
||||
image.generate
|
||||
image.edit
|
||||
browser.automate
|
||||
gui.interact
|
||||
container.run
|
||||
package.manager.install
|
||||
mcp.call
|
||||
skill.run
|
||||
clang-tidy native wrapper
|
||||
sanitizer runner
|
||||
coverage reporter
|
||||
```
|
||||
|
||||
They may be registered by capabilities once the V1 registry, permission model, event schema, and artifact model are stable.
|
||||
545
AirPlan/docs/architecture/vibeboxbaseline.md
Normal file
545
AirPlan/docs/architecture/vibeboxbaseline.md
Normal file
@@ -0,0 +1,545 @@
|
||||
# VibeBox Baseline V1
|
||||
|
||||
Date: 2026-05-26
|
||||
Status: Historical/top-level VibeBox overview; canonical VibeBox branch baseline lives at `AirPlan/docs/architecture/branchvibebox/vibeboxbaseline.md`
|
||||
|
||||
This file is retained as a high-level overview. Implementation decisions for VibeBox V1 are authoritative in `AirPlan/docs/architecture/branchvibebox/vibeboxbaseline.md` and `AirPlan/docs/architecture/branchvibebox/feasibility-plan.md`.
|
||||
|
||||
VibeBox is a highly simplified AirCoding derivative for an ARM Linux appliance. Its goal is to let non-technical users describe a small desktop utility in natural language, then run environment setup, development, testing, review, packaging, and delivery mostly silently in the background, finally handing the user a usable Electron application.
|
||||
|
||||
This baseline intentionally cuts most of AirCoding's general-purpose architecture to minimize implementation cost, runtime risk, and support burden.
|
||||
|
||||
## 1. Product Goal
|
||||
|
||||
VibeBox should behave like an appliance:
|
||||
|
||||
```text
|
||||
User describes desired small tool in natural language
|
||||
→ VibeBox asks only blocking product questions, if any
|
||||
→ Runs doctor/setup silently where allowed
|
||||
→ Generates Electron app from approved template
|
||||
→ Implements UI and local logic in the background
|
||||
→ Runs lint/typecheck/test/smoke test
|
||||
→ Reviews generated code
|
||||
→ Fixes issues automatically when possible
|
||||
→ Packages app for ARM Linux
|
||||
→ Delivers runnable app to user with report
|
||||
```
|
||||
|
||||
Primary experience target: after the user states the requirement, VibeBox should work in the background and only return when a usable tool is ready, unless a truly blocking product or safety decision is required.
|
||||
|
||||
Target user: non-programmer / beginner.
|
||||
|
||||
Target output: small Electron-based desktop utilities for ARM Linux.
|
||||
|
||||
Typical examples:
|
||||
|
||||
- simple file renamer
|
||||
- local note/todo app
|
||||
- clipboard helper
|
||||
- small form/data-entry utility
|
||||
- image batch resizer wrapper
|
||||
- CSV viewer/editor
|
||||
- local dashboard around simple APIs
|
||||
- single-purpose internal workflow helper
|
||||
|
||||
Non-goals:
|
||||
|
||||
- large software projects
|
||||
- multi-language deep toolchains
|
||||
- C++ build/debug loop
|
||||
- complex distributed agents
|
||||
- long-running enterprise workflow automation
|
||||
- arbitrary system administration
|
||||
- production SaaS/backend deployment
|
||||
|
||||
## 2. Relationship to AirCoding
|
||||
|
||||
VibeBox reuses AirCoding principles selectively.
|
||||
|
||||
Keep:
|
||||
|
||||
- Claude Code style execution-layer discipline
|
||||
- Anthropic canonical message format internally
|
||||
- conservative file edit/diff/update primitives
|
||||
- local session persistence
|
||||
- artifact/evidence records
|
||||
- doctor/setup environment checks
|
||||
- TUI/HUD or simple appliance UI status display
|
||||
- review/test before delivery
|
||||
|
||||
Cut or defer:
|
||||
|
||||
- Architecture Designer as a separate agent
|
||||
- complex Scheduler / TaskGraph / worktree parallelism
|
||||
- C++ toolchain profile
|
||||
- multi-language toolchain packages
|
||||
- network/GUI/static-analysis Air plugin family as first-class components
|
||||
- ExperienceMiner / Curator
|
||||
- Debug Knowledge Network
|
||||
- project migration complexity beyond simple schema versioning
|
||||
- multi-provider complexity beyond one configured provider
|
||||
- OpenCode-compatible advanced TUI
|
||||
|
||||
## 3. Core Design Principle
|
||||
|
||||
VibeBox should optimize for appliance reliability over architectural generality.
|
||||
|
||||
Key rule:
|
||||
|
||||
> One user request should produce one small app project through a linear setup → generate → test → review → package → deliver pipeline, with background silent execution as the default.
|
||||
|
||||
The system should not require the user to supervise intermediate development steps. Progress can be visible in status/HUD, but VibeBox should not ask for implementation choices unless the task is blocked.
|
||||
|
||||
No parallel write workers in V1.
|
||||
|
||||
No complex agent hierarchy in V1.
|
||||
|
||||
No automatic architecture replanning loop in V1.
|
||||
|
||||
## 4. Agent Model
|
||||
|
||||
### 4.1 Single Orchestrator
|
||||
|
||||
VibeBox has one main Orchestrator agent.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Understand user's natural language request
|
||||
- Ask only truly blocking product/safety questions
|
||||
- Choose an app template
|
||||
- Produce an internal implementation plan without requiring user approval for implementation details
|
||||
- Run environment setup through doctor/setup according to appliance permission policy
|
||||
- Drive Executor and Reviewer steps sequentially in the background
|
||||
- Present final package and usage instructions
|
||||
|
||||
### 4.2 Executor
|
||||
|
||||
Executor can be implemented as a mode of Orchestrator or a simple child process.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Scaffold Electron project from template
|
||||
- Edit files using Claude Code-like execution primitives
|
||||
- Run npm/pnpm commands
|
||||
- Run tests and smoke checks
|
||||
- Produce structured result
|
||||
|
||||
### 4.3 Reviewer/Tester
|
||||
|
||||
Reviewer/Tester can be a separate pass, not a long-lived agent.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Inspect generated diff
|
||||
- Check for obvious security issues
|
||||
- Verify app matches user request
|
||||
- Verify tests/smoke test passed
|
||||
- Produce a concise approval or requested-change report
|
||||
|
||||
V1 pipeline:
|
||||
|
||||
```text
|
||||
Orchestrator
|
||||
→ Executor
|
||||
→ Reviewer/Tester
|
||||
→ Executor fix pass if needed
|
||||
→ Package
|
||||
→ Deliver
|
||||
```
|
||||
|
||||
Maximum retry cycles: 2.
|
||||
|
||||
If still failing, show clear failure report and ask user whether to continue.
|
||||
|
||||
## 5. Execution-Layer Quality Standard
|
||||
|
||||
VibeBox follows AirCoding D-059: execution-layer primitives align with Claude Code for code quality.
|
||||
|
||||
Required behaviors:
|
||||
|
||||
- read before edit
|
||||
- small exact edits
|
||||
- no broad rewrites unless scaffolding from template
|
||||
- no unrelated refactors
|
||||
- run verification before declaring success
|
||||
- collect evidence for build/test/package results
|
||||
- diagnose root cause on failure, not random retries
|
||||
- explicitly escalate if the requested app is outside supported scope
|
||||
|
||||
This is the most important reuse point from AirCoding.
|
||||
|
||||
## 6. Technology Stack
|
||||
|
||||
Recommended V1 stack:
|
||||
|
||||
```text
|
||||
Runtime: TypeScript + Bun or Node.js
|
||||
App target: Electron
|
||||
Frontend: React + Vite or plain HTML/TS template
|
||||
Package manager: pnpm or npm
|
||||
Testing: vitest + Playwright/Electron smoke test
|
||||
Packaging: electron-builder or electron-forge
|
||||
Target OS: ARM Linux
|
||||
```
|
||||
|
||||
Default app template:
|
||||
|
||||
```text
|
||||
Electron + Vite + TypeScript
|
||||
├── main process
|
||||
├── preload bridge
|
||||
├── renderer UI
|
||||
├── local storage helper
|
||||
├── test harness
|
||||
└── packaging config for ARM Linux
|
||||
```
|
||||
|
||||
Security defaults:
|
||||
|
||||
- `contextIsolation: true`
|
||||
- `nodeIntegration: false`
|
||||
- explicit preload API
|
||||
- no remote code execution
|
||||
- no arbitrary shell command from generated app unless user explicitly requested and approved
|
||||
- local-first storage by default
|
||||
|
||||
## 7. Project Layout
|
||||
|
||||
Each generated app is self-contained.
|
||||
|
||||
```text
|
||||
<workspace>/<app-name>/
|
||||
├── package.json
|
||||
├── src/
|
||||
│ ├── main/
|
||||
│ ├── preload/
|
||||
│ └── renderer/
|
||||
├── tests/
|
||||
├── dist/
|
||||
├── release/
|
||||
└── .vibebox/
|
||||
├── project.json
|
||||
├── session.db
|
||||
├── artifacts/
|
||||
├── reports/
|
||||
└── state.json
|
||||
```
|
||||
|
||||
VibeBox may later converge with AirCoding `.air/shared` + `.air/local`, but V1 uses `.vibebox/` for product clarity and isolation.
|
||||
|
||||
## 8. Session and State
|
||||
|
||||
V1 uses one SQLite database per generated project:
|
||||
|
||||
```text
|
||||
<app>/.vibebox/session.db
|
||||
```
|
||||
|
||||
Minimum tables:
|
||||
|
||||
- `messages`
|
||||
- `message_drafts`
|
||||
- `steps`
|
||||
- `tool_runs`
|
||||
- `command_runs`
|
||||
- `artifacts`
|
||||
- `reports`
|
||||
|
||||
No complex TaskGraph tables in V1.
|
||||
|
||||
Pipeline steps are linear:
|
||||
|
||||
```text
|
||||
clarify
|
||||
plan
|
||||
scaffold
|
||||
implement
|
||||
test
|
||||
review
|
||||
fix
|
||||
package
|
||||
deliver
|
||||
```
|
||||
|
||||
Artifacts:
|
||||
|
||||
```text
|
||||
.vibebox/artifacts/
|
||||
├── command-runs/
|
||||
├── screenshots/
|
||||
├── build-logs/
|
||||
├── test-logs/
|
||||
├── review-reports/
|
||||
└── packages/
|
||||
```
|
||||
|
||||
## 9. Tool Set
|
||||
|
||||
Minimum built-in tools include frontend design and image generation as first-class VibeBox capabilities, because the target output is a user-facing Electron app and the user may not be able to provide UI/assets manually.
|
||||
|
||||
### Filesystem
|
||||
|
||||
- list files
|
||||
- read file
|
||||
- write file
|
||||
- edit file with exact replacement
|
||||
- apply patch
|
||||
- create project from template
|
||||
|
||||
### Shell
|
||||
|
||||
- run command with timeout
|
||||
- capture stdout/stderr artifacts
|
||||
- enforce output limits
|
||||
|
||||
### Electron workflow
|
||||
|
||||
- install dependencies
|
||||
- run dev build
|
||||
- run typecheck
|
||||
- run unit tests
|
||||
- run smoke test
|
||||
- package app
|
||||
|
||||
### Frontend design
|
||||
|
||||
- generate layout plan from natural language requirement
|
||||
- choose sensible UI pattern from templates (form, dashboard, list/detail, wizard, utility panel)
|
||||
- generate component structure and styling tokens
|
||||
- generate CSS/theme defaults suitable for appliance users
|
||||
- generate responsive layout for common small displays
|
||||
- review screenshot against requested UX
|
||||
|
||||
### Image generation / assets
|
||||
|
||||
- generate app icon
|
||||
- generate placeholder illustrations / empty-state images
|
||||
- generate simple background or decorative assets when useful
|
||||
- generate SVG assets when bitmap generation is unavailable
|
||||
- edit/regenerate assets from user feedback
|
||||
- store generated assets as artifacts before copying into the app
|
||||
|
||||
### Electron automated testing
|
||||
|
||||
- generate Playwright/Electron tests for all core user workflows
|
||||
- launch Electron app in controlled test mode
|
||||
- interact with UI elements, forms, menus, file pickers, and local storage paths where applicable
|
||||
- test invalid/empty/large input cases relevant to the generated tool
|
||||
- test restart/persistence behavior when the app stores local data
|
||||
- capture screenshots and traces for failed UI tests
|
||||
- run packaged-app launch test after packaging
|
||||
|
||||
### UI evidence
|
||||
|
||||
- launch app under Xvfb/Wayland-compatible mode if available
|
||||
- capture screenshot
|
||||
- compare screenshot against generated design intent
|
||||
- use automated UI test evidence, not only smoke-test evidence
|
||||
|
||||
### Delivery
|
||||
|
||||
- collect release artifact
|
||||
- generate README / usage instructions
|
||||
- generate final report
|
||||
|
||||
## 10. Doctor / Setup
|
||||
|
||||
First startup runs read-only doctor.
|
||||
|
||||
Checks:
|
||||
|
||||
- Node.js or Bun availability
|
||||
- npm/pnpm availability
|
||||
- Electron install ability
|
||||
- frontend-design capability availability
|
||||
- image generation provider availability or local image model availability
|
||||
- build tools required by native npm modules
|
||||
- display/Xvfb availability for automated Electron UI tests
|
||||
- Playwright/Electron automation support
|
||||
- disk space
|
||||
- write permissions to workspace
|
||||
- ARM Linux architecture
|
||||
- package manager cache availability
|
||||
|
||||
If issues exist:
|
||||
|
||||
- Low-permission mode: ask user before fix
|
||||
- High-permission appliance mode: run fix automatically after showing a brief visible plan, unless the user interrupts
|
||||
- First startup on a prepared appliance may be pre-authorized by the vendor/operator; otherwise it shows the fix plan before proceeding
|
||||
|
||||
VibeBox's default appliance deployment should be high-permission and background-oriented. Environment setup is part of the product promise: the user should not need to manually install Node/Electron/build dependencies.
|
||||
|
||||
## 11. User Interaction Model
|
||||
|
||||
VibeBox should minimize technical language and assume the user lacks computer expertise. Default mode is highest-permission appliance automation with strong test/review gates, not an interactive developer workflow.
|
||||
|
||||
User sees:
|
||||
|
||||
```text
|
||||
1. Understanding your app idea
|
||||
2. Creating the app
|
||||
3. Testing the app
|
||||
4. Reviewing quality
|
||||
5. Packaging for this box
|
||||
6. Ready to use
|
||||
```
|
||||
|
||||
Clarifying questions should be limited to product choices, for example:
|
||||
|
||||
- app name
|
||||
- input/output file types
|
||||
- desired UI layout
|
||||
- whether data stays local
|
||||
- whether app may access network
|
||||
|
||||
Do not ask users about implementation details unless necessary. If a decision can be safely inferred from the user's requirement and appliance defaults, VibeBox should choose automatically and report the choice in the final summary.
|
||||
|
||||
## 12. Review and Test Gate
|
||||
|
||||
VibeBox must maximize testing and review strength because the user may not be able to diagnose failures manually.
|
||||
|
||||
Before delivery, VibeBox must have:
|
||||
|
||||
- environment setup result
|
||||
- dependency install result
|
||||
- install/build command result
|
||||
- typecheck result where TypeScript is used
|
||||
- lint result when configured
|
||||
- unit test result when tests exist
|
||||
- integration test result for file/data flows when applicable
|
||||
- end-to-end UI test result covering the main user workflows
|
||||
- edge-case test result for invalid/empty/large inputs relevant to the app
|
||||
- persistence/restart test result when the app stores local data
|
||||
- frontend design review result
|
||||
- generated asset review result when image-gen is used
|
||||
- packaged-app launch test result
|
||||
- screenshot evidence when a display backend is available
|
||||
- reviewer report
|
||||
- final package artifact
|
||||
|
||||
Recommended review passes:
|
||||
|
||||
1. Functional review: does the app match the user's request?
|
||||
2. Runtime review: does it start and perform the golden path?
|
||||
3. Full workflow test review: are all core user workflows covered by automated tests?
|
||||
4. Edge-case review: are invalid/empty/large-input paths tested where relevant?
|
||||
5. Frontend/design review: does the UI match the generated design intent and stay usable for a novice?
|
||||
6. Asset review: are generated icons/images appropriate, local, and correctly bundled?
|
||||
7. Security review: does it avoid dangerous filesystem/network/shell behavior?
|
||||
8. Packaging review: can the delivered app run on the ARM Linux box?
|
||||
|
||||
If a gate is skipped, final report must say why. Delivery should be blocked if the app cannot be launched, packaged, or validated through all core workflows. Smoke testing alone is insufficient for delivery.
|
||||
|
||||
Delivery is blocked if:
|
||||
|
||||
- app fails to start
|
||||
- package build fails
|
||||
- generated app requests unsafe permissions not approved by user
|
||||
- reviewer finds high-severity issue
|
||||
|
||||
## 13. Packaging and Delivery
|
||||
|
||||
Default package output:
|
||||
|
||||
```text
|
||||
<app>/release/
|
||||
├── <app-name>-arm64.AppImage or unpacked Linux directory
|
||||
├── README.md
|
||||
└── vibebox-report.md
|
||||
```
|
||||
|
||||
If AppImage is not feasible on the target box, deliver an unpacked Electron app directory plus launcher script.
|
||||
|
||||
Final report includes:
|
||||
|
||||
- what was built
|
||||
- how to launch
|
||||
- where files are stored
|
||||
- tests run
|
||||
- known limitations
|
||||
- package path
|
||||
|
||||
## 14. Scope Guards
|
||||
|
||||
VibeBox should refuse or ask for escalation when user asks for:
|
||||
|
||||
- malware, credential stealing, persistence, stealth, evasion
|
||||
- destructive system modification
|
||||
- unsupported drivers/kernel changes
|
||||
- large multi-service systems
|
||||
- cloud deployment requiring secrets
|
||||
- apps that require unapproved network or filesystem access
|
||||
|
||||
## 15. Reuse Strategy
|
||||
|
||||
Reuse strongly from AirCoding:
|
||||
|
||||
- execution-primitives aligned with Claude Code
|
||||
- Anthropic canonical message handling
|
||||
- ToolResult / ArtifactRef / EvidenceRef style
|
||||
- doctor/dependency concepts
|
||||
- basic session/artifact persistence
|
||||
|
||||
Reuse from OpenCode:
|
||||
|
||||
- optional TUI style if VibeBox has an operator console
|
||||
- theme/dialog/status patterns
|
||||
|
||||
Reuse from Codex:
|
||||
|
||||
- shell/patch/test direct loop
|
||||
- broad tool/capability examples
|
||||
|
||||
Reuse from Claude Skills:
|
||||
|
||||
- packaged workflow templates
|
||||
- app-generation skill format
|
||||
|
||||
Do not carry over:
|
||||
|
||||
- AirCoding multi-agent scheduler complexity
|
||||
- C++-specific toolchain
|
||||
- long-term memory/curator in V1
|
||||
- OpenCode business state model
|
||||
|
||||
## 16. MVP Acceptance Criteria
|
||||
|
||||
A VibeBox V1 prototype is acceptable when it can:
|
||||
|
||||
1. Run doctor on the ARM Linux box.
|
||||
2. Accept a novice user's natural-language app request.
|
||||
3. Ask at most 3 clarifying questions for a simple app.
|
||||
4. Scaffold an Electron template.
|
||||
5. Implement requested UI and local behavior.
|
||||
6. Run build/typecheck/test or explain skipped gates.
|
||||
7. Launch the app for a smoke test and capture evidence.
|
||||
8. Run a review pass and fix at least one round of issues.
|
||||
9. Package the app for ARM Linux or deliver a runnable unpacked app.
|
||||
10. Produce a final user-friendly report.
|
||||
|
||||
## 17. Explicit Differences from AirCoding Baseline V1
|
||||
|
||||
| Area | AirCoding | VibeBox |
|
||||
|---|---|---|
|
||||
| Target | General coding agent, C++ first | Appliance for small Electron apps |
|
||||
| User | Developer | Beginner/non-programmer |
|
||||
| Agent model | Main + Architect + Scheduler + Workers | Linear Orchestrator + Executor + Reviewer |
|
||||
| State layout | `.air/shared` + `.air/local` | `.vibebox/` per generated app |
|
||||
| Toolchain | multi-language, C++ deep first | Electron/Node only |
|
||||
| Parallelism | write-area/worktree capable | none in V1 |
|
||||
| Memory | Project Rules + ExperienceMiner + Curator | minimal session memory only |
|
||||
| Debug knowledge | structured local DB | not in V1 |
|
||||
| UI assets | optional capability | useful for app UI generation |
|
||||
|
||||
## 18. Open Issues Before Implementation
|
||||
|
||||
Before coding VibeBox, decide:
|
||||
|
||||
1. Bun vs Node for the appliance runtime.
|
||||
2. Electron template stack: React/Vite vs plain HTML/TS.
|
||||
3. Package manager: npm vs pnpm.
|
||||
4. Packaging target: AppImage vs unpacked app + launcher.
|
||||
5. Whether VibeBox has a TUI/operator UI or only a simple local web/app shell.
|
||||
6. Exact smoke-test approach on the ARM Linux box.
|
||||
7. Whether generated apps may use network by default or must be local-only.
|
||||
174
AirPlan/docs/architecture/多模型三视角审查联合评估.md
Normal file
174
AirPlan/docs/architecture/多模型三视角审查联合评估.md
Normal file
@@ -0,0 +1,174 @@
|
||||
# 多模型三视角审查联合评估
|
||||
|
||||
Date: 2026-05-28
|
||||
Status: Resolved — all P0/P1/P2/UX issues addressed; ready for system overview design
|
||||
Scope:
|
||||
|
||||
- `AirPlan/docs/architecture/MIMO2.5三视角审查.md`
|
||||
- `AirPlan/docs/architecture/DeepSeekV4Pro三视角审查.md`
|
||||
- `Opus4.7三视角审查.md`
|
||||
- `AirPlan/docs/analysis/requirements.md`
|
||||
- `AirPlan/docs/architecture/*`
|
||||
- `AirPlan/plan.md`
|
||||
- `AirPlan/todo.md`
|
||||
- `idea.md`
|
||||
|
||||
## 1. Executive Conclusion
|
||||
|
||||
三份多模型三视角审查在总体方向上高度一致:AirCoding V1.0.0 Alpha 的核心架构方向成立,需求主干对齐,包边界和事件驱动/SQLite 恢复/ToolRegistry + PermissionEngine/独立 worker 进程等关键决策没有方向性错误。
|
||||
|
||||
但报告指出的问题大部分属实,且集中在进入下一阶段前最容易放大的层面:公共契约冻结、跨文档源定义冲突、V1.0.0 Alpha 范围表述漂移,以及若干原始用户体验需求未进入 `plan.md` / `todo.md`。因此不建议直接进入系统概要设计或详细设计。
|
||||
|
||||
阶段门建议:
|
||||
|
||||
```text
|
||||
GO with remediation gate:
|
||||
先处理 P0/P1 架构与契约清理,再进入系统概要设计;
|
||||
不要在这些问题未清理前开始 packages/contracts 或详细设计。
|
||||
```
|
||||
|
||||
## 2. Cross-Model Consensus
|
||||
|
||||
| Area | MIMO2.5 | DeepSeek V4 Pro | Opus 4.7 | Joint assessment |
|
||||
|---|---|---|---|---|
|
||||
| Core architecture direction | 正确 | 正确 | 正确 | 属实:方向成立 |
|
||||
| Requirements alignment | 基本满足 | 完全对齐 | 技术主干满足、UX 计划遗漏 | 属实但需区分技术主干与 UX 表面 |
|
||||
| Interface-contract drift | 高风险 | 高风险 | 高风险 | 属实:进入实现前必须清理 |
|
||||
| DB / event / external store gaps | 高风险 | 高风险 | 中高风险 | 属实:尤其 project-level DB schema 与 FK invariant |
|
||||
| V1.0.0 Alpha vs MVP wording | 未作为主问题 | 未作为主问题 | 关键问题 | 属实:文档漂移影响范围纪律 |
|
||||
| TUI/runtime boundary | 基本认可 ProjectionClient | 基本认可 ProjectionClient | 认为 transport 未定 | 部分属实:边界有,传输机制缺 |
|
||||
| User-facing command/UX gaps | 基本认为满足 | 基本认为满足 | 明确指出遗漏 | 属实:计划/todo 未覆盖若干原始需求 |
|
||||
|
||||
## 3. Verified Findings
|
||||
|
||||
### P0 — Must fix before next phase
|
||||
|
||||
这些问题会导致 `packages/contracts` 冻结失败、实现者根据不同文档写出不兼容代码,或使下一阶段设计建立在不稳定接口上。
|
||||
|
||||
| ID | Finding | Source evidence | Verdict | Required action |
|
||||
|---|---|---|---|---|
|
||||
| P0-1 | `AirError.cause_ref` 类型冲突 | `interface-contracts-v1.md` defines `cause_ref?: EntityRef`; `error-taxonomy-v1.md` defines multi-key object | True | 选定唯一形状。若按 current precedence,改 `error-taxonomy-v1.md` 为 `EntityRef`;若采用多引用诊断能力,则更新 `interface-contracts-v1.md` 并明确 `cause_refs` 数组 |
|
||||
| P0-2 | `EntityRef` / `EntityType` 重复且集合不一致 | `interface-contracts-v1.md` has 12 types including `capability` and `provider`; `event-registry-v1.md` inline `EntityRef` has 10 | True | `event-registry-v1.md` 不再内联定义,引用 contracts 的 `EntityRef` |
|
||||
| P0-3 | `PermissionProfile` 概念命名冲突 | `security-model-v1.md` uses `PermissionProfile = low/normal/high/developer`; `interface-contracts-v1.md` and `baselineV1.md` use `permission_profile = main_direct/executor/...` | True | 将角色模板字段改为 `permission_template` 或 `role_permission_template`;安全态势保留 `permission_profile` |
|
||||
| P0-4 | `TaskInsert = TaskRecord` 不适合作为 insert 契约 | `interface-contracts-v1.md` line concept requires caller-provided generated/default fields | True | 定义 `TaskInsert` / `EventInsert` 子集类型,移除调用方不应提供的默认/生成字段 |
|
||||
| P0-5 | `FollowUpTask.type` 包含 `docs`,但 `TaskType` 不包含 | `interface-contracts-v1.md`: `TaskType` lacks `docs`; `FollowUpTask.type?: TaskType | "docs"` | True | 将 `docs` 加入 `TaskType`,或把 follow-up docs 从 scheduler task 类型中分离 |
|
||||
| P0-6 | `DebugKnowledgeStore` / `LearnedMemoryStore` 被运行时语义引用但无契约 | `runtime-semantics-v1.md` references `DebugKnowledgeStore` and ExperienceMiner/Curator learned-memory writes; `interface-contracts-v1.md` lacks interfaces | True | 在 contracts 或 runtime public contract 中补接口与错误/恢复语义 |
|
||||
| P0-7 | `PromptLayer` / `PromptLayerLoader` / `CompactionPolicy` 被 code-view 引用但 interface contracts 未定义 | `c4/code-view.md` lists classes and `PromptLayer[]`; `interface-contracts-v1.md` only has minimal `ContextAssembler` | True | 补上下文层契约,至少定义 `PromptLayer`、预算结果、加载器/策略边界 |
|
||||
| P0-8 | `debug-records.db` / `learned-memory.db` 无 DDL | `db-schema-v1.md` only defines session DB, while these DBs are in project layout and event/runtime semantics | True | 在 `db-schema-v1.md` 增加 project-level DB schema 或独立 schema 文档并加入 precedence |
|
||||
| P0-9 | ProviderAdapter 方法名跨文档冲突 | `interface-contracts-v1.md` uses `list_models`, `validate_model`, `count_tokens`; `provider-capability-matrix-v1.md` uses camelCase | True | 统一为 internal exported contracts 的 snake_case,并更新 matrix 文档 |
|
||||
| P0-10 | `Diagnostic` 类型缺失 | `c4/code-view.md` has `DiagnosticParser.parse_compiler_output(...): Diagnostic[]`; contracts only define event payload/DB row concepts | True | 增加 `Diagnostic` / `DiagnosticRecord` / parser output contract |
|
||||
|
||||
### P1 — Should fix before system overview design
|
||||
|
||||
这些问题未必阻止 contracts 首次编译,但会影响概要设计的边界表达、测试计划和任务拆解。
|
||||
|
||||
| ID | Finding | Source evidence | Verdict | Required action |
|
||||
|---|---|---|---|---|
|
||||
| P1-1 | V1.0.0 Alpha 与 MVP cut line 术语漂移 | 多个较旧规范仍有 `MVP Cut Line`; newer `requirements.md`, `plan.md`, `runtime-semantics-v1.md` use V1.0.0 Alpha | True | 将所有规范中的 MVP cut line 改为 V1.0.0 Alpha cut line,或明确定义 MVP skeleton 是 Alpha 内部阶段 |
|
||||
| P1-2 | `main-agent-state-machine.md` 仍是早期草案 | 无日期/status;事件名如 `UserMessageReceived` 不在 event registry;DIRECT_MODE 未与 scheduler/task/write scope 绑定 | True | 重写或降级为 historical;对齐 event registry、direct mode、confirmation flow |
|
||||
| P1-3 | C++ DiagnosticParser ownership 表述冲突 | `baselineV1.md` says LLM-based DiagnosticParser; `runtime-semantics-v1.md` says deterministic extraction in toolchain-cpp and LLM interpretation in runtime Debugger/Reviewer | True | 更新 `baselineV1.md`:toolchain-cpp only deterministic parse/signature;LLM interpretation belongs runtime roles |
|
||||
| P1-4 | TUI ↔ runtime transport 未定 | contracts define `ProjectionClient`; C4 says narrow UI API; no in-process vs IPC/command-channel contract | Partially true | 保留 ProjectionClient 边界,但补 `ProjectionTransport` / UI command API 的最小 V1 决策 |
|
||||
| P1-5 | `foreign_keys = OFF` 有理由但缺应用层一致性契约 | `db-schema-v1.md` gives rationale; no orphan/invariant check list | True | 在 runtime semantics 或 DB schema 增加 repository invariant checks、orphan scan、release gate |
|
||||
| P1-6 | `EventBus.subscribe` handler 异常行为未定义 | contracts only define signature; no error propagation semantics | True | 明确 handler error 不传播到 publisher,记录 developer log / event,订阅是否保持 |
|
||||
| P1-7 | `PermissionEngine.record` 无失败路径 | returns `Promise<void>` despite evidence-first and durable decision record expectations | True | 改为 Result-like contract 或明确 typed throw / failure event |
|
||||
| P1-8 | `PathPolicy` 缺 source/role 元数据 | `PathPolicy` only allow/deny; permission model depends on profile/task/capability layers | Mostly true | 若 PathPolicy 只是 raw path list,可延迟;若用于审计决策,需补 `source` / `origin` |
|
||||
| P1-9 | `SchedulerWavePlan.wave_id` 未品牌化 | `wave_id: string`; other IDs are aliases | True but low impact | 增加 `WaveID` 或接受为 non-persistent local ID并说明 |
|
||||
| P1-10 | `ToolCategory` / `ToolResultEnvelope` 重复定义 | `interface-contracts-v1.md` and `tool-registry-v1.md` both inline definitions | True as documentation drift | tool registry doc 改为引用 contracts;避免未来复制到同一 package 时报重复 |
|
||||
| P1-11 | IPC handshake/protocol lifecycle不足 | `IpcEnvelope` has direction but no protocol_version; only `agent.start.version`; no worker ready/hello | True | 增加 `protocol_version` 或 `worker.ready` / version negotiation 最小流程 |
|
||||
| P1-12 | IPC direction not type-enforced | `IpcEnvelope.direction` exists but payload union not discriminated by direction/kind | True but can be runtime-guarded | 最好定义 parent/worker message union;否则明确 runtime validation guard |
|
||||
| P1-13 | DB closed enums 多处未规范 | task_attempts.status, summaries.type, evidence_refs.kind, artifacts.type, diagnostics.severity are open `TEXT` | True | 在 DB schema and contracts 增加 closed enum inventory or documented open extension policy |
|
||||
|
||||
### P2 — Can defer, but should be tracked
|
||||
|
||||
| ID | Finding | Verdict | Suggested handling |
|
||||
|---|---|---|---|
|
||||
| P2-1 | `JsonSchema<T>` phantom generic | True | 可先品牌化或记录 nominal-only;不阻塞概要设计 |
|
||||
| P2-2 | `ToolExecutor.execute()` stream/non-stream union不便测试 | True | 可在 contracts pass 中拆分 `ToolExecutor` / `StreamingToolExecutor` |
|
||||
| P2-3 | `ProjectionStore.apply(RuntimeEvent)` 未类型窄化 | True | 可通过 doc + event handler map 实现;非阶段门阻塞 |
|
||||
| P2-4 | `MessageRecord.role: string` 等 open string | True | 与 P1 closed enum pass 合并处理 |
|
||||
| P2-5 | route_prefix SQLite LIKE 索引性能 | Plausible, not architectural blocker | 实现/性能测试阶段处理 |
|
||||
| P2-6 | Workspace GC retention | True | 加入 runtime semantics/todo;不阻塞 contracts |
|
||||
| P2-7 | Doctor bootstrap self-check | True | 加入 Doctor design/todo;不阻塞 contracts |
|
||||
|
||||
## 4. User-Requirement Alignment Check
|
||||
|
||||
技术主干需求已经在 `requirements.md` 和架构中覆盖:自有 runtime、项目本地状态、SQLite 恢复、独立 worker、C++ 深度工具链、PermissionEngine、Provider boundary、OpenTUI ProjectionStore、Doctor、插件/能力基础均成立。
|
||||
|
||||
但 Opus 用户视角指出的若干 UX/操作面计划遗漏属实:
|
||||
|
||||
| Requirement / decision | Evidence | Current plan/todo state | Verdict |
|
||||
|---|---|---|---|
|
||||
| `/direct` / `/done` direct mode | `idea.md` §5.2; `baselineV1.md` says direct mode foreground lane; `main-agent-state-machine.md` mentions DIRECT_MODE | `plan.md` and `todo.md` have no direct-mode task/contract | True gap |
|
||||
| `air restore` three granularities | `idea.md` §10.3; D-032 | no explicit restore task in `todo.md` | True gap |
|
||||
| ExperienceMiner N-turn Nudge trigger | `idea.md` §12.2; D-024 | T-033 only says candidate flow; no cadence/trigger scheduler detail | True gap |
|
||||
| Curator periodic dedup/archive | `idea.md` §12.2; D-024 | no todo item | True gap |
|
||||
| self-patch flow for stale rules/skills | D-024; runtime-semantics mentions outdated rules route to ExperienceMiner/Curator | no explicit todo/acceptance criterion | True gap |
|
||||
| Doctor fix mode and bundle export | FR-018 requires fix mode; plan Phase 8 has doctor report bundle; T-034 only read-only Doctor | Partially covered; todo incomplete |
|
||||
| CLI command catalog (`resume`, `compact`, `history`, etc.) | idea-level UX | not in `plan.md` / `todo.md` | True gap if intended for Alpha; otherwise explicitly defer |
|
||||
| VibeBox branch visibility | branch baseline exists | main plan/todo does not schedule VibeBox | Not blocker for AirCoding Alpha if explicitly downstream/post-Alpha |
|
||||
|
||||
Conclusion: the architecture does not conflict with user intent, but the Alpha plan risks delivering a strong runtime with an under-specified user-facing command surface unless the omissions are either scheduled or explicitly deferred.
|
||||
|
||||
## 5. Findings That Are Not Fully Supported
|
||||
|
||||
| Claim | Assessment |
|
||||
|---|---|
|
||||
| `foreign_keys = OFF` is itself a blocker | Overstated. The setting is documented with rationale in `db-schema-v1.md`; the real issue is missing invariant/recovery checks, not FK-off itself. |
|
||||
| TUI boundary is completely missing | Overstated. `ProjectionClient` and no-DB/no-EventBus rules exist. Missing part is transport and UI command channel, not the architectural boundary. |
|
||||
| Core architecture fails original requirements | Not supported. Requirements are broadly covered; gaps are UX scheduling and contract details. |
|
||||
| Provider capability matrix is necessarily over-engineered | Judgment call. It is more elaborate than minimal Alpha, but it supports stated provider flexibility and conversion-report requirements. |
|
||||
| 14 architecture docs should be trimmed before proceeding | Optional. The real requirement is consistency and precedence, not fewer docs. |
|
||||
|
||||
## 6. Recommended Remediation Plan
|
||||
|
||||
### Pass A — Source-of-truth and vocabulary cleanup
|
||||
|
||||
1. Replace or define all `MVP Cut Line` sections as `V1.0.0 Alpha Cut Line` / `V1 skeleton within Alpha`.
|
||||
2. Add `packages/contracts` to the canonical package list in `baselineV1.md`.
|
||||
3. Mark `main-agent-state-machine.md` as V1-aligned or historical; if kept, align event names with `event-registry-v1.md`.
|
||||
4. Update `baselineV1.md` DiagnosticParser wording to match `runtime-semantics-v1.md`.
|
||||
|
||||
### Pass B — Public contract freeze repair
|
||||
|
||||
1. Resolve `AirError.cause_ref` shape.
|
||||
2. Single-source `EntityRef` and `EntityType`.
|
||||
3. Rename role permission template field away from security `PermissionProfile`.
|
||||
4. Fix `TaskInsert`, `EventInsert`, `TaskType/docs`, `WaveID`.
|
||||
5. Add missing contracts: `Diagnostic`, `DebugKnowledgeStore`, `LearnedMemoryStore`, `PromptLayer`, `PromptLayerLoader`, `CompactionPolicy`, `EventSchemaRegistry`.
|
||||
6. Normalize ProviderAdapter method names to snake_case.
|
||||
7. Decide IPC protocol version/handshake and direction-typed unions or runtime validation contract.
|
||||
|
||||
### Pass C — Persistence/runtime invariant repair
|
||||
|
||||
1. Add schema for `debug-records.db` and `learned-memory.db`, or create separate canonical schema docs.
|
||||
2. Add application-level reference consistency invariants for `foreign_keys = OFF`.
|
||||
3. Define EventBus subscriber error behavior.
|
||||
4. Define PermissionEngine record failure behavior.
|
||||
5. Add closed enum inventory for DB/contract fields or explicitly mark extension points.
|
||||
|
||||
### Pass D — UX scope gate
|
||||
|
||||
1. Decide which UX commands are Alpha: `/direct`, `/done`, `air restore`, `resume`, `compact`, `history`, `doctor --fix`, `doctor --bundle`.
|
||||
2. For included commands, add `todo.md` rows and plan deliverables.
|
||||
3. For deferred commands, record explicit post-Alpha scope so they are not silently lost.
|
||||
4. Add ExperienceMiner Nudge cadence, Curator, and self-patch acceptance criteria if they remain Alpha.
|
||||
|
||||
## 7. Phase-Gate Decision
|
||||
|
||||
Do not start implementation or detailed design yet.
|
||||
|
||||
Recommended next step:
|
||||
|
||||
```text
|
||||
1. Complete Pass A–C as architecture/document edits.
|
||||
2. Update `AirPlan/todo.md` with any P0/P1 remediation tasks and UX scope decisions.
|
||||
3. Then proceed to system overview design.
|
||||
4. Only after overview design is consistent, produce detailed design and start Phase 0 contracts implementation.
|
||||
```
|
||||
|
||||
Rationale:
|
||||
|
||||
- P0 findings directly affect `packages/contracts`, DB schema, and code-view boundaries.
|
||||
- If ignored, they will force contract churn during Phase 0/1 and invalidate parallel execution boundaries.
|
||||
- The fixes are mostly documentation/contract edits, not architectural redesign.
|
||||
- Core architecture is sound, so the remediation should be short and bounded rather than a new planning cycle.
|
||||
Reference in New Issue
Block a user