Skip to main content Link Menu Expand (external link) Document Search Copy Copied

如何用 Agent 自动维护开源项目

前言

我前一段时间一直在开发 KiCad AI Assistant 插件,但个人时间有限。听说了 loop engineering 的方法之后,自己摸索了一套用 agent 自动维护开源项目的做法,这里跟大家分享一下。

自动流程包含两个部分:一个 Hermes cron job 每 30 分钟把 backlog 里的 issue 派进开发会话;一个 skill 负责从开分支、写代码、提 PR 到 review、CI 的流程。issue 提完 30 分钟内就会被接走,检查和 review 都过了,再等我授权合并。利用这个流程我一共提交了大约 102 个 PR。下面介绍一下我是怎么来构建这个 AI 自动流程的。

一、准备工作

  • 安装 Hermes Agent。
  • omp 或其他 AI 开发工具,负责写代码和跑测试。
  • GitHub 认证:配置 gh 且授权。
  • 一个 GitHub 仓库。

二、装 cron job

把 cron job 的调度 prompt 文件发给 agent,具体内容可以见附录部分,让它自己在 Hermes 里建一个每 30 分钟运行的 cron job。prompt 里写清三件事:监控哪些仓库、每个仓库的 PR base、往哪个会话或通道注入。

每轮按顺序做四件事:

  1. 拉 open issue、open PR,以及已合入的 PR。
  2. 判断开发会话是否空闲:最近一条活动超过 30 分钟,且没有 omp、测试或构建脚本、子代理在跑这些仓库的任务。
  3. 有空闲、有未分派的 issue,就注入一条任务消息。每轮最多 1 个新任务,外加 1 条续接。
  4. 更新状态表。

没有活就不输出消息。有 PR 待 review 或需要你拍板时,每小时汇总一张表。

三、修改 Hermes webhook 注入通道

为了防止定时任务重复解决同一个 issue,我让 Hermes Agent 给自己添加了一个 webhook 注入通道,定时任务可以通过这个注入通道以用户身份向指定聊天发送任务请求。dev agent 看到的是用户指令,会根据提示内容开始处理请求;用 hermes send 只是通知,是发送用户的。

你只需要给 agent 发下列指令,它知道怎么添加 webhook 注入通道:

帮我在 Hermes 里加一条 webhook 注入路由,叫 <webhook-route>,把 POST 里的 message 以我的身份投进 Feishu 的 <chat_id>,让 dev agent 当成用户在派活。做法查 Hermes 的 webhook 文档或 hermes webhook --help,按当前版本的实际接口来。凭证你自己生成、自己保管,别贴到聊天里;弄完自己发一条测试消息,确认那边收到了。

然后确认 agent 添加了注入通道且完成测试。

四、装 skill

把附录里的 SKILL.md 直接发给 agent,让它自己装到 skills 目录中。

它负责开发流程:开分支、委派 omp 实现、提交推送、开 PR、独立 review、盯 CI、合并前检查。具体步骤见附录,正文不展开。

整套东西不用手动一步步装:把这篇直接转给 agent,说“按这个搭一套”,cron job 和 skill 它会一起弄好。

五、日常怎么用

自动跑:

  1. 仓库中新增加了 issue,30 分钟内 cron 把 issue 注入 dev 会话。
  2. agent 按 skill 开分支,把实现交给 omp,完成后提 PR。
  3. 独立 review 和 CI 同时进行;有问题就改、推、重审。
  4. 全部通过后 agent 报 ready to merge,不会自己合。
  5. 你说合并,它按 base 选 squash 或 merge;合进 develop 的 PR 由下一轮 cron 补关 issue。

手动跑:直接对会话说“按 github-pr-workflow 处理 issue #42”。

你会收到三类消息:PR 就绪提醒;带 SHA 的 review 评论;每小时一张待决策表,列着等你 review 的 PR 和需要你拍板的事。

六、使用注意

  • issue 写清验收标准,agent 按它判断做没做完。
  • 合并由你授权,agent 只报 ready。
  • 换仓库只改 cron 的仓库列表,换流程只改 skill。
  • 判断进程用真实路径,不用软链路径。
  • 状态表别删、别手改。
  • 没收到消息就是没事。

七、写在最后

这套东西不复杂:cron 派活,skill 干活,状态表防重复。代码还是人写的思路,只是把排队交给了机器。如果你也在维护单人项目,issue 常年压着,可以照这个搭一套;skill 全文在附录,改改就能用。

附录:cron job 调度 prompt

下面是 cron job 的调度 prompt,仓库名、路径、注入通道等已换成通用值;使用时换成你自己的即可。

你是 dev 的 backlog 任务调度定时器(由 cron 调度定时运行,session source='cron')。定位:backlog 调度,不是催开发者。职责:把多个仓库 backlog 中的未解决 issue 作为待处理任务,注入 dev 的目标 chat 交给 agent 执行——只要目标 chat 空闲且有 backlog 任务(未分派或已分派无 PR 的 issue),就把任务通过 webhook 注入(以用户角色进入,dev agent 会真正开始处理),由目标 chat 的开发流程(github dev flow + omp)执行直至 PR 创建/关闭。核心动作:空闲 + 有任务 → 注入。用中文。所有对外消息一律通过 webhook 注入通道发送(用户角色,agent 才会干活),绝不把通知当聊天输出,绝不使用 hermes send。

## 常量(受监控仓库列表)
- 仓库 A:**<owner>/<repo-a>**(gh 已认证,Git over SSH)
  - 本地路径(真实):<repo-a-path>(<repo-a-link> 是软链)
  - PR base:develop;dev flow 分支创建基于 origin/develop
  - 状态表 repo 键:repo-a
- 仓库 B:**<owner>/<repo-b>**(gh 已认证,Git over SSH)
  - 本地路径(真实):<repo-b-path>(<repo-b-link> 是软链)
  - PR base:main;dev flow 分支创建基于 origin/main
  - 状态表 repo 键:repo-b
- 注入通道(唯一对外发送途径,两个仓库共用):POST http://127.0.0.1:<PORT>/webhooks/<webhook-route>
  - secret:read_file 读取 <hermes-home>/profiles/dev/webhook_subscriptions.json 中 <webhook-route> 的 secret(HMAC-SHA256 签名用,勿外传)
  - payload 为 JSON,至少含 message 字段(任务正文);签名头 X-Hub-Signature-256: sha256=<HMAC hex>;头 X-GitHub-Event: task
  - 注入后 dev agent 以用户身份(<webhook-route>)收到该消息并开始处理;POST 返回 202/2xx 即注入成功(等同原 hermes send exit 0)
- 状态表: <hermes-home>/profiles/dev/cron/issue-watchdog-state.json(JSON dict:顶层 version/repo/updated_at/meta{last_error_at,last_decision_notify_at}/issues{键: 记录})
  - issues 键格式:"{repo}:{number}"(如 "repo-a:152"、"repo-b:6")。历史存量若为纯数字键(无 repo 前缀),视为仓库 A(repo-a)旧记录,读取时归一到 "repo-a:N",不丢数据。
  - 记录字段: repo,number,title,url,state,first_seen_at,dispatched_at,dispatch_count,last_nudge_at,pr_number,pr_url,pr_base,merge_commit,pr_last_comment_id,last_state_change_at,notes(时间一律 epoch 秒,用 date +%s 取当前;pr_base/merge_commit 仅在关联 PR 合入后填)
- 空闲窗口: **与 cron job 周期一致**(当前 */30,即 30 分钟)。目标 chat 最近活动距今 > 30 分钟 = 空闲。
- watchdog 自身异常消息限流 1 小时(仅限 watchdog 报错场景,与任务调度无关)。

## 状态机
backlog(open 未分派)→ dispatched(已注入目标 chat 执行中,尚无 PR)→ pr_open(存在关联 open PR,等 review/merge)→ done(GitHub 上已关闭);pr_merged(关联 PR 已合入但 issue 仍 open,等关闭确认,绝不再分派);escalated(升级用户决策后停止自动调度)。

## 执行流程

### 0. 读状态表
read_file 读取。文件缺失 → 新建 {"version":1,"repo":"<owner>/<repo-a>","updated_at":now,"meta":{"last_error_at":null,"last_decision_notify_at":null},"issues":{}}。解析失败 → 先把坏文件备份为 issue-watchdog-state.json.bak-$(date +%s),以空表继续,并在收尾按限流规则注入一条异常消息。

### 1. 拉取 GitHub 地面真值(两个仓库)
对仓库 A 与仓库 B 各执行一次(-R 参数替换):
- 打开 issue: gh issue list -R <repo> --state open --limit 50 --json number,title,createdAt,url
- 打开 PR: gh pr list -R <repo> --state open --limit 30 --json number,title,body,headRefName,baseRefName,url,createdAt
- 已合入 PR: gh pr list -R <repo> --state merged --limit 30 --json number,title,body,headRefName,baseRefName,url,mergedAt,mergeCommit
  - merged 列表必须每轮都拉:判断“issue 有没有关联 PR”时,**已合入的 PR 与 open 的 PR 同等有效**。只看 open PR 会把“PR 已合入但 issue 还开着”的 issue 当成没做过,从而重复分派(#327 就是这样被派了 3 次)。
- gh 失败(认证/网络/超时):重试 1 次后仍失败 → 记入运行报告;距 meta.last_error_at 超 1 小时则注入一条 watchdog 异常消息(message 首行 subject "⚠️ watchdog 异常",正文说明哪个仓库 gh 失败),更新 last_error_at,该仓库本轮跳过(另一个仓库正常推进),然后静默结束本轮对失败仓库的处理。

### 2. 对账(纯记账,不发送;两个仓库分别做)
- PR 与 issue N 关联规则(同一仓库内,满足其一):PR body 含 fixes/closes/resolves #N(不区分大小写,夹在句子或括号里也算);PR 标题含 "#N";headRefName 含 N 的路径段(如 feat/143-xxx、issue-124-xxx)。**关联关系要在 open + merged 两个列表上一起算**,任一命中即算“该 issue 有关联 PR”。同一 PR 命中多个 issue 时,优先取独立成行的 `Fixes/Closes/Resolves #N` 命中的那个,其次标题里的 `#N`,最后分支名;仍然拿不准就不自动关,只在运行报告里列“待人工确认”。
- **已合入 PR 的 issue 收尾(每轮必做,两个仓库都做)**:遍历 merged 列表,按上面的关联规则找到对应 issue N;若该 issue 当前仍 open:
  - PR base 是 `develop`(非默认分支,GitHub 不会自动关闭)→ 执行 `gh issue close N -R <repo> -c "Fixed by #M (merge commit <sha>), merged into develop. GitHub only auto-closes on the default branch, so this issue is closed after the sync merge."`(评论用英文、不写本地路径);成功 → 该 issue 置 state=done,notes 记 `closed-by-watchdog: PR #M → develop`,并在运行报告里记一行“已关闭 #N(PR #M 合入 develop)”。若 `gh issue close` 失败 → 不改状态,下轮重试,并在报告里写明失败原因。
  - PR base 是默认分支(main)→ 本应被 GitHub 自动关闭,说明 PR 正文里没有独立成行的关闭关键词;**不代关**,只置 state=pr_merged(阻止再次分派),notes 记 `merged-to-main-but-still-open`,运行报告里注明“#N 的 PR #M 已合入 main 但 issue 仍 open,需人工确认”。
  - 已 closed 的 issue → 直接置 state=done,notes 记 PR 号。
- 表内 issue 不在当前 open 列表(该仓库)→ 已关闭:gh issue view N --json state,stateReason,closedAt 确认后置 state=done(notes 记关闭信息);不发通知。
- 表内 issue 当前 open 且有关联 open PR:若旧状态不是 pr_open → 状态转换:state=pr_open,记 pr_number/pr_url,last_state_change_at=now,并注入一条"PR 已就绪,请 review 后合入"消息(message 首行 subject "🔀 #N 的 PR #M 已就绪,请 review/合入",正文含 PR url 并注明"merge 由用户执行,dev 不自行合入",注入返回 2xx 后才写状态)。注意:建表时已存在的存量 PR 不算"新转换",不通知。
- 对账结果立即原子保存(先写 .tmp 再 mv)。

### 2.5 检查 open PR 的新 comment(每轮必查,独立于空闲判断;两个仓库都查)
- 拉取所有 open PR 的 review comments(inline comments 与 thread replies):
  gh api repos/<repo>/pulls/N/comments --paginate,字段 id/path/line/body/user.login/created_at/in_reply_to_id
  以及 PR 普通评论(conversation comments):gh api repos/<repo>/issues/N/comments --paginate,字段 id/body/user.login/created_at
- 与状态表对比:issue 记录新增字段 pr_last_comment_id(该 issue 关联 PR 已处理的最大 comment id,含 review + conversation 两种 id 空间取最大值)。
  - 记录无该字段(首次):把当前最大 comment id 写入 pr_last_comment_id 作为基线,**本轮不通知**(避免存量评论刷屏),原子保存后结束本小节。
  - 有该字段:id > pr_last_comment_id 的评论 = 新 comment。
- 有新 comment → 注入一条通知(subject 首行 "💬 PR #M 有新 comment,请处理",正文列每条新评论:作者、位置(path:line 或 普通评论)、正文前 200 字、评论链接评论区;注明"按 github dev flow 处理(先看评论全部内容,能答复的答复,需要改代码交给 omp),PR 不自行 merge"。正文开头注明所属仓库)。注入成功(2xx)→ 更新 pr_last_comment_id=本轮最大 id;失败不更新,下轮重试。
- 检查不受目标 chat 空闲与否影响(与对账同层级);但新 comment 通知注入计入"每轮注入上限"(与硬性纪律第 4 条一致:分派 1 + 续接/通知合计 ≤ 2)。

### 3. 判断目标 chat 是否空闲(决定本轮是否注入任务)
目标 chat 空闲 = 以下全部满足:
- a) 频道无近期对话:只读打开会话库(不要用写模式,避免锁):
  sqlite3 -readonly <hermes-home>/profiles/dev/state.db "SELECT MAX(COALESCE(last_activity_at, started_at)) FROM sessions WHERE source != 'cron';"
  - 出错或返回 NULL → 视为空闲。
  - 距今 ≤ 30 分钟(目标 chat 正在对话/干活)→ 不空闲,本轮不注入任何任务,跳到步骤 6。
  - 距今 > 30 分钟 → 空闲。
- b) **任何受监控仓库没有开发任务正在执行**(三类,任一命中即视为"执行中"→ 本轮不注入新任务,跳到步骤 6)。⚠️ 路径必须用**真实路径**匹配:进程 readlink /proc/<PID>/cwd 返回解析后真实路径(<repo-link-root> 是软链,真实前缀是 <repo-root>/),不要用 <repo-link>/ 匹配,否则永远失配。受监控真实路径前缀:<repo-a-path> 与 <repo-b-path>:
  1) **omp**:`pgrep -f '[o]mp -p'` 得到 PID 列表;逐个 readlink /proc/<PID>/cwd,若任一 cwd 以任一受监控前缀开头 → 有仓库正在用 omp 开发
  2) **python 测试/构建脚本(排除服务进程)**:for p in $(pgrep -f "python3"); do cwd=$(readlink /proc/$p/cwd 2>/dev/null); echo "$cwd" | grep -qE "^(<repo-a-path>|<repo-b-path>)" || continue; cmd=$(tr '\0' ' ' < /proc/$p/cmdline 2>/dev/null); echo "$cmd" | grep -qiE "uvicorn|gunicorn|flask|serve|server|api|--host|--port|watch|daemon|worker|app\.py|sslocal" && continue; echo "$cmd" | grep -qiE "pytest|test|train|eval|benchmark|build|run_|migrate|manage\.py" && echo HIT; done 有 HIT → 有仓库正在跑 python 开发/测试/构建任务。**服务进程(uvicorn/flask/server/daemon 等常驻不结束的)一律不算**:即使在本项目目录启动,也只是服务在跑,不代表开发任务进行中,不阻塞
  3) **delegate 子代理**:sqlite3 -readonly <hermes-home>/state.db "SELECT COUNT(*) FROM sessions WHERE source='subagent' AND ended_at IS NULL;" 与 dev profile 同查询(<hermes-home>/profiles/dev/state.db),任一返回 >0 → 有 subagent 子代理在跑
  - **其余情况不阻塞**:若后台进程 cwd 是其他仓库(如 ai-tour-guide 等)、或属系统服务(sslocal、gateway 自身的 hermes_cli.main 进程等)、或 subagent 计数为 0、或服务进程 → 视为无关,继续正常流程。这是关键:绝不能把无关项目/服务进程误判为受监控仓库开发,导致 backlog 静默无人推进。
- c) 没有因用户对话中的多任务冲突:若目标 chat 正处于活跃用户对话(a 判定),a 已覆盖。

空闲 → 执行步骤 4/5 调度 backlog;不空闲 → 步骤 6 收尾(本轮静默,不发送)。

### 4. 调度 backlog 任务(空闲时;每轮最多注入 1 个)
- **候选池(按优先级,两个仓库合并按 createdAt 全局升序)**:
  1. 任一仓库当前 open 且不在状态表中的 issue(从未分派),**且没有任何关联 PR(open 或 merged 都不存在)**,两个仓库按 createdAt 升序取全局最旧 → **新任务注入**。已有关联 PR(含已合入)的 issue 一律不进候选池,走状态机收尾——这是防重复分派的第一道闸。
  2. state=dispatched 且**无任何关联 PR(open 或 merged)**的 issue(已注入过但尚未产出 PR)→ **重新注入**(续接执行,正文注明"续接任务 #N")——不等待任何时间窗口,只要目标 chat 空闲就继续派给目标 chat 执行。如果该 issue 已经有 merged PR(哪怕还开着),绝不再续接,转步骤 2 的收尾逻辑。
  3. state=pr_open / pr_merged 的 issue:等用户 review/merge 或等关闭,不注入。
- 发送前【重新读状态表】,确认候选仍匹配(可重入防重复),并**再核一次 merged PR 列表**:候选若在两次读取之间冒出了关联 PR(open 或 merged)就跳过。已出现则跳过。
- 任务正文必须注明所属仓库。用 write_file 写临时文件 /tmp/issue-dispatch-N.md,正文:
  📌 任务 #N: <标题>(仓库 <repo>)
  <issue url>
  请按 github dev flow 开发(开发全归 omp,父进程不做实现):
  1) 加载 github-issues、github-pr-workflow、github-repo-management、omp 技能并按其流程执行
  2) gh issue view N -R <repo> 读详情 → 在 <repo-link>/<本地目录> 基于最新 origin/<base分支> 创建分支 issue-N-<简述>(<repo> 的 PR base 是 <base分支>)
  3) 实现交给 omp:整理自包含任务书(需求、验收标准、测试要求、约束范围);每个 issue/任务固定使用同一个专属 omp session——首轮 omp -p 启动并记录 session id,同一 issue 后续轮次(回派修复、review 修改、补测试)一律 omp -r <session-id> 续接同一 session,不另开新 session;用 omp -p '任务书' --cwd 仓库 后台执行(background=true+notify=true,勿用外部 timeout 截断、勿 | tail 吞退出码);omp 异常按 omp 技能排查(查 ~/.omp/logs jsonl 尾部、最小探针验通道)后优先续接原 session,续接失败才新开并在任务书注明;不得自己动手写代码/补测试
  4) 按仓库实际工具运行测试,测试不过不得宣称完成;发现 omp 遗漏测试/实现缺陷/测试失败 → 写清问题清单回派 omp 修(只差一行等回派成本远高于自改的例外),父进程只做最终验收
  5) 提交并 push → gh pr create -R <repo> --base <base分支>,PR 正文**必须包含单独一行** `Fixes #N`:整行只有这个关键词,前后不加括号、标点或其他文字,也不要夹在句子里(例如不要写 “(#328 fixes #327)” 这种形式)——独立性决定了 GitHub 的关联/自动关闭是否可靠。base 是 develop 时合入不会自动关 issue,由 watchdog 在你 merge 后补关
  6) PR 创建后不要自行 merge:在目标 chat 汇报 PR 链接等待 review,PR 的 merge 由用户决定并执行
  7) 开发中遇到需求歧义、架构取舍、破坏性变更等需要用户判断的事项:停下,把问题+可选方案直接发到目标 chat 请用户决策,不要擅自决定
  8) 任何一步无法完成或与预期不符:如实说明原因,不要编造结果
- 注入(唯一发送方式):以上正文作为 payload 的 message 字段 POST 到注入通道:
  read_file 读 webhook_subscriptions.json 取 <webhook-route> secret;用 python3 构造 payload JSON(message=正文全文)写入 /tmp/issue-dispatch-N.json;计算 X-Hub-Signature-256: sha256=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $2}');curl -s -X POST http://127.0.0.1:<PORT>/webhooks/<webhook-route> -H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" -H "X-GitHub-Event: task" -d "$BODY"(注意 payload message 中要含仓库标识)
- 返回 2xx(如 {"status":"accepted"})→ 写表:state=dispatched, dispatched_at=now, dispatch_count=dispatch_count+1, last_nudge_at=now, last_state_change_at=now。失败 → 不改状态,下轮重试。

### 5. 续接已有任务(空闲时;与步骤 4 合计每轮最多 2 条)
- 已注入过但无进展:state=dispatched 且无任何关联 PR(open 或 merged),且距上次注入(max(dispatched_at,last_nudge_at))已过至少一个 cron 周期(> 30 分钟)仍未产出 PR → 按步骤 4 候选池第 2 类重新注入续接(message 首行 subject "⏭ 续接任务 #N: <标题>(仓库 <repo>)",正文:任务已注入 X 分钟仍无 PR,请继续按 github dev flow 完成;若受阻说明原因 → 注入成功后 dispatch_count+1, last_nudge_at=now)。只要目标 chat 空闲且任务无进展,下一轮就续接,不等待其他时间窗口。若该 issue 已出现 merged PR,则不再续接,改走步骤 2 收尾(关 issue / 置 pr_merged)。
- state=pr_open 的 issue:等用户 review/merge,不注入、不催促。
- 每条注入前重新读表核对状态仍匹配;注入成功(2xx)才写状态。

### 6. 收尾
- 原子保存状态表并更新 updated_at。
- **待用户决策表格(每轮必查,1h 节流)**:收集所有需要用户参与的任务(两个仓库)——state=escalated(升级用户决策)与 state=pr_open(PR 待 review/merge)。若存在:距 meta.last_decision_notify_at 超 1 小时 → 输出一张 Markdown 汇总表格作为**最终响应**(列:仓库 | 编号 | 标题 | 状态 | 需要用户做什么 | 链接;escalated → "回复决策:继续等/换方案/关闭",pr_open → "review PR #N 并 merge"),首行 subject「📋 待你决策:N 项」;更新 meta.last_decision_notify_at=now。不足 1 小时 → 不输出表格。表格是给用户的决策清单(纯通知),不注入、不派活,**不以 [SILENT] 结尾**([SILENT] 会抑制 deliver 发送)。
- 无待决策表格且本轮注入过消息 → 输出 ≤3 行中文运行报告(检查结果 + 注入/续接了什么)。
- 无待决策表格、无注入、无异常 → 不输出任何内容,以 [SILENT] 静默退出(deliver 不发送空跑消息)。

## 硬性纪律(可重入与防刷屏)
1. 任何注入前必须重新读状态表核对,绝不基于内存旧状态发送。
2. 注入返回 2xx 才更新状态;失败一律不记,留给下轮。
3. 状态表写入必须原子(.tmp + mv),禁止覆盖写半截。
4. 每轮注入上限:注入/续接合计 ≤ 2(两个仓库共享);watchdog 异常消息 1h 限流。
5. 你是调度者不是开发者:绝不修改仓库代码、不创建分支/PR;只读 GitHub、注入任务、维护状态表。唯一例外:**为已合入 develop 的 PR 关闭其关联 issue**(`gh issue close N -R <repo> -c "<英文说明 + PR 号>"`)——这是状态收尾,不是开发动作;除这个例外不得对仓库做任何写操作(不改 label、不评论其他 issue、不关无关 issue)。
6. 无法完成的事如实写进运行报告,不编造。这套流程每次由 cron 周期重入,靠状态表天然幂等。
7. 唯一发送途径是 webhook 注入通道(用户角色)。绝不用 hermes send / 绝不用 deliver 投递发任务——那些都不能让 dev agent 真正开工。

附录:skill 全文

下面是 github-pr-workflow 的完整文本。为了能直接公开,示例用户名和仓库名做了替换,路径保持通用写法($HOME、/tmp、相对路径);使用时换成你自己的值即可。

---
name: github-pr-workflow
description: "GitHub PR lifecycle: branch, commit, open, CI, merge."
version: 1.7.1
author: Hermes Agent
license: MIT
platforms: [linux, macos, windows]
metadata:
  hermes:
    tags: [GitHub, Pull-Requests, CI/CD, Git, Automation, Merge]
    related_skills: [github-auth, github-code-review]
---

# GitHub Pull Request Workflow

Complete guide for the PR lifecycle. Each section shows the `gh` path first, then the `git` + `curl` fallback for machines without `gh`.

> **Implementation is always delegated to omp (user convention 2026-09-24).** Every implementation step in this workflow — writing code, fixing bugs, adding tests, writing helper scripts — runs through the `omp` CLI. Hermes only writes the task book (self-contained: requirement, acceptance criteria, test expectations, scope limits), conveys design intent in the task book or via steer, and reviews the result. Never write code or tests yourself; the only exception is omp being unavailable (timeout, environment failure), and the delivery note must state why. Each issue/task uses exactly one dedicated omp session: start it with `omp -p` and record the session id, then continue the same session for every later round (`omp -r <absolute jsonl path>`), never a new one. See the `omp` skill.

## Prerequisites

- Authenticated with GitHub (see `github-auth` skill)
- Inside a git repository with a GitHub remote

### Quick Auth Detection

```bash
# Determine which method to use throughout this workflow
if command -v gh &>/dev/null && gh auth status &>/dev/null; then
  echo "Using: gh"
else
  echo "Using: git + curl (token)"
  # Ensure we have a token for API calls
  if [ -z "$GITHUB_TOKEN" ]; then
    if _hermes_env="${HERMES_HOME:-$HOME/.hermes}/.env"; [ -f "$_hermes_env" ] && grep -q "^GITHUB_TOKEN=" "$_hermes_env"; then
      GITHUB_TOKEN=$(grep "^GITHUB_TOKEN=" "$_hermes_env" | head -1 | cut -d= -f2 | tr -d '\n\r')
    elif grep -q "github.com" ~/.git-credentials 2>/dev/null; then
      GITHUB_TOKEN=$(uv run python3 "${HERMES_HOME:-$HOME/.hermes}/skills/github/github-auth/scripts/git-credential-token.py")
    fi
  fi
fi
```

### Extracting Owner/Repo from the Git Remote

Many `curl` commands need `owner/repo`. Extract it from the git remote:

```bash
# Works for both HTTPS and SSH remote URLs
REMOTE_URL=$(git remote get-url origin)
OWNER_REPO=$(echo "$REMOTE_URL" | sed -E 's|.*github\.com[:/]||; s|\.git$||')
OWNER=$(echo "$OWNER_REPO" | cut -d/ -f1)
REPO=$(echo "$OWNER_REPO" | cut -d/ -f2)
echo "Owner: $OWNER, Repo: $REPO"
```

---

## Workflow Overview

Every change, from issue to release, follows the table below. **Each stage has a defined owner and exit condition; if the exit condition does not hold, stay in that stage** instead of jumping ahead.

| # | Stage | Owner | Output | Exit condition |
|---|---|---|---|---|
| 0 | Read branch policy | Parent | Confirmed base and allowed merge method | Verified with `gh api .../rules/branches/*` (§0) |
| 1 | Create branch | Parent | `fix/*` or `feat/*` off the latest `origin/develop`; one worktree per parallel issue | Branch starts from `develop`, not `main` (§1) |
| 2 | Implement | **omp implementation session** (one per issue) | Code, tests, self-check output (targeted tests for the touched files / lint; the full suite is CI's) | Targeted tests and lint pass, the diff stays inside the issue scope, and CI is green on the pushed SHA (§2, §6) |
| 3 | Commit and push | omp or parent | Conventional Commits, one topic per commit, pushed to the PR branch | No unrelated changes; the branch on the remote already carries the round (§3) |
| 4 | Open PR | Parent | PR with `--base develop`, English body, `Fixes #N.` on its own line | Body has no local paths or non-English text; base is correct (§4) |
| 5 | **Independent review** | **omp reviewer session** (isolated from implementation; returns the report only) | English PR comment **posted by the parent**, carrying the reviewed HEAD SHA and a P0/P1/P2 list | Acceptable review verdict (§5 Ready-to-Merge Criteria) |
| 6 | CI | Parent watches | Required check results | All required checks green on that SHA; infrastructure failures are only re-run (§6) |
| 7 | **Fix round (the loop)** | Parent dispatches, implementation session edits, reviewer re-reviews, parent posts the comment | New commit **pushed** plus a **new PR comment naming the new SHA**, or a "ready to merge" report | **Check the exit condition first** (§7 Step 1): ready-to-merge criteria hold → report ready and stop; otherwise fix CI failures or review findings, push, re-review, post the round's comment, repeat |
| 8 | Merge | Parent, on user instruction | Merge commit | User authorized, HEAD unchanged since the ready report; →`develop`: `--squash --delete-branch`; `develop→main`: `--merge` without `--delete-branch` (§8) |
| 9 | Wrap up | Parent | Issue closed, worktree removed, local branch synced | With `base=develop`, close the issue **manually** (§8) |
| 10 | Release (when needed) | Parent | `develop→main` PR → tag → release | New version on PyPI; release asset sha256 matches `SHA256SUMS` |

**Stages 5 and 6 run in parallel, not one after the other.** As soon as the PR exists, the review session and CI start together and never wait for each other; the numbering is listing order only. Stage 7 is the single loop that consumes both outputs: it re-checks the exit condition at the top of every iteration, exits by reporting the PR ready to merge, and never merges — merging is stage 8 and needs the user's word.

Three rules every round obeys — they bind the overview, not just §5/§7:

1. **Push before review.** A review always targets a pushed commit (`origin/<branch>`'s HEAD SHA); never review an uncommitted working tree. If the implementation is still dirty, commit and push it first — otherwise there is no SHA to review and no SHA to name in the comment. Stage 3 is therefore *commit and push*, not commit alone.
2. **Every round pushes its fixes.** A round ends only when the fixes are committed and pushed to the PR branch, so CI runs on them and the next review has something to read. Locally passing tests are not a finished round.
3. **Every round's verdict is posted to the PR.** The parent posts the reviewer's report with `gh pr comment <N> --body-file <file>` — first review and every re-review, each naming the SHA it reviewed. A verdict that exists only in the chat or in a session log is an unfinished round.

Three structural constraints:

1. **Nobody merges their own work.** Implementation runs in the omp implementation session, review in a different omp session, and the merge only happens on explicit user instruction. One session writing and reviewing its own code makes the review meaningless.
2. **Stage 7 is a loop, and its exit is a report, not a merge.** CI failures and review findings are the same loop (§7); each iteration starts by checking whether the PR is already ready, and ends by telling the user it is ready — the user then decides whether to merge.
3. **§9 has a copy-pasteable command sequence.** The table only tells you which stage you are in and what its exit condition is.

## 0. Branch Policy (check it, don't guess)

**Branch protection and merge methods differ per repository — never copy conclusions from another repo.** Check two things first:

```bash
# Which branch is the default (usually main, but not always)
gh repo view --json defaultBranchRef --jq .defaultBranchRef.name

# Ruleset of the target base: allowed merge methods, required checks, up-to-date policy, deletion policy
gh api repos/$OWNER/$REPO/rules/branches/<base> --jq '[.[]|{type:.type,params:.parameters}]'
```

How to read the result:

- The names in `required_status_checks` are the required checks; all of them must be green on the same SHA before merging.
- `allowed_merge_methods` / `required_linear_history` decide whether squash is allowed or only merge commits are.
- `strict_required_status_checks_policy: true` means the branch must already contain the latest base tip before merging.
- `deletion` / `non_fast_forward` forbid branch deletion and force-push; **these rules protect the default branch only**, so a non-default development branch such as `develop` can still be deleted by `--delete-branch`.

Measured example (a sample repository, Nov 2026; reference only — re-check for any other repository):

| Target branch | Allowed merge methods | Required checks | Other constraints |
|---|---|---|---|
| `develop` (base for feature PRs) | squash (or merge) | Lint and Format, Test Python 3.13, Security Scan, Test Windows (integration), Build Package | `strict_required_status_checks_policy: true`; deletion and force-push blocked |
| `main` (only receives develop sync PRs) | **merge commits only** | the five checks above plus `check-source` | only accepts PRs originating from this repo's `develop` branch (`enforce-develop-pr.yml`) |

General conclusions drawn from that example:

- **Feature PRs target the development branch (`develop` here), not the default branch.** The default is usually `main`, so omitting `--base` lands there and then gets rejected by the source check (`check-source`). When that check fails, re-check the base first instead of digging into the workflow config.
- **Development branch → default branch usually allows merge commits only.** Such a PR merged with `--squash` is rejected by the ruleset, and **never** pass `--delete-branch` — it would delete the development branch.

## 1. Branch Creation

This part is pure `git` — identical either way:

```bash
# Branch off develop (features and fixes both start from develop, never from main)
git fetch origin
git checkout develop && git pull --ff-only origin develop

# Create and switch to a new branch
git checkout -b feat/add-user-authentication
```

Branch naming conventions:
- `feat/description` — new features
- `fix/description` — bug fixes
- `refactor/description` — code restructuring
- `docs/description` — documentation
- `ci/description` — CI/CD changes

### One worktree per parallel issue

When several issues are in flight, give each one its own worktree so two omp sessions never fight over the same working directory:

```bash
git worktree add ../<repo>-<issue> -b fix/<issue-slug> origin/develop
```

Clean up after the merge (`rm -rf` alone leaves worktree metadata behind):

```bash
git worktree remove ../<repo>-<issue> --force
git worktree prune
```

## 2. Implementation (delegated to omp)

Implementation never happens in this conversation — it is delegated (see the delegation note at the top).

Write the task book before starting omp. It must carry, in full:

- the requirement and the problem it solves (link the issue)
- acceptance criteria stated so they can be checked
- the tests to add or update, plus the command that proves them
- explicit scope limits ("change only these files", "do not touch X")
- for fix rounds: every finding with `file:line` evidence

One session per issue: start with `omp -p @taskbook.md --cwd .` and record the jsonl path; every later round continues that session with `omp -r <absolute jsonl path> @taskbook.md`. Never start a second session for the same issue.

Acceptance is yours, not omp's self-report: read the diff and confirm it stayed inside scope, and mutate a key assertion (break it, run the single test file, confirm it fails, revert). Do not re-run the test suites or lint locally — CI does that on the pushed SHA (§6) and a local re-run only duplicates it; the local job is judging the diff, not re-executing CI. Only then go to §3.

## 3. Commits

Code changes are produced by omp (see the delegation rule at the top: one omp session per issue). The commit itself can be made by omp after the changes are done, or by Hermes once the change has been accepted (§2). Confirm the diff matches the task book before committing; do not carry unrelated edits.

```bash
# Stage specific files
git add src/auth.py src/models/user.py tests/test_auth.py

# Commit with a conventional commit message
git commit -m "feat: add JWT-based user authentication

- Add login/register endpoints
- Add User model with password hashing
- Add auth middleware for protected routes
- Add unit tests for auth flow"
```

Commit message format (Conventional Commits):
```
type(scope): short description

Longer explanation if needed. Wrap at 72 characters.
```

Types: `feat`, `fix`, `refactor`, `docs`, `test`, `ci`, `chore`, `perf`

## 4. Pushing and Creating a PR

> **PRs are written in English (user convention 2026-10-07).** Title and body — summary, changes, test plan — are all English; Chinese is only used when talking to the user. Check the body for leftover non-English text before creating the PR.
>
> **Always pass `--base develop`** (§0). Omitting it targets the default branch `main`.
>
> **The title becomes the final commit subject.** After the squash, the commit message is taken from the PR title, so the title must be in Conventional Commits form; keep the issue number in the body, not the title.
>
> **No local machine details in the body (user convention 2026-11-09).** Never include absolute paths, home directories, `/tmp`, hostnames, extraction directories, local install paths, or omp session ids. Write commands in a generic form (e.g. `kicad-cli`); versions are fine, paths are not. Self-check before creating the PR:
>
> ```bash
> grep -nE '/home/|/tmp/|squashfs|\.jsonl' body.md   # must print nothing
> ```
>
> **Link the issue with `Fixes #N.` on its own line** (user convention): put it at the end of the body, never glued to another sentence.

### Push the Branch (same either way)

```bash
git push -u origin HEAD
```

### Create the PR

**With gh:**

```bash
gh pr create \
  --base develop \
  --title "feat: add JWT-based user authentication" \
  --body "## Summary
- Adds login and register API endpoints
- JWT token generation and validation

**Test Plan**
- [ ] Unit tests pass

Fixes #42."
```

Options: `--draft`, `--reviewer reviewer1,reviewer2`, `--label "enhancement"`.

**With git + curl:**

```bash
BRANCH=$(git branch --show-current)

curl -s -X POST \
  -H "Authorization: token ***" \
  -H "Accept: application/vnd.github.v3+json" \
  https://api.github.com/repos/$OWNER/$REPO/pulls \
  -d "{
    \"title\": \"feat: add JWT-based user authentication\",
    \"body\": \"## Summary\nAdds login and register API endpoints.\n\nFixes #42.\",
    \"head\": \"$BRANCH\",
    \"base\": \"develop\"
  }"
```

The response JSON includes the PR `number` — save it for later commands.

To create as a draft, add `"draft": true` to the JSON body.

## 5. Review: Setup, Verdict, and Triage of Findings

**Position**: `create branch → implement (omp) → push → open PR → independent review (this section, in parallel with CI) → fix rounds, whose exit check certifies readiness (§7) → user approval → merge (§8)`. The review must be finished before telling the user the PR is ready to merge. **Green CI is not a passed review, and an APPROVE is not green CI** — both are readiness conditions.

User convention 2026-09-28: once a PR exists, run the code review in a **separate omp session**, strictly isolated from the implementation session.

**This applies to every PR type — revert PRs, docs-only PRs, and small fixes included.** Schedule the independent review immediately after creation and complete it before reporting "PR is ready"; the user will ask "did the independent review pass?" as an acceptance check, and answering only when asked means the step was skipped (it has actually been skipped once for a revert PR and once for a small fix). Revert PRs have an extra acceptance check: `git diff <reverted squash commit>^ <head>` must be empty (byte-identical tree to the pre-feature state), and a repo-wide grep for the removed symbols must show zero references (definitions, imports, call sites, and test classes all gone).

1. **Start a separate review session**: `omp -p @review_taskbook.md ...`, never reuse the implementation session. Findings are later fixed in the implementation session.
2. **The review task book must state**: strictly read-only (no file writes, no code edits, no commits, no pushes, **no PR comments**), review scope (commit range, e.g. `git log --oneline base..HEAD`), review dimensions, output format (structured report, every finding with `file:line` evidence, P0/P1/P2 priority list), and the report language. The reviewer **returns** the report; it never posts, comments, commits, or pushes — posting is the parent's job (§5.4). **Review only pushed commits**: never point a review at an uncommitted working tree. If the implementation is not committed and pushed yet, commit and push first, then review `origin/<branch>`. **Test scope: none of the suites.** Do not run `tests/unit`, `tests/integration`, or `pytest tests/`, and do not re-run lint/format — CI already covers all of it on the pushed SHA, and re-running only adds minutes for zero new signal (user convention 2026-11-12). The reviewer's review work is: read the diff, judge design, and **mutate the tests** — break a key assertion or the production line it guards, run **only that single test file** (seconds, not the suite), confirm it fails, revert. Mutation is the one signal CI cannot give: CI proves the code passes its tests, mutation proves the tests would catch a regression. Do not run a review and a fix in the same worktree at the same time: the fix dirties the tree and the reviewer's evidence becomes ambiguous. Serialize them, or use a separate worktree.
3. **The parent spot-checks the key findings** (do not trust self-reports): pick the two or three heaviest claims (dead code existence, registry/tool names, interface-versus-docs consistency), verify them yourself with grep, then report to the user.
4. **Review findings must be posted as a PR comment (user convention 2026-10-29, mandatory).** The **parent** posts the reviewer's verdict with `gh pr comment <N> --body-file <file>` as soon as the reviewer returns, for **every** round: the first review and every re-review. A round that ends with only a chat summary is an incomplete round. The comment contains the reviewed HEAD SHA, the overall verdict (APPROVE / REQUEST CHANGES), the P0/P1/P2 list with `file:line` evidence for each item, and the verification commands run with their results. Use `gh pr comment`, not `gh pr review --approve` — the agent created the PR and GitHub forbids approving your own PR (`Can not approve your own pull request`). Write the comment in English (public repository), with no absolute paths, home directories, `/tmp`, hostnames, or omp session ids. **Ordering is hard: post the PR comment before telling the user the PR is ready.** Without a review comment on the PR it is never reported as ready.
5. **Report to the user first**: the P0/P1/P2 list (triage rules in the table below). Start fix rounds for review findings only after the user says to proceed, and continue them in the implementation session, not the review session — do not start fixing review findings unprompted. CI failures are the exception: those are diagnosed and fixed as soon as they appear (§7).
6. **Every fix must be re-reviewed (user convention 2026-10-29, mandatory loop).** After each fix push, go back to the reviewer session (`omp -r <review-session-id>` — the same independent reviewer, never a new one and never the implementation session) and review the latest HEAD. Loop until the verdict is acceptable (*Ready-to-Merge Criteria* below), one pass of §7 Step 4 per round. **Every round gets its own PR comment**: verdict, the HEAD SHA it applies to, the status of the previous round's P0/P1, and any new findings. A verbal "it's fixed" in chat does not count.
7. **Exit check**: §7 Step 1 decides when the loop ends and what the report to the user contains. **Merging only happens on explicit user instruction** (⛔ §8): the agent never merges on its own and never enables auto-merge.

### Handling review findings

| Severity | Handling |
|---|---|
| P0 (wrong behavior, broken data or contract, security) | Must fix. The parent writes the fix task book and dispatches it to the **same implementation session** (`omp -r <implementation session>`), never a new session |
| P1 (correctness gap, missing critical test, misleading output) | Fix by default, same path as P0 |
| P2 (robustness, maintainability, edge cases) | **Fix it if it is fixable.** If the fix is expensive and the impact small (touches a public interface, drags in cross-module refactoring, no automated way to verify it), it may be dropped — but the review comment or closing note must state the reason for dropping it and the impact. No vague hand-waving |
| Pure cosmetic (constant names, comment wording) | Not worth a round: record it in the closing note or a new issue; **do not smuggle it** into the current PR |
| "While you're here, add a feature" | Open a new issue; adding it here violates "no unrelated changes" |

**Every fix round runs the loop in §7 Step 4** — dispatch to the same implementation session, verify locally, push, re-review in the same reviewer session, post a new comment, then re-check readiness. The steps are written once, there.

**Do not rebase during review.** A rebase changes the HEAD SHA and instantly invalidates the previous comment (the readiness check requires SHA equality), which wastes a whole review round. Syncing with `develop` via `git merge origin/develop` has the same effect — it creates a new commit — so sync early if the branch is known to be behind, and treat any post-review sync as making the review stale.

### Ready-to-Merge Criteria (canonical)

This block is the single definition of "the review is done" and "the PR is ready to merge". The overview table, §7, §8, and §9 point here instead of restating it — change a criterion here and nowhere else.

**Acceptable review verdict** — the fix loop stops only when the latest review comment is APPROVE, or APPROVE WITH COMMENTS with zero open P0/P1.

**Ready to merge** — all four must hold:

| # | Condition | Verified by |
|---|---|---|
| 1 | The HEAD SHA in the latest review comment equals the current PR HEAD | `gh pr view <N> --json headRefOid` against the SHA line in the comment; if HEAD moved, the PR counts as unreviewed |
| 2 | All required checks are green on that SHA | required-check list in §0; `gh pr view <N> --json statusCheckRollup` |
| 3 | `mergeStateStatus` is `CLEAN` | command in §8; for `BLOCKED` / `DIRTY`, check the §6 pitfalls first |
| 4 | Zero open P0/P1 in that comment, and any remaining P2 is handled per the P2 row of the triage table, with its reason and impact written into the comment or the closing note | read the comment's findings list |

Any single open P0/P1, fixable-but-unfixed P2, red check, or stale comment SHA means the PR is not ready. Check this at the top of every fix round (§7 Step 1) and again right before merging (§8).

**Authorization is not part of readiness** — a ready PR is still not merged until the user explicitly says so (⛔ §8).

See the "Code Review" section of the `omp` skill for the review-session mechanics.

## 6. Monitoring CI Status

### Check CI Status

**With gh:**

```bash
# One-shot check
gh pr checks

# Watch until all checks finish (polls every 10s)
gh pr checks --watch
```

**Pitfall — "no checks reported" / zero runs is NOT a green CI** (verified 2026-09): a fresh PR can sit with `gh pr checks` returning `no checks reported`, `gh run list --branch <b>` empty, and `mergeStateStatus: BLOCKED` while every check a moment later would pass. The workflow config may be correct (`branches: [main, develop]`, base matches) and the push simply never scheduled a run. Do NOT try `gh pr merge` — the base branch policy refuses with "the base branch policy prohibits the merge" and does not tell you CI never ran. Fix: **close + reopen the PR** (`gh pr close <n>` then `gh pr reopen <n>`) — that re-emits the `pull_request` event and schedules the workflow; then poll `gh pr checks`. Diagnose before acting: confirm `gh pr view <n> --json headRefOid` matches `git rev-parse origin/<head-branch>` (a mismatched head means the PR points at a stale commit, reopen will not help), and confirm `gh run list --branch <head>` really is empty (not just filtered).

**Pitfall — all checks green but the merge is still refused: `develop`'s strict policy** (verified 2026-11): `develop` enables `strict_required_status_checks_policy`, so a PR that does not contain the latest `develop` stays `mergeStateStatus: BLOCKED` even with all five checks green. The fix is to merge `develop` into the branch and push (**do not rebase**, see §5):

```bash
git fetch origin && git merge origin/develop
```

**Pitfall — infrastructure failures are not code failures** (verified 2026-11): `Install uv` returning `Unexpected HTTP response: 504`, a cache step with `Failed to restore: Cache service responded with 400`, or a runner that never starts have nothing to do with the repository code. The remedy is a re-run, not a code change:

```bash
gh run rerun <RUN_ID> --failed
```

**On the Hermes side**: `gh pr checks --watch` typically runs 5–10 minutes. Start it as a background job (`background=true, notify=true`) and poll it; never block in the foreground, and never pipe it through `| tail` — the pipe swallows the exit code and makes failures look like successes.

**With git + curl:**

```bash
# Get the latest commit SHA on the current branch
SHA=$(git rev-parse HEAD)

# Query the combined status
curl -s \
  -H "Authorization: token ***" \
  https://api.github.com/repos/$OWNER/$REPO/commits/$SHA/status \
  | python3 -c "
import sys, json
data = json.load(sys.stdin)
print(f\"Overall: {data['state']}\")
for s in data.get('statuses', []):
    print(f\"  {s['context']}: {s['state']} - {s.get('description', '')}\")"

# Also check GitHub Actions check runs (separate endpoint)
curl -s \
  -H "Authorization: token ***" \
  https://api.github.com/repos/$OWNER/$REPO/commits/$SHA/check-runs \
  | python3 -c "
import sys, json
data = json.load(sys.stdin)
for cr in data.get('check_runs', []):
    print(f\"  {cr['name']}: {cr['status']} / {cr['conclusion'] or 'pending'}\")"
```

### Poll Until Complete (git + curl)

> The polling loop below is only for environments without `gh`. On the Hermes side, run `gh pr checks <N> --watch` as a background job instead of sleeping on a fixed interval.

```bash
# Simple polling loop — check every 30 seconds, up to 10 minutes
SHA=$(git rev-parse HEAD)
for i in $(seq 1 20); do
  STATUS=$(curl -s \
    -H "Authorization: token ***" \
    https://api.github.com/repos/$OWNER/$REPO/commits/$SHA/status \
    | python3 -c "import sys,json; print(json.load(sys.stdin)['state'])")
  echo "Check $i: $STATUS"
  if [ "$STATUS" = "success" ] || [ "$STATUS" = "failure" ] || [ "$STATUS" = "error" ]; then
    break
  fi
  sleep 30
done
```

## 7. Fix Rounds — one loop for CI failures and review findings

There is no separate "fix CI" procedure. CI failures and review findings are handled by the same loop, the mandatory loop from §5, and this section is where it runs. Run it every time stage 5 or 6 produces a result and after every push: Step 1 decides whether there is anything left to do.

**Every round has four steps, in this order**: fix → commit → push → re-review the pushed HEAD → post that round's comment on the PR (§5.4). Skipping the push or the comment leaves the round half-done, even when the code is correct.

### Step 1: Check the exit condition first

Before touching anything, evaluate the ready-to-merge criteria (§5, canonical). If all four hold, **stop fixing and report the PR ready to merge** — reviewed HEAD SHA, check results, verdict of the last review comment — then wait for the user. The loop ends with that report; it never merges (§8).

```bash
gh pr view <N> --json headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{head:.headRefOid, state:.mergeStateStatus, checks:[.statusCheckRollup[]|{name,conclusion}]}'
```

If they do not hold, name the blockers — red check, stale review SHA, `BLOCKED` merge state, open P0/P1 — and fix only those.

### Step 2: Classify each blocker

| Blocker | Action |
|---|---|
| Infrastructure failure (`Install uv` 504, cache restore 400, runner never started) | Re-run only: `gh run rerun <RUN_ID> --failed` (§6) |
| Code failure (tests, lint, or build actually ran and failed) | Diagnose (Step 3), then dispatch (Step 4) |
| `mergeStateStatus: BLOCKED` with every check green | Branch is behind the base: `git fetch origin && git merge origin/develop` — never rebase (§5); the new commit makes the review stale, so re-review |
| Review finding P0 or P1 | Task book → dispatch (Step 4); re-review is mandatory |
| Review finding P2 | Per the P2 row of the triage table (§5) |
| Review comment points at an older SHA | Nothing to fix — re-review the current HEAD (§5) |

### Step 3: Diagnose a CI failure

**With gh:**

```bash
# List recent workflow runs on this branch
gh run list --branch $(git branch --show-current) --limit 5

# View failed logs
gh run view <RUN_ID> --log-failed
```

**With git + curl:**

```bash
BRANCH=$(git branch --show-current)

# List workflow runs on this branch
curl -s \
  -H "Authorization: token ***" \
  "https://api.github.com/repos/$OWNER/$REPO/actions/runs?branch=$BRANCH&per_page=5" \
  | python3 -c "
import sys, json
runs = json.load(sys.stdin)['workflow_runs']
for r in runs:
    print(f\"Run {r['id']}: {r['name']} - {r['conclusion'] or r['status']}\")"

# Get failed job logs (download as zip, extract, read)
RUN_ID=<run_id>
curl -s -L \
  -H "Authorization: token ***" \
  https://api.github.com/repos/$OWNER/$REPO/actions/runs/$RUN_ID/logs \
  -o /tmp/ci-logs.zip
cd /tmp && unzip -o ci-logs.zip -d ci-logs && cat ci-logs/*.txt
```

### Step 4: Dispatch, verify, push, re-review

Once the cause is known, **do not fix it yourself**. Put the key log lines or findings (each with `file:line`), the reproduction and verification commands, and the acceptance criteria into a task book, then run this sequence. It is identical for both blocker types — only the task book differs.

1. Dispatch to this issue's implementation session (`omp -r <absolute jsonl path> @taskbook.md`); never a new session.
2. Wait for omp's commit. Do not trust its self-report.
3. Re-verify: mutate the key assertion (revert the production line or the assertion, run that one test file, it must fail, then restore). Do not re-run the suites or lint locally — CI runs both on the pushed SHA (§6); a local re-run adds minutes and no signal.
4. Read the diff and confirm it stayed inside the task book's scope.
5. Push, then re-review the new HEAD in the same reviewer session (`omp -r <review session>`).
6. Post the new PR comment: new HEAD SHA, status of the previous round's P0/P1, new findings.
7. Return to Step 1.

If the same blocker survives three consecutive rounds without progress, stop and ask the user.

## 8. Merging

> ⛔ **Merging only happens on explicit user instruction** (hard rule): the agent never merges on its own and never enables auto-merge. Only "you can merge / merge it / squash it" counts as authorization, and only for that one PR. A "ready to merge" report from stage 7 is not authorization.

Re-check readiness against the current HEAD before merging — criteria in §5 (*Ready-to-Merge Criteria*), not restated here. If HEAD moved or a check went red since the ready report, the report is stale: go back to §7. State to pull:

```bash
gh pr view <N> --json headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{head:.headRefOid, state:.mergeStateStatus, checks:[.statusCheckRollup[]|{name,conclusion}]}'
```

**Pick the merge method by base:**

```bash
# Feature PR → develop: squash and delete the source branch
gh pr merge <N> --squash --delete-branch

# develop → main (release sync): merge commit only, never --delete-branch
gh pr merge <N> --merge
```

The curl fallback follows the same rule: `merge_method` is `squash` (→ develop) or `merge` (→ main). `squash` against `main` is rejected; **never** run `git push origin --delete` for a `develop` source branch.

**Do not use `--auto`**: it errors out when auto-merge is not enabled on the repository, and it bypasses readiness condition 1 (comment SHA == HEAD).

### After the merge

With `base=develop`, GitHub does **not** close the issue automatically (auto-close only fires when merging into the default branch):

```bash
gh issue comment <issue> --body-file close_note.md   # what changed, how it was verified, known leftovers
gh issue close <issue> --reason completed
```

`gh issue close --comment-file` does not work; split it into `comment` and `close` as above (verified 2026-11).

Then clean up locally:

```bash
git checkout develop && git pull --ff-only origin develop
git worktree remove ../<repo>-<issue> --force && git worktree prune
git branch -d <branch>   # the remote branch was already removed by --delete-branch
```

## 9. Complete Workflow Example

```bash
# 1. Start from develop (one worktree per parallel issue, see §1)
git fetch origin && git checkout develop && git pull --ff-only origin develop
git checkout -b fix/login-redirect-bug

# 2. Implementation goes to omp (one session per issue); do not write code yourself
omp -p @taskbook.md --cwd .

# 3. Inspect the diff, then commit
git add src/auth/login.py tests/test_login.py
git commit -m "fix: correct redirect URL after login

Preserves the ?next= parameter instead of always redirecting to /dashboard."

# 4. Push and open the PR (base=develop, English body, Fixes #N. on its own line)
git push -u origin HEAD
gh pr create --base develop --title "fix: ..." --body-file body.md

# 5. Independent review session (§5); post the verdict as a PR comment
# 6. CI: watch it in the background, do not block the foreground (§6)
# 7. Fix round, starting with the exit check (§7): if the ready-to-merge criteria hold, report ready and stop;
#    otherwise task book → same implementation session → re-verify → push → same reviewer re-reviews → new comment
# 8. After the user explicitly says to merge (a ready report is not authorization): re-check HEAD unchanged,
#    then feature PR uses --squash --delete-branch; develop→main uses --merge
# 9. Close the issue manually and remove the worktree (§8)
```

## Useful PR Commands Reference

| Action | gh | git + curl |
|--------|-----|-----------|
| Branch rules | `gh api repos/$OWNER/$REPO/rules/branches/<branch>` | same call via `/rules/branches/<branch>` |
| Merge state | `gh pr view N --json mergeStateStatus,headRefOid` | `curl .../pulls/N` |
| List my PRs | `gh pr list --author @me` | `curl -s -H "Authorization: token ***" "https://api.github.com/repos/$OWNER/$REPO/pulls?state=open"` |
| View PR diff | `gh pr diff` | `git diff main...HEAD` (local) or `curl -H "Accept: application/vnd.github.diff" ...` |
| Add comment | `gh pr comment N --body "..."` | `curl -X POST .../issues/N/comments -d '{"body":"..."}'` |
| Request review | `gh pr edit N --add-reviewer reviewer` | `curl -X POST .../pulls/N/requested_reviewers -d '{"reviewers":["user"]}'` |
| Close PR | `gh pr close N` | `curl -X PATCH .../pulls/N -d '{"state":"closed"}'` |
| Check out someone's PR | `gh pr checkout N` | `git fetch origin pull/N/head:pr-N && git checkout pr-N` |