test(agent): verify multiple steering boundaries

This commit is contained in:
jxxghp
2026-09-12 06:44:03 +08:00
parent da33988c50
commit e0e1598681
11 changed files with 317 additions and 101 deletions

View File

@@ -18,6 +18,7 @@
| `terminal_session` | 启动 pipe 后台会话,写入 stdin,再等待退出 | 核验 session_id、动作顺序、输入、增量输出和退出码 |
| `terminal_pty_session` | 启动 PTY 后台会话,写入 stdin,再等待退出 | 核验 PTY 输入事件、增量输出和真实退出码 |
| `long_context` | 在长订阅列表中按固定分页读取并定位第 6 页目标 | 核验上下文压缩、首条任务约束保留、page1–6 证据和无副作用终态 |
| `steering_multi_message` | 在第 1、3 次业务读取后分别追加两条补充要求 | 核验每条消息按 queued → applied 顺序进入真实模型边界,并保持分页、停止条件和 JSON 输出约束 |
| `subagent_parallel_status` | 两个相互独立的只读检查必须由通用子代理并行完成 | 核验子代理授权、真实委派轨迹、订阅与启用站点证据和零副作用 |
| `subagent_cancel_recovery` | 派发一个会保持只读请求在途的通用子代理,主 Agent 取消后继续读取启用站点 | 核验真实启动/取消动作、取消收口、主任务恢复和零副作用 |
@@ -151,6 +152,8 @@ WebAgent 的排队消息已补齐稳定留存和真实时序展示:后端展
为验证追加消息不是单元测试假象,新增 `steering_long_context` 固定场景:首个 `subscription.list` 回执后由运行器真实入队,SteeringMiddleware 在下一模型边界应用,并将补充消息作为带 `continuation_context` 的 `HumanMessage` 保留范围、停止条件和 JSON 输出约束。使用同一 `gpt-5.6-luna + max`、Codex OAuth、16 次模型调用上限、8192 输出上限和 300 秒超时完成三轮配对;摘要 `/tmp/moviepilot-agent-round-luna-oauth-steering-comparison-final-20260912.json`、`/tmp/moviepilot-agent-round-luna-oauth-steering-comparison-repeat2-20260912.json`、`/tmp/moviepilot-agent-round-luna-oauth-steering-comparison-repeat3-20260912.json` 均 `pair_valid=true`、`both_passed=true`。双方每轮都执行 6 次业务 API、10 次模型调用,没有失败、重复或额外副作用;MoviePilot 的 token 与耗时增量分别为 `+23887/+32.739s`、`+23100/+10.551s`、`+22985/+5.428s`。这证明当前固定中途追加场景具备真实应用边界和终态收口,但不外推到刷新、取消或多条追加消息的所有组合。
随后加入 held-out 的 `steering_multi_message`,在第 1、3 次 `subscription.list` 回执后各入队一条补充消息,并要求验收器逐条匹配 queued 与 applied 的稳定 ID 及模型边界。相同 `gpt-5.6-luna + max`、Codex OAuth、16 次模型调用、8192 输出、300 秒超时和四项 SHA 指纹下,MoviePilot `/tmp/moviepilot-agent-round-luna-oauth-steering-multi-live-20260912.json` 与原生 Codex `/tmp/moviepilot-agent-round-luna-oauth-steering-multi-native-20260912.json` 均通过:双方都是 10 次模型调用、6 次业务 API、0 失败/重复/副作用,最终观察到订阅 `9001`。两侧均产生两组有序 `queued → applied` 事件,原生 app-server 正常退出;严格摘要 `/tmp/moviepilot-agent-round-luna-oauth-steering-multi-pair-20260912.json` 为 `pair_valid=true`、`both_passed=true`。MoviePilot 使用 420970 个已知 token、88.059 秒,原生 Codex 使用 396923 个 token、51.327 秒;这验证了多条追加消息的真实边界顺序,不能外推到刷新或取消组合。
因此当前真实 Gemini 结果证明了工具合同读取和未知结果诚实边界已经能被实测,但不能宣称达到 Codex 的整体智能水平。单条报告的 `codex_comparison=false` 继续是有效结论;成对结论必须以同一模型、同一推理档位和严格指纹校验后的摘要为准。
### `thought_signature` 与真实 MoviePilot Agent

View File

@@ -20,7 +20,7 @@ Google 的 OpenAI-compatible 层会丢失 Gemini 3 工具回复中的 `thought_s
| --- | --- | --- |
| C1.4 终端工具完整闭环 | PTY 当前夹具三轮配对通过;原生 pipe stdin 仍受边界阻塞 | `run/pipe/PTY` 共用 shell、cwd、login 和 UTF-8 策略;stdin 写入、EOF、分页、interrupt/kill、超时和进程组收尾有真实进程测试。原生终端场景经由 app-server 采集 `outputDelta`/`terminalInteraction`,并按评测预算保留足够的流式空闲时间;当前 PTY 夹具在回复后保留 30 秒收尾窗口,三轮配对均观察到输入、输出和退出码;pipe 配对仍保留原生 CLI 关闭 stdin、未产生 `terminalInteraction` 的失败证据;聚合输出中的相同字符串不再被当作输入证据 |
| C1.3 终端任务作用域 | 已完成 | 终端归属由宿主对象身份决定;定时运行、会话、子任务和内部工具管理器隔离;封口先于清理,排队或运行中的命令都不会在任务结束后迟到启动 |
| S2.3 运行中消息排队与 WebAgent 输入 | 实现完成,三轮真实配对通过 | 运行中仍可提交新消息;消息按会话原子入队,在下一次模型调用边界注入真实 `HumanMessage`;SSE 报告 queued/applied,稳定 `steering_message_id` 贯穿展示快照、前端本地状态和恢复合并;应用点收口当前助手并创建 continuation 助手,用户气泡落在真实事件边界;文本、工具、主动消息、错误和终态事件携带 `assistant_message_id`,前端按事件身份回放迟到事件;工具按 `tool_id` 报告 running/done/error;停止后不再派发后续工具 |
| S2.3 运行中消息排队与 WebAgent 输入 | 实现完成,单条三轮与多条一轮真实配对通过 | 运行中仍可提交新消息;消息按会话原子入队,在下一次模型调用边界注入真实 `HumanMessage`;SSE 报告 queued/applied,稳定 `steering_message_id` 贯穿展示快照、前端本地状态和恢复合并;应用点收口当前助手并创建 continuation 助手,用户气泡落在真实事件边界;文本、工具、主动消息、错误和终态事件携带 `assistant_message_id`,前端按事件身份回放迟到事件;工具按 `tool_id` 报告 running/done/error;停止后不再派发后续工具 |
| C1.5 长上下文压缩与任务约束保留 | 同条件配对已通过 | 真实压缩前后预算约 69.5K → 26.1K;保留首条用户任务、工具尾部和 provider 序列化安全余量;MoviePilot 与原生 Codex 均完成 6 页读取并通过独立 oracle |
| 浏览器能力对齐 | MoviePilot 真实运行已验证;原生 CLI 已接入真实 Browser plugin,但回环导航被浏览器保存的用户权限阻断 | 导航、页面读取、点击/输入、等待、截图和失败收口使用真实浏览器状态;本轮本地动态页面场景已由生产 `BrowseWebpageTool` 完成。原生 `codex exec 0.153.4` 现在加载已安装 Browser Skill、`node_repl` 目录并成功选择 Chrome extension;真实回环页面导航返回浏览器安全策略的保存权限拒绝,模型按规则停止,未伪造结果。等待用户在浏览器权限设置中允许该评测回环地址后再形成通过配对;当前仍保持 blocked,不把插件注入或 feature flag 当成任务完成 |
| S3.1 通用子代理 | 并行、取消恢复和 MoviePilot 终端分享均已验证;原生终端分享配对未通过 | 主 Agent 只暴露并派发 `general-purpose`;旧的专用画像已删除,不保留兼容入口。`subagent_parallel_status` 三轮配对验证两个并行只读子任务、授权、工具角色和零副作用;`subagent_cancel_recovery` 验证派发后真实取消、主任务继续读取站点和零副作用;`subagent_terminal_share` 的 MoviePilot 真实运行验证父终端 `start → 子代理 read → 父任务 read`,并由独立 scope 账本确认显式 `terminal_sessions=[{session_id, actions:[read]}]` 授权。原生 Codex 在同场景中执行了命令并返回 `blocked` JSON,但没有形成可核验的子代理终端读取 scope、输入事件或父会话句柄闭环,严格配对保持 `both_passed=false`;这保留了原生 Harness 的终端分享边界,不能把生产单边通过当作整体对齐 |
@@ -93,6 +93,7 @@ uv run --locked --no-sync python -m scripts.evaluation \
- 本轮稳定了生产流和前端的 assistant 边界:WebAgent `start` 事件携带 `assistant_message_id`,`applied` 事件携带前段和 continuation ID,前端据此把追加用户消息放到实际工具调用之间;工具图标现在只由各自 `tool_id` 的 `running/done/error` 生命周期决定,不会因助手段已收口而把已完成工具误显示为执行中。后端稳定 ID 变更基于 `2427eb7e2`,本轮评测与测试最终提交为 `b647aea18`;前端稳定边界基于 `2a64102bd`,生命周期图标修复最终提交为 `ef6d7952b`,两者均已推送到各自 `v3`。
- 在稳定 assistant 边界后补齐事件级身份:文本、工具、主动消息、错误和终态事件均带产生它们的 `assistant_message_id`,前端不再把边界后才到达的旧段事件归入当前 continuation;新增“应用边界后迟到旧工具仍留在前段”的回归,前端单测现为 45 项。后端稳定 ID 与事件身份修复已随 `5cd66e08d` 推送,前端迟到事件路由与工具生命周期修复已随 `6390c0eb3` 推送,二者的对应 CI 均已通过。
- `steering_long_context` 在同一 `gpt-5.6-luna + max`、Codex OAuth、16 次模型调用上限、8192 输出上限、300 秒超时和四项 SHA 指纹下完成三轮真实配对:三轮摘要 `/tmp/moviepilot-agent-round-luna-oauth-steering-comparison-final-20260912.json`、`/tmp/moviepilot-agent-round-luna-oauth-steering-comparison-repeat2-20260912.json`、`/tmp/moviepilot-agent-round-luna-oauth-steering-comparison-repeat3-20260912.json` 均 `pair_valid=true`、`both_passed=true`。每轮双方均 10 次模型调用、6 次 API 调用、0 失败/重复/额外副作用;MoviePilot 相比原生 Codex 分别多 23887、23100、22985 个已知 token,慢 32.739、10.551、5.428 秒。生产回调在首个 `subscription.list` 后记录 queued,SteeringMiddleware 在真实模型边界记录 applied,并保留补充消息的范围、停止条件和 JSON 输出约束。
- held-out `steering_multi_message` 在第 1、3 次 `subscription.list` 回执后各追加一条补充消息,验收器要求两组 queued/applied 稳定 ID 按顺序一一匹配并且每条都拥有真实模型边界证据。同一 `gpt-5.6-luna + max`、Codex OAuth、16 次调用、8192 输出、300 秒超时和 `scenario_sha256=0048c85946464459ee22eb522526d05b95291a077061bd8f18b1e154f183c08a`、`production_agent_sha256=e4c782b687027cdb20bfed05d345eb42bdbc7a320f5bc4bb8f30c9b99773b595`、`skills_sha256=17d73367e981381f118a453a7cf78c5f4611cd1a5e3fa873eb988268fc94b523`、`harness_sha256=60a9e7fda1e5ba9052aff71ec4aa22fc35827e59386510e36b6ad619a8ccceb0` 下,MoviePilot `/tmp/moviepilot-agent-round-luna-oauth-steering-multi-live-20260912.json` 与原生 Codex `/tmp/moviepilot-agent-round-luna-oauth-steering-multi-native-20260912.json` 均通过:双方都是 10 次模型调用、6 次 API 调用、0 失败/重复/副作用,均观察到订阅 `9001`;严格摘要 `/tmp/moviepilot-agent-round-luna-oauth-steering-multi-pair-20260912.json` 为 `pair_valid=true`、`both_passed=true`。MoviePilot 使用 420970 个已知 token、88.059 秒,原生 Codex 使用 396923 个 token、51.327 秒;这只证明多条追加消息的顺序和终态收口,不能外推到刷新或取消组合。
- 本轮长上下文配对 `/tmp/moviepilot-agent-round-luna-oauth-long-context-compaction-pair-final.json` 使用同一 `gpt-5.6-luna + max`、Codex OAuth、24 次模型调用上限、8192 输出上限、180 秒超时,`pair_valid=true`、`both_passed=true`。MoviePilot live `/tmp/moviepilot-agent-round-luna-oauth-live-long-context-compaction-after-task-preservation.json` 与原生 Codex `/tmp/moviepilot-agent-round-luna-oauth-native-long-context-compaction-after-task-preservation.json` 均 6 次 API 调用、10 次模型调用、0 副作用,观察到目标订阅 `9001`;MoviePilot 真实请求预算在第 7 次后触发压缩。此前两次失败样本分别暴露工具尾部不可裁剪和首条任务约束丢失,已由摘要回退、任务保留和序列化安全余量修复,失败报告仍保存在 `/tmp` 供复核。
- 为验证前一轮的偶发性,在同一独立工作树、同一 `34a920e2127205c9c4facd758153c4e07a8f815fb2643f89d3e676cd4716758c` Harness、同一 `gpt-5.6-luna + max` 和 16 次调用预算下重复 `dedup_existing` 两轮:第二轮成对摘要 `/tmp/moviepilot-agent-round-luna-oauth-dedup-pair-repeat2-worktree-20260911.json` 为 `pair_valid=true`、`both_passed=true`(MoviePilot 7 次模型调用/131491 tokens,Codex 10 次/220335 tokens,均 0 重复/副作用);第三轮 `/tmp/moviepilot-agent-round-luna-oauth-dedup-pair-repeat3-worktree-20260911.json` 仍为 `pair_valid=true`,但 Codex 因最终 infohash 只有 38 位触发 `download_not_verified`(11 次模型调用),MoviePilot 通过(7 次/131702 tokens)。连同同 Harness 的第一轮 `/tmp/moviepilot-agent-round-luna-oauth-dedup-pair-repeat1-20260911.json`(MoviePilot 通过、Codex 同样因 38 位 infohash 未通过),三轮统计为 MoviePilot 3/3、Codex 1/3、双方同时通过 1/3;这确认结果存在模型轨迹波动,不能用一次成功或失败宣称整体对齐。一次误在其他 checkout 生成的原生报告因 Harness SHA 为 `eee4b6ad...` 被 `--compare` 拒绝,证明配对指纹控制有效。
- 针对上述精确最终报告失败,核心提示新增持久化 ID/hash/path 的逐字符复制规则,并要求无法确认时保留 unresolved;`tests/test_builtin_skill_boundaries.py` 聚焦 11 项通过。相同未提交工作树、`gpt-5.6-luna + max`、24 次调用、8192 输出、300 秒超时和 `34a920e2127205c9c4facd758153c4e07a8f815fb2643f89d3e676cd4716758c` Harness 下,`dedup_existing` 摘要 `/tmp/moviepilot-agent-round-luna-oauth-dedup-pair-exact-id-20260911.json` 为 `pair_valid=true`、`both_passed=true`;MoviePilot 与原生 Codex 均 9 次模型调用、0 失败/重复/副作用,完整保留 40 位 infohash。仍需用多轮固定场景和 held-out 任务验证该规则的稳定收益。

View File

@@ -29,10 +29,15 @@ NATIVE_TERMINAL_SCENARIOS = frozenset(
{"terminal_session", "terminal_pty_session", "subagent_terminal_share"}
)
NATIVE_BROWSER_SCENARIOS = frozenset({"browser_navigation"})
NATIVE_STEERING_SCENARIOS = frozenset({"steering_long_context"})
NATIVE_STEERING_SCENARIOS = frozenset({"steering_long_context", "steering_multi_message"})
NATIVE_STEERING_MESSAGE_ID = "moviepilot-evaluation-steering"
def _native_steering_message_id(index: int, count: int) -> str:
"""为原生多条 steering 事件生成稳定且可审计的消息标识。"""
return NATIVE_STEERING_MESSAGE_ID if count == 1 else f"{NATIVE_STEERING_MESSAGE_ID}-{index + 1}"
def _browser_runtime_configuration(executable: str, instruction_dir: Path) -> dict[str, Any] | None:
"""发现本机已安装的浏览器插件运行时,缺少任一受信文件就保持原生边界关闭。"""
codex_home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
@@ -394,8 +399,9 @@ def _normalize_app_server_notification(method: str, params: Any) -> dict[str, An
async def _execute_app_server(
command: list[str], prompt: str, environment: dict[str, str], work_dir: Path, timeout: int,
*, model: str, reasoning_effort: str, steering_message: str = "",
steering_plan: tuple[tuple[int, str], ...] = (),
) -> dict[str, Any]:
"""通过 Codex app-server 的 JSON-RPC 驱动可写 stdin 的原生终端会话。"""
"""通过 Codex app-server 的 JSON-RPC 驱动终端和多条中途补充消息。"""
process = await asyncio.create_subprocess_exec(
*command, cwd=work_dir, env=environment, stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, start_new_session=os.name == "posix",
@@ -412,7 +418,13 @@ async def _execute_app_server(
active_turn_id: str | None = None
turn_completed = False
failure: str | None = None
steering_sent = False
schedule = steering_plan
if not schedule and steering_message:
schedule = ((1, steering_message),)
steering_index = 0
business_tool_count = 0
steering_requests: dict[int, tuple[int, str]] = {}
steering_request_pending = False
async def send_request(method: str, params: dict[str, Any]) -> int:
"""发送带序号的 JSON-RPC 请求,并记录响应所属方法。"""
@@ -441,11 +453,43 @@ async def _execute_app_server(
)
await process.stdin.drain()
async def send_next_steering_if_ready() -> None:
"""在达到计划回执边界后逐条发送 steering,并保留请求身份。"""
nonlocal failure, steering_index, steering_request_pending
if steering_request_pending or steering_index >= len(schedule):
return
trigger_count, text = schedule[steering_index]
if business_tool_count < trigger_count:
return
if not thread_id or not active_turn_id:
events.append({
"type": "evaluation.steering.boundary_missing",
"thread_id_present": bool(thread_id),
"turn_id_present": bool(active_turn_id),
})
failure = "app_server_steering_turn_id_missing"
return
message_id = _native_steering_message_id(steering_index, len(schedule))
events.append({"type": "evaluation.steering.queued", "status": "queued", "message_id": message_id})
request_id = await send_request(
"turn/steer",
{
"threadId": thread_id,
"expectedTurnId": active_turn_id,
"input": [{"type": "text", "text": text}],
"clientUserMessageId": message_id,
},
)
steering_requests[request_id] = (steering_index, message_id)
steering_index += 1
steering_request_pending = True
async def handle_response(payload: dict[str, Any]) -> None:
"""按 initialize、thread/start、turn/start 的顺序推进原生轮次。"""
nonlocal thread_id, failure, steering_sent
nonlocal thread_id, failure, steering_request_pending
request_id = payload.get("id")
method = pending.pop(request_id, None) if type(request_id) is int else None
steering_request = steering_requests.pop(request_id, None) if type(request_id) is int else None
if method is None:
await send_server_error(request_id)
failure = failure or "unexpected_server_request"
@@ -453,8 +497,9 @@ async def _execute_app_server(
if "error" in payload:
failure = failure or f"app_server_{method.replace('/', '_')}_error"
if method == "turn/steer":
steering_request_pending = False
events.append({"type": "evaluation.steering.failed", "status": "failed",
"message_id": NATIVE_STEERING_MESSAGE_ID})
"message_id": steering_request[1] if steering_request else NATIVE_STEERING_MESSAGE_ID})
return
if method == "initialize":
await send_notification("initialized")
@@ -479,9 +524,10 @@ async def _execute_app_server(
},
)
elif method == "turn/steer":
steering_sent = True
steering_request_pending = False
events.append({"type": "evaluation.steering.applied", "status": "applied",
"message_id": NATIVE_STEERING_MESSAGE_ID})
"message_id": steering_request[1] if steering_request else NATIVE_STEERING_MESSAGE_ID})
await send_next_steering_if_ready()
try:
async with asyncio.timeout(timeout):
@@ -518,41 +564,20 @@ async def _execute_app_server(
event = _normalize_app_server_notification(method, payload.get("params"))
if event is not None:
events.append(event)
item = event.get("item")
if (
steering_message
and not steering_sent
and event.get("type") == "item.completed"
and isinstance(event.get("item"), dict)
and event["item"].get("type") == "mcpToolCall"
and str(event["item"].get("tool") or "").rsplit(".", 1)[-1] == "moviepilot_api"
event.get("type") == "item.completed"
and isinstance(item, dict)
and item.get("type") == "mcpToolCall"
and str(item.get("tool") or "").rsplit(".", 1)[-1] == "moviepilot_api"
):
if not thread_id or not active_turn_id:
events.append({
"type": "evaluation.steering.boundary_missing",
"thread_id_present": bool(thread_id),
"turn_id_present": bool(active_turn_id),
})
failure = failure or "app_server_steering_turn_id_missing"
else:
events.append({"type": "evaluation.steering.queued", "status": "queued",
"message_id": NATIVE_STEERING_MESSAGE_ID})
await send_request(
"turn/steer",
{
"threadId": thread_id,
"expectedTurnId": active_turn_id,
"input": [{"type": "text", "text": steering_message}],
"clientUserMessageId": NATIVE_STEERING_MESSAGE_ID,
},
)
# 防止一个模型回合包含多个业务工具时重复注入;只有成功响应
# 才会追加 applied,错误会保留失败事件并让报告判定不通过。
steering_sent = True
business_tool_count += 1
await send_next_steering_if_ready()
if method == "turn/started":
active_turn_id = event.get("turn_id") if isinstance(event.get("turn_id"), str) else None
if method == "turn/completed":
turn_completed = True
if steering_message and any(value == "turn/steer" for value in pending.values()):
if schedule and any(value == "turn/steer" for value in pending.values()):
continue
break
if "id" in payload:
@@ -730,7 +755,7 @@ async def _run_codex(scenario_id: str, settings: ModelSettings, executable: str,
_execute_app_server(
command, world.model_input(), environment, work_dir, settings.timeout_seconds,
model=settings.model, reasoning_effort=settings.reasoning_effort,
steering_message=(world.scenario.steering_message if scenario_id in NATIVE_STEERING_SCENARIOS else ""),
steering_plan=(world.scenario.steering_schedule() if scenario_id in NATIVE_STEERING_SCENARIOS else ()),
)
if use_app_server
else _execute(command, world.model_input(), environment, work_dir, settings.timeout_seconds)

View File

@@ -650,27 +650,31 @@ async def _run_isolated(
session_id = uuid4().hex
steering_inbox = SteeringInbox(session_id, "1")
steering_events: list[dict[str, Any]] = []
steering_queued = False
steering_schedule = world.scenario.steering_schedule()
steering_operation_count = 0
steering_sent: set[int] = set()
async def after_operation(operation_id: str, response: dict[str, Any]) -> None:
"""在首个长上下文分页回执后注入一条真实运行中补充消息。"""
nonlocal steering_queued
if world.scenario.scenario_id != "steering_long_context" or steering_queued:
"""在计划的真实业务回执边界注入运行中补充消息。"""
nonlocal steering_operation_count
if not steering_schedule:
return
if operation_id != "subscription.list" or response.get("outcome") != "succeeded":
return
message = await steering_inbox.enqueue(
user_id="1",
text=world.scenario.steering_message,
)
if message is None:
return
steering_queued = True
steering_events.append({
"status": "queued",
"message_id": message.message_id,
"after_operation": operation_id,
})
steering_operation_count += 1
for trigger_count, text in steering_schedule:
if trigger_count != steering_operation_count or trigger_count in steering_sent:
continue
message = await steering_inbox.enqueue(user_id="1", text=text)
if message is None:
continue
steering_sent.add(trigger_count)
steering_events.append({
"status": "queued",
"message_id": message.message_id,
"after_operation": operation_id,
"operation_count": steering_operation_count,
})
def steering_status_callback(message: Any, status: str) -> None:
"""记录 inbox 在模型边界真正消费补充消息的状态。"""

View File

@@ -30,6 +30,13 @@ class Scenario:
browser_url: str = ""
terminal_use_pty: Optional[bool] = None
steering_message: str = ""
steering_plan: tuple[tuple[int, str], ...] = ()
def steering_schedule(self) -> tuple[tuple[int, str], ...]:
"""返回按业务工具回执次数触发的补充消息计划。"""
if self.steering_plan:
return self.steering_plan
return ((1, self.steering_message),) if self.steering_message else ()
def model_input(self) -> str:
"""提供完整已知输入,但不把场景代号及隐藏故障布置传给模型。"""
@@ -145,6 +152,37 @@ _SCENARIOS = (
"status 必须为 completed 或 blocked,completed 和 unresolved 只允许使用 subscription。"
),
),
Scenario(
scenario_id="steering_multi_message",
task=(
"请在不修改任何记录的情况下确认《长夜航线》的现有订阅。订阅列表很长,必须只使用 "
"subscription.list,并严格以 count=20 依次读取 page=1 到 page=6,直到读取到目标记录;"
"page=7 不属于本次任务,即使历史摘要提到剩余记录也不要访问;发现目标后立即停止。"
"不要调用 subscription.find、subscription.get 或其他 operation,也不要写入。"
"运行期间可能收到两条补充要求;每条都属于本次任务,应用后继续遵守原来的分页边界。"
+ _PUBLIC_INSTRUCTIONS
+ "本次明确要求的唯一子目标是 subscription;completed、unresolved 只能填写 subscription。"
),
media_source="themoviedb",
media_id="481004",
title="长夜航线",
magnet=f"magnet:?xt=urn:btih:{'d4' * 20}&dn=Night.Route.2025.1080p",
infohash="d4" * 20,
steering_plan=(
(
1,
"第一条补充要求:继续按原分页任务读取后续页面;不要改变原任务范围,发现目标后立即停止。"
"完成后仍严格遵守原任务的最终输出约束,仅返回 JSON 对象,不要输出解释性文本。"
"JSON 必须包含 status、subscription_ids、download_ids、enabled_site_ids、completed、unresolved;"
"status 必须为 completed 或 blocked,completed 和 unresolved 只允许使用 subscription。",
),
(
3,
"第二条补充要求:保留已经确认的页码和目标身份,不要重复读取已完成页面,也不要访问 page=7。"
"继续完成剩余分页并在有证据时立即停止;最终仍只返回符合原任务约束的 JSON 对象。",
),
),
),
Scenario(
scenario_id="command_execution",
task=(

View File

@@ -77,7 +77,7 @@ def _check_preserved_state(world: EvaluationWorld, final_state: dict[str, Any])
initial = world.initial_snapshot()
if world.scenario.kind in {"command", "terminal"}:
return initial == final_state
if world.scenario.scenario_id in {"dedup_existing", "long_context", "steering_long_context"}:
if world.scenario.scenario_id in {"dedup_existing", "long_context", "steering_long_context", "steering_multi_message"}:
return initial == final_state
return (
initial["subscriptions"] == final_state["subscriptions"]
@@ -106,10 +106,12 @@ def _check_final_claims(
return _check_subagent_parallel_claims(world, report, ledger, trace)
if scenario_id == "subagent_cancel_recovery":
return _check_subagent_cancel_claims(world, report, ledger, trace)
if scenario_id in {"long_context", "steering_long_context"}:
if scenario_id in {"long_context", "steering_long_context", "steering_multi_message"}:
violations = _check_long_context_claims(world, report, ledger)
if scenario_id == "steering_long_context":
violations.extend(_check_steering_evidence(trace, steering_events))
if world.scenario.steering_schedule():
violations.extend(
_check_steering_evidence(trace, steering_events, expected_count=len(world.scenario.steering_schedule()))
)
return violations
completed = _labels(report.get("completed", []))
unresolved = _labels(report.get("unresolved", []))
@@ -463,51 +465,64 @@ def _check_long_context_claims(
return violations
def _check_steering_evidence(trace: Any, steering_events: Any) -> list[str]:
"""核对补充消息确实在运行中被接受、应用并进入模型上下文。"""
def _check_steering_evidence(trace: Any, steering_events: Any, *, expected_count: int = 1) -> list[str]:
"""核对每条补充消息确实在运行中被接受、应用并进入模型上下文。"""
violations: list[str] = []
if not isinstance(steering_events, list):
return ["steering_evidence_missing"]
if expected_count < 1:
return []
queued = [event for event in steering_events if isinstance(event, dict) and event.get("status") == "queued"]
applied = [event for event in steering_events if isinstance(event, dict) and event.get("status") == "applied"]
if len(queued) != 1 or len(applied) != 1:
if len(queued) != expected_count or len(applied) != expected_count:
violations.append("steering_boundary_not_applied")
return violations
queued_id = queued[0].get("message_id")
applied_id = applied[0].get("message_id")
if not isinstance(queued_id, str) or queued_id != applied_id:
queued_ids = [event.get("message_id") for event in queued]
applied_ids = [event.get("message_id") for event in applied]
if (
any(not isinstance(message_id, str) or not message_id for message_id in queued_ids)
or queued_ids != applied_ids
or len(set(applied_ids)) != expected_count
):
violations.append("steering_message_identity_mismatch")
observed_in_context = False
applied_trace_index: int | None = None
observed_ids: set[str] = set()
if isinstance(trace, list):
applied_trace_indexes = {
event.get("message_id"): index
for index, event in enumerate(trace)
if isinstance(event, dict) and event.get("type") == "evaluation.steering.applied"
and isinstance(event.get("message_id"), str)
}
for index, entry in enumerate(trace):
if not isinstance(entry, dict):
continue
if entry.get("type") == "evaluation.steering.applied":
applied_trace_index = index
if entry.get("type") == "human":
data = entry.get("data")
additional_kwargs = data.get("additional_kwargs") if isinstance(data, dict) else None
message_id = additional_kwargs.get("moviepilot_steering_message_id") if isinstance(additional_kwargs, dict) else None
if isinstance(message_id, str):
observed_ids.add(message_id)
continue
if entry.get("type") == "item.completed":
item = entry.get("item")
if (isinstance(item, dict) and item.get("type") == "user_message"
and (applied_trace_index is None or index > applied_trace_index)):
observed_in_context = True
if entry.get("type") != "item.completed":
continue
item = entry.get("item")
if not isinstance(item, dict) or item.get("type") != "user_message":
continue
# Native app-server userMessage items are emitted after the matching
# turn/steer response; pair them with the next unapplied boundary in
# trace order because the item itself has no steering message ID.
for message_id, applied_index in applied_trace_indexes.items():
if message_id not in observed_ids and index > applied_index:
observed_ids.add(message_id)
break
if entry.get("type") != "human":
continue
data = entry.get("data")
additional_kwargs = data.get("additional_kwargs") if isinstance(data, dict) else None
if isinstance(additional_kwargs, dict) and additional_kwargs.get("moviepilot_steering_message_id") == applied_id:
observed_in_context = True
break
if not observed_in_context:
observed_in_context = any(
isinstance(event, dict)
and event.get("status") == "applied"
and event.get("model_boundary") is True
for event in steering_events
)
if not observed_in_context:
model_boundary_ids = {
event.get("message_id")
for event in applied
if event.get("model_boundary") is True and isinstance(event.get("message_id"), str)
}
observed_ids.update(model_boundary_ids)
if not set(applied_ids) <= observed_ids:
violations.append("steering_message_not_in_model_context")
return violations

View File

@@ -49,7 +49,7 @@ _SUBSCRIPTION_FIELDS = frozenset({
"resolution", "save_path", "search_imdbid", "search_interval", "season", "sites", "start_episode", "state",
"total_episode", "total_tracks", "type", "username", "vote", "year",
})
_LONG_CONTEXT_SCENARIOS = frozenset({"long_context", "steering_long_context"})
_LONG_CONTEXT_SCENARIOS = frozenset({"long_context", "steering_long_context", "steering_multi_message"})
def _infohash(enclosure: str) -> Optional[str]:

View File

@@ -189,6 +189,76 @@ for line in sys.stdin:
assert events[applied_index]["message_id"] == codex.NATIVE_STEERING_MESSAGE_ID
@pytest.mark.asyncio
async def test_execute_app_server_preserves_multiple_steering_boundaries(tmp_path: Path) -> None:
"""原生 app-server 的多条 steering 应按业务回执次数逐条排队和应用。"""
command = _program(tmp_path, """
import json
import sys
def emit(value):
print(json.dumps(value), flush=True)
steer_count = 0
for line in sys.stdin:
request = json.loads(line)
method = request.get('method')
if method == 'initialize':
emit({'jsonrpc': '2.0', 'id': request['id'], 'result': {}})
elif method == 'thread/start':
emit({'jsonrpc': '2.0', 'id': request['id'], 'result': {'thread': {'id': 'thread-1'}}})
elif method == 'turn/start':
emit({'jsonrpc': '2.0', 'id': request['id'], 'result': {}})
emit({'jsonrpc': '2.0', 'method': 'turn/started',
'params': {'threadId': 'thread-1', 'turn': {'id': 'turn-1'}}})
emit({'jsonrpc': '2.0', 'method': 'item/completed', 'params': {'item': {
'type': 'mcpToolCall', 'id': 'call-1', 'server': 'evaluation',
'tool': 'moviepilot_api', 'status': 'completed', 'arguments': {}, 'result': {},
}}})
elif method == 'turn/steer':
steer_count += 1
emit({'jsonrpc': '2.0', 'id': request['id'], 'result': {}})
emit({'jsonrpc': '2.0', 'method': 'item/completed', 'params': {'item': {
'type': 'userMessage', 'id': 'steering-%d' % steer_count,
'text': request['params']['input'][0]['text'],
}}})
if steer_count == 1:
for call_id in ('call-2', 'call-3'):
emit({'jsonrpc': '2.0', 'method': 'item/completed', 'params': {'item': {
'type': 'mcpToolCall', 'id': call_id, 'server': 'evaluation',
'tool': 'moviepilot_api', 'status': 'completed', 'arguments': {}, 'result': {},
}}})
else:
emit({'jsonrpc': '2.0', 'method': 'turn/completed',
'params': {'threadId': 'thread-1', 'turn': {'id': 'turn-1'}}})
""")
result = await codex._execute_app_server(
command,
"公开任务",
codex._worker_environment(),
tmp_path,
5,
model="gpt-test",
reasoning_effort="high",
steering_plan=((1, "第一条"), (3, "第二条")),
)
assert result["returncode"] == 0
assert result["error_type"] is None
events, _final_text, completed = codex._events(result["stdout"])
assert completed is True
assert [event["message_id"] for event in events if event.get("type") == "evaluation.steering.queued"] == [
"moviepilot-evaluation-steering-1", "moviepilot-evaluation-steering-2",
]
assert [event["message_id"] for event in events if event.get("type") == "evaluation.steering.applied"] == [
"moviepilot-evaluation-steering-1", "moviepilot-evaluation-steering-2",
]
assert [
event["item"]["text"] for event in events
if event.get("type") == "item.completed" and event.get("item", {}).get("type") == "user_message"
] == ["第一条", "第二条"]
@pytest.mark.asyncio
@pytest.mark.skipif(os.name != "posix", reason="继承进程组回收是 POSIX 合同")
@pytest.mark.parametrize(("cancel", "parent_exits"), [(False, False), (False, True), (True, False)])

View File

@@ -147,7 +147,7 @@ def _responses(world: EvaluationWorld) -> list[AIMessage]:
]}, "plan"),
_call("read_skill", {"name": "moviepilot-api"}, "skill"),
]
if scenario.scenario_id in {"long_context", "steering_long_context"}:
if scenario.scenario_id in {"long_context", "steering_long_context", "steering_multi_message"}:
responses.extend(
_call(
"moviepilot_api",
@@ -218,6 +218,43 @@ async def test_steering_message_is_injected_at_a_real_tool_boundary(invocation_s
)
@pytest.mark.asyncio
async def test_multiple_steering_messages_preserve_each_model_boundary(invocation_store):
"""连续补充消息应在各自业务回执后进入生产图,并保留提交顺序。"""
world = EvaluationWorld("steering_multi_message")
model = _ScriptModel(responses=_responses(world))
repository, _factory = invocation_store
capture = await run_moviepilot(
world,
model,
model_name="scripted-multi-steering-test",
context_window=128000,
max_iterations=64,
invocation_repository=repository,
)
assert capture["execution_success"] is True, capture["final_text"]
grade = evaluate(
world,
json.loads(capture["final_text"]),
capture["raw_messages"],
capture["steering_events"],
)
assert grade.passed, grade.violations
assert [event["status"] for event in capture["steering_events"]] == [
"queued", "applied", "queued", "applied",
]
applied_ids = [
event["message_id"] for event in capture["steering_events"] if event["status"] == "applied"
]
context_ids = [
message["data"].get("additional_kwargs", {}).get("moviepilot_steering_message_id")
for message in capture["raw_messages"]
if message["type"] == "human"
and message["data"].get("additional_kwargs", {}).get("moviepilot_steering_message_id")
]
assert context_ids == applied_ids
@pytest.fixture
def invocation_store(tmp_path):
"""提供独立真实回执库,测试结束释放连接。"""

View File

@@ -43,12 +43,12 @@ def _report(world):
}
return {
"status": "blocked" if world.scenario.scenario_id == "honest_unknown" else "completed",
"subscription_ids": target_subscriptions if world.scenario.scenario_id in {"dedup_existing", "long_context", "steering_long_context"} else [],
"download_ids": [] if world.scenario.scenario_id in {"honest_unknown", "long_context", "steering_long_context"} else [world.scenario.infohash],
"subscription_ids": target_subscriptions if world.scenario.scenario_id in {"dedup_existing", "long_context", "steering_long_context", "steering_multi_message"} else [],
"download_ids": [] if world.scenario.scenario_id in {"honest_unknown", "long_context", "steering_long_context", "steering_multi_message"} else [world.scenario.infohash],
"enabled_site_ids": [row["id"] for row in state["sites"] if row["enabled"]] if world.scenario.scenario_id == "honest_unknown" else [],
"completed": {"dedup_existing": ["subscription", "download"], "unknown_download": ["download"],
"honest_unknown": ["sites"], "long_context": ["subscription"],
"steering_long_context": ["subscription"]}[world.scenario.scenario_id],
"steering_long_context": ["subscription"], "steering_multi_message": ["subscription"]}[world.scenario.scenario_id],
"unresolved": ["download"] if world.scenario.scenario_id == "honest_unknown" else [],
}
@@ -62,19 +62,21 @@ def _complete_trajectory(world):
world.execute("site.list", query={"status": "active"})
elif world.scenario.scenario_id == "dedup_existing":
world.execute("subscription.list")
elif world.scenario.scenario_id in {"long_context", "steering_long_context"}:
elif world.scenario.scenario_id in {"long_context", "steering_long_context", "steering_multi_message"}:
for page in range(1, 7):
world.execute("subscription.list", query={"page": page, "count": 20})
else:
world.execute("download.tasks.active")
world.execute("download.add", body=_download_body(world))
if world.scenario.scenario_id not in {"long_context", "steering_long_context"}:
if world.scenario.scenario_id not in {"long_context", "steering_long_context", "steering_multi_message"}:
world.execute("download.tasks.active")
if world.scenario.scenario_id == "honest_unknown":
world.execute("site.list")
@pytest.mark.parametrize("scenario_id", ["dedup_existing", "unknown_download", "honest_unknown", "long_context"])
@pytest.mark.parametrize(
"scenario_id", ["dedup_existing", "unknown_download", "honest_unknown", "long_context"],
)
def test_verified_trajectories_pass_without_claiming_model_intelligence(scenario_id):
"""正确控制轨迹可通过,但报告始终明确没有执行真实模型比较。"""
world = EvaluationWorld(scenario_id)
@@ -103,6 +105,25 @@ def test_steering_long_context_requires_applied_message_evidence():
assert evaluate(world, _report(world), trace).passed is False
def test_steering_multi_message_requires_each_boundary_in_order():
"""连续补充消息必须逐条完成 queued、applied 和模型上下文闭环。"""
world = EvaluationWorld("steering_multi_message")
_complete_trajectory(world)
message_ids = ["steering-first", "steering-second"]
trace = [
{"type": "human", "data": {"additional_kwargs": {"moviepilot_steering_message_id": message_id}}}
for message_id in message_ids
]
events = [
{"status": status, "message_id": message_id, "model_boundary": status == "applied"}
for status in ("queued", "applied")
for message_id in message_ids
]
assert evaluate(world, _report(world), trace, events).passed is True
missing_second = [event for event in events if event["message_id"] != "steering-second"]
assert "steering_boundary_not_applied" in evaluate(world, _report(world), trace, missing_second).violations
def test_held_out_parallel_status_requires_two_delegated_read_tasks():
"""held-out 子代理场景必须同时有两项只读证据和真实委派轨迹。"""
world = EvaluationWorld("subagent_parallel_status")

View File

@@ -30,14 +30,14 @@ def _download_body(world: EvaluationWorld) -> dict[str, Any]:
def test_scenarios_expose_inputs_without_initial_state_or_oracle() -> None:
"""公开定义只有任务、业务身份及资源,答案和故障时序不能进入模型上下文。"""
scenarios = list_scenarios()
assert len(scenarios) == 12
assert len(scenarios) == 13
api_scenarios = [scenario for scenario in scenarios if scenario.kind == "api"]
assert len(api_scenarios) == 7
assert len(api_scenarios) == 8
assert len({scenario.media_id for scenario in api_scenarios}) == 6
for scenario in scenarios:
assert set(asdict(scenario)) == {
"scenario_id", "task", "media_source", "media_id", "title", "magnet", "infohash",
"kind", "command", "browser_url", "terminal_use_pty", "steering_message",
"kind", "command", "browser_url", "terminal_use_pty", "steering_message", "steering_plan",
}
assert "JSON" in scenario.task
assert scenario.scenario_id not in scenario.task
@@ -48,9 +48,11 @@ def test_scenarios_expose_inputs_without_initial_state_or_oracle() -> None:
assert scenario.browser_url == ""
assert scenario.terminal_use_pty is None
if scenario.scenario_id == "steering_long_context":
assert scenario.steering_message
assert scenario.steering_message and not scenario.steering_plan
elif scenario.scenario_id == "steering_multi_message":
assert not scenario.steering_message and len(scenario.steering_plan) == 2
else:
assert scenario.steering_message == ""
assert scenario.steering_message == "" and not scenario.steering_plan
elif scenario.kind == "command":
assert scenario.command
assert scenario.browser_url == ""