Repository navigation
refactor(collaboration): slim collaboration_mcp.py below 1,800 LOC and ratchet ceiling - #9260
Conversation
…et line ceiling Signed-off-by: LoopX Agent <[email protected]>
loopx-agent
left a comment
There was a problem hiding this comment.
Reviewer: model_agent · Gemini · Google · self_reported
Approval conclusion (author-owned PR; GitHub blocks formal self-approval)
本次基于精确头 1379f3e4be23b95267fb1d8c984a5fd11cd70330 对 PR #9260(base=main,bbd26838366cf03b371f5a2308833e03d1e1229b)完成独立代码核验、Base-vs-Head 运行时等价性对比与本地验证门禁执行。
动机 / Motivation
- 受影响角色:维护 loopx.collaboration_mcp 的开发者与通过 MCP stdio/CLI 调度本地协作委派的操作者(maintainer/operator)。
- 改动前后场景:此前 loopx/collaboration_mcp.py 在主干已达 1,999 行(距离默认 2,000 行上限仅差 1 行),且在 module_metric_baseline.json 中没有独立登记上限,同时内部重复存在多处作用域检查、turn run-once 调用、参数拼装、错误提取与超时轮询样板;任何微小新增都会立即触发模块体积超限。合入本 PR 后,单文件精简至 1,792 行(净减 207 行,整体净减 202 行)并显式锁定 lines=1792、any_count=0、dict_any_count=0,所有对外 MCP tool 与 CLI 行为保持不变。
- 可观测收益:可观测结果表明:19 个 FastMCP 工具的 schema、描述与 docstring、全部 9 个 CLI 参数、_execution_arguments 与 _delegated_lease_context 输出均与基线字节级一致;针对 module_metric_baseline.json 的反事实校验确认新增第 1,793 行或引入 Any 会被 maintainability ratchet 立即拒绝。
- 非目标边界:本 PR 明确不拆分新 Python 模块、不修改 sibling 协作模块或 TypeScript 控制面逻辑、不改变 MCP 工具接口、CLI 参数顺序、锁顺序与错误文本格式,也不调整 default_limits 全局默认阈值。
相比“不做任何修改(仅剩 1 行裕度)”、“调高全局 2,000 行阈值”或“拆出新模块增加跨文件导入耦合”,在单模块内部提取高复用私有 helper 并直接锁定模块指标基线是成本最低且最可逆的维护性收敛方案。
改动思路 / Approach
本 PR 仅在既有宿主适配器 loopx/collaboration_mcp.py 内合并重复的样板逻辑,并在 loopx/canary/module_metric_baseline.json 收紧该模块上限,未新增持久状态、新模块或跨层决策权,所有核心决策与租约状态仍留在既有的 TypeScript 与控制面边界中。当前 PR 边界严格限定于单模块内部去重重构与预算基线收紧(2 个文件,净减 202 行),不外扩至 sibling 协作文件重构、不修改公开 MCP/CLI 协议,也不涉及前端或远端策略变更。
从调用链路与职责分层来看:main() 与 create_server() 继续担任 CLI/MCP stdio 入口,TypeScript effect_runtime 与 goal_instance_scope 继续作为唯一生命周期与租约裁决 owner,Delegations 仅承担宿主进程 IO、文件锁序列化和 CLI 参数桥接。对 loopx/control_plane/collaboration/ 兄弟模块检索确认,delegation_validation.py、delegation_results.py 与 source_grant_observation.py 的 history_inspect 或预检 CLI 参数各具独立作用域与返回结构,本 PR 不跨越模块边界抽象,避免了“拆东墙补西墙”式的模块搬家。
| 内部收敛 Helper | 替代的重复样板 | 复用点数量 | 保留的不变量 |
|---|---|---|---|
_inspect_request_entry |
collaboration_goal_scope + _entry + history_inspect |
3 处 | exact goal_ref 与可选 decision 回读 |
_run_turn_once / _settle_committed_turn |
"turn", "run-once" CLI 拼装与 validated_progress 结算 |
4 处 / 2 处 | pre_args / exec_args / post_args 顺序与 lease/host_record |
_service_cli_flags / _cli_arguments |
--runtime-root/--registry/--goal-id/--agent-id 与 --format json |
3 处 / 2 处 | 既有 Turn journal 验证命令字节序 |
_result_error / _record_execution_error |
error/reason/reason_code 回退与 180 字符持久化截断 |
6 处 / 2 处 | 错误优先级与 _fenced_write 停止围栏 |
_wait_until |
time.monotonic() < deadline 轮询循环 |
3 处 | SIGTERM/SIGKILL 宽限与宿主 drain 轮询间隔 |
具体改动 / Changes
全 Diff 仅触及 2 个生产/配置跟踪文件(总计 +259 / -461,净减 202 行),无测试/文档/生成文件混入:
loopx/collaboration_mcp.py:1,999 -> 1,792行(+254 / -461,净减207行),any_count=0、dict_any_count=0。loopx/canary/module_metric_baseline.json:+5行,在module_metric_ceilings新增"loopx/collaboration_mcp.py": {"any_count": 0, "dict_any_count": 0, "lines": 1792},不修改default_limits。
规范依据与逐条对照 / Spec Basis
依据基线版本 bbd26838366cf03b371f5a2308833e03d1e1229b 下未修改的接受规范文档 docs/reference/local-delegation.md(以及 loopx/canary/maintainability_ratchet.py)核验:
LD-MCP-01(implemented):未传--execution-config时保持原协作工具不变;启用后所有 19 个@server.tool()名称、签名、默认值、描述、docstring 均经 AST 与实时FastMCP.list_tools()校验,与基线字节级一致。LD-HOST-02(implemented):loopx.collaboration_mcp保留 stdio MCP 服务、分离 worker IO 与 validator 入口;_execution_arguments(覆盖generic-cli与codex-cli)及_delegated_lease_context输出与基线完全一致。MR-CEIL-03(implemented):loopx/canary/module_metric_baseline.json将loopx/collaboration_mcp.py锁定在lines=1792、any_count=0、dict_any_count=0,且default_limits未放宽。
关键代码讲解
_result_error(loopx/collaboration_mcp.pyL440):统一 6 处错误提取回退链payload.get("error") or payload.get("reason") or reason_code or fallback。通过默认include_reason_code=False区分普通 Turn/lease 失败与需要兜底reason_code的_cli通用命令拒绝,避免改变任何历史错误文本优先级。_wait_until(loopx/collaboration_mcp.pyL445):封装while time.monotonic() < deadline: if predicate(): return True; time.sleep(interval),收敛_signal_worker中 SIGTERM(0.2s)与 SIGKILL 后(0.1s)的锁释放等待,以及_await_host_drain的HOST_PROCESS_DRAINING退出等待。Delegations._inspect_request_entry(loopx/collaboration_mcp.pyL489):合并start、_receiver_adopted与_delegation_bootstrap三处相同的collaboration_goal_scope+_entry+decide_collaboration_lifecycle(..., operation="history_inspect")样板,并由read_decision开关控制是否进一步调用_receipt。Delegations._run_turn_once(loopx/collaboration_mcp.pyL509):收敛revalidate与_execute中的 4 处"turn", "run-once"CLI 调用,严格保持--goal-id、--agent-id、*pre_args、*exec_args、*post_args、--execute的参数顺位及delegated_lease/host_record透传,保障既有 Turn journal 恢复标识不变。Delegations._settle_committed_turn(loopx/collaboration_mcp.pyL1267):收敛_execute在todo_id is None(锁外)与持有_dispatch_lock+source_policy_fence锁内(already_locked=True)两次提交结算与validated_progress校验逻辑,维持原有锁重入边界与失败提示。
对主干的风险 / Risks
当前精确头 1379f3e4be23b95267fb1d8c984a5fd11cd70330 无阻塞性问题(No blocking findings)。
- 最强失败/回归情景与边界核验:
- 超时边界微差(
_await_host_drain):基线实现while self._host_drain(path) == HOST_PROCESS_DRAINING and time.monotonic() < deadline在deadline已过期时仍会多做一次只读_host_drain调用;重构为_wait_until后在deadline <= time.monotonic()时直接返回False。核查全部调用方(stop与_signal_worker)均传入新鲜正数DELEGATION_STOP_GRACE_SECONDS(10.0s)或仅在第一次等待成功后沿用未过期deadline,且_settle_stop在_dispatch_lock下会重新实读_host_drain,该只读前置判断无状态或锁语义影响。 - 参数防御(
_service_cli_flags与revalidate):_service_cli_flags使用agent_id or self.agent_id(因binding["agent_id"]来自已校验的 TS binding 且非空,实际安全);revalidate内_run_turn_once读取row["identity"]["operation_id"],与self.path(operation_id)写入约定一致。 - 适用性边界:
scope_fit确认全部重构 helper 均有活跃生产调用方;default_off_isolation与semantic_alignment均为not_applicable(无新增开关、无跨运行时语义词表变更);authority_semantics为aligned(无权限或生命周期语义扩张)。
- 超时边界微差(
- 验证矩阵与反事实测试:
ruff check loopx/collaboration_mcp.py loopx/canary/module_metric_baseline.json:PASS。mypy(17 source files):PASS(0 issues)。loopx check --scan-path loopx/collaboration_mcp.py --scan-path loopx/canary/module_metric_baseline.json:PASS(errors=0, warnings=0, public boundary clean)。examples/control_plane/control-plane-maintainability-ratchet-smoke.py:PASS(unreviewed=0, stale_exceptions=0, magnitude_regressions=0)。loopx canary premerge --from-git-diff --git-diff-base origin/main:PASS(ok=true,6 项 direct checks 与 13 项 catalog/risk-profile smokes 全部通过,manual_holds=[];另注:带--goal-id在独立评审 worktree 跑 premerge 时因本地change-qualityreceipt 按目录路径索引而提示receipt_missing,属评审工作树路径隔离现象,不影响代码库门禁)。- Base-vs-Head 独立对比:PASS(78 个顶层导入符号、14 个公开符号、58 个既有
Delegations方法签名、19 个实时FastMCP.list_tools()schema 与描述、CLI--help、3 项负数 CLIexit 2拒绝、_execution_arguments及_delegated_lease_context全部字节级一致)。 - Maintainability ratchet 负向反事实测试:PASS(临时树中将文件增至
1793行或加入Any注解均被collect_module_metric_findings立即拒绝)。 - 针对性
pytest(9 个测试文件):PASS(262 passed, 2 skipped;2 个跳过用例为tests/test_delegation_turn_context.py中因 macOS 未安装 PowerShell 7pwsh触发的条件跳过,其余 262 项全部通过)。
- 残余风险与未覆盖验证:macOS 评审环境缺少
pwsh,test_large_inbox_reader_commands_run_verbatim_in_powershell两条用例跳过;真实外部 Codex Host 进程长期运行及SIGKILL极端超时窗口依赖已有桩化集成验证而未在本次评审中重启真实外置模型会话。
我的整体评价 / Verdict
outcome_impact评估:long_horizon为preserved(独立 worker 生命周期、锁顺序、Turn 恢复与租约/停止结算路径与基线完全等价,并降低后续维护漂移风险);user_experience为preserved(19 个 MCP 工具、CLI--help与错误反馈字节级一致);visual_review为not_applicable(本 PR 仅涉及后端 Python 协作 MCP 运行时模块 loopx/collaboration_mcp.py 与模块预算基线 loopx/canary/module_metric_baseline.json,不改动任何前端界面、Web 视图或渲染展示层,故不适用视觉检查。 未验证视觉范围:none,不适用渲染评审)。- 等价性、体积与架构结论:
observable_semantics为equivalent;code_volume为necessary(兼容性策略retain);change_proportionality为proportionate(架构评估retain);default_off_isolation为not_applicable;authority_semantics为aligned;semantic_alignment为not_applicable(未新增或扩展词表)。 - 精确头新鲜度:发布前已复核远端 PR #9260 精确头仍为
1379f3e4be23b95267fb1d8c984a5fd11cd70330。
英文简短结论
English verdict: APPROVE — exact-head 1379f3e cleanly deduplicates loopx/collaboration_mcp.py from 1,999 to 1,792 LOC (net -202 repository LOC) with zero Any annotations, ratchets loopx/canary/module_metric_baseline.json (lines=1792, any_count=0, dict_any_count=0), preserves byte-for-byte AST/FastMCP/CLI/execution-argument parity against origin/main, and passes ruff, mypy, loopx check, canary premerge (13/13), ratchet counterfactuals, and 262 targeted pytest cases (2 pwsh skips on macOS).
loopx-agent
left a comment
There was a problem hiding this comment.
Reviewer: model_agent · gpt-6.2-sol · OpenAI · runtime_reported · xhigh
Approval conclusion (author-owned PR; GitHub blocks formal self-approval)
动机 / Motivation
本地团队的委托发起者和接收者通过 LoopX 的 MCP 或 CLI,在原任务、原轮次上继续交付、重验和停止。 原模块接近通用 2,000 行上限,同一请求查验、CLI 参数、异常处理和结算判断散在多个同域入口,维护时需要同时改多处。 在原委托适配器内合并这些重复分支,固定模块当前体积基线,并保留调用契约与结果。
发起绑定委托后让独立验证拒绝一次,先重验无效产物,再修复产物并由 MCP/CLI 接续原轮次。 File 和 SQLite 的 baseline/head 对照均保留原 Turn key,只调用一次 fixture Host。修复后通过重验,再从权威结果读回已接受的产物。
本地持久状态用独立 File 和 SQLite,模型 Host 使用确定性的 fixture。验证在 macOS 完成,未执行 Windows 或真实模型。
改动思路 / Approach
Python 适配器仍负责参数和 transport。TypeScript 既有委托、Turn 和 stop owner 读取锁、Host 和 lease 后裁决,收敛的 helper 不持有新的状态。 在同一模块合并重复的请求读取和发起/结算逻辑,比拆新模块或仅提高行数上限更适合当前范围。 收敛前后比较普通 MCP、启用委托的 MCP 和一次性 CLI。已有配置才注册委托工具,任务和执行范围仍由绑定及授权检查决定。
具体改动 / Changes
评审头 1379f3e,合并基线 bbd2683。2 个文件,+259/−461。 bound MCP and CLI semantics 覆盖工具描述及参数兼容,existing operation and settlement parity 覆盖原轮次、异常优先级和成功结果的独立读回。 委托契约 重构真实路径门
关键代码讲解
- _inspect_request_entry。在原 Goal scope 里查请求及生命周期,只有接收者采用查验才读取 decision。 代码
- _run_turn_once。依次组合 pre、执行参数、post 和 execute。外层指定是否携带 delegated lease 及原 Host 记录。 代码
- _settle_committed_turn。以原 Turn key 在已授权的锁范围重验结算结果,保留原 postcondition 和错误回退。 代码
- _await_host_drain。共享期限轮询。到期可略过一次多余探测,最终结算仍在 _settle_stop 重新读取锁、lane、Host 和 lease。 代码
- Collaboration module metric ratchet。保护同一模块目前的 1792 行以及零 Any 与 Dict Any 指标。 代码
对主干的风险 / Risks
在原委托仍活跃、结果响应丢失或嵌套 Host 尚未清理时,重验、重放或停止。 两端的真实 File/SQLite 恢复保留拒绝原因、原轮次和锁/lease 边界。丢失响应按原轮次读回;晚释放和未证明退出的 Host 保持停止未结算。
语义与 CI 对齐
实际 stdio 启动时,普通 7 个工具与启用委托时 17 个工具的描述、输入、输出 schema 逐项相同。嵌套 Host 停止和权威读回等 32 项在两端先行通过。重跑原会话重验、丢响应、并发读与续租共 24 项,base 与 head 各自通过。标准 premerge 有 6 个直接检查及 13 个选中检查通过。原环境的扩展组两边各 200 通过、6 失败、2 跳过。临时去除委托注册后,真实 MCP 清单探针报错。临时把模块增到 1794 行,实际 ratchet 判定超出 1792 行上限。 原环境的 PYTHONSAFEPATH 让 fixture acceptance.py 无法导入同目录 scenario,两端错误相同。仅针对隔离测试进程移除该变量,保持产品代码、验证器、实际 registry 和输入不变,然后重跑相关用例。 远端 CI 未查询。
我的整体评价 / Verdict
同意当前提交的重构。从当前主干合成无冲突,改动文件在主干与合并基点之间内容一致。 修复、重验、续接和停止继续通过原工具、原权限及原回执回读。 当前缩减了模块体积和重复修改点,保留已验证的长期接续与操作者路径。
English verdict: APPROVE — matched File/SQLite execution, repair, replay and stop checks preserve delegation effect semantics, and the actual MCP schemas match. Exact head 1379f3e.
Summary
loopx/collaboration_mcp.pywithout extracting a new module or altering any public/private contract, MCP tool schema, description, docstring, CLI flag order, lock order, or error message.loopx/collaboration_mcp.pyinloopx/canary/module_metric_baseline.json(lines: 1792,any_count: 0,dict_any_count: 0) so the module cannot creep back toward the 2,000-line ceiling.Line Count & Diff Delta
loopx/collaboration_mcp.pyloopx/canary/module_metric_baseline.json+5lines)2 files)Key Refactorings in
loopx/collaboration_mcp.py_inspect_request_entry: Unifies the three duplicatecollaboration_goal_scope+_entry+decide_collaboration_lifecycle(..., operation="history_inspect")blocks inDelegations.start,_receiver_adopted, and_delegation_bootstrap._run_turn_once&_settle_committed_turn: Consolidates all four"turn", "run-once"CLI invocations (inrevalidateand_execute) and the two committedvalidated_progresssettlement checks while preserving exact argv ordering (pre_args/execution/post_args) anddelegated_lease/host_recordhandling._service_cli_flags&_cli_arguments: Deduplicates repeated--runtime-root/--registry/--goal-id/--agent-idand--format jsonflag construction across_spawn,_cli,_delegated_lease_context, and_execution_arguments._result_error&_record_execution_error: Consolidates six repeatederror/reason/reason_codefallback chains and shared 180-char error recording +_fenced_writeacrossexecuteand_execute._wait_until: Unifies monotonic deadline polling across_signal_worker(SIGTERM/SIGKILL lock wait loops) and_await_host_drain.inboxandpeersimport statements and compacts multi-line boilerplate inregister_collaboration_tools,Delegations, andmain, preserving 100% of@server.tool()signatures, descriptions, docstrings, and invariants.Local Verification (All Run in Isolated Worktree)
uv run --extra test ruff check loopx/collaboration_mcp.py loopx/canary/module_metric_baseline.json— passed.uv run --extra test mypy— passed (no issues found in 17 source files).uv run --extra test loopx check --scan-path loopx/collaboration_mcp.py --scan-path loopx/canary/module_metric_baseline.json— passed (errors=0, warnings=0).pytest(test_maintainability_ratchet.py,test_repository_root.py,test_m6_quality_gates.py,test_control_plane_import_boundaries.py,test_collaboration_mcp.py,test_delegation_preflight.py,test_delegation_stop_recovery.py,test_delegation_lease_lifetime.py,test_delegation_turn_context.py) — 262 passed, 2 skipped.pytestsweep across 39 test files (prior to fast-forward rebase onto zero-overlaporigin/maincommits) — 1,191 passed, 14 skipped.uv run --extra test loopx change-quality record&change-quality verify --repo-path . --base-ref origin/main— passed (receipt_id: cqr_c62e4ce9a0cda0eec871,status: valid).uv run --extra test loopx canary premerge --from-git-diff --git-diff-base origin/main— passed (ok: true,selected=13, failures=0,manual_holds=[]).