Skip to content

refactor(todos): slim contract module and eliminate all 101 Any - #8965

Open
loopx-agent wants to merge 1 commit into
mainfrom
codex/todos-contract-slim-20261118
Open

loopx-agent wants to merge 1 commit into
mainfrom
codex/todos-contract-slim-20261118

Conversation

@loopx-agent

Copy link
Copy Markdown
Collaborator

Summary

  • Eliminated all 101 Any usages in loopx/control_plane/todos/contract.py (any_count: 0, dict_any_count: 0) and trimmed the module from 1,469 lines down to 1,259 lines (-210 net lines; git diff --stat: 448 insertions(+), 653 deletions(-) across both touched files).
  • Replaced loose Any / dict[str, Any] signatures with strict boundary types (object, Mapping[str, object], dict[str, object], dict[str, str], typed helper aliases, and ReplanSuccessorSemanticBinding(TypedDict, total=False) for structured caller compatibility in loopx/control_plane/work_items/progress_observation.py).
  • Consolidated repetitive token matching, delimited-list deduplication (_match_token, _choice_token, _split_delimited_items, _dedupe_normalized), and repetitive _TODO_METADATA_FIELD_SCHEMA field boilerplate (_bool_field, _todo_id_message, _csv_field) plus table-driven normalization/update paths (_normalize_todo_metadata_for_write, _apply_todo_block_update) while preserving exact normalization and error-message semantics.
  • Added a zero-Any ratchet ceiling entry for loopx/control_plane/todos/contract.py (any_count: 0, dict_any_count: 0, lines: 1274) in loopx/canary/module_metric_baseline.json.

Verification

  • uv run --extra test python -c 'from pathlib import Path; from loopx.canary.maintainability_ratchet import module_metrics; print(module_metrics(Path("loopx/control_plane/todos/contract.py")))' -> {'lines': 1259, 'any_count': 0, 'dict_any_count': 0}
  • uv run --extra test mypy --strict --follow-imports=silent loopx/control_plane/todos/contract.py -> Success: no issues found in 1 source file
  • uv run --extra test mypy -> Success: no issues found in 17 source files
  • uv run --extra test ruff check loopx/control_plane/todos/contract.py tests/canary/test_maintainability_ratchet.py -> All checks passed!
  • uv run --extra test pytest -q tests/canary/test_maintainability_ratchet.py tests/control_plane/test_todo_metadata_schema.py tests/control_plane/test_contract_quality.py tests/control_plane/test_task_graph_topology.py tests/control_plane/test_local_coordination_authority.py tests/control_plane/test_native_todo_planning_update.py tests/control_plane/test_todo_decision_scope_lifecycle.py tests/control_plane/test_todo_completion_validation.py tests/control_plane/test_todo_completion_state_runtime.py tests/control_plane/test_contract_health.py tests/architecture/test_semantic_vocabulary_drift.py -> 372 passed in 144.31s
  • Todo smokes (todo-contract-smoke.py, todo-write-correctness-smoke.py, todo-continuation-policy-smoke.py, todo-user-gate-scope-smoke.py) -> all passed
  • uv run --extra test loopx canary premerge --tier quick --from-git-diff --git-diff-base origin/main -> status: passed, ok: true (selected=3, executed=3, failures=0)
  • Public/private boundary scan on touched files (loopx check --scan-path ...) -> errors=0, warnings=0

@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 · Gemini · Google (self_reported)

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

已针对 PR #8965 exact head 47a8f0788d2b347dbb61cf4de9481c5d1bb8c35c 完成完整审查与本地验证(审查结论:APPROVE,无 P0/P1/P2 问题)。

动机 / Motivation

受影响调用方与运维者:所有调用 loopx/control_plane/todos/contract.py 的控制面协调器、Todo 读写与元数据校验调用方(如 loopx/control_plane/work_items/progress_observation.py),以及 loopx/canary/ 可维护性棘轮检查维护者。

修改前(6a007683b7):loopx/control_plane/todos/contract.py 存在 1,469 行代码与 101 处 Any / dict[str, Any] 宽松类型标注,且尚未登记进 module_metric_baseline.json 零 Any 棘轮门禁;大量正则匹配、分界列表去重和 _TODO_METADATA_FIELD_SCHEMA 布尔/CSV/Todo-ID 字段定义包含重复样板分支。修改后(47a8f0788d):全模块净减 210 行至 1,259 行,any_count 降至 0、dict_any_count 降至 0,并以 any_count=0, dict_any_count=0, lines=1274 纳入 loopx/canary/module_metric_baseline.json。

可观测结果:module_metrics 返回 {'lines': 1259, 'any_count': 0, 'dict_any_count': 0};mypy --strict --follow-imports=silent 与全仓 mypy(17 个文件)均为 0 错误;11 个相关性单测套件 372 passed、4 个 Todo smokes 与 canary premerge --tier quick 全通过,且归一化值与报错文案保持逐字符兼容。

非目标边界:本 PR 不改变 Todo 状态机语义、元数据持久化格式、正则词表或外部 API 报错字符串,也不顺带修改共享的 tests/control_plane/test_contract_health.py 未用导入(该问题已由独立 PR 跟踪),更不授予自动合入权限。

改动思路 / Approach

全部瘦身与强类型化严格在既有的 loopx/control_plane/todos/contract.py 与 loopx/canary/module_metric_baseline.json 所有者边界内完成,复用已有标准库协议(object、Mapping[str, object]、TypedDict、Callable)与既有的 _TodoMetadataField Schema 驱动管线,未引入任何平行模块、适配器或新运行时开关。

当前 PR 边界:范围严格收敛于 loopx/control_plane/todos/contract.py 的零 Any 强类型化与表驱动结构收敛(净减 210 行)以及 loopx/canary/module_metric_baseline.json 的棘轮基线登记;远端 GitHub 共有静态检查在基础分支 test_contract_health.py:10 存在既有的上游 F401 阻塞,保留独立合入顺序边界。

  • 边界与结构化返回强类型化(loopx/control_plane/todos/contract.py):将所有松散入参 Any 与 dict[str, Any] 收敛为 object / Mapping[str, object] / dict[str, object] / dict[str, str],并为 replan_successor_semantic_binding 定义 ReplanSuccessorSemanticBinding(TypedDict, total=False),满足 progress_observation.py:497 对 .get("explore_result_node_refs") 的精确静态类型推导。
  • 正则与分隔列表去重复用(L204-249):抽取 _match_token、_choice_token、_split_delimited_items 与 _dedupe_normalized,统一收敛 10+ 个字段校验器与 ID/能力/scope 列表去重逻辑。
  • 元数据 Schema 构造因子收敛(L722-1208):引入 _bool_field、_todo_id_message、_csv_field 辅助工厂简化 _TODO_METADATA_FIELD_SCHEMA 声明,并用表驱动收敛 _normalize_todo_metadata_for_write 与 _apply_todo_block_update。
  • 棘轮门禁锁定(loopx/canary/module_metric_baseline.json:64-68):新增 "loopx/control_plane/todos/contract.py": {"any_count": 0, "dict_any_count": 0, "lines": 1274},锁死后续回归空间。

具体改动 / Changes

本次 diff 仅触及 2 个文件(448 insertions(+), 653 deletions(-),净减 205 行):

  1. loopx/control_plane/todos/contract.py(1469 -> 1259 行,-210 行,101 Any -> 0):清除全部 Any/dict[str, Any],补充 ReplanSuccessorSemanticBinding,抽提共用 token/去重及 schema 字段工厂辅助函数,保持对外导出符号与错误文本不变。
  2. loopx/canary/module_metric_baseline.json(+5 行):为 loopx/control_plane/todos/contract.py 注册零 Any 与 1274 行上限基线。

对主干的风险 / Risks

  • 调用方类型与运行时等价性:已跑通 mypy --strict --follow-imports=silent、全量 mypy(含消费 replan_successor_semantic_binding 的 progress_observation.py)、ruff check 与 372 个控制面/棘轮/词表漂移测试及 4 个 Todo smokes,0 失败、0 跳过。
  • 公共与私密边界:loopx check --scan-path ... 与 canary premerge --tier quick 均报 0 错误、0 私密路径/内容泄露;且因纯内部瘦身与静态基线登记,默认开启即完全安全。
  • 本地完整验证结果(exact head 47a8f0788d2b347dbb61cf4de9481c5d1bb8c35c):
    • module_metrics: {'lines': 1259, 'any_count': 0, 'dict_any_count': 0}
    • uv run --extra test mypy --strict --follow-imports=silent loopx/control_plane/todos/contract.py & uv run --extra test mypy: 0 issues(覆盖 17 个核心源码文件)
    • uv run --extra test ruff check loopx/control_plane/todos/contract.py tests/canary/test_maintainability_ratchet.py: All checks passed
    • uv run --extra test pytest -q(11 个测试文件含 test_maintainability_ratchet.py、test_todo_metadata_schema.py、test_contract_quality.py、test_task_graph_topology.py、test_local_coordination_authority.py、test_native_todo_planning_update.py、test_todo_decision_scope_lifecycle.py、test_todo_completion_validation.py、test_todo_completion_state_runtime.py、test_contract_health.py、test_semantic_vocabulary_drift.py): 372 passed in 144.31s
    • Todo smokes(todo-contract-smoke.py、todo-write-correctness-smoke.py、todo-continuation-policy-smoke.py、todo-user-gate-scope-smoke.py): 4/4 passed
    • uv run --extra test loopx canary premerge --tier quick --from-git-diff --git-diff-base origin/main: passed (ok=true, failures=0, selected=3)
    • loopx check --scan-path ...: ok=True (errors=0, warnings=0)

我的整体评价 / Verdict

  • Long-horizon 影响:improved — 彻底消除 Todo 核心契约中 101 处 Any 盲区与 210 行冗余样板并纳入棘轮基线,显著降低长程控制面重构的类型漂移与维护熵。
  • User-experience 影响:not_applicable — 纯控制面内部契约瘦身与静态棘轮基线注册,不改变终端或 UI 展示;visual_review 为 not_applicable。
  • 可观测语义 / 复用 / 词表:observable_semantics 为 equivalent,repository_reuse 为 reused,authority_semantics 与 semantic_alignment 均为 aligned(candidate_decision="reuse_existing")。

本 PR 范围克制、实现干净、静态类型与行为回归验证充分且无阻断问题。本 PR 为作者自有并触及 loopx/control_plane/**,正式合入仍需维护者授权及远端 CI 基线同步。

English verdict: APPROVE exact head 47a8f07 (author-owned COMMENTED approval review); eliminates all 101 Any occurrences and trims 210 net lines in loopx/control_plane/todos/contract.py with a zero-Any baseline ratchet, verified by strict/full mypy (0 issues), ruff, 372 passing pytest cases, 4 todo smokes, and quick premerge canary.

@mergify

mergify Bot commented Nov 18, 2026

Copy link
Copy Markdown

This pull request has merge conflicts with main and cannot be merged
until they are resolved. Please rebase or merge the base branch, @loopx-agent.

Choose the remote for the base repository, not an out-of-date fork.
For a fork clone, first inspect git remote -v; upstream must point
to https://github.com/loopx-project/loopx.git. If it is absent, add it
with git remote add upstream https://github.com/loopx-project/loopx.git.
Then run:

git fetch upstream
git rebase upstream/main
# Resolve each conflict, git add the resolved files, then git rebase --continue.
git push --force-with-lease origin HEAD

For a same-repository clone whose origin points to
https://github.com/loopx-project/loopx.git, use origin instead of
upstream for fetch/rebase. If you prefer merging the base, use
git merge <base-remote>/main and push normally.

Keep the DCO Signed-off-by trailer on every commit when you rebase.
https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork

@mergify mergify Bot added the needs-rebase Mergify: the pull request has merge conflicts with its base branch label Nov 18, 2026
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
@loopx-agent
loopx-agent force-pushed the codex/todos-contract-slim-20261118 branch from 47a8f07 to 7670201 Compare November 18, 2026 19:52
@mergify mergify Bot removed the needs-rebase Mergify: the pull request has merge conflicts with its base branch label Nov 18, 2026

@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 · Gemini · Google (self_reported)

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

已将 PR #8965 cleanly rebase 至最新 origin/main(41ea75e89892ed88d0ae543e97e31aad0a181c47),解决 loopx/canary/module_metric_baseline.json 合并冲突并保留主干全部最新基线条目,随后在独立工作树 exact head 7670201b6dd9822dd7371c3f70c9fa1ed9b4520e 上完成完整代码审校与本地实测验证(审查结论:APPROVE,无阻塞性 P0/P1/P2 问题)。

动机 / Motivation

所有依赖 loopx/control_plane/todos/contract.py 进行 Todo 元数据解析、写入校验、块更新与结构化绑定的控制面调用方(例如 loopx/todos.py、loopx/status.py、loopx/quota.py 与 loopx/control_plane/work_items/progress_observation.py),以及维护 loopx/canary/module_metric_baseline.json 可维护性棘轮基线的维护者。

基线版本(41ea75e898)中,loopx/control_plane/todos/contract.py 共有 1,469 行代码和 101 处 Any / dict[str, Any] 宽松类型标注,正则匹配、分隔符拆分去重与 _TODO_METADATA_FIELD_SCHEMA 字段构造存在大量重复样板,且模块未纳入零 Any 棘轮门禁,导致调用方在静态类型检查时存在盲区。Rebase 至当前主干后的精确提交(7670201b6d)将模块瘦身 210 行至 1,259 行,any_count 与 dict_any_count 均降至 0,抽提公共辅助函数并以 TypedDict 强类型化 ReplanSuccessorSemanticBinding,同时在基线账本中锁死零 Any 与 1,274 行上限。

公共导出符号、58 个元数据时序字段顺序、归一化规则与 ValueError 错误提示文本均保持逐字等价(基线与当前头实测指纹同为 edf70269f75b9d72),mypy --strict --follow-imports=silent 与下游调用方检查均报 0 错误,且棘轮基线已锁死 any_count=0、dict_any_count=0。

本 PR 仅处理 loopx/control_plane/todos/contract.py 的类型收敛、内部样板去重与 loopx/canary/module_metric_baseline.json 冲突整合后的基线登记,不改变 Todo 业务语义、Markdown 注释编码格式或外部命令行参数接口,也不越界修改主干上未触及的 heartbeat/builder.py 与 interaction_contract.py。若保持现状不处理,contract.py 中上百处 Any 会继续掩盖调用方字段类型误用,且缺少基线锁会导致后续改动重新引入宽松类型或膨胀回超限模块;本 PR 是一个边界清晰、可独立验证与回滚的完整质量收敛切片。

改动思路 / Approach

本次采用“原位收敛 + 表驱动去重 + 棘轮锁死”思路,而非拆分出第二套契约文件或兼容垫片。在入口与状态边界上,loopx/control_plane/todos/contract.py 保持全部既定公共函数与 TODO_METADATA_FIELDS 作为唯一元数据规范与编解码所有权入口,loopx/todos.py、loopx/status.py、loopx/quota.py 与 loopx/control_plane/work_items/progress_observation.py 继续消费同一套导出接口。在策略与投影分离上,正则校验与列表去重收拢进 _match_token、_choice_token、_split_delimited_items、_dedupe_normalized,字段读写与严格校验则通过 _TodoMetadataField、normalize_for_write 与表映射 _BLOCK_READ_NORMALIZERS / _BLOCK_TRUTHY_OR_POP_NORMALIZERS / _BLOCK_OPTIONAL_BOOL_NORMALIZERS / _BLOCK_STRICT_SETTERS 统一驱动,未引入任何新的外部状态、I/O 或后台副作用。

所有变更均收敛在现有 loopx/control_plane/todos/contract.py 单一契约拥有者与 loopx/canary/module_metric_baseline.json 基线拥有者内部:_match_token、_choice_token、_split_delimited_items、_dedupe_normalized 与 _TodoMetadataField 属于纯本地辅助与声明表,未新增并行状态拥有者、运行时持久化字段或兼容分支。当前 PR 边界仅覆盖 loopx/control_plane/todos/contract.py(-210 行、消除 101 处 Any)与 loopx/canary/module_metric_baseline.json(保留主干新增条目并补入 contract.py 基线),可直接独立审校、验证和回滚。 Rebase 期间在 loopx/canary/module_metric_baseline.json 保留了主干已合入的 heartbeat_recommendation.py、monitor_poll.py、quota_summary.py、todo_summary.py 等所有基线项,并按字典序登记 loopx/control_plane/todos/contract.py(any_count: 0, dict_any_count: 0, lines: 1274)。

具体改动 / Changes

本次 base..head diff 仅触及 2 个文件(448 insertions(+), 653 deletions(-),净减 205 行;其中 contract.py 由 1,469 行降至 1,259 行,module_metric_baseline.json 新增 5 行)。规范基线说明:本 PR 属于纯内部静态类型与样板收敛,未引入新 RFC 或独立规范文档(spec_basis=no_spec),仅沿用既有 Todo 元数据契约与可维护性基线格式。

  1. loopx/control_plane/todos/contract.py:全部 101 处 Any / dict[str, Any] 替换为精确边界类型(object、Mapping[str, object]、dict[str, object]、dict[str, str] 与类型别名 MetadataValueNormalizer 等),补充 ReplanSuccessorSemanticBinding(TypedDict, total=False) 以精确约束 progress_observation.py:497 的消费形态,并保留全部既有公共函数和常量。
  2. loopx/canary/module_metric_baseline.json(L115-119):合入主干新增基线后,登记 loopx/control_plane/todos/contract.py 的零 Any 与 1274 行上限基线。

关键代码讲解

  1. _match_token / _choice_token / _split_delimited_items / _dedupe_normalized(loopx/control_plane/todos/contract.py:204-248):统一封装去空格、大小写归一化、全匹配/前缀匹配、枚举集合校验、分隔符拆分及保序去重逻辑,替代原先分散在 10 余个 normalize_todo_* 函数中的重复分支,遇到空值或非法字符时仍返回 None 或空列表。
  2. ReplanSuccessorSemanticBinding 与 replan_successor_semantic_binding(loopx/control_plane/todos/contract.py:414-445):定义可选键 TypedDict 替代原有的 dict[str, Any] 返回标注,当 action_kind 无效或既无 target_key 又无 explore_result_node_refs 时仍返回 None,满足 progress_observation.py:474-516 的严格静态键类型推导。
  3. _TodoMetadataField 与 _bool_field / _csv_field 工厂(loopx/control_plane/todos/contract.py:721-777):将 _TODO_METADATA_FIELD_SCHEMA 中重复的布尔字段、CSV 列表字段和 todo_id 错误文案收拢为声明式工厂,并将写入期必填检查统一收口到 normalize_for_write。
  4. _normalize_todo_metadata_for_write(loopx/control_plane/todos/contract.py:987-1012):顺序遍历 _TODO_METADATA_FIELD_SCHEMA 执行写入归一,同时保留 continuation_policy 与 removed_continuation_policy 互斥检查以及 claimed_by 不得出现在 excluded_agents 的 ValueError 拒绝路径。
  5. _apply_todo_block_update 与 metadata_line_for_todo_block(loopx/control_plane/todos/contract.py:1165-1221):通过四张局部静态分发表替代冗长 if/elif 链,保持 None 清除、空列表移除、严格字段校验失败抛出 ValueError 及空白保留字段的既有行为。

对主干的风险 / Risks

  • 静态类型与语义等价性风险:contract.py 对外暴露的边界类型从 Any 收紧为 object / Mapping[str, object] / ReplanSuccessorSemanticBinding,若未检查下游调用方可能引发 mypy 报错或 subtle 的默认空值处理漂移。实测已通过 mypy --strict --follow-imports=silent loopx/control_plane/todos/contract.py(0 issues)、仓库全量 mypy(17 files, 0 issues)、上游消费方 mypy --follow-imports=silent(progress_observation.py、quota_summary.py、todo_summary.py 0 issues)、ruff check 及 tsc --noEmit;并通过基线(41ea75e898)与当前 head(7670201b6d)的实时运行对比(覆盖合法写入编码回环、块更新清除、replan_successor_semantic_binding、互斥策略/冲突认领/非法 decision_scope 等 ValueError 负向用例与文本分类),输出 SHA-256 指纹均为 edf70269f75b9d72(完全一致)。
  • 验证矩阵与主干既有基线说明:
    • 核心变更不变量与架构测试:PASS — tests/canary/test_maintainability_ratchet.py(含 test_module_metric_ratchet_detects_new_oversized_module)、test_top_level_module_budget.py、test_control_plane_import_boundaries.py、test_semantic_vocabulary_drift.py 与核心 Todo/契约 14 个测试集共 397 passed;4 个 Todo smokes 全部通过;loopx check --scan-path 报 0 错误/0 泄露;loopx canary premerge --tier quick 结论 ok: true, merge_gate_passed: true;scripts/check_rfc_bilingual.py 与 git diff --check 全部通过。
    • 主干既有无关失败(非本 PR 回归):test_current_repository_debt_is_reviewed_without_line_count_pins 与 control-plane-maintainability-ratchet-smoke.py --format=json(advisory_inherited_failure)在 origin/main(41ea75e898)上同样因未触及的 heartbeat/builder.py 与 interaction_contract.py 失败,本 PR 所触及 2 个文件发现数为 0;在 125 个全量 todo/contract/调用方测试文件横扫中 2,606 passed,5 个失败用例已逐一在 origin/main 同命令对照确认完全一致(非本 PR 引入),test_todo_consumer_host_retirement.py 10 个 setup error 为干净 worktree 未构建 gitignored Chat 前端产物的环境差异。
  • 权限、隔离与公共边界:本 PR 不引入 opt-in 开关、新权限或持久化字段(default_off_isolation 与 authority_semantics 均无新增暴露面),loopx check --scan-path 确认无私密信息或本地路径泄露。

我的整体评价 / Verdict

  • Long-horizon 影响:improved — 彻底消除了 loopx/control_plane/todos/contract.py 中 101 处 Any 并净减 210 行冗余样板,同时在棘轮基线锁定零 Any 上限,降低控制面长程演进的类型退化与回归熵。
  • User-experience 影响:not_applicable — 本次仅修改内部 Python 契约模块 loopx/control_plane/todos/contract.py 与静态基线配置文件 loopx/canary/module_metric_baseline.json,不涉及任何前端页面、终端视觉排版或用户可见 UI 变更,故无需视觉截图检查。(visual_review=not_applicable,unverified_scope=none)。
  • 语义对齐、代码量与兼容判定:observable_semantics=equivalent、code_volume=necessary(compatibility_assessment=retain,保留全部公共导出签名与既有 ValueError 错误文案且无新增兼容分支)、change_proportionality=proportionate(architecture_assessment=retain)、default_off_isolation=not_applicable、authority_semantics=not_applicable、semantic_alignment=aligned(candidate_decision=reuse_existing,复用既有 TODO_METADATA_FIELDS 与棘轮基线词汇)。

当前剩余风险主要为干净独立 worktree 未构建前端 Chat bundle 导致冷启动包装测试未在该副本运行,且正式合并仍依赖维护者授权(本 PR 为作者自有并触及 loopx/control_plane/**)。全部必检静态类型、契约测试与本地预合并门禁已在 exact head 7670201b6dd9822dd7371c3f70c9fa1ed9b4520e 实测通过,无阻塞问题。

English Verdict: APPROVE

This branch has not been deployed

No deployments
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