opentmd

atomcode-capabilities · subagent / team / setup / world / notify / atomgit

概述

本文覆盖 crates/atomcode-capabilities/src/ 下 6 个与 provider 无关的 L1 能力模块。它们都只依赖 atomcode-kernel(以及可选的 config/auth/i18n),不依赖 atomcode-core。L2 宿主(atomcode-coding、atomcode-harness、atomcode-cli、atomcode-daemon)负责装配和 UI:

模块 一句话 feature
subagent/ 把外部 CLI agent(Claude Code、Codex、Grok、OpenCode)包装成 subagent_<name> 工具,带进程树回收、超时、配额记忆、只读策略校验 subagent(依赖 tools)
team.rs 多 agent 团队的中立契约:14 个内置角色、任务规格、worker 写入范围冲突检测、团队事件编码 无 gate
setup/ /setup 项目初始化:扫描项目信号、解压内嵌种子技能、事务化写入、双轨锁、状态文件、能力推荐目录 setup
world.rs “世界”抽象:FileSystem / Shell / Process trait 和 LocalFs。工具所有 I/O 与判断都通过同一个世界完成,只读是世界的属性 无 gate
notify.rs 回合结束与等待审批的桌面通知:终端 OSC 序列(Kitty/WezTerm/Ghostty/iTerm2)、BEL、系统通知回退 notify(依赖 config)
atomgit/ AtomGit/GitCode v5 REST 客户端与模型,支撑 atomgit_repo/pr/issue/api 工具;git push 后自动打 atomcode 项目标签的中间件 atomgit(tools + reqwest + auth)

团队的“收件箱、唤醒、worktree 隔离”等运行时逻辑不在本 crate,而在 atomcode-harness/src/plugins/team.rs(2393 行)和 atomcode-coding/src/team/manager.rs(见 ADR 0016)。内置 task 子代理工具在 atomcode-harness/src/plugins/subagent.rs(931 行)。本 crate 只提供它们共享的数据契约和外部 CLI 驱动。

源码根:/home/jiahua/Desktop/ETC/atomcode/crates/atomcode-capabilities/src/。


1. 职责与定位

2. 依赖图中的位置

atomcode-kernel (L0): Tool / ToolMiddleware / ToolCall / RiskLevel / CancellationToken ...
        ▲
atomcode-capabilities (L1)
  ├─ subagent/  ──uses──► tools::ToolRegistry, tokio::process, chrono-tz
  ├─ team.rs    (serde only)
  ├─ setup/     ──uses──► atomcode-config::ProductDirs, sha2, fs2, sysinfo, zstd, tar, tempfile
  ├─ world.rs   ──uses──► ignore/globset (walk), tools::bash::LocalShell (re-export)
  ├─ notify.rs  ──uses──► atomcode-config::NotificationConfig, atomcode-i18n
  └─ atomgit/   ──uses──► reqwest, atomcode-auth::oauth
        ▲
consumers:
  atomcode-coding/src/parts.rs:926   register_external_subagent_tools
  atomcode-coding/src/team/manager.rs role_by_id / validate_non_overlapping_worker_scopes / TeamEvent
  atomcode-harness/src/plugins/{subagent,team,world}.rs
  atomcode-cli    (features: notify, setup, atomgit, ...)
  atomcode-daemon (features: atomgit, tools, ...)

3. 模块地图

文件 行数 职责
subagent/mod.rs — 配置模型 ExternalSubagentProfile、SubagentKind、PermissionMode、SubagentBackend trait、事件与错误类型
subagent/tool.rs — ExternalSubagentTool(实现内核 Tool)、register_external_subagent_tools、PATH 探测、工作区预检
subagent/proc.rs — ChildSpec / ManagedChild:进程组或 Job Object,杀整棵进程树;stderr 尾部;wait_or_kill
subagent/failure.rs — 从 stderr/输出分类权限拒绝与 Claude 配额耗尽(解析重置时刻)
subagent/codex.rs — codex exec --json 驱动,解析 JSONL 活动,读 -o 最终答案文件
subagent/claude_code.rs — claude -p --output-format json 驱动,配额记忆
subagent/read_only_cli.rs — Grok 与 OpenCode 的只读驱动(固定参数,OpenCode 运行前校验有效策略)
team.rs 632 角色目录、任务规格、范围重叠检测、团队事件
setup/mod.rs — run() 编排
setup/scan.rs — 纯文件系统扫描生成 ProjectSignals
setup/seeds.rs — 内嵌 setup-seeds.tar.zst 的解压与缓存
setup/install.rs — InstalledTxn RAII 事务:默认回滚,commit 生效
setup/lock.rs — fs2 文件锁加 PID/start_time 哨兵的双轨锁
setup/state.rs — setup-state.json 与 compute_signals_hash
setup/types.rs — RecKind/RecId/Marker/Stack/Framework/PkgMgr... 纯类型
setup/fs_atomic.rs — 原子写:同目录临时文件、fsync、persist、父目录 fsync
setup/recommendations.rs 76 离线能力推荐目录(ast-grep / Context7 / 各语言 LSP)
setup/error.rs — SetupError
build.rs ~60 把 assets/setup-seeds/ 打包为 OUT_DIR/setup-seeds.tar.zst
world.rs 2401 FileSystem/Shell/Process trait、LocalFs、walk/search 实现
notify.rs 850 通知规划与投递
atomgit/mod.rs 105 TokenProvider、AtomgitConfig、DEFAULT_BASE_URL
atomgit/client.rs 475 AtomgitClient:鉴权、错误映射、写操作“结果不确定”语义
atomgit/repo.rs / pr.rs / issue.rs 398 / 502 / 281 端点封装(路径对齐 ag-cli)
atomgit/models.rs 222 serde 模型,de_u64_flex 兼容数字字符串
atomgit/remote.rs 178 git remote URL 解析为 PushTarget
atomgit/push_label_mw.rs 222 GitPushLabelMiddleware
tools/atomgit.rs 1881 4 个 agent 工具的 schema 与分发(属于 tools 模块,此处一并说明)

(“—”表示未逐一统计,subagent/ 合计约 3243 行。)


4. subagent:外部 CLI agent 作为工具

设计规格:docs/plans/2026-08-21-external-agent-subagent-drivers-spec.md。

4.1 配置与核心类型(subagent/mod.rs)

配置来自 [[subagent.external]]:

[[subagent.external]]
name = "claude"          # 工具名 → subagent_claude
kind = "claude-code"     # claude-code|claude_code|claude|cc / codex / grok|grok-build / opencode
model = "sonnet"         # 可选
permission = "read-only" # read-only(默认) | accept-edits | auto | bypass
allow_dangerous = false  # bypass 必须显式允许
timeout = 600            # 秒,可选
pub struct ExternalSubagentProfile { name, kind: SubagentKind, model: Option<String>,
    permission: PermissionMode, allow_dangerous: bool, timeout: Option<Duration> }
pub enum SubagentKind { ClaudeCode, Codex, Grok, OpenCode }     // binary(): claude/codex/grok/opencode
pub enum PermissionMode { ReadOnly, AcceptEdits, Auto, Bypass } // is_dangerous(): Bypass
pub struct SubagentCapabilities { tool_filter: bool, structured_output: bool }
pub enum SubagentEvent { Activity(String), TextDelta(String) }
pub type EventSink = Box<dyn Fn(SubagentEvent) + Send + Sync>;
pub struct SubagentRun { prompt, cwd: PathBuf, tool_filter, cancel: CancellationToken,
                         on_event: Option<EventSink> }
pub enum SubagentStopReason { Completed, Cancelled, PermissionDenied, Timeout }
pub struct SubagentResult { output: String, stop_reason: SubagentStopReason }
pub enum SubagentError { WorkspaceUnavailable, PermissionDenied, RateLimited{message, retry_at},
    BinaryNotFound, SpawnFailed, NonZeroExit{code, stderr_tail}, ProtocolError,
    AgentError, DangerousModeRefused }

#[async_trait]
pub trait SubagentBackend: Send + Sync {
    fn name(&self) -> &str; fn kind(&self) -> SubagentKind;
    fn capabilities(&self) -> SubagentCapabilities;
    async fn run(&self, run: SubagentRun) -> Result<SubagentResult, SubagentError>;
}

4.2 工具包装(subagent/tool.rs)

4.3 进程管理(subagent/proc.rs)

pub struct ChildSpec { program, args, cwd, env: Vec<(String,String)>, stdin: StdinMode /* Null|Piped */ }
pub enum WaitOutcome { Exited(ExitStatus), TimedOut, Cancelled }
impl ManagedChild {
    pub async fn wait_or_kill(&mut self, timeout: Duration, cancel: &CancellationToken) -> WaitOutcome;
}

4.4 失败分类(subagent/failure.rs)

4.5 各驱动

驱动 命令行 输出解析 默认超时
Codex(codex.rs) codex exec --skip-git-repo-check --json --cd <cwd>,加 --sandbox read-only / --sandbox workspace-write / --dangerously-bypass-approvals-and-sandbox,加 -o <tempfile> 和 [-m model];prompt 走 stdin JSONL 活动:command_execution 显示为 $ cmd,另有 web_search、mcp_tool_call、file_change,reasoning 显示为 “thinking…”;turn.failed 映射为 AgentError。最终答案读 -o 文件,为空时回退到流里最后一个 item.completed 的 agent_message(测试 run_falls_back_to_stream_when_output_file_is_empty) 600 s
Claude Code(claude_code.rs) claude -p --output-format json,加 --permission-mode plan / acceptEdits / auto 或 --dangerously-skip-permissions,加 [--model] 单个 JSON:result、is_error(缺失时看 subtype,如 error_max_turns);is_error 映射为 AgentError 600 s
Grok(read_only_cli.rs,仅 macOS/Linux) grok --no-auto-update --sandbox read-only --permission-mode dontAsk --no-subagents --disable-web-search --tools read_file,list_dir,grep --disallowed-tools search_tool,use_tool --output-format streaming-json --single=<prompt> streaming-json 待确认
OpenCode(read_only_cli.rs) opencode --pure run --format json --agent atomcode-readonly;prompt 走 stdin;环境变量 OPENCODE_DISABLE_PROJECT_CONFIG=1、OPENCODE_DISABLE_AUTOUPDATE=1、OPENCODE_CONFIG_CONTENT=<默认拒绝,仅允许 read/glob/grep/list 的 agent 定义> JSON 事件;输出上限 MAX_OUTPUT_BYTES=64 KiB 待确认

4.6 与内置 task 子代理的关系

内置的同进程子代理(工具名 task)在 atomcode-harness/src/plugins/subagent.rs。按其模块注释,子代理是“同进程中拥有自己世界的第二个 agent”:

外部 CLI 子代理则是进程级隔离,靠对方 CLI 自身的沙箱和权限模式加上本 crate 的参数固化。


5. team.rs:团队协作的中立契约

5.1 角色目录

pub enum TeamRoleId { Planner, Architect, Explorer, Implementer, Rust, TuiUx, Reviewer,
    Tester, Debugger, Security, Performance, DocsWriter, ReleaseManager, MigrationCompat }
pub enum TeamPermission { Explore, Worker }   // Worker 可写
pub enum TeamDifficulty { Simple, Hard }      // Simple → 可走 llm-utility 便宜模型
pub struct TeamRoleProfile { id, display_name, permission, difficulty, persona: &'static str,
                             when_to_use: &'static str }
pub static BUILT_IN_ROLES: [TeamRoleProfile; 14];
pub fn role_by_id(id: &str) -> Option<&'static TeamRoleProfile>;

5.2 任务规格与写入范围冲突检测

#[serde(transparent)] pub struct TeamRunId(String);
#[serde(transparent)] pub struct TeamMemberId(String);
pub struct TeamTaskSpec { description, prompt, role: String, permission: Option<TeamPermission>,
                          difficulty: Option<TeamDifficulty>, scope: Vec<String> /* glob */ }
pub fn validate_non_overlapping_worker_scopes(tasks: &[TeamTaskSpec]) -> Result<(), String>;
pub fn worker_scopes_overlap(a: &str, b: &str) -> bool;

5.3 团队事件编码

pub const TEAM_EVENT_MARKER: char = '\u{1f}';    // ASCII Unit Separator
pub fn encode_team_event(e: &TeamEvent) -> String; // MARKER + JSON
pub fn decode_team_event(s: &str) -> Option<TeamEvent>;
pub struct TeamEvent { run_id: TeamRunId, seq: u64, payload: TeamEventPayload }
#[serde(tag = "type")]
pub enum TeamEventPayload { RunStarted{..}, MemberQueued{..}, MemberStarted{..},
    MemberActivity{ output_tokens /* chars/4 估算 */, tool_uses, .. },
    MemberFinished{..}, RunFinished{..} }

用控制字符前缀,把结构化事件混入普通的工具进度文本通道:UI 端识别前缀后解码,普通文本照常显示。这样团队面板不需要新增 IPC 通道。

5.4 收件箱与未完成工作(在 harness/coding,非本 crate)


6. setup/:项目初始化流水线

6.1 入口与流程(setup/mod.rs)

pub struct RunOptions { pub project_root: PathBuf, pub dirs: ProductDirs, pub force: bool }
pub struct SetupReport { pub summary: InstalledSummary, pub duration_ms: u64 }
pub fn run(opts: RunOptions) -> SetupResult<SetupReport>; // 同步;async 中请 spawn_blocking
run()
 ├─ SetupLock::acquire(<root>/.atomcode, force)  ─ 持有中 → SetupError::LockHeld{pid,start_time,host}
 ├─ scan::scan(root) → ProjectSignals ; compute_signals_hash(markers)
 ├─ seeds::ensure_seeds_extracted(user_dir) → cache_dir
 ├─ InstalledTxn::new(root, project_dir)
 ├─ install_directory_skills_from_seeds(cache_dir/skills → <user>/skills/<name>)
 │     每个技能目录算内容哈希(排序后相对路径 + 内容的 SHA-256)→ `.seed-hash`
 │     哈希相同且 !force → skipped(AlreadyInstalled);否则删除重拷 → installed + ReloadDirective::Skill
 ├─ txn.append_gitignore(".atomcode/local/")   (幂等,有备份)
 ├─ txn.commit() → InstalledSummary
 └─ save_setup_state(project_dir, SetupState{...})   (原子写)
 drop(lock)  → 解锁 fs2 + 删除哨兵

dirs: ProductDirs 让“改名发行版”只写自己的目录名(测试 a_renamed_distribution_writes_only_under_its_own_names)。

6.2 扫描(setup/scan.rs)

纯文件系统内省,不调用 git/npm/cargo,不调用 LLM:

6.3 信号哈希与状态(setup/state.rs)

pub const STATE_FILENAME: &str = "setup-state.json";   // 位于 <root>/.atomcode/
pub const CURRENT_SCHEMA_VERSION: u32 = 1;
pub struct SetupState { schema_version, signals_hash: String /* "sha256:<hex>" */,
    completed_at: DateTime<Utc>, atomcode_version: String, accepted: Vec<RecIdRef{kind, slug}> }

6.4 内嵌种子(build.rs + setup/seeds.rs)

6.5 事务化安装(setup/install.rs)

6.6 双轨锁(setup/lock.rs)

单靠 flock 在沙箱、NFS 或容器里不可靠,所以用两条轨道:

  1. 哨兵 <project dir>/.setup.lock.sentinel,内容为 JSON {pid, start_time_nanos, host, atomcode_version}。
    • 记录的 PID 存活且进程启动时间吻合(sysinfo)时视为被持有,可防 PID 复用误判。
    • 持有且未 force:返回 LockError::Held。
    • 过期:删除哨兵。
    • force 且对方存活:不删哨兵,交给 fs2 判定。fs2 也被占用说明对方确实在跑,force 也抢不了。
  2. fs2::try_lock_exclusive 锁 <project dir>/.setup.lock。
  3. 写入新哨兵。

Drop 时解锁并删除哨兵,但保留 .setup.lock 文件,以复用 inode。测试 concurrent_runs_second_fails_lock。

6.7 原子写(setup/fs_atomic.rs)

atomic_write(path, content, mode):在同目录创建 tempfile,写入并 fsync,然后 persist(Windows 上为 MoveFileEx 替换语义),最后对父目录 fsync(POSIX)。

6.8 能力推荐目录(setup/recommendations.rs)

pub enum Capability { AstGrep, Context7, NativeLsp { extension: &'static str } }
pub struct Recommendation { id, revision: u32 /* 变更足够大时才 bump,用于重新提示 */, name, capability }
pub const CONTEXT7_URL: &str = "https://mcp.context7.com/mcp";
pub fn recommendations_for(stacks: &[Stack]) -> Vec<Recommendation>;

7. world.rs:世界抽象

7.1 设计原则

模块注释的核心句:“工具据以分支的每个事实,必须来自它 I/O 去往的同一个世界。”

7.2 FileSystem

pub enum FsErrorKind { NotFound, NotAFile, NotADirectory, Denied, NotText, Io }
pub struct FsError { kind: FsErrorKind, message: String }

#[async_trait]
pub trait FileSystem: Send + Sync {          // world.rs:296
    fn describe(&self) -> String;
    fn root(&self) -> &Path;
    async fn read_bytes(&self, p: &Path) -> Result<Vec<u8>, FsError>;
    async fn write_bytes(&self, p: &Path, data: &[u8]) -> Result<(), FsError>;
    async fn create_dir_all(&self, p: &Path) -> Result<(), FsError>;
    async fn list(&self, p: &Path) -> Result<Vec<DirEntry>, FsError>;
    async fn info(&self, p: &Path) -> Result<FileInfo, FsError>;
    async fn canonicalize(&self, p: &Path) -> Result<PathBuf, FsError>;
    // 带默认实现:
    async fn count_lines_bounded(..); async fn walk(..); async fn walk_with_options(..);
    async fn search(..); async fn read_text(..); async fn write_text(..); async fn edit_text(..);
}

7.3 LocalFs(world.rs:832)

构造器 读 写
unfenced() 任意 任意
new(root) 根内 根内
read_only(root) 根内 拒绝
read_only_unfenced() 任意 拒绝
writes_fenced(root) 任意 根内
.also_writable(dir) / .also_readable(dir) 追加允许的目录(记录其真实路径)  

7.4 Shell / Process

pub enum ShellDialect { Bash, Cmd, PowerShell }
pub enum SpawnError { Unsupported, Failed(String) }
#[async_trait] pub trait Process: Send {
    async fn next_chunk(&mut self) -> Option<Chunk>;   // 原始字节,stdout/stderr 区分
    async fn wait(&mut self) -> Exit; fn kill(&mut self); fn terminate(&mut self);
    async fn collect(..); async fn collect_within(.., timeout);
}
pub trait Shell: Send + Sync {
    fn describe(&self) -> String; fn dialect(&self) -> ShellDialect;
    fn spawn(&self, command: &str, cwd: &Path, ..) -> Result<Box<dyn Process>, SpawnError>;
    fn spawn_program(..) -> Result<..> { Err(Unsupported) }
    fn powershell(&self) -> Option<..> { None }
    fn decode(&self, bytes: &[u8]) -> String { /* UTF-8 lossy */ }
}

8. notify.rs:回合与审批通知

8.1 类型

pub enum NotifyStopReason { Natural, Cancelled, Error, TurnLimit, StepLimit }
pub struct TurnNotification { duration, turn_count, tool_call_count, total_tokens,
                              stop_reason, working_dir }
pub struct ApprovalNotification { tool_name, detail, working_dir }
pub enum NotificationEvent { ApprovalNeeded(ApprovalNotification), TurnFinished(TurnNotification) }
pub fn set_terminal_focus_state(focused: Option<bool>);  // 全局 AtomicU8: 未知/聚焦/失焦
pub fn terminal_focus_state() -> Option<bool>;

TUI 开启终端焦点上报(CSI ? 1004 h)后,把 FocusGained/FocusLost 写入全局状态。

8.2 配置(atomcode-config config/mod.rs:2234)

[notification]
enabled = true
min_duration_secs = 8     # 回合短于此不通知(审批不受限)
terminal = true           # 终端 OSC
system = true             # 系统通知
bell = true               # BEL
background_only = true    # 仅在终端失焦时

8.3 规划规则

  1. enabled=false:不通知。
  2. background_only 且已知聚焦:抑制。
  3. TurnFinished 且时长 < min_duration_secs:抑制。ApprovalNeeded 不受阈值限制。
  4. emit_system 需要同时满足:
    • cfg.system;
    • 非 Windows:PowerShell NotifyIcon 方案曾导致 TUI 崩溃,已禁用;
    • 若 background_only,焦点必须确知为失焦,未知不算。

8.4 投递

终端 序列
Kitty OSC 99:\x1b]99;i=<id>:o=<visibility>:d=0;<title>\x1b\\,再发 p=body 的正文段
WezTerm / Ghostty OSC 777:\x1b]777;notify;<title>;<body>\x1b\\
iTerm2 OSC 9
Apple Terminal / Windows Terminal 无终端通知路径,靠 BEL 或系统通知

9. atomgit/:AtomGit / GitCode REST

9.1 鉴权注入(atomgit/mod.rs)

pub const DEFAULT_BASE_URL: &str = "https://api.atomgit.com/api/v5";
pub trait TokenProvider: Send + Sync { fn token(&self) -> Result<String, String>; }
pub struct AtomgitConfig { pub base_url: String, pub user_agent: String,
                           pub token: Arc<dyn TokenProvider> }
pub struct LiveTokenProvider { user_dir }   // atomcode_auth::oauth::get_valid_token(同步,偶有网络刷新)
pub struct StaticTokenProvider(pub String); // 预取的固定 token

9.2 客户端与错误语义(atomgit/client.rs)

情况 返回(给模型的工具错误)
401 “AtomGit authentication failed — run atomcode login again”
403 权限或 scope 不足;明确告知“重新登录未必有用”
404 长文案:目标可能不存在、无权访问或 API 不支持,要求核对路径;并强调“单个 404 不能证明不支持 issues”
429 明确说明是平台 API 限流而非模型限流,“不要立即重试、不要换评论类型、不要用 curl 绕过”;附 retry-after / 请求 id 等头信息(response_details);响应体中的 token 被替换为 [redacted]
写操作(非 GET/HEAD)的传输错误、5xx、响应解析失败 经 uncertain() 追加:“写入结果未确认,可能已成功。先查询目标,确认前不要重发或换评论类型,以免重复写入”

这类“结果不确定”语义是针对 LLM 的防重复写入设计。

request_raw(method, path, query, body) 是通用调用,供 atomgit_api 使用:

9.3 端点(repo.rs / pr.rs / issue.rs)

路径对齐 ag-cli(pkg/cmd/{repo,pr,issue}):

9.4 模型(models.rs)

9.5 Agent 工具(tools/atomgit.rs)

register_atomgit_tools(reg, Arc<AtomgitClient>) 注册 4 个共用一个 client 的工具。ATOMGIT_TOOL_NAMES 必须与注册列表同步,宿主据此 mount:

工具 action 枚举
atomgit_repo list, view, create, delete, fork, clone, create_tag, labels, ensure_label
atomgit_pr list, list_mine, view, create, update, close, comment_create, comment_view, comment_edit, comment_delete, comment_reply, link_issues(以及解除关联,待确认)
atomgit_issue list, view, create, update, close, comment_create, comment_view, comment_edit, comment_delete
atomgit_api {method: GET|POST|PATCH|PUT|DELETE, path, query?, body?} 通用调用

9.6 push 后自动打标签(remote.rs + push_label_mw.rs)


10. 配置与环境变量汇总

项 模块 说明
[[subagent.external]] subagent name/kind/model/permission/allow_dangerous/timeout
PATH subagent 二进制探测;缺失静默跳过
OPENCODE_DISABLE_PROJECT_CONFIG、OPENCODE_DISABLE_AUTOUPDATE、OPENCODE_CONFIG_CONTENT subagent 注入给 opencode 子进程
[notification] notify 见 8.2
KITTY_WINDOW_ID、WEZTERM_PANE、WT_SESSION、TERM_PROGRAM notify 终端识别
ATOMCODE_HOME / ProductDirs setup 用户树(skills、seeds-cache)与项目目录名
<root>/.atomcode/setup-state.json、.setup.lock、.setup.lock.sentinel setup 持久化与锁
<user>/skills/<name>/.seed-hash setup 种子技能内容哈希
<user>/seeds-cache/<ver>-<hash12>/.extracted setup 种子解压缓存
<user>/auth.toml atomgit OAuth 登录态
AtomgitConfig.base_url atomgit 默认 https://api.atomgit.com/api/v5

11. 扩展点

12. 错误与失败语义

模块 失败 语义
subagent 二进制缺失 注册期静默跳过;运行期为 BinaryNotFound
subagent 超时 / 取消 杀整棵进程树;返回 Timeout / Cancelled 停止原因
subagent Claude 配额 RateLimited{retry_at},到期前不再拉进程
subagent OpenCode 策略被覆盖 拒绝运行(不降级)
subagent Bypass 未授权 DangerousModeRefused
team Worker 范围重叠 validate_… 返回 Err(String),整批不启动
setup 锁被持有 SetupError::LockHeld{pid,start_time,host},提示 --force
setup 中途失败 事务 Drop 自动回滚 .gitignore 等写入
setup 状态文件损坏或来自未来版本 视为不存在,不报错
world 围栏外 / 只读写入 FsErrorKind::Denied
notify 任何投递失败 静默(通知永不影响主流程)
atomgit 写操作结果不明 uncertain() 文案,指导模型先查询再决定
atomgit push 打标签失败 仅 warn

13. 测试

14. 设计要点与坑

  1. 外部 agent 的安全边界在“参数固化 + 策略复核”:OpenCode 不只注入配置,还用 debug agent 读回有效策略确认只读,防止用户全局配置把注入的拒绝规则覆盖掉。这是“信任但验证”的典型做法。
  2. 进程树必须整树回收:CLI agent 会派生 shell、语言服务器等孙进程,只 kill 子进程会留下孤儿并持有管道。setsid/killpg 与 Job Object 是两平台的标准答案;reaped 标志防止误杀复用的 PID。
  3. 配额记忆避免“烧进程”:已知重置时刻前直接报错,节省启动开销,也不会刷爆对方的限流。
  4. 写入范围冲突检测宁可误报:并行 worker 写同一文件的代价远高于少并行一个任务。
  5. 团队事件用 \u{1f} 前缀复用进度通道:零新增 IPC,但要求普通进度文本永不以该字符开头。
  6. setup 的“幂等 + 事务 + 双轨锁 + 原子写 + 版本化状态”是一个完整的本地安装器范式;内容哈希(而非版本号)作为缓存键,解决了同版本重编译的陈旧问题。
  7. world 的“同源事实”原则消除了一类 TOCTOU 和“判断用本地、读写用远程”的错位 bug;只读作为世界属性,比在每个工具里检查更不易遗漏。
  8. 通知在 Windows 上禁用系统路径:历史上 PowerShell NotifyIcon 导致 TUI 崩溃,是取舍而非遗漏。
  9. AtomGit 写操作的“不确定”语义:网络错误或 5xx 后,LLM 最常见的错误是立刻重试,结果出现重复评论或重复 PR。错误文案直接指示“先查询”。
  10. project_labels 缺失 ≠ 空:整体替换式 API 必须区分两者,否则会误删数据。
  11. issue 更新路径无 repo 段(/repos/{owner}/issues/{n}):平台 API 的怪癖,代码注释专门标注。

15. 对 OpenTMD(Go 实现的同类项目)可借鉴之处

  1. 外部 agent 子代理工具:OpenTMD 可在 internal/tool 增加 subagent_<name> 工具,配置写在 config.toml 的 [[subagent.external]]。
    • Go 实现要点:
      • Unix 下设 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true},超时用 syscall.Kill(-pgid, SIGKILL)。
      • Windows 用 golang.org/x/sys/windows 的 Job Object(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE)。
      • 用 context 取消并优先于超时;stderr 只保留 2 KB 尾部。
    • 默认只读:codex exec --sandbox read-only、claude -p --permission-mode plan。
    • 风险分级接入 internal/permission:只读子代理为 AutoApprove,可写为 RequireApproval,bypass 为 RequireApprovalAlways。并在 plan 模式的 planModeBlockedTool 中屏蔽非只读子代理。
  2. 配额记忆:解析 Claude “resets 1:20am (TZ)” 文本得到 retryAt,到期前直接返回错误,Go 用 time.LoadLocation 即可。
  3. 团队/并行写入的范围检查:若 OpenTMD 未来做多 agent 并行,先移植 worker_scopes_overlap(保守 glob 相交判定),在派发前拒绝重叠写入。
  4. 事件复用通道:在 daemon 的 SSE 或 TUI 进度文本中,用 \x1f 前缀加 JSON 夹带结构化事件,可以零成本扩展 UI。
  5. setup 安装器范式:OpenTMD 的 project.Ensure(种子化 .opentmd/skills/example 等)可以借鉴:
    • 每个种子目录写 .seed-hash,未变化则跳过,变化则覆盖。
    • 原子写:同目录 os.CreateTemp、Sync、os.Rename,再对父目录 Sync。
    • 用 flock(syscall.Flock)加 PID/启动时间哨兵做双轨锁,防止两个 opentmd 同时初始化。
    • 状态文件 setup-state.json 带 schema_version,解析失败视为未初始化。
    • 信号哈希规范化 BOM/CRLF,跨平台稳定。
    • 用 Go 的 embed.FS 替代 include_bytes! + tar.zst,更简单,且不需要解压缓存。
  6. 能力推荐:按检测到的技术栈推荐 ast-grep、Context7 MCP(写入 .opentmd/mcp.json 时默认禁用)和对应 LSP,与 OpenTMD 已有的 internal/lsp、internal/mcp 天然契合。
  7. world 抽象:OpenTMD 的 fileio/glob/grep 工具可以统一收口到 type FileSystem interface{...},让“只读”(plan 模式)和“围栏”(workspace 外需审批)成为 FS 实现的属性。目前这部分分散在 permission.Classify 与各工具中,统一后可减少遗漏;也为远程或容器工作区留出接口。walk 默认遵守 gitignore、设条目与时间上限,并返回“请缩小范围”提示。
  8. 桌面通知:在 internal/tui 的 doneMsg 处理中加入:
    • 回合超过 8 s 且终端失焦(Bubble Tea 支持 tea.WithReportFocus() 的 FocusMsg/BlurMsg)时,发 OSC 9/99/777,或 BEL。
    • 等待审批时无条件通知。
    • 通知内容剔除控制字符,以防转义注入。
  9. Git 托管平台工具的防重复写入文案:任何写类 API 工具(包括 MCP 工具)在网络错误或 5xx 时,把“结果未确认,先查询再重试”写进工具结果。这是低成本、高收益的 LLM 行为引导。429 文案明确区分“平台限流”与“模型限流”。
  10. token 注入而非直读:工具层只依赖 TokenProvider 接口,token 不进入工具参数或模型上下文;通用 API 工具只允许相对路径,并固定 base host。