Skip to content

fix(agent): 长任务压缩后不丢结论,重复调用能识别、循环能停下(#5) - #41

Merged
WhiteNightShadow merged 6 commits into
mainfrom
fix/long-task-loops
Nov 9, 2026
Merged

WhiteNightShadow merged 6 commits into
mainfrom
fix/long-task-loops

Conversation

@WhiteNightShadow

@WhiteNightShadow WhiteNightShadow commented Nov 5, 2026 •

Copy link
Copy Markdown
Owner

背景

#5:复杂分析跑着跑着,像是忘了之前的结论和既定步骤,从头开始分析,最后陷进死循环。

读AgentLoop查到的原因分三类,每一条都在旧代码上复现过:

  • 上下文压缩丢东西。压缩时由模型写一份交接摘要,之后的上下文只剩“任务 + 摘要”。
    • 摘要的输入只取执行记录的前6万字,记录一长,最新的进展(真正的“下一步”)摘要模型根本没看到。
    • 任务锚点之前的内容不进摘要。用户发「继续」时,锚点就是这句「继续」,原来的任务和前几轮的结论都在它前面。
    • 任务到轮数上限自动续跑后,引擎自己加的续跑提示成了任务锚点,之后一压缩,上一段的全部工作和用户的任务一起消失。
    • 摘要被长度截断时整份作废,摘要调用失败时退回机械记录,两种情况下之前确认的结论都不在新存档里。
  • 重复检测太窄,还会误拦。只有“同一个调用连续10次、结果相同”才拦,计数按回合清零;“结果相同”读错了层级,所有成功调用的指纹都一样,分页读文件读到第11段会被拒绝执行。
  • 工具自己返回的失败不算失败。run_node退出码非0、net_get没找到请求这类情况返回{ ok:false, … },信封还是ok:true,“同类错误”“连续失败”两条提示对它们不起作用。

改动(按提交)

第一轮

  • fix(agent) 压缩后不丢结论,重复调用能识别、循环能停下(5b78083)
    • 交接摘要的输入:执行记录超长时留开头和最新的部分;加上当前任务、任务锚点之前的对话(节选)和上一份存档;输出上限从2048提到4096 token。
    • 压缩后的上下文结构不变(system + 任务 + 存档 + 续跑说明),任务之前用户发的消息原文附在续跑说明后面。
    • 新增一份一次执行内共用的状态(createRunState),AgentSession每次run建一个,传给每个回合:自动续跑的回合靠它认出用户发的那条任务,循环检测的记录跨压缩、跨续跑。
    • 结果指纹改成返回值的长度加摘要;重复调用在工具结果里提示;最近的调用大多是重复时先提醒、再停下(stopReason为loop,不再自动续跑)。
    • 信封ok:false和返回值里ok:false都算失败。
  • docs(edfa410):readme条目。

第二轮:独立审查之后的修正

第一轮开出pr后做了一次独立代码审查,15条发现里12条复现确认,多数是第一轮改动引入的。下面逐条修了,修法都有对应的自测。

  • fix(agent) 审查发现的修正(a7dc211)
    • 循环检测只认只读查询的重复
      • 第一轮把所有不豁免重复的工具都算进去:signer_trace/hook_inject的start和stop、clear_site_data、cookies这类改动型工具每次回执都一样,按工具说明“start→触发→query→stop”采12组样本,会在第20次调用后被提醒、第36次调用后被停掉。现在只有只读工具(工具表里声明READ_ONLY的)的重复才算;改动型工具用同样的参数再做一次、回执也一样,既不算重复也不算新进展。
      • 被重复熔断拒绝的调用以前一律算重复。熔断按数字归一的参数判断,逐个搜不同的常量(都没命中,返回值逐字节相同)时,第11个起被拒绝的都是没做过的调用,却被说成“和之前做过的完全相同”,提醒一次后整轮停掉。现在只有这个调用确实做过才算重复;拒绝的文案也分开写,不再对没做过的调用说“已用相同参数调用”,也不再建议“换offset”(只换数字照样被拒)。
      • 窗口里放“重复”和“拿到新结果的调用”两种,提醒里写明各有几次。
    • 结果指纹
      • page_snapshot和page_find每次扫描都给元素重新发ref,page_automation_scan带scannedAt。第一轮按整个返回值算指纹,页面一点没变时这几个工具的结果也永远“不一样”,重复熔断、重复提示、循环检测、无进展提醒对它们全部失效。现在算指纹时不看这两个字段。
      • 返回值里ok:false并带错误文本的失败,和抛错一样按归一化的错误文本算指纹。
      • 调用签名里参数的键按字母序排,键换个先后不再被当成另一个调用。
    • 提醒和停止
      • 提醒之后紧接着压缩,提醒那条消息就从上下文里消失,模型没见过提醒就被当成“提醒之后仍在重复”停掉。现在提醒的原文存在运行状态里,压缩后接在续跑说明后面。
      • 提醒超过36次计入的调用之后才再次出现重复,重新提醒,不直接停。
      • 提醒里让模型“卡住就汇报”,可照做的纯文字汇报不含“结论”这类字眼,会被当成漂移,引擎反过来连催三次“现在就调用工具”,再自动续跑一回合。现在提醒之后的第一条纯文字回复按汇报收尾。
      • 循环提醒不再锁死“没明显推进”的提醒;等最后那次汇报时用户点了停止,按手动停止收尾。
    • 失败判定
      • run_node/run_python的输出里,真正的报错在最后;从头取第一条“像报错”的行,会取到脚本自己打印的日志、node回显的throw new Error("…")那一行、python回溯里的raise行,互不相干的失败得到同一个签名,第3次起每次都被提示“撞同一类错误”。现在进程输出从后往前找。
      • 返回值太大被ToolRouter截断时,信封里保留ok:false,输出很大的失败照样计入。
    • 交接账本的沉淀和携带
      • 第一轮把整份存档交给LedgerBackend.mergeHandoff。存档里有锚点之前的对话原文:上一条回复里列着“### 已否决 / - 方向A / - 方向B”让用户选,用户选了b,摘要一失败,“方向B”就被记成已否决,写进按工作目录持久化的账本。存档里还有被截过的旧账本:半句会把库里完整的那条顶掉。现在只把模型这一次写出来的账本(完整的行)交给账本库,机械记录、带过来的旧账本、引用的对话都不交;引用的对话每行加> 。
      • mergeHandoff改成只增不减:库里已有相同的、或更完整的一条就跳过,不删也不重插。事实和已否决假设各自限量(每类一次最多新写入40条)。以前自上而下只取前40条,账本是逐次累积的,过了40条后新结论和排在后面的已否决假设进不了库。
      • 机械存档以前把上一份存档整份再嵌一层、按字符截,连续两次没生成出摘要,排在账本后面的“已否决假设”“工作目录文件”就丢了。现在运行状态里分开记着最近一份完整的账本、之后那份没写完的、和前几段的机械记录,每次都带原文,只在行与行之间截。
      • 被截断的账本去掉最后那半行再用。
      • 过时的“下一步”一节:标题带序号、加粗、表情、#后没空格、crlf换行都认得出,代码块里以#开头的注释不算标题。
      • 写摘要时用户点了停止:不再压缩,按手动停止收尾。
    • 用户此前的消息
      • 第一轮把锚点之前的所有用户消息都带上,线程第一条恒保留,超过6000字时反而会略掉「继续」真正指向的那条。现在只带最近4条,注明只作参考、当前任务以任务消息为准;同一句话又说了一遍按最后一次的位置排;对应的任务被用户手动停止过的,在原话后面注明。
    • 自动续跑的缓存
      • 第一轮在续跑回合里把动态上下文重新挂到任务消息上,账本多记一条,从任务消息起整段对话的前缀缓存都失效。现在续跑的回合原样重发上一回合的消息(连字段顺序都不变),变了的动态上下文只附在续跑提示后面。
    • 半个字符
      • 按下标截断文本会把emoji切成两半,请求体里是一个孤立的\ud83d转义,校验严格的json解析器会拒收。现在截断不切开代理对;LlmClient序列化请求体时把残留的孤立代理项换成U+FFFD(main上工具结果折叠等几处截断也有同样的问题,一并盖住)。
    • 停下的原因
      • 循环停止的说明只拼在返回的content里,而侧栏只要有步骤记录就只渲染步骤,用户看不到。现在各个“引擎主动停下”的出口都另外返回notice,AgentSession收尾时把它追加成步骤里的一段正文。main上原有的几条说明(连续只输出文字、到续跑上限等)同样看不到,一并修了。
    • 测试
      • dev/selftest-loop-guard.mjs重写,143项;AgentSession的加载器抽成dev/agent-session-harness.mjs,selftest-global-system-prompt改用它;selftest-toolrouter、selftest-panel-live各加一项。
  • docs(469a177):readme“main(尚未发布)”改成和实际行为一致。

第三轮:开关型工具的重复熔断

  • fix(agent) 开关动作豁免重复熔断(3b27ba0)
    • 问题:signer_trace、closure_read、debug_breakpoint、hook_inject、whitebox_diff按工具说明是“start→触发→query→stop”每组样本来一遍,start和stop的回执每次都一样,同一回合第11次start会被重复熔断按“同参数同结果”拒绝执行(v0.27.1就有,上面真实工具表的复现里main被拒6次)。
    • 看了几家agent框架的做法:openhands按“同样的动作+同样的观察结果”连续4次判死循环,它的issue里也有“轮询类任务被误判”的反馈,解法是把阈值做成可配置;几个rust实现(zeptoclaw、rsclaw)对工具名+参数做摘要、按摘要计数、分级告警→拦截;lyzr把“同样的调用、没有状态变化”当失控信号。共同点是只看调用和回执,而开关型工具的回执本来就不反映状态变化,调阈值解决不了这类误判,得靠工具声明自己说明哪些动作是开关。
    • 改法:工具声明里的repeatExempt除了true,现在可以写action列表,只有args.action在列表里的调用豁免。五个开关型工具声明["start","stop"],cookies声明["set","remove"],clear_site_data(每组样本重置一次)整个豁免;它们的query/list照旧按空转熔断。ToolRouter.isRepeatExempt(name, args)做判断,AgentLoop把解析后的参数传进去。
    • 验证:selftest-tool-metadata加4项、selftest-toolrouter加2项、selftest-loop-guard加2项(同一回合12组样本48次调用全部执行,反复query同一个空结果照旧第11次被拒);审查时留下的真实工具表复现脚本重跑,12组样本被拒次数从6(main)变成0。

行为变化

  • 模型在同一次任务里反复做已做过、结果相同的只读查询时会收到提示;一直这样会停下,侧栏里能看到“检测到循环”的说明。以前会一直跑到轮数和续跑次数用完。
  • 页面没变时反复page_snapshot:第2次起有重复提示,第11次被拒绝执行(和v0.27.1一样),另外会触发循环提醒。
  • “已连续n次没明显推进”的提醒会少一些:以前只有落盘类工具算进展(读错了层级),现在脚本跑通、抓到带调用栈的请求、查到非空结果也算。
  • 脚本连续跑失败时会多出“同类错误”“连续失败”的提示。
  • 每次压缩的交接摘要请求变大:输入上限从6万字到约12万字,输出上限4096 token;提示词要求账本控制在3000字左右。
  • 交接摘要没生成出来的那次压缩,不再往记忆库里写东西(以前机械记录里的列表偶尔会被写进去)。
  • 自动续跑后的第一个请求,前面和上一回合最后一个请求完全相同。

验证

  • 全量自测:bash scripts/selftest-agent-tools.sh通过,共48步。
  • 新测试能抓到问题:把44处修复点逐个改回去,自测每次都失败。
  • 审查时的复现脚本:审查过程中留下的复现脚本(真实工具表、真实CodeBackend/页面扫描代码、真实sqlite)在修复后的代码上重跑,结论都翻转了:采12组样本全部采完、没有循环事件;库里完整的结论不再被半句顶掉;对话里的列表不再入库;46条事实+12条已否决的账本全部交给了账本库(以前只取前40条);60种截断位置没有孤立代理项。
  • 续跑缓存:6个回合×80轮、账本每回合都变的模拟里,续跑后第一个请求的未缓存部分,main约39万字,第一轮最高78万字,现在约5千字;总的未缓存量比main少44%。
  • 真实引擎:v0.27.1最终arm64包的临时副本,换上改过的5个模块,临时profile、无头启动,本地假模型按脚本回复,经marionette驱动真实的AgentSession、工具、页面和记忆库,47项全部通过:
    • run_node真实输出:同一类报错第3次提示换路线;之后3次各不相同的报错(node都回显了throw那一行)不被说成同一类;
    • 循环:第12次调用后提醒,第24轮停下,停下的原因在步骤记录的正文里;
    • 提醒后模型按提醒汇报:只多发一个请求就收尾;
    • 采样流程:真实的hook_inject start→页面发请求→query→stop,9组全部采完,9次start的回执逐字相同,没有重复提示、没有提醒;
    • 页面没变时反复page_snapshot:每次的ref都不一样,第2次起提示重复,第11次被拒绝;
    • 摘要没生成出来:progress.md是机械存档,对话作为引用带着,记忆库里一条都没有;
    • 「继续」+ 自动续跑 + 压缩:续跑回合的第一个请求等于上一回合最后一个请求加续跑提示,其余和第一轮相同。
  • 只读工具普查:在同一个真实浏览器里把只读工具对一个静止页面各调两次,32个调用里29个两次逐字节相同,3个只在ref/scannedAt上不同,没有别的易变字段。
  • 页面/agent回归:同一个副本上跑scripts/verify-page-interaction.mjs,78项通过,退出码0。
  • 和#42一起:两个pr都改了LedgerBackend,三方合并没有冲突;合并后的文件上,账本关闭14项、账本sql 20项、循环自测143项都通过,真实引擎47项通过,浏览器0.2秒正常退出。

已知问题(本pr未处理)

  • 退出浏览器慢:只有这个pr的改动时,真实引擎那一轮测完浏览器过61秒才退出,而且是崩溃退出。原因和这个pr无关,在没改动的v0.27.1上同样复现,修复在#42。readme同一节两个pr都加了条目,后合并的那个需要变基。
  • 没有用真实模型跑过长任务。循环检测的窗口和阈值是按假模型场景定的;交接提示词里新加的“账本控制在3000字左右”、对“此前用户发过的消息”的处理,模型是否照做没有验证。
  • 重复熔断仍按数字归一的参数判断:同一类调用连续10次结果完全相同之后,本回合内换数字也会被拒(原有行为)。
  • 页面上有心跳请求时反复net_list,每次结果都确实不同,不算重复,也没有别的保护(v0.27.1上第11次起会被拒,但那是因为它把所有结果都当成相同)。
  • 用户此前的消息里,已经做完的旧任务没有标记(只标了被手动停止的),靠说明文字提醒模型。
  • 轮数用尽时的收尾请求仍然不带工具声明,是原有行为。
  • 侧栏的步骤列表仍按信封的ok显示,返回ok:false的调用在界面上还是成功的样式。
  • #5先不关,等报告人在下一个版本上回测。

🤖 Generated with Claude Code

WhiteNightShadow and others added 2 commits November 4, 2026 22:58
… loops (#5)

Long tasks restarted the analysis from scratch after a context compaction
and could then loop for good (#5). Causes found in AgentLoop:

Compaction
- The handoff summary only saw the first 60,000 characters of the flattened
  record, so on a long segment the latest progress (the real next step) was
  never summarised. It now keeps the head and the tail.
- Everything before the task anchor was dropped without being summarised.
  With "继续" as the anchor that is the task itself and the earlier
  conclusions. The summary input now has the user's messages verbatim, the
  conversation before the anchor and the previous checkpoint, and the
  user's earlier messages stay in the context after compaction (appended to
  the resume note).
- After an automatic restart the engine's own resume note became the task
  anchor, so the next compaction dropped the previous turn's work and the
  user's task. The anchor is now carried in a per-run state and stays the
  user's message; the previous turn's work is summarised with the rest.
- A truncated summary was thrown away and a failed one fell back to a
  mechanical record that had none of the earlier findings. A truncated
  summary is kept and completed, and the mechanical record carries the
  previous checkpoint without its outdated next step. Its parts are
  separated by headings so LedgerBackend.mergeHandoff does not file
  narration under the last "rejected" section.

Repeats and loops
- The result fingerprint read count/requests/... from the top of the
  envelope, but tool results live under `data`, so every successful call
  had the fingerprint "ok": paged fs_read calls (arguments differing only
  in digits share a call signature) were refused from the 11th call as
  "same arguments, same result". It is now a hash of the returned data.
- A call made before with identical arguments and an identical result is
  flagged in its tool result. When 8 of the last 12 tracked calls are such
  repeats the model is warned once; if the next window is the same the turn
  stops with stopReason "loop" and AgentSession does not restart it. The
  state is shared by all turns of a run, so it survives compaction and
  automatic restarts.

Failures reported in the tool's return value
- Many tools report failure by returning { ok: false, ... } (run_node with
  a non-zero exit code, net_get for an unknown request). The envelope is
  still ok: true, so the same-error and consecutive-failure hints never
  fired for them and a failed write counted as progress. They now count as
  failures; the no-progress check reads `data` as well.

dev/selftest-loop-guard.mjs covers each of these, including AgentSession
sharing the run state across automatic restarts.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Unreleased section: what changed in context compaction, the repeated-call
and loop detection, the repeat fuse no longer refusing paged reads, and
tool results that report ok:false counting as failures. One line in the
Agent feature list.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
WhiteNightShadow and others added 4 commits November 5, 2026 03:59
…es (#5)

Loop detection
- Only repeats of read-only queries count as redoing the analysis. Repeating
  a mutating tool with the same receipt (trace start/stop, clear site data,
  click, run a script) is neither a repeat nor new work, so a sampling
  workflow that toggles a tracer for every sample is no longer warned and
  stopped.
- A call refused by the repeat breaker counts as a repeat only if that exact
  call was made before. The breaker matches on digit-normalised arguments, so
  calls that had never been made were reported as identical repeats and the
  run was stopped. The refusal text now says which case it is.
- The result fingerprint ignores `ref` and `scannedAt`, which change on every
  page_snapshot / page_find / page_automation_scan call. A return value with
  ok:false and an error text is fingerprinted like a thrown error. Call
  signatures no longer depend on argument key order.
- The loop reminder is carried across a compaction, expires after 36 counted
  calls and no longer latches the no-progress reminder. A text-only report
  after the reminder ends the turn instead of being nudged as drift. An abort
  during the final report request ends the turn as aborted.
- The error signature of process output is taken from the last error line,
  not from the first line that looks like one (a log line, the source line
  node echoes, the raise line of a python traceback). A truncated envelope
  keeps ok:false.

Compaction
- The persistent ledger receives only what the model wrote in this handoff,
  complete lines only. Mechanical records, the carried ledger and quoted
  conversation are not merged. LedgerBackend.mergeHandoff is additive: it
  never replaces a stored row with an equal or shorter one, and it limits new
  rows per kind instead of taking the first 40 bullets.
- The mechanical checkpoint carries the last complete ledger, the last
  truncated one and the previous segment records from the run state, clipped
  at line boundaries, instead of nesting the whole previous checkpoint.
  Quoted conversation is block-quoted. The stale "next step" section is
  recognised with numbering, emphasis, emoji, no space after #, CRLF; code
  fences are skipped.
- Only the latest four user messages before the task are kept as notes,
  labelled as reference; a message whose task was stopped by the user is
  marked.
- An abort during the handoff request ends the turn without compacting.

Other
- An auto-restarted turn resends the previous turn's messages unchanged and
  attaches a changed runtime context to the resume note, so the provider
  prefix cache still matches.
- Text is never cut inside a surrogate pair; LlmClient replaces lone
  surrogates when it serialises the request body.
- Stop notices are returned as `notice`; AgentSession appends them to the
  step list, which is what the sidebar renders.

Tests: selftest-loop-guard rewritten (143 checks), shared AgentSession
harness, one more check each in selftest-toolrouter and selftest-panel-live.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… breaker

signer_trace, closure_read, debug_breakpoint, hook_inject and whitebox_diff are
used as start -> trigger -> query -> stop per sample; their start/stop receipts
are identical every time, so within one turn the 11th start was refused by the
repeat breaker as "same arguments, same result". The breaker is meant for
read-only queries that keep returning the same thing, not for switches.

`repeatExempt` in the tool declaration now also accepts a list of action names:
the call is exempt only when args.action is one of them. The five tracer tools
declare ["start", "stop"]; cookies declares ["set", "remove"]; clear_site_data
(a per-sample reset) is exempt entirely. Their query/list actions stay under the
breaker. ToolRouter.isRepeatExempt(name, args) does the check; AgentLoop passes
the parsed arguments.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@WhiteNightShadow
WhiteNightShadow merged commit 82199d1 into main Nov 9, 2026
2 checks passed
@WhiteNightShadow
WhiteNightShadow deleted the fix/long-task-loops branch November 9, 2026 04:21
@WhiteNightShadow WhiteNightShadow mentioned this pull request Nov 9, 2026
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