Skip to content

feat: implement @botmux-ai/plugin-github PR watcher and automated review group plugin - #1

Merged
deepcoldy merged 5 commits into
mainfrom
wt/botmux-ai-plugin-github-root-iserve
Nov 26, 2026
Merged

deepcoldy merged 5 commits into
mainfrom
wt/botmux-ai-plugin-github-root-iserve

Conversation

@deepcoldy

Copy link
Copy Markdown
Contributor

Summary

Implements the official @botmux-ai/plugin-github plugin for Botmux: GitHub PR event monitoring and crash-safe automated Botmux review group creation (Feishu / Lark), ready to run on current Botmux core (Phase 1 zero-core-change) and automatically forward-compatible with upcoming Botmux core IPC/webhook/dashboard enhancements.

Highlights

  • Self-contained Zero-Dependency Package (Node 22+ & Standalone Bun Binary)
    • package.json: @botmux-ai/plugin-github, botmux.schemaVersion: 1, id: "github", service.mode: "auto", files: ["dist/"], publishConfig.registry: "https://registry.npmjs.org/", zero runtime dependencies.
    • Pure esbuild ESM bundles (dist/service/{index,runner}.js, dist/dashboard/index.js using host api.react, dist/server/settings.js, dist/cli/{index.js,commands.json}, dist/webhooks/index.json, dist/package.json) with atomic directory swap and dist/botmux-build/stamp written last.
  • Dormant-by-Default Background Service & GitHub Reliability
    • Strictly dormant (mode: "dormant") with zero GitHub API calls and zero Feishu/Lark calls until at least one repository watch rule is enabled; supports live dormant <-> active config hot-reload without restart.
    • Auth: Fine-grained/Classic PAT, GitHub App Installation Token (pure node:crypto RS256 JWT + custom apiBaseUrl for GHES), and in-memory gh auth token fallback with single 401 refresh retry.
    • If-None-Match ETag 304 zero-quota polling (keyed by apiBaseUrl + auth principal fingerprint), independent core/search <10% throttling, 429/403 secondary rate-limit backoff (Retry-After -> core X-RateLimit-Reset when remaining == 0 -> 1m..1h monotonic exponential backoff), fail-closed outbound proxy + HTTP CONNECT TLS tunneling, SSRF/redirect defense, and dual-layer secret redaction.
  • Dual-Source Event Ingestion & Anti-Injection Isolation
    • Authoritative poller captures a first-run baseline of open PRs without creating groups for historical PRs (historical backfill via explicit github:open-pr or Dashboard action only).
    • Optional loopback webhook receiver (127.0.0.1:<port>/webhooks/github and /webhook/plugin/github/events) enforcing >=32B high-entropy secrets, <=1 MiB streaming body limits, raw-byte timingSafeEqual X-Hub-Signature-256 verification before JSON parsing, repo allowlist, and bounded X-GitHub-Delivery deduplication — feeding into a shared FIFO PerPrSerialQueue.
    • All untrusted PR fields are sanitized (ANSI, Unicode Tags, BiDi, C0/C1, Feishu <at> / @all) and XML-escaped inside <untrusted_pr_metadata ...> with fail-closed is_fork and maintainer_can_modify flags, never interpolated into shell argv.
  • Crash-Safe Dual-Core HostBridge
    • Direct node:http 127.0.0.1 loopback IPC (immune to Bun fetch $http_proxy 403) with ~/.botmux/.dashboard-secret HMAC auth.
    • creating lock -> anchored GET /api/groups duplicate prevention -> POST /api/groups/create (dual-core kickoff + immediate chatId persistence even on partial 502 + botmux create-group CLI fallback) -> kickoffMessageId readback verification -> dual-path top-notice (POST /api/groups/:chatId/top-notice with brand-aware open.feishu.cn / open.larksuite.com Open API fallback, never lark-cli --as user) -> optional idempotent PR share-link comment & onNewCommit/onPrClosed updates.
  • Dashboard (#/plugins/github), Write-Only 0600 Settings & CLI
    • Dashboard reuses api.react and api.listBots(), supports api.serviceFetch/api.requestService with graceful fallback to getSettings/saveSettings, write-only secret handling, full rule CRUD, auth test, rate-limit health, and PR->group mappings.
    • CLI commands: github:status, github:sync [--repo] [--dry-run], github:open-pr <owner/repo#N> [--dry-run], github:test-auth.
  • Market Entry & Docs: Includes docs/plugin-market-entry.json (matching botmux-ai/plugin-market schema) and bilingual EN/ZH README.md.

Test Plan

  • npm run typecheck (tsc --noEmit) — 0 errors
  • npm run build && npm run validate — self-contained dist/ verified with zero symlinks and standalone temp-dir import checks
  • npm run test:unit — 26/26 passed (ETag 304/bypass/pagination, rate-limit <10% & 1m..1h backoff, PAT/App/GHES/gh auth, real HTTP CONNECT TLS proxy & fail-closed 407, SSRF/redirects, webhook raw-byte HMAC/1 MiB/dedup/anti-CSRF, FIFO queue, <untrusted_pr_metadata> escaping, secret redaction, 0600/O_NOFOLLOW/symlink fs checks)
  • npm run test:integration — 8/8 passed (dormant default zero-request, first-run baseline zero-storm, draft->ready, webhook+poller serial queue, onNewCommit/onPrClosed, HostBridge dual-core/Feishu+Lark/502+crash resume/readback rejection/CLI fallback/idempotent PR comment, settings/dashboard/CLI end-to-end)
  • Clean-room tarball verification (npm pack 165.2 kB -> npm install --ignore-scripts --omit=dev -> isolated dist/ run under both Node v24.22.2 and Bun 1.4.4)
  • Verified manifest & contributions against Botmux core parsePluginPackageManifest and scanPluginContributions

🤖 Generated with Claude Code

…iew group plugin

- Add self-contained esbuild ESM build pipeline (Node 22+ and standalone Bun binary compatible, zero runtime dependencies, atomic dist swap + dist/botmux-build/stamp)
- Implement dormant-by-default background service with PAT, GitHub App RS256 JWT (GHES-ready), and in-memory gh auth token fallback, ETag 304 zero-quota polling, per-resource core/search <10% throttling, 429/403 1m->1h monotonic backoff, fail-closed proxy + HTTP CONNECT TLS tunneling, and dual-layer secret redaction
- Implement dual-source event ingestion (authoritative poller with first-run baseline snapshot + optional 127.0.0.1 HMAC-SHA256 webhook receiver) feeding a shared FIFO per-PR serial queue
- Implement anti-injection <untrusted_pr_metadata> XML escaping with isFork/maintainerCanModify flags and Feishu <at>/@ALL neutralization
- Implement crash-safe dual-core HostBridge (node:http loopback IPC bypassing Bun $http_proxy 403, creating lock, anchored GET /api/groups dedup, POST /api/groups/create with current-core/CLI fallbacks, kickoff readback verification, dual-path Feishu/Lark top-notice, idempotent PR share-link comment, onNewCommit/onPrClosed notifications)
- Add Dashboard UI (#/plugins/github using api.react + api.listBots + dual-path serviceFetch/getSettings), write-only 0600 server/settings.js adapter, 4 CLI commands (github:status, github:sync, github:open-pr, github:test-auth), docs/plugin-market-entry.json, bilingual README, and 34 unit/integration/packaging tests

Co-Authored-By: Claude Code <[email protected]>
@deepcoldy

Copy link
Copy Markdown
Contributor Author

独立复审结论:不可合(head 55cb5a1e71dedcc9110b63be1318eb49ce704e91)

现有 CI、34 个单测/集成测试、构建和打包检查均通过;但使用真实 GitHubWatcher / HostBridge / StateStore 与本地可控 GitHub/daemon 假服务做异常时序复核后,发现以下可稳定复现的问题。正常路径测试没有覆盖这些失败窗口。

**现行核心契约结论(通过):**对照 current core 81a9938b1a(v3.59.32+20,不含后来合入的 deepcoldy/botmux#3827)做了 17/17 真实模块 interop 探针与服务启动 smoke。parsePluginPackageManifest、scanPluginContributions、settings、service definition/env、CLI 注册、daemon discovery、.dashboard-secret HMAC(METHOD path port bind)、GET groups、POST create、消息/回读/members-display、CLI create-group 参数和响应均匹配;现行核心的 Phase 1 路径本身未发现契约阻断。这里未使用真实 GitHub/飞书凭据或线上建群。

P2(deepcoldy/botmux#3830 拟定契约)— 实际生成的 webhook manifest 会让宿主转发 404

插件位置:scripts/build.mjs:163-183(实际 dist/webhooks/index.json 同形)。deepcoldy/botmux#3830 head fdf00bc0583c94f9cc5f8991d8b925bc13089bae 的 src/core/plugins/webhooks/protocol.ts:103-130 只读取 route 的 mount-relative path 与 endpoint;targetEndpoint 被丢弃。公共 URL /webhook/plugin/github/events 经核心解析得到 subpath /events,而插件声明的 route.path 是完整 /webhook/plugin/github/events。

使用 deepcoldy/botmux#3830 指定 head 的真实 parser/matcher 运行本 PR 实际构建产物,观测:

{
  "parsedContribution":{"routes":[{"path":"/webhook/plugin/github/events","maxBodyBytes":1048576}]},
  "incoming":{"ok":true,"pluginId":"github","subpath":"/events"},
  "matched":null,
  "corrected":{"upstreamPathname":"/webhooks/github"}
}

因此 manifest 能通过解析,却在运行时不匹配,正是容易被现有测试漏掉的失败形态。应改为 route { path: "/events", endpoint: "/webhooks/github", maxBodyBytes: 1048576 },并增加直接调用核心 parser/matcher 的契约测试。现行 core 尚未扫描 webhooks contribution,所以此项不影响上述 Phase 1 当前路径,但否定“自动 forward-compatible”的声明。同一拟定契约还要求校验 Authorization: Bearer <BOTMUX_PLUGIN_WEBHOOK_TOKEN>;src/service/runner.ts:129-134,241-314 当前未读取或校验该 token,修复路由时应一并补齐。

P1 — webhook 提前提交 PR 游标,后续权威轮询不再补建群

位置:src/engine/watcher.ts:320-347、src/engine/watcher.ts:790-847;前置失败窗口见 src/host/bridge.ts:736-775。

processWebhookPrEvent() 在处理动作之前就写入 knownPrs。轮询只对“无 prevCursor”或 draft→ready 的 PR 建群,因此:

  1. 空基线后投递 opened,让 bots.json 暂时损坏,使 loadBotsConfig() 在 creating 落盘前失败;修复配置后连续两次 poll(第二次强制绕过 ETag)仍为空:
{"cursorAfterFailure":"present","groupAfterFailure":null,"poll1":[],"poll2":[],"finalGroup":null}

进程在两次状态写入之间崩溃也会形成同一状态。

  1. 对未知非 draft PR 先收到 synchronize(例如 opened 丢失或乱序),webhook 不建群却提交游标;后续两次全量 poll 也为空,groupRecords 保持 []。

**建议:**动作成功后再推进游标;失败时恢复旧游标。未知 PR 的非 opened 事件不能直接把它标记为已完成发现。

P1 — creating 记录不构成跨实例互斥;两种恢复时序都会真实创建重复群

位置:src/host/bridge.ts:751-940、src/state/store.ts:161-185。状态文件锁只保护单次写入,没有覆盖 GET 查重 + POST 建群事务。

**复现 A:**两个独立 bridge/store 实例共用同一 plugin home,同时看到已有 creating 记录;让两个 GET /api/groups 都在空列表时放行:

{"listCalls":2,"createCalls":2,"daemonGroups":["oc_concurrent_1","oc_concurrent_2"],"finalStateChatId":"oc_concurrent_2"}

两个外部群都建成,状态只跟踪最后一个。CLI 的独立 watcher 回退与后台服务并存时,这不是仅限于测试的实例模型。

**复现 B:**第一次 IPC POST 已在 daemon 侧建群,但响应 socket 在返回前断开;此时状态为 creating 且无 chatId。让 daemon 描述符暂时离线后重试,代码走 CLI 创建:

{"stateAfterDroppedResponse":{"status":"creating","chatId":null},"cliCalls":1,"externallyCreated":[{"path":"ipc","chatId":"oc_ipc_outcome_unknown"},{"path":"cli","chatId":"oc_cli_duplicate"}]}

另一个入口也会放大该风险:src/cli/index.ts:130-142,419-440 将 mutation 已被服务接受后的 ECONNRESET 当成 unreachable,再启动独立 watcher 重放 openPr()。实测原操作仍暂停时 singlePrCalls=2,证明第二次流程确实执行;本次一致 GET 查重使 createCalls=1,因此不把它单独宣称为已复现双群,但 mutation 的 unknown outcome 不应自动换成另一执行器重放。

**建议:**增加带 owner/nonce 和过期恢复的跨进程 per-PR 锁,覆盖查重与创建;记录 create attempt/idempotency key。凡 IPC 已尝试但结果未知,不得仅因 daemon 暂时离线或 socket reset 就改用另一条创建路径,必须先恢复可查重状态。

P2 — 关闭事件可被 ETag 永久掩盖(两条独立路径)

**A. 单 PR 确认失败被忽略。**位置:src/engine/watcher.ts:861-879、src/engine/watcher.ts:885-927、src/engine/watcher.ts:698-710。

空 open 列表带新 ETag,GET /pulls/1 返回一次 500;代码仍保存 ETag 并标记 poll ok。下一次 304 后直接跳过:

{"singlePrLookupCalls":1,"etagAfterError":"\"closed-list-v2\"","pollStatusAfterError":"ok","secondActions":[{"action":"skip_not_modified"}],"groupStatusAfter304":"active","processedCloseKeys":[]}

**B. 只校验第 1 页 ETag。**位置:src/github/client.ts:385-429、src/github/client.ts:457-473。

基线含 101 个 open PR 且 #101 有 active 群;关闭第 2 页的 #101,而第 1 页表示与 ETag 不变。合法的第 1 页 304 使第 2 页永不再读取:

{"page1Calls":2,"page2Calls":1,"singlePrLookupCalls":0,"groupStatus":"active","closeEvents":[]}

**建议:**关闭确认失败必须使本轮失败并禁止推进 ETag/游标;有跨页 tracked PR 时不能用第 1 页 304 证明完整 open 集未变,需逐页 validator、定期完整扫描或其他权威关闭通道。

P2 — reopen/second-close 生命周期在轮询与 webhook 均会破坏群状态

位置:src/engine/watcher.ts:333-338、src/engine/watcher.ts:397-408、src/engine/watcher.ts:790-848、src/engine/watcher.ts:543-593、src/state/store.ts:44-51。

**A. close→reopen 不恢复。**轮询没有 closed-cursor→open 的分支;webhook 将 reopened 映射为 opened,同 SHA 时又命中原 opened@SHA processed key。种子为 closed PR + closed group 后:

{"poll1":[],"poll2":[],"statusAfterPolls":"closed","statusAfterSameShaReopenWebhook":"closed","knownStateAfterWebhook":"open"}

**B. 同 SHA 第二次 close 不再关闭群。**通过支持的 manual openPr() 重新激活后,旧 pr_closed@SHA key 使 handlePrClosed() 在更新群状态之前提前返回:

{"manualReactivationAction":"resumed","statusAfterManualReactivation":"active","secondCloseDeliveryPersisted":true,"statusAfterSecondClose":"active","knownStateAfterSecondClose":"closed"}

第二次 close 被确认并记录 delivery,但 knownPrs.state=closed 与 prGroups.status=active 永久不一致。

**建议:**显式实现 reopen 状态转换,并按新的生命周期 generation 去重;即使抑制重复通知,也必须先幂等落实当前 closed 状态。

P2 — 未完成首审校验/置顶也会标记 active,之后无法正常续跑

位置:src/host/bridge.ts:1004-1088、src/host/bridge.ts:1112-1120、src/engine/watcher.ts:387-395、src/engine/watcher.ts:1065-1080。

  • create 返回 kickoffMessageId,readback 返回临时 500:仍调用置顶并标记 active,观测为 {"status":"active","kickoffVerified":null,"topNoticeSet":true,"topNoticeCalls":1}。这与“先读回校验、再置顶/active”的承诺不符。
  • readback 成功但首次置顶 500:再次调用公开 openPr() 返回 already_active,createCalls=1、topNoticeCalls=1、持久化 topNoticeSet=false,没有重试入口。

**建议:**未验证 kickoff 不得置顶或进入 active;active 的提前返回应以所有必需步骤完成为前提,manual open/resume 必须续跑未完成的校验和置顶。

P2 — active→dormant 热切换后,旧 poll 仍会发起新的外呼

位置:src/engine/watcher.ts:186-211、src/engine/watcher.ts:635-668、src/github/client.ts:457-470。

让 page 1 阻塞,reload 为零 enabled rules,观测到 mode=dormant 后释放 page 1;旧闭包继续请求 page 2:

{"modeAfterReload":"dormant","page1BeforeReload":1,"page2AfterReload":1,"page2ObservedMode":"dormant"}

初始默认 dormant 与从未启用时的 reload 均为严格零 GitHub/daemon/Lark/CLI 调用;问题发生在 active→dormant 的在途窗口。

**建议:**reload 引入 generation/AbortSignal,旧 generation 不得再发起分页、处理结果或执行建群/通知。

P2 — webhook admission 同时存在“无界积压”和“满载假 202”

位置:src/engine/webhook.ts:161-203、src/engine/queue.ts:56-80、src/engine/watcher.ts:292-311、src/service/runner.ts:291-309。

maxEntries 只约束 committed entries;in-flight 不过期也不限量。per-PR pending 上限无法约束不同 PR key。真实类探针观测:

configuredMaxEntries=8, inFlightAfter5000WithoutCommit=5000
maxPendingPerKey=1, uniquePrKeys=5000, active=4, globallyPending=4996

另一方面,per-key queue 已满时 queue.enqueue() 返回 rejected promise,但 enqueueWebhookPrEvent() 仍同步返回 true,HTTP 层因此回 202。真实服务 + 有效签名 delivery 的观测为:

{"httpStatus":202,"responseJson":{"accepted":true},"queueBefore":{"active":1,"pending":32},"webhookProcessCalls":0,"deliveryPersisted":false,"queueFullErrors":1}

该 delivery 从未进入处理却被成功确认,GitHub 不会因这个响应重试。接收端先回 202,因此持续的有效签名 delivery 也可以一直积压;卡住的任务还会让同 delivery 在 TTL 后仍永久返回 duplicate。未认证请求不能填充这些结构,但合法 GitHub 事件流/持有 secret 的来源可以触发资源耗尽或事件丢失。

**建议:**增加全局 pending/in-flight 上限;同步识别 enqueue 失败并返回可重试的 429/503,而不是 202;为 in-flight 增加取消/超时语义。

P2 — reload 失败仍返回成功,已更新的 hash 阻止自动重试

位置:src/service/runner.ts:140-160、src/service/runner.ts:353-361、src/service/runner.ts:474-478。

config 与 lastConfigHash 在 await watcher.reloadConfig() 成功前就更新,异常只写日志;HTTP 仍回 200 {ok:true}。让真实 watcher 的 reload 方法抛一次可控临时错误,恢复方法并经过多个文件 hash poll 周期后:

{"httpStatus":200,"responseJson":{"ok":true},"reloadCallsBeforeRecovery":1,"reloadCallsAfterRecovery":1,"watcherPollInterval":60,"diskPollInterval":61,"reloadErrors":1}

未变化的文件不会再自动 reload;显式再次 /api/reload 可以重试,但自动恢复已失效。

**建议:**只在 watcher reload 完整成功后提交新 hash/config;失败返回非 2xx 或 {ok:false},并保留下一轮自动重试与可用的旧运行状态。

P2 — github:test-auth --repo 在仓库不可访问时仍返回成功

位置:src/github/client.ts:625-654、src/cli/index.ts:507-517。

/user 返回 200、GET /repos/acme/core 返回 403 时,显式请求的 repo 检查已失败,但 top-level ok 仍由 /user 成功决定,JSON CLI 只看这个字段退出:

{"cliExitCode":0,"topLevelOk":true,"identity":"@octo-tester","repoAccess":{"repo":"acme/core","ok":false,"error":"...403..."}}

这会让自动化把失败的权限检查当成功。显式提供 --repo 时,应将 repoAccess.ok 纳入顶层结果和 CLI exit code。

P2 — 合法长 repo 名突破群名 100 code-point 上限

位置:src/config/schema.ts:30、src/security/sanitize.ts:356-374。

截断逻辑始终保留完整 [owner/repo#N] marker;marker 自身超过 100 时,remaining=0 仍原样返回超长 prefix。使用 GitHub 合法上限的 39 字 owner + 100 字 repository、PR #123456789:

{"ownerLength":39,"repositoryLength":100,"repoAccepted":true,"renderedCodePoints":152}

这里直接证明函数违反自身 <=100 不变量;未调用真实 Feishu/Lark 来声称线上错误码。应使用有界且仍可查重的唯一 prefix,并为最长 owner/repo/PR 号增加回归测试。

P3 — 安全写文件会穿越非直接祖先 symlink

位置:src/security/fs.ts:58-81、src/security/fs.ts:235-264。

只检查 immediate parent;将更高层 alias 指到另一目录后,alias/one/two/secret.json 会实际写入被指向目录:

{"directSymlinkRejected":true,"nonImmediateAncestorSymlinkRejected":false,"writeTraversedAncestorSymlink":true,"redirectedFileMode":"600"}

这里只证明路径穿越和意外落点,文件仍为 0600,未据此声称跨 UID 泄密。建议逐级校验可信根以下的祖先,或使用 dirfd/openat2 一类相对安全目录句柄的写法。

P3 — README 将有效的核心仓库链接改成了不可解析地址

位置:README.md:3、README.md:155。

PR 前链接为可访问的 https://github.com/deepcoldy/botmux;PR 改为 https://github.com/botmux-ai/botmux。实测 gh repo view deepcoldy/botmux 成功,gh repo view botmux-ai/botmux 返回 repository resolve 错误。建议恢复原链接或改成实际公开地址。

已实际通过的检查

  • npm run typecheck:通过。
  • npm run build && npm run validate:通过。
  • npm run test:unit:26/26;npm run test:integration:8/8;集成套件额外连续重复 5 轮均通过。
  • 首跑历史 baseline 不建群、正常新开 PR、baseline Draft→Ready、同进程 webhook+poll 只建一个群、正常 new-commit/close 流程均通过现有测试与补充探针。
  • 指定 head 的 GitHub Actions test 成功。
  • npm dry-run tarball:12 个文件、165224 bytes;无 runtime dependencies、无符号链接、无 .node addon,Node bundle 的外部导入仅为 node:*。
  • 从隔离复制的纯 dist/ 直接启动真实 service/runner.js:Node 24 与 Bun 1.4.4 均以 dormant 启动、健康检查 200、控制 token 0600、SIGTERM 正常退出。
  • 原始字节 HMAC(重序列化签名拒绝、1-byte mutation 拒绝)、1 MiB exact-cap/overflow、anti-CSRF/Host、SSRF/redirect、CONNECT TLS、XML/<at>/@all/控制字符清洗及 execFile(shell:false) argv 防护的对抗探针通过。
  • 文件 diff 与构建产物未检出真实 token、内部域名、真实员工姓名、内部群/用户 ID 或本机路径;命中的凭据均为测试占位值。

请先用回归用例固定上述异常时序,再重新评估合并。

- [P1 #1] Defer webhook knownPrs commits until after action succeeds; refuse committing knownPrs on synchronize when it would mask undiscovered PRs, draft->ready, closed->open, or incomplete groups, and invalidate repo ETag for poll recovery
- [P1 #2] Add cross-process per-PR exclusive lockfile around HostBridge group orchestration, persist createAttempt.outcomeUnknown so dropped IPC responses fail closed rather than switching to CLI fallback, and gate CLI/settings in-process fallback strictly on ECONNREFUSED/unreachable (never ECONNRESET on POST mutations)
- [P2 #3] Align dist/webhooks/index.json with deepcoldy/botmux#3830 (mount-relative path "/events" -> endpoint "/webhooks/github", maxBodyBytes 1048576) and enforce isolated BOTMUX_PLUGIN_WEBHOOK_TOKEN Bearer auth
- [P2 #4] Prevent ETag advancement on single-PR close lookup failures, validate multi-page (>100 PR) repositories across all pages with per-page ETags and legacy cold-restart page-count inference, and invalidate repo ETag on webhook/openPr mutations
- [P2 #5] Implement explicit reopen lifecycle transitions with lifecycleGeneration-scoped dedup keys and idempotent closed state landing across poll and webhook paths (including onPrClosed=false and creating groups)
- [P2 #6] Keep PR groups in creating state until kickoff readback verification, top-notice pinning, and optional share-link posting complete, allowing poll and manual openPr to resume only unfinished steps
- [P2 #7] Add generation counter + AbortSignal propagation across active->dormant hot-reloads and per-PR handlers so stale polls/webhooks immediately halt without further pagination or state writes
- [P2 #8] Bound DeliveryDedupCache in-flight count/TTL and PerPrSerialQueue global pending cap with cancellable per-task timeouts, synchronously returning retryable HTTP 429/503 instead of fake 202
- [P2 #9] Pre-validate candidate clients in reloadConfig before mutating state/timers, commit config/hash in runner.ts only after reload succeeds, return HTTP 500 ok:false on error, and preserve auto-retry
- [P2 #10] Fold --repo access verification and slug validation into testAuth top-level ok and CLI exit code
- [P2 #11] Enforce <=100 code-point bounded canonical group name prefixes for max-length owner/repo names while preserving anchored GET /api/groups deduplication
- [P3 #12] Reject non-immediate ancestor symlinks below trusted OS roots in src/security/fs.ts (and recover empty/truncated lockfiles via staleMs), and restore deepcoldy/botmux links in README.md

Co-Authored-By: Claude Code <[email protected]>
@deepcoldy

Copy link
Copy Markdown
Contributor Author

第二轮独立复审结论:不可合(head 17133fe7ec17b24cd0aa0ab1d5bc06409df7871c)

该 head 是 55cb5a1 的 fast-forward,CI 为绿;本地 typecheck、build/validate、26 个单测和 18 个集成测试均通过。上一轮探针已按新返回值/generation 去重键适配,并保留原故障时序逐项复跑。结论是:**多数旧问题已真实修复,但建群未知结果只部分闭合,且仍有下列可复现阻断项。**新增问题中会注明“修复增量引入”与“旧 head 已存在、由本轮扩大覆盖发现”,不混为一谈。

上一轮问题闭环情况

上一轮场景 结论 本轮独立复验证据
Webhook 游标提前提交 已闭合 pre-lock 失败后不再写 knownPrs;下一次 poll 真实创建记录并持久化 chatId/kickoffMessageId。未知 PR 的 synchronize 后也能进入建群,不再被 poll 跳过。
建群互斥与 unknown outcome 部分闭合 普通双实例并发现在 listCalls=1, createCalls=1,两个调用返回同一 chatId;daemon 离线恢复时 cliCalls=0。但“旧 create 仍在执行、GET 暂时看不到群”的变体仍会双建,见新 P1-1。
#3830 webhook 契约 已闭合 实际 dist 经 #3830 真实 parser/matcher 得到 /events → /webhooks/github;缺/错 Bearer=401,正确 Bearer=200,webhook token 访问 /api/status=401;现行无 host token 的 Phase 1 ping=200,当前 scanner 对实际 dist 扫描通过。
单 PR 关闭失败与跨页 ETag 已闭合 500 后 lastPollStatus=error,第二次仍重新查询(singlePrLookupCalls=2),不再 304 跳过;101 PR 场景中第二次实际读取 page 2,并发送 notify_pr_closed、持久化 pr_closed:g1、群转 closed。
Reopen / 同 SHA 第二次 close 已闭合 poll reopen 返回 resume_group 并转 active;manual reactivate 后第二次 close 实际发送通知,最终 prGroups.status=closed 且 knownPrs.state=closed。
未验证 kickoff / 置顶失败后的 active 已闭合 readback 500 现在抛错,status=creating, kickoffVerified=false, topNoticeCalls=0;首次置顶失败返回 error,第二次 openPr() 为 resumed,topNoticeCalls=2,最终 active 且 topNoticeSet=true。
Active→dormant 在途外呼 原场景已闭合 同一 page-1 阻塞探针现在 page2AfterReload=0,初始 dormant 仍为零外呼。active→active 的新丢失窗口见新 P2-7。
Queue 无界与 fake 202 已闭合 per-key 满载现在返回 429 {ok:false,error:"pr_queue_full"};全局 pending 配置 64 时 5000 个 key 仅积压 64;in-flight 到上限返回 overloaded,过期后可重新 acquire。
Reload 假成功与不重试 已闭合 失败返回 500 {ok:false};恢复后自动 poll 从 1 次增至 2 次,watcher/disk 配置均为 61。
test-auth --repo 假成功 已闭合 /user=200、repo=403 时真实 CLI handler 返回 exitCode=1, topLevelOk=false, repoAccess.ok=false。
长 repo 群名超限 已闭合 39 字 owner + 100 字 repo 的同一输入现在生成 84 code points;另一组 100+100 输入也为 84,均不超过 100。
祖先 symlink 与 README 链接 已闭合 同一 ancestor-symlink 探针现在 nonImmediateAncestorSymlinkRejected=true, writeTraversedAncestorSymlink=false;两处 README 均恢复可访问的 deepcoldy/botmux。

新增 P1 阻断

P1-1 — 旧 create 仍在执行时,空 GET 会清除 unknown outcome 并再次建群

位置:src/host/bridge.ts:892-981。

这是对上一轮 unknown-outcome 修复的对抗变体:第一次 IPC POST 已被 daemon 接受,但响应断开,真实核心不会在客户端断开时取消创建。若群在 700 ms 后才出现在 GET 列表,第二次调用会把暂时为空的列表当成“未创建”的证据,清除 createAttempt 并再次 POST。持久化的 idempotencyKey 没有发送给核心,当前核心也没有按它去重。

真实 HostBridge + StateStore + 延迟可见本地 daemon 的复跑结果:

{"createCalls":2,"createdChatIds":["oc_delayed_1","oc_delayed_2"],"errors":["socket hang up","socket hang up"]}

因此上一轮 P1 不能完全判定关闭。需要核心的幂等 create/attempt-status 协议,或在原操作仍可能执行时保持 fail closed;空快照不足以证明安全。

P1-2 — --dry-run=true 反而关闭 dry-run,可发起真实 mutation

位置:src/cli/index.ts:44,313,333,397,428。该问题在旧 head 已存在,由本轮扩大覆盖发现。

通用 --name=value 解析把值保存为字符串 "true",而 sync/open-pr 只认 boolean true。真实 CLI 对本地 control-service 的观测:

[
  {"command":"sync --dry-run=true","body":{"dryRun":false,"async":false}},
  {"command":"sync --dry-run","body":{"dryRun":true,"async":false}},
  {"command":"open-pr acme/reg#12 --dry-run=true","body":{"prNumber":12,"dryRun":false}}
]

用户明确写了 dry-run 却可能真实 sync/建群。应显式解析布尔值,或拒绝 --dry-run=<value>,不能静默降级为真实执行。

P1-3 — 达到小时建群上限的 PR 永久不再重试

位置:src/engine/watcher.ts:765-770,1342-1369。旧 head 已存在。

cap=1、同时出现 PR1/PR2 时,PR1 建群,PR2 返回 skip_rate_limited;代码仍提交 PR2 游标与 ETag。假时钟前进一小时后:

{"afterHourConditional":[{"action":"skip_not_modified","reason":"etag_304"}],"afterHourForcedActions":[],"createdGroups":[1]}

即使强制全量 fetch,PR2 也因已是 known cursor 而没有动作。cap-skip 必须保留 pending 状态,不能按成功处理推进游标/ETag。

P1-4 — 现有配置有一项无效时,保存无关设置会清空凭据和全部规则

位置:src/server/settings.ts:273-275,431-435。旧 head 已存在。

真实 saveSettings 探针在原配置含 PAT + 一条 enabled rule、仅 service.port=0 无效时,保存 poll interval 补丁仍返回 ok:true,并从 defaults 写回:

{"before":{"hasPat":true,"repoCount":1},"after":{"hasPat":false,"repoCount":0,"pollIntervalSec":120}}

已有配置解析/校验失败必须 fail closed;只有文件确实不存在才能使用默认配置,不能用默认值覆盖损坏配置。

P1-5 — Dashboard 保存无关设置会丢失只存在于 proxy.url userinfo 的凭据

位置:src/config/schema.ts:553-599。旧 head 已存在。

原配置 http://alice:[email protected]:8080 经 Dashboard 回传为去凭据 URL、空 username、password omitted 时,真实保存结果为:

{"before":{"hasProxyAuth":true},"saved":{"proxy":{"url":"http://proxy.example:8080"},"hasProxyAuth":false}}

unrelated save 后代理认证被静默移除。应在应用 redacted patch 前迁移/保留当前 URL userinfo,除非用户明确清除或更改代理目标。

新增 P2 阻断

P2-1 — 损坏的 state.json 被当作空状态并覆盖

位置:src/state/store.ts:152-182。旧 head 已存在。

写入 group oc_original 和 dedup 记录后破坏 JSON,再 load()/update(),实测:

{"loadAfterCorruption":{"groupCount":0,"dedupCount":0},"persistedAfterUpdate":{"chatId":"oc_replacement","originalChatStillKnown":false,"dedupCount":0}}

该行为会销毁用于防重映射与事件去重的最后一份状态。应在解析失败时 fail closed 或隔离原文件,只有 ENOENT 才返回空状态。

P2-2 — manual sync 等待旧 poll 后,仍使用禁用前的 stale rule 建群

位置:src/engine/watcher.ts:999-1011,1402-1425。旧 head 已存在;新 generation guard 未覆盖该入口。

旧 poll 阻塞时启动 manual sync,再禁用仓库并 reload。实测 reload 后 mode=dormant, enabled=false,旧 poll 无动作,但等待中的 manual sync 仍在新 generation 下发起第三次列表请求并返回:

{"mode":"dormant","actions":[{"prNumber":9,"action":"create_group","chatId":"oc_fake_9"}]}

等待后及多 repo 每项执行前都应重新解析当前 rule/enabled,而不是复用等待前快照。

P2-3 — 分享链接幂等只检查前 100 条 issue comments

位置:src/github/client.ts:632-658、src/host/bridge.ts:748-755。旧 head 已存在。

将既有 marker 放在 comment 101/page 2,连续两次恢复调用真实 GitHubClient + HostBridge:

{"getPages":[1,1],"duplicatePosts":2}

page 2 从未读取,两次 POST 都带同一 marker。需跟随分页直到找到 marker/遍历完毕,或持久化并核验 comment ID。

P2-4 — Dashboard 将 owner/repo#12junk 当作 PR12 执行非 dry-run 打开

位置:src/dashboard/index.ts:764-782。旧 head 已存在。

使用真实 Dashboard 组件的 stateful hook harness,输入 malformed spec 并点击真实 Open Review Group 控件,捕获到:

{"path":"/api/open-pr","method":"POST","body":{"repo":"owner/repo","prNumber":12,"dryRun":false}}

应像 CLI 一样要求完整 /^\d+$/,不能 parseInt 接受数字前缀。

P2-5 — 新增 per-PR lock 会在 live owner 仍执行时因年龄过期

位置:src/host/bridge.ts:775-788、src/security/fs.ts:444-456。由本次修复增量引入。

锁使用 staleMs=90s,底层 dead || ageMs > staleMs 即使 PID 存活也删除锁。真实文件锁探针得到 firstPidAlive=true, secondAcquiredWhileFirstHeld=true;进一步用真实 HostBridge 将首个调用阻塞在消息扫描、假时钟前进 90.1 秒:

{"createCalls":1,"listCalls":2,"secondCompletedWhileFirstBlocked":true,"firstChatId":"oc_live_lock","secondChatId":"oc_live_lock"}

第二个调用在第一个仍处于“互斥区”时完成全部剩余步骤,可能并发执行置顶、分享链接和状态更新。live-PID 锁不应只因年龄过期;需要 liveness + heartbeat/lease renewal 或 fencing。

P2-6 — 明确的 CLI 预创建失败会永久阻止后续 CLI 重试

位置:src/host/bridge.ts:725-729,900-910,1065-1075。由本次修复增量引入。

第一次 fake CLI 明确返回“working-dir 无效、chat.create 未调用”且无 chatId;第二次配置为可成功。实际却发生:

{"cliCalls":1,"errors":["...working-dir path does not exist; chat.create not called","Prior cli group creation attempt ... unknown outcome ... refusing ... retry create"]}

createAttempt.outcomeUnknown 在 CLI 调用前写入,确定性的预创建错误没有清除它。fail-closed 的方向合理,但需要核心 CLI 提供结构化 definitelyNotCreated 结果,仅对这类结果清除 marker;不能把所有 nonzero/no-chat 都贸然视为未创建。

P2-7 — Active→active reload 会静默丢弃已经 202 接收的 queued webhook

位置:src/engine/watcher.ts:290-294,426-454、src/service/runner.ts:335-353。由本次修复增量引入。

将有效签名的 closed webhook 排在同 key blocker 后,HTTP 已回 202;仅把 poll interval 从 60 改为 61 并 reload。释放 blocker 后观测:

{"webhookStatus":202,"reloadOutcome":{"ok":true,"mode":"active"},"cursor":null,"persistedDelivery":null,"dedupInFlight":0,"webhookErrors":0,"queueAfter":{"active":0,"pending":0}}

generation 使 queued action 中止,rejection handler 又故意不记错误/恢复。若该过渡后来已不能由 poll 看到,就会永久丢失。reload 应只取消需要失效的工作;已接收队列项需迁移/重放或返回可重试响应,不能先 202 再无声丢弃。

新增 P3

恰好整百 PR 的仓库会持续请求空终止页

位置:src/github/client.ts:521-596。

100 个 PR、page 1 无 rel=next、page 2 为空的稳定仓库,三次 poll 观测 page1Calls=3, page2Calls=3,后两次即使 notModified=true 仍请求 page 2,且 pageCount 永远为 2。未观测事件丢失,但这是持续额外请求和限流暴露。空终止页不应计入持久化 pageCount。

构建、运行时与卫生

  • npm run typecheck:通过。
  • npm run build && npm run validate:通过。
  • npm run test:unit:26/26;npm run test:integration:18/18。
  • 指定 head 的 GitHub Actions test 成功。
  • 现行 core 环境服务 smoke:health 200、未鉴权 401、control token/HMAC 200、reload 200、正常关闭。
  • 纯 dist runner 在 Node 24 与 Bun 1.4.4 均正常 dormant 启动、健康检查、0600 token 和退出。
  • npm dry-run:12 个文件、185965 bytes;无 runtime dependencies、无 symlink、无 .node addon。
  • 文件 diff 与 dist 未检出真实 token、内部域名、真实员工姓名、内部群/用户 ID 或本机路径;命中凭据均为测试占位值。

请优先修复 P1-1 的幂等创建协议、dry-run 和配置/状态数据保护,再为上述新增时序补独立回归测试。当前测试全绿仍不足以判定可合。

- [P1-1] Keep createAttempt.outcomeUnknown fail-closed across empty GET /api/groups responses until unknownOutcomeSettleMs elapses (while immediately adopting delayed chats once visible), fail closed on malformed GET /api/groups or invalid/future startedAt, and forward idempotencyKey on create
- [P1-2] Explicitly parse boolean CLI flags (--dry-run=true/false/1/0, --json) and reject invalid boolean values, unknown flags, and unexpected positional arguments with exit code 1
- [P1-3] Defer knownPrs cursor and ETag advancement whenever a PR hits skip_rate_limited (hourly creation cap on poll or opened/ready_for_review/reopened webhook) so deferred PRs automatically retry after cap expiry
- [P1-4] Fail closed in loadExistingConfigStrict() and normalizeAndValidateConfig() on corrupt, non-object, wrong-typed, or symlinked config.json instead of overwriting PATs and rules with defaults
- [P1-5] Preserve and migrate credentials stored only in proxy.url userinfo across redacted Dashboard saves while allowing explicit clearPassword, password rotation, and username edits
- [P2-1] Fail closed with StateCorruptError on corrupt or wrong-typed state.json (returning empty state only on ENOENT) without overwriting the original file
- [P2-2] Re-resolve live rule/enabled after waiting on in-flight polls (using a while loop) and before each repo in sync()
- [P2-3] Paginate all issue comment pages with early-stop marker matching and persisted shareLinkCommentId verification for postShareLinkToPr idempotency
- [P2-4] Validate PR numbers with strict /^\d+$/ + Number.isSafeInteger and valid owner/repo slugs across Dashboard, CLI parsePrSpec, watcher.openPr, and runner /api/open-pr
- [P2-5] Prevent live-PID per-PR locks from expiring by wall-clock age alone; keep the exclusive FileHandle open for inode-verified in-place utimes() lease renewal serialized with release() plus pre-create fencing
- [P2-6] Clear createAttempt.outcomeUnknown only for deterministic pre-create CLI validation failures (structured chatCreated:false/definitelyNotCreated, ENOENT/EACCES, or anchored pre-create errors with zero chatId in stdout/stderr and non-killed exit), keeping ambiguous CLI failures fail-closed
- [P2-7] Preserve already-202-accepted queued webhooks across active->active reloads using live repo rules while still aborting cleanly on active->dormant or repo disable
- [P3] Do not count empty terminal pages in persisted pageCount and accurately mark per-page hasNonEmptyNextPage so exact-100/200-PR repos stop polling empty trailing pages

Co-Authored-By: Claude Code <[email protected]>
@deepcoldy

Copy link
Copy Markdown
Contributor Author

第三轮独立复审结论:不可合(head 23a4ccb2d6b2300b8cb3155d1134390bb5fc8d51)

该 head 是 17133fe 的 fast-forward,CI 为绿;本地 26 个单测 + 30 个集成测试(56/56)全部通过。第二轮的 13 个故障序列已在全新 scratch 中逐项复跑,结果为 9 项完全闭合、3 项部分闭合、1 项未闭合;增量对抗另发现 capped pagination 与 disable/re-enable 两项新回归。master ea051dc634 的 #3830 真实 parser/matcher、Bearer 隔离、Phase 1、构建、双运行时和开源卫生均通过。仍有以下可复现阻断项。

已验证闭合的场景

  • P1-1 延迟可见的 unknown create:第二次调用保持 fail-closed,createCalls=1;延迟群出现后第三次采用同一 oc_delayed_1,最终 active,且 create body 已转发 idempotency key。
  • P1-2 dry-run:sync/open-pr --dry-run=true 均发送 dryRun:true。
  • P1-3 小时 cap:PR2 被 cap 时只有 PR1 在 knownPrs,未推进新 ETag;一小时后 PR2 自动 create_group。
  • P1-5 代理凭据:保存后迁移为独立 username/password,hasProxyAuth=true。
  • P2-2 stale rule sync:禁用后 manual sync 返回空 actions、created=[],不再发第三次列表请求。
  • P2-3 评论分页:两次恢复均读取 page 1、2,重复 POST=0,并返回既有 commentId=101。
  • P2-4 Dashboard PR 校验:owner/repo#12junk 不再产生 /api/open-pr 调用。
  • P2-7 active→active reload:已 202 接收的 queued closed webhook 最终写入 closed cursor 和 processedDelivery,queue 正常清空。
  • P3 空终止页:exact-100 场景三次 poll 的计数为 page1Calls=3,page2Calls=1,后续 pageCount=1。

部分闭合 / 未闭合项

P1 — 错误类型的 repository 字段仍会被成功保存并覆盖,而不是 fail closed

位置:src/config/schema.ts:95-122,145、src/server/settings.ts:494-499。

上一轮“无效 service.port=0”现已正确返回 {ok:false} 且不调用 replace;但严格加载仍委托给有损 normalizer。现有 repo rule 含 enabled:"true"、memberBotAppIds:"cli_reviewer2"、triggerOn:"opened" 时,真实 saveSettings() 保存无关 poll interval 的实测结果:

{"ok":true,"replaceCalls":1,"enabled":false,"memberBotAppIds":[],"triggerOn":["opened","ready_for_review"],"pollIntervalSec":90}

这仍会在不报错的情况下改写现有配置。应在 normalization 前逐项校验所有已存在字段的类型,尤其是 repo rules 的 boolean/array/enum 字段,不能以“转换成默认值”代替 wrong-type fail-closed。

P2 — 真实核心 CLI 的确定性预创建错误仍不会清除 unknown outcome

位置:src/host/bridge.ts:145-148,999-1010;对照 master ea051dc634 的 src/cli.ts:18887-18890。

分类器识别的是合成的 working-dir path does not exist; chat.create not called,但真实核心输出由 --working-dir 前缀加 validateWorkingDir() 错误组成,例如:

--working-dir Directory does not exist: /definitely-absent

把这一精确输出送入真实 HostBridge/StateStore,第一次失败后即使前进超过 settle window,第二次仍不调用 CLI:

{"cliCalls":1,"firstError":"...--working-dir Directory does not exist...","secondError":"Prior cli group creation attempt ... unknown outcome ... refusing ... retry create","secondAttempt":{"path":"cli","outcomeUnknown":true}}

daemon 离线时该分支无法通过 settle window 自愈。建议由核心 CLI 为早期校验失败输出结构化 chatCreated:false/definitelyNotCreated,或让分类器覆盖真实、锚定的核心错误格式;回归夹具应使用生产错误文本,而不是自造匹配字符串。

P2 — dedup map 中的非字符串值仍被擦除并持久化

位置:src/state/store.ts:85-95,121-129,215-229。

malformed JSON 现在会正确抛 StateCorruptError 并保留原始字节;但合法 JSON object 内的 wrong-typed entries 仍被静默丢弃。向 processedEvents/processedDeliveries 写入数值后,真实 store 探针得到:

{"loadedEvents":{},"persistedEvents":{},"persistedDeliveries":{}}

load() 未报错,下一次 update 永久覆盖原条目,可能重新触发重复事件/delivery。凡 map 中已存在但值不是 string 的条目都应在写前抛 StateCorruptError。

P2 — PID 复用会让孤儿锁在无关 live PID 存在期间无法恢复

位置:src/security/fs.ts:314-319,536-555。

live-PID 锁不再仅因年龄过期,解决了上一轮场景;但 payload 没有进程启动/boot 身份,只要 PID 被无关进程复用,十分钟前的孤儿锁也无法取得。真实探针用无关 live child PID 构造旧锁:

{"lockAgeMs":600190,"result":{"name":"SecurityFsError","code":"LOCK_TIMEOUT"}}

同一无关进程退出后,锁立即可以取得。重启/PID 复用下可能长期阻塞 state/config/per-PR 操作。需记录并校验 process-start/boot identity,不能把“该 PID 当前活着”等同于“原锁主仍活着”。

P1 — 达到 maxPages 的分页被缓存为 terminal,后续把截断扫描误判为完整扫描

位置:src/github/client.ts:582-603,消费该错误标志的 src/engine/watcher.ts:1435-1445。

末页 cache-marking 没有区分“确认无下一页”与“因 maxPages 停止”。真实 client/local server 以 300 个 open PR、maxPages=2 复现:

{"first":{"pulls":200,"pageCount":2,"truncated":true},"second":{"pulls":200,"pageCount":2,"truncated":false,"notModified":false}}

第二轮只改变 page 1,page 2 合法返回 304 且不携带 Link;page 3 未请求,但 truncated 从 true 变 false。watcher 随后在 !listRes.truncated 分支把未见的 open cursor 标为 closed,可能错误关闭后续 PR 状态。必须分别保存 capped traversal 与 verified terminal/no-next,并在后续 cached poll 中保留 truncation;exact-100 用例覆盖不了这个转换。

P2 — disable→re-enable 会让禁用前已接收的 queued webhook 重新执行

位置:src/engine/watcher.ts:173-177,444-455。

active→active 保留 queued webhook 的修复只检查当前 enablement,没有 per-repo lifecycle epoch。真实 watcher/store 中先排入 closed webhook,再 active→dormant→active,最后释放 queue:

{"accepted":true,"closeMessages":1,"finalGroupStatus":"closed","finalCursorState":"closed","deliveryCommitted":true}

这会在新的生命周期中执行禁用前动作,违背 disable/dormant abort queued work 的语义。应让 repo epoch 在 disable/removal 时变化、active→active 时保持稳定,不能只比较当前 enabled 布尔值。

协议、构建与卫生验证

  • npm run typecheck:通过。
  • npm run build && npm run validate:通过。
  • npm run test:unit:26/26;npm run test:integration:30/30;指定 head CI 成功。
  • 使用 master ea051dc634 的真实 parsePluginWebhooksContribution、parseRawPluginWebhookRequest、matchPluginWebhookRoute 读取实际 dist:/events 正确映射 /webhooks/github,maxBodyBytes=1048576。
  • Bearer:缺失/错误=401,正确=200,webhook token 访问控制 API=401;现行无 host token 的 Phase 1 ping=200。
  • Phase 1 当前核心服务 smoke:health 200、未鉴权 401、control token/HMAC 200、reload 200、正常关闭。
  • 纯 dist runner 在 Node 24 与 Bun 1.4.4 均正常 dormant 启动、健康检查、0600 token 和退出。
  • npm dry-run:12 个文件、196010 bytes;无 runtime dependencies、无 symlink、无 .node addon。
  • 文件 diff 与 dist 未检出真实 token、内部域名、真实员工姓名、内部群/用户 ID 或本机路径;命中凭据均为测试占位值。

请先补齐真实 CLI 错误契约和 wrong-type fail-closed,并处理孤儿锁身份语义;当前 56/56 全绿仍未覆盖上述生产边界。

- [P1 #1] Strictly validate all existing config and incoming patch field types (especially repo rule boolean/array/enum/number fields, nested objects, null scalars, and secret patches) before normalization so wrong-typed configs/patches fail closed without overwriting stored settings
- [P1 #2] Distinguish maxPages-capped pagination ('unknown_capped') from verified terminal pages ('verified_terminal') using explicit 1-based page numbers, separate skipCacheWrite (dryRun only) from bypassEtag, sync persistedEtag/previousTruncated, and handle single-page 304 Link transitions so 304 never flips truncated true->false
- [P2 #3] Align CLI pre-create error classifier with real Botmux core production stderr formats (EN & ZH --working-dir, --bot, --chat-mode, --kickoff-bot 与/未匹配到/匹配到多个, and assertTurnTransportOrExit) and test against real production strings
- [P2 #4] Fail closed with StateCorruptError on non-string values inside processedEvents/processedDeliveries as well as invalid schemaVersion, repos/prGroups entries, and wrong-typed service.* fields
- [P2 #5] Record and verify durable process-start + Linux boot_id identity (including PID 1 in containers, zombie/dead state detection, and transient probe safety) in lockfile payloads so PID-reused orphan locks are reclaimed while genuine live owners remain protected
- [P2 #6] Add per-repo lifecycle epochs incremented on disable/removal/re-enable (and preserved across active->active reloads and rolled back on reload failure) to prevent pre-disable queued webhooks from running after disable -> re-enable

Co-Authored-By: Claude Code <[email protected]>
@deepcoldy

Copy link
Copy Markdown
Contributor Author

第四轮独立复审结论:不可合(head d886903ceb7c679b7c5c07ce6affb09bf3fa0102)

该 head 是 23a4ccb 的 fast-forward,exact commit 的 GitHub Actions test 成功。第三轮的 6 项边界问题已用原故障探针逐项复跑并全部闭合;但增量交叉检查发现 1 个新的 P1 分页回归,当前不能进入合并与灰度。

六项复验结果

上一轮问题 独立复验结果
P1:repo 字段 wrong-type fail-closed 原配置含 enabled:"true"、memberBotAppIds:"cli_reviewer2"、triggerOn:"opened" 时,真实 saveSettings() 现在返回 {ok:false}、replaceCalls=0,三个原始字段和 pollIntervalSec=60 均保持不变,不再规范化覆盖。
P1:maxPages 截断分页 300 个 open PR、maxPages=2,首轮为 truncated:true;第二轮 page 2 返回 304 且无 Link 后仍为 truncated:true、pulls=200,不再翻转成完整扫描。
P2:真实核心 CLI 预创建错误 将生产格式 --working-dir Directory does not exist: ... 送入真实 HostBridge,第一次错误被识别为确定性预创建失败;第二次实际执行 CLI(cliCalls=2),清除 createAttempt 并进入 active,不再永久锁死。
P2:dedup map 非字符串值 数值型 processedEvents/processedDeliveries 现在使 load 和 update 均抛 StateCorruptError,原始文件字节完全不变,不再擦除后持久化。
P2:PID 复用与 live owner 用无关 live child PID 构造十分钟前孤儿锁,现在在 500ms 内成功回收;对照真实 live owner 时第二把锁仍失败、nonce 不变,owner release 后正常删除。50 轮 renewal/release/handoff 也通过。
P2:disable→re-enable 重放 原 queued closed webhook 场景现在 closeMessages=0、群保持 active、cursor 保持 open,旧 delivery 不提交;active→active 对照仍正常写入 closed cursor 和 processedDelivery。

相邻回归检查

  • 扩展分页模型通过:empty、exact-100、100→101、exact-200、200→199、exact-300、缩页、终止页删除与后续 304 均符合预期。
  • 锁的 inode fencing、 renewal/release、新 holder 保护通过;live owner 不会因 wall-clock age 被抢锁。
  • #3830 master ea051dc634 的真实 parser/matcher 继续将 /events 正确映射到 /webhooks/github;缺失/错误 Bearer=401,正确=200,webhook token 访问控制 API=401,Phase 1 无 host token 场景保持兼容。

新增 P1 — Page-1 304 的 terminal-Link 转换会吞掉旧后续页的关闭 reconcile

位置:src/github/client.ts:523-527,592-598;watcher 的提前返回位于 src/engine/watcher.ts:1199-1214。

此前非截断的两页仓库中,anyPageModified 只在 previously capped 时强制为 true。若 page 1 从缓存的 rel="next" 在 304 中转为明确 terminal Link,新 hasMore 会直接跳过 page 2,返回 notModified=true, pulls=[]。真实 GitHubClient + loopback fake 的场景:

  1. 首次:page 1 为 100 PR 且带 rel="next",page 2 有 PR101,pageCount=2, truncated=false。
  2. 第二次:page 1 返回相同 ETag 的 304,但 Link 改为 rel="first";旧 page 2 应为空。
  3. 实测:notModified=true, pulls=[], pageCount=1,且 page2Calls 停在首次的 1,没有再次检查/淘汰旧 page 2。
{"second":{"notModified":true,"pulls":[],"truncated":false,"pageCount":1},"page2Calls":1}

watcher 因 notModified 提前返回,旧 page 2 消失的 PR 不会被关闭或 reconcile;后续 page-1 304 可让状态持续卡住。此前版本的对应分支会重新验证 page 2,因此这是本次分页修复的增量回归。应把任何 cached has_next/unknown_capped → explicit-terminal 转换视为修改,返回可重建的 page-1 数据并处理/淘汰旧后续页,而不是直接 notModified 返回。

构建、打包与卫生

  • npm run typecheck:通过。
  • npm run build && npm run validate:通过。
  • npm run test:unit:26/26;npm run test:integration:36/36,合计 62/62。
  • 本轮 6 项 boundary 回归文件额外连续运行 5 轮,全部通过。
  • 纯 dist runner 在 Node 24 与 Bun 1.4.4 均正常 dormant 启动、健康检查 200、0600 token 和正常退出。
  • npm dry-run:12 个文件、205902 bytes;无 runtime dependencies、无 symlink、无 .node addon。
  • 文件 diff 与 dist 未检出真实 token、内部域名、真实员工姓名、内部群/用户 ID 或本机路径;命中的凭据均为测试占位值。
  • 两个受保护主目录与复审 worktree 均保持 clean;未合码、未发 npm、未部署。

本轮使用真实组件与本地假服务验证,没有执行真实 GitHub/飞书线上建群。六项上一轮问题虽已闭合,但上述 P1 会造成持久状态漏更新;请先修复并补充分页 Link-transition 回归测试,再评估合并与灰度。

…tion as modified and evict stale trailing pages

- Treat any cached has_next / unknown_capped / multi-page / trailing-cache -> explicit terminal Link transition on 304 (for both page 1 and page 2+) as anyPageModified=true so watcher reconciles and closes disappeared trailing-page PRs instead of returning notModified:true early
- Evict all stale cached pages beyond terminal pageCount on shrinks (2->1, 3->2, 3->1) so subsequent steady-state 304 polls cleanly return notModified:true without hitting dead pages
- Add end-to-end regressions covering 2->1 watcher close reconcile + steady-state 304, 3->2 via page-2 304 terminal Link, 3->1 via page-1 304 terminal Link, and maxPages=1 capped->terminal->steady-state 304

Co-Authored-By: Claude Code <[email protected]>
@deepcoldy

Copy link
Copy Markdown
Contributor Author

第五轮聚焦终核结论:可合(head 47255d2afc51ad376c65992ed3d5ed9d5f601aa0)

该 head 是 d886903 的 fast-forward,exact commit 的 GitHub Actions test 成功。上一轮唯一的 P1 分页回归已在客户端与 watcher 两层分别通过真实组件复验;相邻多页缩页、steady-state 304、构建、打包和开源卫生均未发现剩余阻断项。

P1 复验结果

客户端:304 terminal-Link 转换不再被误当成 no-op

使用上一轮真实 GitHubClient + loopback fake:

  1. 首次返回 100 个 page-1 PR、rel="next",page 2 有 PR101,pageCount=2,truncated=false。
  2. 第二次 page 1 返回相同 ETag 的 304,但 Link 变为明确的 rel="first"。
  3. 修复后第二次返回 notModified=false, pullCount=100,pageCount=1,truncated=false,不再以空 notModified 提前返回。
  4. 第三次稳态 304 返回 notModified=true,pageCount=1,旧 page 2 不再请求(总 page2Calls=1)。

Watcher:消失的 trailing-page PR 被真实关闭

使用真实 GitHubWatcher、GitHubClient、StateStore 和独立假 daemon 边界:

  • Poll 1 捕获 101 个 open PR。
  • Page-1 304 terminal-Link 后,Poll 2 实际发出 notify_pr_closed;PR101 的 prGroups.status 与 knownPrs.state 均为 closed,发送计数为 1。
  • Poll 3 恢复 skip_not_modified,page 2 仍只请求首次的 1 次。
{"poll2":[{"prNumber":101,"action":"notify_pr_closed"}],"counts":{"page1Calls":3,"page2Calls":1,"singlePrCalls":1,"closeMessages":1},"final":{"groupStatus":"closed","cursorState":"closed","pageCount":1}}

相邻边界

  • 扩展分页模型通过:empty、exact-100、100→101、exact-200、200→199、exact-300、缩页、终止页删除和后续 304。
  • Round-4 Link-transition 集成用例连续运行 5 轮均通过,覆盖 2→1 watcher reconcile、3→2、3→1、maxPages=1 capped→terminal 及 steady-state。
  • 未观察到请求空终止页、丢失 truncation 或稳态 304 再次访问已淘汰页面。

构建、打包与卫生

  • npm run typecheck:通过。
  • npm run build && npm run validate:通过。
  • npm run test:unit:26/26;npm run test:integration:38/38,合计 64/64。
  • 纯 dist runner 在 Node 24 与 Bun 1.4.4 均正常 dormant 启动、健康检查 200、0600 token 和正常退出。
  • npm dry-run:12 个文件、206820 bytes;无 runtime dependencies、无 symlink、无 .node addon。
  • 文件 diff 与 dist 未检出真实 token、内部域名、真实员工姓名、内部群/用户 ID 或本机路径;命中的凭据均为测试占位值。
  • 两个受保护主目录与复审 worktree 均保持 clean;未合码、未发 npm、未部署。

本轮未执行真实 GitHub/飞书线上建群。按当前 head 和上述聚焦覆盖范围,未发现剩余合并阻断项,可进入本机灰度试跑。

@deepcoldy
deepcoldy merged commit 268b7e9 into main Nov 26, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant