Repository navigation
feat(kernel): 仲裁内核 v1(W1-C2 #165,ADR-0054) - #1
Conversation
|
Warning Review limit reached
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. How can I continue?Wait for the limit to reset, then comment 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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (19)
Comment |
PR Summary by Qodofeat(kernel): 仲裁内核 v1(策略表 + CAS 租约 + 防重放)
AI Description
Diagram
High-Level Assessment
Files changed (19)
|
There was a problem hiding this comment.
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.
| 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 |
| except lease_mod.LeaseError as exc: | ||
| # 租约数据非法(如 ref 指向的 commit JSON 被篡改/损坏)→ fail-closed 拒绝 | ||
| return _decision(VERDICT_DENY, "lease-data-invalid", | ||
| f"租约数据非法: {exc}", **base) |
|
|
||
|
|
||
| def _quote_ref_path(ref: str) -> str: | ||
| """ref 路径段编码('/'→'%' 之外的保留字符按 RFC 3986 编码)。""" |
Code Review by Qodo
1. Empty tree request invalid
|
| 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", {}) |
There was a problem hiding this comment.
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
| "过期租约不接受 release/retry,等待 /claim 原子接管", | ||
| lease=existing, **base) | ||
|
|
||
| backend.delete_ref(ref) |
There was a problem hiding this comment.
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
| if status == 422: | ||
| raise CasConflict(f"createRef 422: {payload.get('message', 'ref 已存在')}") |
There was a problem hiding this comment.
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
| marker = backend.create_commit(ledger_msg) | ||
| try: | ||
| backend.create_ref(seen, marker) | ||
| except CasConflict: |
There was a problem hiding this comment.
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
| seg = f"{org}__{repo}__{number}" | ||
| if not valid_ref_segment(seg): | ||
| raise LeaseError(f"非法 ref 段: {seg!r}") |
There was a problem hiding this comment.
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
| delivery_id=args.delivery_id, | ||
| event=args.event, | ||
| current_state=args.current_state, | ||
| now=_resolve_now(args.now), |
There was a problem hiding this comment.
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
| 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 |
There was a problem hiding this comment.
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
…b97 = v7.0.0 实测解析)
清偿项(全部行为保持,裁决语义/退出码/错误通道零变化): - 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>
动机
宪法 §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)
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=verifiedtests/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)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)tests/test_concurrency.py::TestAc4ReleaseGuard(not-holder / lease-expired 拒绝且不静默删 ref;owner 可强制;holder 可释放)tests/false_decision_ledger.jsonl落盘(初始空+格式注释),记账约定 docs/FALSE-DECISIONS.md测试方法
python -m unittest discover -s tests -v→ 69 tests OK(并发用例连跑 5 遍无 flake)bash -n scripts/adjudicate.sh✓;python -m py_compile全部 ✓安全模型要点
风险与回滚
风险:GitHub refs API 故障窗口 → infra 通道(exit 2),调用方重投;seen ref 数量随事件增长(v2 清扫)。回滚:整仓可拆(ADR-0054 §9)——停转介即回 W0 行为,无数据迁移。