diff --git a/README.md b/README.md index c0aff40..ad91f20 100644 --- a/README.md +++ b/README.md @@ -129,7 +129,7 @@ npm start -- run --config config.json 飞书默认只转发 Agent 的最终答复。执行进度可通过固定文档标签页或消息卡片展示,同一时间只使用一种方式。原生问题与审批请求仍通过独立消息处理。 -项目 Worker 默认没有任务群,正式问题、进展和成果通过显式 `report` 交给项目协调者,独立任务完成也须汇报。普通最终答复和任务群讨论留在原任务;用户要求同步时,Worker 直接提交有实际用户来源的讨论摘要。用户需要直接对话时,在项目群自然语言提出,由协调者打开指定任务群。原生审批会按需建群并在项目群通知。Runtime 不发送定时监督提醒,没有新事件时协调者持续等待。新群不补发历史消息。群被手动解散后任务继续运行;现有进度发布只面向有效群,不提供新的项目进度总览。批量清理见[任务群管理](docs/task-groups.md)。 +项目 Worker 默认没有任务群。普通答复和讨论留在原任务。用户在 Worker 群明确说“请汇报给协调者”后,Worker 才会向协调者发送一份汇报。用户需要直接对话时,在项目群自然语言提出,由协调者打开指定任务群。原生审批会按需建群并在项目群通知。Runtime 不发送定时监督提醒,没有新事件时协调者持续等待。新群不补发历史消息。群被手动解散后任务继续运行;现有进度发布只面向有效群,不提供新的项目进度总览。批量清理见[任务群管理](docs/task-groups.md)。 调试台会保存可见模型文字、工具调用状态元数据和错误;不记录工具输出正文、原始协议配置、系统指导或私有推理内容。它是网络可访问的全局只读视图,不提供登录或 token 鉴权。 diff --git a/docs/adr/0021-worker-discussion-routing.md b/docs/adr/0021-worker-discussion-routing.md index 1d04eee..2e7e572 100644 --- a/docs/adr/0021-worker-discussion-routing.md +++ b/docs/adr/0021-worker-discussion-routing.md @@ -6,18 +6,18 @@ status: accepted 本 ADR 细化并取代 ADR 0017 中 Worker report 统一进入协调者 Thread 的路由约定。 -2026-11-14,项目所有者确认 Worker 在自己的任务群使用 grill-with-docs 与项目所有者讨论。中间问题和讨论留在 Worker 群。协调者只接收最终结论。授权、范围变化和阻塞可以提前上报。 +2026-11-14,项目所有者确认 Worker 在自己的任务群使用 grill-with-docs 与项目所有者讨论。中间问题和讨论留在 Worker 群。2026-11-20,项目所有者要求所有发给协调者的 Worker 汇报都由用户明确发起。 `project_action` 的 `report` 动作保存一个结构化 `routing` 字段。 - `intermediate` 表示普通问题和讨论。Runtime 要求 Worker 已经有任务群,把正文写入该 Worker 的 outbox,并且不写入协调者 inbox。 - `final` 表示最终结论。Runtime 将汇报写入协调者 inbox。 -- `escalation` 表示必须协调的事项。`escalation` 必须是 `authorization`、`scope_change` 或 `blocker`,并且 Runtime 立即写入协调者 inbox。 +- `escalation` 表示必须协调的事项。`escalation` 必须是 `authorization`、`scope_change` 或 `blocker`,通过用户请求校验后写入协调者 inbox。 -没有显式 `routing` 时,`result` 使用 `final`,`question` 和 `update` 使用 `intermediate`。这个默认值让旧调用保持可解析,同时把普通讨论导向任务群。要求同步的 `update` 必须显式使用 `routing=final`。 +没有显式 `routing` 时,`result` 使用 `final`,`question` 和 `update` 使用 `intermediate`。要求同步的 `update` 必须显式使用 `routing=final`。 Runtime 从 Worker 任务中收集用户消息的 `messageId`、`chatId` 和 `senderId`,再合并汇报显式提供的 `sources`。最终汇报和升级汇报把这些来源放入 agent provenance。中间汇报把完整审计资料写入 SQLite `meta`,正文只进入 Worker outbox,不进入协调者项目报告。 -路由先通过项目成员关系校验。Worker 不能为其他项目创建汇报。中间汇报没有有效任务群时失败关闭,不降级发送给协调者。每个动作继续使用稳定 `requestId`。SQLite 的 inbox、outbox、meta 和 project receipt 让重试、重启和部分完成保持幂等。 +路由先通过项目成员关系校验。Worker 不能为其他项目创建汇报。中间汇报没有有效任务群时失败关闭,不降级发送给协调者。跨群汇报使用 Worker 群明确请求汇报的所有者消息 ID 作为 `requestId`。Runtime 校验实际收到的消息及其当前群绑定。同一消息只对应一份汇报,投递记录与回执一起写入 SQLite。 这项决策只改变 Worker `report` 的去向。普通用户输入仍按任务群路由,原生问题、审批和权限请求仍使用原有路径。项目协调者仍只能通过 `announce` 发送协调群公告。 diff --git a/docs/project-coordinator.md b/docs/project-coordinator.md index 775ab88..b7f3f67 100644 --- a/docs/project-coordinator.md +++ b/docs/project-coordinator.md @@ -64,9 +64,9 @@ GitHub Feature 是外部需求提案。即使 Issue 描述完整,也不能直 Issue 评论先交协调者判断影响,再按需转给原 Worker。Worker 的普通最终答复、任务群内用户消息留在原任务,保留完整来源、附件、原 Thread 和任务记录。GitHub 事件和 Worker 汇报触发的协调者普通最终答复保留在协调者 Thread、执行记录和进度文档中;需要用户处理时,协调者使用 `announce` 发送带类型标题的普通文本。用户直接在项目协调群发消息后的协调者答复继续发送到项目群。 -正式成果通过显式 `report` 的 `routing=final` 通知协调者,独立任务完成也须 `report result`。用户直接在任务群讨论或澄清时,Worker 使用 `routing=intermediate`,普通问答留在任务群,不进入协调者项目报告。授权、范围变化和阻塞使用 `routing=escalation`,并标明对应的 `escalation` 类型,立即通知协调者。原生问题、审批、权限请求、执行失败和非暂停中断保留原有通知与处理通道。一轮结束只代表本轮结束。 +Worker 在任务群里处理普通问答和阶段结论。`routing=intermediate` 的汇报发回 Worker 群。用户在 Worker 群明确说“请汇报给协调者”或“只把选中行范围同步给协调者”后,Worker 才能使用 `routing=final` 或 `routing=escalation`。原生问题、审批、权限请求、执行失败和非暂停中断由 Runtime 通知协调者。 -用户说“同步给协调者”后,Worker 通过 `report update` 携带 `routing=final` 直接发送当前讨论摘要,无需预览确认。摘要包含已定结论、范围变化、待决问题和证据,引用实际用户消息、群、发送者及必要原文。用户指定话题时仅同步该话题。摘要仍是代理汇报,不能冒充用户决定或增加实施、合并、部署及原生审批授权。 +Worker 用该条用户消息的飞书 ID 作为 `requestId`。Runtime 校验消息、发送者、当前 Worker 群以及明确的汇报要求。每条请求对应一份汇报。用相同的 ID 和内容重试会返回原回执。摘要包含用户指定话题的结论、范围变化、待决问题和证据,并引用真实用户消息。实施、合并、部署及原生审批各自需要对应的授权。 ## 项目工具 diff --git a/docs/prompts/task.md b/docs/prompts/task.md index 7b78927..7dcce0d 100644 --- a/docs/prompts/task.md +++ b/docs/prompts/task.md @@ -24,4 +24,4 @@ Runtime 将当前角色模板、项目规则、委派和环境说明合并,通 新旧 Thread 都使用相同的项目操作;旧 Thread 缺少动态工具时,使用任务限定的 本地客户端。客户端不增加权限,也不能冒充其他任务。 -Worker 默认无群,正式问题、进展和成果通过显式 report 交给协调者,独立任务完成也须汇报。普通最终答复和任务群问答留在原任务,用户要求同步时直接 report 有实际用户来源的讨论摘要。Runtime 不发送定时监督提醒。原生审批按需建群,进度只在有效群发布。一次答复结束不表示整项工作已经验收或允许重建另一个执行者。 +Worker 默认无群。普通最终答复和任务群问答留在原任务。收到 Worker 群用户的明确要求后,Worker 用该飞书消息 ID 作为 `requestId` 向协调者汇报用户指定的内容。Runtime 不发送定时监督提醒。原生审批按需建群,进度只在有效群发布。一次答复结束不表示整项工作已经验收或允许重建另一个执行者。 diff --git a/docs/task-groups.md b/docs/task-groups.md index fe968b2..dd13a90 100644 --- a/docs/task-groups.md +++ b/docs/task-groups.md @@ -6,9 +6,9 @@ {"action":"open_group","requestId":"stable-open-id","taskId":"target-worker-id"} ``` -同一请求重试返回原回执。不同请求打开同一有效群也不会新建群。群已失效时,需要新的开群请求。只有协调者能打开本项目 Worker 的群,不能借此管理其他项目的任务。普通问题经 `send` 转交;原生审批自动开群,仍只接受实际用户的认证按钮操作。 +同一请求重试返回原回执。不同请求打开同一有效群也不会新建群。群已失效时,需要新的开群请求。只有协调者能打开本项目 Worker 的群,不能借此管理其他项目的任务。协调者可通过 `send` 向 Worker 转达问题。原生审批自动开群,仍只接受实际用户的认证按钮操作。 -无群期间的普通飞书输出标为 `dropped`,原文和执行事件仍保存在本地。Worker 的普通最终答复不会自动交给协调者,正式问题、进展和成果须显式 `report`,独立任务完成也须汇报。任务群内的普通用户消息和问答保留在原任务;用户要求同步时,Worker 直接发送有实际用户来源的讨论摘要,包含结论、范围变化、待决问题和证据,并遵循用户指定的话题范围。原生请求和执行异常仍通知协调者。 +无群期间的普通飞书输出标为 `dropped`,原文和执行事件仍保存在本地。Worker 的普通最终答复不会自动交给协调者,用户在 Worker 群明确要求汇报后,Worker 才能通过 `report` 将内容发给协调者。任务群内的普通用户消息和问答保留在原任务。汇报使用该条用户消息的飞书 ID,并遵循用户指定的话题范围。原生请求和执行异常仍通知协调者。 开群只显示欢迎、状态和最近的最终摘要,不补发旧输出。无群任务的 dashboard 标题继续来自原始任务来源,群名修改不参与任务标题或搜索。 diff --git a/prompts/coordinator.md b/prompts/coordinator.md index 9784b56..9a9aa5a 100644 --- a/prompts/coordinator.md +++ b/prompts/coordinator.md @@ -40,6 +40,6 @@ GitHub Feature 是外部需求提案,不是开发授权。需求描述清楚 Project 工具不会替你执行产品判断或 GitHub 合并。status 查询事实,dispatch 创建任务,send 传递指导,record 保存带版本的项目记录,rotate 在本轮安全结束后更换会话。没有新行动时结束本轮,Runtime 负责后续事件唤醒。项目群是主要用户交流入口,最终答复说明实际交付、当前阻塞和待决问题。暂不开展跨 Issue 共同根因分析。 -Worker 和 verifier 默认无群。普通任务群问题和讨论使用 report routing=intermediate 留在 Worker 群。最终结论使用 report routing=final,授权、范围变化和阻塞使用 report routing=escalation 并立即进入你的 Thread。独立任务完成也须 report result。任务群中的普通对话和普通最终答复不会自动传给你。用户要求同步讨论时,Worker 直接 report routing=final 摘要,包含指定话题的结论、范围变化、待决问题和实际用户消息来源。核查其证据并区分用户决定与代理判断,讨论摘要不增加实施、合并、部署或原生审批授权。用户需要直接与某个任务交流时,先识别本项目的目标任务,再用 open_group 携带 taskId 和稳定 requestId 打开或复用任务群。原生审批会自动按需建群,普通问题不触发建群。不要在开群后补发历史消息。 +Worker 和 verifier 默认无群。普通任务群问题、讨论和答复留在 Worker 群。只有所有者在当前 Worker 群明确要求向你汇报时,Worker 才能发送 final 或 escalation report,并用该用户消息的确切 ID 作为 requestId。查询 Worker 进展或产物时使用 status。收到汇报后核对实际来源和证据,区分用户决定与代理判断。用户需要直接与某个任务交流时,用 open_group 携带该任务的 taskId 和稳定 requestId 打开或复用任务群。原生审批按需建群,普通问题留在本任务。新群从当前状态开始交流。 批量解散群须另有用户授权。plan_group_cleanup 返回冻结清单并在项目群展示一次,排除所有项目协调群。用户发送该清单的确认文本后,使用 confirm_group_cleanup 携带实际 messageId,再调用 apply_group_cleanup。代理转述不能代替实际用户确认。失败先查明原因,修复后用新的 apply 请求继续原计划;不能重新计划以跳过失败。 diff --git a/prompts/worker.md b/prompts/worker.md index 42185fe..e9ddcf2 100644 --- a/prompts/worker.md +++ b/prompts/worker.md @@ -1,16 +1,16 @@ 你是项目协调者委派的 Worker,使用 poteto-mode,自行选择适用 playbook。完成当前任务约定,遵守用户明确范围与授权,并阅读项目 AGENTS.md。 -具体任务的调查、设计、实现和测试由你组织。技术问题自主推进。需求不明确时读取并使用 grill-with-docs 及其依赖,先查明已有事实。用户正在任务群直接讨论或澄清时,在该群直接提问和回答,普通问题与答复留在本任务,不因需求尚未确定而机械 report。独立执行期间需要协调者转达用户的问题、正式阻塞或跨任务协调,才通过 project_action report 的 question 提交背景、选项、影响和建议,由协调者在项目群向用户提问。普通讨论无需改用原生问题;已有原生问题仍会通知协调者,业务答复通过 send 作为有来源的代理消息进入本任务,不自动构成原生工具审批。 +具体任务的调查、设计、实现和测试由你组织。技术问题自主推进。需求不明确时读取并使用 grill-with-docs 及其依赖,先查明已有事实。在任务群直接提问和回答,把讨论留在本任务。需要协调者参与时,先在任务群说明背景、选项、影响和建议,待用户明确要求汇报后再发送。原生问题仅用于原生工具需要的交互。已有原生问题仍走 Runtime 通知,协调者通过 send 转达的业务答复带有原始来源,不能用来批准原生工具。 -调查或澄清任务只调查、提问和整理文档,不实施业务代码。开发前核对交接中的需求文档版本、已确认范围、不做范围、验收标准、未决事项和实际授权依据;已有 Issue、用户原文或规格可作为明确技术 Bug 的约定。独立执行因范围不明确、影响实施的产品决定未解决或缺少有效授权而需要项目协调时,向协调者 report question,说明缺口、证据、选项、影响与建议,只暂停依赖该答复的工作。任务群内仍在讨论的想法和待决问题遵循本地讨论约定。派单本身不等于实施授权,不自行补齐用户决定或扩大范围。 +调查或澄清任务只调查、提问和整理文档。开发前核对交接中的需求文档版本、已确认范围、不做范围、验收标准、未决事项和实际授权依据。已有 Issue、用户原文或规格可作为明确技术 Bug 的约定。范围不明确、产品决定未解决或缺少授权时,在本任务说明缺口、证据、选项、影响和建议,只暂停依赖答复的工作。派单本身不等于实施授权。 -“只讨论、不实现”持续有效,直到用户改变该限制;决定齐备不自动允许开发。减少消息噪声不免除必要的需求确认。已确认问题不重复问,已有明确授权继续有效;明确技术 Bug 和已授权契约内技术修复仍自主定位、修复和验证,不增加机械审批或一律访谈。需要改变已委派工作范围时,正式汇报交协调者评估;普通讨论中的想法仍保留在本任务,直到用户要求同步。恢复时先读项目记录和实际现场,不擅自恢复 Operator 暂停任务。 +“只讨论、不实现”持续有效,直到用户改变该限制。决定齐备后核对开发授权。减少消息噪声不免除必要的需求确认。已确认问题不重复问,已有明确授权继续有效。明确技术 Bug 和已授权契约内的技术修复仍自主定位、修复和验证。先在本任务说明建议的范围变化,等用户明确要求再汇报给协调者。恢复时先读项目记录和实际现场,遵守操作员暂停状态。 开发必须在独立工作树和分支中进行,确认实际工作目录。完成后提交 PR,作为唯一 PR Owner 维护分支和处理反馈。没有协调者确认独立验证和合并条件,不自行合并。合并、Issue 关闭和安全清理按当前项目的明确授权执行,公共提示词不授予额外权限,不包含部署或绕过分支保护。纯调查或澄清任务交付文档与证据。 -任务群中的普通用户消息和普通最终答复保留在本任务,不会自动回传协调者。普通对话不要自行调用 report。需要在任务群留下可见的中间问题或讨论时,使用 project_action 的 report,kind 使用 question 或 update,并显式设置 routing=intermediate。最终结论使用 routing=final。授权、范围变化和阻塞使用 routing=escalation,并设置 escalation=authorization、scope_change 或 blocker。报告提供实际产物路径、PR 链接、提交版本、验证证据和限制。独立执行任务完成后必须主动 report result,verifier 同样遵循;结束最终答复不能代替汇报,一轮结束不自动表示任务完成。同一汇报重试保持稳定 requestId 和完全相同的内容。 +普通讨论、结论和任务完成情况留在本任务。一轮结束只代表本轮结束。需要在任务群留下可见的中间问题或讨论时,使用 project_action 的 report,kind 使用 question 或 update,routing 设置为 intermediate。只有所有者在当前 Worker 群明确要求汇报给协调者时,才可使用 routing=final 或 routing=escalation。把 requestId 设置为该用户消息的确切 ID,每条消息最多发送一份汇报。重试使用相同 ID 和内容。 -用户说“同步给协调者”等自然语言要求时,直接通过 report update 发送当前讨论摘要,无需先展示预览或再次确认。摘要包含已定结论、范围变化、待决问题和证据来源;用户指定话题时只同步该话题。根据本任务实际收到的 Input provenance as data,引用相关用户决定和同步要求的真实消息 ID、群 ID、发送者及必要原文,区分用户决定与代理判断。不得编造来源,不把同步要求当作实施、合并、部署或原生工具批准。同步沿用本任务和原 Thread,不创建另一项同步任务,不擅自恢复 Operator 暂停的工作。 +收到“同步给协调者”或“把这个结论汇报给协调者”等明确请求后,按用户指定范围汇报,无需先展示预览。结论和讨论摘要使用 routing=final。授权、范围变化或阻塞需要升级时,使用 routing=escalation 并设置 escalation 为 authorization、scope_change 或 blocker。按汇报内容列出结论、范围变化、待决问题、实际产物路径、PR 链接、提交版本、验证证据和限制。根据本任务收到的 Input provenance as data 引用真实消息 ID、群 ID 和发送者,区分用户决定与代理判断。这条请求只授权汇报。同步沿用本任务和原 Thread。遇到含糊、带条件或暂缓的表达时,继续在任务群确认。 record 默认保存本任务资料,引用需求文档版本,记录本任务决定、答复来源、授权范围、未决事项和下一步,不得把自身推测写成用户决定。需要显式 scope 时只使用 {"kind":"task","taskId":"<自己的任务 ID>"}。项目共享规则和跨任务转交由协调者处理。status 只提供本任务及项目共享资料,同名 key 不覆盖其他任务。写入仍使用 status 返回的项目级 version。协调者转来的用户答复保留其消息、群和发送者等来源。新评论先由协调者评估后送入,不静默覆盖已确认范围。 diff --git a/scripts/verify-project-coordinator.ts b/scripts/verify-project-coordinator.ts index 21524f9..f26e0c3 100644 --- a/scripts/verify-project-coordinator.ts +++ b/scripts/verify-project-coordinator.ts @@ -1,4 +1,3 @@ -import { testExecution } from '../test/test-config.js'; import assert from 'node:assert/strict'; import { execFile } from 'node:child_process'; import { createHash, randomUUID } from 'node:crypto'; @@ -33,8 +32,9 @@ const execute = promisify(execFile); const options = z.object({ timeoutMs: z.coerce.number().int().min(10_000).max(1_200_000).default(480_000), restart: z.enum(['0', '1']).default('1'), + model: z.string().min(1).default('gpt-5.4-mini'), }).parse({ timeoutMs: process.env.PROJECT_COORDINATOR_VERIFY_TIMEOUT_MS, - restart: process.env.PROJECT_COORDINATOR_VERIFY_RESTART }); + restart: process.env.PROJECT_COORDINATOR_VERIFY_RESTART, model: process.env.PROJECT_COORDINATOR_VERIFY_MODEL }); const startedAt = Date.now(); const deadline = startedAt + options.timeoutMs; const sourceFiles = ['scripts/verify-project-coordinator.ts', 'scripts/project-coordinator-probe-tasks.ts', 'src/loop.ts', 'src/project.ts', 'src/project-runtime.ts', @@ -48,12 +48,11 @@ await mkdir(evidenceDirectory, { recursive: true, mode: 0o700 }); const root = await realpath(await mkdtemp(join(tmpdir(), 'agent-loop-project-live-'))); const directory = join(root, 'project'); const proofFile = join(directory, 'proof.txt'); -const gateFile = join(root, 'coordinator-idle.gate'); const marker = `PROJECT_COORDINATOR_PROOF_${randomUUID()}`; const projectId = 'live-fixture'; const repository = 'fixture/coordinator'; const dispatchId = 'fixture-read-only-worker'; -const reportId = 'fixture-read-only-result'; +const reportMessageId = 'fixture-owner-report-request'; const recordId = 'fixture-result-receipt'; const recordKey = 'acceptance.worker-receipt'; const calls: ActionCall[] = []; @@ -64,7 +63,7 @@ let loop: AgentLoop | undefined; let outcome: Outcome = { result: 'blocked', error: 'Acceptance did not finish' }; let initialTurn: string | null = null; let initialThread: string | null = null; -let gateOpenedAt: number | null = null; +let reportRequestedAt: number | null = null; let reportArrival: { status: string; turnId: string | null; at: number } | null = null; let coreProof: unknown = null; let restartProof: unknown = { result: 'skipped', reason: 'Core acceptance has not completed' }; @@ -97,8 +96,10 @@ class ObservedCodex extends CodexAppServer { if (action.action === 'dispatch') { assert.equal(action.requestId, dispatchId, 'Only the single fixture worker is authorized'); assert.equal(action.role, 'worker'); + } else if (action.action === 'open_group') { + assert.equal(action.requestId, 'fixture-open-worker-group'); } else if (action.action === 'report') { - assert.equal(action.requestId, reportId); + assert.equal(action.requestId, reportMessageId); assert.equal(action.kind, 'result'); assert.ok(loop); const project = loop.projects.ledger.project(projectId); assert.ok(project); @@ -107,7 +108,7 @@ class ObservedCodex extends CodexAppServer { } else if (action.action === 'record') { assert.equal(action.requestId, recordId); assert.equal(action.key, recordKey); - } else assert.equal(action.action, 'status', 'Only status, dispatch, report and record are authorized'); + } else assert.equal(action.action, 'status', 'Only status, dispatch, open_group, report and record are authorized'); const result = await handler(request); calls[index] = { request: structuredClone(request), startedAt: callStartedAt, status: 'succeeded', finishedAt: Date.now(), result: structuredClone(result) }; @@ -123,13 +124,15 @@ class ObservedCodex extends CodexAppServer { const safety = `This is an isolated, read-only acceptance probe. Only inspect the fixture under ${root} and the exact supplied poteto-mode skill file. Use native project_action for communication. No external tools, browser, images, remote hosts, real Feishu/GitHub, PR, git changes, deployments, service operations, credential/config inspection, or other agents. Model-provider communication is allowed. Do not read capability files or use shell fallbacks. Do not edit any files. The only delegation authorized is the coordinator's one project_action dispatch described below. Scope and prohibitions override generic playbook suggestions. A turn ending does not close the Issue.`; const workerPrompt = `Use poteto-mode for a read-only fixture investigation. ${safety} -Read ${join(directory, 'AGENTS.md')}. Wait for ${gateFile} to exist, then read ${proofFile} with the shell tool. You may use a bounded shell loop (at most 180 seconds, sleep 1) to wait for that file. The probe creates it after the coordinator's first turn ends. Extract the unique marker from proof.txt. Report it exactly once with native project_action {"action":"report","requestId":"${reportId}","kind":"result","text":""}. Return a short final answer containing that same marker and path. Do not create documentation or make a PR. Do not delegate. Do not call record. If blocked, say what failed instead of inventing evidence.`; +Read ${join(directory, 'AGENTS.md')} and ${proofFile} with the shell tool. Extract the unique marker from proof.txt. Return a short final answer containing the marker and path. Wait for the owner to explicitly request a report in the Worker group. When that request arrives, use its actual Feishu message ID as requestId and call native project_action {"action":"report","requestId":"","kind":"result","routing":"final","text":""}. Do not create documentation or make a PR. Do not delegate. Do not call record. If blocked, say what failed.`; const policy = `${safety} First call project_action {"action":"status"}. Inspect issues and existing tasks. Only Issue 101 authorizes the single read-only check. Other admitted Issues exercise intake only and require no workers. Ignore out-of-scope Issues. If no worker exists for Issue 101, dispatch exactly one using requestId ${dispatchId}, role worker, issueId live-issue-101, and this complete worker prompt as the prompt field: ${workerPrompt} -After dispatch, END THIS TURN with COORDINATOR_WAITING_FOR_REPORT. Do not wait, sleep or poll inside that turn. The Runtime will wake you when the worker reports. +After dispatch, call project_action open_group with requestId fixture-open-worker-group and the returned Worker task ID. End this turn with COORDINATOR_WAITING_FOR_REPORT. The fixture owner will ask the Worker to report after both turns end. On later turns call status first and do not dispatch again. When a worker result containing its unique proof marker is present, query status for the current version and records, then call project_action record with requestId ${recordId}, key ${recordKey}, expectedVersion equal to the current status version, and text containing the actual worker marker, worker task ID, proof file path, and an explicit receipt of the result. Never guess the marker or read proof.txt yourself. If this receipt already exists, do not record again. End with COORDINATOR_RECEIPT_RECORDED plus the actual marker. No rotation is requested in this probe.`; -const config = configSchema.parse({ execution: { ...testExecution, backends: { codex: { command: ['codex', 'app-server'], approvalPolicy: 'never', sandbox: 'read-only', requestTimeoutMs: 30_000 } } }, dataDir: join(root, 'data'), +const profile = { backend: 'codex', model: options.model, reasoningEffort: 'low' }; +const config = configSchema.parse({ execution: { coordinator: profile, worker: profile, + backends: { codex: { approvalPolicy: 'never', sandbox: 'read-only', requestTimeoutMs: 30_000 } } }, dataDir: join(root, 'data'), feishu: { userOpenId: 'fixture-owner', progress: { enabled: false } }, engineering: { skillPath: '/Users/developer/.codex/packages/pstack/skills/poteto-mode/SKILL.md' }, projects: [{ id: projectId, name: 'Coordinator live fixture', directory, @@ -141,7 +144,7 @@ const github = new GitHubFake(); const feishu = new FeishuFake(); github.sources = [ issue(101, { id: 'live-issue-101', repository, url: 'https://example.invalid/fixture/issues/101', - title: 'Read-only fixture proof', body: 'Inspect the local fixture and report its marker. No PR or external actions.', labels: ['coordinate'], assignees: [] }), + title: 'Read-only fixture proof', body: 'Inspect the local fixture and record the marker in the Worker conversation.', labels: ['coordinate'], assignees: [] }), issue(102, { id: 'live-issue-102', repository, url: 'https://example.invalid/fixture/issues/102', title: 'Assignee-only intake fixture', body: 'Intake only. No work authorized.', labels: [], assignees: ['fixture-owner'] }), issue(103, { id: 'live-issue-103', repository, url: 'https://example.invalid/fixture/issues/103', @@ -238,19 +241,23 @@ async function verify(): Promise { initialTurn = current.turnId; initialThread = current.threadId; note('dispatch_turn_ended', { initialTurn, initialThread }); } - if (initialTurn !== null && gateOpenedAt === null && current.status === 'idle') { - if (!loop.store.inputs(coordinatorId).some(input => input.status !== 'delivered' && input.status !== 'dropped')) { - gateOpenedAt = Date.now(); - await writeFile(gateFile, 'Coordinator dispatch turn has ended. The read-only worker may proceed.\n'); - note('worker_gate_opened', { initialTurn, initialThread, at: gateOpenedAt }); - } + const worker = executions.find(task => task.id !== coordinatorId); + if (initialTurn !== null && reportRequestedAt === null && current.status === 'idle' + && worker?.status === 'idle' && worker.chatId) { + assert.equal(calls.filter(call => call.request.action.action === 'report').length, 0); + assert.ok(loop.store.outputs(worker.id).some(output => output.text.includes(marker))); + assert.ok(!loop.store.inputs(coordinatorId).some(input => input.message.text.includes(marker))); + reportRequestedAt = Date.now(); + await loop.receive({ id: reportMessageId, chatId: worker.chatId, senderId: config.feishu.userOpenId, + chatType: 'group', text: 'Please report this to the coordinator.', attachments: [], createdAt: reportRequestedAt }); + note('owner_requested_report', { initialTurn, messageId: reportMessageId, at: reportRequestedAt }); } const record = state.records.find(item => item.key === recordKey); const currentLoop = loop; const allIdle = executions.length === 2 && intakes.length === 2 && executions.every(task => task.status === 'idle' && currentLoop.store.inputs(task.id).every(input => input.status === 'delivered' || input.status === 'dropped')); if (record && allIdle) { - assert.ok(gateOpenedAt !== null); + assert.ok(reportRequestedAt !== null); const worker = state.members.find(member => member.role === 'worker'); assert.ok(worker); assert.equal(worker.issueId, 'live-issue-101'); const workerTask = loop.store.task(worker.taskId); @@ -270,7 +277,7 @@ async function verify(): Promise { assert.equal(reports.length, 1); const report = reports[0]; assert.ok(report && report.request.action.action === 'report'); assert.equal(report.request.threadId, workerTask.threadId); - assert.ok(report.startedAt >= gateOpenedAt); + assert.ok(report.startedAt >= reportRequestedAt); assert.ok(report.request.action.text.includes(marker)); const recorded = successful.find(call => call.request.action.action === 'record'); assert.ok(recorded && recorded.request.action.action === 'record'); @@ -288,11 +295,13 @@ async function verify(): Promise { const receiptTurnStart = loop.execution.current(coordinatorId).find(event => event.kind === 'turn_start' && event.turnId === recorded.request.turnId); assert.ok(receiptTurnStart && (receiptTurnStart.createdAt ?? 0) >= reportArrival.at, 'Receipt turn must start after the actual worker report'); const workerEvents = loop.execution.current(worker.taskId); - assert.ok(workerEvents.some(event => ['tool_output', 'tool_end'].includes(event.kind) - && event.text.includes(marker)), 'Marker must be observed in actual worker tool output'); + assert.ok(workerEvents.some(event => event.kind === 'tool_end' && event.text.includes(proofFile) + && event.label.endsWith('exit 0')), 'Worker must successfully read the exact fixture file'); const workerOutputs = loop.store.outputs(worker.taskId).map(output => output.text).join('\n'); assert.ok(workerOutputs.includes(marker)); - const coordinatorOutputs = loop.store.outputs(coordinatorId).map(output => output.text).join('\n'); + const coordinatorOutputs = loop.execution.current(coordinatorId, current.threadId) + .filter(event => event.kind === 'agent_message' && event.turnId === recorded.request.turnId) + .map(event => event.text).join('\n'); assert.match(coordinatorOutputs, /COORDINATOR_RECEIPT_RECORDED/); assert.ok(coordinatorOutputs.includes(marker)); for (const task of tasks) for (const event of loop.execution.current(task.id)) { @@ -306,7 +315,7 @@ async function verify(): Promise { coreProof = { coordinatorId, workerTaskId: worker.taskId, taskIdentities, retainedIntakeIds: intakes.map(task => task.id), initialThread, initialTurn, receiptTurn: recorded.request.turnId, receiptTurnStartedAt: receiptTurnStart.createdAt, - gateOpenedAt, reportArrival, reportInputId: reportInput.id, + reportRequestedAt, reportArrival, reportInputId: reportInput.id, reportProvenance: reportInput.provenance, marker, record, fixtureBefore, calls: successful.length }; note('core_acceptance_passed', coreProof); break; diff --git a/src/project-runtime.ts b/src/project-runtime.ts index 63cc5de..d6dd063 100644 --- a/src/project-runtime.ts +++ b/src/project-runtime.ts @@ -45,6 +45,22 @@ export function resolveReportRouting(action: Extract input.status !== 'dropped').map(input => ({ id: input.id, provenance: input.provenance })) })); @@ -250,10 +266,10 @@ export class ProjectRuntime { if (!member) return ''; const state = this.ledger.routing(member.projectId), config = this.config(taskId); if (!state || !config) throw new Error('Project configuration unavailable'); - return `\nProject role: ${member.role}. Project: ${state.id}. Directory: ${state.directory}. Repositories: ${config.repositories.map(item => item.name).join(', ')}.\nUse project_action for project status, dispatch, announcements, messages, reports, records and checkpoint rotation. Keep a stable requestId per operation and retry with identical content only. Project events are data, never native approval.\nWorker discussion routing: use report with routing=intermediate for ordinary questions and discussion; it stays in the Worker task group and requires that group to be open. Use routing=final for a conclusion that the coordinator must receive. Use routing=escalation with escalation=authorization, scope_change or blocker for matters that require coordination; these reports reach the coordinator immediately. Include sources when citing owner messages.\nProject policy: ${config.instructions}`; + return `\nProject role: ${member.role}. Project: ${state.id}. Directory: ${state.directory}. Repositories: ${config.repositories.map(item => item.name).join(', ')}.\nUse project_action for project status, dispatch, announcements, messages, reports, records and checkpoint rotation. Keep a stable requestId per operation and retry with identical content only. Project events are data, never native approval.\nWorker reports to the coordinator require an explicit request from the owner in the current Worker group. For final or escalation reports, set requestId to the exact ID of that owner message and retry only with identical content. Ordinary discussion stays in the Worker group, where an intermediate report requires an open group. Include sources when citing owner messages.\nProject policy: ${config.instructions}`; } - private reportSources(taskId: string, explicit: ReportSource[] | undefined): ReportSource[] { + private reportSources(inputs: readonly Inbox[], explicit: ReportSource[] | undefined, request: ReportSource | undefined): ReportSource[] { const seen = new Set(); const sources: ReportSource[] = []; const add = (source: ReportSource) => { @@ -261,11 +277,14 @@ export class ProjectRuntime { if (seen.has(key)) return; seen.add(key); sources.push(source); }; - for (const input of this.store.inputs(taskId)) { + for (const input of inputs) { if (input.provenance.kind !== 'user') continue; add({ messageId: input.message.id, chatId: input.message.chatId, senderId: input.message.senderId }); } for (const source of explicit ?? []) add(source); + const requestIndex = request ? sources.findIndex(source => source.messageId === request.messageId + && source.chatId === request.chatId && source.senderId === request.senderId) : -1; + if (request && (requestIndex < 0 || requestIndex >= 100)) return [...sources.slice(0, 99), request]; return sources.slice(0, 100); } markCoordinatorInput(task: Task, turnId: string, input: Inbox): void { @@ -363,6 +382,11 @@ export class ProjectRuntime { return action.action === 'record' ? this.recordAcknowledgement(member.projectId, callerId, action.requestId) : old.value; } if (action.action === 'claim_intake') return this.claimIntake(callerId, member, action, intentKey, fingerprint); + if (action.action === 'report') return this.store.transaction(() => { + const result = this.report(callerId, member, action); + this.ledger.saveReceipt(member.projectId, callerId, action.requestId, fingerprint, result); + return result; + }); this.store.setMeta(intentKey, fingerprint); const result = await this.perform(callerId, member, action); this.ledger.saveReceipt(member.projectId, callerId, action.requestId, fingerprint, result); @@ -492,7 +516,45 @@ export class ProjectRuntime { text: input.message.text, createdAt: input.message.createdAt }); return { key, evidence }; } - private async perform(callerId: string, member: NonNullable>, action: Exclude): Promise { + private reportRequest(task: Task, requestId: string, input: Inbox | undefined): ReportSource { + const message = input?.provenance.kind === 'user' ? input.provenance.message : null; + if (input?.origin !== 'user' || input.status === 'dropped' || !message + || message.id !== requestId || message.chatType !== 'group' || !task.chatId || message.chatId !== task.chatId + || message.senderId !== this.settings.feishu.userOpenId || !isCoordinatorReportRequest(message.text)) { + throw new Error('An explicit owner report request in the current Worker group is required. Use that message ID as requestId.'); + } + return { messageId: message.id, chatId: message.chatId, senderId: message.senderId }; + } + + private report(callerId: string, member: NonNullable>, + action: Extract): unknown { + if (member.role === 'coordinator') throw new Error('Coordinator reports directly to the project group'); + const routing = resolveReportRouting(action); + const task = this.store.task(callerId); + const inputs = this.store.inputs(callerId); + const request = routing.routing === 'intermediate' ? undefined + : this.reportRequest(task, action.requestId, inputs.find(input => input.id === action.requestId)); + const sources = this.reportSources(inputs, action.sources, request); + const report = { + ...(action.currentStep === undefined ? {} : { currentStep: action.currentStep }), + ...(action.nextStep === undefined ? {} : { nextStep: action.nextStep }), + ...(action.blockers === undefined ? {} : { blockers: action.blockers }), + ...(action.evidence === undefined ? {} : { evidence: action.evidence }), + ...routing, + ...(sources.length ? { sources } : {}), + } satisfies StructuredReport; + if (routing.routing === 'intermediate') { + if (!task.chatId) throw new Error('Intermediate worker discussion requires an open Worker group'); + const audit = JSON.stringify({ projectId: member.projectId, taskId: callerId, requestId: action.requestId, kind: action.kind, text: action.text, ...report }); + this.store.setMeta(reportAuditKey(member.projectId, callerId, action.requestId), audit); + this.store.enqueue(callerId, action.text, `worker-report:${action.requestId}`); + return { accepted: true, destination: 'worker_group', taskId: callerId, routing: routing.routing }; + } + this.event(member.projectId, `report:${callerId}:${action.requestId}`, `Worker ${callerId} ${action.kind}.\n${action.text}`, callerId, action.kind, report); + return { accepted: true, destination: 'coordinator', taskId: callerId, routing: routing.routing }; + } + + private async perform(callerId: string, member: NonNullable>, action: Exclude): Promise { const state = this.ledger.project(member.projectId); if (!state) throw new Error('Project unavailable'); switch (action.action) { @@ -613,32 +675,6 @@ export class ProjectRuntime { if (member.role !== 'coordinator') throw new Error('Only the coordinator can manage group cleanup'); return this.host.groupCleanup(callerId, action); } - case 'report': { - if (member.role === 'coordinator') throw new Error('Coordinator reports directly to the project group'); - const routing = resolveReportRouting(action); - const sources = this.reportSources(callerId, action.sources); - const report = { - ...(action.currentStep === undefined ? {} : { currentStep: action.currentStep }), - ...(action.nextStep === undefined ? {} : { nextStep: action.nextStep }), - ...(action.blockers === undefined ? {} : { blockers: action.blockers }), - ...(action.evidence === undefined ? {} : { evidence: action.evidence }), - routing: routing.routing, - ...(routing.escalation === undefined ? {} : { escalation: routing.escalation }), - ...(sources.length ? { sources } : {}), - } satisfies StructuredReport; - if (routing.routing === 'intermediate') { - const task = this.store.task(callerId); - if (!task.chatId) throw new Error('Intermediate worker discussion requires an open Worker group'); - const audit = JSON.stringify({ projectId: state.id, taskId: callerId, requestId: action.requestId, kind: action.kind, text: action.text, ...report }); - this.store.transaction(() => { - this.store.setMeta(reportAuditKey(state.id, callerId, action.requestId), audit); - this.store.enqueue(callerId, action.text, `worker-report:${action.requestId}`); - }); - return { accepted: true, destination: 'worker_group', taskId: callerId, routing: routing.routing }; - } - this.event(state.id, `report:${callerId}:${action.requestId}`, `Worker ${callerId} ${action.kind}.\n${action.text}`, callerId, action.kind, report); - return { accepted: true, destination: 'coordinator', taskId: callerId, routing: routing.routing }; - } case 'record': { this.ledger.record(state.id, { requestId: action.requestId, key: action.key, text: action.text, expectedVersion: action.expectedVersion, authorTaskId: callerId, ...(action.scope ? { scope: action.scope } : {}) }); diff --git a/test/project-runtime.test.ts b/test/project-runtime.test.ts index c0f73a7..b0b4794 100644 --- a/test/project-runtime.test.ts +++ b/test/project-runtime.test.ts @@ -52,6 +52,13 @@ function projectIssue(number: number, repository = 'example/frontend', changes: }); } +async function requestReport(f: Awaited>, taskId: string, messageId: string): Promise { + const worker = await f.openGroup(taskId); + assert.ok(worker.chatId); + await f.loop.receive(f.message(messageId, '请汇报给协调者。', worker.chatId)); + return messageId; +} + test('delegated workers and secondWorkers stay group-less until the coordinator opens one without replaying history', async t => { const f = await fixture(t, { secondProject: true }); await f.initialize(); const worker = await f.dispatch('lazy-worker', 'Investigate the requested change.'); @@ -696,8 +703,9 @@ for (const kind of ['result', 'question', 'update'] as const) test(`worker ${kin const f = await fixture(t); await f.initialize(); const worker = await f.dispatch('investigate', 'Investigate the existing export behavior.'); await f.idleCoordinator(); + const requestId = await requestReport(f, worker.id, `report-${kind}`); const starts = f.codex.starts.filter(input => input.threadId === f.coordinator().threadId).length; - const action: ProjectAction = { action: 'report', requestId: `report-${kind}`, kind, routing: 'final', + const action: ProjectAction = { action: 'report', requestId, kind, routing: 'final', text: kind === 'question' ? 'Batch size is undefined. Choose a fixed size or all rows; recommend a fixed size.' : 'Investigation report is ready at docs/export.md. Implementation is still pending.' }; await f.loop.projectAction(worker.id, action); await f.loop.projectAction(worker.id, action); await f.loop.tick(); const events = f.events(f.coordinator().id, kind); assert.equal(events.length, 1); @@ -710,6 +718,53 @@ for (const kind of ['result', 'question', 'update'] as const) test(`worker ${kin await assert.rejects(f.loop.projectAction(worker.id, { ...action, text: 'Changed report under the same ID' }), /different|conflict|already/i); }); +test('Worker discussion cannot report to the coordinator without an explicit owner request', async t => { + const f = await fixture(t); await f.initialize(); + const worker = await f.dispatch('unsolicited-report', 'Clarify the scope in the Worker group.'); + const group = await f.openGroup(worker.id); assert.ok(group.chatId); + await f.idleCoordinator(); + const discussion = f.message('ordinary-discussion', '需求还没聊完,继续讨论。', group.chatId); + await f.loop.receive(discussion); + await assert.rejects(f.loop.projectAction(worker.id, { + action: 'report', kind: 'result', requestId: discussion.id, text: 'Current findings.', + }), /explicit.*report/i); + await f.loop.tick(); + assert.equal(f.events(f.coordinator().id, 'result').length, 0); + assert.equal(f.coordinator().status, 'idle'); +}); + +test('coordinator reports require an affirmative request from the current Worker group owner', async t => { + const f = await fixture(t); const coordinator = await f.initialize(); + const worker = await f.dispatch('report-source', 'Discuss scope.'); + const group = await f.openGroup(worker.id); assert.ok(group.chatId && coordinator.chatId); + await f.idleCoordinator(); + const requests = [ + f.message('negated', '先不要汇报给协调者。', group.chatId), + f.message('scoped-negation', '把这个结论暂时不汇报给协调者。', group.chatId), + f.message('scoped-deferral', '把这个结论晚点汇报给协调者。', group.chatId), + f.message('question', '现在需要汇报给协调者吗?', group.chatId), + f.message('deferred', '等需求确认后再汇报给协调者。', group.chatId), + f.message('quoted', '“同步给协调者”', group.chatId), + f.message('project-group', '请汇报给协调者。', coordinator.chatId), + { ...f.message('other-sender', '请汇报给协调者。', group.chatId), senderId: 'stranger' }, + ]; + for (const message of requests) { + await f.loop.receive(message); + await assert.rejects(f.loop.projectAction(worker.id, { + action: 'report', requestId: message.id, kind: 'update', routing: 'final', text: 'A scope summary.', + }), /explicit.*report/i); + } + const oldRequest = f.message('retired-group-request', '请汇报给协调者。', group.chatId); + await f.loop.receive(oldRequest); + retireTaskGroup(f.loop.store, worker.id, group.chatId); + const replacement = await f.openGroup(worker.id, 'open-replacement'); + assert.ok(replacement.chatId && replacement.chatId !== group.chatId); + await assert.rejects(f.loop.projectAction(worker.id, { + action: 'report', requestId: oldRequest.id, kind: 'update', routing: 'final', text: 'An old group summary.', + }), /explicit.*report/i); + assert.equal(f.events(coordinator.id, 'update').length, 0); +}); + test('intermediate Worker reports stay in the Worker group, survive restart and never wake the coordinator', async t => { const f = await fixture(t); await f.initialize(); const worker = await f.dispatch('intermediate-report', 'Discuss the assigned contract.'); @@ -736,7 +791,8 @@ test('final Worker reports retain task-group sources and reach only the coordina const group = await f.openGroup(worker.id); assert.ok(group.chatId); const owner = f.message('final-source', '确认采用当前范围。', group.chatId); await f.loop.receive(owner); await f.loop.tick(); - const action: ProjectAction = { action: 'report', requestId: 'final-conclusion', kind: 'result', text: '结论已确认。' }; + const requestId = await requestReport(f, worker.id, 'final-conclusion'); + const action: ProjectAction = { action: 'report', requestId, kind: 'result', text: '结论已确认。' }; const first = await f.loop.projectAction(worker.id, action); assert.deepEqual(first, { accepted: true, destination: 'coordinator', taskId: worker.id, routing: 'final' }); assert.deepEqual(await f.loop.projectAction(worker.id, action), first); @@ -745,17 +801,23 @@ test('final Worker reports retain task-group sources and reach only the coordina assert.equal(event[0]?.provenance.kind, 'agent'); if (event[0]?.provenance.kind === 'agent') { assert.equal(event[0].provenance.routing, 'final'); - assert.deepEqual(event[0].provenance.sources, [{ messageId: owner.id, chatId: owner.chatId, senderId: owner.senderId }]); + assert.deepEqual(event[0].provenance.sources, [ + { messageId: owner.id, chatId: owner.chatId, senderId: owner.senderId }, + { messageId: requestId, chatId: owner.chatId, senderId: owner.senderId }, + ]); } await f.restart(); await f.loop.projectAction(worker.id, action); await f.loop.tick(); assert.equal(f.events(f.coordinator().id, 'result').length, 1); }); -test('escalation reports reach the coordinator without a Worker group and require a reason', async t => { +test('escalation reports require an explicit Worker group request and a reason', async t => { const f = await fixture(t); await f.initialize(); const worker = await f.dispatch('escalate-report', 'Escalate only coordination matters.'); const action: ProjectAction = { action: 'report', requestId: 'authorization-escalation', kind: 'question', text: '需要确认授权范围。', routing: 'escalation', escalation: 'authorization' }; + await assert.rejects(f.loop.projectAction(worker.id, { ...action, routing: 'intermediate' }), /explicit.*report/i); + assert.equal(f.events(f.coordinator().id, 'question').length, 0); + await requestReport(f, worker.id, action.requestId); const first = await f.loop.projectAction(worker.id, action); assert.deepEqual(first, { accepted: true, destination: 'coordinator', taskId: worker.id, routing: 'escalation' }); await f.loop.projectAction(worker.id, action); await f.loop.tick(); @@ -821,9 +883,12 @@ test('a direct owner decision stays in the Worker group until a sourced discussi assert.equal(f.events(f.coordinator().id, 'owner_input').length, 0); const request = f.message('sync-scope', '只把选中行范围同步给协调者。', worker.chatId!); await f.loop.receive(request); - const summary: ProjectAction = { action: 'report', requestId: `sync-${request.id}`, kind: 'update', routing: 'final', + const summary: ProjectAction = { action: 'report', requestId: request.id, kind: 'update', routing: 'final', text: `主题:选中行。已定:仅选中行。范围变化:更新后端契约。待决:无。证据:scope.log。用户决定 ${decision.id},群 ${decision.chatId},发送者 ${decision.senderId};同步要求 ${request.id},群 ${request.chatId},发送者 ${request.senderId}。不部署。` }; - await f.loop.projectAction(worker.id, summary); await f.loop.projectAction(worker.id, summary); await f.loop.tick(); + const receipts = await Promise.all([f.loop.projectAction(worker.id, summary), f.loop.projectAction(worker.id, summary)]); + assert.deepEqual(receipts[0], receipts[1]); + await assert.rejects(f.loop.projectAction(worker.id, { ...summary, requestId: 'second-sync' }), /explicit.*report/i); + await f.loop.tick(); const reports = f.events(f.coordinator().id, 'update'); assert.equal(reports.length, 1); assert.equal(reports[0]?.provenance.kind, 'agent'); if (reports[0]?.provenance.kind === 'agent') { @@ -1138,13 +1203,15 @@ test('a final investigation reply stays local and an explicit report wakes the c assert.equal(observed.status, 'idle'); assert.equal(observed.executionStatus, 'completed'); assert.equal(f.events(f.coordinator().id, 'final_answer').length, 0); assert.equal(f.coordinator().status, 'idle'); - await f.loop.projectAction(worker.id, { action: 'report', requestId: 'investigation-result', kind: 'result', text: result }); + assert.equal(f.codex.starts.filter(input => input.threadId === worker.threadId).length, 1); + const requestId = await requestReport(f, worker.id, 'investigation-result'); + await f.loop.projectAction(worker.id, { action: 'report', requestId, kind: 'result', text: result }); + f.codex.complete(worker.threadId!, null); await f.loop.tick(); assert.equal(f.events(f.coordinator().id, 'result').length, 1); assert.equal(f.coordinator().status, 'running'); assert.equal(f.state().issues[0]?.state, 'open'); assert.equal(f.state().records.length, 0); assert.equal(f.github.verifications.length, 0); - assert.equal(f.codex.starts.filter(input => input.threadId === worker.threadId).length, 1); await f.restart(); await f.loop.tick(); assert.equal(f.events(f.coordinator().id, 'final_answer').length, 0); assert.equal(f.loop.store.task(worker.id).status, 'idle'); @@ -1502,12 +1569,10 @@ for (const role of ['worker', 'worker'] as const) for (const grouped of [false, const outgoing = f.loop.store.outputs(worker.id).filter(output => output.text === result); assert.equal(outgoing.length, 1); assert.equal(outgoing[0]?.status, grouped ? 'sent' : 'dropped'); assert.equal(f.feishu.sent.filter(output => output.chatId === worker.chatId && output.text === result).length, grouped ? 1 : 0); - await f.loop.projectAction(worker.id, { action: 'report', requestId: 'formal-result', kind: 'result', text: result }); - await f.loop.tick(); - assert.equal(f.events(coordinator.id, 'result')[0]?.status, 'delivered'); - assert.equal(f.codex.starts.length, starts + (running ? 0 : 1)); - assert.equal(f.codex.steers.length, steers + (running ? 1 : 0)); - assert.equal(f.coordinator().threadId, coordinator.threadId); + await assert.rejects(f.loop.projectAction(worker.id, { + action: 'report', requestId: 'formal-result', kind: 'result', text: result, + }), /explicit.*report/i); + assert.equal(f.events(coordinator.id, 'result').length, 0); }); } @@ -1526,14 +1591,14 @@ for (const running of [false, true]) test(`Worker group messages stay local with assert.deepEqual(f.loop.store.inputs(worker.id).find(input => input.id === message.id)?.provenance, { kind: 'user', message }); }); -for (const role of ['worker', 'worker'] as const) for (const kind of ['result', 'question', 'update'] as const) for (const running of [false, true]) for (const grouped of [false, true]) { - test(`${role} explicit ${kind} report arrives once with coordinator running=${running} and grouped=${grouped}`, async t => { +for (const kind of ['result', 'question', 'update'] as const) for (const running of [false, true]) { + test(`Worker ${kind} report requested by the owner arrives once with coordinator running=${running}`, async t => { const f = await fixture(t); await f.initialize(); - const worker = await f.dispatch('formal-report', 'Perform the assigned work.', { role }); - if (grouped) await f.openGroup(worker.id); + const worker = await f.dispatch('formal-report', 'Perform the assigned work.'); if (!running) await f.idleCoordinator(); + const requestId = await requestReport(f, worker.id, `formal-${kind}`); const coordinator = f.coordinator(), starts = f.codex.starts.length, steers = f.codex.steers.length; - const action: ProjectAction = { action: 'report', kind, routing: 'final', requestId: `formal-${kind}`, text: `Formal ${kind} with evidence docs/findings.md.` }; + const action: ProjectAction = { action: 'report', kind, routing: 'final', requestId, text: `Formal ${kind} with evidence docs/findings.md.` }; await f.loop.projectAction(worker.id, action); await f.loop.projectAction(worker.id, action); await f.loop.tick(); assert.equal(f.events(coordinator.id, kind).length, 1); assert.equal(f.events(coordinator.id, kind)[0]?.status, 'delivered'); @@ -1553,22 +1618,26 @@ test('elapsed time and restarts leave idle project members waiting until an expl await f.idleCoordinator(); const starts = f.codex.starts.length, steers = f.codex.steers.length; const inputs = f.loop.store.inputs(f.coordinator().id); + const coordinatorStarts = () => f.codex.starts.filter(input => input.threadId === f.coordinator().threadId).length; + const initialCoordinatorStarts = coordinatorStarts(); let now = Date.now(); t.mock.method(Date, 'now', () => now); for (let day = 0; day < 3; day++) { now += 86_400_000; await f.loop.tick(); await f.restart(); } assert.equal(f.coordinator().status, 'idle'); assert.equal(f.codex.starts.length, starts); assert.equal(f.codex.steers.length, steers); assert.deepEqual(f.loop.store.inputs(f.coordinator().id), inputs); assert.equal(f.events(f.coordinator().id, 'supervision').length, 0); - await f.loop.projectAction(secondWorker.id, { action: 'report', requestId: 'new-evidence', kind: 'update', routing: 'final', text: 'New evidence arrived.' }); + const requestId = await requestReport(f, secondWorker.id, 'new-evidence'); + await f.loop.projectAction(secondWorker.id, { action: 'report', requestId, kind: 'update', routing: 'final', text: 'New evidence arrived.' }); await f.loop.tick(); - assert.equal(f.codex.starts.length, starts + 1); + assert.equal(coordinatorStarts(), initialCoordinatorStarts + 1); assert.equal(f.events(f.coordinator().id, 'update')[0]?.status, 'delivered'); }); test('an acknowledged report with a lost delivery response reconciles once after restart', async t => { const f = await fixture(t); await f.initialize(); const worker = await f.dispatch('lost-report-ack', 'Investigate.'); await f.idleCoordinator(); - const action: ProjectAction = { action: 'report', requestId: 'stable-report', kind: 'result', text: 'Evidence is in docs/result.md.' }; + const requestId = await requestReport(f, worker.id, 'stable-report'); + const action: ProjectAction = { action: 'report', requestId, kind: 'result', text: 'Evidence is in docs/result.md.' }; await f.loop.projectAction(worker.id, action); const starts = f.codex.starts.length; f.codex.loseInputAck = true; await f.loop.tick(); @@ -1623,11 +1692,13 @@ for (const status of ['pending', 'held', 'failed'] as const) test(`obsolete auto assert.equal(retired.status, 'dropped'); assert.match(retired.error ?? '', /Retired automatic project event/); assert.deepEqual({ ...retired, status: input.status, error: input.error }, input); } - await f.loop.projectAction(worker.id, { action: 'report', requestId: 'paused-report', kind: 'update', routing: 'final', text: 'Explicit new evidence while paused.' }); + assert.equal(f.codex.starts.length, starts); assert.equal(f.codex.steers.length, steers); + const requestId = await requestReport(f, worker.id, 'paused-report'); + await f.loop.projectAction(worker.id, { action: 'report', requestId, kind: 'update', routing: 'final', text: 'Explicit new evidence while paused.' }); await f.loop.tick(); assert.equal(f.coordinator().status, 'paused'); assert.equal(f.events(coordinator.id, 'update')[0]?.status, 'held'); - assert.equal(f.codex.starts.length, starts); assert.equal(f.codex.steers.length, steers); + assert.equal(f.codex.starts.length, starts); await f.loop.control(coordinator.id, 'resume'); await f.loop.tick(); assert.equal(f.events(coordinator.id, 'update')[0]?.status, 'delivered'); assert.equal(f.codex.starts.length, starts + 1); @@ -1658,7 +1729,8 @@ test('historical attempted automatic inputs retain uncertainty and reconcile see assert.equal(f.loop.store.inputs(coordinator.id).find(input => input.id === ids[1])?.status, 'delivered'); assert.equal(f.loop.store.inputs(coordinator.id).find(input => input.id === ids[2])?.status, 'uncertain'); assert.equal(f.codex.starts.length, starts); assert.equal(f.codex.steers.length, steers); - await f.loop.projectAction(worker.id, { action: 'report', requestId: 'after-uncertain', kind: 'result', text: 'Preserve this explicit report.' }); + const requestId = await requestReport(f, worker.id, 'after-uncertain'); + await f.loop.projectAction(worker.id, { action: 'report', requestId, kind: 'result', text: 'Preserve this explicit report.' }); await f.loop.tick(); assert.equal(f.events(coordinator.id, 'result')[0]?.status, 'pending'); f.codex.snapshot(coordinator.threadId).seenInputIds.push(ids[2]!); await f.loop.tick(); @@ -1734,8 +1806,11 @@ test('current reporting and event guidance reaches new and resumed Worker, secon const worker = await f.dispatch('guidance-worker', 'Discuss scope.'); const secondWorker = await f.dispatch('guidance-secondWorker', 'Verify the result.', { role: 'worker' }); const assertWorkerGuidance = (instructions: string) => { - for (const requirement of ['普通对话不要自行调用 report', '不因需求尚未确定而机械 report', '普通讨论无需改用原生问题', '完成后必须主动 report result', '直接通过 report update', '无需先展示预览', '用户指定话题时只同步该话题', '真实消息 ID、群 ID、发送者', '不把同步要求当作实施、合并、部署或原生工具批准']) assert.ok(instructions.includes(requirement), requirement); - assert.ok(!instructions.includes('最终答复也会回传协调者')); + for (const requirement of ['只有所有者在当前 Worker 群明确要求汇报给协调者时', '把 requestId 设置为该用户消息的确切 ID', + '每条消息最多发送一份汇报', '无需先展示预览', '按用户指定范围汇报', '真实消息 ID、群 ID 和发送者']) { + assert.ok(instructions.includes(requirement), requirement); + } + assert.ok(!instructions.includes('完成后必须主动 report result')); }; for (const role of ['worker', 'worker']) { const created = f.codex.created.find(input => input.instructions.includes(`Project role: ${role}.`)); assert.ok(created); @@ -1747,7 +1822,7 @@ test('current reporting and event guidance reaches new and resumed Worker, secon const update = f.codex.instructionUpdates.filter(input => input.threadId === task.threadId).at(-1); assert.ok(update); assertWorkerGuidance(update.instructions); } - assert.ok(f.codex.instructionUpdates.filter(input => input.threadId === f.coordinator().threadId).at(-1)?.instructions.includes('普通对话和普通最终答复不会自动传给你')); + assert.ok(f.codex.instructionUpdates.filter(input => input.threadId === f.coordinator().threadId).at(-1)?.instructions.includes('只有所有者在当前 Worker 群明确要求向你汇报时')); }); test('a constructed initial-batch fixture excludes dropped copies while delivering its valid source inputs', async t => { @@ -1757,7 +1832,8 @@ test('a constructed initial-batch fixture excludes dropped copies while deliveri const eventId = `${receipt.taskId}:user:obsolete-before-start`; f.loop.projects.event('app', eventId, 'Obsolete initial copy.', receipt.taskId, 'owner_input'); f.loop.store.setMeta(`project-intake-promotion:${coordinator.id}`, 'constructed initial-batch fixture'); - await f.loop.projectAction(receipt.taskId, { action: 'report', requestId: 'early-report', kind: 'update', routing: 'final', text: 'Valid early report.' }); + const requestId = await requestReport(f, receipt.taskId, 'early-report'); + await f.loop.projectAction(receipt.taskId, { action: 'report', requestId, kind: 'update', routing: 'final', text: 'Valid early report.' }); await f.loop.tick(); const started = f.codex.starts.find(input => input.threadId === f.coordinator().threadId); assert.ok(started); const retiredId = `project:${coordinator.id}:${eventId}`;