Skip to content

feat(kernel): 仲裁内核 v1(W1-C2 #165,ADR-0054) - #1

Merged
randypanding merged 2 commits into
mainfrom
w1c2-kernel
Aug 21, 2026
Merged

randypanding merged 2 commits into
mainfrom
w1c2-kernel

Conversation

@randypanding

Copy link
Copy Markdown
Contributor

动机

宪法 §1 的仲裁内核仓落地:写入类命令(/claim /release /retry)的确定性裁决——策略表 + 原子 CAS + TTL 租约 + 防重放台账。独立于 conductor/管家(被审计者不组装审计报告)。决策全文见 ADR-0054(agent-registry PR#69 已合并)。

变更清单

  • capabilities.yaml——策略表(唯一授权真源;受限子集解析器加载,零第三方依赖)
  • arbiter/policy.py——加载与判定:严格校验(未知键拒绝)、默认拒绝
  • arbiter/lease.py——租约模型(TTL/过期/holder/ref 命名,纯逻辑)
  • arbiter/kernel.py——adjudicate() 纯函数核心(零网络 import;时钟/状态注入)
  • arbiter/backend.py——CAS 后端:GitHubRefBackend(仅 api.github.com,urllib)+ LocalGitBackend(git CLI,测试)
  • arbiter/cli.py + scripts/adjudicate.sh——CLI 与 bash 包装(铸 App 令牌→CLI→透传退出码/JSON)
  • tests/——四类用例 + 静态扫描 + 误放行台账(初始空)
  • docs/FALSE-DECISIONS.md——误放行/误拒记账约定
  • .github/workflows/ci.yml——lint/test/static-scan/policy-validate + gate 严格聚合
  • README.md——角色、用法、安全模型

AC 映射(.github#165)

AC Given/When/Then 证据
AC-1 静态扫描无 LLM 调用;默认拒绝 tests/test_no_llm.py:(a) kernel/policy/lease/cli 不 import 网络模块(AST 断言);(b) backend.py URL 主机 ⊆ {api.github.com};(c) 全源码无 LLM 端点特征串。默认拒绝:test_policy.py::test_default_deny_unknown_command + CI policy-validate 的 default-deny=verified
AC-2 并发 /claim 同卡恰一胜者,败者明确回复 tests/test_concurrency.py::test_parallel_claim_single_winner(8 线程 + 裸仓 + git 子进程,恰 1 allow,败者 code=lost-race/lease-held)+ test_parallel_claim_after_expiry_single_taker(过期接管 CAS)
AC-3 同 delivery 重复投递→幂等 no-op,台账有记录 tests/test_replay.py:重复 delivery → verdict=noop/replay-detected 且状态零变化;seen ref 的 commit message 即台账(test_seen_ref_commit_is_auditable_ledger);edited 直接 deny(test_edited_event_denied_without_consuming_delivery)
AC-4 过期/holder 不符的 /release /retry → CAS 校验拒绝 tests/test_concurrency.py::TestAc4ReleaseGuard(not-holder / lease-expired 拒绝且不静默删 ref;owner 可强制;holder 可释放)
AC-5 CI 覆盖并发/重放/越权/过期全绿;台账落盘 本 PR ci.yml(unittest 69 例全绿);tests/false_decision_ledger.jsonl 落盘(初始空+格式注释),记账约定 docs/FALSE-DECISIONS.md

测试方法

  • 本地(Windows Git Bash):python -m unittest discover -s tests -v → 69 tests OK(并发用例连跑 5 遍无 flake)
  • bash -n scripts/adjudicate.sh ✓;python -m py_compile 全部 ✓
  • E2E 实测(--backend local 裸仓):claim→allow;并发败者→deny lease-held;非 holder release→deny not-holder;holder release→allow;重放→noop exit 0;edited→deny;seen/lease refs 落盘形态正确
  • MSYS 路径转换豁免(Git Bash 把 /claim 改写为 Windows 路径的已知问题,同 .github 仓 ghcb #159 修法)

安全模型要点

  • 退出码三分:0=allow/noop、1=deny、2=infra(API 失败≠拒绝≠放行,fail-closed 独立通道)
  • 每卡至多 1 个活跃租约:租约 ref 名按卡唯一(refs/leases/),createRef 422 结构性保证
  • 防重放:refs/seen/<sha1(delivery-id)> 原子幂等标记;只认 --event created
  • 纯 Python 3 标准库 + bash,零第三方依赖(不引入 PyYAML——受限子集解析器)

风险与回滚

风险:GitHub refs API 故障窗口 → infra 通道(exit 2),调用方重投;seen ref 数量随事件增长(v2 清扫)。回滚:整仓可拆(ADR-0054 §9)——停转介即回 W0 行为,无数据迁移。

Copilot AI lite review requested due to automatic review settings August 21, 2026 11:58
@coderabbitai

coderabbitai Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@randypanding, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 2 minutes

Limit details: You’ve used all 10 included reviews currently available.

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fb1ecd0b-b6e2-43c2-8842-00c075e6a523

📥 Commits

Reviewing files that changed from the base of the PR and between 7b1a652 and 36d9ff3.

📒 Files selected for processing (19)
  • .github/workflows/ci.yml
  • .gitignore
  • README.md
  • arbiter/__init__.py
  • arbiter/backend.py
  • arbiter/cli.py
  • arbiter/kernel.py
  • arbiter/lease.py
  • arbiter/policy.py
  • capabilities.yaml
  • docs/FALSE-DECISIONS.md
  • scripts/adjudicate.sh
  • tests/fakebackend.py
  • tests/false_decision_ledger.jsonl
  • tests/test_concurrency.py
  • tests/test_lease.py
  • tests/test_no_llm.py
  • tests/test_policy.py
  • tests/test_replay.py

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

feat(kernel): 仲裁内核 v1(策略表 + CAS 租约 + 防重放)

✨ Enhancement 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• 引入 /claim /release /retry 的确定性裁决:策略表 + CAS + TTL 租约。
• 增加防重放台账 refs/seen 与 GitHub/local 两类后端,实现 fail-closed。
• 补齐 CLI/脚本、CI workflow、69 条单测与误放行/误拒台账约定。
Diagram

graph TD
  A[Conductor] --> B["scripts/adjudicate.sh"] --> C["arbiter/cli.py"] --> D["arbiter/kernel.py"]
  D --> E["arbiter/policy.py"]
  D --> F["arbiter/lease.py"]
  D --> G["arbiter/backend.py"] --> H{{"api.github.com"}} --> I[("Git refs")]
  G --> J["Local git CLI"] --> I
  subgraph Legend
    direction LR
    _svc[Service/File] ~~~ _ext{{External}} ~~~ _db[(Database/Refs)]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. 用 Issue/PR 状态(labels/comments/check-runs)存租约与幂等键
  • ➕ 无需 Git Data API 的 commits/refs 操作,实现更“业务层”
  • ➕ 可直接在 GitHub UI 中可见,审计可读性强
  • ➖ 并发原子性弱(缺少结构性 CAS 保证),更难做到“每卡至多 1 租约”
  • ➖ 需要额外的权限与写路径,且失败语义更复杂(可能误判为 deny/allow)
2. 引入外部一致性存储(Redis/DynamoDB/SQL)做租约与幂等表
  • ➕ CAS/TTL 原生支持,性能与可扩展性更好
  • ➕ 天然支持清扫 seen 记录与统计
  • ➖ 引入新基础设施与凭证管理,违反“最小仓/零第三方依赖”的目标
  • ➖ 部署与故障域扩大,不利于快速落地与审计可复算
3. 使用 PyYAML/第三方配置库解析策略表
  • ➕ YAML 兼容性强,维护成本低
  • ➕ 减少自研解析器潜在的边界 bug
  • ➖ 引入第三方依赖,违背当前安全/供应链约束
  • ➖ 更强的 YAML 特性(anchors 等)也可能增加误配置风险

Recommendation: 维持本 PR 的“git refs 作为一致性存储 + 结构性 CAS + 受限策略表解析 + 纯函数裁决核心”的方案最契合 ADR-0054 的约束(默认拒绝、零 LLM、fail-closed、可审计与可离线复现)。上面替代方案要么牺牲并发原子性与结构性不变量,要么引入额外基础设施/依赖并扩大攻击面与运维负担。

Files changed (19) +2338 / -10

Enhancement (6) +1100 / -0
__init__.py新增包元信息与分层不变量声明 +5/-0

新增包元信息与分层不变量声明

• 定义版本号并用注释明确纯函数层不得 import 网络模块的约束,配合静态扫描测试固化边界。

arbiter/init.py

backend.py实现 CAS 后端:GitHubRefBackend + LocalGitBackend +279/-0

实现 CAS 后端:GitHubRefBackend + LocalGitBackend

• 新增生产后端(urllib 访问 api.github.com Git Data API)以创建/读取/更新/删除 refs 并创建空树 commit 作为台账/租约载体。新增本地 git CLI 后端以在裸仓上实现与 GitHub 近似的 CAS 语义,并对 transient lock 做有限重试与错误分类。

arbiter/backend.py

cli.py新增 CLI:加载策略表、选择后端并输出裁决 JSON/退出码 +128/-0

新增 CLI:加载策略表、选择后端并输出裁决 JSON/退出码

• 提供统一命令行入口,解析 card/sender/role/delivery/event/state/now 等输入,并将 policy/clock/state/backend 注入 kernel。对策略表加载失败走 infra 通道并输出可机器消费的 JSON。

arbiter/cli.py

kernel.py新增纯函数裁决核心 adjudicate()(租约 + CAS + 防重放) +224/-0

新增纯函数裁决核心 adjudicate()(租约 + CAS + 防重放)

• 实现事件白名单(仅 created)、delivery-id 幂等(refs/seen)与策略表静态授权(默认拒绝)。定义 /claim 的抢注与过期接管(条件 update-ref)以及 /release /retry 的 holder+未过期双校验与非静默拒绝,并统一 allow/deny/noop/infra 的输出与退出码映射。

arbiter/kernel.py

lease.py新增租约模型:TTL、过期判定、ref 命名与严格 JSON 格式 +205/-0

新增租约模型:TTL、过期判定、ref 命名与严格 JSON 格式

• 定义租约 refs/leases/<org>__<repo>__<n> 与 seen refs/seen/<sha1> 的生成与校验规则。实现 ISO8601 时间处理、过期边界 fail-closed 语义,以及严格键集的序列化/反序列化以防篡改或漂移。

arbiter/lease.py

policy.py新增策略表加载/校验与默认拒绝判定(受限 YAML 子集) +259/-0

新增策略表加载/校验与默认拒绝判定(受限 YAML 子集)

• 实现无第三方依赖的 mini YAML 解析器,并对 schema_version、defaults、commands 及各子键/值域做严格校验(未知键拒绝)。提供 policy.check() 返回 allow/deny 的明确 code/reason,且未知命令默认拒绝。

arbiter/policy.py

Tests (6) +907 / -0
fakebackend.py新增内存 FakeBackend 供离线测试复用 +65/-0

新增内存 FakeBackend 供离线测试复用

• 提供 refs/commits 的内存实现,复刻 create_ref/update_ref 的冲突语义与 commit_message 读取能力。为 replay 等不需要 git 子进程的用例提供更快、更可控的后端替身。

tests/fakebackend.py

test_concurrency.py新增并发 CAS 与 release/retry 防护测试(AC-2/AC-4) +275/-0

新增并发 CAS 与 release/retry 防护测试(AC-2/AC-4)

• 用裸仓 + LocalGitBackend + 多线程验证并发 /claim 恰一胜者与过期接管的条件 CAS。覆盖 /release /retry 的 holder/owner 权限与过期拒绝(非静默删除),并验证 infra 通道与篡改租约 fail-closed。

tests/test_concurrency.py

test_lease.py新增租约模型单测:过期边界、ref 命名与序列化严格性 +160/-0

新增租约模型单测:过期边界、ref 命名与序列化严格性

• 验证 TTL/过期边界判定(now==expires_at 视为过期)、holder 匹配语义与严格 JSON 键集校验。补充 card/ref 命名规则(含 .github)与 seen_ref 的 sha1 计算。

tests/test_lease.py

test_no_llm.py新增无 LLM 边界静态扫描测试(imports/URL host/特征串) +132/-0

新增无 LLM 边界静态扫描测试(imports/URL host/特征串)

• 使用 AST 断言纯函数层不 import 网络/进程逃逸模块,并限制 backend.py 的 URL host 只能是 api.github.com。对全仓源码执行 LLM 端点/SDK 特征串扫描,并额外断言“默认拒绝”有专门回归用例覆盖。

tests/test_no_llm.py

test_policy.py新增策略表单测:默认拒绝、越权拒绝与严格加载失败 +150/-0

新增策略表单测:默认拒绝、越权拒绝与严格加载失败

• 覆盖 policy.check 的 role/state/unknown-command 判定与 fail-closed 行为。验证加载器对未知键、坏 schema_version、非法 TTL、Tab 缩进等情况的拒绝策略,并校验真实 capabilities.yaml 可被加载。

tests/test_policy.py

test_replay.py新增防重放单测:重复 delivery-id → no-op,edited 拒绝且不写入 +125/-0

新增防重放单测:重复 delivery-id → no-op,edited 拒绝且不写入

• 验证同 delivery-id 的重复投递不会产生任何状态变化且返回 noop/replay-detected,并确保被拒的 delivery 同样占用幂等键。覆盖 edited 事件不消耗 delivery 的纵深防御,以及 seen ref 指向的 commit message 可审计性。

tests/test_replay.py

Documentation (3) +138 / -10
README.md完善仲裁内核 v1 说明、用法、安全模型与仓库布局 +76/-10

完善仲裁内核 v1 说明、用法、安全模型与仓库布局

• 扩展 README,解释仲裁职责、命令集语义、退出码与 fail-closed 通道。补充防重放、单租约不变量、分层边界(唯一网络出口)以及本地离线用法与目录结构。

README.md

FALSE-DECISIONS.md新增误放行/误拒定义与记账回流流程 +49/-0

新增误放行/误拒定义与记账回流流程

• 规范 false-allow/false-deny 的判定口径、如何记录到 jsonl 台账以及从台账到回归测试与修复 PR 的回流步骤。明确 infra 不计入误拒并强调可复算审计关系。

docs/FALSE-DECISIONS.md

false_decision_ledger.jsonl新增误放行/误拒台账文件(初始为空,含字段注释) +13/-0

新增误放行/误拒台账文件(初始为空,含字段注释)

• 以 jsonl + 注释形式定义台账格式与字段约定,作为审计与修复回流的落盘入口。初始不包含实际记录行。

tests/false_decision_ledger.jsonl

Other (4) +193 / -0
ci.yml新增 arbiter kernel v1 CI:lint/test/static-scan/policy-validate + gate +94/-0

新增 arbiter kernel v1 CI:lint/test/static-scan/policy-validate + gate

• 添加 GitHub Actions 工作流,包含 bash 语法检查、Python 编译检查、全量 unittest、无 LLM 边界静态扫描与策略表校验。引入严格 gate 聚合器,确保所有上游 job success 才放行。

.github/workflows/ci.yml

.gitignore忽略 Python 缓存文件 +2/-0

忽略 Python 缓存文件

• 添加 __pycache__/ 与 *.pyc 忽略规则,避免提交产物污染仓库。

.gitignore

capabilities.yaml新增仲裁策略表:命令授权、required_state 与 TTL 默认值 +31/-0

新增仲裁策略表:命令授权、required_state 与 TTL 默认值

• 定义 schema_version、默认 TTL(240 分钟)以及 /claim /release /retry 的 allowed_roles 与 required_state/require_holder 规则。作为唯一授权真源供 policy 模块加载与 CI 校验。

capabilities.yaml

adjudicate.sh新增 bash 包装:可选铸币 + CLI 调用 + MSYS 参数豁免 +66/-0

新增 bash 包装:可选铸币 + CLI 调用 + MSYS 参数豁免

• 实现 token 透传/铸造(依赖外部 gh-app-token.sh 单一真源)与后端选择(local 跳过铸币)。对 Git Bash 的 /claim 等参数路径改写问题做 MSYS2_ARG_CONV_EXCL 豁免,并保持退出码与 JSON 原样透传。

scripts/adjudicate.sh

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

该 PR 引入“仲裁内核 v1”,以纯函数 adjudicate() + 策略表 + git refs CAS + TTL 租约 + 防重放台账的方式,对 /claim /release /retry 做确定性裁决,并配套 CLI/脚本、CI 以及覆盖 AC-1~AC-5 的测试与文档,作为 conductor 的独立转介目标。

Changes:

  • 新增 capabilities 策略表加载与严格校验(默认拒绝、未知键拒绝、零第三方依赖的受限 YAML 子集解析)。
  • 实现租约模型与核心裁决逻辑(CAS 抢占/接管、holder/过期校验、防重放 seen refs)。
  • 增加 GitHub/Local 两类后端、CLI + bash 包装、CI 工作流与完整 unittest 测试套件。

Reviewed changes

Copilot reviewed 18 out of 19 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
tests/test_replay.py 覆盖 AC-3:delivery-id 幂等重放、edited 拒绝、台账可审计性与 exit code 映射。
tests/test_policy.py 覆盖 AC-1:默认拒绝、越权拒绝、策略表严格加载与真源文件可加载。
tests/test_no_llm.py 覆盖 AC-1:静态断言纯函数层无网络/进程逃逸 import、后端 URL 主机白名单、全仓无 LLM 特征串。
tests/test_lease.py 覆盖 AC-4 基础:TTL/过期边界、holder 校验、JSON 键集严格性与 ref 命名规则。
tests/test_concurrency.py 覆盖 AC-2/AC-4/infra 通道:并发 claim 单胜者、过期接管 CAS、release/retry 守卫与 infra 分流。
tests/false_decision_ledger.jsonl 误放行/误拒台账落盘形态(初始为空,含字段约定注释)。
tests/fakebackend.py 内存后端替身,用于离线重放类用例复用。
scripts/adjudicate.sh bash 包装:可选铸 App 令牌、调用 CLI、透传退出码与 JSON,并处理 MSYS 参数转换。
README.md 概述 arbiter 角色、用法、命令集语义、安全模型与仓库布局。
docs/FALSE-DECISIONS.md 误放行/误拒的定义、记账字段与回流流程约定。
capabilities.yaml 策略表真源:命令/角色/状态约束与默认 TTL。
arbiter/policy.py 策略表受限 YAML 解析器 + 严格校验 + 授权判定(默认拒绝)。
arbiter/lease.py 租约模型(ref 命名、card 解析、TTL/过期、序列化严格键集)。
arbiter/kernel.py 核心纯函数 adjudicate()(防重放、CAS 租约、release/retry 守卫、infra 分流)。
arbiter/cli.py CLI 参数解析、策略表加载(失败走 infra)、后端选择与输出 JSON/exit code。
arbiter/backend.py GitHub REST refs 后端(urllib)与 Local git CLI 后端(subprocess),对齐 CAS 语义。
arbiter/init.py 包版本与模块不变量说明。
.gitignore 忽略 Python 编译产物。
.github/workflows/ci.yml CI:lint/test/static-scan/policy-validate + gate 严格聚合。

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread arbiter/kernel.py
Comment on lines +95 to +110
seen = lease_mod.seen_ref(delivery_id)
ledger_msg = json.dumps(
{"delivery_id": delivery_id, "command": command, "card": canonical_card,
"sender": sender, "at": lease_mod.to_iso(now)},
ensure_ascii=False, sort_keys=True)
try:
marker = backend.create_commit(ledger_msg)
try:
backend.create_ref(seen, marker)
except CasConflict:
# 台账可查:refs/seen/<sha1> 指向的 commit message 即首次处理记录
return _decision(VERDICT_NOOP, "replay-detected",
f"delivery {delivery_id} 已处理过(seen ref 存在)——幂等 no-op",
**base)
except InfraError:
raise
Comment thread arbiter/kernel.py
Comment on lines +131 to +134
except lease_mod.LeaseError as exc:
# 租约数据非法(如 ref 指向的 commit JSON 被篡改/损坏)→ fail-closed 拒绝
return _decision(VERDICT_DENY, "lease-data-invalid",
f"租约数据非法: {exc}", **base)
Comment thread arbiter/backend.py


def _quote_ref_path(ref: str) -> str:
"""ref 路径段编码('/'→'%' 之外的保留字符按 RFC 3986 编码)。"""
@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (7) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Empty tree request invalid 🐞 Bug ≡ Correctness
Description
GitHubRefBackend.create_commit() sends {} to the create-tree endpoint even though GitHub
requires a tree array, so production cannot create the ledger or lease commits and every created
event falls into the infra path. The LocalGitBackend tests do not exercise this request shape.
Code

arbiter/backend.py[120]

+            "POST", f"/repos/{self._repo}/git/trees", {})
Evidence
The production backend passes an empty body object to /git/trees; GitHub's REST contract marks the
tree array as required, while all command processing starts by creating a commit.

arbiter/backend.py[117-133]
arbiter/kernel.py[94-103]
🌐 GitHub documents tree as a required array for POST /repos/{owner}/{repo}/git/trees.

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
GitHub's create-tree endpoint requires the `tree` request field, but the production backend sends an empty object, preventing commit creation.

## Issue Context
Use the documented empty-tree representation (`{"tree": []}`) and add a production-backend request-shape test.

## Fix Focus Areas
- arbiter/backend.py[117-133]
- tests/test_concurrency.py[72-101]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Release deletes replacement lease 🐞 Bug ≡ Correctness
Description
_release() validates a lease SHA and then unconditionally deletes the ref by name, so another
release/claim can replace that ref between the read/authorization and delete steps and the stale
releaser can delete the newly acquired lease. The same race (or a concurrent deletion) can also
cause a NotFoundError to escape adjudicate() because the delete path and top-level handler do
not classify/catch it into a deterministic verdict.
Code

arbiter/kernel.py[219]

+    backend.delete_ref(ref)
Evidence
The implementation performs an authorization check using the SHA it previously read, but both
backend delete operations take only the ref name/path and provide no way to bind the deletion to the
validated SHA (i.e., no expected-object-ID/CAS parameter). This is corroborated by the GitHub
delete-reference API contract, which deletes by ref path only, and by the local deletion behavior
(git update-ref -d) similarly lacking an expected-SHA condition; therefore, if the ref changes
after the check (e.g., an expired lease is atomically taken over) the subsequent unconditional
delete can remove the new value, and if the ref is concurrently deleted the backend can raise
NotFoundError that is not converted into a verdict.

arbiter/kernel.py[198-224]
arbiter/backend.py[108-115]
arbiter/backend.py[255-260]
arbiter/kernel.py[201-219]
arbiter/backend.py[255-259]
🌐 GitHub's DELETE reference endpoint takes the reference path and provides no expected-SHA condition.

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Release currently follows a read → validate/authorize → unconditional delete sequence that is not atomic: if the lease ref changes after the read (e.g., another claimant takes over an expired lease) the stale releaser can delete the new holder’s lease. Also, a concurrent deletion can surface as an uncaught `NotFoundError` (rather than a deterministic race verdict) because the delete call and the top-level handling in `adjudicate()` do not classify/catch it.

## Issue Context
Neither GitHub’s REST delete-ref operation nor the local `git update-ref -d` invocation binds deletion to the SHA that was read during authorization (there is no expected-SHA/conditional delete parameter). To preserve correctness under concurrency, switch the protocol to a CAS-safe release transition that conditionally advances from the exact observed SHA (for example, updating a “release tombstone” commit as a fast-forward from the checked SHA) and have claim recognize that inactive/released state; when the transition is lost due to a race, treat it as an explicit, deterministic concurrent-loss outcome instead of throwing.

## Fix Focus Areas
- arbiter/kernel.py[198-224]
- arbiter/backend.py[108-115]
- arbiter/backend.py[255-260]
- tests/test_concurrency.py[178-248]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Infra retries become no-ops 🐞 Bug ☼ Reliability
Description
The delivery replay/seen marker is published before policy evaluation and lease/command effects, so
a later backend failure is surfaced as retryable infra while the delivery is permanently recorded
as processed. A subsequent retry then returns replay-detected/noop and never re-attempts the
failed claim, release, or retry operation, effectively losing the command.
Code

arbiter/kernel.py[R101-104]

+            marker = backend.create_commit(ledger_msg)
+            try:
+                backend.create_ref(seen, marker)
+            except CasConflict:
Evidence
The cited code paths install the replay marker before dispatching the command and before applying
policy evaluation and lease mutations; when command execution later fails due to a backend issue,
the outer handler reports that failure as retryable infra. On the next invocation with the same
delivery ID, the existence of the marker immediately routes execution into the replay branch and
exits as noop/replay-detected, preventing the previously-failed claim/release/retry effects from
running again, which demonstrates how a transient backend failure can be turned into a permanent
drop.

arbiter/kernel.py[94-108]
arbiter/kernel.py[112-130]
arbiter/lease.py[117-124]
arbiter/kernel.py[94-130]
arbiter/kernel.py[141-191]
arbiter/kernel.py[198-224]
tests/test_concurrency.py[250-260]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Do not treat a delivery as completed merely because its replay/seen marker was created: today the marker is finalized before policy evaluation and lease/command effects, so any post-marker `InfraError` becomes retryable `infra` while permanently marking the delivery processed, causing retries to short-circuit as `replay-detected`/`noop` and never complete the failed claim, release, or retry.

## Issue Context
The current marker is atomically installed early (before policy evaluation and all lease mutations/command dispatch), and backend failures from command execution are returned as retryable. Because the marker is keyed only by delivery ID, a retry immediately hits the replay path and exits before running the command effects, effectively losing the operation. Adjust the design so the marker represents a completed/deduplicatable operation (or introduce a resumable pending vs completed state) such that retries after post-marker failures can safely resume/retry while concurrent duplicates still cannot execute the command twice, and add failure-injection tests after marker creation for claim and release.

## Fix Focus Areas
- arbiter/kernel.py[94-130]
- arbiter/kernel.py[141-191]
- arbiter/kernel.py[198-224]
- arbiter/lease.py[117-124]
- tests/test_replay.py[47-114]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View high (1)
4. Ambiguous card refs collide 🐞 Bug ≡ Correctness
Description
card_key() concatenates organization and repository components with __, although both accepted
names may themselves contain __; for example, a__b/c#1 and a/b__c#1 map to the same lease ref.
Those distinct cards can therefore block, inspect, or release each other's lease.
Code

arbiter/lease.py[R106-108]

+    seg = f"{org}__{repo}__{number}"
+    if not valid_ref_segment(seg):
+        raise LeaseError(f"非法 ref 段: {seg!r}")
Evidence
The parser's accepted character class includes _ in both components, while the sole lease key
concatenates them using __; the kernel uses that derived ref as the exclusive lease location.

arbiter/lease.py[18-20]
arbiter/lease.py[68-99]
arbiter/lease.py[102-114]
arbiter/kernel.py[141-147]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Encode organization and repository components unambiguously before constructing the lease-ref segment. A separator allowed in both components cannot distinguish all valid source cards.

## Issue Context
The card parser permits underscores in both owner and repository names, and `card_key` currently joins them with a double underscore. The kernel derives its sole per-card lease ref from this key.

## Fix Focus Areas
- arbiter/lease.py[18-20]
- arbiter/lease.py[102-109]
- arbiter/kernel.py[141-147]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

5. All 422s become conflicts 🐞 Bug ≡ Correctness
Description
create_ref() classifies every HTTP 422 as an existing-ref CAS conflict, although GitHub also uses
422 for validation failures and endpoint spam. A first delivery can therefore be reported as
replay/noop, or a claim as lost-race, instead of infra when no competing ref exists.
Code

arbiter/backend.py[R83-84]

+        if status == 422:
+            raise CasConflict(f"createRef 422: {payload.get('message', 'ref 已存在')}")
Evidence
The implementation unconditionally maps status 422 to CasConflict, while GitHub's endpoint
contract explicitly assigns 422 to validation failures or spam as well as any behavior inferred as
an existing ref.

arbiter/backend.py[78-85]
arbiter/kernel.py[100-108]
arbiter/kernel.py[146-165]
🌐 For Create a reference, GitHub documents HTTP 422 as “Validation failed, or the endpoint has been spammed,” not uniquely as ref-already-exists.

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The backend treats every create-ref 422 as proof that the ref already exists, but GitHub assigns that status to unrelated failures as well.

## Issue Context
Confirm the target ref exists and has the expected conflict semantics before raising `CasConflict`; classify ambiguous validation/abuse failures as `InfraError`.

## Fix Focus Areas
- arbiter/backend.py[78-85]
- arbiter/kernel.py[100-108]
- arbiter/kernel.py[146-165]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Invalid clocks crash CLI 🐞 Bug ☼ Reliability
Description
A malformed --now is parsed while evaluating the adjudicate() call arguments, outside any CLI
exception handler, so a resulting LeaseError escapes as a traceback and exits with code 1 instead
of the documented single-line infra JSON response and exit code 2. This breaks the CLI protocol for
callers who need to reliably classify malformed clock input.
Code

arbiter/cli.py[118]

+        now=_resolve_now(args.now),
Evidence
The CLI’s exception handling occurs before the adjudicate(...) call expression is evaluated and
appears to only cover policy-loading failures, but _resolve_now is used to compute the --now
argument value prior to entering adjudicate. Since _resolve_now delegates to parse_iso, and
parse_iso raises LeaseError for invalid timestamp text, an invalid --now triggers LeaseError
outside the CLI’s error boundary, resulting in an uncaught exception (traceback) rather than the
intended one-line JSON infra response with exit code 2.

arbiter/cli.py[65-68]
arbiter/cli.py[100-122]
arbiter/lease.py[52-62]
arbiter/cli.py[96-124]
arbiter/lease.py[52-65]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Catch `LeaseError` raised while resolving `--now` and ensure the CLI returns its structured, single-line infra/input-error JSON response with exit code 2 rather than emitting a traceback and exiting 1.

## Issue Context
`_resolve_now` delegates the user-supplied timestamp to `parse_iso`, which raises `LeaseError` on invalid text. Because `_resolve_now` is evaluated as part of the arguments to `adjudicate()`, it runs before the call enters any lower-level handling, and the current CLI try/except boundary only covers policy-loading errors; as a result, malformed `--now` input escapes uncaught.

## Fix Focus Areas
- arbiter/cli.py[65-68]
- arbiter/cli.py[96-124]
- arbiter/lease.py[52-65]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Equals local backend mints token 🐞 Bug ≡ Correctness
Description
The wrapper recognizes only --backend local, but argparse also accepts --backend=local; with
that valid spelling, the wrapper tries to mint an App token and fails before the CLI can select
LocalGitBackend. This breaks the documented tokenless offline mode for a standard option spelling.
Code

scripts/adjudicate.sh[R32-37]

+for _a in "$@"; do
+  if [[ "$_prev" == "--backend" && "$_a" == "local" ]]; then IS_LOCAL=1; fi
+  _prev="$_a"
+done
+
+if [[ $IS_LOCAL -eq 0 && -z "${ARBITER_TOKEN:-}" && -z "${GH_TOKEN:-}" && -z "${GITHUB_TOKEN:-}" ]]; then
Evidence
The shell loop tests only a two-argument form, then enters token minting whenever that flag remains
false; the CLI's argparse backend option accepts the resulting local value and would otherwise
instantiate the local backend.

scripts/adjudicate.sh[29-55]
arbiter/cli.py[54-55]
arbiter/cli.py[71-78]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Detect both `--backend local` and `--backend=local` before deciding whether token minting is necessary.

## Issue Context
The Python argparse option accepts either spelling, but the shell scan sets `IS_LOCAL` only when the immediately preceding argument equals `--backend`.

## Fix Focus Areas
- scripts/adjudicate.sh[29-37]
- arbiter/cli.py[54-55]
- arbiter/cli.py[71-78]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
✅ Web pages:
  +16 more
Review mode: 🧠 Deep: 这是安全敏感且跨多个独立路径的新仲裁内核,涉及策略授权、CAS并发、租约过期、重放幂等、GitHub API、CLI/CI等大量实质逻辑,存在多个易遗漏的独立缺陷。

Grey Divider

Tip of the day
💡 Did you know, you can tweak Display preferences with a live preview to see your comment before it ships

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread arbiter/backend.py
def create_commit(self, message: str, parent: str | None = None) -> str:
"""空树 commit,message 内嵌 JSON(租约/台账载体,ADR-0054 §2)。"""
status, payload = self._request(
"POST", f"/repos/{self._repo}/git/trees", {})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. Empty tree request invalid 🐞 Bug ≡ Correctness

GitHubRefBackend.create_commit() sends {} to the create-tree endpoint even though GitHub
requires a tree array, so production cannot create the ledger or lease commits and every created
event falls into the infra path. The LocalGitBackend tests do not exercise this request shape.
Agent Prompt
## Issue description
GitHub's create-tree endpoint requires the `tree` request field, but the production backend sends an empty object, preventing commit creation.

## Issue Context
Use the documented empty-tree representation (`{"tree": []}`) and add a production-backend request-shape test.

## Fix Focus Areas
- arbiter/backend.py[117-133]
- tests/test_concurrency.py[72-101]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread arbiter/kernel.py
"过期租约不接受 release/retry,等待 /claim 原子接管",
lease=existing, **base)

backend.delete_ref(ref)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

2. Release deletes replacement lease 🐞 Bug ≡ Correctness

_release() validates a lease SHA and then unconditionally deletes the ref by name, so another
release/claim can replace that ref between the read/authorization and delete steps and the stale
releaser can delete the newly acquired lease. The same race (or a concurrent deletion) can also
cause a NotFoundError to escape adjudicate() because the delete path and top-level handler do
not classify/catch it into a deterministic verdict.
Agent Prompt
## Issue description
Release currently follows a read → validate/authorize → unconditional delete sequence that is not atomic: if the lease ref changes after the read (e.g., another claimant takes over an expired lease) the stale releaser can delete the new holder’s lease. Also, a concurrent deletion can surface as an uncaught `NotFoundError` (rather than a deterministic race verdict) because the delete call and the top-level handling in `adjudicate()` do not classify/catch it.

## Issue Context
Neither GitHub’s REST delete-ref operation nor the local `git update-ref -d` invocation binds deletion to the SHA that was read during authorization (there is no expected-SHA/conditional delete parameter). To preserve correctness under concurrency, switch the protocol to a CAS-safe release transition that conditionally advances from the exact observed SHA (for example, updating a “release tombstone” commit as a fast-forward from the checked SHA) and have claim recognize that inactive/released state; when the transition is lost due to a race, treat it as an explicit, deterministic concurrent-loss outcome instead of throwing.

## Fix Focus Areas
- arbiter/kernel.py[198-224]
- arbiter/backend.py[108-115]
- arbiter/backend.py[255-260]
- tests/test_concurrency.py[178-248]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread arbiter/backend.py
Comment on lines +83 to +84
if status == 422:
raise CasConflict(f"createRef 422: {payload.get('message', 'ref 已存在')}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

3. All 422s become conflicts 🐞 Bug ≡ Correctness

create_ref() classifies every HTTP 422 as an existing-ref CAS conflict, although GitHub also uses
422 for validation failures and endpoint spam. A first delivery can therefore be reported as
replay/noop, or a claim as lost-race, instead of infra when no competing ref exists.
Agent Prompt
## Issue description
The backend treats every create-ref 422 as proof that the ref already exists, but GitHub assigns that status to unrelated failures as well.

## Issue Context
Confirm the target ref exists and has the expected conflict semantics before raising `CasConflict`; classify ambiguous validation/abuse failures as `InfraError`.

## Fix Focus Areas
- arbiter/backend.py[78-85]
- arbiter/kernel.py[100-108]
- arbiter/kernel.py[146-165]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread arbiter/kernel.py
Comment on lines +101 to +104
marker = backend.create_commit(ledger_msg)
try:
backend.create_ref(seen, marker)
except CasConflict:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

4. Infra retries become no-ops 🐞 Bug ☼ Reliability

The delivery replay/seen marker is published before policy evaluation and lease/command effects, so
a later backend failure is surfaced as retryable infra while the delivery is permanently recorded
as processed. A subsequent retry then returns replay-detected/noop and never re-attempts the
failed claim, release, or retry operation, effectively losing the command.
Agent Prompt
## Issue description
Do not treat a delivery as completed merely because its replay/seen marker was created: today the marker is finalized before policy evaluation and lease/command effects, so any post-marker `InfraError` becomes retryable `infra` while permanently marking the delivery processed, causing retries to short-circuit as `replay-detected`/`noop` and never complete the failed claim, release, or retry.

## Issue Context
The current marker is atomically installed early (before policy evaluation and all lease mutations/command dispatch), and backend failures from command execution are returned as retryable. Because the marker is keyed only by delivery ID, a retry immediately hits the replay path and exits before running the command effects, effectively losing the operation. Adjust the design so the marker represents a completed/deduplicatable operation (or introduce a resumable pending vs completed state) such that retries after post-marker failures can safely resume/retry while concurrent duplicates still cannot execute the command twice, and add failure-injection tests after marker creation for claim and release.

## Fix Focus Areas
- arbiter/kernel.py[94-130]
- arbiter/kernel.py[141-191]
- arbiter/kernel.py[198-224]
- arbiter/lease.py[117-124]
- tests/test_replay.py[47-114]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread arbiter/lease.py
Comment on lines +106 to +108
seg = f"{org}__{repo}__{number}"
if not valid_ref_segment(seg):
raise LeaseError(f"非法 ref 段: {seg!r}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

5. Ambiguous card refs collide 🐞 Bug ≡ Correctness

card_key() concatenates organization and repository components with __, although both accepted
names may themselves contain __; for example, a__b/c#1 and a/b__c#1 map to the same lease ref.
Those distinct cards can therefore block, inspect, or release each other's lease.
Agent Prompt
## Issue description
Encode organization and repository components unambiguously before constructing the lease-ref segment. A separator allowed in both components cannot distinguish all valid source cards.

## Issue Context
The card parser permits underscores in both owner and repository names, and `card_key` currently joins them with a double underscore. The kernel derives its sole per-card lease ref from this key.

## Fix Focus Areas
- arbiter/lease.py[18-20]
- arbiter/lease.py[102-109]
- arbiter/kernel.py[141-147]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread arbiter/cli.py
delivery_id=args.delivery_id,
event=args.event,
current_state=args.current_state,
now=_resolve_now(args.now),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

6. Invalid clocks crash cli 🐞 Bug ☼ Reliability

A malformed --now is parsed while evaluating the adjudicate() call arguments, outside any CLI
exception handler, so a resulting LeaseError escapes as a traceback and exits with code 1 instead
of the documented single-line infra JSON response and exit code 2. This breaks the CLI protocol for
callers who need to reliably classify malformed clock input.
Agent Prompt
## Issue description
Catch `LeaseError` raised while resolving `--now` and ensure the CLI returns its structured, single-line infra/input-error JSON response with exit code 2 rather than emitting a traceback and exiting 1.

## Issue Context
`_resolve_now` delegates the user-supplied timestamp to `parse_iso`, which raises `LeaseError` on invalid text. Because `_resolve_now` is evaluated as part of the arguments to `adjudicate()`, it runs before the call enters any lower-level handling, and the current CLI try/except boundary only covers policy-loading errors; as a result, malformed `--now` input escapes uncaught.

## Fix Focus Areas
- arbiter/cli.py[65-68]
- arbiter/cli.py[96-124]
- arbiter/lease.py[52-65]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread scripts/adjudicate.sh
Comment on lines +32 to +37
for _a in "$@"; do
if [[ "$_prev" == "--backend" && "$_a" == "local" ]]; then IS_LOCAL=1; fi
_prev="$_a"
done

if [[ $IS_LOCAL -eq 0 && -z "${ARBITER_TOKEN:-}" && -z "${GH_TOKEN:-}" && -z "${GITHUB_TOKEN:-}" ]]; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

7. Equals local backend mints token 🐞 Bug ≡ Correctness

The wrapper recognizes only --backend local, but argparse also accepts --backend=local; with
that valid spelling, the wrapper tries to mint an App token and fails before the CLI can select
LocalGitBackend. This breaks the documented tokenless offline mode for a standard option spelling.
Agent Prompt
## Issue description
Detect both `--backend local` and `--backend=local` before deciding whether token minting is necessary.

## Issue Context
The Python argparse option accepts either spelling, but the shell scan sets `IS_LOCAL` only when the immediately preceding argument equals `--backend`.

## Fix Focus Areas
- scripts/adjudicate.sh[29-37]
- arbiter/cli.py[54-55]
- arbiter/cli.py[71-78]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

@randypanding
randypanding merged commit 2f344cd into main Aug 21, 2026
11 checks passed
@randypanding
randypanding deleted the w1c2-kernel branch August 21, 2026 12:08
randypanding added a commit that referenced this pull request Aug 26, 2026
清偿项(全部行为保持,裁决语义/退出码/错误通道零变化):
- kernel.adjudicate:删除防重放段无操作的 try/except InfraError: raise 纯透传
  包装(异常本就由函数级 infra 通道统一上报);防重放语义(seen ref + 台账)
  与 CasConflict→noop/replay-detected 路径逐字节不变
- kernel.EXIT_CODE:改由 EXIT_ALLOW/EXIT_DENY/EXIT_INFRA 常量组装,
  消除字面量双写(原三常量从未被引用,属死代码)
- backend.LocalGitBackend:4 处重复的 subprocess.run(git -C …) 样板收敛为
  _exec_git 单一入口;各调用方的异常包装与报错文案逐字保留
  ("git 子进程失败"/"git rev-parse 失败"两通道不合并)
- 魔法常量具名化:timeout=30×4 → GIT_TIMEOUT_SECONDS;重试 3 次/0.15s →
  LOCK_RETRY_MAX_ATTEMPTS / LOCK_RETRY_SLEEP_SECONDS
- 函数内 import(time / urllib.request|error|parse)上提至模块顶部
  (backend.py 是静态扫描白名单中的唯一网络模块,tests/test_no_llm.py 不受限)

不动项:#2 空树 SHA 链路与 _quote_ref_path refs/ 剥离逻辑零触碰;
capabilities.yaml / AGENTS.md / ci.yml / README / tests 断言数量不减。

验证:python -m py_compile arbiter/*.py ✓;
python -m unittest discover -s tests → 73 tests OK ×2 连跑;
python -m arbiter.policy capabilities.yaml → POLICY-OK default-deny=verified。

Co-authored-by: randypanding <randypanding@users.noreply.github.com>
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.

2 participants