diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index d94d34903d..0ab086bc1e 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -444,6 +444,29 @@ retained core capability (D2). recovery semantics from the unified controller/executor design. Required reads and source completeness remain binding. +A Worker launched by a built-in Host receives task requirements, scoped +authority, and the original read route. Todo-authoring CLI templates and the +ordinary delivery mode's quota spend instructions stay with the outer executor +in the complete captured contract, while standard Worker disposition conditions +for owner-only blockers and one-segment execution are delivered through checked +prompt guidance (custom rules and non-ordinary modes keep original rule text). Work, repair, and stop conditions remain +available to the Worker. Unconfigured memory recall and empty pre-turn +observations expose their current scoped status in this view. Their full +receipts stay in the original capture, with observations, failures, required +reads and unfamiliar data still delivered when present. + +Work context carries the selected task, scoped User Todos and their read +provenance. For both registered Todo read formats, the field dictionary stays +with the canonical Todo reader. Existing captures remain available under +their original digests. + +An ordinary admitted task presents its work, scope and validation to the Worker. +Matching ready lease preparations stay with launch and settlement. Unready, +inconsistent and unfamiliar preparations remain visible. +Operators read release readiness and completed-work maintenance through +quota/status or the original capture. Task context omits these maintenance +directions. + Context reuse must be invalidated by relevant source/requirement revisions, session generation changes, compaction or lost acknowledgements. A smaller packet cannot be treated as proof the executor has the prior context. Recover diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md index 5d39b8c7c1..05c8bec0c2 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -307,6 +307,22 @@ capability 包直接采用现有 `extension.toml` 契约,不做扩展。唯一 4. **提供上下文:** 为所选工作和 executor 渲染现有受治理工作契约,复用统一 Controller/Executor 设计的首次完整、后续差量与恢复语义。Required reads 和来源完整性仍有约束力。 +内置 Host 启动的 Worker 收到任务要求、权限范围和原始依据的读取路径。Todo 写入命令模板 +和普通执行模式的扣额说明留在外层执行器持有的完整 capture 中,标准工作段与所有者阻塞时 +的 Worker 报告及独立继续要求则经由已校验来源投影保留给 Worker(自定义规则及非普通模式 +保留原规则原文)。Worker 仍能读取工作、 +修复和停止条件。未配置的记忆召回和没有结果的启动前观察只向 Worker 提供带作用域的 +当前状态,完整回执留在原始 capture 中。有实际结果、失败、必读材料或未知字段时, +Worker 仍会收到对应内容。 + +工作上下文携带选中的任务、作用域内的 User Todo 和读取依据。两种已登记的 Todo 读取 +格式都把字段表留在 canonical Todo 读取入口。已有 capture 仍可按原摘要读取。 + +普通任务准入后,Worker 收到当前任务、范围与验证要求。完全一致的就绪租约记录留在 +启动和结算入口,未就绪、有差异或格式未知的记录仍在任务视图中可见。 +操作方通过 quota/status 或原始 capture 读取发布资格和已完成工作的维护提醒。 +任务上下文省略这些维护指令。 + 相关来源/要求版本变化、Session generation 变化、compaction 或 ACK 丢失时,必须使上下文复用失效。 不能因为 packet 更小,就认为 executor 已掌握前文。连续性未知时走所属契约的恢复路径。 Capability 指令仅在适用时提供;authority 不能从 prompt 文字推导。 diff --git a/docs/reference/protocols/loopx-turn-v0.md b/docs/reference/protocols/loopx-turn-v0.md index 9132cc8865..bc7a30a60f 100644 --- a/docs/reference/protocols/loopx-turn-v0.md +++ b/docs/reference/protocols/loopx-turn-v0.md @@ -101,6 +101,40 @@ the effect projection, scheduler/automation execution data and `interaction_contract.cli_channel` remain with the outer executor. The model view resolves existing replan authoring and Explore guidance references before hiding their outer owner, preserving the original scalar values and text. +Operators can read release readiness and completed Todo archive warnings in +quota/status and the original capture. The built-in Worker view omits these +maintenance directions. +Recognized unconfigured recall keeps its Goal, Agent and disabled status. +Known empty pre-turn observations keep their hook, capability and status. +The full readbacks stay with the executor. Available context, failed +observations, required reads and extended readbacks reach the Worker intact. +Work-context delivery keeps scoped Todo records, their provider revision and +record digest. The canonical Todo reader supplies the field dictionary for +both registered read formats. Unknown formats retain their supplied metadata. +For ordinary admitted work, matching recognized ready lease preparations stay +with the launcher and settlement reader. The Worker retains the admitted task, +scope, required reads and validation conditions. Unready, differing and +extended preparations stay in the task view. +When admitted `steering_audit_then_one_step` carries the standard mixed +accounting clause, that clause stays with the executor and the TypeScript +source check enables the built-in work-segment guidance in the Worker prompt: +check direction, then choose the largest coherent work segment it can reliably +complete and verify given its capabilities, budget, admitted task, scope and +execution profile (`one_step` is a work segment, not a single operation, and a +Todo groups related steps toward one verifiable outcome). Unrecognized policy +text stays in the task view untouched without substituting that guidance, +because it can carry additional constraints. +When admitted ordinary work carries the standard owner-only blocker rule in +`todo_write_hint`, command templates and queue section headings remain with the +outer executor while the TypeScript source check enables the Todo rules owner's +Worker disposition requirements in the prompt: report verified owner-only +blockers for `user_gate` even when noted in Next Action (non-blocking requests +belong in `user_action`), split mixed work and isolate the smallest blocked Todo, +give the owner the exact action and verification check, and continue runnable +independent work or identify a useful independent successor from Goal acceptance +before yielding. Custom `todo_write_hint.rule` text and non-ordinary turns +retain the original `rule` in `task_context` (still isolating CLI templates and +section headers) without substituting the built-in guidance. The model receives the original `source_decision_hash`, reader references and `source_schema_version`; that hash commits the original source, not the task view. Inline task context does not require a filesystem read of a private @@ -120,7 +154,27 @@ reader when needed. 范围、执行要求和未知新增信息。来源绑定、effect projection、scheduler/automation 执行数据及 `interaction_contract.cli_channel` 留在外层执行器。 来源中指向外层 owner 的 replan 编写和 Explore 指导引用在隐藏该 owner 前展开, -保留原始标量和文本。模型仍收到原始 +保留原始标量和文本。操作方在 quota/status 和原始 capture 中读取发布资格和已完成 +Todo 归档提醒。内置 Worker 视图省略这两条维护指令。能识别的未配置召回保留 +Goal、Agent 和停用状态。已知的空观察 +保留钩子、能力和状态。完整回执留在外层执行器。有可用上下文、观察失败、必需读取 +或扩展回执时,Worker 仍收到完整内容。工作上下文保留作用域内的 Todo、读取版本和记录摘要。 +两种已登记格式的字段表由 canonical Todo 读取入口提供,未知格式保留其元数据。 +普通任务准入后,完全一致且可识别的就绪租约记录留在启动和结算入口。Worker 保留已准入 +任务、范围、必需读取与验证条件。未就绪、有差异或带扩展字段的记录继续交付给 Worker。 +当获准执行的 `steering_audit_then_one_step` 携带标准混合扣额条款时,该条款 +留在执行器,由 TypeScript 来源校验开启内置提示中的工作段指导:先核对方向,再按 +自身能力、预算、已准入任务、范围和执行要求,选择能可靠完成并验证的最大连贯工作段 +(`one_step` 指一个工作段而非单次操作,同一可验证结果的相关操作归在一个 Todo)。 +无法识别的策略原文继续完整交付给 Worker 且不以该指导替代,因为它可能带有额外约束。 +当普通任务准入后的 `todo_write_hint` 携带标准所有者阻塞处置规则时,写入命令 +模板与队列标题留在外层执行器,TypeScript 来源校验通过 Todo 规则 owner 在内置 +Worker 提示中保留阻塞报告与继续工作的必要条件:确认属于所有者的阻塞时立即作为 +`user_gate` 报告(即使已在 Next Action 记述;非阻塞请求归入 `user_action`),拆分混合工作并 +隔离最小受阻 Todo,向所有者提供具体动作与验真检查,并在交还前继续独立可做的工作或从 +Goal acceptance 中识别独立后继;自定义 `todo_write_hint.rule` 文本及非普通模式保留原 +`rule`(同时继续隔离命令模板与标题)而不以内置提示替代。 +模型仍收到原始 `source_decision_hash`、reader 引用和 `source_schema_version`;该 hash 绑定原始 来源,不绑定任务视图。已内联的任务上下文不要求 sandbox 读取不可访问的私有 capture, 缺少必需证据仍暂停依赖该证据的工作。此呈现不是 adapter 请求,也不授予权限、结算或 diff --git a/loopx/control_plane/capability_hooks.ts b/loopx/control_plane/capability_hooks.ts index 2d531e18ab..6e32645d88 100644 --- a/loopx/control_plane/capability_hooks.ts +++ b/loopx/control_plane/capability_hooks.ts @@ -131,6 +131,10 @@ const TURN_START_RESULT_FIELDS = new Set([ "provider_payload_returned", "error_code", ]); +const TURN_START_OBSERVATION_FLAGS = [ + "agent_read_required", "external_reads_performed", "external_writes_performed", + "local_private_state_mutated", "private_content_returned", "provider_payload_returned", +]; const POST_WRITEBACK_REGISTRATION_FIELDS = new Set([ "schema_version", "hook_id", @@ -560,14 +564,7 @@ export function validateTurnStartHookInvocation(input: { if (observationCount < 0 || observationCount > 10_000) { throw new Error("turn-start hook observation_count is invalid"); } - for (const field of [ - "agent_read_required", - "external_reads_performed", - "external_writes_performed", - "local_private_state_mutated", - "private_content_returned", - "provider_payload_returned", - ]) { + for (const field of TURN_START_OBSERVATION_FLAGS) { const uncertainEffect = result[field] === null && ["failed", "partial", "unavailable"].includes(status) && ["external_reads_performed", "local_private_state_mutated"].includes(field); @@ -665,6 +662,29 @@ export function projectTurnStartUnavailableContext(value: unknown): JsonObject | }; } +/** Keep current empty/not-applicable observations visible without their effect receipts. */ +export function projectEmptyTurnStartObservations(value: unknown): JsonObject | null { + const dispatch = jsonObject(value); + if (!dispatch || Object.keys(dispatch).length !== 7 || + dispatch.schema_version !== "loopx_turn_start_capability_hook_dispatch_v1" || + dispatch.phase !== "turn_start" || !Array.isArray(dispatch.results) || + dispatch.registered_count !== dispatch.results.length || dispatch.invoked_count !== dispatch.results.length || + !Array.isArray(dispatch.required_reads) || dispatch.required_reads.length !== 0 || + !Array.isArray(dispatch.failures) || dispatch.failures.length !== 0) return null; + const results: JsonObject[] = []; + for (const raw of dispatch.results) { + const row = jsonObject(raw); + if (!row || Object.keys(row).length !== TURN_START_RESULT_FIELDS.size || + row.schema_version !== TURN_START_HOOK_RESULT_SCHEMA_VERSION || row.phase !== "turn_start" || + typeof row.hook_id !== "string" || typeof row.capability_id !== "string" || + (row.status !== "empty" && row.status !== "not_applicable") || + row.observation_count !== 0 || row.error_code !== null || + !TURN_START_OBSERVATION_FLAGS.every(flag => row[flag] === false)) return null; + results.push({hook_id: row.hook_id, capability_id: row.capability_id, status: row.status}); + } + return {results}; +} + export function validatePostWritebackHookRegistration( value: unknown, ): JsonObject & { diff --git a/loopx/control_plane/quota/context_delivery.ts b/loopx/control_plane/quota/context_delivery.ts index 84ba868418..6ed2004993 100644 --- a/loopx/control_plane/quota/context_delivery.ts +++ b/loopx/control_plane/quota/context_delivery.ts @@ -38,7 +38,8 @@ export function compactTodoContextSource(content: JsonObject): JsonObject { } const authority = jsonObject(content.authority_read); const model = jsonObject(authority?.todo_read_model); - if (model?.schema_version === COORDINATION_STATE_CONTRACT.todo_read_record.schema_version + if (model && (model.schema_version === COORDINATION_STATE_CONTRACT.todo_read_record.schema_version + || model.schema_version === COORDINATION_STATE_CONTRACT.todo_domain_record.schema_version) && Array.isArray(model.contract_fields) && model.contract_fields.every(field => typeof field === "string")) { const {contract_fields: _dictionary, ...metadata} = model; diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index ef365fe6f2..d63126e639 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -1,5 +1,7 @@ -import {isDeepStrictEqual} from "node:util"; -import { EXECUTION_PREPARATION_SCHEMA_VERSION } from "../work_items/execution_preparation.ts"; +import { isDeepStrictEqual } from "node:util"; +import { + EXECUTION_PREPARATION_SCHEMA_VERSION, isKnownReadyLeasePreparation, +} from "../work_items/execution_preparation.ts"; import { leaseEpoch } from "../work_items/task_lease_record.ts"; import { capturedContextSelection } from "./context_selection.ts"; import { @@ -36,7 +38,7 @@ import { settlementIdentityFromPlan, settlementIdentityPayload, type JsonObject, } from "../effect_program.ts"; import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; -import { projectTurnStartUnavailableContext } from "../capability_hooks.ts"; +import { projectEmptyTurnStartObservations, projectTurnStartUnavailableContext } from "../capability_hooks.ts"; import { jsonObject, pythonString, requireBoolean, requireJsonObject, requireNonEmptyString, requireStringLiteral, sourceNumberTokens, @@ -822,19 +824,128 @@ export function completeHostSource(request: JsonObject): {decision: JsonObject; return {decision, projection}; } +/** Collapse the unconfigured recall readback. Known active, failed and extended + * records still carry their full context. This only classifies presentation. */ +function disabledRewardMemoryView(value: unknown): JsonObject | null { + const readback = jsonObject(value); + const experiment = jsonObject(readback?.experiment); + const route = jsonObject(experiment?.config_runtime_route); + if (!readback || readback.status !== "disabled" || !experiment || !route || + typeof readback.goal_id !== "string" || typeof readback.agent_id !== "string" || + typeof route.registry_role !== "string" || typeof route.runtime_scope !== "string" || + !Array.isArray(experiment.host_coverage)) return null; + const coverage = experiment.host_coverage; + if (!coverage.every(value => { + const host = jsonObject(value); + return host && Object.keys(host).length === 3 && typeof host.host_id === "string" && + typeof host.automatic_recall === "string" && typeof host.automatic_ingest === "string"; + })) return null; + const {goal_id, agent_id, status} = readback; + const expected = { + schema_version: "agent_turn_recall_v0", ok: true, status, goal_id, agent_id, + surface_id: "agent_workflow.turn_admission", host_wiring: "agent_turn_admission", + reason_code: null, context: null, automatic_recall: false, provider_call_count: 0, + fail_open: true, provider_failure_is_user_gate: false, grants_new_action_authority: false, + quota_spend_performed: false, external_writes_performed: false, suppress_external_sinks: true, + experiment: { + schema_version: "reward_memory_experiment_status_v1", ok: true, status, goal_id, agent_id, + experimental: false, enabled: false, available: false, configured_for_agent: false, + config_pointer_registered: false, automatic_ingest: false, automatic_recall: false, + fail_open: true, external_writes_performed: false, host_coverage: coverage, + config_runtime_route: { + schema_version: "reward_memory_config_runtime_route_v0", registry_source: "invoked_registry", + registry_role: route.registry_role, runtime_scope: route.runtime_scope, goal_source: "registry.goals", + config_source: "goal_repo_relative_config_pointer", readback_status: "not_attempted", + exact_readback_verified: false, + }, + }, + }; + return isDeepStrictEqual(value, expected) ? {status, goal_id, agent_id} : null; +} + /** Task presentation is derived only after full-source validation. Keep task * facts (including unknown additions) and original scalar carriers intact; * scheduler/effect instructions remain with the outer executor. This view is * not a replacement source or a permission/settlement contract. */ +const STANDARD_ONE_STEP_SPEND_POLICY = + "append exactly one heartbeat spend only after scope-bounded work " + + "is validated and written back; one_step: mode, not an operation limit"; + +const STANDARD_TODO_WRITE_HINT_RULE = + "Verified owner-only blocker: add or reuse a user_gate this turn, even if noted " + + "in Next Action. Split mixed work; link the smallest blocked Todo. Give the owner " + + "the action and verification check. Before yielding, reuse a runnable independent " + + "Todo or check Goal acceptance for a useful independent successor to record. " + + "Settle any bound Turn, then rerun admission. Non-blocking requests use user_action."; + +function usesStandardOneStepWorkSegment(decision: JsonObject): boolean { + const heartbeat = object(decision.heartbeat_recommendation); + return decision.normal_delivery_allowed === true && + heartbeat.recommended_mode === "steering_audit_then_one_step" && + heartbeat.spend_policy === STANDARD_ONE_STEP_SPEND_POLICY; +} + +function usesStandardOwnerBlockerGuidance(decision: JsonObject): boolean { + const writeHint = object(decision.todo_write_hint); + return decision.normal_delivery_allowed === true && + decision.effective_action === EffectiveAction.NORMAL_RUN && + writeHint.rule === STANDARD_TODO_WRITE_HINT_RULE; +} + function hostModelContextChanges(decision: JsonObject): JsonObject { const context = {...decision}; + // Maintenance warnings are actionable in the operator's quota/status view. for (const field of ["schema_version", "contract_binding", "projection_envelope", "scheduler_hint", "automation_cadence_readback", "automation_liveness", - "scheduler_execution_context"]) { + "scheduler_execution_context", "promotion_readiness_warning", "completed_todo_archive_warning"]) { delete context[field]; } + // Todo-authoring CLI templates and queue headings stay with the outer executor. + // Strip the standard rule only for admitted ordinary work (replacing it with + // checked Worker disposition guidance); preserve custom or non-ordinary rules. + const writeHint = object(decision.todo_write_hint); + const hintCount = Object.keys(writeHint).length; + const removeWriteHintKeys = usesStandardOwnerBlockerGuidance(decision) + ? ["rule", "section", "agent_todo_command_template", + "user_action_command_template", "user_gate_command_template"] + : ["section", "agent_todo_command_template", + "user_action_command_template", "user_gate_command_template"]; + for (const key of removeWriteHintKeys) { + if (typeof writeHint[key] === "string") delete writeHint[key]; + } + const retainedHints = Object.keys(writeHint).length; + if (retainedHints !== hintCount) { + if (retainedHints) context.todo_write_hint = writeHint; + else delete context.todo_write_hint; + } + // Only the standard legacy rule has a known split: accounting stays with + // settlement, and the built-in renderers explain the work segment. Keep + // unfamiliar text intact; it can carry additional execution conditions. + if (usesStandardOneStepWorkSegment(decision)) { + const heartbeat = object(decision.heartbeat_recommendation); + delete heartbeat.spend_policy; + context.heartbeat_recommendation = heartbeat; + } + const emptyObservations = projectEmptyTurnStartObservations(decision.turn_start_capability_hook_dispatch); + if (emptyObservations) context.turn_start_capability_hook_dispatch = emptyObservations; + const disabledRecall = disabledRewardMemoryView(decision.reward_memory_recall); + if (disabledRecall) context.reward_memory_recall = disabledRecall; const interaction = {...object(decision.interaction_contract)}; const agent = object(interaction.agent_channel); + // Start and settlement use the original preparation. Keep unfamiliar + // records and disagreements visible even when the rest of the task is ready. + const preparation = agent.execution_preparation; + if (decision.ok === true && decision.should_run === true && + decision.normal_delivery_allowed === true && decision.effective_action === EffectiveAction.NORMAL_RUN && + agent.must_attempt === true && agent.delivery_allowed === true && object(agent.work_context).complete === true && + object(interaction.user_channel).action_required === false && decision.replan_action_packet == null && + object(decision.goal_boundary).handoff_mode === "hard_lease" && + isKnownReadyLeasePreparation(preparation, object(decision.agent_identity).agent_id, selectedWorkTodoId(decision)) && + isDeepStrictEqual(decision.execution_preparation, preparation) && + isDeepStrictEqual(object(interaction.cli_channel).execution_preparation, preparation)) { + delete context.execution_preparation; + delete agent.execution_preparation; + } // The complete source may share task authoring/evidence with its effect // owner. Resolve those existing references before omitting that owner. if (Object.hasOwn(agent, "work_context")) interaction.agent_channel = {...agent, @@ -1698,6 +1809,8 @@ export function evaluateTurnEnvelope(value: unknown): JsonObject { return {primary_action: primaryAction, replan_admitted: replanPacket !== null, checkpointed_write_approval: checkpointedBoundaryAuthority(object(decision.goal_boundary)) !== null, execution_profile_present: Object.keys(object(decision.execution_profile)).length > 0, + ordinary_work_segment_guidance: usesStandardOneStepWorkSegment(decision), + owner_blocker_guidance: usesStandardOwnerBlockerGuidance(decision), ...(request.include_model_context === true ? {model_context_schema_version: "loopx_turn_model_context_v0", model_context_changes: hostModelContextChanges(decision)} : {}), diff --git a/loopx/control_plane/todos/write_hint.py b/loopx/control_plane/todos/write_hint.py index 7780d6481c..0ccccfa132 100644 --- a/loopx/control_plane/todos/write_hint.py +++ b/loopx/control_plane/todos/write_hint.py @@ -1,17 +1,47 @@ from __future__ import annotations +from collections.abc import Mapping from typing import Any +STANDARD_TODO_WRITE_HINT_RULE = ( + "Verified owner-only blocker: add or reuse a user_gate this turn, even if noted " + "in Next Action. Split mixed work; link the smallest blocked Todo. Give the owner " + "the action and verification check. Before yielding, reuse a runnable independent " + "Todo or check Goal acceptance for a useful independent successor to record. " + "Settle any bound Turn, then rerun admission. Non-blocking requests use user_action." +) + +# Non-command Worker disposition requirements preserved when standard Todo CLI +# authoring rules remain with the outer executor. +WORKER_OWNER_BLOCKER_DISPOSITION_RULE = ( + "Verified owner-only blocker: report it for a user_gate even if noted in Next Action; " + "non-blocking requests belong in user_action. Split mixed work, isolate the smallest " + "blocked Todo, and give the owner the exact blocking action and verification check. " + "Before yielding, continue runnable independent work or identify a useful independent " + "successor from Goal acceptance; the outer executor records Todos, settles the Turn, " + "and reruns admission." +) + + +def worker_owner_blocker_instruction(source: bool | Mapping[str, Any] | None) -> str: + """Return built-in Worker owner-blocker rules only when TS validated them.""" + if isinstance(source, bool): + enabled = source + elif isinstance(source, Mapping): + flag = ( + source["_owner_blocker_guidance"] + if "_owner_blocker_guidance" in source + else source.get("owner_blocker_guidance") + ) + enabled = flag is True + else: + return "" + return WORKER_OWNER_BLOCKER_DISPOSITION_RULE if enabled else "" + def build_todo_write_hint(goal_id: str) -> dict[str, str]: return { - "rule": ( - "Verified owner-only blocker: add or reuse a user_gate this turn, even if noted " - "in Next Action. Split mixed work; link the smallest blocked Todo. Give the owner " - "the action and verification check. Before yielding, reuse a runnable independent " - "Todo or check Goal acceptance for a useful independent successor to record. " - "Settle any bound Turn, then rerun admission. Non-blocking requests use user_action." - ), + "rule": STANDARD_TODO_WRITE_HINT_RULE, "user_gate_command_template": ( f"loopx todo add --goal-id {goal_id} --role user " "--task-class user_gate --blocks-agent " diff --git a/loopx/control_plane/turn_driver/codex_cli.py b/loopx/control_plane/turn_driver/codex_cli.py index 5bdf56615f..afd925f302 100644 --- a/loopx/control_plane/turn_driver/codex_cli.py +++ b/loopx/control_plane/turn_driver/codex_cli.py @@ -446,8 +446,23 @@ def _render_prompt(request: Mapping[str, Any], *, checked: Mapping[str, Any] | N 'completed_phases must be exactly ["host_execute","typed_result"], and turn_key must match the request.', ] if complete: - from .host_candidate import TURN_EXECUTION_BOUNDARY_RULE, goal_acceptance_prompt_instruction + from ..todos.write_hint import worker_owner_blocker_instruction + from .host_candidate import ( + TURN_EXECUTION_BOUNDARY_RULE, + goal_acceptance_prompt_instruction, + ordinary_work_segment_instruction, + ) + owner_blocker = worker_owner_blocker_instruction( + checked is not None and checked.get("owner_blocker_guidance") is True + ) + if owner_blocker: + instructions.insert(2, owner_blocker) + work_segment = ordinary_work_segment_instruction( + checked is not None and checked.get("ordinary_work_segment_guidance") is True + ) + if work_segment: + instructions.insert(2, work_segment) instructions.insert(2, "Read the supplied task_context before dependent work. " "The host has validated the complete original observation and derived this task view. " diff --git a/loopx/control_plane/turn_driver/host_candidate.py b/loopx/control_plane/turn_driver/host_candidate.py index 21eb004f7b..339c87eb26 100644 --- a/loopx/control_plane/turn_driver/host_candidate.py +++ b/loopx/control_plane/turn_driver/host_candidate.py @@ -154,6 +154,8 @@ def extract_turn_authority( return {**decision, "primary_action": primary_action, "execution_profile": _mapping(decision.get("execution_profile")), "replan_action_packet": decision.get("replan_action_packet") if checked["replan_admitted"] else None, + "_ordinary_work_segment_guidance": checked.get("ordinary_work_segment_guidance") is True, + "_owner_blocker_guidance": checked.get("owner_blocker_guidance") is True, "_work_identity": dict(checked["work_identity"]), **({"_session_lineage": dict(checked["session_lineage"])} if include_session_lineage else {}), "_model_input": projected_host_model_input(request, checked)} @@ -321,6 +323,30 @@ def render_dsh_host_prompt(request: Mapping[str, Any]) -> str | None: return render_prompt(extract_turn_authority(request)) +def ordinary_work_segment_instruction(source: bool | Mapping[str, Any] | None) -> str: + """Return built-in work-segment guidance only when TS replaced the standard rule.""" + if isinstance(source, bool): + enabled = source + elif isinstance(source, Mapping): + flag = ( + source["_ordinary_work_segment_guidance"] + if "_ordinary_work_segment_guidance" in source + else source.get("ordinary_work_segment_guidance") + ) + enabled = flag is True + else: + return "" + if not enabled: + return "" + return ( + "Check the direction first. one_step means one work segment, not one operation. " + "Within the admitted task, execution_profile, permissions and available budget, " + "prefer the largest coherent work segment you can reliably complete and verify with your capabilities. " + "Keep related steps toward the same verifiable outcome in one Todo. " + "Split work at independent outcomes or necessary dependency, approval or validation boundaries." + ) + + def render_prompt(authority: Mapping[str, Any], *, allow_completion: bool = False) -> str: """Wrap one signed Turn authority packet in a typed JSON result request. @@ -345,7 +371,19 @@ def render_prompt(authority: Mapping[str, Any], *, allow_completion: bool = Fals separators=(",", ":"), ) if model_input is not None: + from ..todos.write_hint import worker_owner_blocker_instruction + detail = _mapping(model_input.get("detail_ref")) + work_segment = ordinary_work_segment_instruction( + authority.get("_ordinary_work_segment_guidance") is True + ) + if work_segment: + work_segment += "\n" + owner_blocker = worker_owner_blocker_instruction( + authority.get("_owner_blocker_guidance") is True + ) + if owner_blocker: + owner_blocker += "\n" input_prompt = ( "You are executing one bounded LoopX-governed work segment.\n" "Use task_context for the admitted work. The outer executor retains " @@ -363,6 +401,8 @@ def render_prompt(authority: Mapping[str, Any], *, allow_completion: bool = Fals "The selected Todo summary is not its full requirements, and Todo " "completion cannot close the Goal. Use execution_profile to size and " "qualify work, including artifact, validation, outcome and degradation rules.\n" + f"{work_segment}" + f"{owner_blocker}" "For required additional detail, use detail_ref.full_decision from the " "saved original observation identified by detail_ref.captured_decision; " "verify Goal/Agent/Turn and source_decision_hash. Never re-enter admission " diff --git a/loopx/control_plane/work_items/execution_preparation.ts b/loopx/control_plane/work_items/execution_preparation.ts index a942b66431..48f0f73967 100644 --- a/loopx/control_plane/work_items/execution_preparation.ts +++ b/loopx/control_plane/work_items/execution_preparation.ts @@ -1,9 +1,11 @@ +import {isDeepStrictEqual} from "node:util"; import {HANDOFF_MODES} from "../coordination/handoff_mode_vocabulary.ts"; import {HANDOFF_MODE_RETIRED_REASON, retiredHandoffModeRejection} from "../coordination/handoff_mode_policy.ts"; import type {JsonObject} from "../effect_program.ts"; import {leaseEpoch} from "./task_lease_record.ts"; import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; import { + jsonObject, optionalNonEmptyString, requireBoolean, requireJsonObject, @@ -54,6 +56,32 @@ function claimAction(goalId: string, todoId: string, agentId: string): JsonObjec }; } +function readyLeasePreparation( + base: JsonObject, leaseProof: unknown, leaseEpochValue: unknown, +): JsonObject { + return {...base, state: "ready", delivery_allowed: true, + reason_code: "matching_active_task_lease", + // Capture the admitted generation once. Recovery must not borrow a replacement. + ...(leaseProof === undefined ? {} : {lease_proof: leaseProof, lease_epoch: leaseEpochValue})}; +} + +/** The Worker does not need the launcher's lease transaction record after admission. */ +export function isKnownReadyLeasePreparation( + value: unknown, agentId: unknown, todoId: string | null, +): boolean { + const record = jsonObject(value); + const proof = jsonObject(record?.lease_proof); + const key = proof?.idempotency_key, version = proof?.expected_version, epoch = record?.lease_epoch; + if (typeof agentId !== "string" || !agentId || !todoId || typeof key !== "string" || + !key || key !== key.trim() || typeof version !== "number" || + !Number.isSafeInteger(version) || version < 1 || + typeof epoch !== "number" || !Number.isSafeInteger(epoch) || epoch < 1) return false; + return isDeepStrictEqual(record, readyLeasePreparation({ + schema_version: EXECUTION_PREPARATION_SCHEMA_VERSION, + todo_id: todoId, agent_id: agentId, handoff_mode: "hard_lease", + }, {idempotency_key: key, expected_version: version}, epoch)); +} + /** Decide whether the selected Todo can execute under its current hard lease. * * This is a read-model decision. It never acquires a lease. A capable Host @@ -132,12 +160,7 @@ export function projectExecutionPreparation(value: unknown): JsonObject { reason_code: "active_lease_owned_by_other_agent", ...(owner ? {owner} : {}), reason: "The selected Todo has an active lease owned by another agent; do not take over its execution."}; } - return {...base, state: "ready", delivery_allowed: true, - reason_code: "matching_active_task_lease", - // Capture the admitted generation once. Recovery must not borrow a - // replacement lease after the original Host result was produced. - ...(active[0].lease_proof === undefined ? {} : - {lease_proof: active[0].lease_proof, lease_epoch: active[0].lease_epoch})}; + return readyLeasePreparation(base, active[0].lease_proof, active[0].lease_epoch); } const prior = leases[0]; diff --git a/skills/loopx-self-repair/references/repair-patterns.md b/skills/loopx-self-repair/references/repair-patterns.md index d5b664ec2c..0d7dea043e 100644 --- a/skills/loopx-self-repair/references/repair-patterns.md +++ b/skills/loopx-self-repair/references/repair-patterns.md @@ -251,6 +251,7 @@ teaches a reusable control-plane lesson. | `pr_review_proportionality_goal_drift` | A review approves after the latest bug is fixed and CI passes, while a coupled production mechanism still has unresolved ownership, default strategy or failure semantics; successive fixes grow the mechanism without establishing benefit. | Original caller outcome, immutable base/full head, existing owners, per-mechanism role/default/recovery, current maintainer direction, smallest repair and public verdict. | Scope-fit and a flat proportionality label describe reachability/cost but can omit the decisive architecture judgment. Re-review inherits an approval trajectory or leaves that judgment only in private evidence. | Reset from the original problem. Use `change_proportionality.architecture_assessment` to separate invariants, optional policy, provider IO and projections; justify owners/defaults against the target contract. Required simplification and material unknowns block approval despite a proportionate parent or green CI. Publish the decisive reason and useful current-PR boundary; reject fields that normalize to empty text while accepting ordinary formatting. Keep unaccepted preferences non-blocking; approve evidenced cohesive prerequisites without demanding the parent roadmap. Validate the real packet/checker with blocking and positive controls, and distinguish offline consistency from live model qualification. | | `pr_review_feature_gate_counterfactual_gap` | A review proves the feature-on path and approves an opt-in or default-off change, but users who never enable it still receive new schema requirements, prompt instructions, accepted inputs, persisted projections, scheduling decisions, or effects; scoped sub-agent behavior may also be published under a broader multi-agent protocol name. | Authoritative gate and default, identical disabled/enabled fixtures, pre-change disabled output, every shared changed builder or serializer, emitted schema/prompt/journal/effect differences, public protocol ids, actual actor lifecycle, and granted or excluded authority. | The review inferred whole-change isolation from the absence of one enabled topology or operation list, and treated broad protocol terminology as cosmetic even when it implied registered peers or durable coordination that the implementation did not grant. Feature-on tests then encoded the default-off leakage as expected behavior. | Require typed `default_off_isolation` and `authority_semantics` evidence for every code change, with explicit `not_applicable` only after checking scope. Trace all shared surfaces, run a paired feature-off/feature-on counterfactual, compare the disabled side with the pre-change contract, and block `not_isolated`, `misleading`, or `not_yet_proven`. Prefer established sub-agent/child terminology for ephemeral scoped execution and rename unshipped v0 protocols before compatibility cost accumulates. | | `slash_command_packet_projection_drift` | A slash command tool is called, but the agent pipes or summarizes its JSON into a narrow view such as `.summary` / `.review_sequence`, then ignores the packet's response contract, templates, evidence commands, or final-answer requirements. | Raw session tool calls, command stdout, slash-command catalog `agent_contract`, full CLI JSON packet, skill fallback instructions, final answer shape. | The agent treated the CLI as a queue/statistics helper instead of the authoritative interaction contract; key machine fields never entered model context. | Make the skill name the exact JSON command that preserves contract/template fields, add machine-readable `required_packet_fields_to_preserve`, forbid summary-only projection for the first pass, and cover the required fields with focused smoke tests. | +| `operator_maintenance_in_worker_context` | A bounded Worker receives commands to qualify the runtime for release or archive completed Todos. | The installed host's model input, original signed decision, direct quota/status readback and the command's actual owner. | The model view inherited operator maintenance directions from the complete decision. | Keep the warnings in the operator view and original capture. Test their absence from the built-in Worker view alongside retained task requirements, eligible work and receipt replay. | | `loop_surface_activation_gap` | A thread reports LoopX setup success because `register-agent` or `quota should-run --agent-id` works, but no Codex App heartbeat automation, Codex CLI `/goal`, or other host loop has been installed for that goal. | `upgrade-plan` / host-loop activation status, `$CODEX_HOME/automations/*/automation.toml`, generated `heartbeat-prompt`, target thread id, recent setup final answer, registry coordination fields. | The control-plane identity layer was treated as the host scheduler layer; setup success criteria stopped at registry/quota instead of proving `host_loop_activation.activated=true` or surfacing a concrete host-tool gate. | Project setup and agent registration must surface `host_loop_activation`; create/update the host loop from generated scoped `heartbeat-prompt`, or report the exact missing host capability. Do not claim "connected" as autonomous until the host loop is active. | | `codex_app_automation_toml_contract_gap` | A multiline Codex App heartbeat is visible under a permissive line reader, then disappears from upgrade or RRULE resolution after a standards-compliant TOML reader is introduced; prompts containing backslashes, quote delimiters, or escape-like text are common triggers. | Exact writer output, standard-library TOML readback, prompt digest/counts, manifest parse-error projection, and RRULE resolution before and after the reader change. | The writer interpolated arbitrary prompt text into a TOML basic string without serialization, while the old partial reader masked the invalid file and the strict reader's catch-and-skip path erased the difference between absent and malformed automation. | Treat writer and reader as one storage contract: encode every string through a TOML-safe serializer, parse with the standard library at all read sites, fail closed on malformed content, and expose bounded content-free parse diagnostics. Cover backslashes, embedded delimiters, line-ending escapes, exact prompt identity, and capped malformed-file reporting in the real writer-to-reader path. | | `scheduler_host_update_retry_loop` | The same App heartbeat repeatedly hangs or fails while applying the same recommended RRULE against the same observed host RRULE, including when active-work and monitor-wait targets alternate. | `scheduler_hint.app_automation`, persisted scheduler state, host RRULE observation, recent heartbeat history, host-tool timeout/failure. | Host update failure was treated as turn-local advice or persisted as one scalar, so a cadence phase change overwrote the previous failed pair and the next phase retried it. | Persist a bounded, expiring set of failed target/observed-host pairs with `failure_hint.cli_args`, retain the latest scalar only for compatibility, suppress every retained exact pair without ACK or spend, invalidate old-host entries when the observation changes, and clear the cache after a successful ACK. | diff --git a/tests/control_plane/host_process_fixture.py b/tests/control_plane/host_process_fixture.py index 36ca8c1c3a..5e8af02816 100644 --- a/tests/control_plane/host_process_fixture.py +++ b/tests/control_plane/host_process_fixture.py @@ -27,13 +27,65 @@ def assert_host_task_context(model_input, source): assert all(complete_summary[lane] == [] for lane in omitted), omitted source[key] = {field: value for field, value in complete_summary.items() if field not in omitted} outer_fields = {"schema_version", "contract_binding", "projection_envelope", "scheduler_hint", - "automation_cadence_readback", "automation_liveness", "scheduler_execution_context"} - assert set(context) == set(source) - outer_fields - for field in set(source) - outer_fields - {"interaction_contract"}: + "automation_cadence_readback", "automation_liveness", "scheduler_execution_context", + "promotion_readiness_warning", "completed_todo_archive_warning"} + expected = {field: value for field, value in source.items() if field not in outer_fields} + hints = expected.get("todo_write_hint") + if isinstance(hints, dict): + from loopx.control_plane.todos.write_hint import STANDARD_TODO_WRITE_HINT_RULE + + commands = {"section", "agent_todo_command_template", "user_action_command_template", + "user_gate_command_template"} + if (source.get("normal_delivery_allowed") is True + and source.get("effective_action") == "normal_run" + and hints.get("rule") == STANDARD_TODO_WRITE_HINT_RULE): + commands.add("rule") + retained = {k: v for k, v in hints.items() if k not in commands or not isinstance(v, str)} + if retained: + expected["todo_write_hint"] = retained + elif hints: + del expected["todo_write_hint"] + heartbeat = expected.get("heartbeat_recommendation") + if (source.get("normal_delivery_allowed") is True and isinstance(heartbeat, dict) + and heartbeat.get("recommended_mode") == "steering_audit_then_one_step" + and heartbeat.get("spend_policy") == ( + "append exactly one heartbeat spend only after scope-bounded work " + "is validated and written back; one_step: mode, not an operation limit" + )): + expected["heartbeat_recommendation"] = {k: v for k, v in heartbeat.items() if k != "spend_policy"} + observations = expected.get("turn_start_capability_hook_dispatch") + rendered_observations = context.get("turn_start_capability_hook_dispatch") + if isinstance(observations, dict) and isinstance(rendered_observations, dict) and set(rendered_observations) == {"results"}: + assert observations["failures"] == observations["required_reads"] == [] + assert all(row["status"] in {"empty", "not_applicable"} and row["observation_count"] == 0 + for row in observations["results"]) + expected["turn_start_capability_hook_dispatch"] = {"results": [ + {key: row[key] for key in ("hook_id", "capability_id", "status")} for row in observations["results"] + ]} + recall = expected.get("reward_memory_recall") + rendered_recall = context.get("reward_memory_recall") + if isinstance(recall, dict) and isinstance(rendered_recall, dict) and set(rendered_recall) == {"status", "goal_id", "agent_id"}: + assert recall["status"] == "disabled" and recall["context"] is None + assert recall["experiment"]["automatic_recall"] is recall["experiment"]["automatic_ingest"] is False + expected["reward_memory_recall"] = {key: recall[key] for key in ("status", "goal_id", "agent_id")} + interaction = {key: value for key, value in source["interaction_contract"].items() if key != "cli_channel"} + preparation = expected.get("execution_preparation") + if isinstance(preparation, dict) and "execution_preparation" not in context: + agent = interaction["agent_channel"] + assert preparation["state"] == "ready" and agent["delivery_allowed"] is True + assert preparation == agent["execution_preparation"] + assert preparation == source["interaction_contract"]["cli_channel"]["execution_preparation"] + assert preparation["todo_id"] == source["selected_todo"]["todo_id"] + del expected["execution_preparation"] + interaction["agent_channel"] = {key: value for key, value in agent.items() if key != "execution_preparation"} + assert set(context) == set(expected), { + "unexpected": sorted(context.keys() - expected.keys()), + "missing": sorted(expected.keys() - context.keys()), + } + for field in set(expected) - {"interaction_contract"}: assert json.dumps(context[field], sort_keys=True, ensure_ascii=False) == json.dumps( - source[field], sort_keys=True, ensure_ascii=False), field - interaction = source["interaction_contract"] - assert context["interaction_contract"] == {k: v for k, v in interaction.items() if k != "cli_channel"} + expected[field], sort_keys=True, ensure_ascii=False), field + assert context["interaction_contract"] == interaction if "source_decision_hash" in model_input: assert model_input["source_decision_hash"] == source["contract_binding"]["content_hash"] return context diff --git a/tests/control_plane/test_turn_host_decision_capture.py b/tests/control_plane/test_turn_host_decision_capture.py index e55884838f..8779081e10 100644 --- a/tests/control_plane/test_turn_host_decision_capture.py +++ b/tests/control_plane/test_turn_host_decision_capture.py @@ -1531,6 +1531,51 @@ def test_task_presentation_retains_unknown_values_and_source_gate(complete_host_ _prompt(changed) +@pytest.mark.parametrize(("mode", "custom_policy", "expects_segment_guidance"), [ + ("steering_audit_then_one_step", None, True), + ("steering_audit_then_one_step", "append once; one_step only for bounded readback", False), + ("monitor_quiet_until_material_transition", None, False), +]) +def test_task_presentation_keeps_task_and_stop_guidance_inside_control_records( + complete_host_request, mode, custom_policy, expects_segment_guidance, +): + from loopx.control_plane.quota.turn_envelope import build_turn_envelope, compose_turn_decision + from loopx.control_plane.turn_driver.codex_cli import _prompt + from loopx.control_plane.turn_driver.host_candidate import extract_turn_authority, render_prompt + + request, original = complete_host_request + source = {key: value for key, value in original.items() if key not in {"schema_version", "contract_binding"}} + source["todo_write_hint"] = { + **source["todo_write_hint"], "task_evidence": {"instruction": "Read the result artifact before reporting."}, + } + heartbeat = {**source["heartbeat_recommendation"], "recommended_mode": mode, "stop_if_unchanged": True} + if custom_policy is not None: + heartbeat["spend_policy"] = custom_policy + source["heartbeat_recommendation"] = heartbeat + source["execution_obligation"] = { + **source["execution_obligation"], "spend_policy": "Hold dependent work until the pending evidence is verified.", + } + contract = compose_turn_decision(source) + request = {**request, "work_contract": contract, "turn_envelope": build_turn_envelope(contract)} + codex_prompt = _prompt(request) + structured_prompt = render_prompt(extract_turn_authority(request)) + codex_task = json.loads(codex_prompt.split("Turn request:\n", 1)[1])["task_context"] + structured_model, _ = json.JSONDecoder().raw_decode(structured_prompt.split("Turn request:\n", 1)[1]) + assert codex_task == structured_model["task_context"] + task = codex_task + assert task["todo_write_hint"] == {"task_evidence": source["todo_write_hint"]["task_evidence"]} + assert task["heartbeat_recommendation"]["stop_if_unchanged"] is True + assert task["execution_obligation"] == source["execution_obligation"] + policy = source["heartbeat_recommendation"]["spend_policy"] + assert contract["heartbeat_recommendation"]["spend_policy"] == policy + if expects_segment_guidance: + assert "spend_policy" not in task["heartbeat_recommendation"] + else: + assert task["heartbeat_recommendation"]["spend_policy"] == policy + for rendered in (codex_prompt, structured_prompt): + assert ("one_step means one work segment, not one operation." in rendered) is expects_segment_guidance + + def test_task_view_resolves_authoring_and_explore_before_hiding_effects(complete_host_request): from copy import deepcopy from loopx.control_plane.quota.turn_envelope import build_turn_envelope, compose_turn_decision diff --git a/tests/control_plane/test_work_context_host_delivery.py b/tests/control_plane/test_work_context_host_delivery.py index abe81724f9..3c3e217a28 100644 --- a/tests/control_plane/test_work_context_host_delivery.py +++ b/tests/control_plane/test_work_context_host_delivery.py @@ -79,6 +79,9 @@ def test_policy_observer_reads_original_signed_capture_after_todo_references(tmp @pytest.mark.parametrize('provider', ['file', 'sqlite']) @pytest.mark.parametrize('repetitions', [1, 40]) def test_authored_requirements_survive_capture_projection_and_host(tmp_path, monkeypatch, provider, repetitions): + from loopx.control_plane.quota.turn_envelope import bind_turn_decision_capture + from loopx.control_plane.todos.completed_archive import DEFAULT_MAX_ACTIVE_DONE_TODOS_BEFORE_ARCHIVE + isolate_sqlite_runtime(tmp_path, monkeypatch) project, runtime, registry = _write_fixture(tmp_path) state = _configure_read_only_todo(project) @@ -91,7 +94,14 @@ def test_authored_requirements_survive_capture_projection_and_host(tmp_path, mon '- [ ] [P1] Validate and settle the selected delivery.', f'- [ ] [P1] {task}', ).replace('## Next Action', f'## Acceptance\n\n{goal}\n\n## Next Action') # Author only disposable source input, before creating canonical authority. - state.write_text(authored.replace(' -->', f' note={quote(note, safe="")} -->'), encoding='utf-8') + completed = DEFAULT_MAX_ACTIVE_DONE_TODOS_BEFORE_ARCHIVE + 1 + completed_inputs = ''.join( + f'- [x] [P2] Verify historical artifact {index}.\n' + f' \n' + for index in range(completed) + ) + state.write_text(authored.replace(' -->', f' note={quote(note, safe="")} -->') + completed_inputs, + encoding='utf-8') todos = read_fixture_todos(state) source_task = next(item for item in todos if item['todo_id'] == TODO_ID) # The fixture helper returns an attention view. Seed the canonical record @@ -111,7 +121,11 @@ def test_authored_requirements_survive_capture_projection_and_host(tmp_path, mon saved = capture / 'decision.json' original_bytes = saved.read_bytes() full = json.loads(original_bytes) - assert emitted == full + assert emitted == full and full['schema_version'] == 'loopx_turn_envelope_v1' + promotion = full['promotion_readiness_warning'] + assert promotion['freshness_status'] == 'missing' and promotion['requires_readiness_run'] is True + archive = full['completed_todo_archive_warning'] + assert archive['active_done_count'] == completed and archive['requires_archive'] is True source_context = full['interaction_contract']['agent_channel']['work_context'] assert source_context['complete'] is True assert source_context['instruction'] # Non-vacuous instruction transport. @@ -161,6 +175,9 @@ def test_authored_requirements_survive_capture_projection_and_host(tmp_path, mon assert task_detail['note'] == note delivered_task = task_detail.get('text', authority['selected_todo']['text']) assert delivered_task == source_task['text'] + # The current capture delivers the complete Goal inline. Keep the separate + # acceptance text and avoid making the Worker read the same file twice. + assert source_by_kind['goal_state']['full_source'] is True assert goal in source_by_kind['goal_state']['text'] assert all(item['source'] != 'goal_state' for item in authority['required_reads']) # The actual Host prompt must contain the independent source requirements, @@ -199,9 +216,51 @@ def test_authored_requirements_survive_capture_projection_and_host(tmp_path, mon plan = build_loopx_turn_plan(altered, host='generic-cli', execution_mode='isolated-headless') assert plan['route']['kind'] == 'contract_error' assert plan['route']['would_invoke_host'] is False + plan = build_loopx_turn_plan(full, host='generic-cli', execution_mode='isolated-headless', + turn_instance_id=TURN_ID) + request = build_loopx_turn_host_request(plan) + assert request['work_contract'] == full + request.update(bind_turn_decision_capture( + full, captured_decision_path=str(saved), turn_instance_id=TURN_ID, turn_key=request['turn_key'], + complete_host_request={key: request[key] for key in ('schema_version', 'turn_key', 'source_decision_hash')}, + )) + structured = render_prompt(extract_turn_authority(request)) + codex_prompt = _prompt(request) + for prompt in (structured, codex_prompt): + assert promotion['message'] not in prompt + assert archive['archive_command_template'] not in prompt + assert 'one_step means one work segment' not in prompt + assert 'isolate the smallest blocked Todo' in prompt + assert 'Verified owner-only blocker: report it for a user_gate' in prompt + assert 'loopx todo add' not in prompt + model_input, _ = json.JSONDecoder().raw_decode(structured.split('Turn request:\n', 1)[1]) + codex_input = json.loads(codex_prompt.split('Turn request:\n', 1)[1]) + assert model_input == codex_input + worker = assert_host_task_context(model_input, full) + assert worker['heartbeat_recommendation']['spend_policy'] == full['heartbeat_recommendation']['spend_policy'] + assert 'todo_write_hint' not in worker + assert worker["reward_memory_recall"] == {"status": "disabled", "goal_id": GOAL_ID, "agent_id": AGENT_ID} + full_dispatch = full["turn_start_capability_hook_dispatch"] + assert full_dispatch["results"] and full_dispatch["registered_count"] >= 1 + assert worker["turn_start_capability_hook_dispatch"] == {"results": [ + {key: row[key] for key in ("hook_id", "capability_id", "status")} for row in full_dispatch["results"] + ]} + worker_context = worker['interaction_contract']['agent_channel']['work_context'] + worker_sources = {source['source']: source['content'] for source in worker_context['sources']} + primary = worker_sources['selected_todo']['todo'] + assert primary['note'] == note + assert primary.get('text', worker['selected_todo']['text']) == source_task['text'] + assert goal in worker_sources['goal_state']['text'] + if repetitions == 1: + _assert_one_step_spend_policy_parity(full) + _assert_owner_blocker_rule_parity(full) + if provider == "sqlite" and repetitions == 1: + _assert_optional_readbacks_survive_when_relevant(full) receipts = _heartbeat_receipt_count(runtime, TURN_ID) code, ordinary = _run_cli(registry, runtime, *args) assert code == 0, ordinary + assert ordinary['promotion_readiness_warning'] == promotion + assert ordinary['completed_todo_archive_warning'] == archive ordinary_context = ordinary['interaction_contract']['agent_channel']['work_context'] assert ordinary_context['instruction'] == source_context['instruction'] ordinary_task = next(source['content']['todo'] for source in ordinary_context['sources'] @@ -215,6 +274,186 @@ def test_authored_requirements_survive_capture_projection_and_host(tmp_path, mon assert saved.read_bytes() == original_bytes +def _assert_one_step_spend_policy_parity(full): + """Standard steering_audit_then_one_step moves spend_policy out; custom keeps it.""" + from loopx.control_plane.quota.turn_envelope import compose_turn_decision + from loopx.control_plane.turn_driver.host_candidate import ( + ordinary_work_segment_instruction, + render_dsh_host_prompt, + ) + + standard_policy = ( + "append exactly one heartbeat spend only after scope-bounded work " + "is validated and written back; one_step: mode, not an operation limit" + ) + custom_policy = "append once; keep the unfamiliar limit after readback" + for policy, expects_guidance, extra_fields in ( + (standard_policy, True, {}), + (custom_policy, False, {}), + ( + custom_policy, + False, + { + "ordinary_work_segment_guidance": True, + "_ordinary_work_segment_guidance": True, + }, + ), + ): + source = copy.deepcopy({key: value for key, value in full.items() if key not in {"schema_version", "contract_binding"}}) + source["heartbeat_recommendation"] = { + **source["heartbeat_recommendation"], + "recommended_mode": "steering_audit_then_one_step", + "spend_policy": policy, + } + for key, value in extra_fields.items(): + source[key] = value + decision = compose_turn_decision(source) + plan = build_loopx_turn_plan(decision, host="generic-cli", execution_mode="isolated-headless", + turn_instance_id=TURN_ID) + request = build_loopx_turn_host_request(plan) + authority = extract_turn_authority(request) + assert (authority.get("_ordinary_work_segment_guidance") is True) is expects_guidance + assert bool(ordinary_work_segment_instruction(authority)) is expects_guidance + structured = render_prompt(authority) + dsh_prompt = render_dsh_host_prompt(request) + codex_prompt = _prompt(request) + assert dsh_prompt is not None + for rendered in (structured, dsh_prompt, codex_prompt): + assert ("one_step means one work segment, not one operation." in rendered) is expects_guidance + model_input, _ = json.JSONDecoder().raw_decode(structured.split("Turn request:\n", 1)[1]) + dsh_input, _ = json.JSONDecoder().raw_decode(dsh_prompt.split("Turn request:\n", 1)[1]) + codex_input = json.loads(codex_prompt.split("Turn request:\n", 1)[1]) + assert model_input == codex_input == dsh_input + task_heartbeat = model_input["task_context"]["heartbeat_recommendation"] + if expects_guidance: + assert "spend_policy" not in task_heartbeat + else: + assert task_heartbeat["spend_policy"] == custom_policy + for key, value in extra_fields.items(): + assert model_input["task_context"][key] == value + + +def _assert_owner_blocker_rule_parity(full): + """Ordinary standard blocker rules deliver Worker requirements without templates.""" + from loopx.control_plane.quota.turn_envelope import compose_turn_decision + from loopx.control_plane.todos.write_hint import ( + STANDARD_TODO_WRITE_HINT_RULE, + worker_owner_blocker_instruction, + ) + from loopx.control_plane.turn_driver.host_candidate import render_dsh_host_prompt + + custom_rule = "Custom blocker rule: record blocking verification and keep unrelated work active." + worker_rule = worker_owner_blocker_instruction(True) + for case_name, normal_delivery, effective_action, rule_text, extra_fields, expects_builtin in ( + ("normal", True, "normal_run", STANDARD_TODO_WRITE_HINT_RULE, {}, True), + ("custom_rule", True, "normal_run", custom_rule, {}, False), + ( + "custom_with_colliding_flags", + True, + "normal_run", + custom_rule, + {"owner_blocker_guidance": True, "_owner_blocker_guidance": True}, + False, + ), + ("non_ordinary_delivery_off", False, "normal_run", STANDARD_TODO_WRITE_HINT_RULE, {}, False), + ( + "non_ordinary_repair_with_colliding_flags", + True, + "control_plane_repair", + STANDARD_TODO_WRITE_HINT_RULE, + {"owner_blocker_guidance": True, "_owner_blocker_guidance": True}, + False, + ), + ): + source = copy.deepcopy({key: value for key, value in full.items() if key not in {"schema_version", "contract_binding"}}) + source["normal_delivery_allowed"] = normal_delivery + source["effective_action"] = effective_action + source["todo_write_hint"] = {**source["todo_write_hint"], "rule": rule_text} + for key, value in extra_fields.items(): + source[key] = value + decision = compose_turn_decision(source) + if normal_delivery: + plan = build_loopx_turn_plan(decision, host="generic-cli", execution_mode="isolated-headless", + turn_instance_id=TURN_ID) + request = build_loopx_turn_host_request(plan) + else: + request = { + "schema_version": "loopx_turn_host_request_v1", + "turn_key": f"sha256:{'a' * 64}", + "work_contract": decision, + "source_decision_hash": decision["contract_binding"]["content_hash"], + } + authority = extract_turn_authority(request) + assert (authority.get("_owner_blocker_guidance") is True) is expects_builtin, case_name + assert bool(worker_owner_blocker_instruction(authority)) is expects_builtin, case_name + structured = render_prompt(authority) + dsh_prompt = render_dsh_host_prompt(request) + codex_prompt = _prompt(request) + assert dsh_prompt is not None + for rendered in (structured, dsh_prompt, codex_prompt): + assert (worker_rule in rendered) is expects_builtin, case_name + for fragment in ( + "user_gate", + "user_action", + "smallest blocked Todo", + "action and verification check", + "continue runnable independent work", + ): + if expects_builtin: + assert fragment in rendered, (case_name, fragment) + for forbidden in ( + "loopx todo add", + source["todo_write_hint"]["user_gate_command_template"], + source["todo_write_hint"]["user_action_command_template"], + source["todo_write_hint"]["agent_todo_command_template"], + ): + assert forbidden not in rendered, (case_name, forbidden) + model_input, _ = json.JSONDecoder().raw_decode(structured.split("Turn request:\n", 1)[1]) + dsh_input, _ = json.JSONDecoder().raw_decode(dsh_prompt.split("Turn request:\n", 1)[1]) + codex_input = json.loads(codex_prompt.split("Turn request:\n", 1)[1]) + assert model_input == codex_input == dsh_input + task_context = assert_host_task_context(model_input, decision) + if expects_builtin: + assert "todo_write_hint" not in task_context + else: + assert task_context["todo_write_hint"] == {"rule": rule_text} + assert "section" not in task_context["todo_write_hint"] + for key, value in extra_fields.items(): + assert task_context[key] == value + assert decision["todo_write_hint"] == source["todo_write_hint"] + + +def _assert_optional_readbacks_survive_when_relevant(full): + from loopx.control_plane.quota.turn_envelope import compose_turn_decision + from loopx.control_plane.turn_driver.codex_cli import _prompt + from loopx.control_plane.turn_driver.driver import build_loopx_turn_plan + from loopx.control_plane.turn_driver.executor import build_loopx_turn_host_request + + for case in ("active", "failed", "extended"): + source = copy.deepcopy({key: value for key, value in full.items() if key not in {"schema_version", "contract_binding"}}) + recall = source["reward_memory_recall"] + dispatch = source["turn_start_capability_hook_dispatch"] + if case == "active": + recall["context"] = {"guidance": ["Use independent verification before reporting."]} + recall["automatic_recall"] = True + recall["experiment"].update(enabled=True, automatic_recall=True) + dispatch["results"][0].update(status="observed", observation_count=1, + readback={"summary_lines": ["A required artifact is available."]}) + elif case == "failed": + recall.update(status="runtime_unavailable", reason_code="runtime_unavailable") + dispatch["results"][0].update(status="unavailable", error_code="context_unavailable") + else: + recall["experiment"]["host_coverage"][0]["future_context"] = {"must_read": "captured evidence"} + dispatch["results"][0]["readback"] = {"future_context": {"must_read": "captured evidence"}} + decision = compose_turn_decision(source) + plan = build_loopx_turn_plan(decision, host="generic-cli", execution_mode="isolated-headless", + turn_instance_id=TURN_ID) + request = build_loopx_turn_host_request(plan) + model = json.loads(_prompt(request).split("Turn request:\n", 1)[1])["task_context"] + assert model["reward_memory_recall"] == recall, case + assert model["turn_start_capability_hook_dispatch"] == dispatch, case + + @pytest.mark.parametrize('provider', ['file', 'sqlite']) @pytest.mark.parametrize(('declaration', 'diagnostic'), [ ('version', 'unsupported complete Turn decision version'), diff --git a/tests/control_plane_ts/context_delivery.test.ts b/tests/control_plane_ts/context_delivery.test.ts index a08f0a485c..ab3cf44e91 100644 --- a/tests/control_plane_ts/context_delivery.test.ts +++ b/tests/control_plane_ts/context_delivery.test.ts @@ -701,6 +701,30 @@ test("cold-source title deduplication retains full body, distinct title and orig assert.strictEqual(compactTodoContextSource(distinct), distinct); }); +test("Todo context keeps live User gates and readback proof for both registered record formats", () => { + const todos = [{todo_id: "user-stop", text: "Wait for approval before publication.", future_detail: true}]; + const dictionary = ["todo_id", "text", "approval_state"]; + const readback = { + source_authority: "sqlite_v0", provider_revision: "revision-1", + decision_read_from_provider: true, legacy_fallback_used: false, + }; + for (const schema_version of ["loopx_todo_canonical_read_record_v0", "loopx_todo_domain_read_record_v0"]) { + const metadata = {schema_version, todo_count: 1, records_sha256: "a".repeat(64), future_proof: true}; + const source = {source: "sqlite_v0", todos, authority_read: {...readback, + todo_read_model: {...metadata, contract_fields: dictionary}}}; + assert.deepEqual(compactTodoContextSource(source), + {source: "sqlite_v0", todos, authority_read: {...readback, todo_read_model: metadata}}); + assert.deepEqual(source.authority_read.todo_read_model.contract_fields, dictionary); + } + for (const todo_read_model of [ + {schema_version: "future_todo_read_model", contract_fields: dictionary}, + {schema_version: "loopx_todo_domain_read_record_v0", contract_fields: ["todo_id", null]}, + ]) { + const source = {todos, authority_read: {...readback, todo_read_model}}; + assert.strictEqual(compactTodoContextSource(source), source); + } +}); + function evidenceContext(): JsonObject { return {complete: true, sources: [{source: "turn_start_capability_hook", kind: "explore_turn_context", hook_id: "explore.turn_context", capability_id: "explore", content: { diff --git a/tests/control_plane_ts/turn_envelope.test.ts b/tests/control_plane_ts/turn_envelope.test.ts index da3b87f10f..ee90250cfb 100644 --- a/tests/control_plane_ts/turn_envelope.test.ts +++ b/tests/control_plane_ts/turn_envelope.test.ts @@ -29,6 +29,8 @@ import { controllerRequest } from "../../loopx/control_plane/turn_driver/loop_co import {turnScopedCliSettlementPlan} from "../../loopx/control_plane/quota/settlement_plan.ts"; import {referenceVisionContinuation, requireVisionAuditReferences} from "../../loopx/control_plane/quota/turn_envelope_references.ts"; +import {EXECUTION_PREPARATION_FACTS_SCHEMA_VERSION, projectExecutionPreparation} + from "../../loopx/control_plane/work_items/execution_preparation.ts"; test("normal-work initial navigation stays scoped while other reads keep discovery", () => { const source = payload(); @@ -261,6 +263,9 @@ test("Host task presentation is source-checked and keeps task and backlog facts" payload_compaction: {schema_version: "quota_todo_summary_payload_compaction_v0", compacted_lanes: {gate_open_items: {shown: 0, total: 3}}}, }; + source.heartbeat_recommendation = {recommended_mode: "steering_audit_then_one_step", + spend_policy: "append exactly one heartbeat spend only after scope-bounded work " + + "is validated and written back; one_step: mode, not an operation limit; stop after the readback"}; const complete = evaluateTurnEnvelope({operation: "compose_complete", payload: source, scheduler_execution_args: ""}); const envelope = buildTurnEnvelope({payload: complete, scheduler_execution_args: ""}); const before = structuredClone(complete); @@ -270,6 +275,8 @@ test("Host task presentation is source-checked and keeps task and backlog facts" assert.deepEqual(evaluateTurnEnvelope({...request, include_model_context: false}), plain); const checked = evaluateTurnEnvelope({...request, include_model_context: true}); assert.equal(checked.model_context_schema_version, "loopx_turn_model_context_v0"); + assert.equal(checked.ordinary_work_segment_guidance, false); + assert.equal(checked.owner_blocker_guidance, false); const view = structuredClone(complete); const at = (root: unknown, path: (string | number)[]) => path.reduce((row, key) => (row as Record)[key], root); @@ -285,6 +292,7 @@ test("Host task presentation is source-checked and keeps task and backlog facts" backlog_items: [{todo_id: "later", text: "Required dependency."}], future_attention: [], }); assert.deepEqual(view.user_todo_summary, complete.user_todo_summary); + assert.deepEqual(view.heartbeat_recommendation, source.heartbeat_recommendation); assert.deepEqual(view.goal_boundary, complete.goal_boundary); assert.deepEqual((view.interaction_contract as JsonObject).agent_channel, (complete.interaction_contract as JsonObject).agent_channel); @@ -309,9 +317,103 @@ test("Host task presentation is source-checked and keeps task and backlog facts" const edits = (checked.model_context_changes as JsonObject).changes as JsonObject[]; assert.equal(edits.some(edit => (edit.path as string[])[0] === "agent_todo_summary"), false); } + const standardSource = {...source, heartbeat_recommendation: {recommended_mode: "steering_audit_then_one_step", + spend_policy: "append exactly one heartbeat spend only after scope-bounded work " + + "is validated and written back; one_step: mode, not an operation limit"}}; + for (const allowed of [true, false]) { + const captured = evaluateTurnEnvelope({operation: "compose_complete", + payload: {...standardSource, normal_delivery_allowed: allowed}, scheduler_execution_args: ""}); + const checked = evaluateTurnEnvelope({operation: "host_dispatch_context", payload: captured, include_model_context: true, + complete_host_request: {schema_version: "loopx_turn_host_request_v1", turn_key: `sha256:${"c".repeat(64)}`}}); + assert.equal(checked.ordinary_work_segment_guidance, allowed); + const edits = (checked.model_context_changes as JsonObject).changes as JsonObject[]; + assert.equal(edits.some(edit => + (edit.path as string[]).join(".") === "heartbeat_recommendation.spend_policy" && edit.remove === true), allowed); + } + const standardHint = { + rule: "Verified owner-only blocker: add or reuse a user_gate this turn, even if noted " + + "in Next Action. Split mixed work; link the smallest blocked Todo. Give the owner " + + "the action and verification check. Before yielding, reuse a runnable independent " + + "Todo or check Goal acceptance for a useful independent successor to record. " + + "Settle any bound Turn, then rerun admission. Non-blocking requests use user_action.", + section: "User Todo / Owner Review Reading Queue", + agent_todo_command_template: "loopx todo add --role agent --priority P1 --text ''", + user_action_command_template: "loopx todo add --role user --task-class user_action --text ''", + user_gate_command_template: "loopx todo add --role user --task-class user_gate --text ''", + task_evidence: {instruction: "Preserve extra task hint metadata."}, + }; + for (const [modeName, delivered, action, ruleText, expectsStandard] of [ + ["normal", true, "normal_run", standardHint.rule, true], + ["custom", true, "normal_run", "Custom owner-blocker policy: keep this verbatim.", false], + ["non_ordinary_delivery", false, "normal_run", standardHint.rule, false], + ["non_ordinary_action", true, "control_plane_repair", standardHint.rule, false], + ] as const) { + const captured = evaluateTurnEnvelope({operation: "compose_complete", payload: { + ...source, normal_delivery_allowed: delivered, effective_action: action, + todo_write_hint: {...standardHint, rule: ruleText}, + }, scheduler_execution_args: ""}); + const checked = evaluateTurnEnvelope({operation: "host_dispatch_context", payload: captured, include_model_context: true, + complete_host_request: {schema_version: "loopx_turn_host_request_v1", turn_key: `sha256:${"d".repeat(64)}`}}); + assert.equal(checked.owner_blocker_guidance, expectsStandard, modeName); + const view = structuredClone(captured); + const at = (root: unknown, path: (string | number)[]) => path.reduce((row, key) => + (row as Record)[key], root); + for (const edit of (checked.model_context_changes as JsonObject).changes as JsonObject[]) { + const path = edit.path as (string | number)[], key = path.at(-1)!; + const parent = at(view, path.slice(0, -1)) as Record; + if (edit.remove) delete parent[key]; + else parent[key] = edit.from ? at(captured, edit.from as (string | number)[]) : edit.value; + } + assert.deepEqual(view.todo_write_hint, expectsStandard + ? {task_evidence: standardHint.task_evidence} + : {rule: ruleText, task_evidence: standardHint.task_evidence}, modeName); + assert.equal((captured.todo_write_hint as JsonObject).user_gate_command_template, + standardHint.user_gate_command_template, modeName); + } assert.deepEqual(complete, before); }); +test("Worker omits a matching ready launch record and keeps unresolved or unfamiliar preparation", () => { + const ready = projectExecutionPreparation({ + schema_version: EXECUTION_PREPARATION_FACTS_SCHEMA_VERSION, + goal_id: "goal-turn-envelope", agent_id: "agent-ts", handoff_mode: "hard_lease", + authority_available: true, selected_todo: {todo_id: "todo-1", status: "open", claimed_by: "agent-ts"}, + leases: [{status: "active", active: true, owner: "agent-ts", + lease_proof: {idempotency_key: "bound-to-turn", expected_version: 2}}], + }); + for (const [name, preparation, cliPreparation, completeWork] of [ + ["current", ready, ready, true], + ["future field", {...ready, repair_instruction: "Wait for the verifier."}, + {...ready, repair_instruction: "Wait for the verifier."}, true], + ["other task", {...ready, todo_id: "todo-other"}, {...ready, todo_id: "todo-other"}, true], + ["different receipts", ready, {...ready, lease_proof: {idempotency_key: "new", expected_version: 3}}, true], + ["unresolved", {...ready, state: "claim_required"}, {...ready, state: "claim_required"}, true], + ["incomplete work", ready, ready, false], + ] as const) { + const source = payload(); + source.normal_delivery_allowed = true; + source.execution_preparation = preparation; + const interaction = source.interaction_contract as JsonObject; + const agent = interaction.agent_channel as JsonObject; + agent.execution_preparation = structuredClone(preparation); + agent.work_context = {complete: completeWork, sources: [], instruction: "Use the original task scope."}; + (interaction.cli_channel as JsonObject).execution_preparation = cliPreparation; + (source.goal_boundary as JsonObject).handoff_mode = "hard_lease"; + const captured = evaluateTurnEnvelope({operation: "compose_complete", payload: source, scheduler_execution_args: ""}); + const before = structuredClone(captured); + const model = evaluateTurnEnvelope({operation: "host_dispatch_context", payload: captured, + complete_host_request: {schema_version: "loopx_turn_host_request_v1", turn_key: `sha256:${"a".repeat(64)}`}, + include_model_context: true}); + const changes = (model.model_context_changes as JsonObject).changes as JsonObject[]; + for (const path of [["execution_preparation"], ["interaction_contract", "agent_channel", "execution_preparation"]]) { + const removal = changes.some(change => change.remove === true && + JSON.stringify(change.path) === JSON.stringify(path)); + assert.equal(removal, name === "current", name); + } + assert.deepEqual(captured, before); + } +}); + test("complete Host recovery preserves the existing driver route and hash preimage", () => { const complete = evaluateTurnEnvelope({operation: "compose_complete", payload: payload(), scheduler_execution_args: ""}); const envelope = buildTurnEnvelope({payload: complete, scheduler_execution_args: ""}); diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index 5ca7276c93..c10564cafe 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -973,6 +973,7 @@ def test_installed_core_rejects_unverified_artifact_without_settlement(core_pyth def test_installed_core_codex_prepares_only_an_admitted_valid_request(core_python, task, tmp_path, monkeypatch): + from tests.control_plane.host_process_fixture import assert_host_task_context from tests.test_loopx_turn_codex_cli import _fake_codex workspace, runtime, registry, _ = task @@ -985,7 +986,9 @@ def test_installed_core_codex_prepares_only_an_admitted_valid_request(core_pytho "--owner", AGENT, "--idempotency-key", lease["idempotency_key"], "--expected-version", str(lease["version"])], workspace) binary, log = _fake_codex(tmp_path) - binary.write_text(binary.read_text().replace('output_path = ', + binary.write_text(binary.read_text().replace("prompt = sys.stdin.read()", + 'prompt = sys.stdin.read()\npathlib.Path("worker-prompt.txt").write_text(prompt, encoding="utf-8")' + ).replace('output_path = ', 'pathlib.Path("squares.json").write_text(json.dumps([n*n for n in range(8)]))\noutput_path = ')) home = tmp_path / "codex-home" home.mkdir() @@ -1009,6 +1012,45 @@ def test_installed_core_codex_prepares_only_an_admitted_valid_request(core_pytho workspace, environment=environment).stdout) assert result["status"] == "committed" and result["validation"]["status"] == "passed", result assert json.loads((workspace / "squares.json").read_text()) == [0, 1, 4, 9, 16, 25, 36, 49] + prompt = (workspace / "worker-prompt.txt").read_text(encoding="utf-8") + instructions, task_context_json = prompt.split("Turn request:\n", 1) + assert "one_step means one work segment, not one operation" in instructions + assert "largest coherent work segment you can reliably complete and verify with your capabilities" in instructions + assert "same verifiable outcome in one Todo" in instructions + assert "dependency, approval or validation boundaries" in instructions + assert "isolate the smallest blocked Todo" in instructions + assert "exact blocking action and verification check" in instructions + assert "continue runnable independent work" in instructions + model_input = json.loads(task_context_json) + capture = Path(model_input["detail_ref"]["captured_decision"]["path"]) + original = json.loads(capture.read_text(encoding="utf-8")) + for field in ("agent_todo_command_template", "user_action_command_template", "user_gate_command_template"): + command_template = original["todo_write_hint"][field] + assert command_template.startswith("loopx todo add") + assert command_template not in prompt + assert original["promotion_readiness_warning"]["requires_readiness_run"] is True + spend_policy = original["heartbeat_recommendation"]["spend_policy"] + assert "append exactly one heartbeat spend" in spend_policy + assert "one_step: mode, not an operation limit" in spend_policy + assert "append exactly one heartbeat spend" not in prompt + captured_bytes = capture.read_bytes() + assert original["execution_preparation"]["lease_proof"]["expected_version"] > 0 + assert original["interaction_contract"]["cli_channel"]["execution_preparation"] == original["execution_preparation"] + model_task = model_input["task_context"] + assert "promotion_readiness_warning" not in model_task + assert "execution_preparation" not in model_task + assert "execution_preparation" not in model_task["interaction_contract"]["agent_channel"] + context = assert_host_task_context(model_input, original) + assert "todo_write_hint" not in context + assert "spend_policy" not in context["heartbeat_recommendation"] + assert context["execution_profile"] == original["execution_profile"] + users = context["interaction_contract"]["agent_channel"]["work_context"]["user_todos"] + model_proof = users["authority_read"]["todo_read_model"] + assert model_proof["schema_version"] == "loopx_todo_domain_read_record_v0" + assert model_proof["records_sha256"] and "contract_fields" not in model_proof + original_reader = json.loads(_run(core_python, [*prefix, "todo", "list", "--goal-id", GOAL, "--role", "user", + "--status", "open", "--agent-id", AGENT], workspace).stdout) + assert original_reader["authority_read"]["todo_read_model"]["contract_fields"] assert len(log.read_text().splitlines()) == 1 and _spends(runtime) == 1 resume_command = [item for index, item in enumerate(command) if item != "--todo-id" and (index == 0 or command[index - 1] != "--todo-id")] @@ -1031,3 +1073,4 @@ def test_installed_core_codex_prepares_only_an_admitted_valid_request(core_pytho assert model_input["source_decision_hash"] == original["contract_binding"]["content_hash"] assert replay["replayed"] is True and all(value is False for value in replay["effects"].values()) assert len(log.read_text().splitlines()) == 1 and _spends(runtime) == 1 + assert capture.read_bytes() == captured_bytes