Skip to content

fix(claude): Task 子代理运行时投递的提示也能被确认送达 - #1974

Closed
wzono wants to merge 4 commits into
deepcoldy:masterfrom
wzono:topic/claude-subagent-prompt-detect
Closed

wzono wants to merge 4 commits into
deepcoldy:masterfrom
wzono:topic/claude-subagent-prompt-detect

Conversation

@wzono

@wzono wzono commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

改了什么

Task / Agent 子代理运行期间,用户在飞书发的新消息会被 Claude Code 投递给子代理,写进 <projectDir>/<sid>/subagents/*.jsonl("The user sent a new message while you were working: …")。主会话 jsonl 在子代理返回前没有对应的 user 事件,送达确认只扫描顶层文件,于是误报 submit_unconfirmed,尽管提示其实已经送达并在执行。

  • JsonlFingerprintSearchOptions 新增 includeSubagentTranscripts。开启后额外扫描会话 uuid 目录下一层的 subagents/*.jsonl。只匹配 uuid 形态的目录,不遍历其它嵌套目录。
  • 尾部扫描抽成 jsonlTailMatchFingerprint,顶层与 subagent 文件共用同一套事件解码规则:role:user 文本、可选的 queue-operation enqueue、空白归一化、逐事件时间戳下限。
  • 只有 Claude 适配器的「提示是否送达」布尔判定打开这个选项。需要把匹配路径钉为新监听目标的调用方保持关闭,子代理 jsonl 永远不会替代会话 jsonl 成为 bridge 的监听对象。

影响面

  • 涉及模块:services/claude-transcript.ts、adapters/cli/claude-code.ts。
  • CLI 范围:只有 Claude 家族适配器调用新选项,其它 CLI 不受影响。选项默认关闭,现有调用方行为不变。
  • 开销:只多扫描当前会话 uuid 目录下的 subagents/,每个文件最多读尾部 1MB,与顶层扫描一致。

测试验证

bun run build                      # 通过
npx vitest run --project unit test/claude-transcript.test.ts
# Test Files 1 passed, Tests 127 passed

新增用例:

  • 只有开启 subagent 扫描时才能找到投递给子代理的提示;
  • subagent 文件同样遵守 minMtimeMs;
  • 不下探非会话命名的子目录。

🤖 Generated with Claude Code

zhongweijie.x and others added 2 commits November 3, 2026 12:43
Task/Agent 子代理运行期间投递的输入写入 <sid>/subagents/*.jsonl,主会话
jsonl 在子代理返回前没有 user 事件,送达确认会误判失败。指纹查找新增
includeSubagentTranscripts(仅用于布尔判定,不会把子代理文件钉为监听目标)。

Co-Authored-By: Claude Code <[email protected]>
@wzono
wzono marked this pull request as ready for review November 3, 2026 04:46
@wzono
wzono force-pushed the topic/claude-subagent-prompt-detect branch from 73a136e to 9d6eac0 Compare November 3, 2026 04:46
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T05:51:55.990369Z 28f6a89 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9d6eac0f65

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/services/claude-transcript.ts Outdated
const subFull = join(subDir, subName);
try {
const subSt = statSync(subFull);
if (subSt.isFile()) addCandidateFile(subFull, subSt.mtimeMs);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Distinguish forwarded input from subagent task instructions

When a subagent's initial role:user task instruction falls within the 60-second timestamp floor and contains the next Lark message's fingerprint, this scan treats that model-generated instruction as proof that the new input landed. A fake-clock probe using the real adapter and scanner reproduced this with sendBracketedPaste() returning false and no submit key sent: the parent's recheck() returned false, whereas this version returned true, causing settleDeferredSubmitConfirmation() to choose suppress-confirmed. This silently hides a genuine delivery failure. For child transcripts, require a newly forwarded-user-message record or an equivalent submission-specific boundary rather than accepting arbitrary task instructions as receipts.

AGENTS.md reference: AGENTS.md:L160-L161

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 28f6a89. Subagent transcript receipts now require Claude forwarded-message metadata (isMeta: true); arbitrary initial task instructions can no longer confirm a Lark input. Added a behavioral regression and mutation check. Focused suite: 144/144; build and diff-check pass.

@wzono

wzono commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 28f6a89038

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread test/claude-transcript.test.ts Outdated
const subDir = join(projectDir, sid, 'subagents');
mkdirSync(subDir, { recursive: true });
const subagent = join(subDir, 'agent-aaaaaaaa.jsonl');
writeFileSync(subagent, '{"type":"user","message":{"role":"user","content":"repeatable short prompt"}}\n');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use eligible forwarded events in the exclusion-test fixtures

Both this fixture and the non-session-directory fixture below omit isMeta: true, so jsonlTailMatchFingerprint() rejects them independently of the guards the tests are intended to exercise. In temporary copies running the real scanner, independently removing the minMtimeMs filter or SESSION_SUBDIR_RE check leaves both tests green; adding isMeta: true makes the respective mutation fail. Use otherwise eligible forwarded-message fixtures and positive controls so these tests actually protect the mtime and directory boundaries and satisfy the mutation-check requirement in AGENTS.md.

AGENTS.md reference: AGENTS.md:L162-L162

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9a49411. The exclusion fixtures now use otherwise eligible isMeta forwarded events plus positive controls. Mutation checks confirm removing minMtimeMs or the UUID session-directory guard fails the targeted tests. Focused suite: 144/144; diff-check passes.

@deepcoldy

Copy link
Copy Markdown
Owner

自动评审初步意见:1 个建议修复的问题(P2)+ 2 个收口建议

感谢这个 PR,架构和守卫写得很干净。两轮评审(含一轮独立复审)在机械面上全部认可:开关默认关闭、唯一开启点是 recheck() 的布尔判定、三处会钉路径的调用都未开启、变异守卫全部咬红。但独立复审用本机真实转录数据普查后发现一个功能性问题,建议修复后再合入。这是自动评审的初步意见,最终以维护者审阅为准。

P2:新扫描解不出 CLI 实际写下的那种记录,修复对真实现象很可能不生效

jsonlTailMatchFingerprint 目前只解两种记录:message.role === 'user' 与 type:'queue-operation' + operation:'enqueue'。但 CLI 把「投递给运行中 agent 的人类消息」写成的是第三种形状:

// 顶层 type 是 attachment,没有 message.role;正文在 attachment.prompt
{
  "type": "attachment",
  "timestamp": "2026-11-03T08:05:00.000Z",
  "isSidechain": true,
  "attachment": {
    "type": "queued_command",
    "prompt": "<用户原文>",
    "origin": { "kind": "human" },
    "isMeta": true
    // 主会话完整形状还会带 commandMode: "prompt"
  }
}

代码路径在 CLI bundle 里可以对上:submitToAgent → Hyn({ isMeta: true, origin: { kind: 'human' } }) 写入运行中 agent 的 pendingMessages → flush 时 PDr 产出 { type: 'queued_command', prompt, origin, isMeta } 的 attachment 记录。

本机真实数据普查(866 个项目目录、47 个子代理转录、1078 个会话转录):

记录形状 子代理转录 主会话转录
attachment.queued_command 36(全部 commandMode:'task-notification',attachment 上无 isMeta) origin.kind=human 的 731 条(commandMode:'prompt')
type:'user' + isMeta:true 32(全部是 system-reminder/截断提示/task-notification/开场指令) origin.kind=human 的 0 条
queue-operation 0 数千条

即:本 PR 现在认的 type:user && isMeta 形状,在真实数据里从不携带用户正文;真正的投递路径落在 attachment 这一族。我们用真实形状 + 真实指纹函数做了探针:当前代码对上面两种 human attachment 行都返回 null(期望命中)。

建议修法(已按此写过临时补丁验证:两种 human 形状均正确命中;真实 task-notification 行、缺 isMeta 的 human 行、isMeta 但 origin 非 human 的行均正确返回 null;144 条现有测试双腿仍全绿):在 jsonlTailMatchFingerprint 增加一条分支——

  • 条件:ev.type === 'attachment' 且 ev.attachment?.type === 'queued_command' 且 attachment.commandMode !== 'task-notification'(实测 36 条 task-notification 行该字段恰好都是 'task-notification',而 sidechain flush 的最小形状不带该字段,不会被误伤);
  • 正文取 attachment.prompt(非字符串时走 stringifyUserContent);
  • 子代理候选(requireForwardedSubagentMessage)额外要求 attachment.isMeta === true 且 attachment.origin?.kind === 'human';
  • 该分支同样受逐事件 minEventTimestampMs 约束(attachment 行顶层有 timestamp,已验证)。

两个实现时请注意的点:

  1. 影响面:jsonlTailMatchFingerprint 也被顶层文件扫描共用(worker.ts 的会话切换扫描同样经过它,且不传 includeQueueOperations)。新分支若无条件生效会改变既有调用方行为。建议把它挂在显式 opt-in 选项后(只在 submit 确认路径开启),或在 PR 描述里论证顶层 attachment 匹配对切换判定无副作用。
  2. 请按仓库测试规范补 attachment 形状的用例(PDr 最小形状 + 完整 commandMode 形状 + task-notification 排除对照),并对新分支做摘除式变异确认咬红。

P3-1:isMeta 边界仍放行全部 isMeta user 记录

本机 47 个子代理转录中有 2 个的第 0 条开场任务指令本身就是 type:'user', isMeta:true(内容是 review 指令,可能含用户原文前缀)。30 字符指纹 + 60s 双窗下误判概率很低,但误判方向是「真实投递失败被静默确认」。建议子代理候选不要接受任意 isMeta user 文本:随 P2 一起把 user 分支收紧为内容以 "The user sent a new message while you were working:" 开头(CLI 的 M9n 包装器前缀),或直接只认 P2 的 attachment human 分支。

P3-2:queue-operation 分支在子代理候选上没有边界

子代理扫描带了 includeQueueOperations: true,但该分支不受 requireForwardedSubagentMessage 约束(当前子代理转录中 queue-operation 记录为 0,不可达,但不变量是分形状的)。建议子代理候选显式关掉 queue-operation 匹配,或加注释说明该前提。

另请补充

PR 描述中提到的场景(Task 运行时人类消息写入 subagent jsonl)在我们对 CLI 2.1.312 / 2.1.317 的 PTY 活体探针中没有复现:人类消息两次都只进入主会话 jsonl(317 为即时 user 事件;312 为 queue-operation enqueue 先行)。bundle 中确实存在 agent 定向投递的代码路径(见 P2),麻烦补充一条可复现实证:哪一版 CLI、从哪个入口投递(PTY / SDK / backgrounded agent 等)、以及 <sid>/subagents/ 下那条记录的完整 JSON,便于确认修复对准的触发面。

@deepcoldy

Copy link
Copy Markdown
Owner

更正上一条评审意见中的两处(以本条为准)

接续上一条评论(#issuecomment-6599129637),复审对建议谓词做了二次核验,发现我上一条里有两处错误,作者实现时请以本条为准:

更正 1:新分支必须靠独立的新 opt-in 与既有调用方隔离(不能靠 queue-op 差异)

我上一条写"worker.ts:8987 的会话切换扫描不传 includeQueueOperations"——这是错的。src/worker.ts 的 fingerprintScanOptions 明确带了 includeQueueOperations: true,会话切换扫描(以及 claude-code.ts 里 confirmSubmit 的 1576、末次 fan-out 的 1615)全部开着 queue 分支。

实测后果:若 attachment 解码分支不加新开关直接生效,用不开启子代理扫描的选项(即上述三个调用点的等价形态)去扫一个含人类 queued_command 记录的顶层 sibling jsonl,会直接命中——这会让 8987 把人类投递记录误当"会话切换证据",让 1576/1615 把 pty.claudeJsonlPath 钉到不该钉的文件。

因此 attachment 分支必须挂在一个新的显式选项后(建议 includeQueuedCommandAttachments,与目录下探的 includeSubagentTranscripts 正交、各自命名准确),只在 recheck() 这种"纯布尔、永不钉路径"的送达确认调用开启;不要复用 includeQueueOperations,也不要无条件生效。

更正 2:谓词中去掉 isMeta,改用 origin.kind

我上一条建议的 attachment.isMeta === true 也是错的。本机真实数据普查(1078 个主会话转录):

  • 人类投递族 origin.kind === 'human' 的 queued_command 共 733 条,全部 commandMode: 'prompt',且 733 条全都没有 isMeta 字段;
  • 带 isMeta: true 的 sidechain flush 形状来自 CLI bundle 代码路径反推(PDr 产出),本机没有实测样本;
  • task-notification 族 1570 条(主会话)+ 36 条(子代理)+ 33 条无 origin,全部无 isMeta。

用 isMeta === true 当门会把真实落盘的人类形状全部漏掉。正确的门是 origin.kind === 'human':47 个子代理转录中 32 条 isMeta:true 的 user 记录没有一条 origin.kind 是 human,对现有子代理噪声零误放行。

最终建议谓词(已按真实形状+真实指纹函数验证矩阵全绿)

} else if (
  opts.includeQueuedCommandAttachments &&           // 新 opt-in,仅 recheck 开
  ev.type === 'attachment' &&
  ev.attachment?.type === 'queued_command' &&
  ev.attachment.commandMode !== 'task-notification' // 无 commandMode 的 PDr 最小形状不受影响
) {
  const att = ev.attachment;
  // 子代理候选只认真实人类投递;顶层(非 subagent)候选不需要这条
  if (requireForwardedSubagentMessage && att.origin?.kind !== 'human') continue;
  const prompt = att.prompt;
  text = typeof prompt === 'string' ? prompt : stringifyUserContent(prompt);
}

实测矩阵(临时补丁、已还原):

输入记录 结果
真实人类形状(commandMode:'prompt'、无 isMeta),子代理文件 命中
PDr flush 形状(isMeta:true、无 commandMode、origin:human),子代理文件 命中
task-notification(commandMode + origin 双重排除) null
无 origin / origin:unclassified,子代理文件 null
真实人类形状,顶层 sibling 文件、不开新开关(8987/1576/1615 形态) null(不会顶掉监听目标)

既有 144 条测试双腿(bun:test + vitest)在该补丁下仍全绿。上一条的其余内容不变:P3-1 仍建议顺手收口——attachment 族成为权威路径后,子代理候选的 user 分支可直接不再接受任意 isMeta:true 文本(或收紧为 Tje 前缀),消除"开场指令含同前缀 + 真投递失败"被静默确认的窄窗口;P3-2(queue-operation 分支在子代理候选上无边界)仍建议处理;补可复现实证的请求不变。仍是自动评审初步意见,最终以维护者审阅为准。

@deepcoldy

Copy link
Copy Markdown
Owner

感谢 @wzono 的修复!本 PR 的分支维护者无法直接推送,为了尽快落地,维护者已另开 #3182 接管:保留了你的 4 个原始提交和署名,合入了最新 master,并按评审意见补上 queued_command 记录的解码和子代理记录边界的收紧。

#3182 合入后会关闭本 PR。如果你本地已经改过了,请说一声,我们改用你的版本。

@deepcoldy deepcoldy closed this in 3f6ab73 Nov 8, 2026
@deepcoldy

Copy link
Copy Markdown
Owner

感谢这个修复!本 PR 的完整方案已由维护者通过 #3182 合入 master(squash 提交 3f6ab73,保留了你全部 4 个原始提交的署名),本 PR 随合入自动关闭。

合入版本在你原有改动的基础上,按评审意见补齐了两点:

  • 运行中的子代理收到提示时,Claude Code 实际写的是 attachment(queued_command) 记录(正文在 attachment.prompt),新增加了独立开关解码这一形状,子代理文件只接受 origin.kind === 'human' 的记录,不依赖 isMeta;
  • 子代理转录不再匹配 queue-operation,user 记录收紧为 isMeta 且人工来源,避免任务通知、父代理消息被当成送达证据。

留两个已知的后续方向(不影响本次合入):

  1. 子代理仍在运行时,记录要等它下一步才落盘。如果这一步晚于 worker 的延迟复查窗口,仍可能发出一次「未确认送达」提醒;后续可考虑对运行中的子代理延长复查窗口。
  2. 更老版本的 CLI 如果不写 origin 字段,子代理转发记录不会被识别,行为退回到修复前的误报(不会误确认);需要兼容时可加包装文案前缀兜底。

欢迎继续贡献。

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