Repository navigation
fix(discovery): refuse DiscoveryComplete before any evidence returns - #7552
Conversation
A discovery worker could submit DiscoveryComplete in its first model step, before any other tool returned. GLM-5.3-Flash in Code Mode did this on every scheduled check from 2026-11-29 to 2026-12-02: it meant to call DiscoveryMemory, which is only reachable inside exec there, and sent DiscoveryComplete with a "placeholder" note instead. The check ended with no investigation and stored the placeholder as a record. The driver now refuses DiscoveryComplete while no call to another tool has returned a successful result in the Run, unless the step offers nothing else to call. tool_search does not count. In Code Mode the refusal says that DiscoveryMemory and the other tools run inside exec. Generated-by: Claude Code
M4n5ter
left a comment
There was a problem hiding this comment.
English
Thanks for tracking down the GLM-5.3-Flash Code Mode failure mode. Preventing zero-evidence DiscoveryComplete calls from persisting placeholder records makes sense as a guardrail, though there are a couple of correctness edge cases and design/test gaps worth addressing before merge:
1. [Blocking] investigable checks step_advertised (wire surface), causing false positives in Code Mode and false negatives under toolDiscovery: true
In plugins/agent/native/src/owner/driver.rs, investigable inspects self.step_advertised (the current step's advertised wire tools) against NOT_EVIDENCE = &["DiscoveryComplete", "tool_search"]. That breaks in both directions:
- Code Mode blocks legitimate completion when no investigation tools remain:
discovery_approves_grouped_aliases_and_rechecks_the_parent_ceilingverifies that a worker whose granted tools disappear under the parent Bot's ceiling (leaving onlyDiscoveryComplete) must still be able to complete. However, in Code Mode,CodeCells::cell_definitions_for(plugins/agent/tools/src/cell/session.rs) unconditionally advertises["exec", "wait"]even whenavailability.all().nested()is empty. Becauseexecandwaitare not inNOT_EVIDENCE,investigablestaystrue, refusingDiscoveryCompleteand telling the model to useDiscoveryMemoryinsideexeceven though no investigation tools exist. (Similarly,CompactContextandAskUserQuestionare control/interaction tools rather than investigation tools, yet are not excluded.) - Non-Code Mode with
toolDiscovery: true(production default) bypasses the guard for deferred-only grants: Default installation setstoolDiscovery: true(products/maka/bundle/src/installation.ts), andvisible_before_search(plugins/agent/tool-catalog/src/availability.rs) only eagerly exposesalways_visibletools plusShell/Read/AskUserQuestion/ProcessStop/ProcessInput. If a discovery task is scoped viaDiscoveryToolSelectionto only deferred tools (e.g.,WebFetch,WebSearch,Recall*,SessionList,ScheduledTask, ormcp__*, withoutReadorDiscoveryMemory), Step 1'sstep_advertisedis just{"DiscoveryComplete", "tool_search"}. Both matchNOT_EVIDENCE, soinvestigableevaluates tofalseand a first-stepDiscoveryCompleteis accepted immediately.
Suggested fix: Determine whether the worker has investigation tools from the actual authorized step ToolCatalog (already obtained on the next line via catalog_for_tool, which includes deferred and nested tools without virtual exec/wait/tool_search), excluding non-evidence control tools (DiscoveryComplete, CompactContext, AskUserQuestion).
2. [Important] Store::run_tool_succeeded misses CellRecovered and can deadlock when all investigation tools return Failed
- Restart recovery (
CellRecovered):RunToolSucceeded(plugins/agent/state/src/store.rs) filters onjson_extract(body,'$.accepted.outcome.kind')='succeeded'. If a Code Mode worker'sexecfinishes across a Host restart, recovery accepts it withAcceptedResult::CellRecovered { cell }("cell_recovered"), not"succeeded". Note thatplugins/agent/state/src/fold.rsalready treatsCellRecoveredwithCellStatus::Completedas successful completion; duplicating the success check in raw SQL misses this path and will refuseDiscoveryCompleteafter recovery. (Also, filteringAND pending=0lets the query use theagent_tools_pending(run, pending, key)index.) - Investigation tools that return
AcceptedResult::Failed: WhileReadandWebFetchwrap ordinary file/web errors insideToolSuccess(Succeeded), MCP tools withisError: true(plugins/agent/mcp/src/result.rs) andRecall/DiscoveryMemory/Host errors recordAcceptedResult::Failed. For a worker scoped to e.g. an MCP monitor, anisError: trueresponse is itself the evidence to report, yet requiring strictlysucceededprevents it from ever callingDiscoveryComplete. (By contrast, anexecscript runtime error /Interruptedshould still not count as evidence.)
3. [Important — Design] Address the prompt/tool-description trigger directly and keep discovery policy out of generic NativeDriver::decide_tool
- Preventing the first-step mistake upfront: From the observed runs, the model saw
DiscoveryCompleteandtool_searchat top level in Code Mode whileDiscoveryMemorylived insideexec, andDiscoveryComplete's description (plugins/agent/native/src/owner/discovery.rs) does not warn against calling it before investigating or as a placeholder (compareBot::Sleepinplugins/agent/native/src/owner/bot.rs, which states its preconditions and refusal rule directly). UpdatingDiscoveryComplete's description (and avoiding wasted first-step rejections) addresses the trigger rather than relying solely on the error text. - Refusal message accuracy: In
premature_completion(code_mode), hardcoding{MEMORY}andtools.<name>(input)is inaccurate whenDiscoveryMemoryis not granted to the worker or when Python Code Mode is active. - Layering:
Bot::Sleepkeeps its refusal logic insidebot.rs. Hardcodingsuper::discovery::COMPLETE,NOT_EVIDENCE, and a second lock onself.step_advertised(without re-checkingcached_step == step) inside genericNativeDriver::decide_toolleaks discovery-specific policy into the generic driver. Moving this check to discovery's preparation path (or alongsidePreparedTool::prepare, wherecatalog/access/ownerare already in hand) keepsdecide_toolclean.
4. [Important — Tests] No Code Mode or tool_discovery test coverage
Fixture::new in plugins/agent/native/src/owner/driver/tests/model_recovery/discovery.rs sets codeMode: false and does not exercise tool_discovery: true, so the new if code_mode refusal branch and both edge cases in #1 are currently uncovered (while 13 unrelated tests were modified to prepend Read("discovery.txt")). Adding dedicated behavior tests for:
- Code Mode rejecting first-step
DiscoveryComplete(with the Code Mode hint) and accepting it afterexec, - Code Mode with zero granted investigation tools still allowing
DiscoveryComplete, tool_discovery: truewith deferred-only investigation tools rejecting both first-stepDiscoveryCompleteandtool_search-only before a real tool succeeds,
would directly cover the target scenario and prevent regressions.
Follow-up (non-blocking)
In Code Mode under the Session profile, a background discovery worker still exposes AskUserQuestion and a top-level tool_search (solely for deferred DirectOnly CompactContext), which explains why 5 of the 8 observed runs sent tool_search trying to find DiscoveryMemory. Trimming unnecessary direct-only tools from discovery workers in a follow-up would further reduce confusion.
简体中文
感谢定位 GLM-5.3-Flash 在 Code Mode 下的这个实际问题。给 DiscoveryComplete 加一道防零取证直接交 placeholder 的护栏方向是对的,但对照源码看还有几个正确性边界、分层设计与测试覆盖问题建议在合并前处理掉:
1. [Blocking] investigable 用 step_advertised(当前步 wire 工具面)判断,在 Code Mode 和 toolDiscovery: true(生产默认)下双向误判
plugins/agent/native/src/owner/driver.rs 里用 self.step_advertised 排查 NOT_EVIDENCE = &["DiscoveryComplete", "tool_search"] 之外的工具,这会在两个真实路径下同时出错:
- Code Mode 下无调查工具时把合法完成堵死:已有测试
discovery_approves_grouped_aliases_and_rechecks_the_parent_ceiling明确覆盖了父 Bot 收紧工具上限后 worker 只剩DiscoveryComplete、需要能直接结束的场景。但在 Code Mode 下,CodeCells::cell_definitions_for(plugins/agent/tools/src/cell/session.rs)即使availability.all().nested()为空也会无条件暴露["exec", "wait"]。由于exec和wait不在NOT_EVIDENCE里,investigable恒为true,会把合法的DiscoveryComplete拒掉,并且报错还误导模型去exec里调DiscoveryMemory。(另外CompactContext和AskUserQuestion也不是调查工具,但同样未排除。) - 非 Code Mode +
toolDiscovery: true(生产默认)下全 deferred 工具绕过防线:默认配置启用了toolDiscovery: true(products/maka/bundle/src/installation.ts),而visible_before_search(plugins/agent/tool-catalog/src/availability.rs)在首步只暴露always_visible以及Shell/Read/AskUserQuestion/ProcessStop/ProcessInput。如果用户通过DiscoveryToolSelection只授予了 deferred 调查工具(如WebFetch、WebSearch、Recall*、SessionList、ScheduledTask或mcp__*,不含Read/DiscoveryMemory),首步step_advertised只有{"DiscoveryComplete", "tool_search"},全部命中NOT_EVIDENCE,investigable误判为false,首步直接调用DiscoveryComplete会被放行。
建议修复:不要从当前步 wire 工具面 step_advertised 反推,直接基于这一步实际授权的完整 ToolCatalog(紧接着下一行 catalog_for_tool 就已经拿到,包含全部 deferred 与 nested 工具,且不含虚拟的 exec/wait/tool_search)排除控制类工具(DiscoveryComplete、CompactContext、AskUserQuestion)来判断是否有可调查工具。
2. [Important] Store::run_tool_succeeded 漏掉 CellRecovered,且对全部工具返回 Failed 的调查场景过严
- 重启恢复(
CellRecovered)漏判:RunToolSucceeded(plugins/agent/state/src/store.rs)只匹配json_extract(body,'$.accepted.outcome.kind')='succeeded'。如果 Code Mode worker 的exec在 Host 重启期间完成,恢复结算写入的 outcome 是AcceptedResult::CellRecovered { cell }("cell_recovered"),不是"succeeded"。plugins/agent/state/src/fold.rs本身已经把CellStatus::Completed的CellRecovered视为成功完成;这里单独写 SQL 匹配漏掉了恢复路径,会导致恢复后合法调用DiscoveryComplete被拒。(另外 SQL 加上AND pending=0可以命中agent_tools_pending(run, pending, key)索引。) - 调查工具返回
AcceptedResult::Failed被卡死:虽然Read/WebFetch的常规业务错误会包在ToolSuccess里落为Succeeded,但 MCP 工具返回isError: true(plugins/agent/mcp/src/result.rs)以及Recall/DiscoveryMemory/Host 失败都会记录为AcceptedResult::Failed。如果某个监控任务仅授权了 MCP 工具,目标服务报错本身就是调查结论,纯按succeeded卡死会导致永远无法提交结果。(不过 Code Mode 下exec脚本自身的运行时异常Interrupted确实不应算有效取证。)
3. [Important — 设计] 建议同步修掉工具描述诱因,并把 Discovery 领域策略收口出通用 NativeDriver::decide_tool
- 从源头减少首步误调:从 Observed 日志看,模型在 Code Mode 顶层看到
DiscoveryComplete和tool_search,而DiscoveryMemory藏在exec内;同时DiscoveryComplete的工具描述(plugins/agent/native/src/owner/discovery.rs)完全没说明“必须先调查再单独调用、禁止首步占位”(对比同为FinishTurn的Bot::Sleep,plugins/agent/native/src/owner/bot.rs里直接把调用前提和拒绝条件写进了描述)。把描述补清楚可以避免每次都先浪费一轮失败调用再靠拒绝报错纠偏。 - 拒绝提示准确性:
premature_completion(code_mode)写死了{MEMORY}和 JS 语法tools.<name>(input),在未授权DiscoveryMemory或 Python Code Mode 下不准确。 - 分层归属:
Bot::Sleep的拒绝逻辑收口在bot.rs自身;这里把super::discovery::COMPLETE、NOT_EVIDENCE以及对self.step_advertised的二次加锁(且未重验cached_step == step)直接写进通用NativeDriver::decide_tool,让通用层承担了 Discovery 领域规则。建议收口到 discovery 自己的 prepare 边界(或已经拿到catalog/access/owner的PreparedTool::prepare路径)。
4. [Important — 测试] 缺少 Code Mode 和 tool_discovery 覆盖
plugins/agent/native/src/owner/driver/tests/model_recovery/discovery.rs 里 Fixture::new 固定为 codeMode: false,也没有开启 tool_discovery: true 的用例,导致新增的 if code_mode 分支和第 1 点中的两个问题都没被测试覆盖(同时 13 个不相关用例都被迫加了一步 Read("discovery.txt"))。建议补充独立的行为测试直接覆盖:
- Code Mode 下首步
DiscoveryComplete被拒并带正确提示,随后通过exec调查后放行; - Code Mode 下无调查工具授权时仍允许直接
DiscoveryComplete; tool_discovery: true且仅授权 deferred 工具时,首步DiscoveryComplete和仅调用tool_search后均被拒,实际工具返回后再放行。
Follow-up(非本 PR 阻断项)
Session profile 下后台运行的 Discovery worker 在 Code Mode 顶层仍带着 AskUserQuestion 以及仅服务 CompactContext 的 tool_search(这次 8 次失败里有 5 次因此发了 tool_search 去找 DiscoveryMemory)。后续清理 discovery worker 的顶层 DirectOnly 工具面能进一步减少模型误判。
…alls Move the check into the discovery preparation path. A worker is exempt only when its step catalog holds no investigation tool. Count direct calls that succeeded or failed, and nested calls inside code cells that returned, but not exec, wait or tool_search themselves. State the rule in the DiscoveryComplete description and drop mode-specific refusal text. Generated-by: Claude Code
|
Thanks for the review. All four points were valid. The new head changes the check as follows. 1. Which workers are checked. The check now reads the step's authorized 2. What counts as evidence.
3. Layering and wording.
4. Tests. Two new tests:
The fixture worker has The follow-up about trimming direct-only tools from discovery workers is not in this PR. Posted by Claude Opus 5.5 (AI). |
M4n5ter
left a comment
There was a problem hiding this comment.
English
LGTM — all four points from the previous review are cleanly addressed, and checking CellChild::returned() on agent_cells is even cleaner than relying on exec outcomes (it also blocks empty/no-op exec scripts and handles CellRecovered naturally). Feel free to merge as-is.
One small non-blocking note in case you want to tighten it now or in a follow-up:
- Same-attempt streaming interleaving:
Store::run_tool_returnedcurrently scans allagent_toolsandagent_cellsrows for therunwithout excluding the currentattempt. On adapters withsupports_item_acceptance() == true(OpenAI Responses API / Codex), if a model emits[Read/exec, DiscoveryComplete(placeholder)]in Step 1, the first tool call can execute and settle before the streamedDiscoveryCompletecall arrives in the same attempt (and similarly under Code Mode wheredirect_tool_batching() == false, or across a Host restart between deciding sibling calls). Excluding the currentattempt(available viaToolOrigin::Provider { link }->link.attemptincontext.call.origin) withjson_extract(body,'$.key.attempt') <> ?3onagent_toolsandowner_attempt IS DISTINCT FROM ?2onagent_cellswould strictly enforce the "in a later step" contract with a few lines.
No blocker at all — ready to merge whenever you like.
简体中文
LGTM——上一轮提到的四个问题都已经收口得很干净,通过 agent_cells 上的 CellChild::returned() 判定比依赖 exec 自身状态更简洁(顺手连空跑的 exec 脚本也拦住了,并且天然覆盖 CellRecovered)。可以随时合并。
顺手留一个小问题(非阻塞,想现在补或留作后续都可以):
- 同一
attempt流式交错边界:Store::run_tool_returned目前会扫描整场run的所有agent_tools和agent_cells,没有排除当前attempt。在开启supports_item_acceptance() == true的适配器(OpenAI Responses API / Codex)上,如果模型首步同一次响应连发[Read/exec, DiscoveryComplete(placeholder)],第一个工具可能在流式生成完第二个DiscoveryComplete之前就已经执行结算(Code Mode 下direct_tool_batching() == false或同一步两个调用之间恰好发生 Host 重启恢复时也有类似路径),导致模型还没见过结果就被放行。从context.call.origin的ToolOrigin::Provider { link }取出当前link.attempt,在agent_tools加json_extract(body,'$.key.attempt') <> ?3、在agent_cells加owner_attempt IS DISTINCT FROM ?2即可用几行代码把“必须后续 step 调用”的约束彻底闭环。
不阻断合并,作者觉得合适随时合就行。
A tool that settles while the same streamed response is still producing DiscoveryComplete has a result the model has not seen. Only results from earlier model attempts now count as evidence. Generated-by: Claude Code
|
Thanks. I took the same-attempt note in 6791c2c: I tried to cover it with a test that sends Posted by Claude Opus 5.5 (AI). |
Summary
A Proactive discovery worker could call
DiscoveryCompletein its first model step, before any other tool had returned. The check then ended without investigating, and the submitted note was stored as an investigation record.Preparing
DiscoveryCompletenow fails while no investigation tool has returned anything in an earlier model attempt of the Run. A result from the same model response does not count, because the model has not seen it. A direct call counts when it succeeded or failed. In Code Mode a call made insideexeccounts when it returned a result or an error;execandwaitthemselves do not, so a script that fails before it calls a tool is not evidence.tool_search,AskUserQuestion,CompactContextand the todo tools do not count. The rule does not apply when the step's authorized tool catalog holds no other tool. The refusal tells the model to investigate first, insideexecwhen the tools are not offered as separate functions, and then callDiscoveryCompletealone in a later step. TheDiscoveryCompletedescription states the same rule.Observed
A daily check on a trial root, model GLM-5.3-Flash with Code Mode. From 11-29 to 12-02, all 8 scheduled checks ended in their first model step with
DiscoveryComplete {"kind":"no_report","note":"placeholder"}(or a Chinese note meaning "placeholder: read memory and history first"). Five of them senttool_searchin the same step. Each time the model's reasoning said it would first callDiscoveryMemorywithlist. In Code Mode the model-facing tools areexec,wait,AskUserQuestion,DiscoveryCompleteandtool_search;DiscoveryMemoryis only reachable insideexec. On 11-28 the same model calledexecwithtools.DiscoveryMemory(...)and completed a full report.One earlier check (11-27) shows that an error alone was not enough: the model sent
DiscoveryCompletewith empty arguments, got an input error, wrote "I called DiscoveryComplete prematurely", and then sentDiscoveryCompletewith the placeholder note, which was accepted.Implementation notes
The check is
Owner::require_discovery_evidenceindiscovery.rs, called fromPreparedTool::preparewith the step catalog. It reads theagent_toolsandagent_cellsprojections throughStore::run_tool_returned, because theRunViewgiven to the driver holds only the current step.Tests
The discovery driver tests now read the fixture file before completing. Where a test changes the model route, the model list, the credential or the workspace between the worker's first step and its completion, the read happens before that change. New tests cover Code Mode (refusal, a failing
exec, a nestedDiscoveryMemorycall, a worker with no tools) and deferred tools undertoolDiscovery.AI use
Claude Code (Claude Opus 5.5) found the cause in a trial root, wrote the change and ran the tests. Claude Fable 5.2 advised on the rule, and Claude Sonnet 5.5 reviewed the diff. The author asked for the fix and did not review the diff line by line.