diff --git a/.scratch/worker-execution-identity-v11/spec.md b/.scratch/worker-execution-identity-v11/spec.md new file mode 100644 index 0000000..1051945 --- /dev/null +++ b/.scratch/worker-execution-identity-v11/spec.md @@ -0,0 +1,73 @@ +Status: ready-for-agent + +# Worker execution identity + +Version: v1.2 + +## Problem Statement + +Agent Loop currently reads the shared worker execution profile whenever it creates, resumes, or observes a Worker Thread. A configuration reload can therefore change an existing Worker’s model or reasoning effort. Removing a profile can also make a historical Worker inherit a different profile or fail without preserving the original choice. + +## Solution + +At Worker creation, the coordinator selects one complete model and reasoning-effort pair from the configured Worker allowlist. Agent Loop stores that selection with the Worker task and uses the stored identity for every later turn, observation, pause recovery, and service restart. Configuration changes affect only Workers created after the change. If a historical Worker has no reliable saved original identity, Agent Loop stops before choosing a replacement and reports the ambiguity for coordination. + +## User Stories + +1. As a project coordinator, I want to select a Worker model and reasoning effort from configured complete pairs, so that each Worker starts with an intentional execution identity. +2. As a project coordinator, I want different Workers to use different allowed pairs, so that the selected capability matches each assignment. +3. As a project coordinator, I want an unavailable pair to be rejected at Worker creation, so that no model and effort combination outside the allowlist can run. +4. As a project coordinator, I want a model and effort to be validated as one pair, so that Agent Loop never crosses a model from one entry with an effort from another entry. +5. As a Worker, I want my selected identity saved with my task, so that later turns use the same model and reasoning effort. +6. As a Worker, I want follow-up messages to use my original identity, so that conversation behavior does not change after configuration reload. +7. As a Worker, I want pause and resume to retain my identity, so that recovery does not silently switch execution capability. +8. As an operator, I want a service restart to restore each Worker’s saved identity, so that restart recovery preserves task behavior. +9. As an operator, I want changing the allowlist to affect only new Workers, so that existing work remains stable. +10. As an operator, I want deleting an allowed pair to leave existing Workers usable with their saved identity, so that configuration cleanup does not rewrite history. +11. As a coordinator, I want the coordinator’s own execution profile to keep using the coordinator configuration, so that Worker selection does not expand or alter coordinator model behavior. +12. As a coordinator, I want historical Workers to use their recorded original identity when reliable provenance exists, so that migration preserves the actual prior choice. +13. As a coordinator, I want an ambiguous historical identity to be surfaced as a blocker, so that the system never guesses from the current instance default. +14. As an operator, I want a failed model call to retain its selected identity, so that retry behavior does not become an unannounced model fallback. +15. As a reviewer, I want the persisted identity to be visible in task state and test fixtures, so that restart and legacy behavior can be audited. + +## Implementation Decisions + +- Define the Worker execution identity as one validated execution profile containing the backend, model, and reasoning effort. Treat the model and reasoning effort as an inseparable pair. +- Store the Worker allowlist as a single nonempty list of complete execution profiles. Accept the previous single-profile input as a one-entry list at configuration loading. Validate a dispatch selection against an allowlist entry by structural equality, including backend, model, and reasoning effort. +- Extend Worker dispatch input so the coordinator supplies the selected complete profile. Reject a missing or non-allowlisted selection instead of synthesizing a profile from separate model and effort values. +- Persist the selected profile in the task snapshot at the point the task becomes a Worker execution. Keep it across turns, pause, resume, restart, provider migration, and configuration reload. +- Resolve execution for a Worker from its persisted task identity. Resolve execution for a coordinator from the current coordinator role profile. Do not apply Worker snapshots to coordinator tasks. +- Preserve an existing task’s saved identity even when the current allowlist changes or no longer contains that entry. The allowlist constrains creation, not historical execution. +- Inspect durable task state and any reliable existing execution identity before resuming a historical Worker. Use only the complete, valid legacy task-scoped model and effort metadata as a historical original-value source, and persist the source keys. If no reliable original value exists, preserve task, group, Thread, native approvals, operator pause and held inputs, and report one execution-identity blocker before any execution. Never substitute the current Worker profile. +- Keep the dispatch and execution identity validation at the project execution boundary. The loop passes the resulting profile to the Codex port and does not reselect it. +- Base the model feature directly on current main `3260549ec6b42b27fd62373b7b25dc391119ae0e`. Preserve its report, native request, capability, and Worker group message behavior. The cancelled single-config feature is not a dependency. + +## Testing Decisions + +- Test observable execution behavior. Assert the profile sent to Thread creation, resume, observation, and new turns rather than private maps or helper calls. +- Test dispatch validation for an allowed pair, a crossed pair, a missing selection, and a pair removed from the current allowlist after creation. +- Test task persistence by constructing a Worker, reloading the store, and continuing the Worker with changed configuration. The Codex port must receive the saved profile. +- Test pause and resume, provider restart recovery, and multiple turns with the same saved profile. +- Test historical tasks with reliable saved provenance and tasks without reliable provenance. The first resumes with its recorded identity; the second reports a blocker and never uses the current default. +- Reuse existing project dispatch, project Codex, execution configuration, and runtime recovery fixtures. Add no test that asserts private implementation structure. + +## Out of Scope + +- Runtime model switching, per-turn reselection, manual Worker profile editing, or automatic model fallback. +- New backend support, dashboard changes, coordinator model selection changes, or a separate verifier role. +- Credential storage, credential redaction, and the cancelled single-config migration. +- Deployment, service restart, live database edits, merge, or changes to unrelated task worktrees. + +## Further Notes + +- The product decisions in worker execution requirements v1.0 and v1.1 establish creation-time selection, immutable existing Worker identity, and historical preservation. Technical field names and persistence details remain implementation choices. +- The implementation must report the exact main base and resulting PR head. Independent verification is arranged by the coordinator. + + +## Authorization and sources + +The retained v1.0 requirements have SHA256 `f645ade92f2335c37e4b7d1c6ba718876be54cf36b432acf875e8d772775b90d`. Their U1, U2, and U3 source identifiers remain authoritative for the product rules. v1.1 adds the following supplied owner message: `om_x100b60caf31598a4de137711674c7e7`, chat `oc_586b1866902382e0db4dff8d25c0f3f7`, sender `ou_5c280b16780ac4016c7455a276b2d95b`: "历史worker继续沿用原来它本身的模型和推理强度. 先让worker调用to-spec形成文档然后使用poteto-mode进行开发." + +The coordinator confirmed the historical fail-closed boundary in task `c9edaf14-f18a-42de-841e-d963e1f520cc`, event `worker-model-historical-fail-closed-v1`: complete legacy keys restore with source; missing, partial, or unreliable provenance preserves task state and emits one blocker without execution or defaults. This is a sourced coordinator instruction within the implementation grant, not a native approval or deployment authorization. + +The coordinator relayed owner cancellation of PR63 in event `model-pr63-cancelled-rebase-v1`. Version v1.2 removes that dependency and rebases only the authorized model feature onto main `3260549ec6b42b27fd62373b7b25dc391119ae0e`. Existing environment credential loading remains the main contract. This is a technical base revision; the v1.1 product and implementation authorization remains unchanged. All verification must be refreshed on this base. diff --git a/GLOSSARY.md b/GLOSSARY.md index b74138c..9d28923 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -21,7 +21,10 @@ _Avoid_:将接收请求等同于已委派执行。 **执行后端(Execution Backend)**:实际运行执行角色任务的执行层,例如 Codex、dsh 或 Claude Code。执行后端与模型名称是两个概念,角色可以选择后端及其模型参数。 -**角色执行配置(Role Execution Configuration)**:为每个执行角色指定执行后端、模型和推理强度的共同配置。所有协调项目使用同一套角色执行配置。 +**角色执行配置(Role Execution Configuration)**:为项目协调者指定执行后端、模型和推理强度,并为 Worker 列出允许组合的共同配置。所有协调项目使用同一套角色执行配置。 + +**Worker 执行身份(Worker Execution Identity)**:同一 Worker 在创建时选定的完整执行后端、模型和推理强度,连同其可追溯来源。后续对话、配置变化、暂停恢复和服务重启保留该身份。 +_Avoid_:把当前实例配置当作历史 Worker 的原选择,或把新一轮回复当作重新选择身份。 **工作汇报(Work Report)**:执行者明确向项目协调者提交的工作问题、进展或成果。 _Avoid_:将一次普通回复结束等同于工作汇报。 diff --git a/README.md b/README.md index 82a14cc..0a48c71 100644 --- a/README.md +++ b/README.md @@ -33,9 +33,9 @@ cp config/example.json config.json 正式任务共用本机 Codex daemon。Agent Loop 通过官方 `daemon version` 发现服务,只在服务未运行时调用 `daemon start`。连接失败会报告错误,断线后重新连接并核对原 Thread。Agent Loop 不停止、重启或更新 daemon,也不回退私有 App Server。 -在 `execution.backends` 配置执行后端连接参数,在角色配置中填写 `backend`、`model` 和 `reasoningEffort`。当前提供 Codex 后端,未来可以增加其他执行后端。模型配置属于 Agent Loop 运行时,不修改后端的全局配置;配置文件变化由运行时 watcher 读取,下一次模型调用生效。 +在 `execution.backends` 配置执行后端连接参数。`execution.coordinator` 填写一个完整执行配置,`execution.worker` 列出允许的完整 `backend`、`model`、`reasoningEffort` 组合。当前提供 Codex 后端,未来可以增加其他执行后端。模型配置属于 Agent Loop 运行时,不修改后端的全局配置;配置文件变化由运行时 watcher 读取。协调者在下次调用使用新配置;Worker 只在创建时从允许列表选定一次。多轮对话、暂停恢复和服务重启始终沿用任务保存的选择,删除允许项也不改变已有 Worker。旧的单个 Worker 配置仍作为只含一项的允许列表加载。 -Agent Loop 不再使用模型选择目录。任务必须先归属到已配置项目;未归属 intake 和历史任务保持等待,不创建执行 Thread。项目协调者和 Worker 直接使用项目目录及统一的角色执行配置。 +Agent Loop 不再使用模型选择目录。任务必须先归属到已配置项目;未归属 intake 和历史任务保持等待,不创建执行 Thread。项目协调者和 Worker 直接使用项目目录。协调者从当前配置读取执行参数,Worker 使用自身保存的执行身份。 本地项目可使用 `repositories: []`,不需要 GitHub token。正式会话按角色读取 `prompts/coordinator.md` 或 `prompts/worker.md`,`engineering.promptPath` 不覆盖角色规则。角色指导、委派范围和环境信息通过 `developerInstructions` 与 `additionalContext` 传入正式 Thread;用户消息和 Issue 内容作为请求材料。`engineering.skillPath` 指向已安装的 poteto-mode,其他技能通过现有机制发现。加载与更新方式见[正式会话提示词](docs/prompts/task.md)。 diff --git a/config/example.json b/config/example.json index 0a54448..5745cc1 100644 --- a/config/example.json +++ b/config/example.json @@ -49,11 +49,13 @@ "model": "gpt-6-astra", "reasoningEffort": "high" }, - "worker": { - "backend": "codex", - "model": "gpt-6.1-sol", - "reasoningEffort": "xhigh" - }, + "worker": [ + { + "backend": "codex", + "model": "gpt-6.1-sol", + "reasoningEffort": "xhigh" + } + ], "backends": { "codex": { "executable": "codex", diff --git a/docs/adr/0017-configurable-execution-roles.md b/docs/adr/0017-configurable-execution-roles.md index dd9f26b..94c7e7a 100644 --- a/docs/adr/0017-configurable-execution-roles.md +++ b/docs/adr/0017-configurable-execution-roles.md @@ -21,7 +21,7 @@ Agent Loop 的执行配置由实例统一提供,所有协调项目使用同一 工程归属不再由模型选择。已经明确项目的协调者和 Worker 直接使用项目归属;没有项目归属的 intake 或 legacy Task 保持 pending,不创建执行 Thread,直到协调者完成 `claim_intake` 或 `dispatch`。没有角色的历史 Task 不能回退到通用模型;已有项目成员关系的 Task 保留其 coordinator 或 worker 角色。 -运行时监听配置文件。有效变更在当前轮次结束后、下一次创建、恢复或开始调用时生效;正在执行的轮次不被中断。无效变更保留最后一份有效配置并记录诊断,文件修复后自动恢复。任务只保存角色,不把模型或推理强度快照作为运行时来源,因此已有 Task 也会在下一次调用使用新配置。 +运行时监听配置文件。有效变更在当前轮次结束后、下一次创建、恢复或开始调用时生效;正在执行的轮次不被中断。无效变更保留最后一份有效配置并记录诊断,文件修复后自动恢复。此处原定所有任务在下次调用使用新配置。Worker 的该规则现由 [ADR 0023](0023-worker-execution-identities.md) 取代:创建时选择完整允许配对,保存身份并在后续调用持续使用。协调者仍按当前角色配置执行。 旧项目级模型字段严格拒绝,要求迁移到统一的 `execution` 配置。配置与角色绑定属于实例级契约,不随单个项目或单个任务重复维护。 diff --git a/docs/adr/0023-worker-execution-identities.md b/docs/adr/0023-worker-execution-identities.md new file mode 100644 index 0000000..2f75751 --- /dev/null +++ b/docs/adr/0023-worker-execution-identities.md @@ -0,0 +1,13 @@ +--- +status: accepted +--- + +# Worker 在创建时固定执行身份 + +用户要求协调者依据创建时的相关对话,从配置允许的完整模型与推理强度配对中选择一次。Worker 任务的持续上下文跨越多轮、暂停恢复和服务重启,因此把完整执行配置与来源保存在任务中。修改或删除允许项只限制新 Worker;已有身份不可改写。协调者继续使用当前角色配置。 + +`execution.worker` 使用非空的完整 profile 列表。旧单 profile 作为只含一项的允许列表加载。dispatch 必须显式选择完整 `execution`,保存该选择与来源。按两个独立列表交叉生成配对、逐轮重新选择、运行中修改和静默回退均违反该约定。 + +旧版 dispatch 曾在同一事务保存 `project-task-model:` 与 `project-task-effort:`,当时唯一后端为 Codex。只有这两个键提供完整有效值时才恢复旧身份,来源保留键名。缺失或无可靠证据时,Runtime 保留任务、Thread、群、原生审批、operator-paused 状态和 held 输入,向协调者发送一次执行身份阻塞事件并停止该 Worker 的执行。当前角色配置和 Thread 的当前或最近设置都不能证明原选择。 + +该决策取代 ADR 0017 对 Worker 后续使用热更新配置的规定。它不增加协调者模型选择、执行后端、看板控制、手工改模型或自动模型回退。 diff --git a/docs/project-coordinator.md b/docs/project-coordinator.md index b7f3f67..503d2c9 100644 --- a/docs/project-coordinator.md +++ b/docs/project-coordinator.md @@ -16,7 +16,7 @@ Worker 默认不建群;用户需要直接交流时,由协调者打开指定 { "execution": { "coordinator": {"backend": "codex", "model": "gpt-6-astra", "reasoningEffort": "high"}, - "worker": {"backend": "codex", "model": "gpt-6.1-sol", "reasoningEffort": "xhigh"}, + "worker": [{"backend": "codex", "model": "gpt-6.1-sol", "reasoningEffort": "xhigh"}], "backends": {"codex": {"executable": "codex", "approvalPolicy": "on-request", "sandbox": "workspace-write", "requestTimeoutMs": 120000}} }, "projects": [ @@ -42,9 +42,11 @@ Worker 默认不建群;用户需要直接交流时,由协调者打开指定 配置在启动时加载。启用实际配置前,按[本机服务操作](agents/operations.md)执行切换并核对。源码测试不代表正式实例已经启用。 -协调者和 Worker 使用实例级 `execution` 配置。配置为每个角色指定执行后端、模型和推理强度,所有协调项目共用同一套值。Agent Loop 不提供 验证角色,独立验证由 pstack 负责。执行配置变化由 watcher 读取,已有任务在下一次调用使用新配置。 +协调者和 Worker 使用实例级 `execution` 配置。`execution.coordinator` 指定协调者配置,`execution.worker` 是非空的完整配对允许列表,所有项目共用该配置。旧单配置可加载为只含一项的允许列表。Agent Loop 不提供 验证角色,独立验证由 pstack 负责。执行配置变化由 watcher 读取,协调者在下一次调用使用新配置;Worker 创建后固定使用保存值。 -模型名必须能由本机 Codex 解析。Runtime 不按名称猜测模型家族,也不默默更换不可用模型。任务只保存 coordinator 或 worker 角色;恢复和下一次调用按当前配置解析模型与推理强度。既有任务按保存的项目身份恢复。 +模型名必须能由本机 Codex 解析。Runtime 不按名称猜测模型家族,也不默默更换不可用模型。Worker 任务在创建或接管 intake 时保存完整 `workerExecution` 身份与派单来源。后续多轮、暂停恢复、provider 迁移和服务重启均沿用保存值。允许列表变化或删除仅限制新 Worker。`status` 的 `workerExecutionProfiles` 与协调者每轮上下文提供当前候选。派单必须显式携带完整 `execution`,即使允许列表只有一项。 + +历史 Worker 只从完整有效的 `project-task-model:` 与 `project-task-effort:` 恢复原配对,身份来源保留这两个键。缺失、半项或非法值会生成一次协调者执行身份阻塞事件,保留群、Thread、原生审批、暂停状态及 held 输入。Runtime 不执行该 Worker,也不使用当前默认补值。Thread 当前设置不能证明历史原选择。 ## 对话与角色指导 @@ -52,7 +54,7 @@ Runtime 为项目建立一个协调 Task 及项目群。协调者使用 `prompts GitHub 和历史接单记录保留原文、来源和附件,不自动创建执行 Thread、工作区或任务群。项目不明确时保留问题和现场,不回退到无项目执行。 -协调者派单携带目标、背景、范围、禁止动作、验收及交付要求。接单请求通过 `dispatch` 的 `intakeTaskId` 原地转为 Worker,保留请求身份、原文、附件和范围回答。项目群直接交办的子任务仍可使用普通 `dispatch`。共享项目入口本身不是隔离工作树。 +协调者派单携带目标、背景、范围、禁止动作、验收及交付要求,并根据创建时的相关对话选择一个允许的完整 `execution` 配置。接单请求通过 `dispatch` 的 `intakeTaskId` 原地转为 Worker,保留请求身份、原文、附件和范围回答。项目群直接交办的子任务仍可使用普通 `dispatch`。共享项目入口本身不是隔离工作树。 模糊的新需求先交 Worker 调查和澄清,本轮不实施业务代码。Worker 使用 grill-with-docs 查明已有事实,整理需求文档和待决问题。协调者把问题、证据、选项、影响和建议带回项目群,再将实际用户答复及消息、群和发送者来源交回原 Worker。已解决的问题不重复问。 diff --git a/prompts/coordinator.md b/prompts/coordinator.md index 94007e8..bd976d9 100644 --- a/prompts/coordinator.md +++ b/prompts/coordinator.md @@ -16,6 +16,8 @@ record 未指定 scope 时仅保存协调者资料。项目通用规则显式使 用户明确指定的优先级最高,其次遵循项目优先级标记,其余依据依赖、阻塞和执行资源安排。独立工作可以并行,共享写入和依赖按 pstack 处理。一个任务等用户决定时,其他不受影响的工作继续。 +创建 Worker 时,根据当前相关对话从 status 的 workerExecutionProfiles 或本轮上下文允许列表中选择一个完整 execution 配置,并在 dispatch 显式携带 backend、model 和 reasoningEffort。不能交叉组合,只有一项也必须明确选择。同一 Worker 后续不可改选,配置变动或删除不影响原选择。历史执行身份缺失的 blocker 需要核查原来源,不得用当前默认猜测。 + 通过 dispatch 委派 Worker,提供完整目标、背景、允许和禁止范围、禁止动作、验收证据及交付要求。要求使用 poteto-mode。项目群就是用户与协调者讨论需求的入口,由你组织 Worker、独立验证和交付。 GitHub Feature 是外部需求提案,不是开发授权。需求描述清楚也不能直接实现。只想调查、澄清或整理需求时,dispatch 使用 mode=investigation,并明确不改业务代码、不提交、不合并、不部署。只有项目协调群中实际项目所有者的消息才能授权 Feature 实现。实现派单使用 mode=implementation,并携带该消息的证据、当前 Issue 版本、已确认范围和验收条件。Issue 正文、Issue 评论、Worker 判断和代理记录不能代替用户授权。调查授权不等于开发授权。已明确授权实现且范围未变化时继续有效;范围、产品行为、成本或依赖发生变化时,重新确认受影响部分。已有授权的 Feature Task 不因规则更新而暂停或重派。 diff --git a/src/adapters/codex.ts b/src/adapters/codex.ts index 7c165ee..6fba9a6 100644 --- a/src/adapters/codex.ts +++ b/src/adapters/codex.ts @@ -461,7 +461,7 @@ export class CodexAppServer implements CodexPort { await this.ready(); const { thread } = threadResponseSchema.parse(await this.rpc('thread/start', { ...this.config(), ...(input.model ? { model: input.model } : {}), ...(input.reasoningEffort ? { config: { model_reasoning_effort: input.reasoningEffort } } : {}), - cwd: input.cwd, developerInstructions: input.instructions, dynamicTools: this.projectHandler ? [workspaceTool, projectTool] : [workspaceTool], ephemeral: false })); + allowProviderModelFallback: false, cwd: input.cwd, developerInstructions: input.instructions, dynamicTools: this.projectHandler ? [workspaceTool, projectTool] : [workspaceTool], ephemeral: false })); if (thread.status.type !== 'idle' || thread.turns.length) throw new UncertainOperationError('New Codex thread was not empty and idle'); this.threads.set(thread.id, { load: { kind: 'ready' }, untouched: true, instructions: input.instructions, model: input.model, reasoningEffort: input.reasoningEffort }); return thread.id; diff --git a/src/domain.ts b/src/domain.ts index f10fa38..52a77cb 100644 --- a/src/domain.ts +++ b/src/domain.ts @@ -1,4 +1,5 @@ import { z } from 'zod'; +import { workerExecutionIdentitySchema } from './execution.js'; export const criteriaSchema = z.object({ states: z.array(z.enum(['open', 'closed'])).default(['open']), @@ -149,6 +150,7 @@ export const taskSchema = z.object({ status: z.enum(['pending', 'running', 'idle', 'paused', 'failed']), reason: z.string().nullable(), prompt: z.string(), promptHash: z.string(), skillPath: z.string().nullable(), chatId: z.string().nullable(), threadId: z.string().nullable(), turnId: z.string().nullable(), + workerExecution: workerExecutionIdentitySchema.optional(), executionStatus: z.enum(['unbound', 'idle', 'running', 'completed', 'interrupted', 'failed', 'unknown']).default('unbound'), lastHandledTurnId: z.string().nullable(), requests: z.array(requestSchema), recovery: recoverySchema.default({ attempts: 0, nextAttemptAt: null, lastError: null, interruptedTurnId: null, lastUserInputSeq: null }), diff --git a/src/execution.ts b/src/execution.ts index 43ae5ad..7e838e3 100644 --- a/src/execution.ts +++ b/src/execution.ts @@ -13,17 +13,49 @@ export const executionProfileSchema = z.strictObject({ }); export type ExecutionProfile = z.infer; +export const workerExecutionIdentitySchema = z.strictObject({ + profile: executionProfileSchema, + source: z.discriminatedUnion('kind', [ + z.strictObject({ kind: z.literal('dispatch'), coordinatorTaskId: z.string().min(1), requestId: z.string().min(1) }), + z.strictObject({ kind: z.literal('legacy-task-metadata'), modelKey: z.string().min(1), effortKey: z.string().min(1) }), + ]), +}); +export type WorkerExecutionIdentity = z.infer; + +export const workerExecutionProfilesSchema = z.array(executionProfileSchema).min(1) + .superRefine((profiles, context) => { + const seen = new Set(); + for (const [index, profile] of profiles.entries()) { + const identity = JSON.stringify(profile); + if (seen.has(identity)) context.addIssue({ code: 'custom', path: [index], message: 'Worker execution profiles must be unique' }); + seen.add(identity); + } + }); +export type WorkerExecutionProfiles = z.infer; + +export function sameExecutionProfile(left: ExecutionProfile, right: ExecutionProfile): boolean { + return left.backend === right.backend && left.model === right.model && left.reasoningEffort === right.reasoningEffort; +} + +export class HistoricalExecutionIdentityError extends Error { + constructor(taskId: string) { + super(`Historical Worker ${taskId} has no reliable saved execution identity; coordinator review is required before resume`); + } +} + export const executionConfigSchema = z.strictObject({ coordinator: executionProfileSchema, - worker: executionProfileSchema, + worker: z.union([executionProfileSchema, workerExecutionProfilesSchema]).transform(value => Array.isArray(value) ? value : [value]), }); export type ExecutionConfig = z.infer; export const supportedExecutionBackends = ['codex'] as const; export function assertSupportedExecutionBackends(config: ExecutionConfig): void { - for (const role of ['coordinator', 'worker'] as const) { - const profile = config[role]; + for (const [role, profile] of [ + ['coordinator', config.coordinator] as const, + ...config.worker.map((candidate, index) => [`worker[${index}]`, candidate] as const), + ]) { if (!(supportedExecutionBackends as readonly string[]).includes(profile.backend)) { throw new Error(`Unsupported execution backend for ${role}: ${profile.backend}`); } diff --git a/src/loop.ts b/src/loop.ts index 6ec18aa..ae435a4 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -20,6 +20,7 @@ import { GroupCleanup } from './group-cleanup.js'; import { Store, type Inbox } from './store.js'; import { FeishuProgressPublisher } from './feishu-progress.js'; import { FeishuDocumentProgressPublisher } from './feishu-document-progress.js'; +import { HistoricalExecutionIdentityError } from './execution.js'; import { IntakeOwnershipChanged, intakeMaterialVersion, ProjectRuntime } from './project-runtime.js'; import type { ProjectAction, ProjectConfig } from './project.js'; import { matchesProjectIssue } from './project.js'; @@ -168,7 +169,9 @@ export class AgentLoop { const task = this.store.task(taskId); this.requireMember(task); if (this.closeout.completed(taskId) || this.stopping || ['paused', 'failed'].includes(task.status) || !task.threadId) throw new Error('Capability requires an active conversation'); - const activity = await this.ports.codex.activity(task.threadId); + if (!this.projects.restoreWorkerExecution(task)) throw new HistoricalExecutionIdentityError(task.id); + const profile = this.executionProfile(task); + const activity = await this.ports.codex.activity(task.threadId, undefined, profile.model, profile.reasoningEffort); if (activity.kind !== 'running') throw new Error('Capability requires a proven active turn'); return activity; } @@ -415,21 +418,27 @@ export class AgentLoop { const release = this.closeout.reserve(taskId); try { return await run(); } finally { release(); } } + private executionProfile(task: Task) { + const profile = this.projects.executionProfile(task.id); + if (profile) return profile; + if (this.projects.ledger.membership(task.id)?.role === 'worker') throw new HistoricalExecutionIdentityError(task.id); + throw new Error('Task has no execution role'); + } private async inspect(threadId: string): Promise { const task = this.store.taskForThread(threadId); if (!task) throw new Error('Unbound Thread'); const instructions = await this.instructions(task); this.closeout.assertOpen(task.id); - const profile = this.projects.executionProfile(task.id); - const snapshot = await this.admitted(task.id, () => this.ports.codex.inspect(threadId, instructions, profile?.model, profile?.reasoningEffort)); + const profile = this.executionProfile(task); + const snapshot = await this.admitted(task.id, () => this.ports.codex.inspect(threadId, instructions, profile.model, profile.reasoningEffort)); return snapshot; } private async observation(task: Task, reconcile = false): Promise { if (!task.threadId) throw new Error('Unbound Thread'); if (!reconcile && task.executionStatus === 'running' && !this.hasUnknownInput(task) && !this.store.approvals(task.id).some(approval => approval.status === 'processing' || approval.status === 'uncertain')) { - const profile = this.projects.executionProfile(task.id); - const activity = await this.ports.codex.activity(task.threadId, await this.instructions(task), profile?.model, profile?.reasoningEffort); + const profile = this.executionProfile(task); + const activity = await this.ports.codex.activity(task.threadId, await this.instructions(task), profile.model, profile.reasoningEffort); if (activity.kind === 'running') { return activity; } @@ -611,8 +620,10 @@ export class AgentLoop { return false; } if (task.threadId) { - for (const resource of task.resources) await this.restoreWorkspace(task.id, resource); await this.projects.adopt(task.id, project.id); + task = this.store.task(task.id); + if (!this.projects.restoreWorkerExecution(task)) return false; + for (const resource of task.resources) await this.restoreWorkspace(task.id, resource); return true; } const materials = await this.intakeMaterials(task); @@ -657,9 +668,8 @@ export class AgentLoop { task = this.store.task(task.id); const generation = this.store.meta(`project-generation:${task.id}`); this.closeout.assertOpen(task.id); + const profile = this.executionProfile(task); const releaseAdmission = this.closeout.reserve(task.id); - const profile = this.projects.executionProfile(task.id); - if (!profile) throw new Error('Task has no execution role'); try { task.threadId = await this.effect(task, generation ? `thread:${generation}` : 'thread', false, () => this.ports.codex.createThread({ cwd: this.executionDirectory(task), instructions, model: profile.model, reasoningEffort: profile.reasoningEffort })); this.persist(task); } finally { releaseAdmission(); } } @@ -774,6 +784,7 @@ export class AgentLoop { } private async migratePausedProvider(task: Task, forceProbe = false): Promise { if (task.status !== 'paused' || !task.threadId) return 'not-needed'; + if (!this.projects.restoreWorkerExecution(task)) return 'deferred'; const probeKey = `provider-migration-probed:${task.id}`; if (!forceProbe && this.store.meta(probeKey)) return 'not-needed'; this.store.setMeta(probeKey, String(Date.now())); @@ -852,6 +863,7 @@ export class AgentLoop { task = this.store.task(id); } this.requireMember(task); + if (!this.projects.restoreWorkerExecution(task)) return; if (task.purpose !== 'execution') { task.purpose = 'execution'; this.persist(task); } if (task.status === 'failed' && this.store.inputs(task.id, { statuses: ['pending'], origin: 'user' }).some(input => (task.recovery.lastUserInputSeq === null ? input.message.createdAt > task.updatedAt : input.seq > task.recovery.lastUserInputSeq))) { @@ -1228,6 +1240,7 @@ export class AgentLoop { private async pause(task: Task, reason: string): Promise { task.status = 'paused'; task.reason = reason; task.recovery.nextAttemptAt = null; this.persist(task); if (task.threadId) { + if (!this.projects.restoreWorkerExecution(task)) return; const snapshot = this.projects.ledger.membership(task.id) ? await this.inspect(task.threadId) : await this.ports.codex.inspect(task.threadId); if (snapshot.status === 'running' && snapshot.turnId) { @@ -1242,8 +1255,12 @@ export class AgentLoop { const task = this.store.task(taskId); this.projects.retireObsoleteInputs(task); if (action === 'pause') await this.pause(task, 'Operator paused'); - else if (action === 'status') this.notify(task, `Task ${task.id}\n${task.status}\n${task.reason ?? ''}`, `status:${randomUUID()}`); + else if (action === 'status') { + this.notify(task, `Task ${task.id}\n${task.status}\n${task.reason ?? ''}`, `status:${randomUUID()}`); + await this.flush(task); return; + } else if (['paused', 'failed'].includes(task.status)) { + if (!this.projects.restoreWorkerExecution(task)) return; if (task.status === 'paused') { const migration = await this.migratePausedProvider(task, true); if (migration === 'deferred') { await this.flush(this.store.task(taskId)); return; } @@ -1257,6 +1274,7 @@ export class AgentLoop { }); } private async flush(task: Task): Promise { + if (this.projects.ledger.membership(task.id)?.role === 'worker' && !task.workerExecution) return; for (const output of this.store.outputs(task.id, ['pending', 'sending', 'uncertain'])) { const approval = this.store.meta(`approval-output:${output.id}`); const native = approval ? approvalOutputSchema.parse(JSON.parse(approval)) : null; @@ -1324,7 +1342,7 @@ export class AgentLoop { await Promise.all(tasks.map(task => this.serial(task.id, async () => { try { if (this.closeout.completed(task.id)) { this.forwardCompletedInputs(task); await this.flush(task); return; } - for (const resource of task.resources) await this.restoreWorkspace(task.id, resource); + if (!this.projects.restoreWorkerExecution(task)) return; if (!this.projects.ledger.membership(task.id)) { const project = await this.projects.resolveTask(task); if (project && task.threadId) { @@ -1332,6 +1350,8 @@ export class AgentLoop { task = this.store.task(task.id); } } + if (!this.projects.restoreWorkerExecution(task)) return; + for (const resource of task.resources) await this.restoreWorkspace(task.id, resource); if (task.source.kind === 'github' && !this.projects.ledger.membership(task.id)) { try { const source = await this.ports.github.get(task.source.issue.repository, task.source.issue.number); @@ -1356,7 +1376,7 @@ export class AgentLoop { await this.backfill(); } private async backfillTask(task: Task): Promise { - if (!task.chatId) return; + if (!task.chatId || (this.projects.ledger.membership(task.id)?.role === 'worker' && !task.workerExecution)) return; const previous = Number(this.store.meta(`history:${task.id}`) ?? task.createdAt); const failureKey = `history-failure:${task.id}`; const failure = parseHistoryFailure(task.id, this.store.meta(failureKey)); diff --git a/src/project-runtime.ts b/src/project-runtime.ts index d404eea..2868a5d 100644 --- a/src/project-runtime.ts +++ b/src/project-runtime.ts @@ -5,7 +5,7 @@ import { z } from 'zod'; import type { Config } from './config.js'; 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 { executionProfileSchema, sameExecutionProfile, 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 { TaskCloseout } from './task-closeout.js'; @@ -101,7 +101,28 @@ export class ProjectRuntime { executionProfile(taskId: string): ExecutionProfile | null { const member = this.ledger.membership(taskId); if (!member) return null; - return this.settings.execution[member.role]; + if (member.role === 'coordinator') return this.settings.execution.coordinator; + return this.store.task(taskId).workerExecution?.profile ?? null; + } + restoreWorkerExecution(task: Task): boolean { + const member = this.ledger.membership(task.id); + if (member?.role !== 'worker' || task.workerExecution) return true; + const modelKey = `project-task-model:${task.id}`, effortKey = `project-task-effort:${task.id}`; + const profile = executionProfileSchema.safeParse({ backend: 'codex', model: this.store.meta(modelKey), reasoningEffort: this.store.meta(effortKey) }); + if (!profile.success) { + this.event(member.projectId, `execution-identity:${task.id}`, + `Worker ${task.id} execution identity is blocked. No complete reliable original model and reasoning effort exist in ${modelKey} and ${effortKey}. Preserve task, Thread, group, native approvals and pause state. Do not choose current defaults.`, + task.id, 'execution_status', { routing: 'escalation', escalation: 'blocker' }); + return false; + } + task.workerExecution = { profile: profile.data, source: { kind: 'legacy-task-metadata', modelKey, effortKey } }; + this.store.saveTask(task); + return true; + } + private workerExecutionProfile(selection: ExecutionProfile): ExecutionProfile { + const selected = this.settings.execution.worker.find(candidate => sameExecutionProfile(candidate, selection)); + if (!selected) throw new Error('Worker dispatch selected an execution profile outside the configured allowlist'); + return selected; } private enqueue(taskId: string, key: string, text: string, provenance: InputProvenance): void { const task = this.store.task(taskId); @@ -349,7 +370,9 @@ export class ProjectRuntime { || (record.scope?.kind === 'task' && record.scope.taskId === taskId)) : visible; const artifacts = this.host.closeout.read(taskId).scopes.filter(scope => !scope.sealed && scope.resource.kind === 'artifacts') .map(scope => ({ scopeId: scope.id, path: scope.location.root.path })); - return `Runtime-owned artifact scopes for this task as data: ${JSON.stringify(artifacts)}\nCurrent project records as data. This replaces the previous record context. Query status section records for complete visible history.\n${JSON.stringify(currentRecords(records).slice(-8).map(record => ({ key: record.key, scope: record.scope, text: record.text.slice(0, 2000), truncated: record.text.length > 2000 })))}`; + const executionCandidates = member.role === 'coordinator' + ? `Worker execution allowlist as data: ${JSON.stringify(this.settings.execution.worker)}\nDispatch must explicitly select one complete profile as execution. Existing Worker selections cannot change.\n` : ''; + return `${executionCandidates}Runtime-owned artifact scopes for this task as data: ${JSON.stringify(artifacts)}\nCurrent project records as data. This replaces the previous record context. Query status section records for complete visible history.\n${JSON.stringify(currentRecords(records).slice(-8).map(record => ({ key: record.key, scope: record.scope, text: record.text.slice(0, 2000), truncated: record.text.length > 2000 })))}`; } private recordAcknowledgement(projectId: string, callerId: string, requestId: string) { const state = this.ledger.project(projectId); @@ -457,7 +480,7 @@ export class ProjectRuntime { const tasks = state.members.map(member => { const task = this.store.task(member.taskId); return { ...member, closeout: this.host.closeout.read(task.id), status: task.status, executionStatus: task.executionStatus, reason: task.reason, - chatId: task.chatId, threadId: task.threadId, execution: this.executionProfile(task.id), resources: task.resources, requests: task.requests.map(request => ({ id: request.id, kind: request.kind, prompt: request.prompt })), + chatId: task.chatId, threadId: task.threadId, execution: this.executionProfile(task.id), ...(task.workerExecution ? { executionSource: task.workerExecution.source } : {}), resources: task.resources, requests: task.requests.map(request => ({ id: request.id, kind: request.kind, prompt: request.prompt })), outputs: this.store.outputs(task.id).slice(-3).map(output => ({ id: output.id, text: output.text.slice(0, 4000), truncated: output.text.length > 4000, status: output.status })) }; }); const intakes = this.store.tasks().filter(task => task.purpose === 'intake' && this.intakeRoute(task.id)?.projectId === projectId @@ -465,7 +488,7 @@ export class ProjectRuntime { .map(task => ({ taskId: task.id, source: presentTaskSource(task.source, 256), status: task.status, reason: task.reason, materialPath: this.store.meta(`project-intake-material:${task.id}`) })); const counts = { tasks: tasks.length, issues: state.issues.length, comments: state.comments.length, records: state.records.length, intakes: intakes.length }; - const identity = { id: state.id, name: state.name, directory: state.directory, coordinatorTaskId: state.coordinatorTaskId, version: state.version, counts }; + const identity = { ...(callerId === state.coordinatorTaskId ? { workerExecutionProfiles: this.settings.execution.worker } : {}), id: state.id, name: state.name, directory: state.directory, coordinatorTaskId: state.coordinatorTaskId, version: state.version, counts }; const page = (items: T[]) => ({ ...identity, section, offset, items: items.slice(offset, offset + limit), nextOffset: offset + limit < items.length ? offset + limit : null }); if (section === 'unassigned_intakes') return page(this.store.tasks().filter(task => this.visibleUnassigned(task, projectId)) @@ -593,7 +616,11 @@ export class ProjectRuntime { const feature = targetIssueId ? this.featureIssue(state, config, targetIssueId) : null; const investigation = action.mode === 'investigation'; const existingMember = targetIssueId ? state.members.find(candidate => candidate.issueId === targetIssueId && candidate.role === 'worker') : undefined; - if (existingMember) return { taskId: existingMember.taskId }; + if (existingMember) { + const original = this.store.task(existingMember.taskId).workerExecution; + if (!original || !sameExecutionProfile(original.profile, action.execution)) throw new Error('An existing Worker execution identity cannot change'); + return { taskId: existingMember.taskId }; + } const featureAuthorization = feature && action.role === 'worker' && !investigation ? this.featureAuthorization(state, config, feature, action) : null; const delegationPrompt = feature && investigation @@ -615,6 +642,7 @@ export class ProjectRuntime { if (task.status === 'paused') throw new Error('An operator-paused request must be resumed before delegation'); this.store.transaction(() => { task.purpose = 'execution'; + task.workerExecution = { profile: this.workerExecutionProfile(action.execution), source: { kind: 'dispatch', coordinatorTaskId: callerId, requestId: action.requestId } }; task.status = 'pending'; task.executionStatus = 'unbound'; task.reason = null; task.recovery = { attempts: 0, nextAttemptAt: null, lastError: null, interruptedTurnId: null, lastUserInputSeq: null }; this.store.saveTask(task); @@ -630,11 +658,14 @@ export class ProjectRuntime { const existing = this.store.taskForSource(sourceId); if (existing) { const saved = state.members.find(item => item.taskId === existing.id); - if (existing.source.kind !== 'cli' || existing.source.prompt !== action.prompt || saved?.role !== action.role || saved.issueId !== action.issueId) throw new Error('Dispatch conflicts with an accepted task'); + if (existing.source.kind !== 'cli' || existing.source.prompt !== action.prompt || saved?.role !== action.role || saved.issueId !== action.issueId + || !existing.workerExecution || !sameExecutionProfile(existing.workerExecution.profile, action.execution)) throw new Error('Dispatch conflicts with an accepted task'); return { taskId: existing.id }; } + const execution = this.workerExecutionProfile(action.execution); const task = await this.host.makeTask(sourceId, delegationPrompt); this.store.transaction(() => { + task.workerExecution = { profile: execution, source: { kind: 'dispatch', coordinatorTaskId: callerId, requestId: action.requestId } }; this.store.saveTask(task); if (featureAuthorization) this.store.setMeta(featureAuthorization.key, JSON.stringify(featureAuthorization.evidence)); this.ledger.addMember(state.id, task.id, action.role, action.issueId); diff --git a/src/project.ts b/src/project.ts index 6800d0a..a9dbd73 100644 --- a/src/project.ts +++ b/src/project.ts @@ -2,6 +2,7 @@ import { createHash } from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; import { z } from 'zod'; import { criteriaSchema, matchSource, sourceSchema, sourceCommentSchema, structuredReportSchema, type Source, type SourceComment } from './domain.js'; +import { executionProfileSchema } from './execution.js'; import type { Store } from './store.js'; export { reasoningEffortSchema } from './execution.js'; export type { ReasoningEffort } from './execution.js'; @@ -49,7 +50,8 @@ export const projectActionSchema = z.discriminatedUnion('action', [ offset: versionSchema.optional(), limit: z.number().int().min(1).max(100).optional() }), z.strictObject({ action: z.literal('dispatch'), requestId: idSchema, prompt: textSchema, predecessorTaskId: idSchema.optional(), issueId: idSchema.optional(), intakeTaskId: idSchema.optional(), role: z.literal('worker').default('worker'), - mode: z.enum(['investigation', 'implementation']).optional(), authorization: featureAuthorizationSchema.optional() }), + mode: z.enum(['investigation', 'implementation']).optional(), authorization: featureAuthorizationSchema.optional(), + execution: executionProfileSchema }), z.strictObject({ action: z.literal('allocate_artifacts'), requestId: idSchema, label: textSchema, parent: z.string().min(1).optional() }), z.strictObject({ action: z.literal('register_artifact'), requestId: idSchema, taskId: idSchema.optional(), scopeId: idSchema, path: z.string().min(1), disposition: artifactDispositionSchema, reference: textSchema.optional() }), z.strictObject({ action: z.literal('complete_task'), requestId: idSchema, taskId: idSchema, outcome: z.enum(['delivered', 'terminated']), summary: textSchema, deliveryReferences: z.array(textSchema) }), diff --git a/src/store.ts b/src/store.ts index de870e0..e09b79e 100644 --- a/src/store.ts +++ b/src/store.ts @@ -3,10 +3,13 @@ import { mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { createHash } from 'node:crypto'; import { z } from 'zod'; +import { isDeepStrictEqual } from 'node:util'; +import { workerExecutionIdentitySchema } from './execution.js'; import { approvalActionSchema, feishuCardRecordSchema, inputProvenanceSchema, incomingSchema, repositorySchema, sourceSchema, taskSchema, type ApprovalAction, type FeishuCardRecord, type IncomingMessage, type InputProvenance, type Source, type Task } from './domain.js'; const payloadRow = z.object({ payload: z.string() }); const taskPayloadRow = payloadRow.extend({ id: z.string() }); +const savedWorkerExecutionSchema = z.object({ workerExecution: workerExecutionIdentitySchema.optional() }); const taskIdRow = z.object({ task_id: z.string() }); const metaRow = z.object({ value: z.string() }); const dataVersionRow = z.object({ data_version: z.number() }); @@ -124,6 +127,11 @@ export class Store { return this.prepare('SELECT payload,reason FROM sources').all().map(row => { const parsed = sourceRow.parse(row); return { source: sourceSchema.parse(JSON.parse(parsed.payload)), reason: parsed.reason }; }); } saveTask(task: Task): void { + const saved = this.prepare('SELECT payload FROM tasks WHERE id=?').get(task.id); + if (saved) { + const original = savedWorkerExecutionSchema.parse(JSON.parse(payloadRow.parse(saved).payload)); + if (original.workerExecution && !isDeepStrictEqual(original.workerExecution, task.workerExecution)) throw new Error('Worker execution identity is immutable'); + } const previousThread = this.taskThreads.get(task.id); this.prepare('INSERT INTO tasks VALUES(?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET chat_id=excluded.chat_id,thread_id=excluded.thread_id,payload=excluded.payload').run(task.id, task.sourceId, task.chatId, task.threadId, JSON.stringify(task)); if (previousThread && previousThread !== task.threadId) this.taskIdsByThread.delete(previousThread); diff --git a/test/cli.test.ts b/test/cli.test.ts index 129fc07..75b4546 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -30,7 +30,7 @@ test('doctor reports discovered projects and source-only collection without requ const run = () => execute(process.execPath, [cli, entry, 'doctor', '--config', configPath, '--env-file', join(root, 'fixture.env')], { cwd: root, env }); const output = JSON.parse((await run()).stdout); assert.equal(output.ready, true); assert.equal(output.discovery.readable, true); - assert.deepEqual(output.execution, { coordinator: execution.coordinator, worker: execution.worker }); + assert.deepEqual(output.execution, { coordinator: execution.coordinator, worker: [execution.worker] }); assert.equal(output.discovery.projectRoot, join(root, 'projects')); assert.deepEqual(output.discovery.projects.map((project: { name: string }) => project.name), ['multi-repo']); assert.equal(output.repositories[0].sourceOnly, true); diff --git a/test/coordinated-fixture.ts b/test/coordinated-fixture.ts index 8363e0c..8cebfc0 100644 --- a/test/coordinated-fixture.ts +++ b/test/coordinated-fixture.ts @@ -1,3 +1,4 @@ +import { testExecution } from './test-config.js'; import assert from 'node:assert/strict'; import { z } from 'zod'; import type { AgentLoop } from '../src/loop.js'; @@ -26,7 +27,7 @@ export async function delegateIntake(loop: AgentLoop, taskId: string, prompt = ' assert.equal(loop.projects.ledger.membership(taskId), null); const inbox = loop.store.inputs(taskId).map(input => ({ id: input.id, message: input.message, provenance: input.provenance })); const receipt = dispatchReceipt.parse(await loop.projectAction(route.coordinatorTaskId, { - action: 'dispatch', requestId: `delegate-${taskId}`, intakeTaskId: taskId, role: 'worker', prompt, + action: 'dispatch', execution: testExecution.worker, requestId: `delegate-${taskId}`, intakeTaskId: taskId, role: 'worker', prompt, })); assert.equal(receipt.taskId, taskId); await loop.tick(); diff --git a/test/coordinated-runtime.ts b/test/coordinated-runtime.ts index 6d8f8be..370fa94 100644 --- a/test/coordinated-runtime.ts +++ b/test/coordinated-runtime.ts @@ -1,3 +1,4 @@ +import { testExecution } from './test-config.js'; import { openDirectGroup } from './saved-intake.js'; import assert from 'node:assert/strict'; import { z } from 'zod'; @@ -23,7 +24,7 @@ export async function dispatchIntake(loop: AgentLoop, taskId: string, prompt = ' assert.equal(loop.projects.ledger.membership(taskId), null); const inbox = loop.store.inputs(taskId); const result = z.object({ taskId: z.string() }).parse(await loop.projectAction(route.coordinatorTaskId, { - action: 'dispatch', requestId: `accept-${taskId}`, intakeTaskId: taskId, role: 'worker', mode: 'investigation', prompt, + action: 'dispatch', execution: testExecution.worker, requestId: `accept-${taskId}`, intakeTaskId: taskId, role: 'worker', mode: 'investigation', prompt, })); assert.equal(result.taskId, taskId); const worker = loop.store.task(taskId); diff --git a/test/intake-claim.test.ts b/test/intake-claim.test.ts index cf227b4..50f17b9 100644 --- a/test/intake-claim.test.ts +++ b/test/intake-claim.test.ts @@ -75,7 +75,7 @@ test('claim preserves the saved Task and all materials without execution, then e await f.loop.tick(); assert.equal(f.loop.store.task(task.id).threadId, null); assert.equal(f.loop.store.task(task.id).chatId, null); assert.ok(f.loop.store.meta(`project-intake-material:${task.id}`)); - const delegated = { action: 'dispatch', requestId: 'dispatch-claimed', intakeTaskId: task.id, role: 'worker', prompt: 'Preserve original scope.' } satisfies ProjectAction; + const delegated = { action: 'dispatch', execution: testExecution.worker, requestId: 'dispatch-claimed', intakeTaskId: task.id, role: 'worker', prompt: 'Preserve original scope.' } satisfies ProjectAction; assert.deepEqual(await f.loop.projectAction(coordinator.id, delegated), { taskId: task.id }); await f.loop.tick(); const worker = f.loop.store.task(task.id); assert.ok(worker.threadId); assert.equal(worker.chatId, null); @@ -137,7 +137,7 @@ test('claims reject non-owner decisions, Worker callers, paused, bound and forei const page = await f.loop.projectAction(caller.id, { action: 'status', section: 'unassigned_intakes' }); assert.ok(!JSON.stringify(page).includes(foreign.id)); const receipt = z.object({ taskId: z.string() }).parse(await f.loop.projectAction(caller.id, - { action: 'dispatch', requestId: 'fixture-worker', prompt: 'Do not execute external actions.', role: 'worker' })); + { action: 'dispatch', execution: testExecution.worker, requestId: 'fixture-worker', prompt: 'Do not execute external actions.', role: 'worker' })); await assert.rejects(f.loop.projectAction(receipt.taskId, { ...base, requestId: 'worker-claim' }), /coordinator/i); await assert.rejects(f.loop.projectAction(receipt.taskId, { action: 'status', section: 'unassigned_intakes' }), /coordinator/i); assert.equal(f.loop.projects.intakeRoute(task.id), null); @@ -146,7 +146,7 @@ test('claims reject non-owner decisions, Worker callers, paused, bound and forei test('a concurrent open action cannot reuse a claiming request identity for different content', async t => { const f = await fixture(t), caller = f.coordinator(); const worker = z.object({ taskId: z.string() }).parse(await f.loop.projectAction(caller.id, - { action: 'dispatch', requestId: 'existing-worker', prompt: 'Only preserve this fixture.', role: 'worker' })); + { action: 'dispatch', execution: testExecution.worker, requestId: 'existing-worker', prompt: 'Only preserve this fixture.', role: 'worker' })); const task = f.saved(), messageId = await f.decision('collision-owner'); const outcomes = await Promise.allSettled([ f.loop.projectAction(caller.id, { action: 'claim_intake', requestId: 'same-identity', taskId: task.id, messageId }), diff --git a/test/project-catalog.test.ts b/test/project-catalog.test.ts index 7403da8..9ddefed 100644 --- a/test/project-catalog.test.ts +++ b/test/project-catalog.test.ts @@ -118,13 +118,14 @@ test('dispatch promotes the same intake with old group and resources and rejects await f.runtime.acceptIntake(intake.id, 'explicit-alpha', f.material(intake.id, 'Full original input and prepared files.')); const route = f.runtime.intakeRoute(intake.id); assert.ok(route); const originalInputs = f.store.inputs(intake.id); - const action = { action: 'dispatch', requestId: 'promote', intakeTaskId: intake.id, prompt: 'Delegated scope before initial input.' }; + const action = { action: 'dispatch', execution: testExecution.worker, requestId: 'promote', intakeTaskId: intake.id, prompt: 'Delegated scope before initial input.' }; await assert.rejects(f.runtime.action(route.coordinatorTaskId, action), /paused/); f.store.saveTask({ ...intake, status: 'pending', reason: null }); const first = await f.runtime.action(route.coordinatorTaskId, action); assert.deepEqual(first, { taskId: intake.id }); assert.deepEqual(await f.runtime.action(route.coordinatorTaskId, action), first); - assert.deepEqual(f.store.task(intake.id), { ...intake, purpose: 'execution', status: 'pending', reason: null }); + assert.deepEqual(f.store.task(intake.id), { ...intake, purpose: 'execution', status: 'pending', reason: null, + workerExecution: { profile: testExecution.worker, source: { kind: 'dispatch', coordinatorTaskId: route.coordinatorTaskId, requestId: action.requestId } } }); assert.deepEqual(f.store.inputs(intake.id), originalInputs); assert.equal(f.store.meta(`project-delegation:${intake.id}`), action.prompt); assert.equal(f.store.meta(`project-task-model:${intake.id}`), null); @@ -198,7 +199,7 @@ test('concurrent source collection cannot overwrite a promoted intake with an ea const earlier = f.store.task(request.id); const collecting = f.runtime.collect({ ...source, body: 'Updated issue facts.' }, earlier, resolved); const route = f.runtime.intakeRoute(request.id); assert.ok(route); - await f.runtime.action(route.coordinatorTaskId, { action: 'dispatch', requestId: 'concurrent-promotion', intakeTaskId: request.id, prompt: 'Use the original request and scope.' }); + await f.runtime.action(route.coordinatorTaskId, { action: 'dispatch', execution: testExecution.worker, requestId: 'concurrent-promotion', intakeTaskId: request.id, prompt: 'Use the original request and scope.' }); const promoted = f.store.task(request.id); await collecting; const latest = f.store.task(request.id); diff --git a/test/project-codex.test.ts b/test/project-codex.test.ts index 6105752..a9ba14b 100644 --- a/test/project-codex.test.ts +++ b/test/project-codex.test.ts @@ -1,3 +1,4 @@ +import { testExecution } from './test-config.js'; import assert from 'node:assert/strict'; import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; @@ -185,8 +186,8 @@ const validActions = [ { action: 'control', requestId: 'resume-worker', taskId: 'task-1', operation: 'resume' }, { action: 'status' }, ...['overview', 'issues', 'comments', 'records', 'tasks'].map(section => ({ action: 'status', section, offset: 2, limit: 10 })), - { action: 'dispatch', requestId: 'dispatch-default', prompt: 'Investigate within the assigned scope.' }, - { action: 'dispatch', requestId: 'dispatch-worker', prompt: 'Verify the fixed artifact.', issueId: 'issue-1', role: 'worker' }, + { action: 'dispatch', execution: testExecution.worker, requestId: 'dispatch-default', prompt: 'Investigate within the assigned scope.' }, + { action: 'dispatch', execution: testExecution.worker, requestId: 'dispatch-worker', prompt: 'Verify the fixed artifact.', issueId: 'issue-1', role: 'worker' }, { action: 'send', requestId: 'send-1', taskId: 'task-1', text: 'Additional evidence' }, { action: 'report', requestId: 'report-result', kind: 'result', text: 'Artifact and validation evidence' }, { action: 'report', requestId: 'report-question', kind: 'question', text: 'A business decision is required.' }, @@ -225,12 +226,12 @@ const invalidCalls = [ { name: 'fractional status offset', call: { arguments: { action: 'status', offset: 0.5 } } }, { name: 'zero status limit', call: { arguments: { action: 'status', limit: 0 } } }, { name: 'oversized status page', call: { arguments: { action: 'status', limit: 101 } } }, - { name: 'missing request ID', call: { arguments: { action: 'dispatch', prompt: 'Work' } } }, - { name: 'empty dispatch prompt', call: { arguments: { action: 'dispatch', requestId: 'request', prompt: '' } } }, - { name: 'blank dispatch prompt', call: { arguments: { action: 'dispatch', requestId: 'request', prompt: ' \n\t' } } }, - { name: 'blank request ID', call: { arguments: { action: 'dispatch', requestId: ' ', prompt: 'Work' } } }, - { name: 'control character in request ID', call: { arguments: { action: 'dispatch', requestId: 'request\u0000', prompt: 'Work' } } }, - { name: 'invalid worker role', call: { arguments: { action: 'dispatch', requestId: 'request', prompt: 'Work', role: 'coordinator' } } }, + { name: 'missing request ID', call: { arguments: { action: 'dispatch', execution: testExecution.worker, prompt: 'Work' } } }, + { name: 'empty dispatch prompt', call: { arguments: { action: 'dispatch', execution: testExecution.worker, requestId: 'request', prompt: '' } } }, + { name: 'blank dispatch prompt', call: { arguments: { action: 'dispatch', execution: testExecution.worker, requestId: 'request', prompt: ' \n\t' } } }, + { name: 'blank request ID', call: { arguments: { action: 'dispatch', execution: testExecution.worker, requestId: ' ', prompt: 'Work' } } }, + { name: 'control character in request ID', call: { arguments: { action: 'dispatch', execution: testExecution.worker, requestId: 'request\u0000', prompt: 'Work' } } }, + { name: 'invalid worker role', call: { arguments: { action: 'dispatch', execution: testExecution.worker, requestId: 'request', prompt: 'Work', role: 'coordinator' } } }, { name: 'invalid report kind', call: { arguments: { action: 'report', requestId: 'request', kind: 'approval', text: 'Approve' } } }, { name: 'negative record version', call: { arguments: { action: 'record', requestId: 'request', key: 'key', text: 'text', expectedVersion: -1 } } }, { name: 'fractional record version', call: { arguments: { action: 'record', requestId: 'request', key: 'key', text: 'text', expectedVersion: 0.5 } } }, @@ -315,7 +316,7 @@ test('duplicate native RPC requests invoke the project handler once', async t => test('project action bounds accept the largest valid identifiers, text, and status page', async t => { const actions = [ - { action: 'dispatch', requestId: 'r'.repeat(512), prompt: 'p'.repeat(131_072) }, + { action: 'dispatch', execution: testExecution.worker, requestId: 'r'.repeat(512), prompt: 'p'.repeat(131_072) }, { action: 'status', section: 'records', offset: Number.MAX_SAFE_INTEGER, limit: 100 }, ]; const f = await adapter(t, { calls: actions.map(action => ({ arguments: action })), expectedReplies: actions.length }); diff --git a/test/project-runtime.test.ts b/test/project-runtime.test.ts index 05193d7..851a28f 100644 --- a/test/project-runtime.test.ts +++ b/test/project-runtime.test.ts @@ -469,7 +469,8 @@ async function fixture(t: TestContext, options: { secondProject?: boolean } = {} 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'); const id = `legacy-${source.number}`, chatId = await feishu.ensureGroup({ taskId: id, title: source.title, sourceUrl: source.url }); - const threadId = await codex.createThread({ cwd: directory, instructions: 'Saved legacy instructions' }); + const threadId = await codex.createThread({ cwd: directory, instructions: 'Saved legacy instructions', + model: testExecution.worker.model, reasoningEffort: testExecution.worker.reasoningEffort }); const turnId = await codex.startTurn({ threadId, deliveryId: `${id}:initial`, input: [{ kind: 'text', text: source.body }] }); const task = taskSchema.parse({ id, sourceId: source.id, source: { kind: 'github', issue: source, repository, collectionReason: 'legacy' }, contextDirectory: join(root, 'tasks', id), resources: [{ id: 'legacy-workspace', kind: 'project-directory', repository, workspace: directory }], @@ -478,6 +479,8 @@ async function fixture(t: TestContext, options: { secondProject?: boolean } = {} }); assert.equal(task.purpose, 'legacy'); loop.store.saveTask(task); + loop.store.setMeta(`project-task-model:${id}`, testExecution.worker.model); + loop.store.setMeta(`project-task-effort:${id}`, testExecution.worker.reasoningEffort); loop.store.receive(id, { id: `${id}:initial`, chatId, senderId: 'runtime:initial', chatType: 'group', text: source.body, attachments: [], createdAt: task.createdAt }, 'initial'); loop.store.markInput(`${id}:initial`, 'delivered'); return task; @@ -486,7 +489,7 @@ async function fixture(t: TestContext, options: { secondProject?: boolean } = {} async status(callerId = coordinator().id) { return overviewSchema.parse(await loop.projectAction(callerId, { action: 'status' })); }, async dispatch(requestId: string, prompt: string, extra: { issueId?: string; role?: 'worker'; callerId?: string; mode?: 'investigation' | 'implementation'; authorization?: Extract['authorization'] } = {}) { const result = dispatchReceipt.parse(await loop.projectAction(extra.callerId ?? coordinator().id, { - action: 'dispatch', requestId, prompt, role: extra.role ?? 'worker', ...(extra.issueId ? { issueId: extra.issueId } : {}), + action: 'dispatch', execution: testExecution.worker, requestId, prompt, role: extra.role ?? 'worker', ...(extra.issueId ? { issueId: extra.issueId } : {}), ...(extra.mode ? { mode: extra.mode } : extra.issueId ? { mode: 'investigation' as const } : {}), ...(extra.authorization ? { authorization: extra.authorization } : {}), })); @@ -606,7 +609,7 @@ test('enabling a project adopts a paused legacy Issue and preserves its group, T test('dispatch is idempotent under concurrent requests and restart, rejects conflicts and carries generic worker guidance', async t => { const f = await fixture(t); f.github.sources = [projectIssue(12)]; const coordinator = await f.initialize(); - const action: ProjectAction = { action: 'dispatch', requestId: 'investigate-12', issueId: f.github.sources[0]!.id, + const action: ProjectAction = { action: 'dispatch', execution: testExecution.worker, requestId: 'investigate-12', issueId: f.github.sources[0]!.id, role: 'worker', mode: 'investigation', prompt: 'Investigate batch export. Deliver findings and acceptance criteria only. Do not edit business code or deploy.' }; const [first, duplicate] = await Promise.all([f.loop.projectAction(coordinator.id, action), f.loop.projectAction(coordinator.id, action)]); assert.deepEqual(first, duplicate); @@ -634,7 +637,7 @@ test('dispatch is idempotent under concurrent requests and restart, rejects conf test('a durable dispatch intent rejects changed retries after its result receipt is lost', async t => { const f = await fixture(t); const coordinator = await f.initialize(); - const action: ProjectAction = { action: 'dispatch', requestId: 'lost-receipt', role: 'worker', prompt: 'Investigate the existing export contract only.' }; + const action: ProjectAction = { action: 'dispatch', execution: testExecution.worker, requestId: 'lost-receipt', role: 'worker', prompt: 'Investigate the existing export contract only.' }; t.mock.method(f.loop.projects.ledger, 'saveReceipt', () => { throw new Error('Simulated receipt write failure'); }, { times: 1 }); await assert.rejects(f.loop.projectAction(coordinator.id, action), /Simulated receipt write failure/); const member = f.state().members.find(member => member.role === 'worker'); assert.ok(member); @@ -712,7 +715,7 @@ test('a direct project-group message keeps the coordinator final reply visible', test('Feature implementation needs owner authorization while investigation remains allowed', async t => { const f = await fixture(t); const source = projectIssue(14); f.github.sources = [source]; const coordinator = await f.initialize(); await f.idleCoordinator(); const intake = f.loop.store.taskForSource(source.id); assert.ok(intake); - const missing: ProjectAction = { action: 'dispatch', requestId: 'feature-implementation-missing', issueId: source.id, intakeTaskId: intake.id, + const missing: ProjectAction = { action: 'dispatch', execution: testExecution.worker, requestId: 'feature-implementation-missing', issueId: source.id, intakeTaskId: intake.id, role: 'worker', mode: 'implementation', prompt: 'Implement the requested feature.' }; await assert.rejects(f.loop.projectAction(coordinator.id, missing), /authorization/); assert.equal(f.loop.projects.ledger.membership(intake.id), null); @@ -1023,7 +1026,7 @@ test('rotation waits for coordinator idleness and retains its group, members, pe assert.equal(f.loop.tasks().length, 2); }); -test('role profiles reach Thread creation and hot reload applies to existing tasks', async t => { +test('Worker identity stays fixed while coordinator hot reload applies to existing tasks', async t => { const f = await fixture(t); const coordinator = await f.initialize(); assert.ok(coordinator.threadId); const worker = await f.dispatch('model-worker', 'Investigate the export contract.'); @@ -1031,12 +1034,14 @@ test('role profiles reach Thread creation and hot reload applies to existing tas const inspected = f.codex.instructionUpdates.length; f.config.execution = { coordinator: { backend: 'codex', model: 'reloaded-coordinator', reasoningEffort: 'low' }, - worker: { backend: 'codex', model: 'reloaded-worker', reasoningEffort: 'medium' }, + worker: [{ backend: 'codex', model: 'reloaded-worker', reasoningEffort: 'medium' }], backends: f.config.execution.backends, }; await f.restart(); assert.ok(f.codex.instructionUpdates.slice(inspected).some(input => input.threadId === coordinator.threadId && input.model === 'reloaded-coordinator')); - assert.ok(f.codex.instructionUpdates.slice(inspected).some(input => input.threadId === worker.threadId && input.model === 'reloaded-worker')); + assert.ok(f.codex.instructionUpdates.slice(inspected).some(input => input.threadId === worker.threadId + && input.model === 'test-worker' && input.reasoningEffort === 'xhigh')); + assert.ok(!f.codex.instructionUpdates.slice(inspected).some(input => input.threadId === worker.threadId && input.model === 'reloaded-worker')); await f.loop.projectAction(coordinator.id, { action: 'rotate', requestId: 'rotate-model', checkpoint: 'Use the current role profiles.' }); f.codex.complete(coordinator.threadId, null); await f.loop.tick(); await f.loop.tick(); @@ -1053,7 +1058,7 @@ test('configured coordinator and Worker use the shared role profiles', async t = test('dispatch persisted before launch is recovered once and an uncertain accepted input is never resent', async t => { const f = await fixture(t); await f.initialize(); - const action: ProjectAction = { action: 'dispatch', requestId: 'before-restart', role: 'worker', prompt: 'Investigate without changing source.' }; + const action: ProjectAction = { action: 'dispatch', execution: testExecution.worker, requestId: 'before-restart', role: 'worker', prompt: 'Investigate without changing source.' }; const receipt = dispatchReceipt.parse(await f.loop.projectAction(f.coordinator().id, action)); assert.equal(f.loop.store.task(receipt.taskId).threadId, null); f.codex.loseInputAck = true; @@ -1077,8 +1082,8 @@ test('project and role permissions reject cross-project messages, foreign Issues const before = f.loop.store.inputs(foreign.id).length; const forbidden: { caller: string; action: ProjectAction }[] = [ { caller: app.id, action: { action: 'send', requestId: 'foreign-send', taskId: foreign.id, text: 'Change another project.' } }, - { caller: app.id, action: { action: 'dispatch', requestId: 'foreign-issue', issueId: docsIssue.id, role: 'worker', prompt: 'Take over another project.' } }, - { caller: worker.id, action: { action: 'dispatch', requestId: 'worker-dispatch', role: 'worker', prompt: 'Spawn a peer.' } }, + { caller: app.id, action: { action: 'dispatch', execution: testExecution.worker, requestId: 'foreign-issue', issueId: docsIssue.id, role: 'worker', prompt: 'Take over another project.' } }, + { caller: worker.id, action: { action: 'dispatch', execution: testExecution.worker, requestId: 'worker-dispatch', role: 'worker', prompt: 'Spawn a peer.' } }, { caller: worker.id, action: { action: 'send', requestId: 'worker-send', taskId: foreign.id, text: 'Direct another Worker.' } }, { caller: worker.id, action: { action: 'rotate', requestId: 'worker-rotate', checkpoint: 'Rotate the coordinator.' } }, { caller: app.id, action: { action: 'report', requestId: 'coordinator-report', kind: 'question', text: 'Pretend to be a Worker.' } }, @@ -1860,7 +1865,7 @@ test('current reporting and event guidance reaches new and resumed Worker, secon test('a constructed initial-batch fixture excludes dropped copies while delivering its valid source inputs', async t => { const f = await fixture(t); await f.loop.collect(); const coordinator = f.coordinator(); - const receipt = dispatchReceipt.parse(await f.loop.projectAction(coordinator.id, { action: 'dispatch', requestId: 'before-first-turn', prompt: 'Wait for an explicit task.', role: 'worker' })); + const receipt = dispatchReceipt.parse(await f.loop.projectAction(coordinator.id, { action: 'dispatch', execution: testExecution.worker, requestId: 'before-first-turn', prompt: 'Wait for an explicit task.', role: 'worker' })); 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'); diff --git a/test/project.test.ts b/test/project.test.ts index f4f266c..a87b1ef 100644 --- a/test/project.test.ts +++ b/test/project.test.ts @@ -117,7 +117,7 @@ test('project intake can require an assigned account AND Bug classification', () test('project actions are discriminated strict shapes with a default worker role', () => { const actions: ProjectAction[] = [ - { action: 'status' }, { action: 'dispatch', requestId: 'd', prompt: 'Investigate.', role: 'worker' }, + { action: 'status' }, { action: 'dispatch', execution: testExecution.worker, requestId: 'd', prompt: 'Investigate.', role: 'worker' }, { action: 'send', requestId: 's', taskId: 'worker', text: 'Preserve order.' }, { action: 'announce', requestId: 'a', kind: 'delivery', text: 'Delivered.' }, { action: 'report', requestId: 'r', kind: 'question', text: 'Which format?' }, @@ -128,7 +128,7 @@ test('project actions are discriminated strict shapes with a default worker role { action: 'release_workspace', requestId: 'rel', resourceId: 'resource' }, ]; for (const action of actions) assert.deepEqual(projectActionSchema.parse(action), action); - assert.deepEqual(projectActionSchema.parse({ action: 'dispatch', requestId: 'd', prompt: 'Investigate.' }), actions[1]); + assert.deepEqual(projectActionSchema.parse({ action: 'dispatch', execution: testExecution.worker, requestId: 'd', prompt: 'Investigate.' }), actions[1]); for (const action of actions) assert.equal(projectActionSchema.safeParse({ ...action, projectId: 'other' }).success, false); }); @@ -147,9 +147,9 @@ test('status accepts optional bounded paging without injecting defaults', () => test('project actions reject blank or oversized payloads and invalid record versions', () => { const invalid: unknown[] = [ - { action: 'dispatch', requestId: 'd', prompt: ' ' }, - { action: 'dispatch', requestId: 'd', prompt: 'p'.repeat(131_073) }, - { action: 'dispatch', requestId: 'd', prompt: 'Work.', role: 'coordinator' }, + { action: 'dispatch', execution: testExecution.worker, requestId: 'd', prompt: ' ' }, + { action: 'dispatch', execution: testExecution.worker, requestId: 'd', prompt: 'p'.repeat(131_073) }, + { action: 'dispatch', execution: testExecution.worker, requestId: 'd', prompt: 'Work.', role: 'coordinator' }, { action: 'send', requestId: '', taskId: 'w', text: 'Hello.' }, { action: 'send', requestId: 's', taskId: 'w'.repeat(513), text: 'Hello.' }, { action: 'send', requestId: 's', taskId: 'w', text: '' }, @@ -207,7 +207,7 @@ test('membership rejects cross-project reuse, role changes and missing issue ass fx.create(); fx.create(config('beta'), 'beta-coordinator'); fx.write(ledger => ledger.addMember('alpha', 'worker', 'worker')); assert.throws(() => fx.write(ledger => ledger.addMember('beta', 'worker', 'worker'))); - assert.throws(() => projectActionSchema.parse({ action: 'dispatch', requestId: 'v', prompt: 'Verify.', role: 'verifier', issueId: 'issue-1' })); + assert.throws(() => projectActionSchema.parse({ action: 'dispatch', execution: testExecution.worker, requestId: 'v', prompt: 'Verify.', role: 'verifier', issueId: 'issue-1' })); assert.throws(() => fx.write(ledger => ledger.addMember('alpha', 'second-coordinator', 'coordinator'))); assert.throws(() => fx.write(ledger => ledger.addMember('alpha', 'new-worker', 'worker', 'missing'))); assert.throws(() => fx.write(ledger => ledger.addMember('missing', 'new-worker', 'worker'))); diff --git a/test/runtime.test.ts b/test/runtime.test.ts index 14d3479..fccddcc 100644 --- a/test/runtime.test.ts +++ b/test/runtime.test.ts @@ -57,7 +57,7 @@ async function fixture(t: TestContext) { async restart() { await loop.close(); loop = new AgentLoop(config, ports); await loop.recover(); }, async githubTask() { github.sources = [issue(1)]; await loop.collect(); await loop.tick(); const coordinator = loop.projects.ledger.project('runtime')!.coordinatorTaskId; - await loop.projectAction(coordinator, { action: 'dispatch', requestId: 'test-issue-1', issueId: 'issue-1', role: 'worker', prompt: 'Investigate Issue 1.' }); + await loop.projectAction(coordinator, { action: 'dispatch', execution: testExecution.worker, requestId: 'test-issue-1', issueId: 'issue-1', role: 'worker', prompt: 'Investigate Issue 1.' }); await loop.tick(); await openDirectGroup(loop, task().id); return task(); }, }; } diff --git a/test/task-closeout.test.ts b/test/task-closeout.test.ts index 7410188..6ae5aa5 100644 --- a/test/task-closeout.test.ts +++ b/test/task-closeout.test.ts @@ -54,7 +54,7 @@ async function fixture(t: TestContext) { t.after(async () => { await loop.close(); await rm(root, { recursive: true, force: true }); }); return { root, project, data, codex, feishu, workspace, action, state, finish, completeAction, coordinatorId, get loop() { return loop; }, - async worker() { const result = z.object({ taskId: z.string() }).parse(await action({ action: 'dispatch', requestId: `dispatch-${++request}`, prompt: 'Do fixture work', role: 'worker' })); await loop.tick(); return loop.store.task(result.taskId); }, + async worker() { const result = z.object({ taskId: z.string() }).parse(await action({ action: 'dispatch', execution: testExecution.worker, requestId: `dispatch-${++request}`, prompt: 'Do fixture work', role: 'worker' })); await loop.tick(); return loop.store.task(result.taskId); }, async scope(taskId: string) { const value = (await state(taskId)).scopes.find(scope => scope.resource.kind === 'artifacts'); assert.ok(value); return value; }, async complete(taskId: string) { return receipt.parse(await action(completeAction(taskId))); }, async restart() { await loop.close(); loop = new AgentLoop(config, ports); await loop.recover(); }, @@ -341,7 +341,7 @@ test('completed followups retain original provenance and create no automatic exe assert.equal(f.loop.tasks().length, 2); assert.equal(f.codex.starts.filter(start => start.threadId === worker.threadId).length, starts); await assert.rejects(f.loop.control(worker.id, 'resume'), /completed/); await assert.rejects(f.loop.ensureWorkspace(worker.id, 'example/app'), /completed/); await assert.rejects(f.action({ action: 'send', requestId: 'old-send', taskId: worker.id, text: 'continue' }), /completed/); - const newTask = z.object({ taskId: z.string() }).parse(await f.action({ action: 'dispatch', requestId: 'follow-new', predecessorTaskId: worker.id, prompt: 'New output', role: 'worker' })); + const newTask = z.object({ taskId: z.string() }).parse(await f.action({ action: 'dispatch', execution: testExecution.worker, requestId: 'follow-new', predecessorTaskId: worker.id, prompt: 'New output', role: 'worker' })); assert.equal((await f.state(newTask.taskId)).predecessorTaskId, worker.id); assert.notEqual((await f.scope(newTask.taskId)).location.root.path, (await f.scope(worker.id)).location.root.path); assert.match(f.loop.store.inputs(newTask.taskId)[0]?.message.text ?? '', /Delivered result/); }); diff --git a/test/worker-execution-identity.test.ts b/test/worker-execution-identity.test.ts new file mode 100644 index 0000000..261c5f8 --- /dev/null +++ b/test/worker-execution-identity.test.ts @@ -0,0 +1,264 @@ +import assert from 'node:assert/strict'; +import { DatabaseSync } from 'node:sqlite'; +import { randomUUID } from 'node:crypto'; +import { z } from 'zod'; +import { projectActionSchema } from '../src/project.js'; +import { taskSchema, type Task } from '../src/domain.js'; +import { CodexProviderMismatchError } from '../src/ports.js'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { test, type TestContext } from 'node:test'; +import { configSchema } from '../src/config.js'; +import { AgentLoop } from '../src/loop.js'; +import type { ExecutionProfile } from '../src/execution.js'; +import { CodexFake, FeishuFake, GitHubFake } from './fakes.js'; +import type { CodexPort, WorkspacePort } from '../src/ports.js'; +import { Store } from '../src/store.js'; + +const workerA: ExecutionProfile = { backend: 'codex', model: 'worker-a', reasoningEffort: 'high' }; +const workerB: ExecutionProfile = { backend: 'codex', model: 'worker-b', reasoningEffort: 'medium' }; +const coordinator: ExecutionProfile = { backend: 'codex', model: 'coordinator', reasoningEffort: 'low' }; + +class IdentityCodex extends CodexFake { + readonly observations: { threadId: string; model?: string; reasoningEffort?: string }[] = []; + override async inspect(...args: Parameters) { + const [threadId, _instructions, model, reasoningEffort] = args; + this.observations.push({ threadId, model, reasoningEffort }); + return super.inspect(threadId); + } + override async activity(...args: Parameters) { + const [threadId, _instructions, model, reasoningEffort] = args; + this.observations.push({ threadId, model, reasoningEffort }); + return super.activity(...args); + } +} + +async function fixture(t: TestContext, profiles = [workerA, workerB]) { + const root = await mkdtemp(join(tmpdir(), 'agent-worker-identity-')); + const config = configSchema.parse({ + dataDir: root, + execution: { coordinator, worker: profiles }, + feishu: { userOpenId: 'owner' }, + projects: [{ id: 'app', name: 'Application', directory: root, repositories: [] }], + }); + const codex = new IdentityCodex(); + const workspace: WorkspacePort = { async ensure(input) { return input.kind === 'project-directory' ? input.directory : input.workspace ?? root; }, async head() { return 'head'; } }; + const ports = { github: new GitHubFake(), feishu: new FeishuFake(), codex, workspace }; + let loop = new AgentLoop(config, ports, new Store(root)); + t.after(async () => { await loop.close(); await rm(root, { recursive: true, force: true }); }); + await loop.collect(); await loop.tick(); + const project = loop.projects.ledger.project('app'); + assert.ok(project); + const coordinatorTask = loop.store.task(project.coordinatorTaskId); + return { root, config, get loop() { return loop; }, codex, coordinatorTask, + async restart() { await loop.close(); loop = new AgentLoop(config, ports, new Store(root)); await loop.recover(); } }; +} + +async function dispatch(f: Awaited>, execution?: ExecutionProfile) { + const action = { action: 'dispatch' as const, requestId: `dispatch-${randomUUID()}`, role: 'worker' as const, + prompt: 'Preserve the selected execution identity.', ...(execution ? { execution } : {}) }; + const result = await f.loop.projectAction(f.coordinatorTask.id, projectActionSchema.parse(action)); + await f.loop.tick(); + return f.loop.store.task(z.object({ taskId: z.string() }).parse(result).taskId); +} + +test('worker dispatch accepts only complete allowlisted execution profiles', async t => { + const f = await fixture(t); + const worker = await dispatch(f, workerB); + assert.deepEqual(worker.workerExecution?.profile, workerB); + assert.equal(f.codex.created.at(-1)?.model, workerB.model); + await assert.rejects(dispatch(f, { ...workerA, model: workerB.model }), /outside the configured allowlist/); + await assert.rejects(dispatch(f), /execution/); +}); + +test('a saved Worker identity survives allowlist deletion and restart', async t => { + const f = await fixture(t); + const worker = await dispatch(f, workerB); + const created = f.codex.created.length; + f.config.execution.worker = [workerA]; + await f.restart(); await f.loop.tick(); + const restored = f.loop.store.task(worker.id); + assert.deepEqual(restored.workerExecution?.profile, workerB); + assert.equal(f.codex.created.length, created); + const calls = f.codex.observations.filter(call => call.threadId === worker.threadId); + assert.ok(calls.length > 0); + assert.ok(calls.every(call => call.model === workerB.model && call.reasoningEffort === workerB.reasoningEffort)); +}); + +function replaceAsHistorical(f: Awaited>, worker: Task) { + const legacy = { ...worker }; + delete legacy.workerExecution; + const database = new DatabaseSync(join(f.root, 'tasks.sqlite')); + try { database.prepare('UPDATE tasks SET payload=? WHERE id=?').run(JSON.stringify(legacy), worker.id); } + finally { database.close(); } + return legacy; +} + +for (const missing of ['both', 'model', 'effort', 'invalid-effort'] as const) test(`historical identity ${missing} is blocked without execution or state changes across resume and restart`, async t => { + const f = await fixture(t, [workerA]); + const worker = await dispatch(f, workerA); + assert.ok(worker.threadId); + await f.loop.projectAction(f.coordinatorTask.id, { action: 'open_group', requestId: 'open', taskId: worker.id }); + await f.loop.control(worker.id, 'pause'); + const paused = f.loop.store.task(worker.id); + paused.requests = [{ id: 'pending-native', threadId: worker.threadId, turnId: worker.turnId!, kind: 'approval', prompt: 'Retain approval', method: 'item/commandExecution/requestApproval', payload: {}, isBlocking: true, connectionEpoch: 'original' }]; + f.loop.store.saveTask(paused); + const message = { id: 'held', chatId: paused.chatId!, senderId: 'owner', chatType: 'group' as const, text: 'Continue later', attachments: [], createdAt: Date.now() }; + f.loop.store.receive(worker.id, message); + f.loop.store.markInput(message.id, 'held'); + const original = replaceAsHistorical(f, paused); + if (missing !== 'both' && missing !== 'model') f.loop.store.setMeta(`project-task-model:${worker.id}`, workerB.model); + if (missing === 'model') f.loop.store.setMeta(`project-task-effort:${worker.id}`, workerB.reasoningEffort); + if (missing === 'invalid-effort') f.loop.store.setMeta(`project-task-effort:${worker.id}`, 'invalid'); + const observations = f.codex.observations.length, creates = f.codex.created.length; + const starts = () => f.codex.starts.filter(call => call.threadId === worker.threadId).length; + const steers = () => f.codex.steers.filter(call => call.threadId === worker.threadId).length; + const started = starts(), steered = steers(); + await f.loop.tick(); await f.loop.tick(); + await f.loop.control(worker.id, 'resume'); + assert.deepEqual(f.loop.store.task(worker.id), original); + assert.equal(f.loop.store.input(worker.id, 'held')?.status, 'held'); + assert.ok(f.codex.observations.slice(observations).every(call => call.threadId !== worker.threadId)); + assert.equal(starts(), started); assert.equal(steers(), steered); assert.equal(f.codex.created.length, creates); + const blockers = () => f.loop.store.inputs(f.coordinatorTask.id).filter(input => input.provenance.kind === 'agent' && input.provenance.eventId === `execution-identity:${worker.id}`); + assert.equal(blockers().length, 1); + assert.match(blockers()[0]!.message.text, /No complete reliable original model/); + const blocker = blockers()[0]!.provenance; + assert.equal(blocker.kind === 'agent' && blocker.escalation, 'blocker'); + await f.restart(); await f.loop.tick(); + assert.deepEqual(f.loop.store.task(worker.id), original); + assert.equal(blockers().length, 1); +}); + +test('complete historical task metadata restores the original pair and source independently of the allowlist', async t => { + const f = await fixture(t); + const worker = await dispatch(f, workerB); + f.config.execution.worker = [workerA]; + replaceAsHistorical(f, worker); + const modelKey = `project-task-model:${worker.id}`, effortKey = `project-task-effort:${worker.id}`; + f.loop.store.setMeta(modelKey, workerB.model); f.loop.store.setMeta(effortKey, workerB.reasoningEffort); + const observations = f.codex.observations.length; + await f.loop.tick(); + assert.deepEqual(f.loop.store.task(worker.id).workerExecution, { profile: workerB, source: { kind: 'legacy-task-metadata', modelKey, effortKey } }); + const calls = f.codex.observations.slice(observations).filter(call => call.threadId === worker.threadId); + assert.ok(calls.length); assert.ok(calls.every(call => call.model === workerB.model && call.reasoningEffort === workerB.reasoningEffort)); + assert.equal(f.loop.store.meta(modelKey), workerB.model); assert.equal(f.loop.store.meta(effortKey), workerB.reasoningEffort); +}); + +test('saved execution identity cannot be changed or deleted through task persistence', async t => { + const f = await fixture(t); + const worker = await dispatch(f, workerA); + assert.ok(worker.workerExecution); + await assert.rejects(f.loop.projectAction(f.coordinatorTask.id, { action: 'dispatch', requestId: worker.workerExecution.source.kind === 'dispatch' ? worker.workerExecution.source.requestId : 'unexpected', prompt: 'Preserve the selected execution identity.', role: 'worker', execution: workerB }), /different content/); + const changed = structuredClone(worker); + changed.workerExecution!.profile = workerB; + assert.throws(() => f.loop.store.saveTask(changed), /immutable/); + delete changed.workerExecution; + assert.throws(() => f.loop.store.saveTask(changed), /immutable/); + assert.deepEqual(f.loop.store.task(worker.id).workerExecution, worker.workerExecution); +}); + +test('missing explicit selection rejects even a one-entry allowlist', async t => { + const f = await fixture(t, [workerA]); + await assert.rejects(dispatch(f), /execution/); +}); + +test('duplicate Worker allowlist entries are rejected at the config boundary', () => { + const result = configSchema.safeParse({ execution: { coordinator, worker: [workerA, workerA] }, feishu: { userOpenId: 'owner' } }); + assert.equal(result.success, false); +}); + +test('saved Worker pair remains fixed across multiple turns, pause and provider migration', async t => { + const f = await fixture(t); + const worker = await dispatch(f, workerB); + assert.ok(worker.threadId); + const originalIdentity = worker.workerExecution; + f.config.execution.worker = [workerA]; + await f.loop.projectAction(f.coordinatorTask.id, { action: 'open_group', requestId: 'open', taskId: worker.id }); + const opened = f.loop.store.task(worker.id); + assert.ok(opened.chatId); + f.codex.complete(worker.threadId, null); await f.loop.tick(); + await f.loop.receive({ id: 'second-turn', chatId: opened.chatId, senderId: 'owner', chatType: 'group', text: 'Continue the same task.', attachments: [], createdAt: Date.now() }); + assert.equal(f.codex.starts.filter(call => call.threadId === worker.threadId).length, 2); + await f.loop.control(worker.id, 'pause'); + f.codex.inspectErrors.set(worker.threadId, new CodexProviderMismatchError('old-provider', 'new-provider')); + await f.loop.control(worker.id, 'resume'); await f.loop.tick(); + const migrated = f.loop.store.task(worker.id); + assert.notEqual(migrated.threadId, worker.threadId); + assert.deepEqual(migrated.workerExecution, originalIdentity); + assert.equal(f.codex.created.at(-1)?.model, workerB.model); + assert.equal(f.codex.created.at(-1)?.reasoningEffort, workerB.reasoningEffort); +}); + +test('status queries leave historical execution identity untouched', async t => { + const f = await fixture(t); + const worker = await dispatch(f, workerB); + const original = replaceAsHistorical(f, worker); + f.loop.store.setMeta(`project-task-model:${worker.id}`, workerB.model); + f.loop.store.setMeta(`project-task-effort:${worker.id}`, workerB.reasoningEffort); + await f.loop.projectAction(f.coordinatorTask.id, { action: 'status', section: 'tasks' }); + await f.loop.control(worker.id, 'status'); + assert.deepEqual(f.loop.store.task(worker.id), original); +}); + +test('identity-blocked restart preserves group binding when history says the group is unavailable', async t => { + const f = await fixture(t); + const worker = await dispatch(f, workerB); + await f.loop.projectAction(f.coordinatorTask.id, { action: 'open_group', requestId: 'open', taskId: worker.id }); + await f.loop.control(worker.id, 'pause'); + const original = replaceAsHistorical(f, f.loop.store.task(worker.id)); + assert.ok(original.chatId); + await f.loop.ports.feishu.dissolveGroup(original.chatId); + f.loop.store.enqueue(worker.id, 'Retain pending output until identity is established.', 'before-block'); + const outputs = f.loop.store.outputs(worker.id); + const sent = f.loop.ports.feishu.send; + let sends = 0; + f.loop.ports.feishu.send = async input => { if (input.chatId === original.chatId) { sends++; throw new Error('Unknown original group'); } return sent.call(f.loop.ports.feishu, input); }; + const history = f.loop.ports.feishu.history; + let blockedHistory = 0; + f.loop.ports.feishu.history = async input => { + if (input.chatId === original.chatId) blockedHistory++; + return history.call(f.loop.ports.feishu, input); + }; + await f.restart(); await f.loop.tick(); + assert.deepEqual(f.loop.store.task(worker.id), original); + assert.equal(blockedHistory, 0); assert.equal(sends, 0); + assert.deepEqual(f.loop.store.outputs(worker.id), outputs); +}); + +test('an adopted historical Worker blocks before unavailable saved resources can change its state', async t => { + const f = await fixture(t); + const worker = await dispatch(f, workerB); + const id = 'historical-before-adoption'; + const legacy = taskSchema.parse({ ...worker, id, sourceId: id, + workerExecution: undefined, purpose: 'legacy', chatId: null, + contextDirectory: join(f.root, 'tasks', id), + threadId: await f.codex.createThread({ cwd: f.root, instructions: 'Original historical task.', model: workerB.model, reasoningEffort: workerB.reasoningEffort }), + resources: [{ id: 'saved-resource', kind: 'project', workspace: f.root, + project: { kind: 'project', id: 'saved-project', name: 'Application', entryPath: f.root, canonicalPath: f.root } }], + }); + f.loop.store.saveTask(legacy); + let restores = 0; + f.loop.ports.workspace.ensure = async () => { restores++; throw new Error('Original workspace unavailable'); }; + await f.restart(); + const adopted = f.loop.store.task(id); + assert.equal(adopted.status, legacy.status); assert.equal(adopted.reason, legacy.reason); + assert.equal(adopted.threadId, legacy.threadId); assert.deepEqual(adopted.resources, legacy.resources); + assert.equal(f.loop.projects.ledger.membership(id)?.role, 'worker'); + assert.equal(restores, 0); +}); + +test('lost dispatch receipt retries preserve the accepted pair after it is removed from the allowlist', async t => { + const f = await fixture(t); + const action = { action: 'dispatch' as const, requestId: 'lost-receipt', prompt: 'Preserve accepted work.', role: 'worker' as const, execution: workerB }; + t.mock.method(f.loop.projects.ledger, 'saveReceipt', () => { throw new Error('Receipt write failed after acceptance'); }, { times: 1 }); + await assert.rejects(f.loop.projectAction(f.coordinatorTask.id, action), /Receipt write failed/); + const accepted = f.loop.tasks().find(task => f.loop.projects.ledger.membership(task.id)?.role === 'worker'); + assert.ok(accepted); + f.config.execution.worker = [workerA]; + await f.restart(); + assert.deepEqual(await f.loop.projectAction(f.coordinatorTask.id, action), { taskId: accepted.id }); + assert.deepEqual(f.loop.store.task(accepted.id).workerExecution?.profile, workerB); + assert.equal(f.loop.tasks().filter(task => f.loop.projects.ledger.membership(task.id)?.role === 'worker').length, 1); +}); diff --git a/test/worker-execution-wire.test.ts b/test/worker-execution-wire.test.ts new file mode 100644 index 0000000..8deb96b --- /dev/null +++ b/test/worker-execution-wire.test.ts @@ -0,0 +1,118 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { setTimeout as delay } from 'node:timers/promises'; +import { z } from 'zod'; +import { configSchema, ExecutionConfigWatcher } from '../src/config.js'; +import { AgentLoop } from '../src/loop.js'; +import { CodexAppServer } from './helpers/codex.js'; +import { FeishuFake, GitHubFake } from './fakes.js'; + +const provider = String.raw` +const fs = require('node:fs'); +const readline = require('node:readline'); +const log = process.argv[1], file = process.argv[2]; +const threads = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {}; +const send = value => process.stdout.write(JSON.stringify(value) + '\n'); +const persist = () => fs.writeFileSync(file, JSON.stringify(threads)); +readline.createInterface({ input: process.stdin }).on('line', line => { + const message = JSON.parse(line); + fs.appendFileSync(log, line + '\n'); + const p = message.params; + let result; + switch (message.method) { + case 'initialize': result = { userAgent: 'identity-wire-fixture' }; break; + case 'initialized': return; + case 'thread/start': { + const id = 'thread-' + (Object.keys(threads).length + 1); + const thread = { id, model: p.model, reasoningEffort: p.config.model_reasoning_effort, status: { type: 'idle' }, turns: [] }; + threads[id] = thread; persist(); result = { thread }; break; + } + case 'thread/resume': { + const thread = threads[p.threadId]; + thread.model = p.model; thread.reasoningEffort = p.config.model_reasoning_effort; + persist(); result = { thread }; break; + } + case 'thread/read': { + const thread = threads[p.threadId]; + result = { thread: { ...thread, turns: p.includeTurns ? thread.turns : [] } }; break; + } + case 'turn/start': { + const thread = threads[p.threadId]; + const turn = { id: thread.id + '-turn-' + (thread.turns.length + 1), status: 'completed', items: [ + { id: p.clientUserMessageId, type: 'userMessage', clientId: p.clientUserMessageId, content: p.input } + ] }; + thread.turns.push(turn); persist(); result = { turn }; break; + } + default: throw new Error('Unexpected identity fixture request ' + message.method); + } + send({ id: message.id, result }); +}); +`; + +const profileA = { backend: 'codex', model: 'model-a', reasoningEffort: 'high' as const }; +const profileB = { backend: 'codex', model: 'model-b', reasoningEffort: 'medium' as const }; +const requestSchema = z.object({ method: z.string().optional(), params: z.object({ + threadId: z.string().optional(), model: z.string().optional(), effort: z.string().optional(), + config: z.object({ model_reasoning_effort: z.string() }).optional(), allowProviderModelFallback: z.boolean().optional(), +}).optional() }); + +test('real Codex adapter sends the saved pair on start, resume and every turn after service restart and allowlist deletion', async t => { + const root = await mkdtemp(join(tmpdir(), 'worker-wire-')); + const log = join(root, 'wire.jsonl'), state = join(root, 'provider.json'); + const configInput = { dataDir: join(root, 'data'), feishu: { userOpenId: 'owner' }, + projects: [{ id: 'app', name: 'Application', directory: root, repositories: [] }], + execution: { coordinator: { backend: 'codex', model: 'coordinator-original', reasoningEffort: 'low' }, worker: [profileA, profileB] } }; + const configFile = join(root, 'config.json'); + await writeFile(configFile, JSON.stringify(configInput)); + const config = configSchema.parse(configInput); + const errors: unknown[] = []; + const watcher = new ExecutionConfigWatcher(configFile, config, error => errors.push(error)); + watcher.start(); + t.after(() => watcher.close()); + const github = new GitHubFake(), feishu = new FeishuFake(); + const create = () => new AgentLoop(config, { github, feishu, + codex: new CodexAppServer({ command: [process.execPath, '-e', provider, log, state], approvalPolicy: 'never', sandbox: 'read-only', requestTimeoutMs: 2000 }), + workspace: { async ensure() { return root; }, async head() { return 'fixture'; } } }); + let loop = create(); + t.after(async () => { await loop.close(); await rm(root, { recursive: true, force: true }); }); + await loop.collect(); await loop.tick(); + const coordinator = loop.projects.ledger.project('app')!.coordinatorTaskId; + const action = { action: 'dispatch' as const, requestId: 'wire-worker', prompt: 'Use this immutable pair.', role: 'worker' as const, execution: profileB }; + const receipt = z.object({ taskId: z.string() }).parse(await loop.projectAction(coordinator, action)); + await loop.tick(); await loop.tick(); + const worker = loop.store.task(receipt.taskId); assert.ok(worker.threadId); + const first = (await readFile(log, 'utf8')).trim().split('\n').map(line => requestSchema.parse(JSON.parse(line))).filter(row => row.method === 'thread/start'); + assert.equal(first[1]?.params?.model, profileB.model); + assert.equal(first[1]?.params?.config?.model_reasoning_effort, profileB.reasoningEffort); + assert.equal(first[1]?.params?.allowProviderModelFallback, false); + await loop.projectAction(coordinator, { action: 'send', requestId: 'turn-two', taskId: worker.id, text: 'Continue the original Worker.' }); + await loop.tick(); await loop.tick(); + await loop.control(worker.id, 'pause'); + await writeFile(configFile, JSON.stringify({ ...configInput, execution: { worker: [profileA], coordinator: { backend: 'codex', model: 'coordinator-new', reasoningEffort: 'xhigh' } } })); + for (let attempt = 0; config.execution.worker.length !== 1 && attempt < 200; attempt++) await delay(10); + assert.equal(config.execution.worker.length, 1); assert.deepEqual(config.execution.worker[0], profileA); + assert.equal(errors.length, 0); + await loop.close(); loop = create(); await loop.recover(); + assert.equal(loop.store.task(worker.id).status, 'paused'); + await loop.control(worker.id, 'resume'); + await loop.projectAction(coordinator, { action: 'send', requestId: 'turn-three', taskId: worker.id, text: 'Continue after restart.' }); + await loop.tick(); await loop.tick(); + assert.deepEqual(await loop.projectAction(coordinator, action), receipt); + const rows = (await readFile(log, 'utf8')).trim().split('\n').map(line => requestSchema.parse(JSON.parse(line))); + const resumes = rows.filter(row => row.method === 'thread/resume' && row.params?.threadId === worker.threadId); + assert.ok(resumes.length > 0); + for (const row of resumes) { + assert.equal(row.params?.model, profileB.model); assert.equal(row.params?.config?.model_reasoning_effort, profileB.reasoningEffort); + } + const turns = rows.filter(row => row.method === 'turn/start' && row.params?.threadId === worker.threadId); + assert.equal(turns.length, 3); + for (const row of turns) assert.equal(row.params?.effort, profileB.reasoningEffort); + assert.ok(rows.some(row => row.method === 'thread/resume' && row.params?.model === 'coordinator-new' && row.params.config?.model_reasoning_effort === 'xhigh')); + const newWorker = z.object({ taskId: z.string() }).parse(await loop.projectAction(coordinator, { ...action, requestId: 'new-a', execution: profileA })); + await loop.tick(); + assert.deepEqual(loop.store.task(newWorker.taskId).workerExecution?.profile, profileA); + await assert.rejects(loop.projectAction(coordinator, { ...action, requestId: 'deleted-pair' }), /outside the configured allowlist/); +});