Skip to content

fix(traex): 修复临时起轮误吞回复和完成后输入隔离 - #2480

Merged
deepcoldy merged 1 commit into
deepcoldy:masterfrom
xinna2001:fix/traex-confirmed-input-quarantine-20261028
Oct 28, 2026
Merged

deepcoldy merged 1 commit into
deepcoldy:masterfrom
xinna2001:fix/traex-confirmed-input-quarantine-20261028

Conversation

@xinna2001

@xinna2001 xinna2001 commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

问题与结果

TraeX 已执行并回复,Botmux 却仍报 submit_unconfirmed,后续消息留在 Holding ... pending message(s) behind unconfirmed input delivery。本次修复两条已独立复现的路径:

  • 临时起轮误吞当前回复:task_started 先被残留旧轮次临时认领;当前 user 记录不带 message id 时,被提前当成同 native turn 的重复记录忽略。尚未由 user 佐证的临时起点继续接受后继指纹匹配,保留慢 hook 保护与已佐证 user 的去重。
  • 原生完成/成功发送早于接收确认返回:按 (turnId, dispatchAttempt, cliGeneration) 保留有界的真实写入起点和原生终态;设置输入隔离前检查早到终态,延迟确认从实际写入时刻检查精确发送证据。合成的失败或 ambiguous 终态不算原生接收证据。

解除隔离后重新检查待投递消息:composer 已就绪时直接排空,无须等待新 PTY 边缘;未就绪时重新触发 idle 检查。微任务再次验证 backend、generation 和重启状态。旧轮次已有精确成功发送回执时,过期剪枝不再追加“采集不到回复”告警。

时序与影响范围

共享结构化队列、Worker 提交确认/输入隔离,以及普通写入与 adopt 路径共用精确证据。每次 spawn 和 restart 清掉旧 generation 证据;终态后 composer 检查、忙碌输入保护仍生效。没有本轮接收证据时继续隔离,不自动重放不明确输入,不使用无关轮次终态解除隔离。

结构化输入的弱 pty-output 活动证据在 20 秒 recheck 后进入有界 confirmed lease,31 秒时不会按原 verification grace 提前剪枝;它不构成无限续命。若 callback 延迟到精确 head 已被剪枝之后,跳过 adapter recheck,不持久化旧 session id、不调用释放隔离回调,等待其它精确终态或 generation 重建。

回归测试

  • 两个既有 worker harness 注入真实 InputDeliveryEvidenceTracker,补齐实际依赖,修复 CI 首跑的 6 个失败用例。
  • 新增 11 个行为用例,覆盖 spawn/restart 清理真实证据、静态屏幕下只投递一次、未就绪 idle 重驱、微任务前 restart/backend/generation 变化、结构化弱证据租约与先剪枝后 recheck 的排序语义、早到终态不打印虚假的 queued 日志。既有剪枝测试另覆盖按精确 turnId 返回的发送证据豁免及真实写入 baseline。
  • Worker function harness 通过 AST 将 import.meta.url 保留为 worker 模块的实际 URL,支持执行真实 spawn 函数而不启动 Worker 入口。
  • 保留真实 Worker + 私有 tmux 的五种集成场景;rollout 目录使用当前日期,标注 macOS 私有 socket 的路径长度约束。

验证

基于最新 origin/master 的 94e307acc;环境为 macOS、Node 24.16.0、Bun 1.4.3、Vitest 4.1.11。

  • Node/Vitest 定向回归:15 个文件,459 passed,包括队列、证据、提交确认、失败链、TraeX adapter、bridge fallback、重启、测试 hygiene 与 Bun selectors。
  • Bun:复用 scripts/run-bun-tests.mjs 的选择器、启动前隔离和每文件独立进程执行,限定相同的 15 个文件,15/15 文件通过。
  • 真实 Worker + 私有 tmux:early-terminal、early-send、late-terminal、history、unknown,5/5 通过,后续消息按顺序仅投递一次。
  • 异常时序探针:人工重启发生在回执等待中、部分写入只产生合成终态、真实发送先到、await 中 generation 更换、await 中精确 head 过期,5/5 通过;另复跑部分/中止转录相关用例 6/6。
  • 删除式变异:spawn 清理、restart 清理、精确发送豁免、整个 terminal redrive、ready 时直接 flush,以及 restart/backend/generation 守卫、structuredTarget 回退,共 9 项在 Vitest 与 Bun 下均被对应断言检出。
  • 最后一次主干同步后复跑:14 文件 458 passed;既有屏幕更新计数用例并行运行出现一次 3→4 采样漂移,单独重跑通过。同组 Bun 15/15 文件通过。该用例与主干内容相同,未修改其断言;受测生产文件与先前 459 passed 的版本内容相同。
  • 修改后的测试文件与 helper 独立 TypeScript 检查通过;bun run build 完整构建通过;git diff --check 通过。

全部 CLI 场景使用可控假 TRAE,未调用真实模型。测试中的飞书投递通过 IPC 记录,没有向真实会话发送测试消息;本机正式 Botmux 未部署或重启。Linux 和全仓库验证由新 head 的官方 CI 执行。

@deepcoldy

Copy link
Copy Markdown
Owner

自动评审初步意见(最终以维护者审阅为准):

生产改动的方向和实现经核对没有发现阻断问题,四处改动都有真实行为对应:

  1. CodexBridgeQueue 镜像守卫把仅有 task_started 的 provisional claim 排除,指纹后继可以越过丢失输入的旧认领拿到终态;native message id 的去重、指纹/新鲜度与 10 分钟 corroboration 保护均保留。
  2. 新增 InputDeliveryEvidenceTracker:按 (turnId, dispatchAttempt, cliGeneration) 精确记录写入时刻与原生终态,合成的失败/ambiguous 终态不进入,容量有界且在 CLI generation 更换时清理;武装 quarantine 前检查早到终态,避免漏放唯一的释放信号。
  3. 延迟确认链的活动证据窗口锚到真实写入时刻(原来锚在适配器 history 轮询结束之后),早于 submitted:false 返回的 botmux send 标记能正确取消告警。
  4. 预启动租约剪枝时,本轮已有精确 botmux-send 回执的旧轮次不再追加"采集不到回复"告警;quarantine 释放后的重驱增加了 backend/generation/restart 校验。

但本 PR 当前 CI 首跑是红的,需要先修(本地已复现,vitest 与 bun 双引擎一致):

  • test/worker-durable-expiry-order.test.ts(3 个用例):spawnCli/restartCliProcess 新增的 inputDeliveryEvidence.clear() 是 worker 闭包自由变量,worker-function-harness 未注入,报 Cannot read properties of undefined (reading 'clear')。
  • test/worker-structured-uncollected-notice.test.ts(3 个用例):pruneExpiredStructuredHeadsAndEmit 新增的证据豁免子句引用 process-global inputDeliveryEvidence 和 submitActivityEvidenceSince,harness 未注入,报 Cannot read properties of undefined (reading 'writeStartedAtMs')。同一测试文件在 master 上 4/4 通过,可确认是本 PR 引入。

建议的修法(任选其一,倾向前者):

  • 直接在两个 harness 的 scope 里注入真实的 InputDeliveryEvidenceTracker(已是独立可导出 service)和一个返回 undefined 的 submitActivityEvidenceSince stub;
  • 或者把"本轮是否有精确 botmux-send 回执可豁免采集失败通知"抽成可导出的纯函数(输入 baseline/identity/send markers),prune 内调用,测试直接断言纯函数,避免继续往 harness 里堆自由变量。

两个非阻断的小建议:

  • 早到终态跳过 quarantine 武装后,延迟确认链仍会被 schedule(20 秒后以 stale-attempt 静默退出),会多一个定时器和一条误导性的 "deferred recheck queued" 日志;能在同一证据分支跳过 schedule 更干净。
  • 新增集成测试里 rollout 路径硬编码了 2026/10/28 日期目录;目前按 session id 全树扫描仍能找到历史目录、不会失效,但用 new Date() 生成更稳妥。

本地验证(Linux):定向相关测试 vitest 全绿(queue 112、evidence 10、submit-confirmation/failure-chain/grok/pi/traex/deferred 等 80、write-input/correlation/wording/bridge-gate 335);新增 5 场景真实 worker + 私有 tmux 集成测试 5/5 通过;对四处生产守卫分别做删除式变异,均被对应测试咬红(queue 守卫变异 vitest+bun 双引擎红);bun run build 通过。CI 上 build / 三平台 bun-binary / network-boundary 已绿,test 分片 1/4、3/4 绿,2/4、4/4 与 bun-test 仅因上述两个既有测试文件失败。

@deepcoldy

Copy link
Copy Markdown
Owner

双审已收敛,结论:仍需修改。生产代码四处改动经两轮独立变异复验未发现阻断,但需补齐测试后再过。以下为合并后的完整修改清单(第 2、3 项与第 1 项的断言要求为维护者复审补充,均已本地复跑验证):

1. P1|修复两个既有 harness(CI 首跑红 6 用例,vitest / bun 双引擎一致)

修法(已验证 vitest + bun + test-hygiene + tsc 全绿):注入真实 InputDeliveryEvidenceTracker,不要用裸 stub,也不必为此抽纯函数:

--- test/worker-durable-expiry-order.test.ts
+import { InputDeliveryEvidenceTracker } from '../src/services/input-delivery-evidence.js'
     submitFailureChains: { clear: vi.fn() },
+    inputDeliveryEvidence: new InputDeliveryEvidenceTracker(),

--- test/worker-structured-uncollected-notice.test.ts
+import { InputDeliveryEvidenceTracker } from '../src/services/input-delivery-evidence.js'
     structuredTurnsWithSubmitNotice: new Set(['om_write_failed']),
+    inputDeliveryEvidence: new InputDeliveryEvidenceTracker(),
+    // 只有「这条 input 之后确实有过 botmux send」的回合才豁免告警。
+    submitActivityEvidenceSince: (_sinceMs: number, identity?: { turnId?: string }) =>
+      identity?.turnId === 'om_sent_during_receipt' ? 'botmux-send' : undefined,
     submitFailureChains: {
@@
       { turnId: 'om_rechecking', started: false },
+      { turnId: 'om_sent_during_receipt', started: false },
     ])

同时必须补断言,否则只是修绿、新守卫仍零覆盖(已变异验证:只注入不补断言时,删掉 src 对应守卫全套测试照绿):

  • worker-durable-expiry-order:restart 前先 start() 一条旧代证据,restart 后断言 hasStructuredTerminal 为 false、writeStartedAtMs 为 undefined——守住 spawnCli / restartCliProcess 两处 inputDeliveryEvidence.clear()(当前零守护)。
  • worker-structured-uncollected-notice:submitActivityEvidenceSince 必须是按 turnId 返回 'botmux-send' 的行为 stub(写成 () => undefined 只够修绿),dropped 里加 om_sent_during_receipt 让新豁免分支真正被走到(已验证:删掉 worker 里 || submitActivityEvidenceSince(...) === 'botmux-send' 子句,该用例立即红)。

2. P2|structuredTarget: false → codexBridgeActive 当前零测试守护,且带出一条新排序语义

把这处改回 false,5 个集成场景 + 317 个相关单测(codex-bridge-queue / submit-confirmation / traex-adapter-submit / bridge-fallback-gate / input-delivery-evidence / deferred-schedule-settlement)全绿——CI 目前对这处改动不可证伪。

另一个需要确认的副作用:settleDeferredSubmitConfirmation 的 targetStillCurrent() 在适配器 recheck() 之前判定。structuredTarget=true 时,一旦 head 已被 30s verification grace 剪枝,recheck 根本不会执行(探针:recheckCalls=0),onConfirmed 也不会被调用——而它是 quarantine 唯一的主动释放回调;旧值下同一时间线 recheck 仍会执行并能 suppress-confirmed + persistCliSessionId。20s recheck 通常先于剪枝、窗口很窄,且改动方向(与 adopt 路径 13221 行的 true 对齐、对其它结构化桥是把弱证据变成 20s 有界确认租约的放宽、不会无限续命)是对的,但这条排序语义需要测试明确承认。

请在 test/submit-confirmation.test.ts 补一条假时钟用例钉住:弱 pty-output 证据下 settlement.lifecycle === 'confirmed'(旧值给 'unchanged');31s tick 后 head 存活、不发 terminal(旧值剪枝并 emit ambiguous structured_start_timeout)。该用例对 true→false 变异须咬红(已实测)。

3. 测试缺口|redriveTerminal 新路径目前完全无守护

删除 releaseInputDeliveryQuarantine 里整段 queueMicrotask redrive,5 个集成场景全绿(fixture 终态会重绘 idle 屏,PTY idle edge 兜底投递,测不到该路径真正服务的"终态后静态屏幕无新 PTY 边缘"场景);cliRestartInProgress 守卫、ready 时直 flushPending() 两个分支删改后同样全部存活。请补 worker-function-harness 用例(3–4 行即可咬红):

const release = loadWorkerFunction('releaseInputDeliveryQuarantine', {
  backend, cliSpawnGeneration: 7, cliRestartInProgress: false, isPromptReady: true,
  inputDeliveryQuarantine: quarantine, flushPending: vi.fn(async () => {}),
  idleDetector: { fireIdle: vi.fn() }, log: vi.fn(),
})
release(quarantine, 'x', { redriveTerminal: true })
await Promise.resolve()
expect(flushPending).toHaveBeenCalledTimes(1)   // 改成只 fireIdle / 删掉整段 时咬红

另置 cliRestartInProgress: true 断言 flushPending 与 fireIdle 均不被调用(守住重启中分支)。

4. nit|一条与事实相反的日志(首审"多一个定时器"经复审证伪,下调为 nit)

早到原生终态时 chain key 已进入 terminalReceipts,submitFailureChains.schedule() 返回 armed: false 不挂 timer(实测 chains.size()=0),但 worker.ts:17546 的 deferred 20000ms recheck queued 在 schedule 之前无条件打印。建议把该日志移入 armDeferredRecheck 按 armed 决定是否打印(不要省整个 schedule 分支,那会丢失终态登记路径)。

5. 可选

  • 集成测试 rollout 路径硬编码 2026/10/28 已确认不致命(date-tree 按目录名形状递归扫,换成 2019/01/02 仍绿),改 new Date() 生成更好读;
  • 默认 $TMPDIR 下私有 tmux socket 路径超过 104 字符会导致 worker 启动即退(复跑需 TMPDIR=/tmp),建议在用例注释里写一句,方便他人复跑。

验证基线(两轮评审合计)

  • tsc 0 错、bun run build 通过;
  • 生产四处守卫删除式变异全部被测试咬红(queue 镜像守卫 vitest+bun 双引擎;arm 早到终态检查、baseline 锚点、prune 豁免由 5 场景真实 worker + 私有 tmux 集成测试咬住;tracker 身份隔离单测 7/10 红);
  • 新增集成 5/5 通过(early-terminal / early-send / late-terminal / history / unknown);
  • CI 首跑:build、三平台 bun-binary、network-boundary、test 1/4、3/4 绿;2/4、4/4、bun-test 仅因第 1 项两个既有测试文件红。

push 新 head 后我们会在新 head 上全套重审,再请维护者在新 head 表态。

@deepcoldy

Copy link
Copy Markdown
Owner

对上一条清单(6471039708)的两处勘误,均已在当前 head 15a6f8e86 本地复跑验证,请以本条为准:

勘误 1|第 4 项 nit 不能只改日志,必须连带改集成用例同步点

只把日志改成按 armed 门控、不动测试,会新打红 early-terminal(实测 27.5s timeout: adapter receipt exhausted):集成用例第 143 行把 deferred 20000ms recheck queued 这句日志当作"适配器回执轮询已结束"的同步点,而 early-terminal 恰是终态早于回执、armed=false 的场景,门控后该句永不出现。

最小正确组合(已验证:集成 5/5、tsc 0 错、submit-confirmation / submit-failure-chain / input-delivery-evidence 42 单测全绿):

--- a/src/worker.ts
-  log(`writeInput: submit not confirmed after retries — deferred ${SUBMIT_DEFERRED_RECHECK_MS}ms recheck queued. preview="${preview}"`)
   const runDeferredRecheck = ...
@@ const armDeferredRecheck
-    const { replaced } = submitFailureChains.schedule(...)
-    if (replaced) { log(`Deferred recheck already live ...`) }
+    const { armed, replaced } = submitFailureChains.schedule(...)
+    if (armed) {
+      log(`writeInput: submit not confirmed after retries — deferred ${SUBMIT_DEFERRED_RECHECK_MS}ms recheck queued. preview="${preview}"`)
+    } else if (replaced) {
+      log(`Deferred recheck already live for this attempt — replaced timer instead of stacking. preview="${preview}"`)
+    } else {
+      log(`writeInput: submit not confirmed after retries — no recheck armed for this attempt (already settled). preview="${preview}"`)
+    }
--- a/test/traex-input-delivery-evidence.integration.test.ts
-          await wait(() => logs.join('').includes('deferred 20000ms recheck queued'), 'adapter receipt exhausted')
+          await wait(() => logs.join('').includes('writeInput: submit not confirmed after retries'), 'adapter receipt exhausted')

注意保留独立的 replaced 分支——"替换了已有 timer"和"控制器拒绝挂 timer(已终态)"是两回事,三元按 armed 覆盖会吞掉前者。不要删整个 schedule 分支,那会丢失 chain key 的终态登记路径。

勘误 2|第 2 项 P2 补的假时钟用例只构成"部分闭环"

该用例能钉住 settleDeferredSubmitConfirmation 的 structuredTarget 语义(已实测:把 service 内该分支强制关掉,TRUE 分支立即从 confirmed/不剪枝 退化为 unchanged/剪枝,用例咬红),但钉不住 worker 调用点传参——把 worker.ts:19081 的 codexBridgeActive 改回 false,303+ 个相关用例仍全绿(调用点在 1100 行的 flushPending 内,现有 harness 只能整体执行)。可二选一:

  • 接受这个残留(纯函数语义已有守护,接线靠 review);或
  • 在 worker 里抽一个 submitFailureStructuredTarget() 之类的可测小函数再单测调用点。

另:用例 FALSE 分支的正确期望是 { lifecycle: 'unchanged', stillPending: false, pruned: ['om_slow_receipt'] }——mark() 会以 markTimeMs 初始化 unconfirmedAttributionStartedAtMs,到 31s 时 20s unconfirmed 租约已过期、head 已被剪掉,故 hasPendingTurn 为 false(读取必须在 pruneExpiredPreStartHeads 之后)。

补充|第 3 项 redriveTerminal 用例

releaseInputDeliveryQuarantine 是顶层函数,worker-function-harness 可直接加载(注入 backend / cliSpawnGeneration / cliRestartInProgress / isPromptReady / inputDeliveryQuarantine / flushPending / idleDetector / log),按上一条给的原型写即可,需覆盖三态 + 不带 redriveTerminal 不动作(opt-in 边界)。这部分没有现成 patch 可抄,需要新写。

其余各项(P1 两条断言、new Date()、TMPDIR 注释)不变。状态不变:等作者 push 新 head 后在新 head 上全套重审。

@xinna2001
xinna2001 force-pushed the fix/traex-confirmed-input-quarantine-20261028 branch from 15a6f8e to de88101 Compare October 28, 2026 14:55
@xinna2001
xinna2001 force-pushed the fix/traex-confirmed-input-quarantine-20261028 branch from de88101 to ddfe86d Compare October 28, 2026 14:59
@deepcoldy

Copy link
Copy Markdown
Owner

三轮双审已收敛,以下为最终修改清单和一份参考补丁(在当前 head 15a6f8e86 上 git apply 即可,含 1 个新测试文件)。该补丁已由评审双方分别独立 apply 实跑通过;你也可以用等价的自己的实现,push 后我们以新 head 全套重审为准。

清单

项 内容
P1-1 两个既有 harness(worker-durable-expiry-order / worker-structured-uncollected-notice)注入真实 InputDeliveryEvidenceTracker,修复 CI 首跑 6 个红用例
P1-2 submitActivityEvidenceSince 用行为 stub(按 turnId 返回 'botmux-send',不能写成 () => undefined),dropped 加 om_sent_during_receipt 走通 prune 新豁免分支
P1-3 restart 后旧代证据被清的断言(守住 restart 路径的 inputDeliveryEvidence.clear();spawnCli 初次启动时 tracker 本就为空,同一 clear() 实现不再重复断言)
P2 test/submit-confirmation.test.ts 假时钟用例:弱 pty-output 证据下 structuredTarget=true → confirmed 租约/31s 不剪枝;false → unchanged/剪枝。注意 FALSE 期望 stillPending: false(mark() 以 markTimeMs 初始化 unconfirmedAttributionStartedAtMs,31s 时 20s 租约已过期,且必须先 prune 再读 hasPendingTurn)
GAP 新增 test/worker-input-delivery-redrive.test.ts 五态:ready 直 flush / 未 ready fireIdle / restart 中不动作 / 代际变化不动作 / 未 opt-in 不动作
nit recheck 日志改三分支(armed 新挂 / replaced 替换 / 两者皆否=已终态拒挂),同时把集成用例 143 行同步点放宽为 writeInput: submit not confirmed after retries,两处必须一起改,否则 early-terminal 必超时
可选 1 集成 fixture rollout 路径的 2026/10/28 改 new Date() 生成(不致命,date-tree 只校验目录名形状)
可选 2 集成用例注释里写明复跑需 TMPDIR=/tmp(默认 TMPDIR 下私有 tmux socket 超 104 字符,worker 启动即退)

一个已知的"部分闭环"(可选做 P2')

P2 用例只钉住 settleDeferredSubmitConfirmation 的语义,钉不住 worker.ts:19081 调用点传参(flushPending 约 1100 行,现有 harness 无法局部执行;把 codexBridgeActive 改回 false 全套单测仍绿)。若要彻底闭环,可抽一个 submitFailureStructuredTarget() 小函数再单测调用点。抽的时候请注意调用点共 5 处(13166 / 13220 / 19072 / 29454 / 29470):其中 29454 / 29470 的 argv-baked 首轮路径硬传 false,而该路径在 worker.ts:29288-29289 mark 后已立即 confirmPendingTurn——这个 false 看起来是刻意的(生命周期另有 watch 收口),但请在抽函数时确认并加注释说明,不要机械统一成 codexBridgeActive。不做这一项不阻断合入。

参考补丁验证记录(评审侧独立复跑)

  • git apply --check 干净;tsc --noEmit 0 错;
  • vitest:submit-confirmation / worker-durable-expiry-order / worker-structured-uncollected-notice / worker-input-delivery-redrive 共 30 测全绿;traex-input-delivery-evidence 集成 5/5(约 145s);
  • bun 引擎:redrive 5、uncollected-notice 4、durable-expiry-order 3 全绿;test-hygiene 26 绿;
  • 变异复验:删 cliRestartInProgress 守卫 → restart 用例红;ready 分支退化为只 fireIdle → ready-flush 用例红;删整段 redrive microtask → 2 红;service 内 structuredTarget 分支强制关闭 → P2 用例 TRUE 分支退化变红。
diff --git a/src/worker.ts b/src/worker.ts
index 5b3c09988..0ee3fc358 100644
--- a/src/worker.ts
+++ b/src/worker.ts
@@ -17543,7 +17543,6 @@ function scheduleSubmitFailureNotify(
   // With botmux's SessionStart hook armed, that signal and the transcript are
   // the only arbiters (see decideSessionStartGatedSubmitWarning).
   const sessionStartGated = readyGate.isArmed;
-  log(`writeInput: submit not confirmed after retries — deferred ${SUBMIT_DEFERRED_RECHECK_MS}ms recheck queued. preview="${preview}"`);
   const runDeferredRecheck = async (chainIsCurrent: () => boolean): Promise<void> => {
     const settlement = await settleDeferredSubmitConfirmation(codexBridgeQueue, {
       turnId: bridgeTurnId,
@@ -17735,13 +17734,21 @@ function scheduleSubmitFailureNotify(
   };
   const armDeferredRecheck = (): void => {
     deferredRecheckAttempts++;
-    const { replaced } = submitFailureChains.schedule(
+    const { armed, replaced } = submitFailureChains.schedule(
       chainKey,
       SUBMIT_DEFERRED_RECHECK_MS,
       runDeferredRecheck,
     );
-    if (replaced) {
+    // Three distinct outcomes, and the log must not conflate them: a native
+    // terminal can arrive while writeInput awaits its receipt, and the
+    // controller then refuses the timer outright (armed && replaced both
+    // false). Claiming that one was "queued" is the misleading case.
+    if (armed) {
+      log(`writeInput: submit not confirmed after retries — deferred ${SUBMIT_DEFERRED_RECHECK_MS}ms recheck queued. preview="${preview}"`);
+    } else if (replaced) {
       log(`Deferred recheck already live for this attempt — replaced timer instead of stacking. preview="${preview}"`);
+    } else {
+      log(`writeInput: submit not confirmed after retries — no recheck armed for this attempt (already settled). preview="${preview}"`);
     }
   };
   armDeferredRecheck();
diff --git a/test/submit-confirmation.test.ts b/test/submit-confirmation.test.ts
index eace6f8d3..7cc9f9109 100644
--- a/test/submit-confirmation.test.ts
+++ b/test/submit-confirmation.test.ts
@@ -111,6 +111,51 @@ describe('decideSubmitConfirmationAction', () => {
     ]);
   });
 
+  it('keeps a weak-evidence confirmed head alive past the attribution lease (structuredTarget)', async () => {
+    // A CLI whose submit receipt is slow (traex/codex history.jsonl) returns
+    // {submitted:false, recheck}; the deferred chain then sees only weak
+    // pty-output. On a structured target that weak evidence must install the
+    // bounded CONFIRMED lease, not leave the mark on its unconfirmed
+    // attribution clock: otherwise the 1s expiry tick prunes the head and the
+    // worker emits an ambiguous structured_start_timeout for a turn that is
+    // still running. Without `structuredTarget` the same timeline prunes.
+    const run = async (structuredTarget: boolean) => {
+      let now = 0;
+      const queue = new CodexBridgeQueue(() => now);
+      queue.mark('om_slow_receipt', 'check version', 0, 5);
+      queue.beginSubmitVerification('om_slow_receipt', 0, 5);
+      now = 20_000;
+      const settlement = await settleDeferredSubmitConfirmation(queue, {
+        turnId: 'om_slow_receipt',
+        dispatchAttempt: 5,
+        structuredTarget,
+        recheck: async () => false,
+        usageLimitDetected: () => false,
+        activityEvidence: () => 'pty-output',
+      });
+      now = 31_000;
+      const pruned = queue.pruneExpiredPreStartHeads(now).map(turn => turn.turnId);
+      return {
+        lifecycle: settlement.lifecycle,
+        stillPending: queue.hasPendingTurn('om_slow_receipt', 5),
+        pruned,
+      };
+    };
+
+    expect(await run(true)).toEqual({
+      lifecycle: 'confirmed',
+      stillPending: true,
+      pruned: [],
+    });
+    // Why the flag matters: the identical evidence without it leaves the head
+    // on the shorter unconfirmed clock, so the very next tick drops it.
+    expect(await run(false)).toEqual({
+      lifecycle: 'unchanged',
+      stillPending: false,
+      pruned: ['om_slow_receipt'],
+    });
+  });
+
   it('still runs Claude deferred rechecks whose bridge ID is not in the structured queue', async () => {
     const structuredQueue = new CodexBridgeQueue();
     let recheckCalls = 0;
diff --git a/test/traex-input-delivery-evidence.integration.test.ts b/test/traex-input-delivery-evidence.integration.test.ts
index 174fa17de..c596c4474 100644
--- a/test/traex-input-delivery-evidence.integration.test.ts
+++ b/test/traex-input-delivery-evidence.integration.test.ts
@@ -140,7 +140,7 @@ setInterval(() => {
         }
         if (mode === 'early-send') await wait(() => existsSync(sendMarker), 'send during adapter wait');
         if (mode !== 'history') {
-          await wait(() => logs.join('').includes('deferred 20000ms recheck queued'), 'adapter receipt exhausted');
+          await wait(() => logs.join('').includes('writeInput: submit not confirmed after retries'), 'adapter receipt exhausted');
         }
         sent('diagnose one', 'om_follow_one');
         sent('diagnose two', 'om_follow_two');
diff --git a/test/worker-durable-expiry-order.test.ts b/test/worker-durable-expiry-order.test.ts
index a5a4c6820..852affaf4 100644
--- a/test/worker-durable-expiry-order.test.ts
+++ b/test/worker-durable-expiry-order.test.ts
@@ -11,6 +11,7 @@ import { describe, expect, it, vi } from 'vitest';
 import { classifyRestartTeardown } from '../src/adapters/backend/destroy-result.js';
 import { isRemoteBackendType } from '../src/core/persistent-backend.js';
 import { decideRestartFollowup, restartLaunchSettings } from '../src/core/restart-followup-policy.js';
+import { InputDeliveryEvidenceTracker } from '../src/services/input-delivery-evidence.js';
 import { loadWorkerFunction } from './helpers/worker-function-harness.js';
 
 type Restart = (reason: string, opts?: { immediate?: boolean; preservePending?: boolean; restartCause?: 'traex-auto-model' }) => Promise<void>;
@@ -23,6 +24,7 @@ function restartHarness(opts: { replacementPromptReadyDuringSpawn: boolean }) {
     lastInitConfig: { cliId: 'claude-code', sessionId: 'sid', workingDir: '/project', resume: false },
     cliSpawnGeneration: 1,
     submitFailureChains: { clear: vi.fn() },
+    inputDeliveryEvidence: new InputDeliveryEvidenceTracker(),
     queuedActivationReceipts: { clear: vi.fn() },
     cliRestartInProgress: false,
     replacementSpawnInProgress: false,
@@ -91,6 +93,8 @@ describe('worker restart input fence', () => {
   it('keeps the input fence armed through teardown and spawn, then leaves the first flush to markPromptReady', async () => {
     const h = restartHarness({ replacementPromptReadyDuringSpawn: false });
 
+    h.scope.inputDeliveryEvidence.start({ turnId: 'old-generation', cliGeneration: 1 }, 1);
+
     await h.restart('daemon request', { preservePending: true });
     // Old backend torn down, replacement not spawned yet: fence still armed.
     expect(h.scope.killCli).toHaveBeenCalledWith({ preservePending: true, preservePolicyCapability: true });
@@ -105,6 +109,14 @@ describe('worker restart input fence', () => {
     // The replacement process exists but its prompt is not ready: no
     // type-ahead wake from the restart continuation.
     expect(h.scope.flushPending).not.toHaveBeenCalled();
+    // Old-generation evidence must not survive into the replacement: a stale
+    // native terminal would silently suppress this generation's quarantine.
+    expect(h.scope.inputDeliveryEvidence.hasStructuredTerminal(
+      { turnId: 'old-generation', cliGeneration: 1 },
+    )).toBe(false);
+    expect(h.scope.inputDeliveryEvidence.writeStartedAtMs(
+      { turnId: 'old-generation', cliGeneration: 1 },
+    )).toBeUndefined();
   });
 
   it('wakes queued input once when the replacement prompt became ready during the fence', async () => {
diff --git a/test/worker-input-delivery-redrive.test.ts b/test/worker-input-delivery-redrive.test.ts
new file mode 100644
index 000000000..9dd64b81b
--- /dev/null
+++ b/test/worker-input-delivery-redrive.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Executes the worker's real releaseInputDeliveryQuarantine (extracted from
+ * src/worker.ts, see helpers/worker-function-harness.ts): what the quarantine
+ * release does to the queued successors.
+ *
+ * The integration fixture cannot cover this. Its fake CLI redraws an idle
+ * screen after every terminal, so the ordinary PTY idle edge delivers the
+ * held messages whether or not the release re-drives anything — deleting the
+ * whole redrive microtask leaves test/traex-input-delivery-evidence green.
+ * The case this code exists for is the opposite one: the native terminal was
+ * the LAST output of the turn, so no further PTY edge will ever arrive and
+ * without an explicit re-drive the held successors stay parked forever.
+ */
+import { describe, expect, it, vi } from 'vitest';
+import { loadWorkerFunction } from './helpers/worker-function-harness.js';
+
+type Release = (q: unknown, reason: string, opts?: { redriveTerminal?: boolean }) => boolean;
+
+/** The release toggles module-global state, so each case gets its own scope. */
+function harness(opts: { promptReady: boolean; restarting?: boolean; generation?: number }) {
+  const backend = { id: 'backend-at-arm' };
+  const quarantine = { backend, generation: 7, turnId: 'om_first', dispatchAttempt: undefined };
+  const scope: Record<string, any> = {
+    backend,
+    cliSpawnGeneration: opts.generation ?? 7,
+    cliRestartInProgress: opts.restarting ?? false,
+    isPromptReady: opts.promptReady,
+    inputDeliveryQuarantine: quarantine,
+    flushPending: vi.fn(async () => {}),
+    idleDetector: { fireIdle: vi.fn() },
+    log: vi.fn(),
+  };
+  return {
+    scope,
+    quarantine,
+    release: loadWorkerFunction<Release>('releaseInputDeliveryQuarantine', scope),
+  };
+}
+
+describe('worker quarantine release re-drive', () => {
+  it('flushes the held successors directly when the CLI is already ready', async () => {
+    const { scope, quarantine, release } = harness({ promptReady: true });
+
+    expect(release(quarantine, 'authoritative deferred submit evidence', { redriveTerminal: true })).toBe(true);
+    await Promise.resolve();
+
+    // Ready + a quiet screen: the idle detector is already idle, so fireIdle()
+    // would be a no-op and nothing would drain the queue. The release has to
+    // call flushPending itself.
+    expect(scope.flushPending).toHaveBeenCalledTimes(1);
+    expect(scope.idleDetector.fireIdle).not.toHaveBeenCalled();
+  });
+
+  it('fires the idle edge when readiness has not been published yet', async () => {
+    const { scope, quarantine, release } = harness({ promptReady: false });
+
+    release(quarantine, 'authoritative deferred submit evidence', { redriveTerminal: true });
+    await Promise.resolve();
+
+    expect(scope.idleDetector.fireIdle).toHaveBeenCalledTimes(1);
+    expect(scope.flushPending).not.toHaveBeenCalled();
+  });
+
+  it('does not re-drive into a generation that is being restarted away', async () => {
+    const { scope, quarantine, release } = harness({ promptReady: true, restarting: true });
+
+    release(quarantine, 'authoritative deferred submit evidence', { redriveTerminal: true });
+    await Promise.resolve();
+
+    expect(scope.flushPending).not.toHaveBeenCalled();
+    expect(scope.idleDetector.fireIdle).not.toHaveBeenCalled();
+  });
+
+  it('does not re-drive once the backend generation moved on', async () => {
+    const { scope, quarantine, release } = harness({ promptReady: true, generation: 8 });
+
+    release(quarantine, 'authoritative deferred submit evidence', { redriveTerminal: true });
+    await Promise.resolve();
+
+    expect(scope.flushPending).not.toHaveBeenCalled();
+    expect(scope.idleDetector.fireIdle).not.toHaveBeenCalled();
+  });
+
+  it('leaves the queue alone when the caller did not opt in', async () => {
+    const { scope, quarantine, release } = harness({ promptReady: true });
+
+    expect(release(quarantine, 'notify-only release')).toBe(true);
+    await Promise.resolve();
+
+    expect(scope.flushPending).not.toHaveBeenCalled();
+    expect(scope.idleDetector.fireIdle).not.toHaveBeenCalled();
+  });
+});
diff --git a/test/worker-structured-uncollected-notice.test.ts b/test/worker-structured-uncollected-notice.test.ts
index 4ec991647..e06a00dbc 100644
--- a/test/worker-structured-uncollected-notice.test.ts
+++ b/test/worker-structured-uncollected-notice.test.ts
@@ -7,6 +7,7 @@
 import { describe, expect, it, vi } from 'vitest';
 import type { CodexPendingTurn } from '../src/services/codex-bridge-queue.js';
 import { uncollectedTurnsNeedingNotice } from '../src/services/structured-uncollected-notice.js';
+import { InputDeliveryEvidenceTracker } from '../src/services/input-delivery-evidence.js';
 import { loadWorkerFunction } from './helpers/worker-function-harness.js';
 
 /** CLI readiness as the worker tracks it. Default: the CLI did come up. */
@@ -59,6 +60,10 @@ function harness(dropped: CodexPendingTurn[], readiness: Readiness = { isPromptR
     // The write of this turn threw; its own submit-failure notice is out.
     structuredTurnsWithSubmitNotice: new Set(['om_write_failed']),
     // A deferred submit recheck is still deciding this one.
+    inputDeliveryEvidence: new InputDeliveryEvidenceTracker(),
+    // 只有「这条 input 之后确实有过 botmux send」的回合才豁免告警。
+    submitActivityEvidenceSince: (_sinceMs: number, identity?: { turnId?: string }) =>
+      identity?.turnId === 'om_sent_during_receipt' ? 'botmux-send' : undefined,
     submitFailureChains: {
       has: (key: { turnId?: string; cliGeneration: number }) => key.turnId === 'om_rechecking' && key.cliGeneration === 3,
     },
@@ -82,6 +87,7 @@ describe('worker: expired structured heads', () => {
       { turnId: 'codex-local-1', isLocal: true, started: false },
       { turnId: 'om_write_failed', started: false },
       { turnId: 'om_rechecking', started: false },
+      { turnId: 'om_sent_during_receipt', started: false },
     ]);
 
     expect(prune('structured bridge tick')).toBe(true);

push 新 head 后请确保 CI 在新 head 首跑全绿(含 bun-test),我们会在新 head 上全套重审并做变异复验,再请维护者在新 head 表态,之后才进入合码流程。

@deepcoldy

Copy link
Copy Markdown
Owner

对最终清单(6472504340)再补两点,均为非阻断的完善项:

补充 1(可选 3)|集成用例 late-terminal 的 12s 墙钟在片内并发下偏紧,建议放宽

评审复跑时实测到一次假红:整文件与其它单测文件并发执行时 late-terminal 在 ~30s 超时,单独 -t late-terminal 连续多次、以及整文件 5 场景单独跑均通过。触发条件是与其它测试文件并发抢 CPU,而 unit project 文件并发是开启的(vitest forks pool,CI 每个分片内常态)。预算构成:fake CLI 的 release 文件 25ms 轮询 + complete() 300ms 动画 + rollout 落盘后 worker 约 1s 的 bridge tick + quarantine 释放重驱 + 两轮完整 worker 回合各自的 prompt gate,CPU 饱和时累计超过 12s 是现实的(该 PR 描述里作者自己也记录过此文件并行首跑出现过一次计数漂移、单独跑通过,互相印证)。

建议把非 early-send 分支的两个 12_000 一并放宽(断言全部不变,用例自身 80s 上限余量充足):

-        await wait(() => received().length === 3, 'two successors delivered', mode === 'early-send' ? 55_000 : 12_000);
+        await wait(() => received().length === 3, 'two successors delivered', mode === 'early-send' ? 55_000 : 25_000);
...
-          && m.turnId === 'om_follow_two' && m.status === 'completed'), 'successors completed',
-        mode === 'early-send' ? 35_000 : 12_000);
+          && m.turnId === 'om_follow_two' && m.status === 'completed'), 'successors completed',
+        mode === 'early-send' ? 35_000 : 25_000);

这是纯测试宽松化(真实逻辑失败仍会在 25s 超时红,不会被掩盖),不涉及生产代码。

补充 2|P1-3 措辞精确化:spawnCli 处那行 clear() 不是死代码,请保留

参考补丁只为 restartCliProcess 处的 inputDeliveryEvidence.clear() 补了断言;删除式变异验证显示:删掉 spawnCli(worker.ts:20179 附近)那处 clear(),全部相关测试仍绿。但它不是死代码,理由比"初次启动 tracker 本就为空"更硬:spawnCli 在该行之前已先执行 ++cliSpawnGeneration,而 tracker 的键包含 cliGeneration——上一代条目留着也永远不会命中新一代的查询(同 turnId、新 generation 查 hasStructuredTerminal/writeStartedAtMs 均为空,已实测)。那处 clear() 的可观测作用只剩容量回收(上限 512,不清会让旧代条目白占名额,驱逐方向虽安全但是浪费)。

建议在该行保留一行注释说明"跨代由键隔离,此处理论上无正确性作用,仅回收容量",避免后续维护者看到无测试覆盖而误删。测试只守 restart 处是刻意的:restart 路径才存在"同代证据残留导致错误释放/错误豁免"的可观测窗口,spawn 处的旧代条目结构上不可能影响新代。

其余结论不变。

@deepcoldy
deepcoldy merged commit bf7ebf0 into deepcoldy:master Oct 28, 2026
11 checks passed
@deepcoldy

Copy link
Copy Markdown
Owner

已合并,感谢修复!这个补丁解决了 TraeX 已在终端作答却仍报 submit_unconfirmed、并把后续消息长时间隔离的问题,两处根因(临时起轮的回复归属、完成早于适配器回执的输入隔离时序)都处理得很到位,配套测试也很扎实。

合入时有两处测试侧的小尾巴未包含在内,方便的话欢迎后续单独提(均不影响本次修复的正确性):

  1. test/traex-input-delivery-evidence.integration.test.ts 中 late-terminal / unknown 两个场景的后继消息等待目前是 12s 墙钟,在 CI 分片片内与其它测试文件并发抢 CPU 时偏紧(评审复跑时观察到过一次并发下超时,单独跑稳定通过)。用例自身有 80s 上限,建议把这两处非 early-send 分支放宽到 25s 左右,断言不变。
  2. src/worker.ts 中 spawnCli 路径的 inputDeliveryEvidence.clear() 目前没有直接测试覆盖——这是刻意的(证据键含 CLI generation,跨代天然不串号,这行只用于回收 512 条上限的容量)。建议在该行补一句注释说明,避免后续维护者把它当成无覆盖的死代码删掉(restartCliProcess 路径的那处有测试守住)。

欢迎继续贡献。

deepcoldy pushed a commit to haozhenfei/botmux that referenced this pull request Oct 28, 2026
@github-actions

Copy link
Copy Markdown

🚀 Released in v3.55.0

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.

2 participants