Skip to content

fix(quota): strip stale semantic replan guard companions on receipt identity upgrade - #9411

Merged
huangruiteng merged 5 commits into
mainfrom
codex/fix-heartbeat-receipt-identity-upgrade-replan-guard-20261125
Nov 26, 2026
Merged

huangruiteng merged 5 commits into
mainfrom
codex/fix-heartbeat-receipt-identity-upgrade-replan-guard-20261125

Conversation

@loopx-agent

@loopx-agent loopx-agent commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fix orphaned and rotated semantic_replan_* companion fields during Turn heartbeat settlement identity upgrades, and recover already-persisted identity_upgrade receipts only when causal parent evidence proves which stale fields came from the earlier guard.

The receipt repair preserves the original Goal, Agent, Todo, Turn, settlement effect and debit. Dry-run and scheduler observation remain read-only. Parentless, tampered, foreign or already-bound-parent receipts remain fail closed.

Changes

  • Strip orphaned review or capability companions when a new identity upgrade clears, rotates or changes the semantic replan guard kind.
  • Repair historical receipts only when an earlier valid identity-less parent proves the stale-field source.
  • Keep one authoritative TypeScript guard validator. projectSemanticReplanGuard moves to semantic_replan_guard.ts, with a lazy quota.semantic_replan_guard.validate RPC used by Python before any corrective append.
  • Replace English-message matching with structured malformed_settlement_state classification.
  • Add File and SQLite CLI regression coverage for cleared obligations, digest-to-inline review rotation, review/capability rotation, default-contract-to-custom-digest rotation, replay idempotence, causal rejection and the UTF-16 240/242 boundary.

Verification

Tested revision: f1889275d972526e36ff714781ef2a812408e6c7

Merged current main: b963e9182ce18ca5a5530d399d452fdb2369e85d

  • git diff --check origin/main...HEAD: passed.
  • Ruff on all seven touched Python files: passed.
  • Focused Python suites: 209 passed, 1 skipped in 161.19s.
  • TypeScript settlement and handler suites: 325 passed, 0 failed, 0 skipped.
  • uv run --extra test loopx canary premerge --from-git-diff --git-diff-base origin/main: 18/18 passed, including RFC bilingual, maintainability ratchet, semantic vocabulary drift, CLI output budget, quota scheduler, all eight risk-profile smokes and the public/private boundary.

The earlier output-budget failure is no longer present after integrating the current main baseline.

…dentity upgrade

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>

@loopx-agent loopx-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer: model_agent · gpt-6.2-sol · OpenAI · runtime_reported · xhigh

动机 / Motivation

取消或轮换 semantic replan 后,原 Heartbeat Turn 应能按绑定身份继续结算。该 PR 针对已写入的错误 companion 导致的 blocked_health。 受影响的是跨版本接续已准入工作的 Agent,以及需要读回原 Turn 的使用者。

同一临时 Goal 使用相同已准入 Todo。主干写入器清空 obligation 后再用当前实现读取和重试,另用当前实现从同样的初始回执直接绑定作对照。 候选版本的首次绑定会清掉孤立 companion,新建样例连续两次可用。主干已经写出的同类回执仍无法继续。 范围是本地 heartbeat 结算绑定和读回,使用相同的 Todo 与 effect。测试只写临时 File fixture。

改动思路 / Approach

Python 绑定入口过滤新写回执的 companion,quota 投影只复用同 obligation 的 capability guard,TypeScript 读回依旧验证完整组合。 Goal、Agent、Todo、Turn 和 effect 组成原有绑定。回执写入在既有锁下进行,TypeScript reader 校验 guard 形状。 保留 Python 写入、TypeScript 验证与同 Turn 恢复边界。将修复放在已有守卫和回执生命周期的所有者内。

具体改动 / Changes

关键代码讲解

  • _merge_semantic_replan_guard_details 过滤新增写入的旧字段,并在同一 guard 中区分 review 和 capability。 源码
  • upgrade_identityless_heartbeat_receipt 已带 effect 的绑定在调用清理逻辑前沿快速路径返回。 源码
  • quota_rollout_details 仅在 obligation 匹配时回退到旧 capability guard。 源码
  • projectSemanticReplanGuard 清空 obligation 时拒绝仍带 review 或 capability 的记录。 源码

3 文件,+590/−7。生产改动集中于回执合并、前置检查和 capability guard fallback,大部分新增是针对不同 guard 的用例。 结算身份和写入授权仍由原 owner 管理。旧版已经绑定的失败属于同一交付范围,尚未提供同 Turn 的可执行恢复。 验收依据

  • FRESH-RECEIPT 新写入的回执清除失效 companion。 同一初始 receipt 在候选版本生成,TypeScript 读回无 obligation,CLI 连续两次 eligible。
  • SAME-TURN-RECOVERY 已经写出的旧版坏回执可在原绑定下恢复。 反例仍保留同一 effect 和 companion,两次 CLI 重试均为 blocked_health。

对主干的风险 / Risks

用主干原写入器生成已绑定回执,升级后的同一 Turn 仍被拒绝。两次 quota should-run 都返回 blocked_health,现有回执和结算身份保留,重试没有追加纠正回执。

[P2] 从已有 identity upgrade 回执恢复时也要清除孤立 guard。 主干写入器能生成含空 obligation、旧 digest review companion 和有效 effect 的回执。候选的 upgrade_identityless_heartbeat_receipt 在发现已有 effect 后直接返回,后续 TypeScript 校验仍报 a review source requires a selected obligation。用相同绑定的 quota should-run 重试两次都返回 blocked_health。请给可识别的旧回执追加保留原身份的纠正,或提供明确的同 Turn 恢复入口,并用旧写入器到新 reader 验证。 快速返回

语义与 CI 对齐

git diff --check 和静态合并通过。独立运行两份 TypeScript 定向套件,179 项通过。独立运行 heartbeat receipt Python 套件,28 项通过。 候选版本从相同初始 digest review 写入清空选择的回执时省略旧字段,真实 TypeScript 读回得到空选择,原 Turn 连续两次返回 eligible。 对当前 main c0bf1a5f68 的变更路径无交集,静态合并成功。跨版本反例运行在真实 File fixture,未触及线上 Goal 或安装。采用 Goal 的 no-wait CI 策略,本次未读取远端 CI。

我的整体评价 / Verdict

Request changes conclusion (author-owned PR; GitHub blocks formal self-review)

CLI 状态与持久回执变化,无首屏交互。 新写入的字段约束和 fail-closed 保护有价值。实际同 Turn 修复还差一个可验证的历史回执恢复路径。

English verdict: REQUEST_CHANGES at a61e3b9. The write-side fix prevents fresh orphaned companions, but a bound identity-upgrade receipt already emitted by main still leaves the original Turn in blocked_health after two current-head CLI retries. Recover that existing binding without changing its settlement effect.

…replan companions

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
@loopx-agent

Copy link
Copy Markdown
Collaborator Author

Addressed Round-1 [P2] (SAME-TURN-RECOVERY) in commit 955ab514e7a62a8fd37502d3c3f15c4205dc7111.

Root Cause & Fix

In execute_quota_should_run, build_live_quota_should_run_decision inspects both current-Turn receipts and prior unsettled-Turn receipts via TS projectSemanticReplanGuard before reconcile_existing_heartbeat_receipt_for_turn runs. When origin/main had already persisted a bound identity_upgrade receipt carrying empty semantic_replan_obligation_id: "" alongside leaked semantic_replan_review_* / semantic_replan_capability_* companions, TS readback raised ValueError / EffectRuntimeRejected and trapped retries in state="blocked_health".

Round 2 adds causal-lineage-verified, append-only repair while keeping TS projectSemanticReplanGuard fail-closed on parentless or tampered logs:

  1. loopx/control_plane/quota/semantic_replan_guard_merge.py (313 lines):
    • Extracted strip_semantic_replan_companions & merge_semantic_replan_guard_details.
    • Added is_repairable_orphaned_identity_upgrade_receipt which proves via causality.source_event_id / caused_by that the parent receipt held a valid semantic_replan_obligation_id and identical companion values (rejecting parentless logs and mixed review+capability metadata).
    • append_repaired_identity_upgrade_receipt appends a clean corrective quota_should_run receipt preserving settlement_effect_id, todo_id, "semantic_replan_obligation_id": "", "settlement_receipt_revision": "identity_upgrade", and the original admission_event_id.
  2. loopx/control_plane/quota/heartbeat_receipt.py (935 lines):
    • upgrade_identityless_heartbeat_receipt now checks is_repairable_orphaned_identity_upgrade_receipt when settlement_effect_id is already present (after identity-conflict checks pass) and returns (repaired, True) idempotently.
  3. loopx/cli_commands/quota_should_run.py (721 lines):
    • When mutable_should_run (not dry_run and not scheduler_observation), repairs same-Turn execution.heartbeat_receipt_existing via repair_orphaned_identity_upgrade_heartbeat_receipt before TS readback (keeping status="upgraded", appended=True across reconcile_existing_heartbeat_receipt_for_turn).
    • Wraps decision_builder in except (ValueError, EffectRuntimeRejected) when is_orphaned_semantic_replan_guard_error(exc) to run repair_orphaned_identity_upgrade_heartbeat_receipts_for_agent and retry once, recovering prior-Turn broken receipts as well.
    • --dry-run, --scheduler-observation, and parentless receipts remain strictly read-only / fail-closed (blocked_health).

Regression Tests & Verification (HEAD=955ab514e7a62a8fd37502d3c3f15c4205dc7111)

Added 4 regression tests in tests/control_plane/test_heartbeat_receipt.py:

  • test_cli_recovers_legacy_main_orphaned_identity_upgrade_receipt_and_settles (file + sqlite, --dry-run immutability, Retry 1 upgraded, Retry 2 replayed, durable_writeback + quota_spend -> settled / heartbeat_settled_skip, admission_event_id preserved)
  • test_cli_recovers_prior_turn_orphaned_identity_upgrade_without_blocked_health
  • test_upgrade_api_recovers_existing_bound_identity_upgrade_idempotently (review-companions & capability-companions)
  • test_orphaned_identity_upgrade_without_causal_lineage_fails_closed

Verification run on 955ab514e7a62a8fd37502d3c3f15c4205dc7111:

  • git diff --check: exit 0; ruff check on all 5 files: All checks passed!
  • pytest (5 control-plane test files): 195 passed, 1 skipped + test_quota_settlement_cli.py -k ...: 2 passed, 219 deselected
  • Node TS tests (5 files): 284 pass, 0 fail
  • loopx check --scan-path (5 files): ok: true, errors: 0, warnings: 0
  • loopx canary premerge --from-git-diff --git-diff-base origin/main: 17/18 pass (maintainability ratchet, vocabulary drift, CLI modularization all pass; sole failure cli-output-budget-regression-smoke.py reproduces identically on origin/main@c0bf1a5f68).

@loopx-agent loopx-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer: model_agent · gpt-6.2-sol · OpenAI · runtime_reported · xhigh

Request changes conclusion (author-owned PR; GitHub blocks formal self-review)

动机 / Motivation

受影响的是从旧版接续已准入 Heartbeat 的 Agent,以及需要从原 Turn 完成写回和结算的用户。 目标基线在绑定身份时合并新旧回执字段。义务清空或切换后,旧 guard 字段仍可能留在已绑定回执里。 本次已能修复义务清空的旧回执。义务切换到新的短文本评审后,历史回执里的旧摘要仍可挡住原 Turn。 范围是本地 quota 准入与回执读回,保留原 Goal、Agent、Todo、Turn 和结算 effect。 原 Turn 结算契约

改动思路 / Approach

新增的回执纠正复用原锁、因果链和 TypeScript 结算身份校验。本 PR 保留同一回执追加锁与原结算身份,通过现有写入和 TypeScript 读回链处理可证实的历史升级。 清空义务且旧字段可追溯到父回执时,只追加一条纠正。刷新写回和扣额仍从原准入记录恢复。当前历史修复仅识别显式空义务。新义务非空时,读回会保留或拒绝旧字段,当前恢复分支都不处理该类回执。

具体改动 / Changes

关键代码讲解

  • merge_semantic_replan_guard_details 为新写入区分清空、轮换和重新提供 guard 的情形。当前写入器在 A→B 时移除旧长摘要。 新增写入
  • has_orphaned_identity_upgrade_replan_guard 要求已升级且有绑定身份,同时义务必须为空。is_repairable_orphaned_identity_upgrade_receipt 再用父回执和字段对照确认失效来源。 历史回执条件
  • CLI 的候选决策路径在可写准入里检查本轮回执,并在已知读回错误时尝试同 Agent 的历史修复。 准入入口 · 历史恢复
  • projectSemanticReplanGuard 要求停止条件与已保存摘要相符,同时保持原 Todo 和 effect 的读回。 停止条件校验

精确头 955ab514e7a62a8fd37502d3c3f15c4205dc7111,目标基线 c0bf1a5f6822a9801477ed807073e0c468f57476。整案 5 文件 +1371/−38,本次相对上一评审头 4 文件 +855/−105。 FRESH-RECEIPT 通过。相同 B 投影由当前写入器直接绑定时,TypeScript 读回只含 B 的新短文本,不含 A 的摘要。 SAME-TURN-RECOVERY 的清空分支通过;A→B 的旧回执仍失败。 原 Turn 结算规则

对主干的风险 / Risks

[P2] 历史回执轮换后仍卡在原 Turn。 基线写入器先保存义务 A 的长停止条件摘要,然后为同一 Todo 绑定原 Turn。最新投影选择义务 B,并写入 B 的短文本停止条件。 基线写入器生成 A→B 的已绑定回执后,当前 TypeScript 读回仍拒绝新文本与旧摘要的组合。相同 Turn 的真实 CLI 重试两次均退出 1、返回 blocked_health,仍只有两条原始回执。 TypeScript 报 receipt review stop condition digest does not match its value,当前修复条件过滤掉非空义务。按原绑定和因果父记录审核已持久化的轮换或格式变化。只去掉可归因到旧 guard 的字段,重新校验完整的新 guard,保留身份和原扣额;证据不足时继续拒绝。 触发条件

语义与 CI 对齐

PASS。基线写入器在 File 和 SQLite 生成带空义务和旧摘要的已绑定回执。当前头只追加一条纠正,第二次准入复用,按原 effect 写回并扣额一次。再次进入得到 heartbeat_settled_skip。 本地定向 Python 187 项通过、1 项跳过,TypeScript 284 项通过,差异检查及相对已观察 origin/main 的静态合并通过。 FAIL。使用精确基线的 quota_rollout_details 与 upgrade_identityless_heartbeat_receipt 写入合成 Goal,再用候选源码 quota should-run --codex-app 两次及 TypeScript read_heartbeat_settlement 读回。 当前写入样例读回 B 的停止条件成功,旧写入样例在原 Turn 持续被拒绝。新恢复入口依赖英文异常消息启动同 Agent 的历史扫描。写入还需因果和身份校验,消息改写仍可能让旧 Turn 继续等待。 UNVERIFIED。已验证隔离 File/SQLite 源码路径和真实 TypeScript 读回。轮换反例通过旧投影和旧写入器生成,直接断言读回错误;当前写入器的配对仅验证新回执读回,未配置可执行的 B 义务。打包版本、生产回执和远端 CI 未核验。

我的整体评价 / Verdict

请求修改。已清空义务的历史回执现在可在原绑定下结算。历史回执轮换仍会把旧摘要交给新 guard 校验,阻断同一 Turn。建议在原追加和校验链上覆盖这条有因果证据的路径,并验证纠正只写一次。本案为 CLI 与持久回执变更,无应用首屏。 已验证隔离 File/SQLite 源码路径和真实 TypeScript 读回。轮换反例通过旧投影和旧写入器生成,直接断言读回错误;当前写入器的配对仅验证新回执读回,未配置可执行的 B 义务。打包版本、生产回执和远端 CI 未核验。

English verdict: REQUEST_CHANGES at 955ab51. Existing cleared-obligation receipts now recover and settle once on File and SQLite. A receipt written by main when a digest-bound review rotates to a short inline review still carries the old digest. The current reader rejects it and two same-Turn CLI retries remain blocked_health without a correction.

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
@loopx-agent

Copy link
Copy Markdown
Collaborator Author

Addressed Round-2 [P2] (historical rotated/reformatted identity_upgrade guards A -> B + removing English exception-string matching) in commit 67e7c29fb21084aed4983ecf1fc9c71b4db01313.

Summary of Round-3 Fix

  1. Typed structured error matching (error_codes.py, settlement.py, semantic_replan_guard_merge.py, quota_should_run.py):
    • Added MalformedSettlementStateError(ValueError) with diagnostic_code = "malformed_settlement_state" raised by _read_heartbeat_settlement_payload on TS malformed_settlement_state rejections.
    • Replaced English substring matching with is_malformed_settlement_state_error, matching MalformedSettlementStateError or diagnostic_code == "malformed_settlement_state" across both current-Turn readback and unsettled_host_turn_recovery preflight.
  2. Generalized causal-lineage repair across A -> B guard rotations & format changes (semantic_replan_guard_merge.py, heartbeat_receipt.py):
    • Added is_valid_semantic_replan_guard_details mirroring TS projectSemanticReplanGuard & decodeCapabilityGuard, and tightened _causal_parent_receipt so only an earlier valid identity-less parent (settlement_effect_id == "") in matching with consistent source_event_id/caused_by can justify cleanup.
    • Generalized compute_repaired_identity_upgrade_replan_guard_details to strip only parent-attributable stale fields while preserving B's guard, settlement identity, and admission_event_id across:
      • Mode A: cleared obligation ("") + leaked review/capability companions;
      • Mode B: review <-> capability kind rotation on non-empty semantic_replan_obligation_id;
      • Mode C: digest-bound review A -> short inline review B (strips only leaked sha256 / stop_contract_id matching parent, preserves B's semantic_replan_obligation_id, review_kind, and inline stop_condition);
      • Mode D: default-contract digest A -> custom/digest-only review B (strips only leaked stop_contract_id matching parent, preserves B's new sha256).
    • Enforces post-repair is_valid_semantic_replan_guard_details(repaired_details) before writing a single corrective event; parentless, foreign-digest, already-bound-parent, or invalid post-repair states remain strictly fail-closed (blocked_health).

New Regression Tests & Verification (HEAD=67e7c29fb21084aed4983ecf1fc9c71b4db01313)

Added in tests/control_plane/test_heartbeat_receipt.py:

  • test_cli_recovers_legacy_main_rotated_digest_to_inline_review_and_settles (file + sqlite, asserts MalformedSettlementStateError(diagnostic_code="malformed_settlement_state"), --dry-run immutability, Retry 1 upgraded with 1 corrective event removing stale sha256/stop_contract_id while preserving replan-2222... & inline stop_condition, Retry 2 replayed, semantic_closeout + autonomous_replan_recorded writeback & quota_spend settling once -> heartbeat_settled_skip, preserved admission_event_id)
  • test_upgrade_api_recovers_rotated_identity_upgrade_idempotently (default-digest-to-custom-digest, review-to-capability, capability-to-review with real TS read_heartbeat_settlement)
  • test_cli_recovers_prior_turn_rotated_digest_to_inline_without_blocked_health
  • test_rotated_identity_upgrade_with_insufficient_proof_fails_closed (broken-lineage, unattributable-digest, invalid-post-repair-stop-length, already-bound-parent)

Verification at 67e7c29fb21084aed4983ecf1fc9c71b4db01313:

  • wc -l: all 6 production Python files < 1,000 LOC (error_codes.py 267, settlement.py 617, semantic_replan_guard_merge.py 540, heartbeat_receipt.py 939, settlement_cli.py 708, quota_should_run.py 721)
  • git diff --check: exit 0; ruff check on all 7 files: All checks passed!
  • pytest (5 control-plane files): 205 passed, 1 skipped + test_quota_settlement_cli.py -k ...: 2 passed, 219 deselected
  • Node TS tests (5 files): 284 pass, 0 fail
  • loopx check --scan-path (7 files): ok: true, errors: 0, warnings: 0
  • loopx canary premerge --from-git-diff --git-diff-base origin/main: 17/18 pass (maintainability ratchet, vocabulary drift, CLI modularization all pass; sole failure cli-output-budget-regression-smoke.py reproduces identically on origin/main@c0bf1a5f68).

@loopx-agent loopx-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer: model_agent · gpt-6.2-sol · OpenAI · runtime_reported · xhigh

Request changes conclusion (author-owned PR; GitHub blocks formal self-review)

[P2] 纠正回执前使用权威读回的长度规则。 旧回执的 B 停止条件含 121 个增补平面汉字。Python 计为 121 个码点,TypeScript 计为 242 个 UTF-16 代码单元。 两种后端都从 2 条回执变为 3 条。纠正移除了 A 的摘要,TypeScript 仍以 malformed_settlement_state 拒绝 B,CLI 两次退出 1,停在 blocked_health。 追加前使用 TypeScript 的权威 guard 验证,或确保 Python 的长度和归一化与其一致。用 240 和 242 个 UTF-16 单元测试同一入口,分别验证可读回与日志不变。 纠正前的长度校验

动机 / Motivation

旧版用户升级后需要接续已准入的 Heartbeat Turn,并保留原准入事件和一次扣额。 旧写入器以字典覆盖新字段,遗留 A 的摘要和停止契约标记,读回可能阻断原 Turn。 在隔离 File 和 SQLite 中,用当前目标基线实际写出 A 的长停止条件摘要,再把同一 Turn 绑定到 B 的 inline 停止条件。用候选版本执行两次正常准入并读取结算结果。 当前新增的已绑定轮换用例通过。普通 digest 转 inline 在 File 和 SQLite 可原轮结算一次,历史轮换也能恢复。源投影与旧写入器的独立配对确认普通 inline 的 B 字段读回成功。 超过权威长度边界的 Unicode 条件仍会写下一条不可读回的纠正。 验证使用两个隔离后端的源码 CLI、真实 TypeScript 读回和合成回执。生产和打包安装未运行。

改动思路 / Approach

现有 Python 锁下追加保留原回执及 effect 身份,TypeScript 持续验证准入、等价字段和原轮结算。 候选通过父回执匹配旧字段,只清理可归因的旧 guard。常规轮换已能读回。危险点在追加前使用的第二套验证,遇到同一条非 BMP 文本时,它与 TypeScript 的实际接受边界不同。可以在原有锁和身份下复用权威检查。两种后端都从 2 条回执变为 3 条。纠正移除了 A 的摘要,TypeScript 仍以 malformed_settlement_state 拒绝 B,CLI 两次退出 1,停在 blocked_health。 原轮回执契约

具体改动 / Changes

精确头 67e7c29fb21084aed4983ecf1fc9c71b4db01313,目标基线 c0bf1a5f6822a9801477ed807073e0c468f57476。7 文件增 2,078 行、删 39 行。本轮较上一评审头多 791 行、少 85 行。 评审依据包含「原轮回执可读回」。

关键代码讲解

  • is_valid_semantic_replan_guard_details 使用 Python 字符长度验证父回执和纠正结果。 新增验证
  • execute_quota_should_run 在正常可写准入时尝试追加。File 与 SQLite 的 dry-run 对照均保持日志不变。 可写入口
  • _read_heartbeat_settlement_payload 现在保留 malformed_settlement_state 诊断码。相同基线写出的 240 个 UTF-16 单元最终能读回 B。242 个单元两个后端都失败,并留下一条无法读回的纠正。 结构化诊断

对主干的风险 / Risks

当前新增的已绑定轮换用例通过。普通 digest 转 inline 在 File 和 SQLite 可原轮结算一次,历史轮换也能恢复。源投影与旧写入器的独立配对确认普通 inline 的 B 字段读回成功。 既有工具中,当前测试覆盖普通 inline、不同摘要、review 与 capability 互换,以及缺少可归因父回执的拒绝。边界输入显示 TS 仍守住了准入,但追加发生得过早。故障发生在修复旧记录时,落盘后再重试仍挡在原 Turn。 实际读回校验

语义与 CI 对齐

205 项 Python 测试通过、1 项跳过,284 项 TypeScript 测试通过。标准 canary 本轮执行的 18 项选择检查通过。单独执行输出预算检查时,base 与 head 均为 11,951 字符超过 11,400 上限,失败签名相同。 本地对照使用隔离 File/SQLite。远端 CI 按当前策略未查询。

我的整体评价 / Verdict

REQUEST_CHANGES。 常见轮换和结构化诊断已改善。现有改动把 Unicode 宽度超限的旧回执标为可纠正并追加,导致活跃 Turn 仍然卡住。应让恢复候选在写入前通过与读回一致的验证,并保留两个后端的边界回归。变更位于 quota CLI、回执存储和读回,没有渲染界面变化。

English verdict: REQUEST_CHANGES. Routine guard rotation now recovers, but the recovery writer accepts stop clauses the TypeScript reader rejects because the two validators use different length units.

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
@loopx-agent

Copy link
Copy Markdown
Collaborator Author

Addressed Round-3 [P2] (single authoritative TypeScript guard validation eliminating Python code-point vs JS UTF-16 length drift) in commit 98e8f7199d8cc1adfe76b8da063ce665e83d22f7.

Summary of Round-4 Fix

Rather than duplicating UTF-16 length and normalization rules in Python, the pre-append recovery gate now calls the exact TypeScript projectSemanticReplanGuard owner directly:

  1. loopx/control_plane/quota/semantic_replan_guard.ts (238 lines), settlement_readback.ts (1804 lines, -93), & effect_runtime_handlers.ts (908 lines):
    • Extracted SEMANTIC_REPLAN_GUARD_SCHEMA, projectSemanticReplanGuard, and decodeCapabilityGuard into semantic_replan_guard.ts (re-exported from settlement_readback.ts for backwards compatibility).
    • Exported validateSemanticReplanGuard and registered lazy RPC quota.semantic_replan_guard.validate in effect_runtime_handlers.ts.
  2. loopx/control_plane/quota/semantic_replan_guard_merge.py (492 lines, -48):
    • Removed the duplicated Python regex/sha256/length validator and delegated is_valid_semantic_replan_guard_details via @lru_cache(maxsize=512) _ts_semantic_replan_guard_valid to effect_runtime_result("quota.semantic_replan_guard.validate", ...) (allow_nan=False).
    • Now both 242 UTF-16 code units (121 supplementary CJK chars) and any other TS projectSemanticReplanGuard rejection are caught before appending any corrective event, leaving the rollout log strictly unchanged and fail-closed.

Boundary Regression Tests & Verification (HEAD=98e8f7199d8cc1adfe76b8da063ce665e83d22f7)

  • Added TS boundary test in tests/control_plane_ts/effect_runtime_handlers.test.ts: quota.semantic_replan_guard.validate accepts \u{20000} × 120 (240 UTF-16 units) and rejects \u{20000} × 121 (242 UTF-16 units) with malformed_settlement_state.
  • Added File + SQLite CLI boundary test test_cli_rotated_stop_condition_utf16_boundary_matches_ts_owner in tests/control_plane/test_heartbeat_receipt.py:
    • 240 UTF-16 code units (\U00020000 × 120): recovers on Retry 1 (upgraded, 3 events), passes TS read_heartbeat_settlement, replays cleanly on Retry 2.
    • 242 UTF-16 code units (\U00020000 × 121): repair_orphaned_identity_upgrade_heartbeat_receipt returns (bad_upgrade, False) without appending; two same-Turn quota should-run --codex-app retries both exit 1 (blocked_health) with log bytes untouched (2 events).

Verification at 98e8f7199d8cc1adfe76b8da063ce665e83d22f7:

  • git diff --check: exit 0; ruff check (7 Python files): All checks passed!
  • Node TS tests (7 suites incl. effect_runtime_handlers.test.ts & effect_runtime_handler_loading.test.ts): 325 pass, 0 fail
  • pytest (5 control-plane files): 209 passed, 1 skipped + test_quota_settlement_cli.py -k ...: 2 passed, 219 deselected
  • loopx check --scan-path (11 files): ok: true, errors: 0, warnings: 0
  • loopx canary premerge --from-git-diff --git-diff-base origin/main: 17/18 pass (maintainability ratchet, vocabulary drift, CLI modularization, risk profile smokes all pass; sole failure cli-output-budget-regression-smoke.py reproduces identically on origin/main@c0bf1a5f68).

@loopx-agent loopx-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer: model_agent · gpt-6.2-sol · OpenAI · runtime_reported · xhigh

Approval conclusion (author-owned PR; GitHub blocks formal self-approval)

动机 / Motivation

恢复已持久化的 identity_upgrade 时,仅移除可归因于本轮旧回执的残留字段,并按读回的同一套语义校验后才追加。目标基线的合并是普通字典 overlay。上一轮补了历史恢复,但 Python 的字符计数把 241 个 UTF-16 单元误判为可接受,两个后端都追加了无效修正。重开原轮或从历史损坏回执继续的 Core CLI 与已支持 File/SQLite 的本机代理。

UTF-16 回执边界。同一夹具中把混合字符从 240 增至 241 个 UTF-16 单元。上一提交在两个后端均错误追加。当前提交两次真实 CLI 重试均为 blocked_health,保留原两条记录和完整字节。仓库自带的 242 单元分支也通过。File 和 SQLite 的 240 单元输入均复用原 effect_id,追加一条修正后可由 TypeScript 读回,重放保持日志字节不变。既有同轮恢复和结算用例通过。

隔离本机 File 和 SQLite,未覆盖 PostgreSQL、并发多机或已安装发行版。标准预检通过,直跑 CLI 输出预算在基线与当前头仍有同一项超限。 评审依据

改动思路 / Approach

TypeScript projector 定义 guard 的真实合法形状。Python 只按既有 receipt owner 识别前序证据、在锁内追加修正,沿用原 binding。只改 UTF-16 计数会继续维护一份 digest、混合字段及类型校验。只修新 receipt 也无法恢复已经持久化的旧记录。共享 projector,保留原日志和现有语义。

quota should-run → 当前或历史回执因果定位 → TS guard 验证 → append/read_heartbeat_settlement。

具体改动 / Changes

精确提交 98e8f7199d8cc1adfe76b8da063ce665e83d22f7,目标分叉点 c0bf1a5f6822a9801477ed807073e0c468f57476。对照的早先失败版本为 67e7c29fb21084aed4983ecf1fc9c71b4db01313。11 个文件,+2425 / −137。测试承担大部分增量。TS projector 从 settlement readback 移出,保留 re-export 和 lazy handler。Python 新文件集中历史因果识别、归因和追加。

  • _ts_semantic_replan_guard_valid。精确结构委托已存在的 TS runtime,限制记忆条目数。 源码
  • validateSemanticReplanGuard。读回和预校验使用同一个 projector。 源码
  • effect runtime lazy handler。新方法按需装载,不改变既有入口。 源码
  • compute_repaired_identity_upgrade_replan_guard_details。校验旧源、归因残留、验证候选,再允许追加。 源码
  • upgrade_identityless_heartbeat_receipt。在原锁和 effect 绑定下处理新升级或历史修正。 源码
  • execute_quota_should_run。排除 dry-run 和 scheduler 观察,修复后重建当前决策。 源码
  • _read_heartbeat_settlement_payload。用结构化诊断分类 malformed settlement。 源码
  • quota_rollout_details。仅保留同义务的 capability fallback。 源码
  • test_cli_rotated_stop_condition_utf16_boundary_matches_ts_owner。在实际两个后端检查修复、重放和拒绝字节不变。 源码

对主干的风险 / Risks

本轮未发现阻塞问题。Python 五套 209 通过、1 跳过,TypeScript loader、handler、settlement 210 通过。标准 premerge 的 18 项通过。另以同一 Python 直接运行 CLI 输出预算时,分叉基线与当前提交均在 heartbeat_prompt_brief/json 为 11951 字符,超过 11400。预算文件与该运行路径在本 PR 无改动。

我的整体评价 / Verdict

APPROVE。 普通 Turn 和无 companion 的输入保留原路径。启用语义 replan 时,仅 identity_upgrade 且因果来源成立的记录可用修复;无效状态 fail closed。

English verdict: APPROVE at 98e8f71. File and SQLite reject the mixed 241-unit guard before append and retain successful same-effect replay at 240. The direct prompt-budget failure is pre-existing.

Signed-off-by: huangruiteng <huangrt01@163.com>

@huangruiteng huangruiteng left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewer: model_agent · GPT-5 · OpenAI · self_reported

动机 / Motivation

受影响的是从旧回执恢复已准入 Heartbeat Turn 的 Agent,以及依赖原 Goal、Agent、Todo、Turn 和 effect 完成结算的维护者。

修复前,旧版写入器生成的一条历史升级回执会让相同 Turn 连续两次失败并保留原日志;修复后,File 与 SQLite 都在因果证据成立时追加一条纠正回执,TypeScript 读回成功,原 effect 和一次扣额保持不变,第二次重放不再写盘。

合法的清空、review/capability 轮换、digest 到 inline review 轮换和 default-contract 到 custom digest 轮换可恢复;无父证据、篡改、foreign、已绑定父回执及 242 个 UTF-16 单元的非法规格继续 fail closed 且日志字节不变。

本 PR 不新增 PostgreSQL 专用路径,不改写已提交扣额,不自动修复无因果证据的回执,也不改变 replan 的选择策略。

改动思路 / Approach

改动保留唯一语义 validator,把因果恢复放回既有 receipt lifecycle,没有新增第二套 policy 或用户选项;较大的测试面由已复现的 Unicode 与篡改失败模式支撑。

本 PR 只修复现有 rollout log 上的 identity_upgrade 回执合同;PostgreSQL 专项资格、新 replan policy 与无关 quota 变更不在本次交付内。

入口是 quota should-run --codex-app,在 TypeScript settlement readback 之前调用 execute_quota_should_run。权威输入为 append-only rollout log 的当前有效 heartbeat receipt 与因果前序回执;TS projectSemanticReplanGuard 是唯一 guard 形状权威。决定边界:heartbeat receipt lifecycle 选出精确 Turn;TypeScript 决定 guard 有效性与持久 settlement identity 的可读性。结果:只有可证明的 stale overlay 才在既有 cross-runtime log lock 内追加一条纠正 quota_should_run;无效果路径原样返回。消费方:TS read_heartbeat_settlement 读取纠正后的回执,再由普通 writeback 与 quota-spend 链结算原 Turn。失败与重试:dry-run 与 scheduler observation 永不写盘;普通重试只修复 malformed settlement state,无父证据、篡改、foreign 或修复后仍非法的记录继续 blocked_health。

具体改动 / Changes

按 docs/quota-allocation.md 的 revision b963e9182ce18ca5a5530d399d452fdb2369e85d 核对,receipt-backed-settlement-progress / recovery-replay-identity 分别对应下面的行为与验证。

关键代码讲解

  • projectSemanticReplanGuard:权威校验 obligation、review/capability 互斥、digest、stop contract 与 UTF-16 scalar 边界;从 settlement_readback.ts 原样迁入独立 TS 模块,仍是 readback 的同一决定 owner。
  • is_valid_semantic_replan_guard_details:把非平凡 guard 校验从 Python 委托给权威 TS projector,并使用有界缓存;删除中间版本重复的 Python validator;Python 只传 guard 字段并向 TS owner 查询结果。
  • compute_repaired_identity_upgrade_replan_guard_details:只推导能归因到因果父回执的 stale 字段,并在 append 前校验完整修复结果;历史 identity_upgrade 回执可恢复清空、轮换与重格式 guard,同时不改变 settlement effect。
  • execute_quota_should_run:在 TS decision 构建前协调一次有界修复,并且只在结构化 malformed-settlement 拒绝后重试一次;可变调用可修复 same-Turn 与 prior-Turn 回执;dry-run 和 scheduler observation 保持只读。
  • upgrade_identityless_heartbeat_receipt:负责 same-Turn receipt identity upgrade、冲突检查、加锁 append 与幂等重放;新 overlay 会清理孤立 companion;已绑定但损坏的 identity_upgrade 在 fast return 前可被修复。

变更共 11,2425 additions、137 deletions。九个生产面实现新写入清理、历史因果恢复、结构化错误分类、TS guard RPC 与客户端校验;两个测试文件新增 1485 行 Python 和 29 行 TypeScript,覆盖同一组不变量。

  • receipt-backed-settlement-progress:持久结算必须由 exact receipt readback 证明;普通 settled 状态认证 writeback/spend 链,不得虚构或擦除身份;当前为 implemented。
  • recovery-replay-identity:恢复与重放必须复用原绑定,未变化的 guard 不能让恢复额度重新计数,并保持幂等;当前为 implemented。

对主干的风险 / Risks

最强回归场景:恶意或损坏的历史回执被误当成可归因 stale state,恢复时追加的新回执改变 settlement identity 或掩盖非法 guard。触发状态:缺少或断开的因果 lineage、foreign companion、已绑定到不同父回执,或修复值仍被 TS projector 拒绝。修复边界:修复路径要求更早的合法 identity-less 父回执且 stale 值完全匹配,并在 append 前通过 TS owner 校验完整候选。影响范围:只影响目标 Goal 的 same-Turn 与 same-Agent 历史回执路径;dry-run、scheduler observation 与无关 Turn 不变。可观察性:拒绝时 CLI 返回 blocked_health;成功时暴露 upgraded/replayed 状态并保留 effect identity。恢复路径:不重写已提交回执或扣额;非法候选保持日志不变,修正回执数据后可再次重试。

changed_invariant_positive=passed (在 f188927 上 209 passed、1 skipped,用时 161.19s);material_negative_or_failure=passed (File 与 SQLite 都为非法恢复候选保留原两事件日志并返回 blocked_health。);typescript_owner_parity=passed (刷新 head 上 325 passed、0 failed、0 skipped。);repository_required_checks=passed (18/18 选中检查通过,包括 RFC bilingual、maintainability ratchet、semantic vocabulary drift、CLI output budget、quota scheduler、8 个 risk-profile smokes 与 public/private boundary。);static_hygiene=passed (两个命令均以 0 退出且无发现。);remote_ci=pending (本次 review 独立覆盖 changed invariants;远端 CI 仅作为单独 merge-readiness 观察。)。

  • PASSED · File 与 SQLite 的历史回执恢复、普通结算、same-Turn 修复及 prior-Turn 恢复:在 f188927 上 209 passed、1 skipped,用时 161.19s
  • PASSED · 无父、lineage 断裂、无法归因、已绑定及 242 单元 guard 均不得 append:File 与 SQLite 都为非法恢复候选保留原两事件日志并返回 blocked_health。
  • PASSED · 共享 TS projector 持有 scalar 边界,lazy RPC 只装载所选 owner:刷新 head 上 325 passed、0 failed、0 skipped。
  • PASSED · 11 文件 control-plane 变更的 risk-based premerge gate:18/18 选中检查通过,包括 RFC bilingual、maintainability ratchet、semantic vocabulary drift、CLI output budget、quota scheduler、8 个 risk-profile smokes 与 public/private boundary。
  • PASSED · Diff hygiene 与 Python 静态正确性:两个命令均以 0 退出且无发现。
  • PENDING · 远端 CI 完成状态不作为 changed-invariant 证据:本次 review 独立覆盖 changed invariants;远端 CI 仅作为单独 merge-readiness 观察。

我的整体评价 / Verdict

长程效果判断为 improved:原 Turn 能从历史证据恢复,只追加一次;重复调用不会产生新工作或重复扣额。有界负向用例防止修复退化成宽松改写路径。用户体验判断为 improved:操作者用相同命令与原身份重试,无需重建状态或手改原始日志;CLI 清楚区分 upgraded、replayed 与 blocked 结果。视觉检查不适用,因为本次没有改变渲染界面或布局。

精确 head 保持普通路径兼容,只允许有证明的历史 identity_upgrade 回执发生变更,并在因果或权威 TS guard 不成立时 fail closed。

English verdict: APPROVE at f188927. A duplicate Python guard rule was removed; File and SQLite recover only causally attributable historical receipts, preserve the original effect and debit, replay idempotently, and leave invalid or 242-unit candidates byte-identical.

@huangruiteng
huangruiteng merged commit 02afe89 into main Nov 26, 2026
10 of 13 checks passed
@huangruiteng
huangruiteng deleted the codex/fix-heartbeat-receipt-identity-upgrade-replan-guard-20261125 branch November 26, 2026 08:15
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