Files
codex-app-server/examples/harness2_demo.py
T
host f39ed3654e ci3: lint/mypy 第二阶段清理 + 覆盖率 76% -> 78%(门槛不动)
基底:#251 头 174b631(堆叠于 #242 feat-ci-expand 之上),
基线 origin/main aebc6238;本轨不改 #251 已定语义、不动
workflow 门槛、不删检查、不加 skip。

lint(ruff E,F@120):109 -> 10
- F401 43 -> 0:删未用导入;try/except 双绑定的名字出现
  “打地鼠”(删 except 分支后 try 分支又被标出),两分支
  均已核对正文无引用后清掉;MCP 三模块的 Error 名不删,
  改走 importlib 属性绑定(见下),两路径绑定都保留。
- E702 40 -> 0:全在 host.py main() 的 argparse 段,纯分行,
  tokenize 按分号 token 拆(含 2377 行多行语句只断首个分号);
  一次 5 空格缩进失误已回滚重做并以 ast + 全量 host 测试验证。
- E501 13 -> 0:host.py 5 项随 E702 分行连带清掉;mcp_server
  3 项把描述拆成相邻字面量(AST 比对 24 条工具描述与原值
  完全一致,注意 ruff 按东亚宽度计长,CJK 算 2);test_host
  5 项断开 git commit 参数表。
- E402 8 -> 10:生产侧 2 项清掉(db.py _re、github_app
  _base64 移到顶部,之前无引用、无重名);剩余 10 项全是
  tests/ 的 sys.path 前置 import(6 项旧 + 4 个新测试文件
  沿用同一既定模式),移上去会破坏单文件直跑,有意保留。
- F841 4 -> 0:只去绑定、不删调用(run_task、DB 入队、
  tarfile 上下文、git 提交),各有注释与原测试/新测试覆盖;
  host dispatch_from_branch 新增真实 git 仓库回归测试。
- F811 1 -> 0:server 本地 _row_get 与 peer_messages.row_get
  逐行相同,删本地定义,全部调用点解析到同一 import;
  新增 test_server_row_get(同一对象 + 三路行为)。

mypy(生产范围):24 -> 0,零新增 type: ignore
- no-redef 9 -> 0:MCP 三模块 try/except 两次 from-import
  改 importlib.import_module + 属性绑定(cloud 优先、flat
  copy 回落、内层 ImportError 同样回落,语义与原来一致;
  flat-copy 子进程测试证实回落后 __module__ 为顶层名);
  server _row_get 随 F811 消除。
- arg-type 10 -> 0:harness2_tasks shared 改 TypedDict
  逐键精确类型;CodexProbeAdapter 补 no-op validate_tree
  (_adapter_validate 本就跳过缺失方法,行为一致)。
- var-annotated 3 -> 0:sub2api _SHARED_ADMIN/_login_slots、
  verify-multiuser RESULTS 加精确注解。
- assignment/misc 2 -> 0:marker_tools ZoneInfo 先声明
  Any 再 try import(草稿先验 mypy 通过)。

bandit:总数 286 不变,High 仍 4 项,全在 host.py,本轨不改
(属第 3 项白名单轨范围),只做 triage:
- 1319 run_verify:无插值,整串验测命令,管道/&& 须 shell
  语义(新增 test_host_run_verify 断言管道与 && 真实生效)。
- 1497 notify:模板来自算子配置,三处插值全部 shlex.quote,
  证据为既有 test_notify_failure_quotes_shell_metacharacters
  (; touch 与 $(touch ) 不执行)。
- 2099/2103 goal verify:无插值,任务配置验测串,同 run_verify。
- 无新增 High;pip-audit 0 漏洞。

覆盖率(同口径三套件 coverage 计量):75.96% -> 77.87%
(22392 行/缺 5385 -> 22437 行/缺 4963,显示 76% -> 78%)
- client.py 0% -> 90%(pipe 假子进程 + main 分支)
- run_parallel.py 0% -> 97%、migrate 包装 0% -> 95%
- playwright_mcp 37% -> 62%、imagegen_mcp 47% -> 79%、
  websearch_mcp 51% -> 86%、deploy.py 56% -> 77%
- verify-multiuser 0% -> 27%(仅 check/req helper;main()
  是主机侧真实多用户实弹验证,按门禁不建生产任务、
  不以 mock 冒充,仍为缺口)
- host.py 55% -> 57%(文件 2020 -> 2060 行系 E702 分行
  的计量口径变化,非代码膨胀)
- 未到 85%:门槛保持 75% 不动,不删低覆盖模块出统计口径;
  缺口主力仍是 server.py / worker.py / host.py 大文件,
  下一阶段须针对性深测,非本轨快赢可及。

验证:三套件 1576 -> 1629 项全过(tests 127、cloud/tests
1449 skipped=4、deploy/tests 53);ruff E9 通过;mypy 0;
bandit High 4(同上);pip-audit 0 漏洞;试跑产物已删,
提交后工作树干净。
2026-11-03 02:48:54 +00:00

138 lines
5.6 KiB
Python

"""Harness² 融合演示:不花模型钱,跑通一轮完整改进。
用法(在项目根目录):
python3 examples/harness2_demo.py --mode parallel --k 1
python3 examples/harness2_demo.py --mode sequential --k 1 --output /tmp/h2demo
任务是对账本求和。base harness 的脚本只加正数(账本含一笔负数 credit,
base 会漏掉它);确定性编辑器去掉正数过滤;选择器按产物挑带符号和;
反思器把“正负都要算”写进经验库。跑完打印:被采纳的产物、回落情况、
经验库条目位置。真实接线时,这里的三个确定性类换成 codex 任务
(见 docs/harness2.md),执行器换成 Worker 的任务执行,循环本身不变。
"""
import argparse
import subprocess
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from cloud.harness2 import ( # noqa: E402
EditResult, Library, Rollout, improve_task, read_tree, write_tree,
)
BASE_SCRIPT = """import csv
import sys
from decimal import Decimal
with open(sys.argv[1]) as f:
amounts = [Decimal(r['amount']) for r in csv.DictReader(f)]
print(f"Total: {sum((a for a in amounts if a > 0), Decimal(0)):.2f}")
"""
BASE_TREE = {
"AGENTS.md": "Use scripts/summarize.py to total the ledger.\n",
"scripts/summarize.py": BASE_SCRIPT,
}
class LedgerAdapter:
task_id = "ledger-1"
domain = "accounting"
prompt = "Sum every signed amount in ledger.csv. Return Total: with two decimals."
def __init__(self, root):
self.root = Path(root)
self.root.mkdir(parents=True, exist_ok=True)
self.ledger = self.root / "ledger.csv"
self.ledger.write_text("amount\n100.25\n-20.10\n5.00\n", encoding="utf-8")
self.executions = 0
def base_harness(self):
return dict(BASE_TREE)
def execute(self, label, harness):
self.executions += 1
work = self.root / "runs" / label
work.mkdir(parents=True, exist_ok=True)
write_tree(harness, work / "harness")
proc = subprocess.run(
[sys.executable, str(work / "harness" / "scripts" / "summarize.py"),
str(self.ledger)], capture_output=True, text=True, timeout=10)
out = proc.stdout.strip()
return Rollout(label=label, ok=proc.returncode == 0,
delivered=out.startswith("Total:"), deliverable_text=out,
trajectory="[ACTION] Run scripts/summarize.py\n[OBSERVATION]\n" + out,
cost_usd=0.01)
def validate_tree(self, harness):
if "scripts/summarize.py" not in harness:
raise ValueError("The local executor requires scripts/summarize.py")
class FixEditor:
def edit(self, mission, context_dir, label):
harness_dir = Path(context_dir) / "harness"
script = harness_dir / "scripts" / "summarize.py"
script.write_text(script.read_text().replace(" if a > 0", ""), encoding="utf-8")
return EditResult(tree=read_tree(harness_dir),
notes="Keep signed amounts: the base total omitted credits.")
class PickSignedSelector:
def select(self, mission, context_dir):
for path in sorted((Path(context_dir) / "candidates").glob("*.md")):
if "Total: 85.15" in path.read_text():
return path.stem, "The signed total matches the source ledger.", 0.0
raise ValueError("no candidate with the signed total")
class LedgerReflector:
def reflect(self, mission, context_dir):
root = Path(context_dir)
changed = (root / "harness" / "scripts" / "summarize.py").read_text() != (
root / "base_harness" / "scripts" / "summarize.py").read_text()
if not changed:
return {}
return {
"cue": "When a ledger includes credits and debits",
"lesson": "Include both signs when summing in scripts/summarize.py.",
"evidence": "Removing the positive-only filter changed the probe total to "
"include the credits omitted by the base trajectory.",
"confidence": "high for this observed arithmetic contrast",
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--mode", default="parallel", choices=["parallel", "sequential"])
ap.add_argument("--k", type=int, default=1)
ap.add_argument("--output", default="")
args = ap.parse_args()
tmp = None
root = Path(args.output) if args.output else Path(tempfile.mkdtemp(prefix="h2demo-"))
if not args.output:
tmp = root
adapter = LedgerAdapter(root)
library = Library(root / "library", "accounting")
result = improve_task(adapter, FixEditor(), selector=PickSignedSelector(),
reflector=LedgerReflector(), work_dir=root / "work",
k=args.k, mode=args.mode, library=library)
chosen = result.mode_result.rollouts[result.selection.chosen_label]
print(f"mode={result.mode} k={args.k} ok={result.ok}")
print(f"executions={adapter.executions} (base + candidates + finals)")
print(f"chosen={result.selection.chosen_label} deliverable={chosen.deliverable_text}")
print(f"fell_back={result.mode_result.fell_back or 'none'}")
print(f"library_entry={result.library_entry}")
print(f"experience={result.experience.get('lesson', '(none)')}")
print(f"work_dir={root}")
assert chosen.deliverable_text == "Total: 85.15", "demo must end at the signed total"
assert result.library_entry is not None, "demo must enter the library"
print("demo OK: signed total adopted and stored in the library")
_ = tmp
if __name__ == "__main__":
main()