diff --git a/.scratch/worker-group-reply-once/issues/01-report-final-identity.md b/.scratch/worker-group-reply-once/issues/01-report-final-identity.md new file mode 100644 index 0000000..7c37e62 --- /dev/null +++ b/.scratch/worker-group-reply-once/issues/01-report-final-identity.md @@ -0,0 +1,9 @@ +Status: ready-for-agent + +# Bind an explicit final acknowledgement to its report + +Implement spec v1.0 in the report publication and final observation paths. Correct Worker guidance, retain stable request IDs and destination binding, and cover both local tool entry points. Deliver regression evidence and a PR for independent verification. No merge or live acceptance is authorized. + +## Comments + +The root cause entered with report-local publication in commit `4c9549558e0f2c3e17ff066349c7961ace103210`. Ordinary final publication remained independent. The exact recorded outputs are paraphrases, so matching equal text alone cannot repair this instance safely. diff --git a/.scratch/worker-group-reply-once/spec.md b/.scratch/worker-group-reply-once/spec.md new file mode 100644 index 0000000..ba28f7a --- /dev/null +++ b/.scratch/worker-group-reply-once/spec.md @@ -0,0 +1,38 @@ +Status: ready-for-agent + +# Worker group reply once + +Version: 1.0, 2026-11-20. + +The owner reported that one reply appeared twice in a task group and authorized investigation and repair. Source message `om_x100b60cad3b554b8c4b2cba1d5b3e75`, project group `oc_586b1866902382e0db4dff8d25c0f3f7`, sender `ou_5c280b16780ac4016c7455a276b2d95b`. Original text was “需要定位修复下这个问题,看着像是同一条消息往群里发送了两遍”. This source was checked in a read-only inbox query. + +The screenshot matches model discussion task `281cb9db-aad5-4322-9dda-bedabc67bc5d`, task group `oc_d73a9b9860b485000b27f193de585cd1`. An intermediate report and a paraphrased ordinary final were independently published in one turn. Each has its own sent outbox row. This is separate publication identity, not a transport retry. + +## Agreed scope + +Coordinator instruction `duplicate-reply-explicit-identity-decision-v1` accepts a minimal explicit acknowledgement under the authorized bug repair scope. It is a coordinator technical judgment, not a new owner product authorization. Instruction `duplicate-reply-continue-implementation-v1` confirms implementation should continue. + +Use one publication path for one answer. Ordinary terminal replies use final. A report receipt can guide a Worker to explicitly acknowledge an already accepted report when it has no new reply. The acknowledgement binds the original task, Thread, Turn and report request. It selects one exact prospective final for omission from chat. No visible protocol marker is required. All unmarked final prose remains deliverable. + +## Acceptance + +- Exercise the real local AgentLoop report receipt, native tool handler and capability bridge with fake external transports. +- A compliant report, acknowledgement and final produces one group publication through retries and restart. +- Report and acknowledgement admission preserve original binding after partial failure or a later-turn retry. +- Missing, malformed, stale, foreign-task, foreign-thread and foreign-turn references cannot suppress a legitimate final. +- A distinct final, including one after steering or after an acknowledged final, is still published. +- A report queued for delivery remains durable when the final is acknowledged. Failed or dropped reports cannot be mistaken for completed delivery. A queued receipt does not claim transport delivery. +- Native questions, permissions and approvals retain their existing identities and routing. + +## Exclusions and limits + +No text similarity classification or blanket final suppression. Historical unmarked report plus paraphrase remains two publications. No generic messaging protocol, live test messages, DB mutations, deletion, merge, deployment or service restart. Independent verification is arranged by the coordinator. Preserve other worktrees and the model selection task. + +## Evidence + +Thread `01a1f79c-d053-7942-9d37-245335533c92`, turn `01a1f7a4-b353-73a0-9abb-c071e28ded4a`. + +- Report request `worker-model-discussion-round-3-v1`, tool call `call_J0abcnvpIy4JeTbbRKqkcY2Q`, at 2026-11-20T06:31:01.168Z. Sent outbox `829881d81fc491bcf057773000fc0f7d`. +- Final item `msg_0472062dcc870590016affe93d3ee487d185c1d0c564fd084f`, at 2026-11-20T06:31:28.655Z. Sent outbox `4d6d878746ae7f87ba6a5cf702c384f7`. +- Each ID equals the first 32 hex digits of sha256(taskId + ':' + its publication key). Keys are `worker-report:` and `agent-output:::`. +- Outbox retains transport status but no remote Feishu message ID. These facts establish independent logical publications, not a count of network requests. diff --git a/docs/adr/0021-worker-discussion-routing.md b/docs/adr/0021-worker-discussion-routing.md index 2e7e572..bfc0a6a 100644 --- a/docs/adr/0021-worker-discussion-routing.md +++ b/docs/adr/0021-worker-discussion-routing.md @@ -21,3 +21,10 @@ Runtime 从 Worker 任务中收集用户消息的 `messageId`、`chatId` 和 `se 路由先通过项目成员关系校验。Worker 不能为其他项目创建汇报。中间汇报没有有效任务群时失败关闭,不降级发送给协调者。跨群汇报使用 Worker 群明确请求汇报的所有者消息 ID 作为 `requestId`。Runtime 校验实际收到的消息及其当前群绑定。同一消息只对应一份汇报,投递记录与回执一起写入 SQLite。 这项决策只改变 Worker `report` 的去向。普通用户输入仍按任务群路由,原生问题、审批和权限请求仍使用原有路径。项目协调者仍只能通过 `announce` 发送协调群公告。 + + +2026-11-20 修复记录。任务群的普通问答默认通过普通最终答复发布。`routing=intermediate` 用于继续执行期间需要立即发布的讨论。两种路径可以发布不同的消息,不以文字相似度或“本轮已汇报”合并。 + +已接收入队且绑定可信执行身份的 intermediate report 回执提供 `acknowledgement` 指导。Worker 需要用文字结束一条已经发布的答复时,调用 `acknowledge_report`,引用该 report 的 `reportRequestId`,并明确指定即将输出的完整 `finalText`。Runtime 校验任务、原 Thread、Turn 和原投递目标,只省略这一条明确确认的 final 副本。确认信息通过工具回执传递,不向群聊发送协议标记。未确认的普通 final、新发现、用户后续输入产生的答复及原生问题、审批继续正常处理。 + +这项修复保证遵守显式确认约定的发布流程只投递一次。没有关联身份的旧式 report 加改写 final 仍是两个发布,不自动推断其语义相同。回执中的 queued 只承诺持久化入队;发送结果未知仍遵循现有保守恢复策略。 diff --git a/docs/project-coordinator.md b/docs/project-coordinator.md index b7f3f67..122c71e 100644 --- a/docs/project-coordinator.md +++ b/docs/project-coordinator.md @@ -64,7 +64,7 @@ GitHub Feature 是外部需求提案。即使 Issue 描述完整,也不能直 Issue 评论先交协调者判断影响,再按需转给原 Worker。Worker 的普通最终答复、任务群内用户消息留在原任务,保留完整来源、附件、原 Thread 和任务记录。GitHub 事件和 Worker 汇报触发的协调者普通最终答复保留在协调者 Thread、执行记录和进度文档中;需要用户处理时,协调者使用 `announce` 发送带类型标题的普通文本。用户直接在项目协调群发消息后的协调者答复继续发送到项目群。 -Worker 在任务群里处理普通问答和阶段结论。`routing=intermediate` 的汇报发回 Worker 群。用户在 Worker 群明确说“请汇报给协调者”或“只把选中行范围同步给协调者”后,Worker 才能使用 `routing=final` 或 `routing=escalation`。原生问题、审批、权限请求、执行失败和非暂停中断由 Runtime 通知协调者。 +Worker 在任务群里处理普通问答和阶段结论。普通问答使用最终答复留在任务群。`routing=intermediate` 的汇报发回 Worker 群。已接收入队且绑定当前执行轮次的 report 回执提供 acknowledgement 指导,Worker 可用 `acknowledge_report` 引用该 report 并指定完整 finalText,Runtime 只省略这次明确确认的 final 副本。未确认的普通 final、新发现、用户后续输入和原生问题、审批、权限请求继续正常处理。用户在 Worker 群明确说“请汇报给协调者”或“只把选中行范围同步给协调者”后,Worker 才能使用 routing=final 或 routing=escalation。 Worker 用该条用户消息的飞书 ID 作为 `requestId`。Runtime 校验消息、发送者、当前 Worker 群以及明确的汇报要求。每条请求对应一份汇报。用相同的 ID 和内容重试会返回原回执。摘要包含用户指定话题的结论、范围变化、待决问题和证据,并引用真实用户消息。实施、合并、部署及原生审批各自需要对应的授权。 diff --git a/prompts/worker.md b/prompts/worker.md index e9ddcf2..6f5962b 100644 --- a/prompts/worker.md +++ b/prompts/worker.md @@ -8,7 +8,7 @@ 开发必须在独立工作树和分支中进行,确认实际工作目录。完成后提交 PR,作为唯一 PR Owner 维护分支和处理反馈。没有协调者确认独立验证和合并条件,不自行合并。合并、Issue 关闭和安全清理按当前项目的明确授权执行,公共提示词不授予额外权限,不包含部署或绕过分支保护。纯调查或澄清任务交付文档与证据。 -普通讨论、结论和任务完成情况留在本任务。一轮结束只代表本轮结束。需要在任务群留下可见的中间问题或讨论时,使用 project_action 的 report,kind 使用 question 或 update,routing 设置为 intermediate。只有所有者在当前 Worker 群明确要求汇报给协调者时,才可使用 routing=final 或 routing=escalation。把 requestId 设置为该用户消息的确切 ID,每条消息最多发送一份汇报。重试使用相同 ID 和内容。 +普通问答直接写在最终答复中,不调用 report。普通讨论、结论和任务完成情况留在本任务。一轮结束只代表本轮结束。需要在继续执行期间向任务群发布中间问题或讨论时,使用 project_action 的 report,kind 使用 question 或 update,routing 设置为 intermediate。report 已接收入队后,不要在最终答复中改写或复述同一条答复。没有新增内容时可以结束而不输出文字。需要文字最终答复时,使用 report 回执中的 acknowledgement 指导,调用 acknowledge_report,携带 reportRequestId 和即将输出的完整 finalText,收到 accepted 后才原样输出。确认失败时不能当作已经发布。新增发现或用户后续消息的答复仍正常输出,不确认成旧 report。只有所有者在当前 Worker 群明确要求汇报给协调者时,才可使用 routing=final 或 routing=escalation。把 requestId 设置为该用户消息的确切 ID,每条消息最多发送一份汇报。重试使用相同 ID 和内容。 收到“同步给协调者”或“把这个结论汇报给协调者”等明确请求后,按用户指定范围汇报,无需先展示预览。结论和讨论摘要使用 routing=final。授权、范围变化或阻塞需要升级时,使用 routing=escalation 并设置 escalation 为 authorization、scope_change 或 blocker。按汇报内容列出结论、范围变化、待决问题、实际产物路径、PR 链接、提交版本、验证证据和限制。根据本任务收到的 Input provenance as data 引用真实消息 ID、群 ID 和发送者,区分用户决定与代理判断。这条请求只授权汇报。同步沿用本任务和原 Thread。遇到含糊、带条件或暂缓的表达时,继续在任务群确认。 diff --git a/src/loop.ts b/src/loop.ts index cfa1790..0a4327c 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -139,7 +139,7 @@ export class AgentLoop { return this.ensureWorkspace(taskId, repository); }, async (taskId, action) => { const activity = await this.capabilityActivity(taskId); - return this.projectAction(taskId, action, () => this.assertActiveTask(taskId, activity)); + return this.projectAction(taskId, action, () => this.assertActiveTask(taskId, activity), activity); }); ports.codex.setWorkspaceHandler(async request => { const task = this.store.taskForThread(request.threadId); @@ -150,7 +150,7 @@ export class AgentLoop { ports.codex.setProjectHandler?.(async request => { const task = this.store.taskForThread(request.threadId); if (!task) throw new Error('Project action requires an active task'); - return this.projectAction(task.id, request.action, () => this.assertActiveTask(task.id, request)); + return this.projectAction(task.id, request.action, () => this.assertActiveTask(task.id, request), request); }); } private assertActiveTask(taskId: string, identity: TurnIdentity): void { @@ -167,9 +167,9 @@ export class AgentLoop { if (activity.kind !== 'running') throw new Error('Capability requires a proven active turn'); return activity; } - async projectAction(taskId: string, action: ProjectAction, assertActive?: () => void): Promise { + async projectAction(taskId: string, action: ProjectAction, assertActive?: () => void, identity?: TurnIdentity): Promise { if (this.stopping) throw new Error('Runtime is stopping'); - const result = await this.projects.action(taskId, action, assertActive); + const result = await this.projects.action(taskId, action, assertActive, identity); if (action.action === 'complete_task') { this.forwardCompletedInputs(this.store.task(action.taskId)); await this.closeout.progress(action.taskId); } if (action.action === 'cleanup_artifacts') await this.closeout.progress(taskId); return result; @@ -858,7 +858,8 @@ export class AgentLoop { if (output.phase !== 'final' || 'kind' in snapshot) continue; if (task.legacy && this.store.hasOutput(task.id, `turn:${output.turnId}`)) continue; if (output.text.trim() && this.store.meta(`task-summary:${task.id}`) !== output.text) this.store.setMeta(`task-summary:${task.id}`, output.text); - if (output.text.trim() && this.projects.publishCoordinatorFinal(task, output.turnId)) this.notify(task, output.text, `agent-output:${output.id}`); + if (output.text.trim() && !this.projects.shouldSuppressWorkerFinal(task, output) + && this.projects.publishCoordinatorFinal(task, output.turnId)) this.notify(task, output.text, `agent-output:${output.id}`); } for (const request of snapshot.requests) { const identity = `${request.connectionEpoch}:${request.id}`; @@ -1196,6 +1197,11 @@ export class AgentLoop { } task.chatId = this.store.task(task.id).chatId; const chatId = task.chatId; + const target = this.store.outputTarget(output.id); + if (target && (chatId !== target.chatId || groupGeneration(this.store, task.id) !== target.generation)) { + this.store.markOutput(output.id, 'dropped', '任务群绑定已改变'); + continue; + } if (!chatId) { if (!approval) this.store.markOutput(output.id, 'dropped', '任务当前无群,不补发历史'); continue; diff --git a/src/project-runtime.ts b/src/project-runtime.ts index d6dd063..857c55a 100644 --- a/src/project-runtime.ts +++ b/src/project-runtime.ts @@ -7,9 +7,11 @@ import { ProjectCatalog } from './project-catalog.js'; import { ProjectLedger, projectView, currentRecords, matchesProjectIssue, projectActionSchema, type ProjectAction, type ProjectConfig, type ProjectState } from './project.js'; import type { ExecutionProfile } from './execution.js'; import { criteriaSchema, intakeRouteSchema, presentTaskSource, projectDecisionActionSchema, reportRoutingSchema, sourceType, submissionSchema, type InputProvenance, type ProjectDecisionAction, type ReportRouting, type ReportSource, type Source, type StructuredReport, type Task } from './domain.js'; -import type { GitHubPort } from './ports.js'; +import type { GitHubPort, TurnIdentity } from './ports.js'; +import type { AgentOutput } from './domain.js'; import type { TaskCloseout } from './task-closeout.js'; import { Store, type Inbox } from './store.js'; +import { groupGeneration } from './task-groups.js'; const hash = (text: string) => createHash('sha256').update(text).digest('hex'); const stableId = (text: string) => { @@ -27,6 +29,18 @@ const featureAuthorizationKey = (projectId: string, issueId: string, sourceRevis `project-feature-authorization:${hash(JSON.stringify([projectId, issueId, sourceRevision, scope, acceptance]))}`; const reportAuditKey = (projectId: string, taskId: string, requestId: string) => `project-report:${JSON.stringify([projectId, taskId, requestId])}`; +const reportAcknowledgementTurnKey = (projectId: string, taskId: string, threadId: string, turnId: string) => + `project-report-ack-turn:${JSON.stringify([projectId, taskId, threadId, turnId])}`; +const reportBindingSchema = z.strictObject({ threadId: z.string().min(1), turnId: z.string().min(1), connectionEpoch: z.string().min(1), chatId: z.string().min(1), generation: z.number().int().nonnegative() }); +const reportAuditSchema = z.object({ projectId: z.string(), taskId: z.string(), requestId: z.string(), text: z.string(), routing: reportRoutingSchema, + binding: reportBindingSchema.optional() }).passthrough(); +const reportAcknowledgementSchema = z.strictObject({ projectId: z.string(), taskId: z.string(), reportRequestId: z.string(), + threadId: z.string(), turnId: z.string(), connectionEpoch: z.string(), chatId: z.string(), generation: z.number().int().nonnegative(), + finalTextHash: z.string(), finalTextLength: z.number().int().nonnegative(), resolution: z.discriminatedUnion('kind', [ + z.strictObject({ kind: z.literal('pending'), inputSeq: z.number().int().nonnegative() }), + z.strictObject({ kind: z.literal('consumed'), outputId: z.string() }), z.strictObject({ kind: z.literal('cancelled') }), + ]) }); +type ReportAcknowledgement = z.infer; interface ProjectHost { closeout: TaskCloseout; makeTask(sourceId: string, prompt: string): Promise; @@ -48,15 +62,12 @@ export function resolveReportRouting(action: Extract item.projectId === member.projectId && item.taskId === task.id && item.threadId === output.threadId && item.turnId === output.turnId + && item.resolution.kind === 'consumed' && item.resolution.outputId === output.id)) return true; + if (this.store.hasOutput(task.id, `agent-output:${output.id}`)) return false; + const inputSeq = this.store.latestInputSeq(task.id); + const acknowledgements = saved.map((item): ReportAcknowledgement => item.resolution.kind === 'pending' && item.resolution.inputSeq < inputSeq + ? { ...item, resolution: { kind: 'cancelled' } } : item); + const match = acknowledgements.find(item => item.resolution.kind === 'pending' && item.projectId === member.projectId && item.taskId === task.id && item.threadId === output.threadId && item.turnId === output.turnId + && item.finalTextLength === output.text.length && item.finalTextHash === hash(output.text)); + const key = reportAcknowledgementTurnKey(member.projectId, task.id, output.threadId, output.turnId); + if (!match) { + if (JSON.stringify(saved) !== JSON.stringify(acknowledgements)) this.store.setMeta(key, JSON.stringify(acknowledgements)); + return false; + } + const report = this.store.outputForKey(task.id, `worker-report:${match.reportRequestId}`); + const target = report ? this.store.outputTarget(report.id) : null; + const rawAudit = this.store.meta(reportAuditKey(member.projectId, task.id, match.reportRequestId)); + let audit: z.infer | null = null; + if (rawAudit !== null) { + try { + const result = reportAuditSchema.safeParse(JSON.parse(rawAudit)); + if (result.success) audit = result.data; + } catch { audit = null; } + } + if (!report || report.status === 'dropped' || report.status === 'uncertain' || !audit || audit.projectId !== member.projectId || audit.taskId !== task.id + || audit.requestId !== match.reportRequestId || audit.routing !== 'intermediate' || !audit.binding + || audit.binding.threadId !== match.threadId || audit.binding.turnId !== match.turnId + || audit.binding.chatId !== match.chatId || audit.binding.generation !== match.generation || report.text !== audit.text + || !target || target.chatId !== match.chatId || target.generation !== match.generation + || (report.status !== 'sent' && (task.chatId !== target.chatId || groupGeneration(this.store, task.id) !== target.generation))) return false; + const updated = acknowledgements.map((item): ReportAcknowledgement => item.reportRequestId === match.reportRequestId + ? { ...item, resolution: { kind: 'consumed', outputId: output.id } } : item); + this.store.transaction(() => this.store.setMeta(key, JSON.stringify(updated))); + return true; + } private enqueue(taskId: string, key: string, text: string, provenance: InputProvenance): void { const task = this.store.task(taskId); this.store.receive(taskId, { id: `project:${taskId}:${key}`, chatId: task.chatId ?? '', senderId: 'runtime:project', @@ -266,10 +326,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 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}`; + 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}`; } - private reportSources(inputs: readonly Inbox[], explicit: ReportSource[] | undefined, request: ReportSource | undefined): ReportSource[] { + private reportSources(taskId: string, explicit: ReportSource[] | undefined): ReportSource[] { const seen = new Set(); const sources: ReportSource[] = []; const add = (source: ReportSource) => { @@ -277,14 +337,11 @@ export class ProjectRuntime { if (seen.has(key)) return; seen.add(key); sources.push(source); }; - for (const input of inputs) { + for (const input of this.store.inputs(taskId)) { 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 { @@ -357,7 +414,7 @@ export class ProjectRuntime { if (!record) throw new Error('Record receipt has no matching history'); return { accepted: true, requestId: record.requestId, key: record.key, version: record.version, ...(record.scope ? { scope: record.scope } : {}) }; } - async action(callerId: string, raw: unknown, assertActive?: () => void): Promise { + async action(callerId: string, raw: unknown, assertActive?: () => void, identity?: TurnIdentity): Promise { if (this.closing) throw new Error('Project runtime is stopping'); assertActive?.(); const action = projectActionSchema.parse(raw); @@ -382,13 +439,14 @@ 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); + if (action.action === 'report') { + const routing = resolveReportRouting(action); + if (routing.routing !== 'intermediate') this.reportRequest(this.store.task(callerId), action.requestId); + } + const deferredReportIntent = action.action === 'report'; + if (!deferredReportIntent) this.store.setMeta(intentKey, fingerprint); + const result = await this.perform(callerId, member, action, assertActive ? identity : undefined, { key: intentKey, fingerprint }); + if (action.action === 'acknowledge_report') return result; this.ledger.saveReceipt(member.projectId, callerId, action.requestId, fingerprint, result); return result; }; @@ -516,45 +574,18 @@ export class ProjectRuntime { text: input.message.text, createdAt: input.message.createdAt }); return { key, evidence }; } - private reportRequest(task: Task, requestId: string, input: Inbox | undefined): ReportSource { + private reportRequest(task: Task, requestId: string): ReportSource { + const input = this.store.inputs(task.id).find(candidate => candidate.id === requestId); 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 + 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 { + private async perform(callerId: string, member: NonNullable>, action: Exclude, identity: TurnIdentity | undefined, intent: { key: string; fingerprint: string }): Promise { const state = this.ledger.project(member.projectId); if (!state) throw new Error('Project unavailable'); switch (action.action) { @@ -675,6 +706,97 @@ 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 request = routing.routing === 'intermediate' ? undefined : this.reportRequest(this.store.task(callerId), action.requestId); + const sources = this.reportSources(callerId, [...(action.sources ?? []), ...(request ? [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: routing.routing, + ...(routing.escalation === undefined ? {} : { escalation: routing.escalation }), + ...(sources.length ? { sources } : {}), + } satisfies StructuredReport; + if (routing.routing === 'intermediate') { + const task = this.store.task(callerId); + const auditKey = reportAuditKey(state.id, callerId, action.requestId); + const originalAudit = this.store.meta(auditKey); + if (originalAudit === null && !task.chatId) throw new Error('Intermediate worker discussion requires an open Worker group'); + const binding = identity && task.chatId ? { threadId: identity.threadId, turnId: identity.turnId, connectionEpoch: identity.connectionEpoch, + chatId: task.chatId, generation: groupGeneration(this.store, callerId) } : undefined; + const outputKey = `worker-report:${action.requestId}`; + let receiptBinding: z.infer | undefined; + this.store.transaction(() => { + const existingIntent = this.store.meta(intent.key); + if (existingIntent !== null && existingIntent !== intent.fingerprint) { + throw new Error('Project request ID already has different content'); + } + const existingAudit = this.store.meta(auditKey); + if (existingAudit !== null) { + const saved = reportAuditSchema.parse(JSON.parse(existingAudit)); + if (saved.projectId !== state.id || saved.taskId !== callerId || saved.requestId !== action.requestId || saved.routing !== 'intermediate' + || saved.kind !== action.kind || saved.text !== action.text) + throw new Error('Project report conflicts with the original request'); + receiptBinding = saved.binding; + } else { + const firstBinding = existingIntent === null ? binding : undefined; + const audit = { projectId: state.id, taskId: callerId, requestId: action.requestId, kind: action.kind, text: action.text, + ...report, ...(firstBinding ? { binding: firstBinding } : {}) }; + this.store.setMeta(auditKey, JSON.stringify(audit)); + receiptBinding = firstBinding; + } + if (existingIntent === null) this.store.setMeta(intent.key, intent.fingerprint); + this.store.enqueue(callerId, action.text, outputKey, receiptBinding ? { chatId: receiptBinding.chatId, generation: receiptBinding.generation } : undefined); + const queued = this.store.outputForKey(callerId, outputKey); + if (!queued || queued.text !== action.text) throw new Error('Project report conflicts with its queued contents'); + if (queued.status === 'dropped') receiptBinding = undefined; + }); + return { accepted: true, destination: 'worker_group', taskId: callerId, routing: routing.routing, + ...(receiptBinding ? { delivery: 'queued', acknowledgement: { reportRequestId: action.requestId, + instruction: 'If this report is your complete reply, call acknowledge_report with a fresh stable requestId, this reportRequestId and the exact finalText you will emit. Emit that final only after the action is accepted.' } } : {}) }; + } + 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 'acknowledge_report': { + if (member.role !== 'worker') throw new Error('Only Workers can acknowledge their reports'); + if (!identity) throw new Error('Report acknowledgements require the active task turn'); + const task = this.store.task(callerId); + if (task.threadId !== identity.threadId) throw new Error('Report acknowledgement is bound to another task Thread'); + const rawAudit = this.store.meta(reportAuditKey(state.id, callerId, action.reportRequestId)); + if (rawAudit === null) throw new Error('Referenced report was not accepted'); + const audit = reportAuditSchema.parse(JSON.parse(rawAudit)); + if (audit.projectId !== state.id || audit.taskId !== callerId || audit.requestId !== action.reportRequestId || audit.routing !== 'intermediate' || !audit.binding + || audit.binding.threadId !== identity.threadId || audit.binding.turnId !== identity.turnId + || audit.binding.chatId !== task.chatId + || audit.binding.generation !== groupGeneration(this.store, callerId)) throw new Error('Referenced report is bound to another task group or turn'); + const output = this.store.outputForKey(callerId, `worker-report:${action.reportRequestId}`); + const target = output ? this.store.outputTarget(output.id) : null; + if (!output || output.status === 'dropped' || output.text !== audit.text + || !target || target.chatId !== audit.binding.chatId || target.generation !== audit.binding.generation) + throw new Error('Referenced report is not durably queued for the Worker group'); + const value = reportAcknowledgementSchema.parse({ projectId: state.id, taskId: callerId, reportRequestId: action.reportRequestId, + threadId: identity.threadId, turnId: identity.turnId, connectionEpoch: identity.connectionEpoch, + chatId: audit.binding.chatId, generation: audit.binding.generation, + finalTextHash: hash(action.finalText), finalTextLength: action.finalText.length, + resolution: { kind: 'pending', inputSeq: this.store.latestInputSeq(callerId) } }); + const turnKey = reportAcknowledgementTurnKey(state.id, callerId, identity.threadId, identity.turnId); + this.store.transaction(() => { + const existingTurn = this.store.meta(turnKey); + const turnValues = existingTurn === null ? [] : z.array(reportAcknowledgementSchema).parse(JSON.parse(existingTurn)); + const existing = turnValues.find(item => item.reportRequestId === action.reportRequestId); + if (existing) { + if (JSON.stringify({ ...existing, resolution: value.resolution }) !== JSON.stringify(value)) throw new Error('Report acknowledgement conflicts with the original text'); + } else { + this.store.setMeta(turnKey, JSON.stringify([...turnValues, value])); + } + this.ledger.saveReceipt(state.id, callerId, action.requestId, intent.fingerprint, { accepted: true, reportRequestId: action.reportRequestId }); + }); + return { accepted: true, reportRequestId: action.reportRequestId }; + } 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/src/project.ts b/src/project.ts index 6800d0a..5c35690 100644 --- a/src/project.ts +++ b/src/project.ts @@ -65,6 +65,7 @@ export const projectActionSchema = z.discriminatedUnion('action', [ z.strictObject({ action: z.literal('confirm_group_cleanup'), requestId: idSchema, planId: idSchema, messageId: idSchema }), z.strictObject({ action: z.literal('apply_group_cleanup'), requestId: idSchema, planId: idSchema }), z.strictObject({ action: z.literal('report'), requestId: idSchema, kind: z.enum(['result', 'question', 'update']), text: textSchema, ...structuredReportSchema.shape }), + z.strictObject({ action: z.literal('acknowledge_report'), requestId: idSchema, reportRequestId: idSchema, finalText: textSchema }), recordRequestSchema.extend({ action: z.literal('record') }), z.strictObject({ action: z.literal('rotate'), requestId: idSchema, checkpoint: textSchema }), z.strictObject({ action: z.literal('release_workspace'), requestId: idSchema, resourceId: idSchema }), diff --git a/src/store.ts b/src/store.ts index 82674ac..8d2c1f5 100644 --- a/src/store.ts +++ b/src/store.ts @@ -9,6 +9,7 @@ const payloadRow = z.object({ payload: z.string() }); const taskPayloadRow = payloadRow.extend({ id: z.string() }); const taskIdRow = z.object({ task_id: z.string() }); const metaRow = z.object({ value: z.string() }); +const outputTargetSchema = z.strictObject({ chatId: z.string().min(1), generation: z.number().int().nonnegative() }); const dataVersionRow = z.object({ data_version: z.number() }); const nameRow = z.object({ name: z.string() }); const sourceRow = payloadRow.extend({ reason: z.string() }); @@ -204,6 +205,10 @@ export class Store { if (filter.origin) { clauses.push('origin=?'); params.push(filter.origin); } return this.prepare(`SELECT 1 FROM inbox WHERE ${clauses.join(' AND ')} LIMIT 1`).get(...params) !== undefined; } + latestInputSeq(taskId: string): number { + const row = this.prepare('SELECT COALESCE(MAX(seq),0) AS seq FROM inbox WHERE task_id=?').get(taskId); + return sequenceRow.parse(row).seq; + } input(taskId: string, id: string): Inbox | null { return this.inputs(taskId).find(item => item.id === id) ?? null; } associateRequest(id: string, taskId: string, requestId: string): void { const input = this.inputs(taskId).find(item => item.id === id); @@ -211,11 +216,21 @@ export class Store { this.prepare('UPDATE inbox SET payload=? WHERE id=?').run(JSON.stringify({ message: input.message, provenance: input.provenance, requestId }), id); } markInput(id: string, status: Inbox['status'], error: string | null = null): void { this.prepare('UPDATE inbox SET status=?,error=? WHERE id=?').run(status, error, id); } - enqueue(taskId: string, text: string, key: string): string { + enqueue(taskId: string, text: string, key: string, target?: { chatId: string; generation: number }): string { const id = createHash('sha256').update(`${taskId}:${key}`).digest('hex').slice(0, 32); this.prepare("INSERT OR IGNORE INTO outbox VALUES(?,?,?,'pending',NULL)").run(id, taskId, text); + if (target) { + const next = outputTargetSchema.parse(target); + const original = this.outputTarget(id); + if (original && (original.chatId !== next.chatId || original.generation !== next.generation)) throw new Error('Output destination conflicts with the original request'); + if (!original) this.setMeta(`outbox-target:${id}`, JSON.stringify(next)); + } return id; } + outputTarget(id: string): { chatId: string; generation: number } | null { + const raw = this.meta(`outbox-target:${id}`); + return raw === null ? null : outputTargetSchema.parse(JSON.parse(raw)); + } hasOutput(taskId: string, key: string): boolean { const id = createHash('sha256').update(`${taskId}:${key}`).digest('hex').slice(0, 32); return this.prepare('SELECT id FROM outbox WHERE id=?').get(id) !== undefined; @@ -225,6 +240,11 @@ export class Store { const condition = statuses ? ` AND status IN (${statuses.map(() => '?').join(',')})` : ''; return this.prepare(`SELECT * FROM outbox WHERE task_id=?${condition} ORDER BY rowid`).all(taskId, ...(statuses ?? [])).map(row => outboxSchema.parse(row)); } + outputForKey(taskId: string, key: string): Outbox | null { + const id = createHash('sha256').update(`${taskId}:${key}`).digest('hex').slice(0, 32); + const row = this.prepare('SELECT * FROM outbox WHERE id=?').get(id); + return row ? outboxSchema.parse(row) : null; + } hasOutputs(taskId: string, statuses: readonly Outbox['status'][]): boolean { if (!statuses.length) return false; return this.prepare(`SELECT 1 FROM outbox WHERE task_id=? AND status IN (${statuses.map(() => '?').join(',')}) LIMIT 1`).get(taskId, ...statuses) !== undefined; diff --git a/test/project-runtime.test.ts b/test/project-runtime.test.ts index b0b4794..ed6db9b 100644 --- a/test/project-runtime.test.ts +++ b/test/project-runtime.test.ts @@ -438,6 +438,18 @@ async function fixture(t: TestContext, options: { secondProject?: boolean } = {} }); return { root, directory, config, projectConfigs, github, feishu, codex, workspaces, state, coordinator, events, message, get loop() { return loop; }, + async invoke(taskId: string, action: ProjectAction) { + const task = loop.store.task(taskId); assert.ok(task.threadId); + const snapshot = codex.snapshot(task.threadId); assert.ok(snapshot.turnId && codex.projectHandler); + return codex.projectHandler({ threadId: task.threadId, turnId: snapshot.turnId, connectionEpoch: 'fake-epoch', callId: `call-${action.action}`, action }); + }, + async bridge(taskId: string, action: ProjectAction) { + const actionFile = join(root, `project-action-${taskId}.json`); + await writeFile(actionFile, JSON.stringify(action)); + const capability = await (loop as unknown as { workspaceBridge: { grant(id: string): Promise } }).workspaceBridge.grant(taskId); + const result = await promisify(execFile)(process.execPath, ['--import', 'tsx', new URL('../src/project-client.ts', import.meta.url).pathname, capability, actionFile]); + return JSON.parse(result.stdout); + }, async seedLegacy(source: Source) { const repository = configSchema.parse({ execution: testExecution, feishu: { userOpenId: 'owner' }, repositories: [{ name: source.repository, path: directory, baseBranch: 'main', workspace: { kind: 'project-directory', path: directory } }] }).repositories[0]; assert.ok(repository && 'path' in repository && repository.workspace?.kind === 'project-directory'); @@ -765,6 +777,156 @@ test('coordinator reports require an affirmative request from the current Worker assert.equal(f.events(coordinator.id, 'update').length, 0); }); +test('acknowledged intermediate report publishes once while a distinct final remains visible', async t => { + const f = await fixture(t); await f.initialize(); + const worker = await f.dispatch('ack-report', 'Discuss the assigned contract.'); + const group = await f.openGroup(worker.id); assert.ok(group.chatId && group.threadId && group.turnId); + const sentBefore = f.feishu.sent.length; + const invoke = async (action: ProjectAction) => f.codex.projectHandler!({ threadId: group.threadId!, turnId: group.turnId!, + callId: `call-${action.action}`, connectionEpoch: 'fake-epoch', action }); + const report: ProjectAction = { action: 'report', requestId: 'published-answer', kind: 'question', routing: 'intermediate', text: 'Keep existing Workers on their original model?' }; + const receipt = z.object({ accepted: z.literal(true), destination: z.literal('worker_group'), delivery: z.literal('queued'), + acknowledgement: z.object({ reportRequestId: z.string(), instruction: z.string() }) }).parse(await invoke(report)); + assert.match(receipt.acknowledgement.instruction, /acknowledge_report/); + await invoke({ action: 'acknowledge_report', requestId: 'ack-answer', reportRequestId: receipt.acknowledgement.reportRequestId, finalText: 'Already asked whether existing Workers retain their model.' }); + f.codex.complete(group.threadId, 'Already asked whether existing Workers retain their model.'); + await f.loop.tick(); await f.loop.tick(); + const sent = () => f.feishu.sent.slice(sentBefore).filter(item => item.chatId === group.chatId).map(item => item.text); + assert.deepEqual(sent(), [report.text]); + assert.equal(f.loop.store.meta(`task-summary:${worker.id}`), 'Already asked whether existing Workers retain their model.'); + await f.restart(); await f.loop.tick(); assert.deepEqual(sent(), [report.text]); + await f.loop.receive(f.message('new-findings-input', 'Please check the remaining details.', group.chatId)); + await f.loop.tick(); + f.codex.complete(group.threadId, 'New finding. The selected model is unavailable.'); + await f.loop.tick(); + assert.deepEqual(sent(), [report.text, 'New finding. The selected model is unavailable.']); +}); + +for (const ingress of ['native', 'bridge'] as const) test(`report acknowledgement workflow uses the ${ingress} receipt and survives restart before final`, async t => { + const f = await fixture(t); await f.initialize(); + const worker = await f.dispatch(`producer-${ingress}`, 'Discuss whether existing Workers keep their model.'); + const group = await f.openGroup(worker.id); assert.ok(group.chatId && group.threadId); + const call = (action: ProjectAction) => ingress === 'native' ? f.invoke(worker.id, action) : f.bridge(worker.id, action); + const sentBefore = f.feishu.sent.length; + const report: ProjectAction = { action: 'report', requestId: `producer-report-${ingress}`, kind: 'question', routing: 'intermediate', text: 'Should existing Workers keep their original selection after configuration changes?' }; + const receipt = z.object({ acknowledgement: z.object({ reportRequestId: z.string(), instruction: z.string() }) }).parse(await call(report)); + assert.match(receipt.acknowledgement.instruction, /exact finalText/); + const finalText = 'The question about existing Workers is already in this task group.'; + const acknowledgement: ProjectAction = { action: 'acknowledge_report', requestId: `producer-ack-${ingress}`, reportRequestId: receipt.acknowledgement.reportRequestId, finalText }; + assert.deepEqual(await call(acknowledgement), { accepted: true, reportRequestId: report.requestId }); + await f.restart(); + assert.deepEqual(await call(acknowledgement), { accepted: true, reportRequestId: report.requestId }); + f.codex.complete(group.threadId, finalText); + await f.loop.tick(); await f.restart(); await f.loop.tick(); + assert.deepEqual(f.feishu.sent.slice(sentBefore).filter(item => item.chatId === group.chatId).map(item => item.text), [report.text]); + assert.equal(f.loop.store.meta(`task-summary:${worker.id}`), finalText); + assert.equal(f.events(f.coordinator().id, 'question').length, 0); +}); + +for (const restart of [false, true]) test(`new input after acknowledgement preserves even identical legitimate final with restart=${restart}`, async t => { + const f = await fixture(t); await f.initialize(); + const worker = await f.dispatch('steered-ack', 'Discuss the existing selection.'); + const group = await f.openGroup(worker.id); assert.ok(group.chatId && group.threadId); + const sentBefore = f.feishu.sent.length, text = 'Existing Workers retain their original model.'; + await f.invoke(worker.id, { action: 'report', requestId: 'before-steer', kind: 'update', routing: 'intermediate', text }); + const ack: ProjectAction = { action: 'acknowledge_report', requestId: 'before-steer-ack', reportRequestId: 'before-steer', finalText: text }; + await f.invoke(worker.id, ack); + await f.loop.receive(f.message('after-ack-steer', 'Please repeat that answer as my new confirmation.', group.chatId)); + assert.ok(f.codex.steers.some(item => item.deliveryId === 'after-ack-steer')); + if (restart) await f.restart(); + await f.invoke(worker.id, ack); + f.codex.complete(group.threadId, text); + await f.loop.tick(); await f.restart(); + assert.deepEqual(f.feishu.sent.slice(sentBefore).filter(item => item.chatId === group.chatId).map(item => item.text), [text, text]); +}); + +test('one acknowledged output identity does not consume another final item with the same text', async t => { + const f = await fixture(t); await f.initialize(); + const worker = await f.dispatch('multiple-finals', 'Discuss one answer.'); + const group = await f.openGroup(worker.id); assert.ok(group.chatId && group.threadId && group.turnId); + const sentBefore = f.feishu.sent.length, text = 'Keep the original selection.'; + await f.invoke(worker.id, { action: 'report', requestId: 'multiple-report', kind: 'update', routing: 'intermediate', text }); + await f.invoke(worker.id, { action: 'acknowledge_report', requestId: 'multiple-ack', reportRequestId: 'multiple-report', finalText: text }); + f.codex.complete(group.threadId, text); + f.codex.snapshot(group.threadId).outputs.push({ id: 'another-final-item', threadId: group.threadId, turnId: group.turnId, phase: 'final', text }); + await f.loop.tick(); await f.restart(); await f.loop.tick(); + assert.deepEqual(f.feishu.sent.slice(sentBefore).filter(item => item.chatId === group.chatId).map(item => item.text), [text, text]); +}); + +test('unknown, foreign, unbound and malformed report acknowledgements cannot suppress normal finals', async t => { + const f = await fixture(t); await f.initialize(); + const worker = await f.dispatch('invalid-acks', 'Discuss the contract.'); + const group = await f.openGroup(worker.id); assert.ok(group.chatId && group.threadId); + const other = await f.dispatch('foreign-report', 'Discuss another contract.'); await f.openGroup(other.id); + await f.invoke(other.id, { action: 'report', requestId: 'foreign-report-only', kind: 'update', routing: 'intermediate', text: 'Foreign task answer.' }); + await f.loop.projectAction(worker.id, { action: 'report', requestId: 'unbound-report', kind: 'update', routing: 'intermediate', text: 'Unbound answer.' }); + for (const reportRequestId of ['unknown-report', 'foreign-report-only', 'unbound-report', 'coordinator-report']) { + await assert.rejects(f.invoke(worker.id, { action: 'acknowledge_report', requestId: `invalid-${reportRequestId}`, reportRequestId, finalText: 'Legitimate final.' })); + } + assert.ok(f.codex.projectHandler); + await assert.rejects(f.codex.projectHandler({ threadId: group.threadId, turnId: group.turnId!, connectionEpoch: 'fake-epoch', callId: 'malformed-ack', + action: { action: 'acknowledge_report', requestId: 'malformed', reportRequestId: 'unknown-report', finalText: '' } })); + const sentBefore = f.feishu.sent.length; + f.codex.complete(group.threadId, 'Legitimate final.'); await f.loop.tick(); + assert.equal(f.feishu.sent.slice(sentBefore).filter(item => item.chatId === group.chatId && item.text === 'Legitimate final.').length, 1); +}); + +test('report acknowledgement cannot move to a later turn after a report receipt write failure', async t => { + const f = await fixture(t); await f.initialize(); + const worker = await f.dispatch('lost-report-receipt', 'Discuss the contract.'); + const group = await f.openGroup(worker.id); assert.ok(group.chatId && group.threadId && group.turnId); + const report: ProjectAction = { action: 'report', requestId: 'lost-bound-report', kind: 'update', routing: 'intermediate', text: 'Original turn report.' }; + t.mock.method(f.loop.projects.ledger, 'saveReceipt', () => { throw new Error('Lost report receipt'); }, { times: 1 }); + await assert.rejects(f.invoke(worker.id, report), /Lost report receipt/); + assert.equal(f.loop.store.outputForKey(worker.id, `worker-report:${report.requestId}`)?.status, 'pending'); + f.codex.complete(group.threadId, null); await f.loop.tick(); + await f.loop.receive(f.message('later-turn-input', 'Continue with a new answer.', group.chatId)); + await f.loop.tick(); await f.restart(); + assert.notEqual(f.codex.snapshot(group.threadId).turnId, group.turnId); + await f.invoke(worker.id, report); + await assert.rejects(f.invoke(worker.id, { action: 'acknowledge_report', requestId: 'later-ack', reportRequestId: report.requestId, finalText: 'Later legitimate answer.' }), /turn/); + f.codex.complete(group.threadId, 'Later legitimate answer.'); await f.loop.tick(); + assert.equal(f.feishu.sent.filter(item => item.chatId === group.chatId && item.text === report.text).length, 1); + assert.equal(f.feishu.sent.filter(item => item.chatId === group.chatId && item.text === 'Later legitimate answer.').length, 1); +}); + +test('failed acknowledgement receipt is atomic and leaves an unacknowledged final visible', async t => { + const f = await fixture(t); await f.initialize(); + const worker = await f.dispatch('lost-ack-receipt', 'Discuss the contract.'); + const group = await f.openGroup(worker.id); assert.ok(group.chatId && group.threadId); + await f.invoke(worker.id, { action: 'report', requestId: 'ack-rollback-report', kind: 'update', routing: 'intermediate', text: 'Report before failed acknowledgement.' }); + t.mock.method(f.loop.projects.ledger, 'saveReceipt', () => { throw new Error('Lost acknowledgement receipt'); }, { times: 1 }); + await assert.rejects(f.invoke(worker.id, { action: 'acknowledge_report', requestId: 'ack-rollback', reportRequestId: 'ack-rollback-report', finalText: 'Final after failed acknowledgement.' }), /Lost acknowledgement receipt/); + await f.restart(); f.codex.complete(group.threadId, 'Final after failed acknowledgement.'); await f.loop.tick(); + assert.equal(f.feishu.sent.filter(item => item.chatId === group.chatId && item.text === 'Final after failed acknowledgement.').length, 1); +}); + +test('unacknowledged paraphrases remain separate messages', async t => { + const f = await fixture(t); await f.initialize(); + const worker = await f.dispatch('unack-report', 'Discuss the assigned contract.'); + const group = await f.openGroup(worker.id); assert.ok(group.chatId && group.threadId); + const sentBefore = f.feishu.sent.length; + await f.loop.projectAction(worker.id, { action: 'report', requestId: 'separate-answer', kind: 'question', routing: 'intermediate', text: 'Keep existing Workers on their original model?' }); + f.codex.complete(group.threadId, 'New information. Existing Workers now retain their original model.'); + await f.loop.tick(); + assert.equal(f.feishu.sent.slice(sentBefore).filter(item => item.chatId === group.chatId).length, 2); +}); + +test('an uncertain report delivery leaves its explicitly acknowledged final deliverable', async t => { + const f = await fixture(t); await f.initialize(); + const worker = await f.dispatch('uncertain-report', 'Discuss the contract.'); + const group = await f.openGroup(worker.id); assert.ok(group.chatId && group.threadId); + const originalSend = f.feishu.send.bind(f.feishu); + let failed = true; + f.feishu.send = async input => { if (failed && input.text === 'Report whose transport failed.') { failed = false; throw new Error('transport failed'); } await originalSend(input); }; + await f.invoke(worker.id, { action: 'report', requestId: 'uncertain-report-action', kind: 'update', routing: 'intermediate', text: 'Report whose transport failed.' }); + await f.loop.tick(); + assert.equal(f.loop.store.outputForKey(worker.id, 'worker-report:uncertain-report-action')?.status, 'uncertain'); + await f.invoke(worker.id, { action: 'acknowledge_report', requestId: 'uncertain-report-ack', reportRequestId: 'uncertain-report-action', finalText: 'Final remains deliverable.' }); + f.codex.complete(group.threadId, 'Final remains deliverable.'); await f.loop.tick(); + assert.equal(f.feishu.sent.filter(item => item.chatId === group.chatId && item.text === 'Final remains deliverable.').length, 1); +}); + 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.');