EmDash Bot 状态机架构:issue 生命周期与 Agent 运行生命周期的完整设计解析

原创2026-09-22 20:58:152,163 阅读
文章标签:CMS后端前端插件系统认证鉴权

EmDash Bot 状态机架构:issue 生命周期与 Agent 运行生命周期的完整设计解析

本篇技术指南以 BOT_STATE_MACHINE.md 为骨架,系统讲解 EmDash 仓库中 emdash-bot(基于 Cloudflare Workers 的 GitHub issue 自动化编排器)的两套正交状态机:协调长生命周期 GitHub issue 的 Issue Lifecycle,以及记录单次有界 Agent 执行尝试的 Agent Run Lifecycle。读完你将掌握全部 16 个 issue 状态、25 类事件的语义、140+ 条状态迁移规则,以及从 .flue/lib/machine.ts 单一事实源生成文档、运行时 JSON 与测试的全链路机制。

一、概览:为什么需要两套正交的生命周期机

emdash-bot 的核心矛盾在于:一个 GitHub issue 是长生命周期的(可能持续数天,跨越多次机器人执行),而每一次 Agent 执行是短生命周期的(有明确的阶段、超时与结果)。如果把两者混在一个状态机里,一次执行失败就会污染 issue 的整体状态。

因此仓库采用了正交设计,这一点在文档开头被明确为设计原则:

The issue lifecycle coordinates the long-lived GitHub item. The agent run lifecycle records one bounded execution attempt. GitHub labels project the issue state; run mode and phase remain in Durable Object storage.

对应到实现(machine.ts):

  • Issue 状态通过 GitHub labels 投影到仓库看板,例如 bot:triage、bot:working;
  • Run 的模式与阶段只存放在 Cloudflare Durable Object 存储中,不污染 issue 的 label 空间;
  • 每个 item 同时满足"恰好一个 kind label + 一个 state label"的不变式。

这套设计在 machine.ts 文件头注释中列出了四个由 validateMachine() 强制校验的设计不变量:

  1. 每个 item 恰好一个 kind label 和一个 state label;
  2. 每个非终态都有至少一条出边;
  3. 没有死胡同:每个状态都能到达终态,且每个终态都有 reopen 边回到活状态机;
  4. 每个状态都能从 unmanaged 入口状态到达。

二、文档即代码:单一事实源与生成链路

BOT_STATE_MACHINE.md 文件头有一行关键注释:

<!-- Generated from .flue/lib/machine.ts by `pnpm bot:generate`. Do not edit by hand. -->

这意味着这份文档不是手写的,而是从 machine.ts 这个单一事实源(single source of truth)确定性渲染出来的。整个生成链路为:

  • generate-machine.ts:先调用 validateMachine() 校验状态机设计不变量,再调用渲染函数,把产物写入磁盘;
  • machine-artifacts.ts:纯渲染函数(不含 node:fs),把 machine.ts 投影为两份产物:
    • machine.json(.flue/lib/machine.json):运行时元数据,供 Worker 路由与校验使用;
    • BOT_STATE_MACHINE.md:本文档,含状态表、事件表、迁移表和 Mermaid 图;
  • 漂移测试 machine-artifacts.test.ts:CI 中重跑生成器,若已提交的产物与渲染结果不一致则测试失败——与 query-count 快照同一契约。

生成命令定义在 package.json 中:

pnpm bot:generate   # node --experimental-strip-types scripts/generate-machine.ts

修改状态机的正确工作流是:编辑 machine.ts → 运行 pnpm bot:generate → 三份文件(machine.ts、machine.json、BOT_STATE_MACHINE.md)一起提交。从源码结构看,machine-artifacts.ts 使用显式 .ts 扩展名导入,是为了让 node scripts/generate-machine.ts 无需打包器即可运行,同时 allowImportingTsExtensions 保证 tsc 在漂移测试引入该模块时不报错。

三、Issue 生命周期(Issue Lifecycle)

3.1 入口与分类维度

入口状态为 unmanaged——即机器人从未接触过的 issue,它不携带任何 state label,因此不占用看板,直到命令将其移入。Kinds 有三个互斥类别:bug、enhancement、task,由命令(如 triage 默认 task、investigate 默认 bug、implement 默认 enhancement)在首触时赋予(见 machine.ts 的 defaultKind 机制),维护者之后可通过重新打标签覆盖。

3.2 八个阶段(Phases)

Issue 的八个阶段与其看板 Label 一一对应:

Phase Label
intake Triage
evidence Investigate
verdict Establish
candidate Build
preview Preview
confirmation Confirm
review Review
complete Done

阶段(phase)是状态的稳定分组维度,被 dashboard 投影用作看板聚合(见 machine.ts 中 StateMeta.phase 字段注释 "Stable issue-lifecycle phase used by the dashboard projection")。

3.3 十六个状态(States)

以下为当前文档中的全部状态定义。表中每个状态都标注了所属阶段、GitHub label、看板列、是否终态、是否瞬态(transient)以及该状态下向用户展示的可执行命令:

State Phase Label Board column Terminal Transient Offered commands
unmanaged intake — (none) no no triage, work, investigate, decline
triage intake bot:triage Triage no no triage, work, investigate, decline
triaging intake bot:triaging Triage no yes status, work, take_over
awaiting_approval verdict bot:awaiting-approval Awaiting approval no no work, triage, investigate, decline, take_over
working evidence bot:working Working no yes status
blocked candidate bot:blocked Blocked no no triage, work, investigate, retry, decline, take_over
in_review review bot:in-review In review no no work, decline, take_over
human_owned review bot:human-owned Human owned no no hand_back
done complete bot:done Done yes no reopen
declined complete bot:declined Declined yes no reopen
needs_attention candidate bot:needs-attention Needs attention no no retry, work, triage, investigate, decline, take_over
investigating evidence bot:investigating Investigating no yes status
reproduced verdict bot:reproduced Reproduced no no work, investigate, decline, take_over
diagnosed verdict bot:diagnosed Diagnosed no no work, investigate, decline, take_over
not_reproduced verdict bot:not-reproduced Not reproduced no no triage, investigate, decline, take_over
needs_info verdict bot:needs-info Needs info no no triage, work, investigate, decline, take_over
preview_building preview bot:preview-building Building preview no yes status
awaiting_reporter confirmation bot:awaiting-reporter Awaiting reporter no no accept, needs_changes, decline, take_over

几个值得注意的语义细节(均可从 machine.ts 的 StateMeta 定义与注释中印证):

  • 瞬态(transient)状态是"向后兼容的 GitHub 投影":triaging、working、investigating、preview_building 表示一次 run 正在飞行中,真正的执行阶段与状态由独立的 run 生命周期拥有(见 StateMeta.transient 注释 "Transient states are backwards-compatible GitHub projections while a run is active");
  • blocked 与 needs_attention 是 detour 状态(detour: true):表示偏离主路径、需要人类决策的旁路,原因记录在 bot 的评论中;
  • not_reproduced 是一等结果而非失败:证据转录已附上,报告人可以补充复现步骤,维护者可以重新调查;
  • in_review 的 defaultCommentEvent: "work" 机制:在 bot 撰写的 PR 上,一条不以已知动词开头的 @emdashbot 评论会被当作反馈处理(详见 machine.ts 的注释)——审阅者无需记住 revise 关键字,直接留言即可,但 @emdashbot 提及仍然是必需的,随机闲聊不会触发动作;
  • awaiting_reporter 描述中写明:预览链接发布后等待报告人确认,确认则打开 draft PR,否认或 14 天沉默则回收分支(reapBranch)。

3.4 事件(Events)

事件按类别可分为五类:命令(人/系统发起)、Agent 结果、PR 生命周期、预览部署、定时器。文档中的完整事件表如下:

Event Category Actors Arg Description
triage command maintainer, system directive Classify the issue, apply useful labels, ask for missing information, and proceed automatically only when the work is clear and low risk.
work command maintainer directive Take the issue as far as a verified candidate release, reproducing bugs when appropriate.
accept command reporter, maintainer — Confirm the candidate works and open its draft pull request.
needs_changes command reporter, maintainer feedback Explain what is still wrong so the bot can revise the candidate.
investigate command maintainer directive Reproduce and diagnose the issue as a bug, with evidence. Does not attempt a fix.
retry command maintainer — Retry the last triage, investigation, work, or PR repair run.
decline command maintainer — Won't be actioned; move to declined.
reopen command maintainer — Bring a terminal item back into triage.
take_over command maintainer — A maintainer takes the item; the bot disengages but stays on the board.
hand_back command maintainer — Return a human-owned item to the bot.
reset command maintainer — Force-reset to triage. Maintainer recovery for conflicting state labels.
status command reporter, maintainer — Render the item's current state and available commands.
help command reporter, maintainer — Show the command grammar.
agent.auto_work agent result system — Triage found an obvious, low-risk task that can proceed automatically.
agent.awaiting_approval agent result system — Triage found work that needs maintainer approval.
agent.skipped agent result system — Agent skipped (non-bug kind, or repro needs external/prod-only conditions).
agent.not_reproduced agent result system — Agent could not reproduce the issue.
agent.by_design agent result system — Agent verified the behaviour as intended.
agent.reproduced agent result system — Reproduced, but the fix needs a human decision.
agent.diagnosed agent result system — Root cause identified without a confirming reproduction.
agent.revised agent result system — Review feedback is addressed and the PR branch is updated.
agent.fix_ready agent result system — A candidate change is published on bot/fix-.
agent.needs_info agent result system — Investigation is blocked on information only the reporter can supply.
agent.failed agent result system — Agent run errored or produced no usable result.
pr.opened pr lifecycle system — A bot PR was opened for this item.
pr.updated pr lifecycle system — The attached PR head changed; refresh its checks and review state.
pr.problems pr lifecycle system feedback The attached PR has failing checks, conflicts, or requested changes.
pr.green pr lifecycle system — The attached PR is mergeable and all reported checks pass.
pr.merged pr lifecycle system — The bot PR was merged.
pr.closed pr lifecycle system — The bot PR was closed without merging.
pr.approved pr lifecycle system — A reviewer approved the PR (review sub-state).
preview.ready preview system — The preview deploy for the candidate change is live; link ready to post.
preview.failed preview system — The preview deploy failed to build.
expire timer system — The reporter-confirmation window elapsed without a reply.

从源码角度看事件建模有几个要点:

  • Actor 权限模型(machine.ts):三类 actor——reporter(原 issue 报告人,可确认/拒绝自己的报告)、maintainer(任何持有仓库写/分诊/维护/管理角色的账号)、system(Agent run 自身发射结果,不是人);
  • 破坏性命令保护(machine.ts):decline、take_over、reset 被标记为 destructive。在自由文本模式下,它们不会被提供给意图分类器,只能通过精确的裸动词 @emdashbot <verb> 触发——确保一条被误读的句子永远不会静默关闭或脱离某个 item;
  • status 与 help 是只读事件(readOnly: true):渲染 item 状态,绝不改变状态;
  • Agent 事件与 Flue 结果字段 1:1 映射(machine.ts):如 agent.not_reproduced ← !skipped && !reproduced、agent.by_design ← verdict === "intended-behavior"、agent.fix_ready ← reproduced && fixed、agent.failed ← 非零退出码或无结果文件。

3.5 迁移(Transitions)与动作

文档的迁移表列出 140+ 条 From → Event → To 规则,其中部分迁移携带动作(Action),例如:

  • unmanaged → triage → triaging 触发 investigate.triage:启动分类 run;
  • working → agent.fix_ready → preview_building:候选修复发布后进入预览构建;
  • awaiting_reporter → accept → in_review 触发 openDraftPr:报告人确认后打开 draft PR;
  • in_review → decline → declined 触发 closePr:关闭 bot PR;
  • awaiting_reporter → expire → reproduced/blocked(按 kind 分派)触发 reapBranch:超时回收分支。

两个特殊规则值得展开:

  1. 按 kind 分派目标(toByKind):preview.failed 与 expire 的目标因 kind 而异——bug 回到 reproduced(有证据的等待状态),enhancement/task 回到 blocked。渲染器 machine-artifacts.ts 会将其格式化为 default: reproduced; enhancement: blocked; task: blocked 的形式;
  2. reset 全局逃生舱:从几乎所有状态强制回到 triage,用于处理"多个 state label 同时存在"这类半应用标签交换的冲突恢复。它只破坏 bot:* 状态元数据,不触碰 issue 内容,且与 decline、take_over 一样仅限裸动词触发。

动作由 router 分发,其实现是 investigate agent(见 ActionId 定义,machine.ts)。mode 选择入口行为:investigate.triage 是分类、investigate.work 是完整交付、investigate.diagnose 是只诊断不修复、investigate.revise 是针对已有 bot/fix-<n> 分支结合 PR 反馈重跑、investigate.fix 是构建候选修复并推送触发预览。

3.6 完整状态图(Mermaid)

stateDiagram-v2
    [*] --> unmanaged
    unmanaged --> triaging: triage / investigate.triage
    unmanaged --> working: work / investigate.work
    triage --> triaging: triage / investigate.triage
    triage --> working: work / investigate.work
    triaging --> working: agent.auto_work / investigate.work
    triaging --> awaiting_approval: agent.awaiting_approval
    triaging --> needs_info: agent.needs_info
    triaging --> awaiting_approval: agent.not_reproduced
    triaging --> awaiting_approval: agent.diagnosed
    triaging --> awaiting_approval: agent.reproduced
    triaging --> awaiting_approval: agent.by_design
    triaging --> awaiting_approval: agent.skipped
    triaging --> needs_attention: agent.failed
    triaging --> working: work / investigate.work
    triaging --> human_owned: take_over
    triaging --> declined: decline
    awaiting_approval --> triaging: triage / investigate.triage
    awaiting_approval --> working: work / investigate.work
    awaiting_approval --> investigating: investigate / investigate.diagnose
    awaiting_approval --> human_owned: take_over
    awaiting_approval --> declined: decline
    needs_attention --> working: retry / investigate.work
    needs_attention --> working: work / investigate.work
    needs_attention --> triaging: triage / investigate.triage
    needs_attention --> investigating: investigate / investigate.diagnose
    needs_attention --> human_owned: take_over
    needs_attention --> declined: decline
    needs_attention --> needs_attention: pr.updated
    needs_attention --> in_review: pr.problems / investigate.revise
    needs_attention --> in_review: pr.green
    needs_attention --> done: pr.merged
    needs_attention --> needs_attention: pr.closed
    needs_info --> triaging: triage / investigate.triage
    done --> triaging: triage / investigate.triage
    declined --> triaging: triage / investigate.triage
    unmanaged --> declined: decline
    triage --> declined: decline
    working --> blocked: agent.skipped
    working --> not_reproduced: agent.not_reproduced
    working --> blocked: agent.by_design
    working --> reproduced: agent.reproduced
    working --> diagnosed: agent.diagnosed
    working --> needs_info: agent.needs_info
    working --> preview_building: agent.fix_ready
    working --> in_review: agent.revised
    working --> needs_attention: agent.failed
    blocked --> triaging: triage / investigate.triage
    blocked --> working: work / investigate.work
    blocked --> working: retry / investigate.repro
    blocked --> declined: decline
    blocked --> human_owned: take_over
    in_review --> in_review: pr.opened
    in_review --> in_review: pr.approved
    in_review --> in_review: work / investigate.revise
    in_review --> in_review: needs_changes / investigate.revise
    in_review --> in_review: pr.updated
    in_review --> in_review: pr.problems / investigate.revise
    in_review --> in_review: pr.green
    in_review --> in_review: agent.revised
    in_review --> needs_attention: agent.failed
    in_review --> done: pr.merged
    working --> done: pr.merged
    in_review --> needs_attention: pr.closed
    working --> blocked: pr.closed
    unmanaged --> triage: reset
    triage --> triage: reset
    working --> triage: reset
    blocked --> triage: reset
    in_review --> triage: reset
    human_owned --> triage: reset
    done --> triage: reset
    declined --> triage: reset
    in_review --> declined: decline / closePr
    in_review --> human_owned: take_over
    human_owned --> triage: hand_back
    done --> triage: reopen
    declined --> triage: reopen
    unmanaged --> investigating: investigate / investigate.diagnose
    triage --> investigating: investigate / investigate.diagnose
    blocked --> investigating: investigate / investigate.diagnose
    not_reproduced --> investigating: investigate / investigate.diagnose
    needs_info --> investigating: investigate / investigate.diagnose
    reproduced --> investigating: investigate / investigate.diagnose
    investigating --> reproduced: agent.reproduced
    investigating --> diagnosed: agent.diagnosed
    investigating --> not_reproduced: agent.not_reproduced
    investigating --> needs_info: agent.needs_info
    investigating --> blocked: agent.by_design
    investigating --> blocked: agent.skipped
    investigating --> needs_attention: agent.failed
    reproduced --> working: work / investigate.work
    reproduced --> working: needs_changes / investigate.work
    reproduced --> declined: decline
    reproduced --> human_owned: take_over
    diagnosed --> working: work / investigate.work
    diagnosed --> working: needs_changes / investigate.work
    diagnosed --> declined: decline
    diagnosed --> human_owned: take_over
    diagnosed --> investigating: investigate / investigate.diagnose
    not_reproduced --> triaging: triage / investigate.triage
    not_reproduced --> declined: decline
    not_reproduced --> human_owned: take_over
    needs_info --> working: work / investigate.work
    needs_info --> declined: decline
    needs_info --> human_owned: take_over
    preview_building --> awaiting_reporter: preview.ready
    preview_building --> reproduced: preview.failed [default]
    preview_building --> blocked: preview.failed [enhancement, task]
    awaiting_reporter --> in_review: accept / openDraftPr
    awaiting_reporter --> working: needs_changes / investigate.revise
    awaiting_reporter --> working: work / investigate.revise
    awaiting_reporter --> reproduced: expire [default] / reapBranch
    awaiting_reporter --> blocked: expire [enhancement, task] / reapBranch
    awaiting_reporter --> human_owned: take_over
    awaiting_reporter --> declined: decline / reapBranch
    investigating --> triage: reset
    reproduced --> triage: reset
    not_reproduced --> triage: reset
    needs_info --> triage: reset
    preview_building --> triage: reset
    awaiting_reporter --> triage: reset
    triaging --> triage: reset
    awaiting_approval --> triage: reset
    needs_attention --> triage: reset

这张图揭示了端到端主路径:unmanaged → triage → triaging → working → preview_building → awaiting_reporter → in_review → done,以及围绕它的所有旁路(blocked、needs_attention、declined、human_owned)与恢复路径(reopen、reset、hand_back、retry)。

四、Agent 运行生命周期(Agent Run Lifecycle)

4.1 独立存储的运行记录

一次 run 独立于 issue 状态存储以下信息:mode(模式)、所选阶段计划(plan)、当前阶段、状态、尝试次数(attempt)与固定截止时间(deadline)。实现见 run-lifecycle.ts 的 RunLifecycle 接口:

export interface RunLifecycle {
  readonly runId: string;
  readonly mode: RunMode;
  readonly status: RunStatus;
  readonly phase: RunPhaseId;
  readonly plan: readonly RunPhaseId[];
  readonly attempt: number;
  readonly createdAt: number;
  readonly startedAt: number;
  readonly deadlineAt: number;
  readonly completedAt: number | null;
}

关键语义:triage 与 investigation 是只读的(不发布候选);work 与 revision run 可能发布候选(publish 阶段)。

4.2 九个阶段与四个模式计划

运行阶段的完整集合:

Phase Label
prepare Prepare
reproduce Reproduce
diagnose Diagnose
work Work
edit Edit
finalize Finalize
verify Verify
publish Publish
report Report

四个当前模式的有序阶段计划:

Mode Ordered phases
triage prepare → diagnose → report
investigate prepare → reproduce → diagnose → report
work prepare → work → finalize → verify → publish → report
revise prepare → edit → finalize → verify → publish → report

RUN_PLANS 在 machine.ts 中定义,且保留了旧命令模型的模式(repro、implement、diagnose、fix)以保证已存储的旧 run 仍可恢复(注释明确:"Stored runs from the previous command model remain resumable")。

从 run-lifecycle.ts 的 progressPhase 可以看到阶段推进与进度事件的映射:workspace_ready 把 run 推进到 plan[1](即首个实质阶段),verification_passed/failed 推进到 verify,candidate_published 推进到 report。

4.3 任务级工作计划(Task-specific work plan)

这是运行生命周期中与"阶段计划"解耦的另一个维度。每次 Agent 运行都通过 update_work_plan 为其具体指令创建一个有界的工作计划(bounded work plan):该计划可以描述任意仓库工作内容,而运行阶段只负责跟踪截止时间与发布。

工作计划的校验与渲染在 work-plan.ts 中实现,值得注意的约束:

  • 最多 8 个步骤(MAX_STEPS = 8),步骤 id 必须匹配 /^[a-z][a-z0-9_-]{0,39}$/ 且唯一;
  • 摘要最长 240 字符(超长截断),步骤标题最长 120 字符;
  • 至多一个 in_progress 步骤;
  • 已完成/已跳过的步骤不可回退:已 completed/skipped 的步骤必须保留,且不能改变其状态与标题(preserveFinishedSteps);
  • 步骤状态枚举:pending、in_progress、completed、blocked、skipped。

该计划的注释投影(renderWorkPlanComment)会渲染进一个不断演化的 GitHub 评论(标题随状态切换:Working on it / Completed / Needs follow-up / Timed out / Cancelled / Failed),同时投影到 dashboard。语义要点(文档原文):

  • Resume 更新同一条 run 评论;
  • 全新的 retry 或 directive 创建新的 run 评论;
  • 最终 agent 结果更新同一条评论;只有该模式的受信结果成功时才使用 Completed(对应 work-plan.ts 的 renderWorkPlanComment 中 status === "succeeded" 分支)。

4.4 五种运行状态(Statuses)

running, succeeded, failed, timed_out, cancelled

状态推进由 run-lifecycle.ts 的 settleRunLifecycle 负责:成功后 phase 固定为 report,其他终态保留当前 phase,并写入 completedAt。resumeRunLifecycle 增加 attempt 计数并重新计算截止时间(deadlineAt = startedAt + runBudgetMs(mode)),预算函数 runBudgetMs 定义在 run-policy.ts 中,按 mode 给出各自的执行预算。

4.5 运行生命周期图(Mermaid)

stateDiagram-v2
    [*] --> prepare
    prepare --> diagnose: triage
    diagnose --> report: triage, investigate
    prepare --> reproduce: investigate
    reproduce --> diagnose: investigate
    prepare --> work: work
    work --> finalize: work
    finalize --> verify: work, revise
    verify --> publish: work, revise
    publish --> report: work, revise
    prepare --> edit: revise
    edit --> finalize: revise
    report --> [*]

注意:这张图是由 machine-artifacts.ts 的 runLifecycle() 从各模式的阶段计划推导出的边(同一对阶段间若有多个模式则标注模式名),而非手写——因此它与 Plans 表始终一致。

五、从设计到落地:测试与运行时佐证

状态机不是纸面设计,仓库内有多层测试与运行时产物支撑:

  • 漂移测试 machine-artifacts.test.ts:守护"文档/JSON 与 machine.ts 不漂移"契约;
  • 生命周期专项测试:
  • 运行时产物 machine.json:序列化的 issue + run 机器元数据,被运行时直接消费;
  • 执行入口:整套能力由 orchestrator.ts(编排器)与 webhook.ts(webhook 入口)驱动,webhook 将 GitHub 事件转换为上述 pr.*/命令事件,路由到状态机。

六、小结:一套可验证、可生成、可恢复的状态机体系

emdash-bot 的生命周期设计可以提炼为三个值得借鉴的原则:

  1. 单一事实源 + 生成式文档:手写 machine.ts,用 pnpm bot:generate 一次性生成运行时 JSON 与人类可读文档,并用漂移测试锁死一致性——文档永远与代码同步;
  2. 双状态机正交解耦:issue 状态(长生命周期、label 投影)与 run 状态(短生命周期、DO 存储)分离,一次执行失败不会污染 issue 的整体叙事;配合 resume/retry/reopen/reset 形成完整的恢复语义;
  3. 人类在环与安全护栏:decline/take_over/reset 等破坏性命令仅限裸动词触发,status/help 只读,human_owned/hand_back 提供机器人与维护者的交接通道,not_reproduced/needs_info 把"无法进展"本身也建模为一等结果。

如需进一步深入,建议按此顺序阅读仓库源码:machine.ts(状态机定义)→ machine-artifacts.ts(文档渲染)→ run-lifecycle.ts(运行推进)→ work-plan.ts(工作计划约束)→ 对应单元测试,形成从设计到验证的完整闭环。

登录后查看全文
emdash