From f94703ec5ae45ce239334c8f6965188f51a1feec Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:45:35 +0800 Subject: [PATCH 1/3] refactor(stride): make evidence_conditioned_v1 unconditional default and remove live switch Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../smoke/capability-configuration-smoke.ts | 78 +++--- .../src/data/capability-configuration.ts | 15 +- .../capability-localization.ts | 6 +- benchmark/edgebench/README.md | 34 ++- benchmark/edgebench/causal_attribution.py | 22 ++ benchmark/edgebench/export_report.py | 7 +- benchmark/edgebench/run.py | 11 +- benchmark/runtime/EXECUTION_OBSERVATIONS.md | 26 +- benchmark/runtime/harbor.py | 32 +-- benchmark/runtime/sforge.py | 12 +- .../tests/test_checkpoint_joint_receiver.py | 4 +- benchmark/tests/test_edgebench_report.py | 46 ++++ .../tests/test_native_checkpoint_handoff.py | 2 +- benchmark/tests/test_sforge_runtime.py | 56 +++- benchmark/tests/test_shared_codex_runtime.py | 52 +++- benchmark/tests/test_task_entry.py | 24 +- docs/quota-allocation.md | 15 +- .../goal-vision-replan-contract-v0.md | 71 ++--- .../autonomous-replan-obligation-smoke.py | 67 ++++- ...h-state-shared-runtime-projection-smoke.py | 17 +- .../replan-cadence.mjs | 64 ++--- examples/project/configure-goal-smoke.py | 3 +- .../goal-vision-refresh-state-budget-smoke.py | 18 +- loopx/capabilities/configuration_ui.py | 10 +- .../todo_replan_cadence/goal_configuration.py | 2 +- .../todo_replan_cadence/machine_defaults.py | 46 +++- loopx/chat/goal_configuration_api.py | 21 +- loopx/cli_commands/goal_amendment_proposal.py | 4 +- loopx/cli_commands/manager_inbox.py | 2 - .../cli_commands/project_lifecycle_inputs.py | 1 - loopx/cli_commands/registry_admin.py | 2 - .../cli_commands/registry_admin_configure.py | 9 - loopx/collaboration_mcp.py | 2 - loopx/configuration_catalog.py | 6 +- loopx/configure_goal.py | 3 - .../collaboration/request_amendment.py | 34 +-- .../goals/goal_amendment_runtime.py | 28 +- .../goals/goal_frontier/__init__.py | 11 +- .../goals/goal_frontier/ack_policy.py | 6 +- .../control_plane/goals/vision_checkpoint.py | 2 - .../control_plane/goals/vision_checkpoint.ts | 8 +- .../control_plane/host_adapter_settlement.py | 4 +- .../control_plane/quota/should_run_prepare.py | 5 +- .../control_plane/stride_strategy_schema.json | 3 +- .../work_items/lifecycle_recovery.py | 5 +- .../work_items/progress_observation.py | 13 +- .../work_items/replan_context.ts | 17 +- .../work_items/replan_context_codec.py | 5 - .../work_items/replan_history_codec.py | 2 - .../work_items/replan_semantics.ts | 38 ++- .../work_items/semantic_replan_writeback.py | 6 +- .../control_plane/work_items/stride_policy.ts | 12 +- .../work_items/stride_policy_codec.py | 7 + loopx/execution_profile.py | 15 +- loopx/goal_mode_mcp.py | 34 +-- loopx/presentation/goal_amendment_api.py | 10 +- loopx/presentation/request_control_api.py | 5 +- loopx/state_refresh.py | 4 - packages/loopx-jev/tests/test_closed_loop.py | 77 ++++-- .../loopx-jev/tests/test_identity_binding.py | 9 +- ...est_machine_configuration_goal_defaults.py | 251 +++++++++++------- tests/control_plane/replan_packet_fixture.py | 4 +- .../test_effective_turn_replan.py | 38 +-- .../test_final_outcome_diagnostics.py | 3 + .../test_goal_amendment_authority.py | 62 +++-- .../test_goal_amendment_proposal_lifecycle.py | 5 +- .../test_goal_frontier_replan_rules.py | 6 +- .../test_long_chain_projected_closeout.py | 3 +- .../test_material_feedback_checkpoint.py | 39 ++- .../test_outcome_replan_composition_cli.py | 54 ++-- .../test_quota_settlement_cli.py | 120 +++++---- .../test_receipt_next_action_cli.py | 5 +- .../test_refresh_state_replan_gate.py | 129 ++++++++- .../test_replan_context_evidence.py | 24 +- .../test_replan_context_order.py | 34 ++- .../test_replan_history_policy.py | 9 +- .../test_replan_host_context_projection.py | 21 +- .../test_replan_progress_native_cli.py | 69 ++++- .../control_plane/test_replan_staged_read.py | 65 +++-- .../test_replan_successor_guard_reentry.py | 4 +- .../test_replan_terminal_spend_ordering.py | 44 +-- .../test_replan_writeback_lease_scope.py | 29 +- .../test_request_amendment_recovery.py | 16 +- .../test_research_comparison_cli.py | 2 +- .../test_research_context_adoption.py | 3 +- .../test_research_execution_loop.py | 7 +- .../test_research_replan_basis_cli.py | 8 +- .../test_selection_replan_reentry.py | 37 ++- .../test_settlement_input_discovery_cli.py | 24 +- ...est_stride_comparison_followthrough_cli.py | 4 +- .../test_turn_todoless_settlement.py | 38 +-- .../test_vision_checkpoint_runtime.py | 1 - .../control_plane/test_work_yardstick_cli.py | 4 +- tests/control_plane_ts/progress_delta.test.ts | 23 +- tests/control_plane_ts/replan_context.test.ts | 6 +- .../control_plane_ts/replan_semantics.test.ts | 111 +++++--- .../stride_comparison_selection.test.ts | 14 +- .../stride_explore_pagination.test.ts | 10 +- tests/control_plane_ts/stride_policy.test.ts | 34 ++- tests/test_chat_goal_configuration_api.py | 1 - tests/test_chat_machine_configuration_api.py | 1 - tests/test_host_vision_recovery.py | 15 +- 102 files changed, 1496 insertions(+), 1031 deletions(-) diff --git a/apps/presentation/dashboard/smoke/capability-configuration-smoke.ts b/apps/presentation/dashboard/smoke/capability-configuration-smoke.ts index 9033ddff70..330b37f752 100644 --- a/apps/presentation/dashboard/smoke/capability-configuration-smoke.ts +++ b/apps/presentation/dashboard/smoke/capability-configuration-smoke.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; -import { changeStewardExecutorDraft, goalExploreEditorValue, goalExploreWriteValue, goalReplanCadenceEditorValue, goalReplanCadenceWriteValue, hasReplanCadenceOverride, goalStorageEditorValue, parseEditableCapabilityJson, projectEditableCapabilityConfiguration, replanCadenceEditorDefaults } from "../src/data/capability-configuration.js"; +import { changeStewardExecutorDraft, goalExploreEditorValue, goalExploreWriteValue, goalReplanCadenceEditorValue, goalReplanCadenceWriteValue, hasReplanCadenceOverride, goalStorageEditorValue, parseEditableCapabilityJson, projectEditableCapabilityConfiguration, replanCadenceEditorDefaults, replanCadenceEditorValue } from "../src/data/capability-configuration.js"; const exploreEditor = {fields: [{key: "mode"}, {key: "profile"}, {key: "composition_mode"}, {key: "composition_scope_id", nullable: true}]}; const exploreEffective = {mode: "planning", profile: "generic", composition_mode: "disabled", composition_scope_id: null}; @@ -40,53 +40,65 @@ const periodicReportEditor = { }; const storageEditor = { fields: [{ key: "new_goal_provider" }, { key: "canonical_creation" }, { key: "new_goal_handoff_mode" }] }; -const cadenceEditor = { fields: [{ key: "count_unit" }, { key: "count" }, { key: "stride_strategy" }] }; -const cadenceDefault = { count_unit: "effective_turns", count: 6, stride_strategy: "off" }; +const cadenceEditor = { fields: [{ key: "count_unit" }, { key: "count" }, { key: "planning_horizon_goal" }] }; +const cadenceDefault = { count_unit: "effective_turns", count: 6 }; assert.deepEqual(projectEditableCapabilityConfiguration(cadenceEditor, - { stride_strategy: "evidence_conditioned_v1" }, - replanCadenceEditorDefaults({ count_unit: "effective_turns", count: 3, stride_strategy: "off" }, cadenceDefault)), - { count_unit: "effective_turns", count: 3, stride_strategy: "evidence_conditioned_v1" }, + { planning_horizon_goal: false }, + replanCadenceEditorDefaults({ count_unit: "effective_turns", count: 3 }, cadenceDefault)), + { count_unit: "effective_turns", count: 3, planning_horizon_goal: false }, "a sparse JSON draft returning to the form preserves the effective review interval"); assert.deepEqual(projectEditableCapabilityConfiguration(cadenceEditor, { count_unit: "completed_todos", count: 2 }, - replanCadenceEditorDefaults({ count_unit: "effective_turns", count: 3, stride_strategy: "evidence_conditioned_v1" }, cadenceDefault)), - { count_unit: "completed_todos", count: 2, stride_strategy: "off" }, - "an explicit cadence wins and omitted strategy retains default-off semantics"); + replanCadenceEditorDefaults({ count_unit: "effective_turns", count: 3 }, cadenceDefault)), + { count_unit: "completed_todos", count: 2 }, + "an explicit cadence wins over the effective interval"); assert.deepEqual(replanCadenceEditorDefaults( { schema_version: "todo_replan_cadence_machine_defaults_v0", completed_todos: 4 }, cadenceDefault), - { count_unit: "completed_todos", count: 4, stride_strategy: "off" }, + { count_unit: "completed_todos", count: 4 }, "legacy effective intervals retain their own unit and count"); -const inheritedReview = { count_unit: "effective_turns", count: 3, stride_strategy: "off" }; +// The stride switch was removed: evidence-conditioned v1 is always on. Legacy +// saved values are history only and never displayed or resubmitted. +for (const legacy of ["off", "evidence_conditioned_v1"]) { + assert.deepEqual(replanCadenceEditorValue({ count_unit: "effective_turns", count: 3, stride_strategy: legacy }), + { count_unit: "effective_turns", count: 3 }, `legacy stride_strategy=${legacy} is not displayed`); + assert.equal(Object.hasOwn(goalReplanCadenceEditorValue({ stride_strategy: legacy }, cadenceDefault), "stride_strategy"), false, + `legacy Goal stride_strategy=${legacy} is not displayed`); + assert.equal(Object.hasOwn(replanCadenceEditorDefaults({ ...cadenceDefault, stride_strategy: legacy }, cadenceDefault), "stride_strategy"), false); +} +assert.deepEqual(replanCadenceEditorValue({ completed_todos: 2 }), { count_unit: "completed_todos", count: 2 }); +assert.equal(parseEditableCapabilityJson(cadenceEditor, JSON.stringify({ stride_strategy: "off" })), null, + "the removed stride switch is not an editable JSON field"); +const inheritedReview = { count_unit: "effective_turns", count: 3 }; assert.deepEqual(goalReplanCadenceWriteValue({...inheritedReview, planning_horizon_goal: true}, false, false), - {stride_strategy: "off"}, "displaying the default Goal context does not create an override"); + {}, "displaying the default Goal context does not create an override"); for (const enabled of [true, false]) { assert.deepEqual(goalReplanCadenceWriteValue({...inheritedReview, planning_horizon_goal: enabled}, false, true), - {stride_strategy: "off", planning_horizon_goal: enabled}, "explicit horizon choices survive a form save"); + {planning_horizon_goal: enabled}, "explicit horizon choices survive a form save"); } assert.equal(replanCadenceEditorDefaults({...inheritedReview, planning_horizon_goal: false}, {...cadenceDefault, planning_horizon_goal: true}).planning_horizon_goal, false, "a sparse Goal form displays the effective machine opt-out"); -assert.deepEqual(goalReplanCadenceEditorValue({ stride_strategy: "evidence_conditioned_v1" }, inheritedReview), - { ...inheritedReview, stride_strategy: "evidence_conditioned_v1" }, - "strategy-only Goal settings display the live review interval"); -assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview, stride_strategy: "evidence_conditioned_v1" }, false), - { stride_strategy: "evidence_conditioned_v1" }, - "changing only the strategy must not pin the displayed interval"); -assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview, count: 2, stride_strategy: "evidence_conditioned_v1" }, true), - { count_unit: "effective_turns", count: 2, stride_strategy: "evidence_conditioned_v1" }, +assert.deepEqual(goalReplanCadenceEditorValue({ planning_horizon_goal: false }, inheritedReview), + { ...inheritedReview, planning_horizon_goal: false }, + "horizon-only Goal settings display the live review interval"); +assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview, planning_horizon_goal: false }, false), + { planning_horizon_goal: false }, + "changing only the horizon must not pin the displayed interval"); +assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview, count: 2 }, true), + { count_unit: "effective_turns", count: 2 }, "an edited interval remains an explicit Goal override"); -assert.deepEqual(goalReplanCadenceWriteValue({ count_unit: "completed_todos", count: 2, stride_strategy: "off" }, +assert.deepEqual(goalReplanCadenceWriteValue({ count_unit: "completed_todos", count: 2 }, false), - { stride_strategy: "off" }, + {}, "legacy device units can be inherited without pinning their count"); -assert.equal(hasReplanCadenceOverride({ stride_strategy: "evidence_conditioned_v1" }), false); +assert.equal(hasReplanCadenceOverride({ planning_horizon_goal: false }), false); assert.equal(hasReplanCadenceOverride({ count_unit: "effective_turns", count: 3 }), true); assert.equal(hasReplanCadenceOverride({ completed_todos: 2 }), true, "legacy pinned cadences stay explicit"); -assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview, stride_strategy: "evidence_conditioned_v1" }, true), - { ...inheritedReview, stride_strategy: "evidence_conditioned_v1" }, +assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview }, true), + { ...inheritedReview }, "an explicit interval remains pinned even when it matches the machine policy"); -assert.deepEqual(goalReplanCadenceWriteValue({ count_unit: "effective_turns", count: 2, stride_strategy: "evidence_conditioned_v1" }, false), - { stride_strategy: "evidence_conditioned_v1" }, +assert.deepEqual(goalReplanCadenceWriteValue({ count_unit: "effective_turns", count: 2, yardstick_enabled: true }, false), + { yardstick_enabled: true }, "removing JSON interval fields clears only the cadence, including a previously pinned value"); const storageDefault = { schema_version: "loopx_goal_storage_defaults_v1", new_goal_provider: "sqlite", canonical_creation: true, new_goal_handoff_mode: "hard_lease" }; @@ -172,12 +184,8 @@ assert.deepEqual( "an explicit Goal CI opt-out must survive default projection and omit envelope fields", ); -// Capability defaults may enable Stride without changing saved legacy choices. -const enabledStrideDefault = {...cadenceDefault, stride_strategy: "evidence_conditioned_v1"}; -assert.deepEqual(goalReplanCadenceEditorValue(null, enabledStrideDefault), enabledStrideDefault); -assert.equal(goalReplanCadenceEditorValue({stride_strategy: "off"}, enabledStrideDefault).stride_strategy, "off"); -assert.equal(goalReplanCadenceEditorValue({count_unit: "effective_turns", count: 3}, enabledStrideDefault).stride_strategy, "off"); -assert.equal(projectEditableCapabilityConfiguration(cadenceEditor, {}, enabledStrideDefault).stride_strategy, "evidence_conditioned_v1"); +// An unconfigured Goal displays the live inherited review value unchanged. +assert.deepEqual(goalReplanCadenceEditorValue(null, cadenceDefault), cadenceDefault); // Independent Yardstick inheritance must not be pinned by editing the interval. const yardstickEffective = {...inheritedReview, yardstick_enabled: true}; @@ -186,6 +194,6 @@ assert.deepEqual(goalReplanCadenceWriteValue({...yardstickEffective, count: 2}, {...inheritedReview, count: 2}, "an unchanged inherited measurement choice stays live"); for (const enabled of [true, false]) { assert.deepEqual(goalReplanCadenceWriteValue({...yardstickEffective, yardstick_enabled: enabled}, false, false, true), - {stride_strategy: "off", yardstick_enabled: enabled}, "explicit measurement opt-in and opt-out survive form saving"); + {yardstick_enabled: enabled}, "explicit measurement opt-in and opt-out survive form saving"); } assert.equal(replanCadenceEditorDefaults(yardstickEffective, {...cadenceDefault, yardstick_enabled: false}).yardstick_enabled, true); diff --git a/apps/presentation/dashboard/src/data/capability-configuration.ts b/apps/presentation/dashboard/src/data/capability-configuration.ts index 0a0469b9ff..1c86cd9628 100644 --- a/apps/presentation/dashboard/src/data/capability-configuration.ts +++ b/apps/presentation/dashboard/src/data/capability-configuration.ts @@ -62,13 +62,19 @@ export function parseEditableCapabilityJson( return value as Record; } -/** Read the legacy cadence without reinterpreting its unit or writing it back. */ +/** + * Read the legacy cadence without reinterpreting its unit or writing it back. + * Evidence-conditioned stride is always on; a legacy saved `stride_strategy` + * is history only, so the editor never displays or resubmits it. + */ export function replanCadenceEditorValue(value: unknown): unknown { const record = configurationObject(value); if (Object.hasOwn(record, "completed_todos") && !Object.hasOwn(record, "count_unit")) { - return { count_unit: "completed_todos", count: record.completed_todos, stride_strategy: "off" }; + return { count_unit: "completed_todos", count: record.completed_todos }; } - return { ...record, stride_strategy: record.stride_strategy ?? "off" }; + const editable = { ...record }; + delete editable.stride_strategy; + return editable; } /** Fill omitted review interval fields from the currently effective value. */ @@ -79,11 +85,10 @@ export function replanCadenceEditorDefaults(effective: unknown, fallback: unknow if (Object.hasOwn(live, "count")) defaults.count = live.count; if (Object.hasOwn(live, "planning_horizon_goal")) defaults.planning_horizon_goal = live.planning_horizon_goal; if (Object.hasOwn(live, "yardstick_enabled")) defaults.yardstick_enabled = live.yardstick_enabled; - // Strategy omission keeps the existing default-off meaning. return defaults; } -/** Show the live interval when a Goal stores only its strategy choice. */ +/** Show the live interval when a Goal stores only horizon or Yardstick choices. */ export function goalReplanCadenceEditorValue(current: unknown, effective: unknown): Record { const inherited = configurationObject(replanCadenceEditorValue(effective)); return current == null ? inherited : { diff --git a/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts b/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts index 3e21cefefd..f93f635ee8 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts +++ b/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts @@ -29,7 +29,7 @@ const capabilityCopy: Record> = { displayName: "Isolated OpenViking memory", description: "Connects owner private steward conversations to an isolated OpenViking memory namespace with per-speaker preferences and bounded recall.", }, - todo_replan_cadence: { displayName: "Goal review and stride", description: "Set review frequency and optionally choose a versioned stride strategy for work scope and route changes." }, + todo_replan_cadence: { displayName: "Goal review and stride", description: "Set review frequency. Evidence-conditioned stride (v1) is always on and reviews work scope and route changes." }, change_quality_qualification: { displayName: "Change quality qualification", description: "Prepares a provider-neutral review packet, allows at most one policy-authorized safe-fix pass, and can require an exact-diff receipt.", @@ -103,7 +103,7 @@ const capabilityCopy: Record> = { displayName: "独立 OpenViking 长期记忆", description: "为本人私聊管家启用独立身份的 OpenViking 记忆命名空间:按已验证发言人持久化偏好、跨会话按需检索并限制超时,不向群聊或工作 Agent 泄露。", }, - todo_replan_cadence: { displayName: "Goal 复盘与步幅", description: "设置复盘周期,可选用带版本的步幅策略,调节工作大小与路线变化。" }, + todo_replan_cadence: { displayName: "Goal 复盘与步幅", description: "设置复盘周期。依据证据的步幅策略(v1)始终开启,复核工作大小与路线变化。" }, change_quality_qualification: { displayName: "变更质量验证", description: "生成与 Provider 无关的审阅包,最多允许一次策略授权的安全修复,并可要求精确 diff 回执。", @@ -178,7 +178,6 @@ const fieldCopy: Record = { count_unit: { label: "Review after", description: "Work Turns require accepted settlement; polls and retries do not count.", options: { completed_todos: "Completed Todos", effective_turns: "Settled work Turns" } }, planning_horizon_goal: { label: "Show Goal in planning horizon", description: "Default on. Keep the original Goal and acceptance visible before choosing work. Turn off for rollback or comparisons; replan, stride and execution authority are unchanged." }, yardstick_enabled: { label: "Review measurement criteria", description: "Default off. Review measurement scope and feedback using available Explore evidence. Requires Explore evidence; does not enable it or authorize execution." }, - stride_strategy: { label: "Stride strategy", description: "Structured work scope, route and validation proposals are required for enabled fresh Vision reviews. Does not grant execution authority.", options: { off: "Off", evidence_conditioned_v1: "Evidence-conditioned · v1" } }, count: { label: "Number between reviews", description: "Settled work Turns: 1–6; completed Todos: 1–5. Goal overrides take precedence over device defaults." }, allowed_domains: { label: "Allowed responsibility domains", description: "Enter one bounded, public-safe domain per line." }, coordinator_agent_id: { label: "Coordinator Agent", description: "Use an already registered Agent id; leave blank to disable coordination." }, @@ -219,7 +218,6 @@ const fieldCopy: Record = { count_unit: { label: "复核计数依据", description: "有效工作 Turn 须完成结算;轮询和重复重试不计数。", options: { completed_todos: "已完成 Todo", effective_turns: "已结算工作 Turn" } }, planning_horizon_goal: { label: "在规划视野中显示 Goal", description: "默认开启,选择工作前可见原目标与验收要求。可为回滚或对照实验关闭;不改变复盘、步幅策略或执行权限。" }, yardstick_enabled: { label: "复核衡量标准", description: "默认关闭。使用已有 Explore 证据复核测量范围与反馈;需有可用的 Explore 证据,不会自动启用它或授予执行权限。" }, - stride_strategy: { label: "步幅策略", description: "启用后,新的 Vision 路线复盘须提交工作大小、路线及验证范围的结构化提案,不授予执行权限。", options: { off: "关闭", evidence_conditioned_v1: "依据证据调整 · v1" } }, count: { label: "两次复核间的数量", description: "已结算工作 Turn 为 1–6,已完成 Todo 为 1–5;Goal 显式设置优先于设备默认值。" }, allowed_domains: { label: "允许的职责域", description: "每行填写一个有边界、可公开的职责域。" }, coordinator_agent_id: { label: "协调 Agent", description: "填写一个已经注册的 Agent ID;留空表示关闭协调。" }, diff --git a/benchmark/edgebench/README.md b/benchmark/edgebench/README.md index 7a790c98e5..d0745071e7 100644 --- a/benchmark/edgebench/README.md +++ b/benchmark/edgebench/README.md @@ -601,8 +601,9 @@ official feedback; best-only retains its strictly improving snapshot channel. Shared `loopx-planned` entry also drops the adapter's research-strategy prefix. The product planning packet, including Core first-delivery guidance, is unchanged -and remains a separate experimental variable. Optional execution observations, -stride settings and checkpoint storage guidance retain their explicit selection. +and remains a separate experimental variable. Optional execution observations +and checkpoint storage guidance retain their explicit selection; LoopX arms +always run the `evidence_conditioned_v1` stride policy. Budgets and deadlines stay with the existing runner. Opted-in native Goal continuation retains the original task and evaluation rules without requiring a prior improvement claim before submission. @@ -969,7 +970,7 @@ New `heartbeat-resume` and `heartbeat-explore` trials include the same-source original Goal and acceptance in preselection planning context by default. `--no-planning-horizon-goal` disables it for rollback or comparison; `--planning-horizon-goal` explicitly enables it. Plain and native-Goal workers reject -this setting. It does not enable stride, Explore or TurnEnvelope. +this setting. It does not change stride, Explore or TurnEnvelope. The adapter writes the shared `execution_profile.planning_horizon_goal` through `configure-goal`, checks the effective readback before work, and records an @@ -984,17 +985,22 @@ Compare on/off from the same qualified pre-replan checkpoint with equal remainin budget, source and other settings. Input fidelity does not establish better research or scores. See the [shared Goal configuration and rollback](../../docs/reference/protocols/quota-planning-horizon-v0.md#enable-read-back-and-disable). -### Optional structured stride strategy - -Add `--stride-strategy evidence_conditioned_v1` to a new `heartbeat-resume` -or `heartbeat-explore` trial to opt into the existing Goal review strategy. -The runner writes the option together with the resolved cadence and checks -the real Goal configuration before planning or execution. The install, -worker-profile and runtime receipts record an explicitly selected version. -Omitting the option preserves ordinary off commands and receipt shapes; -`--stride-strategy off` explicitly selects the disabled treatment. Plain and -native-goal profiles reject this option before creating a trial. Unknown -versions also fail before registration or execution. +### Structured stride strategy (always on for LoopX arms) + +`evidence_conditioned_v1` is the only live LoopX stride policy. New +`heartbeat-resume`, `heartbeat-explore` and `turn-resume` trials run it +unconditionally; there is no on/off switch, and the former `--stride-strategy` +option has been removed (passing it fails argument parsing before a trial is +created). The runner no longer sends a stride setting to `configure-goal`. +The install, worker-profile and runtime receipts of every new LoopX trial record +`"stride_strategy": "evidence_conditioned_v1"`, and report export requires the +worker profile and runtime receipt to agree. Plain and native-Goal workers do not +run LoopX and keep their previous receipt shape without this field. + +Historical receipts remain readable as recorded: absence, `"off"` and +`"evidence_conditioned_v1"` all validate in report export and causal +attribution, so archived studies are not rewritten or relabeled. Comparisons +with older off-treatment runs must pin their original product/runner revisions. The [Goal review contract](../../docs/reference/protocols/goal-vision-replan-contract-v0.md) defines structured proposals and the three independently controlled axes. diff --git a/benchmark/edgebench/causal_attribution.py b/benchmark/edgebench/causal_attribution.py index 5af3f644a3..5f38460bff 100644 --- a/benchmark/edgebench/causal_attribution.py +++ b/benchmark/edgebench/causal_attribution.py @@ -18,6 +18,23 @@ from typing import Any, Dict, List, Optional, Tuple +# Values historical arms may have recorded. New LoopX arms always record +# evidence_conditioned_v1; absence (None) and "off" remain readable history. +_HISTORICAL_STRIDE_STRATEGIES: Tuple[Optional[str], ...] = (None, "off", "evidence_conditioned_v1") + + +def historical_stride_strategy_options() -> Tuple[Optional[str], ...]: + """Return read-only stride strategy values accepted in historical records.""" + return _HISTORICAL_STRIDE_STRATEGIES + + +def validate_historical_stride_strategy(value: Any) -> Optional[str]: + """Validate a recorded stride strategy without selecting a live policy.""" + if value not in _HISTORICAL_STRIDE_STRATEGIES: + raise ValueError("stride_strategy must be absent, off or evidence_conditioned_v1") + return value + + @dataclass(frozen=True) class InflectionPoint: """A decisive inflection point in an agent's execution trajectory.""" @@ -68,6 +85,9 @@ class ArmPerformance: explore_enabled: bool = False grounding_retention_ratio: float = 1.0 # last_score / best_score + def __post_init__(self) -> None: + validate_historical_stride_strategy(self.stride_strategy) + def compute_sha256(data: bytes) -> str: """Return lowercase hex SHA-256 digest of data bytes.""" @@ -149,6 +169,8 @@ def load_cross_task_data(data_dir: Path) -> Dict[str, Any]: raise FileNotFoundError(f"Missing required study data file: {path}") with path.open("r", encoding="utf-8") as f: loaded[key] = json.load(f) + for arm in loaded["five_arms_matrix"].get("arms", []): + validate_historical_stride_strategy(arm.get("stride_strategy")) return loaded diff --git a/benchmark/edgebench/export_report.py b/benchmark/edgebench/export_report.py index 09a8ac39ad..c257125ea7 100644 --- a/benchmark/edgebench/export_report.py +++ b/benchmark/edgebench/export_report.py @@ -19,6 +19,7 @@ from loopx.capabilities.benchmark_toolkit.experiment_board import ( normalize_benchmark_experiment_board_row, ) +from .causal_attribution import validate_historical_stride_strategy from .feedback_hook import FEEDBACK_PAYLOAD from .result_publication import native_grading_complete @@ -278,8 +279,10 @@ def export(runs_root: Path, selection: list, output: Path, *, observed_at: str): if receipt.get("stride_strategy") != profile.get("stride_strategy"): raise ValueError("Profile disagrees with runtime: stride_strategy") if "stride_strategy" in receipt: - from loopx.control_plane.work_items.stride_policy_codec import normalize_stride_strategy - normalize_stride_strategy(receipt["stride_strategy"]) + # Read-only history: absent, "off" or evidence_conditioned_v1. + if receipt["stride_strategy"] is None: + raise ValueError("stride_strategy must be omitted rather than null") + validate_historical_stride_strategy(receipt["stride_strategy"]) if number(final["best_score"]) != number(receipt["best_score"]): raise ValueError("Final and runtime scores disagree") score_entries = [ diff --git a/benchmark/edgebench/run.py b/benchmark/edgebench/run.py index e679d04b05..d873021115 100644 --- a/benchmark/edgebench/run.py +++ b/benchmark/edgebench/run.py @@ -32,7 +32,6 @@ from benchmark.runtime.codex import TASK_ENTRIES, turn_envelope_receipt from loopx.reasoning_effort import REASONING_EFFORTS -from loopx.control_plane.work_items.stride_policy_codec import stride_strategy_options from benchmark.runtime.sforge import ( DEFAULT_TIMEOUT_SECONDS, PROFILES, SForgeWorker, profile_execution, ) @@ -165,8 +164,6 @@ def main(argv=None): help="Explicit completed-Todo cadence ablation for heartbeat profiles") parser.add_argument("--planning-horizon-goal", action=argparse.BooleanOptionalAction, default=None, help="Heartbeat workers include the original Goal before selection by default; --no-planning-horizon-goal opts out") - parser.add_argument("--stride-strategy", choices=stride_strategy_options(), - help="Explicit heartbeat Goal-review strategy; omitted keeps the ordinary off treatment") parser.add_argument("--checkpoint-controller-file", type=Path, help="Host-private native checkpoint controller; requires full fresh-replan handoff") parser.add_argument("--checkpoint-export-root", type=Path, @@ -271,8 +268,6 @@ def main(argv=None): if (args.replan_after_turns is not None or args.replan_after_todos is not None ) and not execution.uses_loopx: parser.error("Replan cadence requires a heartbeat worker or turn-resume") - if args.stride_strategy is not None and not execution.uses_loopx: - parser.error("--stride-strategy requires a heartbeat worker or turn-resume") if args.planning_horizon_goal is not None and not execution.uses_loopx: parser.error("--planning-horizon-goal requires a heartbeat worker or turn-resume") checkpoint_request = None @@ -476,8 +471,6 @@ def main(argv=None): replan_after_turns=args.replan_after_turns, replan_after_todos=args.replan_after_todos, planning_horizon_goal=args.planning_horizon_goal, - **({"stride_strategy": args.stride_strategy} - if args.stride_strategy is not None else {}), **({"checkpoint_request": checkpoint_request} if checkpoint_request is not None else {})) if args.api_proxy_url: @@ -579,8 +572,8 @@ def main(argv=None): if agent.replan_after_todos is not None else {}), **({"planning_horizon_goal": agent.planning_horizon_goal} if agent.planning_horizon_goal is not None else {}), - **({"stride_strategy": args.stride_strategy} - if args.stride_strategy is not None else {}), + **({"stride_strategy": agent.stride_strategy} + if agent.stride_strategy is not None else {}), **({"checkpoint_request_sha256": hashlib.sha256(checkpoint_request).hexdigest()} if checkpoint_request is not None else {}), **({"checkpoint_export_directory": str(checkpoint.destination)} if checkpoint is not None else {}), diff --git a/benchmark/runtime/EXECUTION_OBSERVATIONS.md b/benchmark/runtime/EXECUTION_OBSERVATIONS.md index 844c44aee1..eeeca3978b 100644 --- a/benchmark/runtime/EXECUTION_OBSERVATIONS.md +++ b/benchmark/runtime/EXECUTION_OBSERVATIONS.md @@ -4,8 +4,8 @@ For heartbeat work that needs local execution measurements, set `execution_observation="local_probe"` on `BenchmarkCodex`. Keep the full task -in the existing Goal/Todo planning input and choose `task_entry` and -`stride_strategy` independently. Merge these settings into the experiment's +in the existing Goal/Todo planning input and choose `task_entry` +independently. Merge these settings into the experiment's existing agent configuration, retaining its model, task inputs and budgets: ```yaml @@ -15,21 +15,22 @@ agents: execution_mode: heartbeat task_entry: loopx-planned execution_observation: local_probe - stride_strategy: "off" ``` -`evidence_conditioned_v1` remains an independent, explicit strategy choice. +LoopX execution modes always run the `evidence_conditioned_v1` stride policy +and record it in their receipts; the former `stride_strategy` kwarg has been +removed and fails before runner setup with a migration error. With `loopx-planned`, the ordinary planner determines the work; with `seeded-todo`, the adapter seeds only the ordinary task and its full acceptance criteria. No research preset creates candidate/research stages, a successor -Todo, a Vision patch or a forced stride strategy. Work after an initial +Todo or a Vision patch. Work after an initial candidate follows the original Goal, accepted requirements, ordinary Todo/continuation/replan and remaining useful authorized work. Candidate completion does not settle other requested work. User Stop, original budgets and genuine blockers remain authoritative; no work is created just to fill time. This option supports heartbeat only. Omission or `None` leaves it off and -preserves the ordinary task-entry, stride and probe-installation defaults. +preserves the ordinary task-entry and probe-installation defaults. When selected, the adapter installs `loopx-research-probe` and passes `LOOPX_EXECUTION_OBSERVATION=local_probe` to the worker. Planning and heartbeat instructions request reuse of applicable observations from an execution that @@ -72,8 +73,7 @@ native-model adoption, long-Turn supervision and outcome benefit remain unqualif `research_loop` and `LOOPX_RESEARCH_LOOP` have been removed. Any presence of the adapter kwarg (including `False`) or worker environment variable (including `0`) fails before runner setup or wake creation with a migration error. Remove -both fields from new configurations; choose observation and stride separately -as above. The fixed two-stage initializer and its additional research +both fields from new configurations; choose observation separately as above. The fixed two-stage initializer and its additional research instructions are removed rather than retained as a compatibility mode. Use a new trial for a changed treatment. Historical configurations, scores, @@ -99,7 +99,7 @@ historical versions. The [execution integration fixtures](../../tests/control_plane/test_research_execution_loop.py) exercise the adapter, real local process, File/SQLite authorities, Explore writeback, evidence-driven replan and subsequent changed execution. They also -cover independent observation with stride off and preservation of waits and Stop. +cover observation independent of stride review and preservation of waits and Stop. The [ordinary stage-continuity fixture](../../tests/control_plane/test_research_stage_continuity.py) uses accepted requirements, the real scheduler/subprocess Host and exactly-once settlement to verify that a completed stage cannot hide already requested work, @@ -188,11 +188,11 @@ long-horizon benefit or complete-cost efficiency. ## 中文交付边界 执行观测复用普通 Goal/Todo/Explore:heartbeat 可独立选择 -`execution_observation="local_probe"`,`task_entry` 和 `stride_strategy` 分别配置。 +`execution_observation="local_probe"`,`task_entry` 单独配置;LoopX 模式始终运行 +`evidence_conditioned_v1` stride 策略并写入收据,原 `stride_strategy` kwarg 已移除。 `loopx-planned` 由普通 planner 决定任务;`seeded-todo` 只预置保留完整验收要求的 -普通任务。省略观测或设为 `None` 时,不安装探针、不追加观测指引,任务入口和 -stride 默认选择保持不变。观测不创建候选/研究两阶段、研究后继或 Vision 补丁, -不强制 `evidence_conditioned_v1`。初始候选之后,按原目标、已接受要求、普通 +普通任务。省略观测或设为 `None` 时,不安装探针、不追加观测指引,任务入口 +默认选择保持不变。观测不创建候选/研究两阶段、研究后继或 Vision 补丁。初始候选之后,按原目标、已接受要求、普通 Todo/replan/Explore 及剩余有价值工作接续;候选完成不能关闭其他已请求工作。 Stop、原预算和真实阻塞继续有效,不为填满时长制造任务。 diff --git a/benchmark/runtime/harbor.py b/benchmark/runtime/harbor.py index 8e4aed0100..3f15c34e03 100644 --- a/benchmark/runtime/harbor.py +++ b/benchmark/runtime/harbor.py @@ -17,7 +17,7 @@ from harbor.models.trajectories import FinalMetrics, Trajectory from harbor.utils.trajectory_utils import format_trajectory_json -from loopx.control_plane.work_items.stride_policy_codec import normalize_stride_strategy +from loopx.control_plane.work_items.stride_policy_codec import LIVE_STRIDE_STRATEGY from loopx.control_plane.goals.goal_vision_policy import DEFAULT_PLANNING_HORIZON_GOAL from .codex_offline import MODEL_CATALOG_REMOTE, CodexOffline, stage_portable_python @@ -67,7 +67,6 @@ def __init__( scheduler_timeout_sec=5080, replan_after_todos=None, replan_after_turns=None, - stride_strategy=None, planning_horizon_goal=None, checkpoint_request_path=None, checkpoint_request=None, @@ -90,8 +89,13 @@ def __init__( if "research_loop" in kwargs: raise ValueError( "research_loop has been removed; remove it from the adapter kwargs. " - "Use ordinary Goal/Todo planning, choose stride_strategy independently, " - "and select execution_observation='local_probe' only when needed." + "Use ordinary Goal/Todo planning and select " + "execution_observation='local_probe' only when needed." + ) + if "stride_strategy" in kwargs: + raise ValueError( + "stride_strategy has been removed; remove it from the adapter kwargs. " + f"LoopX execution modes always run {LIVE_STRIDE_STRATEGY}." ) if isinstance(validation_command, str): raise ValueError("validation_command must be an argv list, not shell text") @@ -138,10 +142,8 @@ def __init__( self.replan_after_todos = int(3 if replan_after_todos is None else replan_after_todos) if not 1 <= self.replan_after_todos <= 5: raise ValueError("replan_after_todos must be between 1 and 5") - if stride_strategy is not None and not self.execution.uses_loopx: - raise ValueError("stride_strategy requires a LoopX execution mode") - self.stride_strategy = (normalize_stride_strategy(stride_strategy) - if stride_strategy is not None else None) + # Recorded, not selected: LoopX always runs the live stride policy. + self.stride_strategy = LIVE_STRIDE_STRATEGY if self.execution.uses_loopx else None if planning_horizon_goal is not None: if not isinstance(planning_horizon_goal, bool): raise ValueError("planning_horizon_goal must be a boolean") @@ -502,10 +504,9 @@ async def _prepare_phase( self, environment: BaseEnvironment, instruction: str, *, cwd: str ) -> None: key, option, expected = self._replan_configuration() - stride_args = (["--execution-stride-strategy", self.stride_strategy] - if self.stride_strategy is not None else []) + horizon_args = [] if self.planning_horizon_goal is not None: - stride_args.append("--execution-planning-horizon-goal" if self.planning_horizon_goal + horizon_args.append("--execution-planning-horizon-goal" if self.planning_horizon_goal else "--no-execution-planning-horizon-goal") pending = await environment.exec( command=f"test -e {_LOOPX_RUNTIME}/benchmark-pending-turn.json" @@ -565,7 +566,7 @@ async def _prepare_phase( "trial-workspace", option, str(expected), - *stride_args, + *horizon_args, "--agent-work-mode", f"{self.agent_id}=active", "--execute", @@ -582,7 +583,7 @@ async def _prepare_phase( self.goal_id, option, str(expected), - *stride_args, + *horizon_args, "--execute", ], cwd=cwd, @@ -609,11 +610,6 @@ async def _verify_phase_configuration(self, environment: BaseEnvironment, *, cwd actual_horizon = configured_state.get("execution_profile", {}).get("planning_horizon_goal") if type(actual_horizon) is not bool or actual_horizon != self.planning_horizon_goal: raise RuntimeError("planning_horizon_goal readback mismatch") - strategy = configured_state.get("execution_profile", {}).get("stride_strategy", "off") - if strategy != (self.stride_strategy or "off"): - raise RuntimeError( - f"stride strategy readback mismatch: expected {self.stride_strategy or 'off'}, got {strategy!r}" - ) def _verify_native_child_configuration(self, configured_state: dict) -> None: if self.execution.native_child_limit is None: diff --git a/benchmark/runtime/sforge.py b/benchmark/runtime/sforge.py index 6887532256..6d00f794e9 100644 --- a/benchmark/runtime/sforge.py +++ b/benchmark/runtime/sforge.py @@ -16,6 +16,7 @@ from sforge.harness.agent.codex import CodexAgent from loopx.control_plane.goals.goal_vision_policy import DEFAULT_PLANNING_HORIZON_GOAL +from loopx.control_plane.work_items.stride_policy_codec import LIVE_STRIDE_STRATEGY from benchmark.edgebench.feedback import FEEDBACK_MODES from benchmark.edgebench.feedback_hook import FEEDBACK_PAYLOAD @@ -125,7 +126,6 @@ def __init__(self, config, *, profile: str, cwd: str, native_readiness_attempt_seconds: float | None = None, replan_after_turns: int | None = None, replan_after_todos: int | None = None, - stride_strategy: str | None = None, planning_horizon_goal: bool | None = None, checkpoint_request_path: str | None = None, checkpoint_request: bytes | None = None, @@ -193,11 +193,6 @@ def __init__(self, config, *, profile: str, cwd: str, replan_after_turns = DEFAULT_REPLAN_AFTER_TURNS self.replan_after_turns = replan_after_turns self.replan_after_todos = replan_after_todos - if stride_strategy is not None and not self.execution.uses_loopx: - raise ValueError("stride_strategy requires a heartbeat profile or turn-resume") - if stride_strategy is not None: - from loopx.control_plane.work_items.stride_policy_codec import normalize_stride_strategy - stride_strategy = normalize_stride_strategy(stride_strategy) if planning_horizon_goal is not None: if not isinstance(planning_horizon_goal, bool): raise ValueError("planning_horizon_goal must be a boolean") @@ -207,7 +202,9 @@ def __init__(self, config, *, profile: str, cwd: str, DEFAULT_PLANNING_HORIZON_GOAL if planning_horizon_goal is None and self.execution.uses_loopx else planning_horizon_goal ) - self.stride_strategy = stride_strategy + # Recorded, not selected: LoopX always runs the live stride policy and + # the same value reaches worker-profile.json and runtime-receipt.json. + self.stride_strategy = LIVE_STRIDE_STRATEGY if self.execution.uses_loopx else None self.checkpoint_request_path = None self.checkpoint_request = checkpoint_request if checkpoint_request is not None: @@ -431,7 +428,6 @@ def _install_worker(self, backend, handle, log_dir, logger): native_goal_continue=self.native_goal_continue, replan_after_turns=self.replan_after_turns, replan_after_todos=self.replan_after_todos, - stride_strategy=self.stride_strategy, planning_horizon_goal=self.planning_horizon_goal, checkpoint_request_path=self.checkpoint_request_path, checkpoint_request=self.checkpoint_request, diff --git a/benchmark/tests/test_checkpoint_joint_receiver.py b/benchmark/tests/test_checkpoint_joint_receiver.py index 25eddd72a5..a8156fbfaf 100644 --- a/benchmark/tests/test_checkpoint_joint_receiver.py +++ b/benchmark/tests/test_checkpoint_joint_receiver.py @@ -157,8 +157,8 @@ def receiver_guard(*args): agent + "=active", *( [ - "--execution-stride-strategy", - "evidence_conditioned_v1", + # evidence_conditioned_v1 is always live; this receiver only + # tightens the cadence and enables Explore planning. "--execution-replan-after-turns", "1", "--explore-mode", diff --git a/benchmark/tests/test_edgebench_report.py b/benchmark/tests/test_edgebench_report.py index fb718b9580..cb62b0d4ae 100644 --- a/benchmark/tests/test_edgebench_report.py +++ b/benchmark/tests/test_edgebench_report.py @@ -55,6 +55,52 @@ def test_report_rejects_unbound_or_unknown_stride_version(trial, runner, profile export(runs, selection, output, observed_at="2026-01-02T00:00:00+00:00") +def test_historical_stride_values_do_not_depend_on_the_live_schema(trial, monkeypatch): + from benchmark.edgebench import causal_attribution + from loopx.control_plane.work_items import stride_policy_codec + + # Even if the live enum later drops "off", archived reports stay readable. + monkeypatch.setattr(stride_policy_codec, "stride_strategy_options", + lambda: (stride_policy_codec.LIVE_STRIDE_STRATEGY,)) + assert causal_attribution.historical_stride_strategy_options() == ( + None, "off", "evidence_conditioned_v1") + runs, selection, output, task = trial + task = runs / "run" / "case" + for name in ("runtime-receipt", "worker-profile"): + path = task / (name + ".json") + value = json.loads(path.read_text()) + value["stride_strategy"] = "off" + value["worker" if name == "runtime-receipt" else "profile"] = "heartbeat-resume" + write(path, value) + export(runs, selection, output, observed_at="2026-01-02T00:00:00+00:00") + config = json.loads((output / "settings/run.json").read_text()) + assert config["runner"]["stride_strategy"] == config["worker_profile"]["stride_strategy"] == "off" + + +def test_report_rejects_explicit_null_stride_strategy(trial): + runs, selection, output, task = trial + task = runs / "run" / "case" + for name in ("runtime-receipt", "worker-profile"): + path = task / (name + ".json") + value = json.loads(path.read_text()) + value["stride_strategy"] = None + write(path, value) + with pytest.raises(ValueError, match="stride_strategy"): + export(runs, selection, output, observed_at="2026-01-02T00:00:00+00:00") + + +def test_causal_attribution_validates_historical_arm_stride_values(): + from benchmark.edgebench.causal_attribution import ArmPerformance + + common = dict(arm_id="a", profile="heartbeat-resume", feedback_mode="native", evaluator="e", + best_score=1.0, last_score=1.0, runtime_minutes=1.0, + agent_evaluations=1, auto_evaluations=0) + for value in (None, "off", "evidence_conditioned_v1"): + assert ArmPerformance(**common, stride_strategy=value).stride_strategy == value + with pytest.raises(ValueError, match="stride_strategy"): + ArmPerformance(**common, stride_strategy="future_policy") + + @pytest.fixture def trial(tmp_path): row = dict( diff --git a/benchmark/tests/test_native_checkpoint_handoff.py b/benchmark/tests/test_native_checkpoint_handoff.py index a4ed93821a..a76fad32db 100644 --- a/benchmark/tests/test_native_checkpoint_handoff.py +++ b/benchmark/tests/test_native_checkpoint_handoff.py @@ -422,7 +422,7 @@ def run(*args): run("task-lease", "acquire", "--goal-id", cli.GOAL_ID, "--todo-id", cli.TODO_ID, "--owner", cli.AGENT_ID, "--idempotency-key", "source-work") configured = run("configure-goal", "--goal-id", cli.GOAL_ID, - "--execution-replan-after-turns", "6", "--execution-stride-strategy", "evidence_conditioned_v1", + "--execution-replan-after-turns", "6", "--explore-mode", explore_mode, "--execute") assert configured["after"]["execution_profile"]["replan_after_effective_turns"] == 6 diff --git a/benchmark/tests/test_sforge_runtime.py b/benchmark/tests/test_sforge_runtime.py index 8c1668f02e..7c231f7738 100644 --- a/benchmark/tests/test_sforge_runtime.py +++ b/benchmark/tests/test_sforge_runtime.py @@ -122,6 +122,44 @@ def test_runtime_protocol_attests_only_official_stop_hook(profile, monkeypatch): assert protocol["stop_hook_enabled"] is (profile == "official") +@pytest.mark.parametrize("profile,expected", [ + ("official", None), ("single", None), ("native-goal", None), + ("heartbeat-resume", "evidence_conditioned_v1"), + ("heartbeat-explore", "evidence_conditioned_v1"), +]) +def test_worker_profile_records_live_stride_only_for_loopx(tmp_path, monkeypatch, profile, expected): + pytest.importorskip("sforge") + pytest.importorskip("harbor") + from sforge.harness.config import SForgeConfig + from benchmark.runtime.sforge import BenchmarkCodex, SForgeWorker + + monkeypatch.setenv("CODEX_AUTH_JSON_PATH", "/synthetic-credential") + + async def installed(self, environment): + pass + + monkeypatch.setattr(BenchmarkCodex, "install", installed) + worker = SForgeWorker(SForgeConfig(agent_model="fixture", agent_effort="xhigh"), + profile=profile, cwd="/task") + assert worker.stride_strategy == expected + if expected is not None: + worker.install_stop_hook(None, None, tmp_path, None) + recorded = json.loads((tmp_path / "worker-profile.json").read_text()) + assert recorded["stride_strategy"] == worker.runtime.stride_strategy == expected + + +def test_removed_worker_stride_selection_is_not_accepted(monkeypatch): + pytest.importorskip("sforge") + pytest.importorskip("harbor") + from sforge.harness.config import SForgeConfig + from benchmark.runtime.sforge import SForgeWorker + + monkeypatch.setenv("CODEX_AUTH_JSON_PATH", "/synthetic-credential") + with pytest.raises(TypeError, match="stride_strategy"): + SForgeWorker(SForgeConfig(agent_model="fixture", agent_effort="xhigh"), + profile="heartbeat-resume", cwd="/task", stride_strategy="off") + + def test_invalid_worker_inputs_fail_before_install(monkeypatch): pytest.importorskip("sforge") pytest.importorskip("harbor") @@ -416,7 +454,8 @@ async def installed(self, environment): if profile.startswith("heartbeat-") else {"replan_after_completed_todos": 3}) assert worker.runtime._replan_receipt() == {**expected_cadence, - **({"planning_horizon_goal": True} if profile.startswith("heartbeat-") else {})} + **({"planning_horizon_goal": True, "stride_strategy": "evidence_conditioned_v1"} + if profile.startswith("heartbeat-") else {})} receipt = json.loads((tmp_path / "worker-profile.json").read_text()) if profile.startswith("heartbeat-"): assert all(receipt.get(k) == v for k, v in expected_cadence.items()) @@ -878,9 +917,10 @@ async def installed(self, environment): ("native-goal", ["--replan-after-todos", "3"]), ("heartbeat-resume", ["--replan-after-turns", "3", "--replan-after-todos", "3"]), ("heartbeat-explore", ["--replan-after-todos", "0"]), + # The live stride switch is removed; LoopX workers always record v1. ("official", ["--stride-strategy", "off"]), - ("native-goal", ["--stride-strategy", "evidence_conditioned_v1"]), - ("heartbeat-resume", ["--stride-strategy", "future_policy"]), + ("heartbeat-resume", ["--stride-strategy", "off"]), + ("heartbeat-resume", ["--stride-strategy", "evidence_conditioned_v1"]), ("official", ["--checkpoint-request", "missing.json"]), ("native-goal", ["--checkpoint-request", "missing.json"]), ("heartbeat-explore", ["--checkpoint-retention-policy", "policy.json"]), @@ -1107,6 +1147,7 @@ def stop_before_solver(**kwargs): horizon = (True if "--planning-horizon-goal" in cadence_args else False if "--no-planning-horizon-goal" in cadence_args else True) assert receipt["planning_horizon_goal"] is horizon + assert receipt["stride_strategy"] == "evidence_conditioned_v1" other = ("replan_after_completed_todos" if field == "replan_after_effective_turns" else "replan_after_effective_turns") assert other not in receipt @@ -1195,7 +1236,9 @@ async def installed(self, environment): profile=profile, cwd="/task", replan_after_todos=3) worker.install_stop_hook(None, None, tmp_path, None) assert worker.replan_after_turns is None - assert worker.runtime._replan_receipt() == {"replan_after_completed_todos": 3, "planning_horizon_goal": True} + assert worker.runtime._replan_receipt() == { + "replan_after_completed_todos": 3, "planning_horizon_goal": True, + "stride_strategy": "evidence_conditioned_v1"} receipt = json.loads((tmp_path / "worker-profile.json").read_text()) assert receipt["replan_after_completed_todos"] == 3 assert "replan_after_effective_turns" not in receipt @@ -1674,6 +1717,7 @@ def stop_before_model(**kwargs): worker.install_stop_hook(backend, None, trial, None) profile_receipt = json.loads((trial / "worker-profile.json").read_text()) assert profile_receipt.get("execution_observation") == producer + profiles.append(profile_receipt) assert profile_receipt.get("native_result_comparison") is (True if compare else None) assert installed_tools == ([ ("loopx-bind-native-candidate", "sforge_candidate_binding.py", "--generated-file") @@ -1682,6 +1726,7 @@ def stop_before_model(**kwargs): assert ("content refs do not cover modes" in worker.workspace_instructions) is selected raise RuntimeError("isolated install boundary") + profiles = [] monkeypatch.setattr(run, "run_agent", stop_before_model) args = ["--task", "fixture", "--tasks-dir", str(tmp_path), "--log-dir", str(tmp_path), "--run-id", "probe", "--worker", profile, "--model", "fixture", @@ -1700,6 +1745,9 @@ def stop_before_model(**kwargs): run.main(args) receipt = json.loads((trial / "runtime-receipt.json").read_text()) assert receipt.get("execution_observation") == producer + # New LoopX runs stamp the live stride policy identically in both records. + profile_receipt, = profiles + assert receipt["stride_strategy"] == profile_receipt["stride_strategy"] == "evidence_conditioned_v1" assert receipt.get("native_result_comparison") is (True if compare else None) assert installed == (["loopx-bind-native-candidate"] if selected or compare else []) assert bool(scopes) is compare diff --git a/benchmark/tests/test_shared_codex_runtime.py b/benchmark/tests/test_shared_codex_runtime.py index fe2a5e5624..9d2964f4e7 100644 --- a/benchmark/tests/test_shared_codex_runtime.py +++ b/benchmark/tests/test_shared_codex_runtime.py @@ -1102,16 +1102,41 @@ async def no_pending(**kwargs): configured = [args for args in calls if option in args] assert configured and all(args[args.index(option) + 1] == str(value) for args in configured) - assert agent._replan_receipt() == {field: value, "planning_horizon_goal": True} + assert agent._replan_receipt() == {field: value, "planning_horizon_goal": True, + "stride_strategy": "evidence_conditioned_v1"} assert all("--execution-planning-horizon-goal" in args for args in configured) + assert all("--execution-stride-strategy" not in args + and "--clear-execution-stride-strategy" not in args for args in calls) -def test_requested_stride_requires_configuration_readback_before_execution(tmp_path, monkeypatch): +@pytest.mark.parametrize("mode", ["heartbeat", "turn", "loopx-goal"]) +def test_loopx_modes_record_live_stride_without_selecting_it(tmp_path, mode): pytest.importorskip("harbor") from benchmark.runtime.harbor import BenchmarkCodex + from loopx.control_plane.work_items.stride_policy_codec import LIVE_STRIDE_STRATEGY - agent = BenchmarkCodex(logs_dir=tmp_path, model_name="fixture", - stride_strategy="evidence_conditioned_v1") + agent = BenchmarkCodex(logs_dir=tmp_path, model_name="fixture", execution_mode=mode, + **({"validation_command": ["python", "validate.py"]} if mode == "turn" else {})) + assert agent.stride_strategy == LIVE_STRIDE_STRATEGY == "evidence_conditioned_v1" + assert agent._replan_receipt()["stride_strategy"] == LIVE_STRIDE_STRATEGY + + +@pytest.mark.parametrize("mode", ["plain", "native-goal"]) +def test_non_loopx_modes_record_no_stride_strategy(tmp_path, mode): + pytest.importorskip("harbor") + from benchmark.runtime.harbor import BenchmarkCodex + + agent = BenchmarkCodex(logs_dir=tmp_path, model_name="fixture", execution_mode=mode) + assert agent.stride_strategy is None + assert "stride_strategy" not in agent._replan_receipt() + + +def test_phase_readback_does_not_reconfigure_or_check_stride(tmp_path, monkeypatch): + pytest.importorskip("harbor") + from benchmark.runtime.harbor import BenchmarkCodex + + agent = BenchmarkCodex(logs_dir=tmp_path, model_name="fixture") + calls = [] async def prepared(*args, **kwargs): return True @@ -1119,28 +1144,31 @@ async def prepared(*args, **kwargs): async def no_pending(**kwargs): return SimpleNamespace(return_code=1) - async def wrong_strategy(*args, **kwargs): + async def historical_profile(environment, args, **kwargs): + calls.append(args) + # A restored Goal may still carry a historical value; it is not a switch. return {"after": {"execution_profile": { "replan_after_effective_turns": 6, "stride_strategy": "off", "planning_horizon_goal": True, }}} monkeypatch.setattr(agent, "_registry_exists", prepared) monkeypatch.setattr(agent, "_write_task_document", prepared) - monkeypatch.setattr(agent, "_loopx", wrong_strategy) - with pytest.raises(RuntimeError, match="stride strategy readback mismatch"): - asyncio.run(agent._prepare_phase(SimpleNamespace(exec=no_pending), "Synthetic task", cwd=str(tmp_path))) + monkeypatch.setattr(agent, "_loopx", historical_profile) + asyncio.run(agent._prepare_phase(SimpleNamespace(exec=no_pending), "Synthetic task", cwd=str(tmp_path))) + assert calls and all("--execution-stride-strategy" not in args for args in calls) @pytest.mark.parametrize("settings", [ - {"stride_strategy": "future_policy"}, - {"stride_strategy": True}, + {"stride_strategy": "evidence_conditioned_v1"}, + {"stride_strategy": "off"}, + {"stride_strategy": None}, {"execution_mode": "plain", "stride_strategy": "off"}, ]) -def test_stride_rejects_unknown_version_and_incompatible_mode(tmp_path, settings): +def test_removed_stride_strategy_kwarg_is_rejected(tmp_path, settings): pytest.importorskip("harbor") from benchmark.runtime.harbor import BenchmarkCodex - with pytest.raises(ValueError, match="stride_strategy"): + with pytest.raises(ValueError, match="stride_strategy has been removed"): BenchmarkCodex(logs_dir=tmp_path, model_name="fixture", **settings) diff --git a/benchmark/tests/test_task_entry.py b/benchmark/tests/test_task_entry.py index a8c1073889..61aabb681e 100644 --- a/benchmark/tests/test_task_entry.py +++ b/benchmark/tests/test_task_entry.py @@ -44,16 +44,15 @@ def test_task_entry_defaults_to_planning_only_for_loopx_modes(mode): @pytest.mark.parametrize("entry", ["loopx-planned", "seeded-todo"]) -@pytest.mark.parametrize("strategy", [None, "off", "evidence_conditioned_v1"]) -def test_execution_observation_keeps_task_entry_and_stride_independent(tmp_path, entry, strategy): +def test_execution_observation_keeps_task_entry_and_stride_independent(tmp_path, entry): pytest.importorskip("harbor") from benchmark.runtime.harbor import BenchmarkCodex agent = BenchmarkCodex(logs_dir=tmp_path, model_name="fixture", task_entry=entry, - stride_strategy=strategy, execution_observation="local_probe") + execution_observation="local_probe") env = agent._worker_env(cwd=str(tmp_path)) assert agent.execution.task_entry == entry - assert agent.stride_strategy == strategy + assert agent.stride_strategy == "evidence_conditioned_v1" assert env["LOOPX_EXECUTION_OBSERVATION"] == "local_probe" assert "LOOPX_RESEARCH_LOOP" not in env @@ -100,7 +99,7 @@ def test_observation_guidance_is_optional_without_a_research_stage(tmp_path): plain_env = ordinary._worker_env(cwd=str(tmp_path)) assert "LOOPX_RESEARCH_LOOP" not in plain_env assert "LOOPX_EXECUTION_OBSERVATION" not in plain_env - assert ordinary.stride_strategy is None + assert ordinary.stride_strategy == "evidence_conditioned_v1" observed = BenchmarkCodex(logs_dir=tmp_path / "observed", model_name="fixture", execution_observation="local_probe") observed_env = observed._worker_env(cwd=str(tmp_path)) @@ -220,7 +219,7 @@ async def execute_root(*args, **kwargs): assert receipt.get("execution_observation") == ("local_probe" if selected else None) assert "research_loop" not in receipt assert receipt["task_entry"] == "loopx-planned" - assert receipt.get("stride_strategy") is None + assert receipt["stride_strategy"] == "evidence_conditioned_v1" if entry == "workspace-shadow": candidate = tmp_path / "candidate.py" candidate.write_text("print('real probe kept the task cwd')") @@ -658,7 +657,7 @@ async def upload_file(self, source, target): Path(target).write_bytes(Path(source).read_bytes()) agent = harbor.BenchmarkCodex(logs_dir=tmp_path / "logs", model_name="fixture", - execution_observation=producer, stride_strategy="off", task_objective=objective) + execution_observation=producer, task_objective=objective) monkeypatch.setattr(agent, "_profile_env", lambda: env) task = ("Start from the supplied solution.py and compare one alternative against it.\n" "First preserve correctness, then minimize operations. Retain useful negative results.\n" @@ -1084,9 +1083,7 @@ def test_sforge_planning_failed_host_has_no_execution_handoff(planning_env): ({"planning_horizon_goal": False}, "replan_after_effective_turns", 6), ({"replan_after_turns": 2}, "replan_after_effective_turns", 2), ({"replan_after_todos": 3}, "replan_after_completed_todos", 3), - ({"stride_strategy": "off"}, "replan_after_effective_turns", 6), - ({"stride_strategy": "evidence_conditioned_v1"}, "replan_after_effective_turns", 6), - ({"stride_strategy": "evidence_conditioned_v1", "replan_after_todos": 2}, "replan_after_completed_todos", 2), + ({"replan_after_todos": 2}, "replan_after_completed_todos", 2), ]) def test_runner_cadence_persists_through_real_configure_goal( planning_env, tmp_path, monkeypatch, settings, field, value @@ -1127,13 +1124,12 @@ async def no_pending(**kwargs): other = ("replan_after_completed_todos" if field == "replan_after_effective_turns" else "replan_after_effective_turns") assert other not in profile - strategy = settings.get("stride_strategy") - assert profile.get("stride_strategy", "off") == (strategy or "off") + # Cadence-pinned Goals no longer fall back to "off"; any recorded value is v1. + assert profile.get("stride_strategy", "evidence_conditioned_v1") == "evidence_conditioned_v1" horizon = settings.get("planning_horizon_goal", True) assert profile["planning_horizon_goal"] is horizon assert agent._replan_receipt() == {field: value, - "planning_horizon_goal": horizon, **({"stride_strategy": strategy} - if strategy is not None else {})} + "planning_horizon_goal": horizon, "stride_strategy": "evidence_conditioned_v1"} def test_sforge_planning_entry_retries_a_dropped_planning_wake_within_budget(planning_env, monkeypatch): diff --git a/docs/quota-allocation.md b/docs/quota-allocation.md index 6b1e506e69..b2af017427 100644 --- a/docs/quota-allocation.md +++ b/docs/quota-allocation.md @@ -167,11 +167,16 @@ loopx configure-goal --goal-id example --clear-execution-replan-after-turns --ex The Dashboard exposes **Goal review and stride** in the Capability Center for both the device and selected Goal. The existing machine namespace `todo_replan_cadence_machine_defaults_v2` stores `count_unit` (`effective_turns` -or `completed_todos`), `count` and optional strategy selection. Existing v0/v1 -configurations remain readable without migrating them on inspection. The -strategy defaults off; `evidence_conditioned_v1` adds evidence-conditioned scope -and route advice, with unchanged admission and semantic exits. See the -[versioned strategy configuration and rollback](reference/protocols/goal-vision-replan-contract-v0.md#configure-and-roll-back-the-stride-strategy). It is built into the control plane and needs +or `completed_todos`) and `count`. Existing v0/v1 configurations remain readable +without migrating them on inspection. The stride strategy is not configurable: +`evidence_conditioned_v1` is always on and adds evidence-conditioned scope and +route advice, with unchanged admission and semantic exits. There is no +`--execution-stride-strategy` flag, Dashboard selector or device field. A +`stride_strategy` value saved by an earlier release (`off` or +`evidence_conditioned_v1`) in a v2 device file or Goal profile still loads, but +it is ignored and dropped the next time that configuration is written; new +writes that include `stride_strategy` are rejected. See the +[versioned strategy contract](reference/protocols/goal-vision-replan-contract-v0.md#configure-and-roll-back-the-stride-strategy). It is built into the control plane and needs no provider installation. The CLI, settings readback, quota decision and writeback validation use the same effective configuration. diff --git a/docs/reference/protocols/goal-vision-replan-contract-v0.md b/docs/reference/protocols/goal-vision-replan-contract-v0.md index 5b77a43c5e..c58727800f 100644 --- a/docs/reference/protocols/goal-vision-replan-contract-v0.md +++ b/docs/reference/protocols/goal-vision-replan-contract-v0.md @@ -549,59 +549,30 @@ fresh-path 决定仍受既有结构校验约束。这些是机器执行的字段 ### Configure and roll back the stride strategy Use the existing **Goal review and stride** capability editor, selecting device -defaults or an explicit Goal target. Preview, confirm and read back the effective -configuration/source. A Goal can select only the strategy and keep inheriting -the live device review interval (six settled work Turns by default). An explicit -Goal review unit/count still pins that interval; an older cadence-only override -without a strategy remains `off`, even when the device strategy is enabled. -Clearing the interval alone retains the Goal strategy, while clearing both -restores device defaults. There is no separate stride timer. Switching between -JSON and the form preserves that choice: omitted interval fields keep inheritance, -while explicit fields remain pinned even when they equal the current device value. -A strategy-only Goal capability JSON object clears an existing interval override. -The CLI's single-field strategy option retains a stored interval; use its explicit -cadence-clear options to restore inheritance. - -![Versioned stride strategy in the existing capability editor](assets/stride-strategy-editor.png) - -Isolated packaged editor with the real revision-checked configuration handler; -workspace discovery is synthetic. This demonstrates configuration readback, not -installed-App adoption or research utility. - -CLI preview/apply and readback (replace `GOAL`): - -```sh -loopx configure-goal --goal-id GOAL --execution-stride-strategy evidence_conditioned_v1 -loopx configure-goal --goal-id GOAL --execution-stride-strategy evidence_conditioned_v1 --execute -loopx --format json configure-goal --goal-id GOAL -loopx configure-goal --goal-id GOAL --execution-stride-strategy off --execute -``` - -Turning the strategy off retains the review interval and ordinary review. To -restore device defaults for the entire review configuration, clear the cadence -and strategy through the editor or `--clear-execution-replan-after-turns ---clear-execution-replan-after-todos --clear-execution-stride-strategy --execute`. -Historical evidence remains readable after disabling. Activation cannot authorize -experiments, spend quota, clone a checkpoint, relax acceptance or rewrite a -frozen experiment. Configuration is versioned; preregister the selected version -and captured input scope for comparisons. - -在既有「Goal 复盘与步幅」能力中心中选择设备默认值或明确的 Goal,预览、确认并 -回读生效来源。Goal 可仅选择策略,继续沿用设备的实时复盘周期(默认每 6 个已结算 -工作 Turn);显式设置 Goal 计数依据和数量仍会固定该周期。旧的仅含周期覆盖没有 -策略时仍为 off。单独清除周期会保留 Goal 策略;两者都清除才恢复设备默认值。 -步幅策略没有第二个独立计时器。JSON 与表单切换保留原选择:省略周期字段继续 -继承,显式字段即使等于当前设备值也保持固定。Goal 能力 JSON 仅含策略时清除 -已有周期覆盖;CLI 单字段策略选项仍保留已存周期,要恢复继承须显式使用周期 -清除选项。关闭策略保留复盘周期。 -历史引用仍可读取。启用不会授权实验、消耗配额、复制 checkpoint、放宽验收或 -改写冻结实验;比较时预先记录策略版本与输入覆盖范围。 +defaults or an explicit Goal target to configure the review cadence (six settled +work Turns by default). Evidence-conditioned stride (`evidence_conditioned_v1`) +is unconditionally enabled as the live strategy; there is no live on/off toggle +and no separate stride timer. An explicit Goal review unit/count still pins that +interval, and clearing the cadence restores live device defaults via the editor +or `--clear-execution-replan-after-turns --clear-execution-replan-after-todos --execute`. +Legacy saved `stride_strategy` fields in `registry.json` or +`machine_configuration.json` remain readable on load, are ignored at runtime, +and are dropped on rewrite. Activation cannot authorize experiments, spend +quota, clone a checkpoint, relax acceptance or rewrite a frozen experiment. + +在既有「Goal 复盘与步幅」能力中心中选择设备默认值或明确的 Goal 来配置复盘周期 +(默认每 6 个已结算工作 Turn)。基于证据的步幅策略(`evidence_conditioned_v1`) +现为无条件生效的在线策略,不再提供在线开关,也没有第二个独立计时器。显式设置 Goal +计数依据和数量仍会固定该周期,可通过编辑器或 `--clear-execution-replan-after-turns +--clear-execution-replan-after-todos --execute` 恢复设备默认值。旧配置文件中残留的 +`stride_strategy` 字段在读取时保持兼容、运行时忽略、重写时移除;历史引用仍可读取。 +策略不会授权实验、消耗配额、复制 checkpoint、放宽验收或改写冻结实验。 ### Structured stride control -One opt-in strategy is selectable: `off | evidence_conditioned_v1`. The existing -activation token remains stable; the initial implementation now replaces its -fixed evidence-label mapping with **three independently justified coordinates**. +The sole live strategy is `evidence_conditioned_v1` (historical `"off"` records +remain readable for read-only audit/replay). The initial implementation replaces +its fixed evidence-label mapping with **three independently justified coordinates**. Pin the exact source revision when comparing runs. Frozen workers retain their installed source; historical fixed-vector declarations remain readable without being reinterpreted as new decisions. diff --git a/examples/autonomous-replan-obligation-smoke.py b/examples/autonomous-replan-obligation-smoke.py index 43fb790883..4bf8c4743c 100644 --- a/examples/autonomous-replan-obligation-smoke.py +++ b/examples/autonomous-replan-obligation-smoke.py @@ -180,8 +180,6 @@ def write_fixture( { "id": GOAL_ID, "domain": "autonomous-replan-fixture", - # Isolate progress/cadence semantics from optional structured work-shape review. - "execution_profile": {"stride_strategy": "off"}, "status": "active", "repo": str(project), "state_file": state_file, @@ -303,9 +301,49 @@ def assert_typed_repeat_requires_two_equivalent_observations() -> None: assert guard["replan_action_packet"]["required_outcome"] == "semantic_delta", guard +def _write_stride_stop_vision(path: Path, guard: dict) -> Path: + decision = dict(guard["replan_action_packet"]["stride_control"]["minimal_example"]) + path.write_text( + json.dumps( + { + "schema_version": "goal_vision_replan_contract_v0", + "agent_id": AGENT_ID, + "state": "active", + "vision_patch": { + "acceptance_summary": "Advance the next bounded hardening slice.", + }, + "path_delta": { + "schema_version": "goal_path_delta_v0", + "outcome": "stop", + "prior_assumption": "Repeating the prior surface could advance the slice.", + "observed_reality": "Two equivalent observations produced no semantic progress.", + "stopped": ["Stop repeating the prior unchanged surface."], + "evidence_refs": ["evidence-current-route"], + }, + "stride_decision": decision, + }, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + return path + + def assert_equivalent_observation_is_rejected_before_write() -> None: with tempfile.TemporaryDirectory(prefix="loopx-typed-replan-") as tmp: registry_path, runtime = write_fixture(Path(tmp), typed_repeat_count=2) + guard = run_cli( + "quota", + "should-run", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + registry_path=registry_path, + runtime=runtime, + ) + vision_path = _write_stride_stop_vision(Path(tmp) / "stop-vision.json", guard) runs_index = runtime / "goals" / GOAL_ID / "runs" / "index.jsonl" before = runs_index.read_text(encoding="utf-8") error = run_cli_error( @@ -316,6 +354,8 @@ def assert_equivalent_observation_is_rejected_before_write() -> None: AGENT_ID, "--classification", "source_audit_progress", + "--agent-vision-json", + str(vision_path), "--progress-result-class", "advanced", "--progress-surface-id", @@ -347,6 +387,7 @@ def assert_new_typed_surface_closes_exact_obligation() -> None: runtime=runtime, ) obligation_id = before["autonomous_replan_obligation"]["obligation_id"] + vision_path = _write_stride_stop_vision(Path(tmp) / "stop-vision.json", before) # Execute the host projection itself; a hand-authored command can hide # missing flags or an unusable printed transition. action = next( @@ -355,15 +396,25 @@ def assert_new_typed_surface_closes_exact_obligation() -> None: ) tokens = shlex.split(action) replacements = { - "": "advanced", - "": "surface-new-route", - "": "hypothesis-current-boundary", - "": "probe-current-route", - "": "evidence-new-route", + "": str(vision_path), } # The fixture supplies the isolated registry/runtime; preserve every # projected refresh argument and replace only declared input slots. - args = [replacements.get(token, token) for token in tokens[tokens.index("refresh-state"):]] + args = [ + replacements.get(token, token) + for token in tokens[tokens.index("refresh-state"):] + ] + [ + "--progress-result-class", + "advanced", + "--progress-surface-id", + "surface-new-route", + "--progress-hypothesis-id", + "hypothesis-current-boundary", + "--progress-probe-kind", + "probe-current-route", + "--progress-evidence-id", + "evidence-new-route", + ] refresh = run_cli(*args, registry_path=registry_path, runtime=runtime) semantic_delta = refresh["autonomous_replan_ack"]["semantic_delta"] assert semantic_delta["accepted"] is True, refresh diff --git a/examples/control_plane/refresh-state-shared-runtime-projection-smoke.py b/examples/control_plane/refresh-state-shared-runtime-projection-smoke.py index 5121407aa5..4e3e0f0d7d 100644 --- a/examples/control_plane/refresh-state-shared-runtime-projection-smoke.py +++ b/examples/control_plane/refresh-state-shared-runtime-projection-smoke.py @@ -95,8 +95,6 @@ def write_fixture(root: Path) -> tuple[Path, Path, Path, Path]: goal = { "id": GOAL_ID, "domain": "refresh-state-shared-runtime-smoke", - # This fixture qualifies routing/writeback, not a Stride review. - "execution_profile": {"stride_strategy": "off"}, "status": "active", "repo": str(project), "state_file": str(state_file.relative_to(project)), @@ -317,6 +315,18 @@ def main() -> None: no_sync_unqualified["error"] ), no_sync_unqualified + no_sync_guard = run_cli( + "--registry", + str(source_registry), + "quota", + "should-run", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + cwd=project, + shared_runtime=shared_runtime, + ) no_change_vision = Path(tmp) / "no-change-vision.json" no_change_vision.write_text( json.dumps( @@ -342,6 +352,9 @@ def main() -> None: "retained": ["Keep the shared-runtime projection boundary."], "evidence_refs": ["evidence:shared-runtime-projection-verified"], }, + "stride_decision": no_sync_guard["replan_action_packet"][ + "stride_control" + ]["minimal_example"], }, ensure_ascii=False, indent=2, diff --git a/examples/personal-workspace-browser/replan-cadence.mjs b/examples/personal-workspace-browser/replan-cadence.mjs index 5eda91d8ed..76daa3737e 100644 --- a/examples/personal-workspace-browser/replan-cadence.mjs +++ b/examples/personal-workspace-browser/replan-cadence.mjs @@ -81,9 +81,9 @@ export const replanCadenceScenario = { await selectMachineCadence(); const unit = page.getByLabel(/^复核计数依据/); const count = page.getByLabel("两次复核间的数量", { exact: true }); - const strategy = page.getByLabel(/^步幅策略/); await waitForInputValue(count, "6"); - if (await strategy.inputValue() !== "evidence_conditioned_v1") throw new Error("Stride must default to evidence_conditioned_v1"); + // Evidence-conditioned stride is always on; there is no switch to show. + assert.equal(await page.getByLabel(/^步幅策略/).count(), 0, "the removed stride switch must not render"); if (await unit.inputValue() !== "effective_turns") throw new Error("Product default is not settled work Turns"); const yardstick = page.getByLabel(/^复核衡量标准/); assert.equal(await yardstick.isChecked(), false, "Yardstick remains a separate explicit opt-in"); @@ -109,13 +109,12 @@ export const replanCadenceScenario = { stored = (await request(base)).machine_configuration.namespaces.todo_replan_cadence; if (stored.completed_todos !== 2) throw new Error("Invalid preview mutated state"); await count.fill("3"); - await strategy.selectOption("evidence_conditioned_v1"); await page.getByRole("button", { name: "预览变更", exact: true }).click(); await page.getByRole("button", { name: "应用已审阅预览", exact: true }).click(); await page.getByRole("button", { name: "预览回滚", exact: true }).waitFor(); stored = (await request(base)).machine_configuration.namespaces.todo_replan_cadence; if (stored.count_unit !== "effective_turns" || stored.count !== 3 || "completed_todos" in stored) throw new Error("Migration did not persist the selected unit"); - if (stored.stride_strategy !== "evidence_conditioned_v1" || stored.schema_version !== "todo_replan_cadence_machine_defaults_v2") throw new Error("Machine stride version not recorded"); + if ("stride_strategy" in stored || stored.schema_version !== "todo_replan_cadence_machine_defaults_v2") throw new Error("Machine v2 must not record the removed stride switch"); await page.screenshot({ path: resolve(outputDir, "replan-cadence-machine.png"), animations: "disabled" }); await page.getByRole("radio", { name: "Goal 设置", exact: true }).check(); await page.getByRole("combobox", { name: "目标 Goal", exact: true }).selectOption("multi-agent-projection"); @@ -126,9 +125,8 @@ export const replanCadenceScenario = { const packet = await request("/api/chat/goal-configuration?goal_id=multi-agent-projection"); return packet.capability_catalog.capabilities.find((row) => row.capability_id === "todo_replan_cadence"); } - if (await strategy.inputValue() !== "evidence_conditioned_v1") throw new Error("Goal did not inherit strategy version"); await page.getByRole("button", { name: "编辑 JSON", exact: true }).click(); - await page.locator("#goal-configuration-json").fill(JSON.stringify({ stride_strategy: "evidence_conditioned_v1" })); + await page.locator("#goal-configuration-json").fill(JSON.stringify({ yardstick_enabled: false })); await page.getByRole("button", { name: "返回表单", exact: true }).click(); if (await unit.inputValue() !== "effective_turns" || await count.inputValue() !== "3") { throw new Error("JSON-to-form conversion lost the effective review interval"); @@ -142,13 +140,12 @@ export const replanCadenceScenario = { } await page.getByText("复盘周期沿用设备默认;规划选项由本 Goal 设置。", { exact: true }).waitFor(); await page.screenshot({ path: resolve(outputDir, "replan-cadence-json-form.png"), animations: "disabled" }); - if (JSON.stringify(converted.current) !== JSON.stringify({ stride_strategy: "evidence_conditioned_v1" })) { - throw new Error("JSON-to-form strategy-only save pinned a cadence"); + if (JSON.stringify(converted.current) !== JSON.stringify({ yardstick_enabled: false })) { + throw new Error("JSON-to-form option-only save pinned a cadence"); } async function changeMachineCount(value) { const change = { namespace: "todo_replan_cadence", namespace_configuration: { schema_version: "todo_replan_cadence_machine_defaults_v2", count_unit: "effective_turns", count: value, - stride_strategy: "evidence_conditioned_v1", } }; const planned = await request(base + "/preview", change); await request(base + "/apply", { ...change, expected_plan_revision: planned.plan_revision }); @@ -166,7 +163,7 @@ export const replanCadenceScenario = { .getByRole("button", { name: english ? /Goal review and stride/ : /Goal 复盘与步幅/ }).click(); } // Default context is visible to the Agent without an owner setup step. - // Advanced opt-out persists without pinning cadence or changing stride. + // Advanced opt-out persists without pinning cadence or other options. assert.equal(await horizonGoal.isVisible(), false); await advanced.click(); assert.equal(await horizonGoal.isChecked(), true); @@ -178,7 +175,7 @@ export const replanCadenceScenario = { assert.equal(await horizonGoal.isChecked(), false); let horizonReadback = await readGoalCadence(); assert.equal(horizonReadback.current.planning_horizon_goal, false); - assert.equal(horizonReadback.current.stride_strategy, "evidence_conditioned_v1"); + assert.equal(horizonReadback.current.yardstick_enabled, false); assert.equal(horizonReadback.current.count, undefined); await page.screenshot({ path: resolve(outputDir, "planning-horizon-goal-disabled.png"), animations: "disabled" }); await horizonGoal.check(); @@ -191,19 +188,19 @@ export const replanCadenceScenario = { assert.equal(horizonReadback.current.planning_horizon_goal, true); // Restore the sparse pre-existing scenario before its cadence transitions. await page.getByRole("button", { name: "编辑 JSON", exact: true }).click(); - await page.locator("#goal-configuration-json").fill(JSON.stringify({stride_strategy: "evidence_conditioned_v1"})); + await page.locator("#goal-configuration-json").fill(JSON.stringify({yardstick_enabled: false})); await page.getByRole("button", { name: "返回表单", exact: true }).click(); await page.getByRole("button", { name: "预览变更", exact: true }).click(); await applyGoalPreview(); await changeMachineCount(4); if ((await readGoalCadence()).effective_configuration.configuration.count !== 4) { - throw new Error("Strategy-only Goal did not follow a later machine policy"); + throw new Error("Option-only Goal did not follow a later machine policy"); } await reopenGoalCadence(); await waitForInputValue(count, "4"); await page.getByRole("button", { name: "编辑 JSON", exact: true }).click(); await page.locator("#goal-configuration-json").fill(JSON.stringify({ - count_unit: "effective_turns", count: 4, stride_strategy: "evidence_conditioned_v1", + count_unit: "effective_turns", count: 4, yardstick_enabled: false, })); await page.getByRole("button", { name: "返回表单", exact: true }).click(); await page.getByRole("button", { name: "预览变更", exact: true }).click(); @@ -216,24 +213,24 @@ export const replanCadenceScenario = { throw new Error("An explicit Goal cadence unexpectedly followed the machine policy"); } await page.getByRole("button", { name: "编辑 JSON", exact: true }).click(); - await page.locator("#goal-configuration-json").fill(JSON.stringify({ stride_strategy: "evidence_conditioned_v1" })); + await page.locator("#goal-configuration-json").fill(JSON.stringify({ yardstick_enabled: false })); await page.getByRole("button", { name: "返回表单", exact: true }).click(); await page.getByRole("button", { name: "预览变更", exact: true }).click(); await applyGoalPreview(); const intervalCleared = await readGoalCadence(); - if (JSON.stringify(intervalCleared.current) !== JSON.stringify({ stride_strategy: "evidence_conditioned_v1" }) + if (JSON.stringify(intervalCleared.current) !== JSON.stringify({ yardstick_enabled: false }) || intervalCleared.effective_configuration.configuration.count !== 3) { - throw new Error("Clearing only the cadence through JSON-to-form lost the strategy or retained the pin"); + throw new Error("Clearing only the cadence through JSON-to-form lost the option or retained the pin"); } await reopenGoalCadence(); await waitForInputValue(count, "3"); - await strategy.selectOption("off"); + await yardstick.check(); await page.getByRole("button", { name: "预览变更", exact: true }).click(); const delayedReadback = holdGoalReadback(); await applyGoalPreview(); await delayedReadback.started; assert.equal(await count.isDisabled(), true, "A committed write must keep the editor closed until its readback settles"); - assert.equal(await strategy.isDisabled(), true); + assert.equal(await yardstick.isDisabled(), true); assert.equal(await horizonGoal.isDisabled(), true); assert.equal(await page.getByRole("button", { name: "编辑 JSON", exact: true }).isDisabled(), true); assert.equal(await page.getByRole("button", { name: "预览变更", exact: true }).isDisabled(), true); @@ -244,24 +241,23 @@ export const replanCadenceScenario = { await page.screenshot({ path: resolve(outputDir, "replan-cadence-saving-readback.png"), animations: "disabled" }); delayedReadback.release(); let goalCadence = await readGoalCadence(); - if (JSON.stringify(goalCadence.current) !== JSON.stringify({ stride_strategy: "off" }) + if (JSON.stringify(goalCadence.current) !== JSON.stringify({ yardstick_enabled: true }) || goalCadence.effective_configuration.configuration.count !== 3) { - throw new Error("Goal strategy-only override pinned or lost the inherited review interval"); + throw new Error("Goal option-only override pinned or lost the inherited review interval"); } await count.fill("2"); - await strategy.selectOption("off"); await page.getByRole("button", { name: "预览变更", exact: true }).click(); await applyGoalPreview(); await page.getByRole("button", { name: "恢复沿用设备默认", exact: true }).waitFor(); goalCadence = await readGoalCadence(); if (goalCadence.effective_configuration.source !== "goal_override" || goalCadence.current.count !== 2) throw new Error("Goal override readback failed"); - if (goalCadence.current.stride_strategy !== "off") throw new Error("Goal stride opt-out failed"); - if ((await request(base)).machine_configuration.namespaces.todo_replan_cadence.stride_strategy !== "evidence_conditioned_v1") throw new Error("Goal override changed machine strategy"); - await strategy.selectOption("evidence_conditioned_v1"); + if (goalCadence.current.yardstick_enabled !== true) throw new Error("Goal Yardstick choice was lost by the interval edit"); + if ((await request(base)).machine_configuration.namespaces.todo_replan_cadence.yardstick_enabled === true) throw new Error("Goal override changed the machine preference"); + await yardstick.uncheck(); await page.getByRole("button", { name: "预览变更", exact: true }).click(); await applyGoalPreview(); await page.getByRole("button", { name: "恢复沿用设备默认", exact: true }).waitFor(); - if ((await readGoalCadence()).current.stride_strategy !== "evidence_conditioned_v1") throw new Error("Goal strategy activation failed"); + if ((await readGoalCadence()).current.yardstick_enabled !== false) throw new Error("Goal Yardstick opt-out failed"); await page.getByRole("button", { name: "恢复沿用设备默认", exact: true }).click(); await applyGoalPreview(); await page.getByRole("button", { name: "恢复沿用设备默认", exact: true }).waitFor({ state: "detached" }); @@ -271,8 +267,6 @@ export const replanCadenceScenario = { await unit.focus(); await page.keyboard.press("Tab"); await page.keyboard.press("Tab"); - if (!(await strategy.evaluate((element) => element === document.activeElement))) throw new Error("Strategy is not keyboard reachable"); - await page.keyboard.press("Tab"); assert.equal(await yardstick.evaluate((element) => element === document.activeElement), true, "Measurement review is keyboard reachable"); await page.keyboard.press("Tab"); assert.equal(await advanced.evaluate((element) => element === document.activeElement), true, "Advanced settings is keyboard reachable"); @@ -286,9 +280,9 @@ export const replanCadenceScenario = { await reopenGoalCadence(); const englishUnit = page.getByLabel(/^Review after/); const englishCount = page.getByLabel("Number between reviews", { exact: true }); - const englishStrategy = page.getByLabel(/^Stride strategy/); await waitForInputValue(englishCount, "3"); - if (await englishUnit.inputValue() !== "effective_turns" || await englishStrategy.inputValue() !== "evidence_conditioned_v1") throw new Error("English editor lost the unit or strategy"); + if (await englishUnit.inputValue() !== "effective_turns") throw new Error("English editor lost the unit"); + assert.equal(await page.getByLabel(/^Stride strategy/).count(), 0, "the removed stride switch must not render"); await englishCount.fill("1"); await page.getByRole("button", { name: "Preview changes", exact: true }).click(); await applyGoalPreview("Apply preview"); @@ -306,7 +300,7 @@ export const replanCadenceScenario = { if (inherited.source !== "capability_default" || inherited.configuration.count_unit !== "effective_turns" || inherited.configuration.count !== 6) throw new Error("Removing device policy did not restore product default"); await reopenGoalCadence(); await waitForInputValue(englishCount, "6"); - if (await englishUnit.inputValue() !== "effective_turns" || await englishStrategy.inputValue() !== "evidence_conditioned_v1") throw new Error("Goal editor did not restore product defaults"); + if (await englishUnit.inputValue() !== "effective_turns") throw new Error("Goal editor did not restore product defaults"); await englishCount.fill("5"); await page.getByRole("button", { name: "Preview changes", exact: true }).click(); const failedReadback = holdGoalReadback(); @@ -319,7 +313,7 @@ export const replanCadenceScenario = { const recovery = page.locator(".personal-capability-recovery"); await recovery.getByText("Configuration written; readback unverified", {exact: true}).waitFor(); assert.equal(await englishCount.inputValue(), "5", "A failed readback preserves the submitted draft"); - for (const control of [englishCount, englishUnit, englishStrategy, + for (const control of [englishCount, englishUnit, page.getByRole("button", {name: "Edit JSON", exact: true}), page.getByRole("button", {name: "Preview changes", exact: true}), page.getByRole("button", {name: "Apply preview", exact: true})]) { @@ -354,7 +348,7 @@ export const replanCadenceScenario = { // preference. Editing that interval does not silently pin the switch. const measurementPreference = {namespace: "todo_replan_cadence", namespace_configuration: { schema_version: "todo_replan_cadence_machine_defaults_v2", count_unit: "effective_turns", count: 6, - stride_strategy: "evidence_conditioned_v1", yardstick_enabled: true, + yardstick_enabled: true, }}; const measurementPreview = await request(base + "/preview", measurementPreference); await request(base + "/apply", {...measurementPreference, expected_plan_revision: measurementPreview.plan_revision}); @@ -389,7 +383,7 @@ export const replanCadenceScenario = { await reopenGoalCadence(); assert.equal((await readGoalCadence()).current.yardstick_enabled, true); await page.getByRole("button", {name: "Edit JSON", exact: true}).click(); - await page.locator("#goal-configuration-json").fill(JSON.stringify({count_unit: "effective_turns", count: 3, stride_strategy: "off"})); + await page.locator("#goal-configuration-json").fill(JSON.stringify({count_unit: "effective_turns", count: 3})); await page.getByRole("button", {name: "Back to form", exact: true}).click(); await page.getByRole("button", {name: "Preview changes", exact: true}).click(); await applyGoalPreview("Apply preview"); @@ -397,7 +391,7 @@ export const replanCadenceScenario = { assert.equal((await readGoalCadence()).current.yardstick_enabled, undefined); assert.equal(await englishYardstick.isChecked(), true, "clearing only the switch restores independent device inheritance"); await page.screenshot({path: resolve(outputDir, "yardstick-goal-inherited-desktop.png"), animations: "disabled"}); - return { coverageEntries: context.coverageEntries, note: "Packaged default six effective Turns, machine v0→v2 migration, strategy-only JSON/form inheritance across later machine changes, equal-value explicit pin and interval-only clear, default-off/versioned strategy, invalid preview, Goal override/clear, device removal, mobile keyboard and English labels through real handlers. Independent default-off Yardstick inheritance, explicit false/true and sparse JSON/form clear reuse the same revision-checked handler. Delayed post-apply readback keeps editing closed across capability changes; failed readback retains the disabled draft and invalidates its preview, recovers through GET only, then admits a new explicitly previewed change." }; + return { coverageEntries: context.coverageEntries, note: "Packaged default six effective Turns, machine v0→v2 migration, option-only JSON/form inheritance across later machine changes, equal-value explicit pin and interval-only clear, no stride switch (evidence-conditioned v1 always on), invalid preview, Goal override/clear, device removal, mobile keyboard and English labels through real handlers. Independent default-off Yardstick inheritance, explicit false/true and sparse JSON/form clear reuse the same revision-checked handler. Delayed post-apply readback keeps editing closed across capability changes; failed readback retains the disabled draft and invalidates its preview, recovers through GET only, then admits a new explicitly previewed change." }; } catch (error) { if (context) { await context.page.screenshot({ path: resolve(outputDir, "replan-cadence-failure.png"), animations: "disabled" }); diff --git a/examples/project/configure-goal-smoke.py b/examples/project/configure-goal-smoke.py index 68ebdb0e7a..48515e7f47 100644 --- a/examples/project/configure-goal-smoke.py +++ b/examples/project/configure-goal-smoke.py @@ -332,7 +332,6 @@ def main() -> int: "count_unit": "effective_turns", "count": 6, "planning_horizon_goal": True, - "stride_strategy": "evidence_conditioned_v1", "yardstick_enabled": False, } # Goal-scoped cadence is omitted when no explicit override is present; @@ -346,6 +345,8 @@ def main() -> int: assert "--execute" in replan_commands["apply_enable"] assert "--clear-execution-replan-after-todos" in replan_commands["preview_disable"] assert "--clear-execution-replan-after-turns" in replan_commands["preview_disable"] + # Evidence-conditioned stride is always on; no reset flag exists for it. + assert "stride" not in replan_commands["preview_disable"] assert "--execute" not in replan_commands["preview_disable"] assert "--execute" in replan_commands["apply_disable"] assert features["local_authority_shadow"]["availability"] == "retired" diff --git a/examples/project/goal-vision-refresh-state-budget-smoke.py b/examples/project/goal-vision-refresh-state-budget-smoke.py index 63d9ed62ab..81b97a4e07 100644 --- a/examples/project/goal-vision-refresh-state-budget-smoke.py +++ b/examples/project/goal-vision-refresh-state-budget-smoke.py @@ -62,8 +62,6 @@ def write_fixture(root: Path) -> tuple[Path, Path, Path]: "status": "active", "repo": str(project), "state_file": state_file, - # This fixture isolates vision authoring from Stride review. - "execution_profile": {"stride_strategy": "off"}, "adapter": {"kind": "fixture", "status": "connected-read-only"}, "authority_sources": [], "coordination": { @@ -300,6 +298,11 @@ def assert_vision_budget(provider: str) -> None: "acceptance_summary" ], missing_baseline_gap + valid_packet = json.loads(valid_path.read_text(encoding="utf-8")) + valid_packet["stride_decision"] = missing_baseline_quota[ + "replan_action_packet" + ]["stride_control"]["minimal_example"] + write_json(valid_path, valid_packet) valid = payload( run_cli(registry_path, runtime, vision_path=valid_path, check=True) ) @@ -360,7 +363,7 @@ def assert_vision_budget(provider: str) -> None: ), latest_status_vision assert latest_status_vision["todo_delta"] == ["create_successor"], latest_status_vision assert "field_limits" not in latest_status_vision["vision_budget"], latest_status_vision - assert latest_status_vision["vision_budget"]["field_usage"] == { + expected_usage = { "vision_summary": 63, "role_scope": 38, "acceptance_summary": 44, @@ -371,7 +374,13 @@ def assert_vision_budget(provider: str) -> None: "path_delta.observed_reality": 58, "path_delta.retained[0]": 47, "path_delta.evidence_refs[0]": 27, - }, latest_status_vision + "stride_decision.strategy_version": 23, + } + for key, value in expected_usage.items(): + assert latest_status_vision["vision_budget"]["field_usage"].get(key) == value, ( + key, + latest_status_vision, + ) assert latest_status_checkpoint["agent_id"] == AGENT_ID, latest_status_checkpoint assert latest_status_checkpoint["decision"] == "patched", latest_status_checkpoint assert latest_status_checkpoint["triggers"][0]["kind"] == ( @@ -418,6 +427,7 @@ def assert_vision_budget(provider: str) -> None: )["error"], unexplained_inline_drift.stdout drift_packet = json.loads(valid_path.read_text(encoding="utf-8")) + drift_packet.pop("stride_decision", None) drift_packet["vision_patch"]["vision_summary"] = ( "Wait for one supporting pull request." ) diff --git a/loopx/capabilities/configuration_ui.py b/loopx/capabilities/configuration_ui.py index f40f8bbdd2..3a75d3c2c7 100644 --- a/loopx/capabilities/configuration_ui.py +++ b/loopx/capabilities/configuration_ui.py @@ -6,7 +6,6 @@ from ..configuration_transaction import configuration_payload_revision from ..control_plane.goals.goal_vision_policy import DEFAULT_PLANNING_HORIZON_GOAL, MAX_EFFECTIVE_TURN_REPLAN_THRESHOLD -from ..control_plane.work_items.stride_policy_codec import stride_strategy_options from .progress_review.policy import ( PROGRESS_REVIEW_MAX_DRIFT_THRESHOLD, @@ -156,9 +155,6 @@ def capability_configuration_editor( description="Effective Turns: 1–6; completed Todos: 1–5. Effective Turns require accepted work settlement. Retries and observation-only polls do not count."), _field("planning_horizon_goal", "Show Goal in planning horizon", "boolean", description="Default on. Include the original Goal and acceptance before choosing work. Advanced opt-out for rollback or comparisons; does not change replan, stride or execution authority."), - _field("stride_strategy", "Stride strategy", "select", - options=list(stride_strategy_options()), - description="Off retains ordinary review. Evidence-conditioned v1 independently reviews work-slice size, route changes and validation scope; fresh Vision path reviews require a structured proposal, without automatic execution."), _field("yardstick_enabled", "Review measurement criteria", "boolean", description="Default off. Use available Explore evidence to review measurement scope and feedback before choosing work. Requires Explore evidence; does not enable it or authorize execution."), ], @@ -723,15 +719,15 @@ def _attach_effective_configuration(entry: dict[str, Any]) -> None: entry["capability_id"] == "todo_replan_cadence" and goal_override is not None and bool(goal_override) - and set(goal_override) <= {"stride_strategy", "planning_horizon_goal", "yardstick_enabled"} + and set(goal_override) <= {"planning_horizon_goal", "yardstick_enabled"} ): from .todo_replan_cadence.machine_defaults import ( cadence_configuration_value, default_replan_cadence_configuration, ) - # The Goal chooses the strategy while the existing review cadence stays - # live. Keep `current` sparse so readback does not claim a pinned count. + # The Goal chooses horizon/Yardstick while the existing review cadence + # stays live. Keep `current` sparse so readback does not claim a pinned count. inherited_cadence = ( cadence_configuration_value(machine_default) if machine_default is not None diff --git a/loopx/capabilities/todo_replan_cadence/goal_configuration.py b/loopx/capabilities/todo_replan_cadence/goal_configuration.py index 80de6d1107..06b47fdbc6 100644 --- a/loopx/capabilities/todo_replan_cadence/goal_configuration.py +++ b/loopx/capabilities/todo_replan_cadence/goal_configuration.py @@ -12,7 +12,7 @@ def configuration_summary(goal: Mapping[str, Any]) -> dict[str, Any] | None: profile = goal.get("execution_profile") if not isinstance(profile, Mapping): return None - strategy = {key: profile[key] for key in ("stride_strategy", "planning_horizon_goal", "yardstick_enabled") if key in profile} + strategy = {key: profile[key] for key in ("planning_horizon_goal", "yardstick_enabled") if key in profile} if "replan_after_effective_turns" in profile: return { "count_unit": "effective_turns", diff --git a/loopx/capabilities/todo_replan_cadence/machine_defaults.py b/loopx/capabilities/todo_replan_cadence/machine_defaults.py index b15113e49c..e11081a7c9 100644 --- a/loopx/capabilities/todo_replan_cadence/machine_defaults.py +++ b/loopx/capabilities/todo_replan_cadence/machine_defaults.py @@ -30,6 +30,32 @@ class ReplanCadenceUnit(str, Enum): TODO_REPLAN_CADENCE_MACHINE_DEFAULTS_V1 = "todo_replan_cadence_machine_defaults_v1" TODO_REPLAN_CADENCE_MACHINE_DEFAULTS_V2 = "todo_replan_cadence_machine_defaults_v2" +# Removed live switch. Evidence-conditioned stride is unconditional; saved v2 +# machine files and Goal profiles may still carry this key, so reads validate +# the historical value and then drop it. Nothing displays or acts on "off". +LEGACY_STRIDE_STRATEGY_KEY = "stride_strategy" + + +def _validate_legacy_stride_strategy(value: Any) -> None: + from ...control_plane.work_items.stride_policy_codec import normalize_stride_strategy + + normalize_stride_strategy(value) + + +def reject_removed_stride_strategy(update: Mapping[str, Any]) -> None: + """Writes no longer accept the removed switch; legacy reads still decode.""" + + if LEGACY_STRIDE_STRATEGY_KEY in update: + raise ValueError( + "stride_strategy was removed: evidence_conditioned_v1 stride is always on " + "and cannot be configured" + ) + + +def _apply_public_update(_current: Any, update: Mapping[str, Any]) -> dict[str, Any]: + reject_removed_stride_strategy(update) + return dict(update) + def normalize_replan_cadence_configuration(raw: Mapping[str, Any]) -> dict[str, Any]: if set(raw) == {"completed_todos"}: @@ -37,7 +63,7 @@ def normalize_replan_cadence_configuration(raw: Mapping[str, Any]) -> dict[str, "count_unit": ReplanCadenceUnit.COMPLETED_TODOS.value, "count": normalize_completed_todo_replan_threshold(raw["completed_todos"]), } - if not {"count_unit", "count"} <= set(raw) or set(raw) - {"count_unit", "count", "stride_strategy", "planning_horizon_goal", "yardstick_enabled"}: + if not {"count_unit", "count"} <= set(raw) or set(raw) - {"count_unit", "count", LEGACY_STRIDE_STRATEGY_KEY, "planning_horizon_goal", "yardstick_enabled"}: raise ValueError("review cadence requires count_unit and count") try: unit = ReplanCadenceUnit(raw["count_unit"]) @@ -51,9 +77,8 @@ def normalize_replan_cadence_configuration(raw: Mapping[str, Any]) -> dict[str, else: count = normalize_effective_turn_replan_threshold(count) result = {"count_unit": unit.value, "count": count} - if "stride_strategy" in raw: - from ...control_plane.work_items.stride_policy_codec import normalize_stride_strategy - result["stride_strategy"] = normalize_stride_strategy(raw["stride_strategy"]) + if LEGACY_STRIDE_STRATEGY_KEY in raw: + _validate_legacy_stride_strategy(raw[LEGACY_STRIDE_STRATEGY_KEY]) if "planning_horizon_goal" in raw: if not isinstance(raw["planning_horizon_goal"], bool): raise ValueError("planning_horizon_goal must be a boolean") @@ -82,7 +107,8 @@ def normalize_todo_replan_cadence_machine_defaults( raise ValueError("todo_replan_cadence must use a supported v0, v1 or v2 schema") expected = {"schema_version", "count_unit", "count"} if version == TODO_REPLAN_CADENCE_MACHINE_DEFAULTS_V2: - expected.add("stride_strategy") + if LEGACY_STRIDE_STRATEGY_KEY in raw: + expected.add(LEGACY_STRIDE_STRATEGY_KEY) if "planning_horizon_goal" in raw: expected.add("planning_horizon_goal") if "yardstick_enabled" in raw: @@ -110,7 +136,6 @@ def default_replan_cadence_configuration() -> dict[str, Any]: "count_unit": ReplanCadenceUnit.EFFECTIVE_TURNS.value, "count": DEFAULT_EFFECTIVE_TURN_REPLAN_THRESHOLD, "planning_horizon_goal": DEFAULT_PLANNING_HORIZON_GOAL, - "stride_strategy": "evidence_conditioned_v1", "yardstick_enabled": False, } @@ -129,12 +154,12 @@ def todo_replan_cadence_machine_configuration_namespace() -> ( ), normalize=normalize_todo_replan_cadence_machine_defaults, project_public=lambda value: dict(value), - apply_public_update=lambda _current, update: dict(update), + apply_public_update=_apply_public_update, title="Goal review and stride", description=( "Live review threshold for Goals without an explicit cadence override. " "Defaults to six settled work Turns; completed Todos remain an explicit option. " - "Evidence-conditioned stride is enabled by default; fresh Vision reviews require a bounded structured work-shape proposal. Explicit off and legacy saved configurations retain their meaning. " + "Evidence-conditioned stride is always on; fresh Vision reviews require a bounded structured work-shape proposal. " "It does not create " "turns, spend quota, or grant authority." ), @@ -179,7 +204,8 @@ def apply_todo_replan_cadence_machine_default( if cadence is None: cadence = default_replan_cadence_configuration() profile = dict(raw_profile) if isinstance(raw_profile, Mapping) else {} - # Yardstick is independent of the legacy cadence/stride override. Keep + profile.pop(LEGACY_STRIDE_STRATEGY_KEY, None) + # Yardstick is independent of the cadence override. Keep # absence sparse and default-off; explicit false always wins inheritance. if "yardstick_enabled" not in profile and cadence.get("yardstick_enabled") is True: profile["yardstick_enabled"] = True @@ -193,8 +219,6 @@ def apply_todo_replan_cadence_machine_default( else "replan_after_completed_todos" ) profile[field] = cadence["count"] - if "stride_strategy" not in profile and cadence.get("stride_strategy", "off") != "off": - profile["stride_strategy"] = cadence["stride_strategy"] if "planning_horizon_goal" not in profile and "planning_horizon_goal" in cadence: profile["planning_horizon_goal"] = cadence["planning_horizon_goal"] projected["execution_profile"] = profile diff --git a/loopx/chat/goal_configuration_api.py b/loopx/chat/goal_configuration_api.py index 64dcfb383c..2c13e0be77 100644 --- a/loopx/chat/goal_configuration_api.py +++ b/loopx/chat/goal_configuration_api.py @@ -201,7 +201,7 @@ def _goal_capability_options( if capability_id == "periodic_report": return {"clear_periodic_report_configuration": True} if capability_id == "todo_replan_cadence": - return {"clear_execution_replan_after_todos": True, "clear_execution_replan_after_turns": True, "clear_execution_stride_strategy": True, "clear_execution_planning_horizon_goal": True, "clear_execution_yardstick_enabled": True} + return {"clear_execution_replan_after_todos": True, "clear_execution_replan_after_turns": True, "clear_execution_planning_horizon_goal": True, "clear_execution_yardstick_enabled": True} if capability_id == "pull_request_review": return {"clear_pull_request_review_configuration": True} if capability_id == "change_quality_qualification": @@ -214,7 +214,7 @@ def _goal_capability_options( config = dict(configuration) allowed: dict[str, set[str]] = { "goal_capability_organization": {"mode", "discovery_budget_minutes", "max_trials"}, - "todo_replan_cadence": {"completed_todos", "count_unit", "count", "stride_strategy", "planning_horizon_goal", "yardstick_enabled"}, + "todo_replan_cadence": {"completed_todos", "count_unit", "count", "planning_horizon_goal", "yardstick_enabled"}, "multi_subagent": { "enabled", "max_children", @@ -237,6 +237,9 @@ def _goal_capability_options( } if capability_id not in allowed: raise ValueError(f"Goal capability is read-only in Dashboard: {capability_id}") + if capability_id == "todo_replan_cadence" and "stride_strategy" in config: + from ..capabilities.todo_replan_cadence.machine_defaults import reject_removed_stride_strategy + reject_removed_stride_strategy(config) unknown = sorted(set(config) - allowed[capability_id]) if unknown: raise ValueError( @@ -249,7 +252,6 @@ def _goal_capability_options( return {"capability_improvement_configuration": config} if capability_id == "todo_replan_cadence": from ..capabilities.todo_replan_cadence.machine_defaults import normalize_replan_cadence_configuration - from ..control_plane.work_items.stride_policy_codec import normalize_stride_strategy horizon = {"clear_execution_planning_horizon_goal": True} if "planning_horizon_goal" in config: if not isinstance(config["planning_horizon_goal"], bool): @@ -260,22 +262,19 @@ def _goal_capability_options( if not isinstance(config["yardstick_enabled"], bool): raise ValueError("yardstick_enabled must be a boolean") yardstick = {"execution_yardstick_enabled": config["yardstick_enabled"]} - if config and set(config) <= {"stride_strategy", "planning_horizon_goal", "yardstick_enabled"}: - # The capability editor submits the complete sparse value. Unlike - # the CLI's single-field strategy patch, omission restores live - # interval inheritance even when this Goal was previously pinned. + if config and set(config) <= {"planning_horizon_goal", "yardstick_enabled"}: + # The capability editor submits the complete sparse value; omitting + # the interval restores live inheritance even when this Goal was + # previously pinned. return { **horizon, **yardstick, - **({"execution_stride_strategy": normalize_stride_strategy(config["stride_strategy"])} - if "stride_strategy" in config else {}), "clear_execution_replan_after_turns": True, "clear_execution_replan_after_todos": True, } cadence = normalize_replan_cadence_configuration(config) option = ("execution_replan_after_turns" if cadence["count_unit"] == "effective_turns" else "execution_replan_after_todos") - return {option: cadence["count"], **horizon, **yardstick, **({"execution_stride_strategy": cadence["stride_strategy"]} - if "stride_strategy" in cadence else {})} + return {option: cadence["count"], **horizon, **yardstick} if capability_id == "periodic_report": from ..capabilities.periodic_report.goal_configuration import normalize_configuration # Validate the payload before the Session guard reads native sources. diff --git a/loopx/cli_commands/goal_amendment_proposal.py b/loopx/cli_commands/goal_amendment_proposal.py index efd8e8d485..7f98b29ae3 100644 --- a/loopx/cli_commands/goal_amendment_proposal.py +++ b/loopx/cli_commands/goal_amendment_proposal.py @@ -207,12 +207,10 @@ def handle_goal_amendment_proposal_command( if "operation_id" in parameters: raise ValueError("supply operation_id once") parameters["operation_id"] = args.operation_id - from ..capabilities.todo_replan_cadence.machine_defaults import resolve_todo_replan_cadence_goal payload = execute_goal_amendment(registry_path=registry_path, goal_id=goal_id, goal_instance_id=args.goal_instance_id, operation=args.governed, actor_agent_id=args.agent_id, parameters=parameters, - runtime_root=runtime_root, execute=args.execute, - replan_configuration_reader=resolve_todo_replan_cadence_goal) + runtime_root=runtime_root, execute=args.execute) accepted = payload.get("ok") is True print_payload(payload, output_format(args), render_goal_amendment_proposal_markdown) return 0 if accepted else 1 diff --git a/loopx/cli_commands/manager_inbox.py b/loopx/cli_commands/manager_inbox.py index 4d744b3155..2d191e97a3 100644 --- a/loopx/cli_commands/manager_inbox.py +++ b/loopx/cli_commands/manager_inbox.py @@ -334,10 +334,8 @@ def handle_manager_inbox(args, registry_path, runtime_root): raise ValueError("control parameters must be an object; use --operation-id for retry identity") if args.control_operation in {"revise", "cancel"}: parameters["operation_id"] = args.operation_id - from ..capabilities.todo_replan_cadence.machine_defaults import resolve_todo_replan_cadence_goal result = control_request(registry_path=registry_path, runtime_root=runtime_root, - replan_configuration_reader=resolve_todo_replan_cadence_goal, goal_ref=exact_goal_ref(args.goal_id, args.goal_instance_id), receiver_agent_id=receiver, request_id=args.request_id, actor_agent_id=args.agent_id, operation=args.control_operation, parameters=parameters, execute=args.execute) diff --git a/loopx/cli_commands/project_lifecycle_inputs.py b/loopx/cli_commands/project_lifecycle_inputs.py index 2644cd21b0..36947d25a8 100644 --- a/loopx/cli_commands/project_lifecycle_inputs.py +++ b/loopx/cli_commands/project_lifecycle_inputs.py @@ -273,7 +273,6 @@ def parse_refresh_state_inputs( existing_agent_vision=None, merge_patch=False, require_path_delta_for_durable_change=False, - allow_terminal_stride_path=True, ) progress_observation = inline_progress_observation(args) diff --git a/loopx/cli_commands/registry_admin.py b/loopx/cli_commands/registry_admin.py index 32c1e56dcb..a0cff3cb8c 100644 --- a/loopx/cli_commands/registry_admin.py +++ b/loopx/cli_commands/registry_admin.py @@ -469,8 +469,6 @@ def handle_registry_admin_command( clear_execution_planning_horizon_goal=args.clear_execution_planning_horizon_goal, execution_yardstick_enabled=args.execution_yardstick_enabled, clear_execution_yardstick_enabled=args.clear_execution_yardstick_enabled, - execution_stride_strategy=args.execution_stride_strategy, - clear_execution_stride_strategy=args.clear_execution_stride_strategy, clear_execution_replan_after_turns=args.clear_execution_replan_after_turns, clear_execution_replan_after_todos=bool( args.clear_execution_replan_after_todos diff --git a/loopx/cli_commands/registry_admin_configure.py b/loopx/cli_commands/registry_admin_configure.py index 39c958fb60..b8f079d0b8 100644 --- a/loopx/cli_commands/registry_admin_configure.py +++ b/loopx/cli_commands/registry_admin_configure.py @@ -91,15 +91,6 @@ def register_configure_goal_command(subparsers: argparse._SubParsersAction) -> N "--clear-execution-yardstick-enabled", action="store_true", help="Remove the Goal Yardstick choice and restore the live device preference.", ) - from ..control_plane.work_items.stride_policy_codec import stride_strategy_options - configure_goal_parser.add_argument( - "--execution-stride-strategy", choices=stride_strategy_options(), - help="Choose a versioned Agent stride strategy. Off preserves ordinary review; no automatic execution or authority change.", - ) - configure_goal_parser.add_argument( - "--clear-execution-stride-strategy", action="store_true", - help="Remove the strategy from the Goal review override (off). Clear the review cadence too to restore device defaults.", - ) configure_goal_parser.add_argument( "--quota-compute", type=float, diff --git a/loopx/collaboration_mcp.py b/loopx/collaboration_mcp.py index 4c032d292b..8d1e533bb1 100644 --- a/loopx/collaboration_mcp.py +++ b/loopx/collaboration_mcp.py @@ -417,11 +417,9 @@ def control_peer_request(request_id: str, receiver_agent_id: str, not revoke committed Goal work or grant new execution permission. """ from .control_plane.collaboration.request_amendment import control_request - from .capabilities.todo_replan_cadence.machine_defaults import resolve_todo_replan_cadence_goal check_scope() return control_request(registry_path=registry, runtime_root=root, goal_ref=caller_goal_ref, - replan_configuration_reader=resolve_todo_replan_cadence_goal, receiver_agent_id=receiver_agent_id, request_id=request_id, actor_agent_id=agent_id, operation=operation, parameters=parameters, execute=execute) diff --git a/loopx/configuration_catalog.py b/loopx/configuration_catalog.py index 18ee62fa33..42e3444484 100644 --- a/loopx/configuration_catalog.py +++ b/loopx/configuration_catalog.py @@ -170,7 +170,7 @@ def build_goal_configuration_catalog( "effect": ( "Choose 1–6 settled work Turns or 1–5 completed Todos per Agent. " "Legacy settings retain their completed-Todo units until explicitly changed. " - "The optional versioned stride strategy proposes work-slice and route adjustments; off retains ordinary review." + "Evidence-conditioned stride (v1) is always on: fresh Vision reviews propose bounded work-slice and route adjustments." ), "does_not": [ "create host continuation turns or interrupt running work", @@ -187,10 +187,10 @@ def build_goal_configuration_catalog( str(default_replan_cadence_configuration()["count"]), execute=True ), "preview_disable": _configure_command( - goal_id, "--clear-execution-replan-after-todos", "--clear-execution-replan-after-turns", "--clear-execution-stride-strategy" + goal_id, "--clear-execution-replan-after-todos", "--clear-execution-replan-after-turns" ), "apply_disable": _configure_command( - goal_id, "--clear-execution-replan-after-todos", "--clear-execution-replan-after-turns", "--clear-execution-stride-strategy", execute=True + goal_id, "--clear-execution-replan-after-todos", "--clear-execution-replan-after-turns", execute=True ), "verify": [inspect_command], }, diff --git a/loopx/configure_goal.py b/loopx/configure_goal.py index 4ac5f6c14b..d5144ba351 100644 --- a/loopx/configure_goal.py +++ b/loopx/configure_goal.py @@ -438,8 +438,6 @@ def configure_goal( execution_turn_granularity: str | None = None, execution_replan_after_todos: int | None = None, execution_replan_after_turns: int | None = None, - execution_stride_strategy: str | None = None, - clear_execution_stride_strategy: bool = False, execution_planning_horizon_goal: bool | None = None, clear_execution_planning_horizon_goal: bool = False, execution_yardstick_enabled: bool | None = None, @@ -837,7 +835,6 @@ def configure_goal( turn_granularity=execution_turn_granularity, replan_after_completed_todos=execution_replan_after_todos, replan_after_effective_turns=execution_replan_after_turns, - stride_strategy=execution_stride_strategy, clear_stride_strategy=clear_execution_stride_strategy, planning_horizon_goal=execution_planning_horizon_goal, clear_planning_horizon_goal=clear_execution_planning_horizon_goal, yardstick_enabled=execution_yardstick_enabled, diff --git a/loopx/control_plane/collaboration/request_amendment.py b/loopx/control_plane/collaboration/request_amendment.py index 257ceb29ee..4a91039b21 100644 --- a/loopx/control_plane/collaboration/request_amendment.py +++ b/loopx/control_plane/collaboration/request_amendment.py @@ -6,7 +6,6 @@ from __future__ import annotations from pathlib import Path -from collections.abc import Callable from typing import Any, Mapping from .request_control_source import _execute, execute_request_control, request_amendment_snapshot @@ -46,25 +45,21 @@ def _reservation(snapshot: Mapping[str, Any], operation_id: Any) -> dict[str, An def _goal(registry: Path, root: Path, ref: Mapping[str, str], receiver: str, operation: str, parameters: Mapping[str, Any], *, context: Mapping[str, Any] | None = None, - replan_configuration_reader: Callable[[Mapping[str, Any], Path], Mapping[str, Any]], execute: bool = False) -> dict[str, Any]: return _execute_goal_amendment(registry_path=registry, runtime_root=root, goal_id=ref["goal_id"], goal_instance_id=ref["goal_instance_id"], actor_agent_id=None if operation == "receipt" else receiver, - operation=operation, parameters=parameters, request_context=context, execute=execute, - replan_configuration_reader=replan_configuration_reader) + operation=operation, parameters=parameters, request_context=context, execute=execute) def _finish(*, registry: Path, root: Path, ref: Mapping[str, str], receiver: str, actor: str | None, snapshot: dict[str, Any], reservation: dict[str, Any], execute: bool, - replan_configuration_reader: Callable[[Mapping[str, Any], Path], Mapping[str, Any]], attempt_observation: Mapping[str, Any] | None = None) -> dict[str, Any]: """Re-read the actual Goal receipt, then link it at the request owner.""" terminal = None errors = [] bound = reservation["binding"] try: - readback = _goal(registry, root, ref, receiver, "receipt", {"receipt_operation_id": bound["operation_id"]}, - replan_configuration_reader=replan_configuration_reader) + readback = _goal(registry, root, ref, receiver, "receipt", {"receipt_operation_id": bound["operation_id"]}) observation = effect_runtime_result("goal.amendment.request_receipt", { "entry": snapshot["_entry"], "reservation_digest": reservation["digest"], "receipt": readback}) terminal = observation["terminal"] @@ -97,7 +92,6 @@ def _finish(*, registry: Path, root: Path, ref: Mapping[str, str], receiver: str def execute_request_amendment(*, registry_path: Path, runtime_root: Path | None, goal_ref: Mapping[str, str], - replan_configuration_reader: Callable[[Mapping[str, Any], Path], Mapping[str, Any]], receiver_agent_id: str, parameters: Mapping[str, Any], execute: bool) -> dict[str, Any]: if set(parameters) != {"source_request", "operation_id", "proposal_id", "proposal_digest"}: raise ValueError("request-derived commit needs the original proposal, source basis and operation id") @@ -112,8 +106,7 @@ def execute_request_amendment(*, registry_path: Path, runtime_root: Path | None, reservation = _reservation(snapshot, parameters["operation_id"]) if reservation is None: # Resolve from the real Goal owner, not caller-provided policy/basis. - goal = _goal(registry_path, root, goal_ref, receiver_agent_id, "request_basis", {}, - replan_configuration_reader=replan_configuration_reader) + goal = _goal(registry_path, root, goal_ref, receiver_agent_id, "request_basis", {}) if goal.get("ok") is not True or not isinstance(goal.get("intent"), dict): raise ValueError("current Goal amendment authority is unavailable") proposal = next((row for row in goal["intent"]["proposals"] if row["proposal_id"] == parameters["proposal_id"]), None) @@ -136,24 +129,20 @@ def execute_request_amendment(*, registry_path: Path, runtime_root: Path | None, context = {"entry": snapshot["_entry"], "reservation_digest": reservation["digest"], "preview": not execute} effect = {key: parameters[key] for key in ("operation_id", "proposal_id", "proposal_digest")} if not execute: - preview = _goal(registry_path, root, goal_ref, receiver_agent_id, "commit", effect, context=context, - replan_configuration_reader=replan_configuration_reader) + preview = _goal(registry_path, root, goal_ref, receiver_agent_id, "commit", effect, context=context) return {**preview, "request_preview": snapshot["view"], "request_reservation_recorded": not snapshot.get("planned", False)} try: - attempted = _goal(registry_path, root, goal_ref, receiver_agent_id, "commit", effect, context=context, execute=True, - replan_configuration_reader=replan_configuration_reader) + attempted = _goal(registry_path, root, goal_ref, receiver_agent_id, "commit", effect, context=context, execute=True) observation = {key: attempted[key] for key in ("status", "reason_code", "reason") if key in attempted} except (OSError, ValueError, EffectRuntimeRejected) as exc: # The exact receipt # read below owns that conclusion and keeps an absent result pending. observation = {"error": str(exc)} return _finish(registry=registry_path, root=root, ref=goal_ref, receiver=receiver_agent_id, - actor=receiver_agent_id, snapshot=snapshot, reservation=reservation, execute=True, attempt_observation=observation, - replan_configuration_reader=replan_configuration_reader) + actor=receiver_agent_id, snapshot=snapshot, reservation=reservation, execute=True, attempt_observation=observation) def recover_request_amendment(*, registry_path: Path, runtime_root: Path, goal_ref: Mapping[str, str], - replan_configuration_reader: Callable[[Mapping[str, Any], Path], Mapping[str, Any]], receiver_agent_id: str, request_id: str, actor_agent_id: str | None, execute: bool = False) -> dict[str, Any]: root = _root(registry_path, runtime_root) @@ -168,18 +157,15 @@ def recover_request_amendment(*, registry_path: Path, runtime_root: Path, goal_r try: attempted = _goal(registry_path, root, goal_ref, receiver_agent_id, "abort_request", {key: bound[key] for key in ("operation_id", "proposal_id", "proposal_digest")}, - context={"entry": snapshot["_entry"], "reservation_digest": reservation["digest"]}, execute=True, - replan_configuration_reader=replan_configuration_reader) + context={"entry": snapshot["_entry"], "reservation_digest": reservation["digest"]}, execute=True) observation = {key: attempted[key] for key in ("status", "reason_code", "reason") if key in attempted} except (OSError, ValueError, EffectRuntimeRejected) as exc: observation = {"error": str(exc)} # Read the receipt; never infer an abort. return _finish(registry=registry_path, root=root, ref=goal_ref, receiver=receiver_agent_id, - actor=actor_agent_id, snapshot=snapshot, reservation=reservation, execute=execute, attempt_observation=observation, - replan_configuration_reader=replan_configuration_reader) + actor=actor_agent_id, snapshot=snapshot, reservation=reservation, execute=execute, attempt_observation=observation) def control_request(*, registry_path: Path, runtime_root: Path, goal_ref: Mapping[str, str], - replan_configuration_reader: Callable[[Mapping[str, Any], Path], Mapping[str, Any]], receiver_agent_id: str, request_id: str, actor_agent_id: str | None, operation: str, parameters: Mapping[str, Any] | None = None, execute: bool = False) -> dict[str, Any]: """Shared source UI/CLI path; cancellation settles only through its owner.""" @@ -188,12 +174,12 @@ def control_request(*, registry_path: Path, runtime_root: Path, goal_ref: Mappin if operation == "recover": if parameters: raise ValueError("request recovery takes its binding from the original source") - return recover_request_amendment(**common, execute=execute, replan_configuration_reader=replan_configuration_reader) + return recover_request_amendment(**common, execute=execute) if operation not in {"inspect", "revise", "cancel"}: raise ValueError("source request control operation is unsupported") result = execute_request_control(**common, operation=operation, parameters=parameters, execute=execute) if execute and (operation == "cancel" or result["view"].get("recovery_operation") == "abort_request"): - recovery = recover_request_amendment(**common, execute=True, replan_configuration_reader=replan_configuration_reader) + recovery = recover_request_amendment(**common, execute=True) return {**result, "ok": recovery["ok"], "view": recovery.get("request_control", recovery.get("view")), "effect_recovery": recovery} return result diff --git a/loopx/control_plane/goals/goal_amendment_runtime.py b/loopx/control_plane/goals/goal_amendment_runtime.py index 07eb3f28f1..f7ffd31576 100644 --- a/loopx/control_plane/goals/goal_amendment_runtime.py +++ b/loopx/control_plane/goals/goal_amendment_runtime.py @@ -6,7 +6,6 @@ from __future__ import annotations import json -from collections.abc import Callable from pathlib import Path from typing import Any, Mapping @@ -24,8 +23,7 @@ from ..work_items.autonomous_replan_obligation import ensure_replan_novelty_policy -def _replan_readback(derived: Mapping[str, Any], inventory: list[dict[str, Any]], view: Mapping[str, Any], - *, stride_strategy: str = "off") -> list[dict[str, Any]]: +def _replan_readback(derived: Mapping[str, Any], inventory: list[dict[str, Any]], view: Mapping[str, Any]) -> list[dict[str, Any]]: """Transport the existing replan owner's decisions, never create an ACK.""" if view.get("current_lifetime") is not True or not isinstance(view.get("intent"), dict): return [] @@ -41,11 +39,9 @@ def _replan_readback(derived: Mapping[str, Any], inventory: list[dict[str, Any]] obligation = obligations[item["obligation_id"]] for agent in item["bound_agent_ids"]: ack = replan_successor_transition_ack(None, agent_id=agent, - replan_obligation=obligation, agent_todo_items=view.get("work_items") or [], - stride_strategy=stride_strategy) + replan_obligation=obligation, agent_todo_items=view.get("work_items") or []) accepted = autonomous_replan_ack_satisfies_obligation(ack, - replan_obligation=obligation, acceptance_gaps=None, - stride_strategy=stride_strategy) + replan_obligation=obligation, acceptance_gaps=None) rows.append({"obligation_id": item["obligation_id"], "agent_id": agent, "state": "settled" if accepted else "pending", "acknowledgement": ack if accepted else None, @@ -56,7 +52,6 @@ def _replan_readback(derived: Mapping[str, Any], inventory: list[dict[str, Any]] def _execute_goal_amendment( *, registry_path: Path, goal_id: str, goal_instance_id: str, operation: str, actor_agent_id: str | None, - replan_configuration_reader: Callable[[Mapping[str, Any], Path], Mapping[str, Any]], parameters: Mapping[str, Any] | None = None, runtime_root: Path | None = None, execute: bool = False, request_context: Mapping[str, Any] | None = None, @@ -92,7 +87,6 @@ def _execute_goal_amendment( gate_path = source_turn_effect_gate_path(registry_path, goal_id) gate = json.loads(gate_path.read_text(encoding="utf-8")) if gate_path.exists() else None agents = registered_agent_ids_for_goal(goal) - effective_replan_goal: Mapping[str, Any] | None = None derived = _derive_open_replan_obligation_inventory(runtime_root=root, goal_id=goal_id, goal=goal, state_text="", goal_ref=goal_ref) obligations = _open_replan_obligation_inventory(goal_id=goal_id, registered_agents=agents, status_item=derived) @@ -114,17 +108,11 @@ def _execute_goal_amendment( "runtime_root": str(root), "observed_at": now_utc_iso(), "source": source} def inspect() -> dict[str, Any]: - nonlocal effective_replan_goal value = effect_runtime_result("goal.amendment.execute", {**common, "operation": "inspect", "dry_run": True}, timeout=CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS) if not isinstance(value, dict): raise TypeError("Goal amendment readback is invalid") - # Resolve once for current review observations. Historical - # receipt lookup must not depend on current configuration IO. - if effective_replan_goal is None: - effective_replan_goal = replan_configuration_reader(goal, root) - value["replan_observations"] = _replan_readback(derived, obligations, value, - stride_strategy=(effective_replan_goal.get("execution_profile") or {}).get("stride_strategy", "off")) + value["replan_observations"] = _replan_readback(derived, obligations, value) return value if operation in {"propose", "commit", "claim"}: @@ -152,7 +140,6 @@ def inspect() -> dict[str, Any]: def execute_goal_amendment( *, registry_path: Path, goal_id: str, goal_instance_id: str, operation: str, actor_agent_id: str | None, - replan_configuration_reader: Callable[[Mapping[str, Any], Path], Mapping[str, Any]], parameters: Mapping[str, Any] | None = None, runtime_root: Path | None = None, execute: bool = False, ) -> dict[str, Any]: @@ -162,8 +149,7 @@ def execute_goal_amendment( raise ValueError("request effect recovery must use its original request entrypoint") if "source_request" not in params: return _execute_goal_amendment(registry_path=registry_path, goal_id=goal_id, goal_instance_id=goal_instance_id, - operation=operation, actor_agent_id=actor_agent_id, parameters=params, runtime_root=runtime_root, execute=execute, - replan_configuration_reader=replan_configuration_reader) + operation=operation, actor_agent_id=actor_agent_id, parameters=params, runtime_root=runtime_root, execute=execute) if operation not in {"propose", "commit"} or actor_agent_id is None: raise ValueError("source request context requires an explicit receiver proposal or commit") from ..collaboration.request_amendment import execute_request_amendment, request_proposal_context @@ -171,9 +157,9 @@ def execute_goal_amendment( if operation == "commit": return execute_request_amendment(registry_path=registry_path, runtime_root=runtime_root, goal_ref=exact_goal_ref(goal_id, goal_instance_id), receiver_agent_id=actor_agent_id, - parameters=params, execute=execute, replan_configuration_reader=replan_configuration_reader) + parameters=params, execute=execute) root, context = request_proposal_context(registry_path=registry_path, runtime_root=runtime_root, goal_ref=exact_goal_ref(goal_id, goal_instance_id), receiver_agent_id=actor_agent_id, reference=params["source_request"]) return _execute_goal_amendment(registry_path=registry_path, goal_id=goal_id, goal_instance_id=goal_instance_id, operation="propose", actor_agent_id=actor_agent_id, parameters=params, runtime_root=root, - execute=execute, request_context=context, replan_configuration_reader=replan_configuration_reader) + execute=execute, request_context=context) diff --git a/loopx/control_plane/goals/goal_frontier/__init__.py b/loopx/control_plane/goals/goal_frontier/__init__.py index 42f04bf906..f83e84745e 100644 --- a/loopx/control_plane/goals/goal_frontier/__init__.py +++ b/loopx/control_plane/goals/goal_frontier/__init__.py @@ -1591,15 +1591,11 @@ def build_goal_frontier_projection_context_from_status( acceptance_gaps=source_acceptance_gaps, goal_id=goal_id, agent_id=agent_id, runtime_root=status_payload.get("runtime_root"), ) - stride_strategy = ((project_asset or {}).get("execution_profile") or {}).get( - "stride_strategy", "off" - ) replan_transition_ack = replan_successor_transition_ack( agent_todo_summary, agent_id=agent_id, replan_obligation=replan_obligation, agent_todo_items=agent_todo_source_items, - stride_strategy=stride_strategy, ) # Keep the validated history-obligation transition distinct from any # successor frontier obligation derived below. Exact Turn settlement may @@ -1614,7 +1610,6 @@ def build_goal_frontier_projection_context_from_status( replan_obligation=replan_obligation, acceptance_gaps=source_acceptance_gaps, todo_succession_gap_open=todo_succession_gap_open, - stride_strategy=stride_strategy, ) and autonomous_replan_ack_matches_frontier( obligation_ack, @@ -1653,7 +1648,6 @@ def build_goal_frontier_projection_context_from_status( agent_id=agent_id, replan_obligation=frontier_replan_obligation, agent_todo_items=agent_todo_source_items, - stride_strategy=stride_strategy, ) frontier_obligation_ack = frontier_transition_ack or effective_replan_ack frontier_transition_candidate = {"obligation": frontier_replan_obligation, "ack": frontier_transition_ack} @@ -1696,7 +1690,6 @@ def build_goal_frontier_projection_context_from_status( source_ack = replan_successor_transition_ack( agent_todo_summary, agent_id=agent_id, replan_obligation=source, agent_todo_items=agent_todo_source_items, - stride_strategy=stride_strategy, ) frontier_transition_candidate = { "obligation": source, @@ -1731,7 +1724,6 @@ def build_goal_frontier_projection_context_from_status( replan_obligation=frontier_replan_obligation, acceptance_gaps=source_acceptance_gaps, todo_succession_gap_open=todo_succession_gap_open, - stride_strategy=stride_strategy, ) and autonomous_replan_ack_matches_frontier( frontier_obligation_ack, @@ -1754,7 +1746,7 @@ def build_goal_frontier_projection_context_from_status( replan_obligation = attach_receipt_replan_context( replan_obligation, lifecycle_candidate, goal_id=goal_id, agent_id=agent_id, - source_status=status_payload, stride_strategy=stride_strategy, + source_status=status_payload, explore_reader=replan_explore_reader, todo_items=agent_todo_source_items, goal_acceptance_contract=(agent_todo_summary or {}).get("goal_acceptance_contract"), receipt_bound_replan_obligation_id=receipt_bound_replan_obligation_id, @@ -1779,7 +1771,6 @@ def build_goal_frontier_projection_context_from_status( return { "schema_version": "goal_frontier_projection_context_v0", "replan_obligation": replan_obligation, - "stride_strategy": stride_strategy, "replan_scope": replan_scope, "goal_frontier_projection": goal_frontier_projection, "acceptance_gaps": acceptance_gaps, diff --git a/loopx/control_plane/goals/goal_frontier/ack_policy.py b/loopx/control_plane/goals/goal_frontier/ack_policy.py index a7ca7268bc..9219fa372a 100644 --- a/loopx/control_plane/goals/goal_frontier/ack_policy.py +++ b/loopx/control_plane/goals/goal_frontier/ack_policy.py @@ -44,14 +44,13 @@ def autonomous_replan_ack_satisfies_obligation( replan_obligation: dict[str, Any] | None, acceptance_gaps: list[dict[str, Any]] | None, todo_succession_gap_open: bool = False, - stride_strategy: str = "off", ) -> bool: """Reject ACKs that miss the obligation's typed semantic outcome.""" if not autonomous_replan_ack_has_frontier_delta(ack): return False if ack.get("source") == "todo_replan_successor_transition" and not replan_successor_transition_allowed( - replan_obligation or {}, stride_strategy=stride_strategy, + replan_obligation or {}, ): return False semantic_delta = ack.get("semantic_delta") if isinstance(ack, dict) else {} @@ -90,7 +89,6 @@ def replan_successor_transition_ack( agent_id: str | None, replan_obligation: dict[str, Any] | None, agent_todo_items: Iterable[dict[str, Any]] | None = None, - stride_strategy: str = "off", ) -> dict[str, Any] | None: """Project an exact runnable-successor Todo as the replan receipt. @@ -168,7 +166,7 @@ def replan_successor_transition_ack( if successor_binding is None: return None if not replan_successor_transition_allowed( - replan_obligation or {}, stride_strategy=stride_strategy, + replan_obligation or {}, ): return None if trigger_checkpoints is None: diff --git a/loopx/control_plane/goals/vision_checkpoint.py b/loopx/control_plane/goals/vision_checkpoint.py index 99ad164304..e8c5f397e9 100644 --- a/loopx/control_plane/goals/vision_checkpoint.py +++ b/loopx/control_plane/goals/vision_checkpoint.py @@ -77,7 +77,6 @@ def prepare_vision_refresh( existing_agent_vision: dict[str, Any] | None, merge_patch: bool, require_path_delta_for_durable_change: bool, - allow_terminal_stride_path: bool = False, ) -> dict[str, Any]: """Run the TS-owned Vision preflight before semantic-replan qualification.""" @@ -95,7 +94,6 @@ def prepare_vision_refresh( "require_path_delta_for_durable_change": bool( require_path_delta_for_durable_change ), - "allow_terminal_stride_path": allow_terminal_stride_path, }, ) except EffectRuntimeRejected as exc: diff --git a/loopx/control_plane/goals/vision_checkpoint.ts b/loopx/control_plane/goals/vision_checkpoint.ts index c8557ed3f3..ffbaf90ef6 100644 --- a/loopx/control_plane/goals/vision_checkpoint.ts +++ b/loopx/control_plane/goals/vision_checkpoint.ts @@ -236,7 +236,6 @@ interface VisionRefreshPrepareRequest { existing_agent_vision: JsonObject | null; merge_patch: boolean; require_path_delta_for_durable_change: boolean; - allow_terminal_stride_path: boolean; } interface VisionRefreshFinalizeRequest { @@ -679,8 +678,6 @@ function decodePrepareRequest(request: JsonObject): VisionRefreshPrepareRequest request.require_path_delta_for_durable_change, "require_path_delta_for_durable_change", ), - allow_terminal_stride_path: request.allow_terminal_stride_path === undefined ? false - : requiredBoolean(request.allow_terminal_stride_path, "allow_terminal_stride_path"), }; } @@ -772,9 +769,8 @@ function prepareVisionRefresh(request: VisionRefreshPrepareRequest): JsonObject Object.assign(fieldUsage, pathDeltaUsage); const [strideDecision, strideUsage] = normalizeStrideDecision(updatePacket.stride_decision, (field, value, limit) => boundedPublicText(field, value, limit, diagnostics)); - const allowedStridePaths = request.allow_terminal_stride_path - ? ["continue", "no_change", "replan", "stop"] - : ["continue", "no_change", "replan"]; + // The live stride strategy always admits a supported terminal stop path. + const allowedStridePaths = ["continue", "no_change", "replan", "stop"]; // An oversized list has not supplied a validated evidence set yet; report its // count first rather than diagnosing the temporary placeholder as missing. if (diagnostics.completeUsage && strideDecision && (!pathDelta || !allowedStridePaths.includes(String(pathDelta.outcome)) || diff --git a/loopx/control_plane/host_adapter_settlement.py b/loopx/control_plane/host_adapter_settlement.py index 5b945ac3a9..08b6c9dc5a 100644 --- a/loopx/control_plane/host_adapter_settlement.py +++ b/loopx/control_plane/host_adapter_settlement.py @@ -118,7 +118,6 @@ def _request_payload( @contextmanager def host_vision_request( request: HostTodoSettlementRequest, vision: dict | None, unchanged: str, - *, allow_terminal_stride_path: bool = False, ): """Materialize authored JSON for the existing CLI codec, never as public state.""" if vision is not None and unchanged: @@ -132,8 +131,7 @@ def host_vision_request( # This is syntax/budget preflight only: refresh-state still validates against # the real baseline and current replan/settlement state at writeback time. prepare_vision_refresh(vision, goal_id=request.goal_id, agent_id=request.agent_id, - existing_agent_vision=None, merge_patch=False, require_path_delta_for_durable_change=False, - allow_terminal_stride_path=allow_terminal_stride_path) + existing_agent_vision=None, merge_patch=False, require_path_delta_for_durable_change=False) with tempfile.TemporaryDirectory(prefix="loopx-host-vision-") as directory: path = Path(directory) / "vision.json" path.write_text(json.dumps(vision, ensure_ascii=False, allow_nan=False), encoding="utf-8") diff --git a/loopx/control_plane/quota/should_run_prepare.py b/loopx/control_plane/quota/should_run_prepare.py index 28a32881f3..04caa7ff73 100644 --- a/loopx/control_plane/quota/should_run_prepare.py +++ b/loopx/control_plane/quota/should_run_prepare.py @@ -199,7 +199,6 @@ def _preserve_receipt_bound_replan_obligation( agent_id: str | None = None, replay_phase: ReceiptBoundReplayPhase | None = None, transition_candidates: list[dict[str, Any]] | None = None, - stride_strategy: str = "off", receipt_review: Mapping[str, Any] | None = None, goal_id: str | None = None, guard_recorded_at: str | None = None, @@ -218,7 +217,6 @@ def _preserve_receipt_bound_replan_obligation( "agent_id": agent_id, "replay_phase": replay_phase.value if replay_phase is not None else None, "transition_candidates": transition_candidates or [], - "stride_strategy": stride_strategy, "receipt_review": receipt_review, "goal_id": goal_id, "guard_recorded_at": guard_recorded_at, @@ -300,7 +298,6 @@ def _prepare_quota_replan_context( transition_candidates=( goal_frontier_context.get("replan_transition_candidates") if reconstruct_review else None ), - stride_strategy=goal_frontier_context["stride_strategy"], receipt_review=receipt_bound_replan_review, goal_id=safe_goal_id, guard_recorded_at=receipt_bound_guard_recorded_at, @@ -310,7 +307,7 @@ def _prepare_quota_replan_context( if replan_obligation and not replan_obligation.get("replan_context") and not replan_obligation.get("settlement_action_packet"): replan_obligation = attach_receipt_replan_context( replan_obligation, None, goal_id=safe_goal_id, agent_id=agent_frontier_id, - source_status=status_payload, stride_strategy=goal_frontier_context["stride_strategy"], + source_status=status_payload, explore_reader=replan_explore_reader, goal_acceptance_contract=(agent_todo_summary or {}).get("goal_acceptance_contract"), todo_items=agent_todo_terminal_source_items, diff --git a/loopx/control_plane/stride_strategy_schema.json b/loopx/control_plane/stride_strategy_schema.json index af086af5dc..79fc0697c5 100644 --- a/loopx/control_plane/stride_strategy_schema.json +++ b/loopx/control_plane/stride_strategy_schema.json @@ -1,7 +1,8 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Stride strategy version", + "description": "evidence_conditioned_v1 is the only live strategy. \"off\" remains decodable only in historical records.", "type": "string", "enum": ["off", "evidence_conditioned_v1"], - "default": "off" + "default": "evidence_conditioned_v1" } diff --git a/loopx/control_plane/work_items/lifecycle_recovery.py b/loopx/control_plane/work_items/lifecycle_recovery.py index 78a62e8673..12e86a0233 100644 --- a/loopx/control_plane/work_items/lifecycle_recovery.py +++ b/loopx/control_plane/work_items/lifecycle_recovery.py @@ -44,7 +44,6 @@ def receipt_bound_lifecycle_candidate( def attach_receipt_replan_context( current: dict[str, Any] | None, lifecycle_candidate: dict[str, Any] | None, *, goal_id: str, agent_id: str | None, source_status: Mapping[str, Any] | None, - stride_strategy: str, explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None, goal_acceptance_contract: Mapping[str, Any] | None, todo_items: Iterable[Mapping[str, Any]] | None = None, @@ -71,11 +70,11 @@ def attach_receipt_replan_context( if not obligations: return current todos = list(todo_items) if todo_items is not None else None - explore_context = explore_reader(goal_id, agent_id) if stride_strategy != "off" and explore_reader else None + explore_context = explore_reader(goal_id, agent_id) if explore_reader else None for obligation in obligations: obligation["replan_context"] = build_replan_context( obligation, goal_id=goal_id, agent_id=agent_id, newest_first_runs=(), - source_status=source_status, stride_strategy=stride_strategy, + source_status=source_status, explore_context=explore_context, goal_acceptance_contract=goal_acceptance_contract, todo_items=todos, ) diff --git a/loopx/control_plane/work_items/progress_observation.py b/loopx/control_plane/work_items/progress_observation.py index 4ab7e18f80..7149d938cf 100644 --- a/loopx/control_plane/work_items/progress_observation.py +++ b/loopx/control_plane/work_items/progress_observation.py @@ -236,14 +236,11 @@ def required_semantic_outcomes(obligation: Mapping[str, Any]) -> list[str]: return list(replan_writeback_requirements(obligation)["required_any_of"]) -def replan_successor_transition_allowed( - obligation: Mapping[str, Any], *, stride_strategy: str = "off", -) -> bool: +def replan_successor_transition_allowed(obligation: Mapping[str, Any]) -> bool: """Ask the typed owner whether a Todo transition can settle this review.""" try: result = project_replan_semantics({ "operation": "transition_eligibility", "obligation": dict(obligation), - "stride_strategy": stride_strategy, }) except EffectRuntimeRejected as exc: raise ValueError(str(exc)) from None @@ -254,7 +251,7 @@ def replan_successor_transition_allowed( def guarded_replan_transition_delta( *, guard_scoped: bool, selected_obligation_id: str | None, - transition_candidates: list[dict[str, Any]], stride_strategy: str = "off", + transition_candidates: list[dict[str, Any]], goal_id: str | None = None, agent_id: str | None = None, guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None, @@ -265,7 +262,6 @@ def guarded_replan_transition_delta( "operation": "turn_transition", "guard_scoped": guard_scoped, "selected_obligation_id": selected_obligation_id, "transition_candidates": transition_candidates, - "stride_strategy": stride_strategy, "goal_id": goal_id, "agent_id": agent_id, "guard_recorded_at": guard_recorded_at, @@ -387,7 +383,7 @@ def semantic_delta_from_writeback( source_review = None stride = vision.get("stride_decision") review = stride.get("previous_review") if isinstance(stride, Mapping) else None - if (runs is not None and context is not None and context.get("stride_strategy") != "off" + if (runs is not None and context is not None and context.get("decision_followthrough") and isinstance(review, Mapping)): from .replan_context_codec import replay_stride_review_evidence @@ -412,7 +408,6 @@ def build_replan_context( obligation: Mapping[str, Any], *, goal_id: str, agent_id: str | None, newest_first_runs: Iterable[Mapping[str, Any]], source_status: Mapping[str, Any] | None = None, - stride_strategy: str = "off", explore_context: Mapping[str, Any] | None = None, goal_acceptance_contract: Mapping[str, Any] | None = None, todo_items: Iterable[Mapping[str, Any]] | None = None, @@ -422,7 +417,7 @@ def build_replan_context( return project_replan_context( goal_id=goal_id, agent_id=agent_id or obligation.get("agent_id"), runs=newest_first_runs, obligation=obligation, source_status=source_status, - goal_acceptance_contract=goal_acceptance_contract, stride_strategy=stride_strategy, + goal_acceptance_contract=goal_acceptance_contract, history_newest_first=True, explore_context=explore_context, todo_items=todo_items, ) diff --git a/loopx/control_plane/work_items/replan_context.ts b/loopx/control_plane/work_items/replan_context.ts index 1ed7d528c2..0d9fc9b5f0 100644 --- a/loopx/control_plane/work_items/replan_context.ts +++ b/loopx/control_plane/work_items/replan_context.ts @@ -8,7 +8,7 @@ import {requireJsonObject, requireNonEmptyString} from "../runtime_decode.ts"; import {FRESH_PATH_DISPOSITIONS, requiredSemanticOutcomes} from "./replan_semantics.ts"; import {readReplanSnapshot} from "./replan_history_snapshot.ts"; import {normalizeGoalPathDelta} from "../goals/vision_checkpoint.ts"; -import {normalizeRecordedStrideDecision, normalizeStrideStrategy, projectStrideExploreBasis, STRIDE_REVIEW_REFERENCE_LIMIT} from "./stride_policy.ts"; +import {LIVE_STRIDE_STRATEGY, normalizeRecordedStrideDecision, normalizeStrideStrategy, projectStrideExploreBasis, STRIDE_REVIEW_REFERENCE_LIMIT} from "./stride_policy.ts"; import {PROGRESS_RESULT_CLASSES} from "./replan_history.ts"; import {MATERIAL_DELIVERY_OUTCOMES} from "./delivery_outcome.ts"; @@ -687,9 +687,12 @@ export function projectReplanContext(value: unknown): JsonObject { ? (obligation.triggers as JsonObject[]).find(trigger => trigger.progress_baseline)?.progress_baseline : null ) ?? null; - const strideStrategy = normalizeStrideStrategy(request.stride_strategy); - // This context has not been attached yet. Project outcomes with its current - // effective strategy through the same owner used by requirements/writeback. + // There is one live strategy. A caller cannot select "off" for a new context; + // historically recorded contexts remain decodable through validation above. + if (request.stride_strategy !== undefined) normalizeStrideStrategy(request.stride_strategy); + const strideStrategy = LIVE_STRIDE_STRATEGY; + // This context has not been attached yet. Project outcomes with the live + // strategy through the same owner used by requirements/writeback. const frontier = {baseline, required_any_of: obligation ? requiredSemanticOutcomes({ ...obligation, replan_context: {stride_strategy: strideStrategy}, }) : []}; @@ -748,12 +751,12 @@ export function projectReplanContext(value: unknown): JsonObject { : null; if (evidenceReadTemplate) for (const row of shown) delete row.read_action; const core = projectCoreGoal(request.goal_facts); - const exploreBasis = strideStrategy !== "off" ? projectStrideExploreBasis(request.explore_context, goal, agent) : null; + const exploreBasis = projectStrideExploreBasis(request.explore_context, goal, agent); const followthrough = agent ? decisionFollowthrough(rows, request.goal_facts, request.from_full_index === true, request.todo_items) : null; const contextId = "replan-context-" + digest({goal, agent, obligationId, core, ledger, shown, frontier, ...(evidenceReadTemplate ? {evidence_read_action_template: evidenceReadTemplate} : {}), - ...(strideStrategy !== "off" ? {stride_strategy: strideStrategy} : {}), + stride_strategy: strideStrategy, ...(followthrough ? {decision_followthrough: followthrough} : {}), ...(exploreBasis ? {explore_basis: exploreBasis} : {})}); const context: JsonObject = { @@ -767,7 +770,7 @@ export function projectReplanContext(value: unknown): JsonObject { coverage_ledger: ledger, coverage_count: coverage.size, coverage_truncated: coverage.size > ledger.length, uncovered_frontier: frontier, }; - if (strideStrategy !== "off") context.stride_strategy = strideStrategy; + context.stride_strategy = strideStrategy; if (followthrough) context.decision_followthrough = followthrough; if (exploreBasis) context.explore_basis = exploreBasis; // Source-replayed supplemental pages qualify a proposal, not a new admission diff --git a/loopx/control_plane/work_items/replan_context_codec.py b/loopx/control_plane/work_items/replan_context_codec.py index f5d927c7b3..330a7ecf6e 100644 --- a/loopx/control_plane/work_items/replan_context_codec.py +++ b/loopx/control_plane/work_items/replan_context_codec.py @@ -180,15 +180,11 @@ def project_replan_context( obligation: Mapping[str, Any] | None = None, evidence_ref: str | None = None, source_status: Mapping[str, Any] | None = None, goal_acceptance_contract: Mapping[str, Any] | None = None, - stride_strategy: str = "off", explore_context: Mapping[str, Any] | None = None, history_newest_first: bool | None = None, todo_items: Iterable[Mapping[str, Any]] | None = None, ) -> dict[str, Any]: from .replan_history_codec import project_replan_request - from .stride_policy_codec import normalize_stride_strategy - - strategy = normalize_stride_strategy(stride_strategy) prefix = ["loopx"] if source_status is not None: @@ -205,7 +201,6 @@ def project_replan_context( "rows": replan_evidence_rows(runs, goal_id=goal_id, agent_id=agent_id, include_decisions=bool(agent_id), history_newest_first=history_newest_first), - "stride_strategy": strategy, # Canonical caller-owned facts only. TypeScript joins the declared # work with the accepted decision and causally later observations. **({"todo_items": [{key: item[key] for key in ( diff --git a/loopx/control_plane/work_items/replan_history_codec.py b/loopx/control_plane/work_items/replan_history_codec.py index 0b41d5ba2b..d1a6230d46 100644 --- a/loopx/control_plane/work_items/replan_history_codec.py +++ b/loopx/control_plane/work_items/replan_history_codec.py @@ -55,7 +55,6 @@ def effective_turn_cadence_context( "goal_ref": goal_ref, "source_admission": source_admission, "threshold": threshold, - "stride_strategy": profile.get("stride_strategy", "off"), "settlement_source": { "runtime_root": str(runtime_root.resolve()), "goal_id": goal["id"], @@ -209,7 +208,6 @@ def project_replan_history( if effective_turn_cadence is not None: params["settlement_source"] = effective_turn_cadence["settlement_source"] params["periodic_threshold"] = effective_turn_cadence["threshold"] - params["stride_strategy"] = effective_turn_cadence.get("stride_strategy", "off") try: if effective_turn_cadence is None: result = project_replan_request(params) diff --git a/loopx/control_plane/work_items/replan_semantics.ts b/loopx/control_plane/work_items/replan_semantics.ts index 31e62ea64f..aeddeae4e2 100644 --- a/loopx/control_plane/work_items/replan_semantics.ts +++ b/loopx/control_plane/work_items/replan_semantics.ts @@ -8,7 +8,7 @@ import { parseTodoTimestampMicros } from "../runtime_timestamp.ts"; import { TODO_COMPLETION_RECOVERIES } from "../todos/completion_state.ts"; import { id as todoId, readResume, taskClass } from "../todos/read_codec.ts"; import { indexInferredSuccessors } from "../todos/succession.ts"; -import {normalizeStrideDecision, normalizeStrideStrategy, STRIDE_DECISION_SCHEMA, strideControlContract, strideReviewMismatch} from "./stride_policy.ts"; +import {normalizeStrideDecision, STRIDE_DECISION_SCHEMA, strideControlContract, strideReviewMismatch} from "./stride_policy.ts"; import { projectProgressDelta } from "./progress_delta.ts"; const PROGRESS_OUTCOMES = [ @@ -104,15 +104,14 @@ function isExternalReview(obligation: JsonObject): boolean { return triggerKinds(obligation).some(kind => EXTERNAL_REVIEW_TRIGGERS.has(kind)); } -// Existing cadence and observed-stall triggers become decision checkpoints -// only for the opted-in strategy. This does not detect stalls or force a pivot. +// Existing cadence and observed-stall triggers are decision checkpoints under +// the only live stride strategy. This does not detect stalls or force a pivot. +// A historical replan_context that recorded "off" (or omitted the strategy) +// cannot opt an obligation out of the review. const STRIDE_REVIEW_TRIGGERS = new Set(["periodic_review_due", "typed_progress_repeat", "no_progress_streak", "repeated_action_loop", "external_progress_review_drift"]); -function requiresStrideDecision(obligation: JsonObject, fallbackStrategy: unknown = "off"): boolean { - const context = object(obligation.replan_context); - const strategy = Object.hasOwn(context, "stride_strategy") ? context.stride_strategy : fallbackStrategy; - return triggerKinds(obligation).some(kind => STRIDE_REVIEW_TRIGGERS.has(kind)) && - normalizeStrideStrategy(strategy) !== "off"; +function requiresStrideDecision(obligation: JsonObject): boolean { + return triggerKinds(obligation).some(kind => STRIDE_REVIEW_TRIGGERS.has(kind)); } /** Route only a revalidated canonical transition to its original Turn guard. @@ -182,7 +181,7 @@ function projectTurnTransition(request: JsonObject): JsonObject { } const sourceObligation = object(candidateSource.obligation); if (sourceObligation.obligation_id !== selected) continue; - if (requiresStrideDecision(sourceObligation, request.stride_strategy)) continue; + if (requiresStrideDecision(sourceObligation)) continue; const ack = object(candidateSource.ack); const candidate = object(ack.semantic_delta); if (ack.schema_version === "autonomous_replan_ack_v0" && @@ -353,7 +352,7 @@ function preserveReceiptBoundObligation(request: JsonObject): JsonObject { if (!requiredSemanticOutcomes(obligation).includes("new_runnable_successor")) continue; const result = projectTurnTransition({guard_scoped: request.guard_scoped, selected_obligation_id: selected, transition_candidates: [candidate], - stride_strategy: request.stride_strategy, goal_id: request.goal_id, + goal_id: request.goal_id, agent_id: request.agent_id, guard_recorded_at: request.guard_recorded_at, guard_turn_instance_id: request.guard_turn_instance_id}); if (result.semantic_delta !== null) { @@ -504,7 +503,7 @@ export function requiredSemanticOutcomes(obligation: JsonObject): SemanticOutcom ? ["fresh_vision_path_outcome", ...PROGRESS_OUTCOMES] : [...PROGRESS_OUTCOMES]; } -function writebackProjection(required: SemanticOutcome[], externalReview: boolean, strideEnabled: boolean): JsonObject { +function writebackProjection(required: SemanticOutcome[], externalReview: boolean): JsonObject { // This chooses a usable refresh path, not the only legal exit. Successor and // terminal alternatives still have their own typed transitions and gates. if (externalReview) { @@ -528,7 +527,7 @@ function writebackProjection(required: SemanticOutcome[], externalReview: boolea preferred_input: "evidence_linked_vision_path", vision_authoring: visionAuthoringContract(true), required_fields: ["vision_patch.acceptance_summary", "path_delta.outcome", "path_delta.evidence_refs", - ...(strideEnabled ? ["agent_vision.stride_decision"] : [])], + "agent_vision.stride_decision"], path_outcomes: [...FRESH_PATH_DISPOSITIONS], rule: "First reuse observed evidence valid for current source/acceptance; probe missing, stale or insufficient evidence. Write a JSON file with acceptance summary and evidence-linked path outcome, then run bound refresh and spend. An unchanged reason alone is insufficient. Explicit validation gates and other required_any_of contracts apply.", }, @@ -635,13 +634,13 @@ export function projectReplanSemantics(value: unknown): JsonObject { ? {kind, stop_condition: obligation.stop_condition} : null}; } if (request.operation === "transition_eligibility") { - return {allowed: !requiresStrideDecision(obligation, request.stride_strategy)}; + return {allowed: !requiresStrideDecision(obligation)}; } const required = requiredSemanticOutcomes(obligation); const externalReview = isExternalReview(obligation); if (request.operation === "requirements") { const strideControl = strideControlContract(object(obligation.replan_context), obligation.obligation_id); - const writeback = writebackProjection(required, externalReview, strideControl !== null); + const writeback = writebackProjection(required, externalReview); if (required.includes("coverage_backed_no_followup")) { writeback.writeback_contract = {...object(writeback.writeback_contract), no_followup_requirements: { @@ -666,7 +665,7 @@ export function projectReplanSemantics(value: unknown): JsonObject { String(contract.rule ?? "")}; } return {required_any_of: required, planning_guidance: REPLAN_PLANNING_GUIDANCE, - ...(strideControl ? {stride_control: strideControl} : {}), + stride_control: strideControl, ...writeback}; } if (request.operation !== "qualify") { @@ -680,7 +679,6 @@ export function projectReplanSemantics(value: unknown): JsonObject { const path = object(vision.path_delta); const context = object(obligation.replan_context); const [strideDecision] = normalizeStrideDecision(vision.stride_decision); - const structuredReview = normalizeStrideStrategy(context.stride_strategy) !== "off"; const selectedComparison = object(strideDecision?.explore_review).selected_candidate != null; const requiredStrideReview = requiresStrideDecision(obligation); const pathOutcome = String(path.outcome ?? "").trim(); @@ -688,14 +686,14 @@ export function projectReplanSemantics(value: unknown): JsonObject { (FRESH_PATH_DISPOSITIONS.has(pathOutcome) || pathOutcome === "stop") && strings(path.evidence_refs).length); const freshPath = evidenceLinkedPath && FRESH_PATH_DISPOSITIONS.has(pathOutcome); const independentStride = strideDecision?.schema_version === STRIDE_DECISION_SCHEMA; - const missingStride = structuredReview && (freshPath || requiredStrideReview) && + const missingStride = (freshPath || requiredStrideReview) && (!strideDecision || !independentStride); const missingStridePath = requiredStrideReview && !evidenceLinkedPath; - const staleStride = !!strideDecision && (structuredReview || selectedComparison) && + const staleStride = !!strideDecision && strideDecision.reference_obligation_id !== obligation.obligation_id; - const reviewContextChanged = !!strideDecision && (structuredReview || selectedComparison) + const reviewContextChanged = !!strideDecision && (requiredStrideReview || selectedComparison) && strideDecision.reference_context_id !== context.context_id; - const reviewMismatch = strideDecision && (structuredReview || selectedComparison) + const reviewMismatch = strideDecision ? reviewContextChanged ? "Stride decision references a different review context. Read the returned context_recovery before retrying the original writeback." : strideReviewMismatch(strideDecision, context, request.stride_review_evidence, vision.todo_delta) diff --git a/loopx/control_plane/work_items/semantic_replan_writeback.py b/loopx/control_plane/work_items/semantic_replan_writeback.py index 38ff46c6b3..bdadcfcaa1 100644 --- a/loopx/control_plane/work_items/semantic_replan_writeback.py +++ b/loopx/control_plane/work_items/semantic_replan_writeback.py @@ -411,9 +411,6 @@ def qualify_replan_writeback( guard_scoped=guard_scoped, selected_obligation_id=guard_semantic_replan_obligation_id, transition_candidates=context.get("replan_transition_candidates", []), - stride_strategy=((registry_goal or {}).get("execution_profile") or {}).get( - "stride_strategy", "off" - ), goal_id=goal_id, agent_id=safe_agent_id, guard_recorded_at=receipt_bound_guard_recorded_at, @@ -447,7 +444,6 @@ def qualify_replan_writeback( "current_obligation": obligation, "receipt_review": receipt_bound_replan_review, "transition_candidates": context.get("replan_transition_candidates", []), - "stride_strategy": context["stride_strategy"], "goal_id": goal_id, "guard_recorded_at": receipt_bound_guard_recorded_at, "guard_turn_instance_id": receipt_bound_guard_turn_instance_id, @@ -455,7 +451,7 @@ def qualify_replan_writeback( if obligation and not obligation.get("replan_context") and not obligation.get("settlement_action_packet"): obligation = attach_receipt_replan_context( obligation, None, goal_id=goal_id, agent_id=safe_agent_id, - source_status=status_payload, stride_strategy=context["stride_strategy"], + source_status=status_payload, explore_reader=replan_explore_reader, goal_acceptance_contract=( contract if isinstance(contract := (agent_todos or {}).get("goal_acceptance_contract"), Mapping) else None diff --git a/loopx/control_plane/work_items/stride_policy.ts b/loopx/control_plane/work_items/stride_policy.ts index 58d5e4219e..bd26ed6f08 100644 --- a/loopx/control_plane/work_items/stride_policy.ts +++ b/loopx/control_plane/work_items/stride_policy.ts @@ -9,6 +9,10 @@ import {requireJsonObject, requireNonEmptyString, requireStringLiteral} from ".. import {EXPLORE_RESULT_PAGE_MAX, normalizeExploreResultPages} from "../capabilities/explore_result_page.ts"; import {PLANNING_TODO_ID} from "./planning_relations.ts"; +/** The only live strategy. "off" stays decodable for historical records only. */ +export const LIVE_STRIDE_STRATEGY = "evidence_conditioned_v1"; + +/** Validate a historically recorded strategy value; never selects live behavior. */ export function normalizeStrideStrategy(value: unknown): string { if (value === undefined) return schema.default; if (typeof value !== "string" || !schema.enum.includes(value)) { @@ -384,12 +388,12 @@ export function strideReviewMismatch(decision: JsonObject, context: JsonObject, return null; } -export function strideControlContract(context: JsonObject, obligationId: unknown = null): JsonObject | null { - if (normalizeStrideStrategy(context.stride_strategy) === "off") return null; +export function strideControlContract(context: JsonObject, obligationId: unknown = null): JsonObject { + if (context.stride_strategy !== undefined) normalizeStrideStrategy(context.stride_strategy); const follow = context.decision_followthrough as JsonObject | undefined; const previous = (follow?.previous_decision as JsonObject | undefined)?.evidence_ref ?? null; const basis = context.explore_basis as JsonObject | undefined; - const example: JsonObject = {schema_version: decisionSchema.schema_version, strategy_version: context.stride_strategy, + const example: JsonObject = {schema_version: decisionSchema.schema_version, strategy_version: LIVE_STRIDE_STRATEGY, reference_context_id: context.context_id ?? null, reference_obligation_id: obligationId, basis: "uncertain_evidence", action: "verify", axes: { work_slice: {plan: "Complete the work and checks for the adoption decision.", reason: "Resolve adoption uncertainty before expanding."}, @@ -401,7 +405,7 @@ export function strideControlContract(context: JsonObject, obligationId: unknown evidence_refs: [], lesson: "Example only: inspect subsequent work and evidence before replacing these unknowns."}; if (basis) example.explore_review = {revision: basis.revision, disposition: basis.availability === "unavailable" ? "unavailable" : "deferred", considered_refs: [], reason: "Example only: inspect applicable findings, counterexamples and alternatives, then replace."}; - return {schema_version: decisionSchema.schema_version, strategy_version: context.stride_strategy, + return {schema_version: decisionSchema.schema_version, strategy_version: LIVE_STRIDE_STRATEGY, reference_context_id: context.context_id ?? null, reference_obligation_id: obligationId, axis_names: decisionSchema.axis_names, actions: decisionSchema.actions, basis_options: decisionSchema.basis_options, diff --git a/loopx/control_plane/work_items/stride_policy_codec.py b/loopx/control_plane/work_items/stride_policy_codec.py index e34f9ab4a8..7039d91439 100644 --- a/loopx/control_plane/work_items/stride_policy_codec.py +++ b/loopx/control_plane/work_items/stride_policy_codec.py @@ -11,13 +11,20 @@ from typing import Any +# The only live stride strategy. There is no live switch: Goal profiles, +# machine defaults and benchmark arms cannot select "off" for new decisions. +LIVE_STRIDE_STRATEGY = "evidence_conditioned_v1" + + @lru_cache(maxsize=1) def stride_strategy_options() -> tuple[str, ...]: + """Historically recorded strategy values, accepted only when decoding stored data.""" contract = json.loads(files("loopx.control_plane").joinpath("stride_strategy_schema.json").read_text(encoding="utf-8")) return tuple(contract["enum"]) def normalize_stride_strategy(value: Any) -> str: + """Validate a historically recorded strategy; live decisions use LIVE_STRIDE_STRATEGY.""" if not isinstance(value, str) or value not in stride_strategy_options(): raise ValueError("stride_strategy must be off or evidence_conditioned_v1") return value diff --git a/loopx/execution_profile.py b/loopx/execution_profile.py index f503a65d7c..e0640ac7e7 100644 --- a/loopx/execution_profile.py +++ b/loopx/execution_profile.py @@ -166,8 +166,11 @@ def compact_execution_profile(value: Any) -> dict[str, Any]: profile["yardstick_enabled"] = value["yardstick_enabled"] if "stride_strategy" in value: + # Removed live switch: a saved Goal may still record "off" or + # "evidence_conditioned_v1". Decode it as history, then drop it so no + # surface displays or acts on it; evidence-conditioned stride is live. from .control_plane.work_items.stride_policy_codec import normalize_stride_strategy - profile["stride_strategy"] = normalize_stride_strategy(value["stride_strategy"]) + normalize_stride_strategy(value["stride_strategy"]) if "replan_after_effective_turns" in value and "replan_after_completed_todos" in value: raise ValueError("choose one review cadence unit") @@ -258,8 +261,6 @@ def apply_goal_execution_profile_change( clear_replan_after_completed_todos: bool, replan_after_effective_turns: int | None = None, clear_replan_after_effective_turns: bool = False, - stride_strategy: str | None = None, - clear_stride_strategy: bool = False, planning_horizon_goal: bool | None = None, clear_planning_horizon_goal: bool = False, yardstick_enabled: bool | None = None, @@ -277,8 +278,6 @@ def apply_goal_execution_profile_change( replan_after_completed_todos is not None or clear_replan_after_effective_turns ): raise ValueError("choose one review cadence override or clear operation") - if stride_strategy is not None and clear_stride_strategy: - raise ValueError("choose a stride strategy override or clear operation") if planning_horizon_goal is not None and clear_planning_horizon_goal: raise ValueError("choose a planning horizon Goal override or clear operation") if yardstick_enabled is not None and clear_yardstick_enabled: @@ -290,8 +289,6 @@ def apply_goal_execution_profile_change( and not (clear_yardstick_enabled and "yardstick_enabled" in profile) and planning_horizon_goal is None and not clear_planning_horizon_goal - and stride_strategy is None - and not clear_stride_strategy and turn_granularity is None and replan_after_completed_todos is None and replan_after_effective_turns is None @@ -307,10 +304,6 @@ def apply_goal_execution_profile_change( profile.pop("planning_horizon_goal", None) if planning_horizon_goal is not None: profile["planning_horizon_goal"] = planning_horizon_goal - if clear_stride_strategy: - profile.pop("stride_strategy", None) - if stride_strategy is not None: - profile["stride_strategy"] = stride_strategy if clear_replan_after_effective_turns or replan_after_completed_todos is not None: profile.pop("replan_after_effective_turns", None) if replan_after_completed_todos is not None: diff --git a/loopx/goal_mode_mcp.py b/loopx/goal_mode_mcp.py index 45c0384311..4fef4af90a 100644 --- a/loopx/goal_mode_mcp.py +++ b/loopx/goal_mode_mcp.py @@ -9,7 +9,6 @@ import sys from collections.abc import Callable, Mapping from dataclasses import dataclass -from pathlib import Path from typing import Any from .control_plane.host_adapter_settlement import ( @@ -63,33 +62,6 @@ def goal_ref(self) -> dict[str, str] | None: "goal_instance_id": goal_instance_id, } - def _allow_terminal_stride_path(self, goal_id: str, vision: dict[str, Any] | None) -> bool: - """Use the same effective Goal cadence as formal writeback before Todo effects.""" - if not isinstance(vision, dict) or not isinstance(vision.get("path_delta"), dict): - return False - if vision["path_delta"].get("outcome") != "stop" or "stride_decision" not in vision: - return False - from .capabilities.todo_replan_cadence.machine_defaults import resolve_todo_replan_cadence_goal - from .control_plane.projects.registry_codec import load_registry - from .paths import (default_registry_path, global_registry_path, - resolve_runtime_root, select_default_runtime_root) - from .registry import find_registry_goal - - selected = self.context()[1] - if selected == "@host-global": - registry_path = global_registry_path(select_default_runtime_root()) - else: - registry_path = Path(selected).expanduser() if selected else default_registry_path() - if not selected and not registry_path.exists(): - registry_path = global_registry_path(select_default_runtime_root()) - registry = load_registry(registry_path) - goal = find_registry_goal(registry, goal_id) - if goal is None: - raise ValueError(f"{goal_id}: registry does not contain the Goal for Vision preflight") - runtime_root = resolve_runtime_root(registry, registry_path=registry_path) - effective = resolve_todo_replan_cadence_goal(goal, runtime_root) - return (effective.get("execution_profile") or {}).get("stride_strategy") == "evidence_conditioned_v1" - def command_prefix(self) -> list[str]: executable = shutil.which("loopx") return [executable] if executable else [sys.executable, "-m", "loopx.cli"] @@ -281,8 +253,7 @@ def complete_task( no_follow_up=no_follow_up, goal_ref=self.goal_ref(), ) - with host_vision_request(request, agent_vision, vision_unchanged_reason, - allow_terminal_stride_path=self._allow_terminal_stride_path(goal_id, agent_vision)) as authored: + with host_vision_request(request, agent_vision, vision_unchanged_reason) as authored: return settle_host_todo_completion(authored, run_cli=self.run_cli) def review_task_vision( @@ -305,8 +276,7 @@ def review_task_vision( checkpoint_read_context_id=read_context_id or None, goal_ref=self.goal_ref(), ) - with host_vision_request(request, agent_vision, vision_unchanged_reason, - allow_terminal_stride_path=self._allow_terminal_stride_path(goal_id, agent_vision)) as authored: + with host_vision_request(request, agent_vision, vision_unchanged_reason) as authored: return refresh_host_todo_vision(authored, run_cli=self.run_cli) diff --git a/loopx/presentation/goal_amendment_api.py b/loopx/presentation/goal_amendment_api.py index aa0d06d6d5..5808b77918 100644 --- a/loopx/presentation/goal_amendment_api.py +++ b/loopx/presentation/goal_amendment_api.py @@ -11,7 +11,6 @@ from ..chat import redact_local_paths from ..feedback import validate_goal_id -from ..capabilities.todo_replan_cadence.machine_defaults import resolve_todo_replan_cadence_goal from ..control_plane.goals.goal_amendment_runtime import execute_goal_amendment from ..control_plane.goals.source_session_registry_state import current_goal_ref from ..control_plane.projects.registry_codec import load_project_registry @@ -74,12 +73,10 @@ def _amendment_inspect(self) -> None: if len(query.get("operation_id", [])) != 1 or len(query.get("goal_instance_id", [])) != 1: raise ValueError("Historical lookup requires one operation and exact Goal instance") result = execute_goal_amendment(registry_path=source, goal_id=goal_id, goal_instance_id=query["goal_instance_id"][0], - operation="receipt", actor_agent_id=None, parameters={"receipt_operation_id": query["operation_id"][0]}, - replan_configuration_reader=resolve_todo_replan_cadence_goal) + operation="receipt", actor_agent_id=None, parameters={"receipt_operation_id": query["operation_id"][0]}) else: result = execute_goal_amendment(registry_path=source, goal_id=goal_ref["goal_id"], - goal_instance_id=goal_ref["goal_instance_id"], operation="inspect", actor_agent_id=None, - replan_configuration_reader=resolve_todo_replan_cadence_goal) + goal_instance_id=goal_ref["goal_instance_id"], operation="inspect", actor_agent_id=None) self._send_json(_public(result)) except (OSError, TypeError, ValueError) as exc: self._send_error(redact_local_paths(str(exc)), status=400, error_code="goal_amendment_unavailable") @@ -97,8 +94,7 @@ def _amendment_configure(self) -> None: parameters = body["parameters"] if set(parameters) != {"permission_scope", "terminal_conditions", "policy", "expected_provider_revision"}: raise ValueError("Only initial root policy fields are accepted here") - common = dict(registry_path=source, goal_id=goal_id, goal_instance_id=str(body["goal_instance_id"]), actor_agent_id=None, - replan_configuration_reader=resolve_todo_replan_cadence_goal) + common = dict(registry_path=source, goal_id=goal_id, goal_instance_id=str(body["goal_instance_id"]), actor_agent_id=None) current = execute_goal_amendment(**common, operation="inspect") if current.get("ok") is not True: self._send_json(_public(current)) diff --git a/loopx/presentation/request_control_api.py b/loopx/presentation/request_control_api.py index 28132b19e5..f879469f93 100644 --- a/loopx/presentation/request_control_api.py +++ b/loopx/presentation/request_control_api.py @@ -19,7 +19,6 @@ from ..control_plane.goals.goal_ref_validation import exact_goal_ref from ..control_plane.projects.registry_codec import load_project_registry from ..capabilities.manager_context import target_authority -from ..capabilities.todo_replan_cadence.machine_defaults import resolve_todo_replan_cadence_goal from ..control_plane.collaboration.source_chat_observation import original_delivery_facts from .goal_source_routing import source_registry_for_goal @@ -196,8 +195,7 @@ def _request_control_read(self) -> None: query = parse_qs(urlparse(self.path).query, keep_blank_values=True) if set(query) != _ROUTING or any(len(value) != 1 for value in query.values()): raise ValueError("request routing fields are required exactly once") - result = control_request(**self._request_control_source({key: values[0] for key, values in query.items()}), operation="inspect", - replan_configuration_reader=resolve_todo_replan_cadence_goal) + result = control_request(**self._request_control_source({key: values[0] for key, values in query.items()}), operation="inspect") self._send_json(_operator_payload(result)) except (OSError, ValueError, TypeError, KeyError, EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc: self._send_error(redact_local_paths(str(exc)), status=400, error_code="request_control_unavailable") @@ -210,7 +208,6 @@ def _request_control_write(self) -> None: or not isinstance(body["parameters"], dict) or type(body["execute"]) is not bool): raise ValueError("only original source correction, cancellation or recovery is accepted here") result = control_request(**self._request_control_source(body), operation=body["operation"], - replan_configuration_reader=resolve_todo_replan_cadence_goal, parameters=body["parameters"], execute=body["execute"]) self._send_json(_operator_payload(result)) except (OSError, ValueError, TypeError, KeyError, EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc: diff --git a/loopx/state_refresh.py b/loopx/state_refresh.py index 890e255286..64807c824a 100644 --- a/loopx/state_refresh.py +++ b/loopx/state_refresh.py @@ -1094,10 +1094,6 @@ def refresh_state_run( existing_agent_vision=existing_agent_vision, merge_patch=merge_agent_vision_patch, require_path_delta_for_durable_change=autonomous_replan_recorded, - allow_terminal_stride_path=( - (effective_replan_goal.get("execution_profile") or {}).get("stride_strategy") - == "evidence_conditioned_v1" - ), ) generated_at = now_local() # Next Action is now an actor/Todo-bound recommendation in the existing diff --git a/packages/loopx-jev/tests/test_closed_loop.py b/packages/loopx-jev/tests/test_closed_loop.py index d2bdfbed0a..acb01bf4e1 100644 --- a/packages/loopx-jev/tests/test_closed_loop.py +++ b/packages/loopx-jev/tests/test_closed_loop.py @@ -92,13 +92,50 @@ def _find(payload, key: str): yield from _find(item, key) +def _stride_vision( + registry: Path, + runtime: Path, + *, + outcome: str = "stop", + acceptance_summary: str = "deliver() retries one transient TimeoutError", + evidence_ref: str = "evidence:progress-review-vision", +) -> dict: + from copy import deepcopy + from loopx.quota import build_quota_should_run + from loopx.status import collect_status + + status_payload = collect_status( + registry_path=registry, + runtime_root_override=str(runtime), + goal_id=GOAL_ID, + limit=20, + ) + guard = build_quota_should_run(status_payload, goal_id=GOAL_ID, agent_id=AGENT_ID) + decision = deepcopy(guard["replan_action_packet"]["stride_control"]["minimal_example"]) + path_delta: dict = { + "schema_version": "goal_path_delta_v0", + "outcome": outcome, + "prior_assumption": "Renaming the delay constant prepared the retry slice.", + "observed_reality": "The evaluated deltas changed no behaviour; the retry branch is still missing.", + "evidence_refs": [evidence_ref], + } + if outcome == "stop": + path_delta["stopped"] = ["Stop cosmetic renames while resolving the external-review obligation."] + elif outcome == "continue": + path_delta["retained"] = ["retry.py stays the surface; the next slice adds the retry branch."] + return { + "agent_id": AGENT_ID, + "state": "active", + "vision_patch": {"acceptance_summary": acceptance_summary}, + "path_delta": path_delta, + "stride_decision": decision, + } + + @pytest.fixture def sequence(tmp_path): project, runtime, registry = _write_fixture(tmp_path / "fixture") _initialize_fixture_authority(project, runtime) - # This sequence isolates the external-review obligation from structured Stride decisions. - configure_goal(registry_path=registry, goal_id=GOAL_ID, - execution_stride_strategy="off", execute=True) work = tmp_path / "delivery" work.mkdir() git(work, "init", "-q") @@ -231,6 +268,7 @@ def test_same_sequence_off_sees_nothing_and_assist_raises_the_obligation(sequenc # Repeating the evaluated observation, or the same hypothesis with fresh # evidence ids, is not a discharge: the obligation binds that window's typed # baseline and the real writeback rejects both. + stop_vision = _stride_vision(registry, runtime, outcome="stop") for non_novel, message in ( ({"schema_version": "typed_progress_observation_v0", "result_class": "advanced", "surface_id": "retry", "hypothesis_id": "hypothesis-2", "evidence_ids": ["evidence-2"]}, "already claimed in the obligation window"), ({"schema_version": "typed_progress_observation_v0", "result_class": "advanced", "surface_id": "retry", "hypothesis_id": "hypothesis-2", "evidence_ids": ["evidence-fresh"]}, "typed semantic delta"), @@ -251,6 +289,7 @@ def test_same_sequence_off_sees_nothing_and_assist_raises_the_obligation(sequenc autonomous_replan_recorded=True, repair_delta_kinds=["blocker"], progress_observation=non_novel, + agent_vision_packet=stop_vision, dry_run=False, sync_global=False, ) @@ -272,6 +311,7 @@ def test_same_sequence_off_sees_nothing_and_assist_raises_the_obligation(sequenc autonomous_replan_recorded=True, repair_delta_kinds=["blocker"], progress_observation={"schema_version": "typed_progress_observation_v0", "result_class": "advanced", "surface_id": "retry", "hypothesis_id": "hypothesis-renamed", "evidence_ids": ["evidence-2"]}, + agent_vision_packet=stop_vision, dry_run=False, sync_global=False, ) @@ -294,6 +334,7 @@ def test_same_sequence_off_sees_nothing_and_assist_raises_the_obligation(sequenc autonomous_replan_recorded=True, repair_delta_kinds=["blocker"], progress_observation={"schema_version": "typed_progress_observation_v0", "result_class": "advanced", "surface_id": "retry", "hypothesis_id": "hypothesis-1", "evidence_ids": ["evidence-1"]}, + agent_vision_packet=stop_vision, dry_run=False, sync_global=False, ) @@ -324,6 +365,7 @@ def test_same_sequence_off_sees_nothing_and_assist_raises_the_obligation(sequenc "blocker_id": "blocker-cosmetic-churn", "evidence_ids": ["evidence-progress-review-obligation"], }, + agent_vision_packet=stop_vision, dry_run=False, sync_global=False, ) @@ -386,9 +428,6 @@ def test_retried_turn_claim_is_rejected_by_real_refresh_writeback(tmp_path): project, runtime, registry = _write_fixture(tmp_path / "retry-fixture") _initialize_fixture_authority(project, runtime) - # Exercise duplicate claims independently of the optional Stride decision. - configure_goal(registry_path=registry, goal_id=GOAL_ID, - execution_stride_strategy="off", execute=True) first = run(1, turn="t1", agent=AGENT_ID) typed_retry = run(2, turn="t2", agent=AGENT_ID) untyped_retry = run(3, turn="t2", agent=AGENT_ID) @@ -430,11 +469,13 @@ def test_retried_turn_claim_is_rejected_by_real_refresh_writeback(tmp_path): assert obligation is not None and obligation["required"] is True assert [claim["result_class"] for claim in obligation["progress_window"]] == ["advanced", "blocked"] before = len(_newest_first_runs(runtime)) + stop_vision = _stride_vision(registry, runtime, outcome="stop") with pytest.raises(ValueError, match="already claimed in the obligation window"): _refresh( project, runtime, registry, autonomous_replan_recorded=True, repair_delta_kinds=["blocker"], progress_observation=typed_retry["progress_observation"], + agent_vision_packet=stop_vision, ) assert len(_newest_first_runs(runtime)) == before # The older blocker is also in the same window. It is not a new blocker @@ -444,6 +485,7 @@ def test_retried_turn_claim_is_rejected_by_real_refresh_writeback(tmp_path): project, runtime, registry, autonomous_replan_recorded=True, repair_delta_kinds=["blocker"], progress_observation=first["progress_observation"], + agent_vision_packet=stop_vision, ) assert len(_newest_first_runs(runtime)) == before assert _refresh( @@ -453,6 +495,7 @@ def test_retried_turn_claim_is_rejected_by_real_refresh_writeback(tmp_path): **typed_retry["progress_observation"], "hypothesis_id": "hypothesis-new", "evidence_ids": ["evidence-new"], }, + agent_vision_packet=stop_vision, )["ok"] is True assert _newest_first_runs(runtime)[0]["autonomous_replan_ack"]["recorded"] is True @@ -486,6 +529,7 @@ def test_outstanding_evaluations_keep_the_obligation_and_an_evidence_linked_visi assert open_obligation["progress_baseline"]["hypothesis_id"] == "hypothesis-3" # The writeback owner sees the same obligation: re-submitting the pending # claim, or renaming its hypothesis over its evidence ids, is refused. + stop_vision = _stride_vision(registry, runtime, outcome="stop") for observation, message in ( ({"hypothesis_id": "hypothesis-3", "evidence_ids": ["evidence-3"]}, "already claimed in the obligation window"), ({"hypothesis_id": "hypothesis-4", "evidence_ids": ["evidence-3"]}, "evidence ids absent from the evaluated baseline"), @@ -494,7 +538,7 @@ def test_outstanding_evaluations_keep_the_obligation_and_an_evidence_linked_visi with pytest.raises(ValueError, match=message): _refresh(project, runtime, registry, autonomous_replan_recorded=True, repair_delta_kinds=["blocker"], progress_observation={ "schema_version": "typed_progress_observation_v0", "result_class": "advanced", "surface_id": "retry", **observation, - }) + }, agent_vision_packet=stop_vision) # The outstanding evaluation fails closed: still no verdict, still open. calls = {"n": 0} @@ -515,21 +559,10 @@ def failing(request, config_, key): time.sleep(1.05) kept = _refresh(project, runtime, registry, autonomous_replan_recorded=True, repair_delta_kinds=["blocker"], recommended_action="Keep the retry slice; implement the TimeoutError retry next.", - agent_vision_packet={ - "agent_id": AGENT_ID, - "state": "active", - # `continue` keeps the acceptance as seeded; changing it would be a - # durable replan and the vision prepare gate demands `outcome=replan`. - "vision_patch": {"acceptance_summary": "deliver() retries one transient TimeoutError"}, - "path_delta": { - "schema_version": "goal_path_delta_v0", - "outcome": "continue", - "prior_assumption": "Renaming the delay constant prepared the retry slice.", - "observed_reality": "The evaluated deltas changed no behaviour; the retry branch is still missing.", - "retained": ["retry.py stays the surface; the next slice adds the retry branch."], - "evidence_refs": ["evidence:progress-review-vision-continue"], - }, - }) + agent_vision_packet=_stride_vision( + registry, runtime, outcome="continue", + evidence_ref="evidence:progress-review-vision-continue", + )) assert kept.get("ok") is True runs = _newest_first_runs(runtime) ack = runs[0].get("autonomous_replan_ack") or {} diff --git a/packages/loopx-jev/tests/test_identity_binding.py b/packages/loopx-jev/tests/test_identity_binding.py index b08b0366d3..a6b9a67a31 100644 --- a/packages/loopx-jev/tests/test_identity_binding.py +++ b/packages/loopx-jev/tests/test_identity_binding.py @@ -19,7 +19,7 @@ _initialize_fixture_authority, _write_fixture, ) -from test_closed_loop import SOURCE, _find, _goal, _newest_first_runs, _refresh +from test_closed_loop import SOURCE, _find, _goal, _newest_first_runs, _refresh, _stride_vision @pytest.mark.parametrize("unbound_field", ["agent_id", "todo_id", "ack_agent_id"]) @@ -75,10 +75,9 @@ def test_unattributed_newer_result_cannot_hide_existing_obligation(tmp_path, unb _refresh(project, runtime, registry, autonomous_replan_recorded=True, progress_observation=rows[0]["progress_observation"]) assert index.read_bytes() == before - # Isolate the external-review identity rule without weakening that default gate. - configure_goal(registry_path=registry, goal_id=GOAL_ID, - execution_stride_strategy="off", execute=True) + # Supplying a current terminal stride review reaches the external-review identity rule. with pytest.raises(ValueError, match="already claimed in the obligation window"): _refresh(project, runtime, registry, autonomous_replan_recorded=True, - progress_observation=rows[0]["progress_observation"]) + progress_observation=rows[0]["progress_observation"], + agent_vision_packet=_stride_vision(registry, runtime, outcome="stop")) assert index.read_bytes() == before diff --git a/tests/capabilities/test_machine_configuration_goal_defaults.py b/tests/capabilities/test_machine_configuration_goal_defaults.py index bb3c022810..709bb721d5 100644 --- a/tests/capabilities/test_machine_configuration_goal_defaults.py +++ b/tests/capabilities/test_machine_configuration_goal_defaults.py @@ -353,78 +353,139 @@ def test_product_default_and_namespace_removal_use_six_settled_turns(tmp_path, m assert _history_goal(registry_path, runtime_root)["execution_profile"]["replan_after_effective_turns"] == 6 -def test_stride_version_inherits_and_rolls_back(tmp_path: Path) -> None: - from loopx.chat.goal_configuration_api import _goal_capability_options +def _write_goal_profile(registry_path: Path, profile: dict[str, object]) -> None: + """Simulate a registry saved by a release that still had the stride switch.""" + payload = json.loads(registry_path.read_text()) + payload["goals"][0]["execution_profile"] = profile + registry_path.write_text(json.dumps(payload), encoding="utf-8") + + +def _cadence_review(registry_path: Path, runtime_root: Path) -> dict[str, object]: from loopx.capabilities.goal_inspection import inspect_goal_capabilities + inspected = inspect_goal_capabilities( + registry_path=registry_path, runtime_root=runtime_root, goal_id=GOAL_ID, + )["configuration"] + return next(item for item in inspected["capability_catalog"]["capabilities"] + if item["capability_id"] == "todo_replan_cadence") + + +@pytest.mark.parametrize("legacy", ["off", "evidence_conditioned_v1"]) +def test_legacy_machine_stride_strategy_loads_and_is_ignored(tmp_path: Path, legacy: str) -> None: + from loopx.capabilities.machine_configuration.store import machine_configuration_store_path + _repo, registry_path, runtime_root = _fixture(tmp_path) - owner = build_builtin_machine_configuration_registry() - configuration = _machine_configuration() - configuration["namespaces"]["todo_replan_cadence"] = { + # A v2 device file written by an earlier release still carries the switch. + store = machine_configuration_store_path(runtime_root) + saved = json.loads(store.read_text()) + saved["namespaces"]["todo_replan_cadence"] = { "schema_version": "todo_replan_cadence_machine_defaults_v2", - "count_unit": "effective_turns", "count": 6, - "stride_strategy": "evidence_conditioned_v1", + "count_unit": "effective_turns", "count": 4, "stride_strategy": legacy, } - before = registry_path.read_bytes() - preview = configure_machine_configuration(runtime_root=runtime_root, - registry=owner, configuration=configuration) - assert registry_path.read_bytes() == before - configure_machine_configuration(runtime_root=runtime_root, registry=owner, - configuration=configuration, execute=True, expected_plan_revision=preview["plan_revision"]) - assert _history_goal(registry_path, runtime_root)["execution_profile"]["stride_strategy"] == "evidence_conditioned_v1" - # A cadence-only Goal override retains the previous default-off meaning. - configure_goal(registry_path=registry_path, goal_id=GOAL_ID, - execution_replan_after_turns=3, execute=True) - assert "stride_strategy" not in _history_goal(registry_path, runtime_root)["execution_profile"] - enabled = _goal_capability_options("todo_replan_cadence", { - "count_unit": "effective_turns", "count": 3, "stride_strategy": "evidence_conditioned_v1"}) - configure_goal(registry_path=registry_path, goal_id=GOAL_ID, execute=True, **enabled) - inspected = inspect_goal_capabilities(registry_path=registry_path, runtime_root=runtime_root, - goal_id=GOAL_ID)["configuration"] - review = next(item for item in inspected["capability_catalog"]["capabilities"] - if item["capability_id"] == "todo_replan_cadence") - assert review["current"] == {"count_unit": "effective_turns", "count": 3, "stride_strategy": "evidence_conditioned_v1"} + store.write_text(json.dumps(saved), encoding="utf-8") + before = store.read_bytes() + profile = _history_goal(registry_path, runtime_root)["execution_profile"] + assert profile["replan_after_effective_turns"] == 4 + assert "stride_strategy" not in profile + review = _cadence_review(registry_path, runtime_root) + assert "stride_strategy" not in review["machine_current"] + assert "stride_strategy" not in review["effective_configuration"]["configuration"] + assert all(field["key"] != "stride_strategy" for field in review["configuration_editor"]["fields"]) + assert store.read_bytes() == before, "reading must not migrate the stored device file" + + # A whole-document write of the same legacy shape is accepted (restore of an + # old backup) and persists without the removed field. + owner = build_builtin_machine_configuration_registry() + configuration = _machine_configuration() + configuration["namespaces"]["todo_replan_cadence"] = dict(saved["namespaces"]["todo_replan_cadence"]) + preview = configure_machine_configuration(runtime_root=runtime_root, registry=owner, configuration=configuration) + configure_machine_configuration(runtime_root=runtime_root, registry=owner, configuration=configuration, + execute=True, expected_plan_revision=preview["plan_revision"]) + stored = json.loads(store.read_text())["namespaces"]["todo_replan_cadence"] + assert stored == {"schema_version": "todo_replan_cadence_machine_defaults_v2", + "count_unit": "effective_turns", "count": 4} + + +@pytest.mark.parametrize("legacy", ["off", "evidence_conditioned_v1"]) +def test_legacy_goal_stride_strategy_loads_is_ignored_and_dropped_on_write(tmp_path: Path, legacy: str) -> None: + from loopx.chat.goal_configuration_api import _goal_capability_options + from loopx.execution_profile import compact_execution_profile + + _repo, registry_path, runtime_root = _fixture(tmp_path) + _write_goal_profile(registry_path, {"replan_after_effective_turns": 3, "stride_strategy": legacy}) + raw = json.loads(registry_path.read_text())["goals"][0]["execution_profile"] + assert "stride_strategy" not in compact_execution_profile(raw) + profile = _history_goal(registry_path, runtime_root)["execution_profile"] + assert profile["replan_after_effective_turns"] == 3 + assert "stride_strategy" not in profile + review = _cadence_review(registry_path, runtime_root) + assert review["current"] == {"count_unit": "effective_turns", "count": 3} assert review["effective_configuration"]["source"] == "goal_override" - configure_goal(registry_path=registry_path, goal_id=GOAL_ID, - execution_stride_strategy="off", execute=True) - assert _history_goal(registry_path, runtime_root)["execution_profile"]["stride_strategy"] == "off" - clear_options = _goal_capability_options("todo_replan_cadence", None) - before = registry_path.read_bytes() - preview = configure_goal(registry_path=registry_path, goal_id=GOAL_ID, **clear_options) - assert preview["changed"] is True - assert registry_path.read_bytes() == before - configure_goal(registry_path=registry_path, goal_id=GOAL_ID, - execute=True, **clear_options) - assert "stride_strategy" not in json.loads(registry_path.read_text())["goals"][0]["execution_profile"] - assert _history_goal(registry_path, runtime_root)["execution_profile"]["stride_strategy"] == "evidence_conditioned_v1" - inspected = inspect_goal_capabilities(registry_path=registry_path, runtime_root=runtime_root, - goal_id=GOAL_ID)["configuration"] - review = next(item for item in inspected["capability_catalog"]["capabilities"] - if item["capability_id"] == "todo_replan_cadence") + + # A stride-only legacy profile is no override at all. + _write_goal_profile(registry_path, {"stride_strategy": legacy}) + assert "stride_strategy" not in _history_goal(registry_path, runtime_root)["execution_profile"] + review = _cadence_review(registry_path, runtime_root) assert "current" not in review assert review["effective_configuration"]["source"] == "machine_default" - assert review["effective_configuration"]["inherited"] is True - assert _history_goal(registry_path, runtime_root)["execution_profile"]["replan_after_effective_turns"] == 6 - # Unsupported versions fail before any registry mutation. + + # Clearing the capability no longer names the removed switch, yet drops it. + clear_options = _goal_capability_options("todo_replan_cadence", None) + assert not any("stride" in key for key in clear_options) + configure_goal(registry_path=registry_path, goal_id=GOAL_ID, execute=True, **clear_options) + assert "stride_strategy" not in json.loads(registry_path.read_text())["goals"][0]["execution_profile"] + + # Any later profile write also drops the legacy key. + _write_goal_profile(registry_path, {"replan_after_effective_turns": 3, "stride_strategy": legacy}) + configure_goal(registry_path=registry_path, goal_id=GOAL_ID, execution_replan_after_turns=4, execute=True) + stored = json.loads(registry_path.read_text())["goals"][0]["execution_profile"] + assert stored["replan_after_effective_turns"] == 4 + assert "stride_strategy" not in stored + + +def test_removed_stride_switch_rejects_new_writes(tmp_path: Path) -> None: + from loopx.capabilities.machine_configuration.contract import merge_machine_configuration_namespace + from loopx.chat.goal_configuration_api import _goal_capability_options + from loopx.execution_profile import compact_execution_profile + + _repo, registry_path, runtime_root = _fixture(tmp_path) before = registry_path.read_bytes() - with pytest.raises(ValueError, match="stride_strategy"): - configure_goal(registry_path=registry_path, goal_id=GOAL_ID, - execution_replan_after_turns=3, execution_stride_strategy="future_v2", execute=True) + for strategy in ("off", "evidence_conditioned_v1"): + for payload in ({"stride_strategy": strategy}, + {"count_unit": "effective_turns", "count": 3, "stride_strategy": strategy}): + with pytest.raises(ValueError, match="stride_strategy was removed"): + _goal_capability_options("todo_replan_cadence", payload) + with pytest.raises(ValueError, match="stride_strategy was removed"): + merge_machine_configuration_namespace( + _machine_configuration(), namespace="todo_replan_cadence", + namespace_configuration={ + "schema_version": "todo_replan_cadence_machine_defaults_v2", + "count_unit": "effective_turns", "count": 3, "stride_strategy": strategy, + }, + registry=build_builtin_machine_configuration_registry(), + ) + with pytest.raises(TypeError, match="execution_stride_strategy"): + configure_goal(registry_path=registry_path, goal_id=GOAL_ID, # type: ignore[call-arg] + execution_stride_strategy="off", execute=True) + with pytest.raises(TypeError, match="clear_execution_stride_strategy"): + configure_goal(registry_path=registry_path, goal_id=GOAL_ID, # type: ignore[call-arg] + clear_execution_stride_strategy=True, execute=True) assert registry_path.read_bytes() == before + # Historical decode still validates the recorded value. + with pytest.raises(ValueError, match="stride_strategy"): + compact_execution_profile({"stride_strategy": "future_v2"}) -def test_goal_stride_only_uses_live_review_interval(tmp_path: Path) -> None: +def test_goal_option_only_override_uses_live_review_interval(tmp_path: Path) -> None: from loopx.chat.goal_configuration_api import _goal_capability_options - from loopx.capabilities.goal_inspection import inspect_goal_capabilities _repo, registry_path, runtime_root = _fixture(tmp_path) options = _goal_capability_options("todo_replan_cadence", { - "stride_strategy": "evidence_conditioned_v1", + "yardstick_enabled": False, }) assert options == { "clear_execution_planning_horizon_goal": True, - "clear_execution_yardstick_enabled": True, - "execution_stride_strategy": "evidence_conditioned_v1", + "execution_yardstick_enabled": False, "clear_execution_replan_after_turns": True, "clear_execution_replan_after_todos": True, } @@ -434,25 +495,18 @@ def test_goal_stride_only_uses_live_review_interval(tmp_path: Path) -> None: assert registry_path.read_bytes() == before configure_goal(registry_path=registry_path, goal_id=GOAL_ID, execute=True, **options) raw = json.loads(registry_path.read_text())["goals"][0]["execution_profile"] - assert raw["stride_strategy"] == "evidence_conditioned_v1" + assert raw["yardstick_enabled"] is False assert "replan_after_effective_turns" not in raw assert "replan_after_completed_todos" not in raw inherited = _history_goal(registry_path, runtime_root)["execution_profile"] assert inherited["replan_after_completed_todos"] == 2 - assert inherited["stride_strategy"] == "evidence_conditioned_v1" - - def review() -> dict[str, object]: - inspection = inspect_goal_capabilities( - registry_path=registry_path, runtime_root=runtime_root, goal_id=GOAL_ID, - )["configuration"] - return next(row for row in inspection["capability_catalog"]["capabilities"] - if row["capability_id"] == "todo_replan_cadence") + assert "stride_strategy" not in inherited - first = review() - assert first["current"] == {"stride_strategy": "evidence_conditioned_v1"} + first = _cadence_review(registry_path, runtime_root) + assert first["current"] == {"yardstick_enabled": False} + assert first["effective_value_policy"] == "goal_stride_over_live_review_cadence" assert first["effective_configuration"]["configuration"] == { "count_unit": "completed_todos", "count": 2, - "stride_strategy": "evidence_conditioned_v1", "planning_horizon_goal": True, "yardstick_enabled": False, } @@ -461,7 +515,7 @@ def review() -> dict[str, object]: machine = _machine_configuration() machine["namespaces"]["todo_replan_cadence"] = { "schema_version": "todo_replan_cadence_machine_defaults_v2", - "count_unit": "effective_turns", "count": 4, "stride_strategy": "off", + "count_unit": "effective_turns", "count": 4, } preview = configure_machine_configuration( runtime_root=runtime_root, registry=machine_registry, configuration=machine, @@ -472,8 +526,7 @@ def review() -> dict[str, object]: ) projected = _history_goal(registry_path, runtime_root)["execution_profile"] assert projected["replan_after_effective_turns"] == 4 - assert projected["stride_strategy"] == "evidence_conditioned_v1" - second = review() + second = _cadence_review(registry_path, runtime_root) assert second["current"] == first["current"] assert second["effective_configuration"]["configuration"]["count"] == 4 assert second["effective_configuration"]["effective_revision"] != first["effective_configuration"]["effective_revision"] @@ -481,28 +534,19 @@ def review() -> dict[str, object]: configure_goal(registry_path=registry_path, goal_id=GOAL_ID, execution_replan_after_turns=3, execute=True) assert _history_goal(registry_path, runtime_root)["execution_profile"]["replan_after_effective_turns"] == 3 - assert _history_goal(registry_path, runtime_root)["execution_profile"]["stride_strategy"] == "evidence_conditioned_v1" - # Strategy-only capability JSON replaces its interval override; the CLI's - # strategy-only patch above does not silently clear a stored interval. + # Option-only capability JSON replaces its interval override. configure_goal(registry_path=registry_path, goal_id=GOAL_ID, execute=True, **options) raw = json.loads(registry_path.read_text())["goals"][0]["execution_profile"] assert "replan_after_effective_turns" not in raw - assert raw["stride_strategy"] == "evidence_conditioned_v1" assert _history_goal(registry_path, runtime_root)["execution_profile"]["replan_after_effective_turns"] == 4 - configure_goal(registry_path=registry_path, goal_id=GOAL_ID, - execution_stride_strategy="off", execute=True) - assert _history_goal(registry_path, runtime_root)["execution_profile"]["stride_strategy"] == "off" - with pytest.raises(ValueError, match="stride_strategy"): - _goal_capability_options("todo_replan_cadence", {"stride_strategy": "unknown"}) - @pytest.mark.parametrize("schema_version, strategy", [ ("todo_replan_cadence_machine_defaults_v1", "evidence_conditioned_v1"), ("todo_replan_cadence_machine_defaults_v2", "future_v2"), ("todo_replan_cadence_machine_defaults_v2", None), ]) -def test_stride_configuration_rejects_unsupported_or_ambiguous_versions(schema_version, strategy): +def test_legacy_stride_field_rejects_unsupported_or_ambiguous_versions(schema_version, strategy): with pytest.raises(ValueError): normalize_todo_replan_cadence_machine_defaults({ "schema_version": schema_version, "count_unit": "effective_turns", @@ -510,6 +554,18 @@ def test_stride_configuration_rejects_unsupported_or_ambiguous_versions(schema_v }) +@pytest.mark.parametrize("legacy", [None, "off", "evidence_conditioned_v1"]) +def test_v2_machine_defaults_make_stride_strategy_optional_on_read(legacy): + raw = {"schema_version": "todo_replan_cadence_machine_defaults_v2", + "count_unit": "effective_turns", "count": 6, "yardstick_enabled": True} + if legacy is not None: + raw["stride_strategy"] = legacy + assert normalize_todo_replan_cadence_machine_defaults(raw) == { + "schema_version": "todo_replan_cadence_machine_defaults_v2", + "count_unit": "effective_turns", "count": 6, "yardstick_enabled": True, + } + + def test_horizon_goal_defaults_on_with_explicit_overrides_and_clear(tmp_path): from loopx.chat.goal_configuration_api import _goal_capability_options from loopx.capabilities.goal_inspection import inspect_goal_capabilities @@ -561,12 +617,11 @@ def effective(): assert registry_path.read_bytes() == before -def test_stride_default_preserves_explicit_off_and_saved_legacy_configuration(tmp_path: Path) -> None: +def test_stride_is_not_a_configuration_default_and_never_projected(tmp_path: Path) -> None: from loopx.capabilities.todo_replan_cadence.machine_defaults import ( apply_todo_replan_cadence_machine_default, default_replan_cadence_configuration, todo_replan_cadence_machine_configuration_namespace, ) - from loopx.capabilities.goal_inspection import inspect_goal_capabilities _repo, registry, runtime = _fixture(tmp_path) from loopx.capabilities.machine_configuration.contract import remove_machine_configuration_namespace owner = build_builtin_machine_configuration_registry() @@ -576,25 +631,27 @@ def test_stride_default_preserves_explicit_off_and_saved_legacy_configuration(tm configure_machine_configuration(runtime_root=runtime, registry=owner, configuration=removed, execute=True, expected_plan_revision=preview["plan_revision"]) original = registry.read_bytes() - assert default_replan_cadence_configuration()["stride_strategy"] == "evidence_conditioned_v1" - assert todo_replan_cadence_machine_configuration_namespace().default_configuration["stride_strategy"] == "evidence_conditioned_v1" + assert "stride_strategy" not in default_replan_cadence_configuration() + assert "stride_strategy" not in todo_replan_cadence_machine_configuration_namespace().default_configuration inherited = _history_goal(registry, runtime) - assert inherited["execution_profile"]["stride_strategy"] == "evidence_conditioned_v1" + assert "stride_strategy" not in inherited["execution_profile"] assert registry.read_bytes() == original - catalog = inspect_goal_capabilities(registry_path=registry, runtime_root=runtime, - goal_id=GOAL_ID)["configuration"]["capability_catalog"]["capabilities"] - effective = next(c for c in catalog if c["capability_id"] == "todo_replan_cadence")["effective_configuration"] - assert effective["source"] == "capability_default" - assert effective["configuration"]["stride_strategy"] == "evidence_conditioned_v1" - off = apply_todo_replan_cadence_machine_default({"execution_profile": {"stride_strategy": "off"}}, None) - assert off["execution_profile"]["stride_strategy"] == "off" + review = _cadence_review(registry, runtime) + assert review["effective_configuration"]["source"] == "capability_default" + assert "stride_strategy" not in review["effective_configuration"]["configuration"] + for legacy in ("off", "evidence_conditioned_v1"): + for profile in ({"stride_strategy": legacy}, + {"stride_strategy": legacy, "replan_after_effective_turns": 3}): + projected = apply_todo_replan_cadence_machine_default({"execution_profile": profile}, None) + assert "stride_strategy" not in projected["execution_profile"] for saved in ({"schema_version": "todo_replan_cadence_machine_defaults_v0", "completed_todos": 2}, {"schema_version": "todo_replan_cadence_machine_defaults_v1", "count_unit": "effective_turns", "count": 4}, + {"schema_version": "todo_replan_cadence_machine_defaults_v2", "count_unit": "effective_turns", "count": 4}, {"schema_version": "todo_replan_cadence_machine_defaults_v2", "count_unit": "effective_turns", "count": 4, "stride_strategy": "off"}): machine = _machine_configuration() machine["namespaces"]["todo_replan_cadence"] = saved projected = apply_todo_replan_cadence_machine_default({}, machine) - assert projected["execution_profile"].get("stride_strategy", "off") == "off" + assert "stride_strategy" not in projected["execution_profile"] legacy_goal = {"execution_profile": {"replan_after_effective_turns": 3}} assert apply_todo_replan_cadence_machine_default(legacy_goal, None) == legacy_goal @@ -611,8 +668,7 @@ def test_yardstick_inherits_independently_of_a_pinned_goal_cadence(tmp_path): machine = _machine_configuration() machine["namespaces"]["todo_replan_cadence"] = { "schema_version": "todo_replan_cadence_machine_defaults_v2", - "count_unit": "effective_turns", "count": 5, - "stride_strategy": "evidence_conditioned_v1", "yardstick_enabled": True, + "count_unit": "effective_turns", "count": 5, "yardstick_enabled": True, } owner = build_builtin_machine_configuration_registry() plan = configure_machine_configuration(runtime_root=runtime_root, registry=owner, configuration=machine) @@ -622,7 +678,7 @@ def test_yardstick_inherits_independently_of_a_pinned_goal_cadence(tmp_path): effective = resolve_todo_replan_cadence_goal(raw, runtime_root)["execution_profile"] assert effective["replan_after_effective_turns"] == 3 assert effective["yardstick_enabled"] is True - assert "stride_strategy" not in effective, "legacy cadence-only strategy semantics remain off" + assert "stride_strategy" not in effective, "the removed stride switch is never projected" assert registry_path.read_bytes() == original, "inheritance must not migrate stored Goal state" projected = _history_goal(registry_path, runtime_root) assert projected["execution_profile"]["yardstick_enabled"] is True @@ -669,9 +725,10 @@ def test_legacy_cadence_keeps_yardstick_absent_and_default_off(version): legacy = {"schema_version": f"todo_replan_cadence_machine_defaults_v{version}"} legacy.update({"completed_todos": 2} if version == 0 else {"count_unit": "effective_turns", "count": 6}) + expected = dict(legacy) if version == 2: - legacy["stride_strategy"] = "off" - assert normalize_todo_replan_cadence_machine_defaults(legacy) == legacy + legacy["stride_strategy"] = "off" # legacy v2 files load; the field is dropped + assert normalize_todo_replan_cadence_machine_defaults(legacy) == expected machine = {"schema_version": "loopx_machine_configuration_v0", "namespaces": {"todo_replan_cadence": legacy}} assert "yardstick_enabled" not in apply_todo_replan_cadence_machine_default({}, machine)["execution_profile"] if version < 2: diff --git a/tests/control_plane/replan_packet_fixture.py b/tests/control_plane/replan_packet_fixture.py index 23d9aec6bd..c2d38cfa42 100644 --- a/tests/control_plane/replan_packet_fixture.py +++ b/tests/control_plane/replan_packet_fixture.py @@ -17,7 +17,7 @@ def populated_replan_source(root, *, acceptance=False, explore_context=None): - source = _quota_payload(stride_strategy="evidence_conditioned_v1") + source = _quota_payload() source["replan_read_path"] = "/synthetic/decision.json" obligation = deepcopy(source["autonomous_replan_obligation"]) _, decision, work = _rows() @@ -104,7 +104,7 @@ def scoped(value): index.parent.mkdir(parents=True) index.write_text("".join(json.dumps(row) + "\n" for row in rows)) context = project_replan_context(goal_id=GOAL_ID, agent_id=AGENT_ID, obligation=obligation, - runs=(), source_status={"registry": str(registry), "runtime_root": str(runtime), "run_history": {"runs": []}}, stride_strategy="evidence_conditioned_v1", + runs=(), source_status={"registry": str(registry), "runtime_root": str(runtime), "run_history": {"runs": []}}, goal_acceptance_contract=contract, explore_context=explore_context, todo_items=[{"todo_id": "todo-a", "goal_id": GOAL_ID, "role": "agent", "status": "waiting", "claimed_by": AGENT_ID, "task_class": "advancement_task", "action_kind": "validate"}]) diff --git a/tests/control_plane/test_effective_turn_replan.py b/tests/control_plane/test_effective_turn_replan.py index 4422758afc..f17d182db3 100644 --- a/tests/control_plane/test_effective_turn_replan.py +++ b/tests/control_plane/test_effective_turn_replan.py @@ -41,7 +41,7 @@ def test_refresh_and_spend_survive_an_unrelated_invalid_review_receipt(tmp_path, isolate_sqlite_runtime(tmp_path, monkeypatch) project, runtime, registry = _write_fixture(tmp_path, provider=provider) rc, configured = _run_cli(registry, runtime, "configure-goal", "--goal-id", GOAL_ID, - "--execution-stride-strategy", "off", "--execution-replan-after-turns", "6", "--execute") + "--execution-replan-after-turns", "6", "--execute") assert rc == 0, configured turn = "peer-isolation-turn" binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID, @@ -125,20 +125,18 @@ def test_open_todo_settled_turn_cadence_and_evidence_linked_review( runtime_root=runtime, registry=machine_registry, configuration=configuration, execute=True, expected_plan_revision=preview["plan_revision"], ) - rc, configured = _run_cli( - registry, - runtime, - "configure-goal", - "--goal-id", - GOAL_ID, - # This matrix isolates cadence and typed-delta authority from the - # optional structured Stride decision. Inherited-on behavior is - # covered by machine-default and actual Stride followthrough tests. - "--execution-stride-strategy", "off", "--execute", - *(["--execution-replan-after-turns", str(threshold_override)] - if threshold_override else []), - ) - assert rc == 0, configured + if threshold_override: + rc, configured = _run_cli( + registry, + runtime, + "configure-goal", + "--goal-id", + GOAL_ID, + "--execution-replan-after-turns", + str(threshold_override), + "--execute", + ) + assert rc == 0, configured goal = json.loads(registry.read_text())["goals"][0] if threshold_override: assert goal["execution_profile"]["replan_after_effective_turns"] == threshold_override @@ -349,6 +347,9 @@ def periodic(): "prior_assumption": "The existing method remains viable.", "observed_reality": "Current validation supports continuing it.", "retained": ["Existing method and open Todo"], "evidence_refs": []} + vision["stride_decision"] = json.loads( + json.dumps(selected["replan_action_packet"]["stride_control"]["minimal_example"]) + ) command = shlex.split(selected["interaction_contract"]["cli_channel"]["next_cli_actions"][0]) command = command[command.index("refresh-state"):] command[command.index("--agent-vision-json") + 1] = str(vision_path) @@ -356,7 +357,7 @@ def periodic(): vision_path.write_text(json.dumps(vision)) rc, rejected = _run_cli(registry, runtime, *command) assert rc == 1 and rejected["appended"] is False, rejected - assert "typed semantic delta" in rejected["error"], rejected + assert "evidence" in rejected["error"].lower(), rejected vision["path_delta"]["evidence_refs"] = ["evidence:method-validation"] vision_path.write_text(json.dumps(vision)) rc, accepted = _run_cli(registry, runtime, *command) @@ -417,8 +418,7 @@ def call(*args: str, expected_code: int = 0) -> dict: assert code == expected_code, json.dumps(result, indent=2) return result - call("configure-goal", "--goal-id", GOAL_ID, "--execution-replan-after-turns", "2", - "--execution-stride-strategy", "evidence_conditioned_v1", "--execute") + call("configure-goal", "--goal-id", GOAL_ID, "--execution-replan-after-turns", "2", "--execute") for index in range(2): turn = f"stride-cadence-{index}" guard = call("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, @@ -769,7 +769,7 @@ def call(*args: str, expected_code: int = 0) -> dict: context = project_replan_context(goal_id=GOAL_ID, agent_id=AGENT_ID, runs=load_index_snapshot(runtime / "goals" / GOAL_ID / "runs/index.jsonl", include_artifact_status=False).records, - history_newest_first=False, stride_strategy="evidence_conditioned_v1") + history_newest_first=False) assert any(row["coverage_ref"] == status_run["progress_observation"]["fingerprint"] for row in context["decision_followthrough"]["observations"]) pending = context["decision_followthrough"]["work_result_use"] diff --git a/tests/control_plane/test_final_outcome_diagnostics.py b/tests/control_plane/test_final_outcome_diagnostics.py index b73aeba4de..51aabbc8fd 100644 --- a/tests/control_plane/test_final_outcome_diagnostics.py +++ b/tests/control_plane/test_final_outcome_diagnostics.py @@ -447,6 +447,9 @@ def test_public_cli_diagnostic_reentry_preserves_guard_identity_without_spending corrected["path_delta"]["observed_reality"] = ( "The route and evidence are valid; add the missing final-outcome claim." ) + corrected["stride_decision"] = results[0]["replan_action_packet"][ + "stride_control" + ]["minimal_example"] written = refresh_state_run( registry_path=registry, runtime_root_override=str(runtime), diff --git a/tests/control_plane/test_goal_amendment_authority.py b/tests/control_plane/test_goal_amendment_authority.py index 6e4f52a8f7..30a8864df2 100644 --- a/tests/control_plane/test_goal_amendment_authority.py +++ b/tests/control_plane/test_goal_amendment_authority.py @@ -13,17 +13,26 @@ from loopx.control_plane.projects.registry_codec import load_project_registry -def _configure_fixture_stride(runtime: Path, strategy: str) -> None: - from loopx.capabilities.machine_configuration.builtins import build_builtin_machine_configuration_registry - from loopx.capabilities.machine_configuration.store import configure_machine_configuration - - owner = build_builtin_machine_configuration_registry() - configuration = {"schema_version": "loopx_machine_configuration_v0", "namespaces": { - "todo_replan_cadence": {"schema_version": "todo_replan_cadence_machine_defaults_v2", - "count_unit": "effective_turns", "count": 6, "stride_strategy": strategy}}} - preview = configure_machine_configuration(runtime_root=runtime, registry=owner, configuration=configuration) - configure_machine_configuration(runtime_root=runtime, registry=owner, configuration=configuration, - execute=True, expected_plan_revision=preview["plan_revision"]) +def _monitor_repeat_runs(*, goal_ref: dict, count: int = 6) -> list[dict]: + return [ + { + "generated_at": f"2026-01-01T02:{offset:02d}:00+00:00", + "classification": "quota_monitor_poll", + "agent_id": "agent-a", + "delivery_outcome": "surface_only", + "todo_id": "todo_due_monitor", + "target_key": "monitor-current-route", + "goal_ref": goal_ref, + "monitor_target": { + "schema_version": "quota_monitor_target_v0", + "target_id": "monitor-current-route", + "monitor_mode": "due_monitor_observed_without_material_transition", + "effective_action": "normal_run", + "agent_id": "agent-a", + }, + } + for offset in range(count) + ] @pytest.fixture(params=["file", "sqlite"]) @@ -192,9 +201,20 @@ def delayed(method, params, **kwargs): @pytest.mark.parametrize("claim_agent", ["agent-a", "agent-b"]) def test_claimed_successor_is_consumed_by_existing_replan_owner(source_goal, tmp_path, capsys, claim_agent): f = source_goal - # This journey verifies the direct successor acknowledgement and lease - # replay. The periodic journey below covers the distinct Stride gate. - _configure_fixture_stride(f["runtime"], "off") + # Use a non-stride obligation (dead_monitor_repeat) to verify direct + # successor acknowledgement and lease replay; the periodic journey below + # verifies that cadence/stall stride reviews never auto-settle on claim. + monitor_rows = _monitor_repeat_runs(goal_ref=f["ref"]) + f["runs"].write_text("".join(json.dumps(row) + "\n" for row in monitor_rows)) + goal = load_project_registry(f["registry"])["goals"][0] + derived = _derive_open_replan_obligation_inventory( + runtime_root=f["runtime"], goal_id=f["ref"]["goal_id"], + goal=goal, state_text="", goal_ref=f["ref"], + ) + inventory = _open_replan_obligation_inventory( + goal_id=f["ref"]["goal_id"], registered_agents=["agent-a", "agent-b"], status_item=derived, + ) + f["obligation"] = next(row["obligation_id"] for row in inventory if "agent-a" in row["bound_agent_ids"]) view = _call(f, tmp_path, capsys, "inspect")[1] root = _root(view) assert _call(f, tmp_path, capsys, "configure", root, agent=None, operation_id="root", execute=True)[0] == 0 @@ -236,8 +256,7 @@ def test_claimed_successor_is_consumed_by_existing_replan_owner(source_goal, tmp assert original["receipts"][0]["result"]["replan_settlement"] == "pending" -@pytest.mark.parametrize("strategy", ["off", "evidence_conditioned_v1"]) -def test_periodic_successor_readback_uses_live_machine_stride(source_goal, tmp_path, capsys, strategy): +def test_periodic_successor_readback_enforces_unconditional_stride(source_goal, tmp_path, capsys): from loopx.capabilities.todo_replan_cadence.machine_defaults import resolve_todo_replan_cadence_goal f = source_goal @@ -249,11 +268,10 @@ def test_periodic_successor_readback_uses_live_machine_stride(source_goal, tmp_p row["progress_observation"].update(result_class="advanced", surface_id=f"coverage-{index}", hypothesis_id=f"hypothesis-{index}") f["runs"].write_text("".join(json.dumps(row) + "\n" for row in rows)) - _configure_fixture_stride(f["runtime"], strategy) goal = load_project_registry(f["registry"])["goals"][0] assert "stride_strategy" not in goal.get("execution_profile", {}) effective = resolve_todo_replan_cadence_goal(goal, f["runtime"]) - assert effective["execution_profile"].get("stride_strategy", "off") == strategy + assert "stride_strategy" not in effective.get("execution_profile", {}) derived = _derive_open_replan_obligation_inventory(runtime_root=f["runtime"], goal_id=f["ref"]["goal_id"], goal=goal, state_text="", goal_ref=f["ref"]) candidates = list(derived.get("autonomous_replan_obligations_by_agent", {}).values()) @@ -283,12 +301,8 @@ def test_periodic_successor_readback_uses_live_machine_stride(source_goal, tmp_p assert code == 0, claimed observation = next(row for row in claimed["current_projection"]["replan_observations"] if row["obligation_id"] == f["obligation"] and row["agent_id"] == "agent-a") - if strategy == "off": - assert observation["state"] == "settled" - assert observation["acknowledgement"]["source"] == "todo_replan_successor_transition" - else: - assert observation["state"] == "pending" - assert observation["acknowledgement"] is None + assert observation["state"] == "pending" + assert observation["acknowledgement"] is None # The source observation neither fabricates a decision nor rewrites history. assert f["runs"].read_text() == "".join(json.dumps(row) + "\n" for row in rows) diff --git a/tests/control_plane/test_goal_amendment_proposal_lifecycle.py b/tests/control_plane/test_goal_amendment_proposal_lifecycle.py index 83c46b60ba..ec440bb0ca 100644 --- a/tests/control_plane/test_goal_amendment_proposal_lifecycle.py +++ b/tests/control_plane/test_goal_amendment_proposal_lifecycle.py @@ -343,8 +343,10 @@ def test_production_quota_obligation_survives_the_full_amendment_lifecycle( "retained": ["Original Goal objective, completion criteria and proposal review authority."], "evidence_refs": [listed["rows"][0]["proposal_id"]], }, + "stride_decision": guard["replan_action_packet"]["stride_control"]["minimal_example"], }), encoding="utf-8") evidence = { + "": str(vision), "": "advanced", "": "surface:amendment-proposal", "": "hypothesis:proposal-admission", @@ -352,11 +354,12 @@ def test_production_quota_obligation_survives_the_full_amendment_lifecycle( "": listed["rows"][0]["proposal_id"], } refresh_args = [evidence.get(arg, arg) for arg in _projected_cli_args(refresh_command)] + extra_vision = [] if "--agent-vision-json" in refresh_args else ["--agent-vision-json", str(vision)] refresh_rc, refresh = _run_cli( registry_path, runtime, *refresh_args, - "--agent-vision-json", str(vision), + *extra_vision, "--no-global-sync", "--suppress-external-sinks", ) diff --git a/tests/control_plane/test_goal_frontier_replan_rules.py b/tests/control_plane/test_goal_frontier_replan_rules.py index a0f1e3e83e..a4f3a991fa 100644 --- a/tests/control_plane/test_goal_frontier_replan_rules.py +++ b/tests/control_plane/test_goal_frontier_replan_rules.py @@ -680,14 +680,10 @@ def test_exact_replan_successor_uses_authoritative_todo_source() -> None: due = {"obligation_id": obligation_id, "triggers": [{"kind": "periodic_review_due"}]} assert replan_successor_transition_ack( None, agent_id="current-agent", replan_obligation=due, - agent_todo_items=[successor], stride_strategy="evidence_conditioned_v1", + agent_todo_items=[successor], ) is None assert not autonomous_replan_ack_satisfies_obligation( ack, replan_obligation=due, acceptance_gaps=None, - stride_strategy="evidence_conditioned_v1", - ) - assert autonomous_replan_ack_satisfies_obligation( - ack, replan_obligation=due, acceptance_gaps=None, stride_strategy="off", ) diff --git a/tests/control_plane/test_long_chain_projected_closeout.py b/tests/control_plane/test_long_chain_projected_closeout.py index 3cdc553896..84981b2fc7 100644 --- a/tests/control_plane/test_long_chain_projected_closeout.py +++ b/tests/control_plane/test_long_chain_projected_closeout.py @@ -132,8 +132,7 @@ def guard(turn): ) call("configure-goal", "--goal-id", GOAL_ID, - "--execution-replan-after-turns", "6", - "--execution-stride-strategy", "evidence_conditioned_v1", "--execute") + "--execution-replan-after-turns", "6", "--execute") shared = call("quota", "should-run", "--runtime-profile", "generic_cli", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID) diff --git a/tests/control_plane/test_material_feedback_checkpoint.py b/tests/control_plane/test_material_feedback_checkpoint.py index b4066905bc..c8bae16afb 100644 --- a/tests/control_plane/test_material_feedback_checkpoint.py +++ b/tests/control_plane/test_material_feedback_checkpoint.py @@ -20,11 +20,11 @@ import test_quota_settlement_cli as fixture -@pytest.mark.parametrize(("provider", "strategy", "handoff_mode", "preexisting_feedback"), [ - (*case, False) for case in product(["file", "sqlite"], ["off", "evidence_conditioned_v1"], ["soft_claim", "hard_lease"]) -] + [pytest.param("sqlite", "evidence_conditioned_v1", "hard_lease", True, id="historical-feedback-is-context")]) +@pytest.mark.parametrize(("provider", "handoff_mode", "preexisting_feedback"), [ + (*case, False) for case in product(["file", "sqlite"], ["soft_claim", "hard_lease"]) +] + [pytest.param("sqlite", "hard_lease", True, id="historical-feedback-is-context")]) def test_feedback_checkpoint_reaches_next_actual_experiment( - tmp_path, monkeypatch, provider, strategy, handoff_mode, preexisting_feedback, + tmp_path, monkeypatch, provider, handoff_mode, preexisting_feedback, ): isolate_sqlite_runtime(tmp_path, monkeypatch) project, runtime, registry = fixture._write_fixture(tmp_path) @@ -63,7 +63,7 @@ def read_stage(command): return json.loads(result.stdout) cli("configure-goal", "--goal-id", fixture.GOAL_ID, "--execution-replan-after-turns", "1", - "--execution-stride-strategy", strategy, "--explore-graph-enabled", "--execute") + "--explore-graph-enabled", "--execute") if handoff_mode == "hard_lease": claimed = cli("todo", "claim", *binding, "--todo-id", fixture.TODO_ID, "--claimed-by", fixture.AGENT_ID, "--claim-operation-id", "route-original-execution") @@ -207,22 +207,19 @@ def read_stage(command): "observed_reality": "The scoped validation retains a cost-two route; one allowed direct route remains untested.", "retained": ["Original objective and feasible incumbent."], "changed": ["Compare the allowed direct route on the same graph."], "evidence_refs": [evidence]}} - if strategy == "off": - assert control is None - else: - assert control - explore = read_stage(reviewed["capabilities"]["explore"]["read_action"])["explore_basis"] - finding = next(row for row in explore["finding_refs"] - if row.get("execution_observation", {}).get("candidate_sha256") == observed["candidate_sha256"]) - decision = control["minimal_example"] - decision.update(action="switch", next_probe={"scope": "Compare the permitted direct route.", - "prediction": "The independently checked route cost falls from two to one.", - "adoption_criterion": "Same graph, valid endpoints and a lower actual route cost.", - "cost_bound": "One local process and existing settlement; no new evaluation authority.", - "minimum_evidence": "Exact route bytes and evaluator output."}) - decision["explore_review"] = {"revision": explore["revision"], "disposition": "used", - "considered_refs": [finding["finding_id"]], "reason": "The measured feasible candidate leaves the direct edge untested."} - packet["stride_decision"] = decision + assert control + explore = read_stage(reviewed["capabilities"]["explore"]["read_action"])["explore_basis"] + finding = next(row for row in explore["finding_refs"] + if row.get("execution_observation", {}).get("candidate_sha256") == observed["candidate_sha256"]) + decision = control["minimal_example"] + decision.update(action="switch", next_probe={"scope": "Compare the permitted direct route.", + "prediction": "The independently checked route cost falls from two to one.", + "adoption_criterion": "Same graph, valid endpoints and a lower actual route cost.", + "cost_bound": "One local process and existing settlement; no new evaluation authority.", + "minimum_evidence": "Exact route bytes and evaluator output."}) + decision["explore_review"] = {"revision": explore["revision"], "disposition": "used", + "considered_refs": [finding["finding_id"]], "reason": "The measured feasible candidate leaves the direct edge untested."} + packet["stride_decision"] = decision vision.write_text(json.dumps(packet)) acknowledged = execute(review_plan["ordered_steps"][1]["command_template"] + " --agent-vision-json " + shlex.quote(str(vision)) + " --no-global-sync --suppress-external-sinks", diff --git a/tests/control_plane/test_outcome_replan_composition_cli.py b/tests/control_plane/test_outcome_replan_composition_cli.py index e38b4b9c04..54b76fab86 100644 --- a/tests/control_plane/test_outcome_replan_composition_cli.py +++ b/tests/control_plane/test_outcome_replan_composition_cli.py @@ -96,9 +96,8 @@ def _review_packet(control: dict | None) -> dict: @pytest.mark.parametrize("provider", ["file", "sqlite"]) -@pytest.mark.parametrize("stride", [False, True]) def test_batched_review_previews_post_refinement_basis_and_recovers_once( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, stride: bool, + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, ) -> None: if provider == "sqlite": isolate_sqlite_runtime(tmp_path, monkeypatch) @@ -117,8 +116,7 @@ def call(*args: str, expected_code: int = 0) -> dict: def inspect() -> dict: return call("goal-acceptance", "inspect", "--goal-id", GOAL_ID) - call("configure-goal", "--goal-id", GOAL_ID, "--execution-replan-after-turns", "1", - *(["--execution-stride-strategy", "evidence_conditioned_v1"] if stride else []), "--execute") + call("configure-goal", "--goal-id", GOAL_ID, "--execution-replan-after-turns", "1", "--execute") original = {"outcome_id": "export", "owner_agent_id": AGENT_ID, "objective": "Deliver a recoverable export", "todo_ids": [TODO_ID], "requirements": [{"id": "content", "description": "Preserve the original content"}], @@ -141,7 +139,7 @@ def inspect() -> dict: "--agent-id", AGENT_ID, "--turn-instance-id", TURN_ID) assert "periodic_review_due" in {row["kind"] for row in due["autonomous_replan_obligation"]["triggers"]} bound = _bind_selected_replan_guard(registry, runtime, project, TURN_ID, todo_id=TODO_ID) - control = bound["replan_action_packet"].get("stride_control") if stride else None + control = bound["replan_action_packet"]["stride_control"] packet = _review_packet(control) decision = tmp_path / "decision.json" decision.write_text(json.dumps(packet)) @@ -158,39 +156,37 @@ def inspect() -> dict: batch = (*refresh, "--goal-outcome-update-json", str(update)) index = runtime / "goals" / GOAL_ID / "runs" / "index.jsonl" original_index = index.read_bytes() - preview = call(*batch, "--dry-run", expected_code=1 if stride else 0) + preview = call(*batch, "--dry-run", expected_code=1) assert preview["goal_outcome_update"]["status"] == "planned" - if stride: - assert preview["replan_transition"]["reason_code"] == "stride_review_basis_mismatch" + assert preview["replan_transition"]["reason_code"] == "stride_review_basis_mismatch" assert inspect() == before and index.read_bytes() == original_index assert _spend_run_count(runtime) == 1 # Execution keeps its sequential, non-atomic contract. A rejected review # must retain the independently committed refinement receipt. - actual = call(*batch, expected_code=1 if stride else 0) + actual = call(*batch, expected_code=1) assert actual["goal_outcome_update"]["status"] == "applied" after = inspect() assert after["goal_acceptance_contract"]["outcome_requirements"]["revision"] == 2 - if stride: - assert actual["appended"] is False - assert actual["replan_transition"]["reason_code"] == "stride_review_basis_mismatch" - assert index.read_bytes() == original_index - fresh = call("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, - "--agent-id", AGENT_ID, "--todo-id", TODO_ID, "--turn-instance-id", TURN_ID) - assert fresh["heartbeat_receipt"]["settlement_identity"] == bound["heartbeat_receipt"]["settlement_identity"] - current = fresh["replan_action_packet"]["stride_control"] - assert current["reference_context_id"] != control["reference_context_id"] - # Read the current facts before authoring against this new basis. Merely - # replaying the stale packet still cannot settle the review. - context = fresh["interaction_contract"]["agent_channel"]["work_context"] - acceptance = next(row["content"] for row in context["sources"] if row.get("source") == "goal_acceptance") - assert acceptance["goal_acceptance_contract"] == after["goal_acceptance_contract"] - replay = call(*batch, expected_code=1) - assert replay["goal_outcome_update"]["status"] == "replayed" - assert inspect() == after and index.read_bytes() == original_index - decision.write_text(json.dumps(_review_packet(current))) - actual = call(*refresh) - assert "goal_outcome_update" not in actual + assert actual["appended"] is False + assert actual["replan_transition"]["reason_code"] == "stride_review_basis_mismatch" + assert index.read_bytes() == original_index + fresh = call("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, + "--agent-id", AGENT_ID, "--todo-id", TODO_ID, "--turn-instance-id", TURN_ID) + assert fresh["heartbeat_receipt"]["settlement_identity"] == bound["heartbeat_receipt"]["settlement_identity"] + current = fresh["replan_action_packet"]["stride_control"] + assert current["reference_context_id"] != control["reference_context_id"] + # Read the current facts before authoring against this new basis. Merely + # replaying the stale packet still cannot settle the review. + context = fresh["interaction_contract"]["agent_channel"]["work_context"] + acceptance = next(row["content"] for row in context["sources"] if row.get("source") == "goal_acceptance") + assert acceptance["goal_acceptance_contract"] == after["goal_acceptance_contract"] + replay = call(*batch, expected_code=1) + assert replay["goal_outcome_update"]["status"] == "replayed" + assert inspect() == after and index.read_bytes() == original_index + decision.write_text(json.dumps(_review_packet(current))) + actual = call(*refresh) + assert "goal_outcome_update" not in actual assert actual["autonomous_replan_ack"]["semantic_delta"]["accepted"] is True spent = call(*_projected_cli_args(actual["settlement_owed"]["command"], turn_instance_id=TURN_ID)) assert spent["ok"] and _spend_run_count(runtime) == 2 diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index c8d0668982..871778c457 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -600,8 +600,6 @@ def _configure_autonomous_replan_fixture( project: Path, runtime: Path, registry_path: Path, - *, - stride_strategy: str | None = None, ) -> None: state_path = project / f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md" state_path.write_text( @@ -626,8 +624,6 @@ def _configure_autonomous_replan_fixture( ) registry = json.loads(registry_path.read_text(encoding="utf-8")) registry["goals"][0]["status"] = "active" - if stride_strategy is not None: - registry["goals"][0].setdefault("execution_profile", {})["stride_strategy"] = stride_strategy registry_path.write_text( json.dumps(registry, indent=2, sort_keys=True) + "\n", encoding="utf-8", @@ -671,11 +667,41 @@ def _configure_autonomous_replan_fixture( ) +def _write_dead_monitor_replan_runs(runtime: Path) -> None: + runs_dir = runtime / "goals" / GOAL_ID / "runs" + runs_dir.mkdir(parents=True, exist_ok=True) + monitor_runs = [] + for offset in range(6): + row = { + "generated_at": f"2026-01-01T02:{offset:02d}:00+00:00", + "goal_id": GOAL_ID, + "agent_id": AGENT_ID, + "classification": "quota_monitor_poll", + "delivery_outcome": "surface_only", + "todo_id": "todo_replan_monitor", + "target_key": "replan-settlement-fixture", + "monitor_target": { + "schema_version": "quota_monitor_target_v0", + "target_id": "replan-settlement-fixture", + "monitor_mode": "due_monitor_observed_without_material_transition", + "effective_action": "normal_run", + "agent_id": AGENT_ID, + }, + } + jpath = runs_dir / f"monitor-{offset}.json" + mpath = runs_dir / f"monitor-{offset}.md" + jpath.write_text(json.dumps(row) + "\n", encoding="utf-8") + mpath.write_text("# Monitor fixture\n", encoding="utf-8") + monitor_runs.append({**row, "json_path": str(jpath), "markdown_path": str(mpath)}) + (runs_dir / "index.jsonl").write_text( + "".join(json.dumps(row) + "\n" for row in monitor_runs), + encoding="utf-8", + ) + + def _configure_selected_todo_replan_fixture( project: Path, registry_path: Path, - *, - stride_strategy: str | None = None, ) -> None: state_path = project / f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md" todo_rows = "\n".join( @@ -706,8 +732,6 @@ def _configure_selected_todo_replan_fixture( ) registry = json.loads(registry_path.read_text(encoding="utf-8")) registry["goals"][0]["status"] = "active" - if stride_strategy is not None: - registry["goals"][0].setdefault("execution_profile", {})["stride_strategy"] = stride_strategy registry_path.write_text( json.dumps(registry, indent=2, sort_keys=True) + "\n", encoding="utf-8", @@ -810,7 +834,7 @@ def test_same_explicit_todo_retry_preserves_original_identity( """Retrying the retained planning choice reuses the admitted replan.""" project, runtime, registry = _write_fixture(tmp_path) - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) _initialize_git_checkout(project) _initialize_fixture_authority(project, runtime, provider=provider) turn = "turn-same-explicit-todo-replan-retry" @@ -2641,12 +2665,6 @@ def test_same_todo_writeback_reentry_only_settles_original_turn( _initialize_git_checkout(project) todo_id = SELECTED_REPLAN_TODO_ID _initialize_fixture_authority(project, runtime, provider=provider) - if writeback_kind == "replan": - # This replay fixture supplies the ordinary typed replan delta. Keep - # its strategy explicit; Stride decision followthrough is tested separately. - rc, configured = _run_cli(registry, runtime, "configure-goal", "--goal-id", GOAL_ID, - "--execution-stride-strategy", "off", "--execute") - assert rc == 0, configured turn_id = "turn-same-todo-writeback" host_args = ("--codex-app",) if host == "codex_app" else ("--runtime-profile", "generic_cli") guard_args = ( @@ -2669,7 +2687,7 @@ def test_same_todo_writeback_reentry_only_settles_original_turn( assert guard["interaction_contract"]["agent_channel"]["delivery_allowed"] is True identity = ("--agent-id", AGENT_ID, "--todo-id", todo_id, "--turn-instance-id", turn_id) vision = project / "vision.json" - vision.write_text(json.dumps({ + vision_payload: dict[str, Any] = { "schema_version": "goal_vision_replan_contract_v0", "state": "vision_patch_proposed", "vision_patch": {"acceptance_summary": "Verified fixture artifact; original work remains open."}, @@ -2681,7 +2699,10 @@ def test_same_todo_writeback_reentry_only_settles_original_turn( "retained": ["Original requirements and the existing Todo."], "evidence_refs": ["evidence:fixture-check"], }, - }), encoding="utf-8") + } + if writeback_kind == "replan": + vision_payload["stride_decision"] = guard["replan_action_packet"]["stride_control"]["minimal_example"] + vision.write_text(json.dumps(vision_payload), encoding="utf-8") refresh_args = ( "refresh-state", "--goal-id", GOAL_ID, *identity, "--classification", "verified_fixture_work", "--delivery-batch-scale", "single_surface", @@ -6966,11 +6987,10 @@ def test_todoless_autonomous_replan_settles_quota_refresh_spend_chain( ) -> None: project, runtime, registry_path = _write_fixture(tmp_path) _configure_autonomous_replan_fixture(project, runtime, registry_path) - # This case owns ordinary settlement/recovery, independently of Stride. - # Enabled decision adoption has separate real native coverage. - rc, configured = _run_cli(registry_path, runtime, "configure-goal", "--goal-id", GOAL_ID, - "--execution-stride-strategy", "off", "--execute") - assert rc == 0, configured + if not write_vision: + # Use dead_monitor_repeat (non-stride trigger) so the missing-vision + # branch still verifies vision_checkpoint_missing after settlement. + _write_dead_monitor_replan_runs(runtime) registry = json.loads(registry_path.read_text(encoding="utf-8")) registry["goals"][0]["control_plane"] = { "periodic_report": { @@ -7061,8 +7081,22 @@ def test_todoless_autonomous_replan_settles_quota_refresh_spend_chain( "retained": ["The existing monitor and its due date."], "evidence_refs": ["evidence-new"], }, + "stride_decision": guard["replan_action_packet"]["stride_control"]["minimal_example"], }), encoding="utf-8") - refresh_command += f" --agent-vision-json {shlex.quote(str(vision_path))}" + if "" in refresh_command: + refresh_command = refresh_command.replace( + "", + shlex.quote(str(vision_path)), + ) + refresh_command += ( + " --progress-result-class advanced" + " --progress-surface-id surface-new" + " --progress-hypothesis-id hypothesis-new" + " --progress-probe-kind probe-new" + " --progress-evidence-id evidence-new" + ) + else: + refresh_command += f" --agent-vision-json {shlex.quote(str(vision_path))}" refresh_rc, refresh = _run_cli( registry_path, runtime, @@ -7212,11 +7246,6 @@ def test_blocked_replan_keeps_material_checkpoint_in_native_readback(tmp_path, m isolate_sqlite_runtime(tmp_path, monkeypatch) project, runtime, registry_path = _write_fixture(tmp_path) _configure_autonomous_replan_fixture(project, runtime, registry_path) - # This case owns ordinary settlement/recovery, independently of Stride. - # Enabled decision adoption has separate real native coverage. - rc, configured = _run_cli(registry_path, runtime, "configure-goal", "--goal-id", GOAL_ID, - "--execution-stride-strategy", "off", "--execute") - assert rc == 0, configured _initialize_fixture_authority(project, runtime, provider=provider) stamp = "2026-01-01T00:00:00+00:00" prior = { @@ -7249,9 +7278,11 @@ def test_blocked_replan_keeps_material_checkpoint_in_native_readback(tmp_path, m "schema_version": "goal_vision_replan_contract_v0", "state": "vision_patch_proposed", "vision_patch": {"vision_summary": "Continue after the source is available.", "acceptance_summary": "The source is still unavailable; the outcome remains open."}, - "path_delta": {"outcome": "wait", "prior_assumption": "The source may be available.", + "path_delta": {"outcome": "stop", "prior_assumption": "The source may be available.", "observed_reality": "An independent read confirmed the source is unavailable.", - "retained": ["Keep the outcome open."], "evidence_refs": ["evidence:source-unavailable"]}, + "stopped": ["Stop probing until the source is available."], + "evidence_refs": ["evidence:source-unavailable"]}, + "stride_decision": guard["replan_action_packet"]["stride_control"]["minimal_example"], })) rc, closed = _run_cli( registry_path, runtime, "refresh-state", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, @@ -7293,11 +7324,9 @@ def test_todoless_blocked_replan_settles_read_only_external_evidence_without_wor ) -> None: project, runtime, registry_path = _write_fixture(tmp_path) _configure_autonomous_replan_fixture(project, runtime, registry_path) - # This case owns ordinary settlement/recovery, independently of Stride. - # Enabled decision adoption has separate real native coverage. - rc, configured = _run_cli(registry_path, runtime, "configure-goal", "--goal-id", GOAL_ID, - "--execution-stride-strategy", "off", "--execute") - assert rc == 0, configured + # Use a non-stride Todo-less obligation so this blocked writeback without + # agent_vision proceeds to the explicit spend-slot workspace-guard check. + _write_dead_monitor_replan_runs(runtime) _initialize_git_checkout(project) registry = json.loads(registry_path.read_text(encoding="utf-8")) registry["goals"][0]["coordination"]["registered_agents"].append( @@ -7563,7 +7592,7 @@ def test_autonomous_replan_semantic_delta_keeps_accountable_receipt_chain( isolate_sqlite_runtime(tmp_path, monkeypatch) project, runtime, registry_path = _write_fixture(tmp_path) - _configure_selected_todo_replan_fixture(project, registry_path, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry_path) _initialize_git_checkout(project) turn_instance_id = "turn-autonomous-replan-semantic-1" @@ -7958,10 +7987,9 @@ def test_runtime_capability_reentry_preserves_receipt_bound_autonomous_replan( @pytest.mark.parametrize("provider", ["file", "sqlite"]) -@pytest.mark.parametrize("stride", [False, True]) @pytest.mark.parametrize("vision_gap", [False, True]) def test_replan_reentry_after_outcome_work_refinement_keeps_original_turn( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, stride: bool, vision_gap: bool, + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, vision_gap: bool, ) -> None: """Refreshing cumulative requirements must not rebind an admitted review.""" if provider == "sqlite": @@ -7990,9 +8018,6 @@ def refine(document: dict[str, Any], operation: str) -> dict[str, Any]: "--agent-id", AGENT_ID, "--document", str(path), "--operation-id", operation, "--expected-provider-revision", current["provider_revision"], "--execute") - if stride: - call("configure-goal", "--goal-id", GOAL_ID, - "--execution-stride-strategy", "evidence_conditioned_v1", "--execute") refine({"outcome_id": "delivery", "owner_agent_id": AGENT_ID, "objective": "Deliver the requested artifact", "requirements": [{"id": "original", "description": "Retain the original evidence"}], @@ -9413,7 +9438,7 @@ def test_exact_later_ack_executes_original_todo_settlement_commands( tmp_path: Path, provider: str, legacy_turn_ref: bool, ) -> None: project, runtime, registry = _write_fixture(tmp_path) - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) _initialize_git_checkout(project) _initialize_fixture_authority(project, runtime, provider=provider) original_turn = "turn-historical-todo-settlement" @@ -9491,7 +9516,7 @@ def test_same_second_historical_ack_requires_writeback_after_admission( tmp_path: Path, provider: str, order: str, ) -> None: project, runtime, registry = _write_fixture(tmp_path) - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) _initialize_git_checkout(project) _initialize_fixture_authority(project, runtime, provider=provider) original_turn = "turn-historical-same-second" @@ -9515,6 +9540,7 @@ def test_same_second_historical_ack_requires_writeback_after_admission( "retained": ["Original requirements and the existing Todo."], "evidence_refs": ["evidence:fixture-check"], }, + "stride_decision": later_admitted["replan_action_packet"]["stride_control"]["minimal_example"], }), encoding="utf-8") rc, refreshed = _run_cli( registry, runtime, "refresh-state", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, @@ -9614,7 +9640,7 @@ def test_retired_instance_writeback_cannot_drop_same_second_historical_ack( acceptance depends on the alias owner's own refresh following admission. """ project, runtime, registry = _write_fixture(tmp_path) - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) _initialize_git_checkout(project) _initialize_fixture_authority(project, runtime, provider="file") original_turn = "turn-historical-same-second" @@ -9638,6 +9664,7 @@ def test_retired_instance_writeback_cannot_drop_same_second_historical_ack( "retained": ["Original requirements and the existing Todo."], "evidence_refs": ["evidence:fixture-check"], }, + "stride_decision": later_admitted["replan_action_packet"]["stride_control"]["minimal_example"], }), encoding="utf-8") rc, refreshed = _run_cli( registry, runtime, "refresh-state", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, @@ -9721,7 +9748,7 @@ def test_only_retired_instance_ack_keeps_the_original_replan( instance's later confirmation. """ project, runtime, registry = _write_fixture(tmp_path) - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) _initialize_git_checkout(project) _initialize_fixture_authority(project, runtime, provider=provider) original_turn = "turn-retired-ack-only" @@ -9778,6 +9805,7 @@ def test_only_retired_instance_ack_keeps_the_original_replan( "retained": ["Original requirements and the existing Todo."], "evidence_refs": ["evidence:fixture-check"], }, + "stride_decision": admitted["replan_action_packet"]["stride_control"]["minimal_example"], }), encoding="utf-8") refresh_rc, refreshed = _run_cli( registry, runtime, "refresh-state", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, @@ -9924,7 +9952,7 @@ def test_same_turn_receipt_upgrade_keeps_historical_ack_admission( """ project, runtime, registry = _write_fixture(tmp_path) - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) _initialize_git_checkout(project) _initialize_fixture_authority(project, runtime, provider=provider) original_turn = "turn-historical-ack-after-upgrade" diff --git a/tests/control_plane/test_receipt_next_action_cli.py b/tests/control_plane/test_receipt_next_action_cli.py index 892ccf81fd..4646b72985 100644 --- a/tests/control_plane/test_receipt_next_action_cli.py +++ b/tests/control_plane/test_receipt_next_action_cli.py @@ -230,7 +230,7 @@ def test_todoless_replan_refuses_step_and_recovers_original_settlement( ) -> None: isolate_sqlite_runtime(tmp_path, monkeypatch) project, runtime, registry = fixture._write_fixture(tmp_path) - fixture._configure_autonomous_replan_fixture(project, runtime, registry, stride_strategy="off") + fixture._configure_autonomous_replan_fixture(project, runtime, registry) state = project / f".codex/goals/{fixture.GOAL_ID}/ACTIVE_GOAL_STATE.md" def run(*args: str) -> tuple[int, dict]: @@ -262,7 +262,8 @@ def run(*args: str) -> tuple[int, dict]: "prior_assumption": "The monitor might need another early observation.", "observed_reality": "Independent evidence retains its future observation window.", "retained": ["Original monitor identity, state and deadline."], - "evidence_refs": ["evidence:replan-recommendation"]}}), encoding="utf-8") + "evidence_refs": ["evidence:replan-recommendation"]}, + "stride_decision": guard["replan_action_packet"]["stride_control"]["minimal_example"]}), encoding="utf-8") refresh = ("refresh-state", "--goal-id", fixture.GOAL_ID, "--agent-id", fixture.AGENT_ID, "--replan-obligation-id", identity["replan_obligation_id"], "--turn-instance-id", turn, "--classification", "bounded_replan_progress", "--delivery-batch-scale", "single_surface", diff --git a/tests/control_plane/test_refresh_state_replan_gate.py b/tests/control_plane/test_refresh_state_replan_gate.py index 23d7c772cc..f0420a63e1 100644 --- a/tests/control_plane/test_refresh_state_replan_gate.py +++ b/tests/control_plane/test_refresh_state_replan_gate.py @@ -138,9 +138,65 @@ def _current_obligation_id( return str(obligation["obligation_id"]) +def _stride_decision_for_obligation(obligation: dict) -> dict: + from loopx.control_plane.work_items.progress_observation import ( + build_replan_action_packet, + ) + + packet = build_replan_action_packet(obligation, goal_id=GOAL_ID, agent_id=AGENT_ID) + return dict(packet["stride_control"]["minimal_example"]) + + +def _stride_vision_for( + runs: list[dict], + *, + state_text: str = STATE_TEXT, + outcome: str = "stop", + acceptance_summary: str = "Review the open obligation against current evidence.", + evidence_ref: str = "evidence:stride-review", + registry_goal: dict | None = None, +) -> dict: + obligation, _ = qualify_replan_writeback( + newest_first_runs=runs, + state_text=state_text, + agent_id=AGENT_ID, + goal_id=GOAL_ID, + registry_goal=registry_goal, + ) + assert obligation is not None + path_delta: dict = { + "schema_version": "goal_path_delta_v0", + "outcome": outcome, + "prior_assumption": "Prior slices were still advancing.", + "observed_reality": "Review trigger fired under current evidence.", + "evidence_refs": [evidence_ref], + } + if outcome == "stop": + path_delta["stopped"] = ["Stop repeating the prior unchanged route."] + elif outcome == "continue": + path_delta["retained"] = ["Retain the current evidence-backed route."] + return { + "schema_version": "goal_vision_replan_contract_v0", + "agent_id": AGENT_ID, + "state": "active", + "vision_patch": {"acceptance_summary": acceptance_summary}, + "path_delta": path_delta, + "stride_decision": _stride_decision_for_obligation(obligation), + } + + def test_maintenance_writeback_rejected_when_replan_due() -> None: + runs = _durable_runs(AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD) + with pytest.raises(ValueError, match="stride_decision"): + _call_gate(runs=runs) with pytest.raises(ValueError) as exc: - _call_gate(runs=_durable_runs(AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD)) + enforce_open_replan_writeback( + newest_first_runs=runs, + state_text=STATE_TEXT, + agent_id=AGENT_ID, + goal_id=GOAL_ID, + agent_vision=_stride_vision_for(runs), + ) message = str(exc.value) assert "autonomous replan obligation" in message assert "typed semantic delta" in message @@ -148,13 +204,13 @@ def test_maintenance_writeback_rejected_when_replan_due() -> None: def test_typed_surface_delta_satisfies_periodic_obligation() -> None: + runs = _durable_runs(AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD) semantic_delta = enforce_open_replan_writeback( - newest_first_runs=_durable_runs( - AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD - ), + newest_first_runs=runs, state_text=STATE_TEXT, agent_id=AGENT_ID, goal_id=GOAL_ID, + agent_vision=_stride_vision_for(runs), progress_observation={ "schema_version": "typed_progress_observation_v0", "work_item_id": "todo-replan-slice", @@ -246,17 +302,26 @@ def _typed_repeat_runs() -> list[dict]: def test_repair_delta_claim_alone_cannot_close_typed_repeat_obligation() -> None: runs = _typed_repeat_runs() + stop_vision = _stride_vision_for(runs) # Semantic-gate level: a writeback whose progress observation does not # carry a NEW typed semantic delta relative to the obligation baseline is # rejected. This pins enforce_open_replan_writeback; the full # repair-delta command path (blocker todo + --repair-delta-kind blocker) # is covered by the refresh_state_run regressions below. + with pytest.raises(ValueError, match="stride_decision"): + enforce_open_replan_writeback( + newest_first_runs=runs, + state_text=STATE_TEXT, + agent_id=AGENT_ID, + goal_id=GOAL_ID, + ) with pytest.raises(ValueError) as exc: enforce_open_replan_writeback( newest_first_runs=runs, state_text=STATE_TEXT, agent_id=AGENT_ID, goal_id=GOAL_ID, + agent_vision=stop_vision, ) message = str(exc.value) assert "autonomous replan obligation" in message @@ -268,6 +333,7 @@ def test_repair_delta_claim_alone_cannot_close_typed_repeat_obligation() -> None state_text=STATE_TEXT, agent_id=AGENT_ID, goal_id=GOAL_ID, + agent_vision=stop_vision, progress_observation={ "schema_version": "typed_progress_observation_v0", "result_class": "blocked", @@ -287,6 +353,7 @@ def test_atomic_new_blocker_delta_closes_typed_repeat_obligation() -> None: state_text=STATE_TEXT, agent_id=AGENT_ID, goal_id=GOAL_ID, + agent_vision=_stride_vision_for(runs), progress_observation={ "schema_version": "typed_progress_observation_v0", "result_class": "blocked", @@ -323,6 +390,7 @@ def _call_refresh_state_run( runtime_root: Path, project: Path, progress_observation: dict | None = None, + agent_vision_packet: dict | None = None, ) -> dict: return refresh_state_run( registry_path=registry_path, @@ -338,11 +406,42 @@ def _call_refresh_state_run( autonomous_replan_recorded=True, repair_delta_kinds=["blocker"], progress_observation=progress_observation, + agent_vision_packet=agent_vision_packet, dry_run=False, sync_global=False, ) +def _replan_gate_stop_vision(registry_path: Path, runtime_root: Path) -> dict: + from loopx.quota import build_quota_should_run + from loopx.status import collect_status + + status_payload = collect_status( + registry_path=registry_path, + runtime_root_override=str(runtime_root), + goal_id=GOAL_ID, + limit=20, + ) + guard = build_quota_should_run(status_payload, goal_id=GOAL_ID, agent_id=AGENT_ID) + return { + "schema_version": "goal_vision_replan_contract_v0", + "agent_id": AGENT_ID, + "state": "active", + "vision_patch": {"acceptance_summary": "Review the blocked external gate."}, + "path_delta": { + "schema_version": "goal_path_delta_v0", + "outcome": "stop", + "prior_assumption": "Prior blocker remained active.", + "observed_reality": "Reviewing typed blocker delta against baseline.", + "stopped": ["Stop repeating the prior blocker claim."], + "evidence_refs": ["evidence-external-review"], + }, + "stride_decision": dict( + guard["replan_action_packet"]["stride_control"]["minimal_example"] + ), + } + + def _replan_gate_tmp_fixture( tmp_path: Path, ) -> tuple[Path, Path, Path, Path]: @@ -360,7 +459,6 @@ def _replan_gate_tmp_fixture( "status": "active", "repo": str(project), "state_file": str(state.relative_to(project)), - "execution_profile": {"stride_strategy": "off"}, "coordination": { "agent_model": "peer_v1", "registered_agents": [AGENT_ID], @@ -395,6 +493,7 @@ def test_refresh_state_run_repair_delta_alone_rejected_without_new_typed_delta( registry_path=registry_path, runtime_root=runtime_root, project=project, + agent_vision_packet=_replan_gate_stop_vision(registry_path, runtime_root), ) assert runs_index.read_text().splitlines() == before @@ -409,6 +508,7 @@ def test_refresh_state_run_atomic_blocker_delta_persists_repair_and_semantic_evi registry_path=registry_path, runtime_root=runtime_root, project=project, + agent_vision_packet=_replan_gate_stop_vision(registry_path, runtime_root), progress_observation={ "schema_version": "typed_progress_observation_v0", "result_class": "blocked", @@ -425,7 +525,7 @@ def test_refresh_state_run_atomic_blocker_delta_persists_repair_and_semantic_evi persisted = json.loads(json_path.read_text(encoding="utf-8")) ack = persisted.get("autonomous_replan_ack") or {} assert ack.get("recorded") is True - assert (ack.get("delta_contract") or {}).get("delta_kinds") == ["blocker"] + assert "blocker" in (ack.get("delta_contract") or {}).get("delta_kinds", []) semantic_delta = ack.get("semantic_delta") or {} assert semantic_delta.get("accepted") is True assert semantic_delta.get("satisfying_outcomes") == ["new_concrete_blocker"] @@ -494,7 +594,7 @@ def test_legacy_material_run_cadence_rejects_maintenance_writeback(tmp_path: Pat sync_global=False, ) message = str(exc.value) - assert "typed semantic delta" in message + assert "stride_decision" in message def _prior_periodic_ack() -> dict: @@ -715,6 +815,7 @@ def test_admitted_vision_checkpoint_survives_a_new_periodic_review() -> None: agent_vision={ "vision_patch": {"acceptance_summary": "An independent check supports continuing."}, "path_delta": {"outcome": "continue", "evidence_refs": ["evidence:checkpoint-review"]}, + "stride_decision": _stride_decision_for_obligation(admitted), }, ) assert delta is not None @@ -909,9 +1010,18 @@ def test_completed_or_wrong_obligation_successor_cannot_close_rotated_duty() -> def test_rotated_vision_obligation_accepts_fresh_evidence_linked_path() -> None: + runs = _rotated_vision_runs() + state_text = _completed_advancement_chain_state() + obligation, _ = qualify_replan_writeback( + newest_first_runs=runs, + state_text=state_text, + agent_id=AGENT_ID, + goal_id=GOAL_ID, + ) + assert obligation is not None semantic_delta = enforce_open_replan_writeback( - newest_first_runs=_rotated_vision_runs(), - state_text=_completed_advancement_chain_state(), + newest_first_runs=runs, + state_text=state_text, agent_id=AGENT_ID, goal_id=GOAL_ID, agent_vision={ @@ -922,6 +1032,7 @@ def test_rotated_vision_obligation_accepts_fresh_evidence_linked_path() -> None: "outcome": "replan", "evidence_refs": ["evidence:current-outcome"], }, + "stride_decision": _stride_decision_for_obligation(obligation), }, ) assert semantic_delta is not None diff --git a/tests/control_plane/test_replan_context_evidence.py b/tests/control_plane/test_replan_context_evidence.py index 970940fceb..4ea36c8a60 100644 --- a/tests/control_plane/test_replan_context_evidence.py +++ b/tests/control_plane/test_replan_context_evidence.py @@ -92,13 +92,12 @@ def test_projection_rejects_invalid_typed_records_and_preserves_scoped_prose(): @pytest.mark.parametrize("source", ["active_state", "registry"]) -@pytest.mark.parametrize("stride_strategy", ["off", "evidence_conditioned_v1"]) @pytest.mark.parametrize("objective", [ "Read /home/runner/work/task.md and meet its acceptance criteria.", "Optimize the accepted result. Write test inputs to /tmp/task-seeds.txt.", ]) def test_goal_and_evidence_paths_survive_scoped_replan( - tmp_path: Path, source: str, stride_strategy: str, objective: str, + tmp_path: Path, source: str, objective: str, ) -> None: project, runtime = tmp_path / "project", tmp_path / "runtime" project.mkdir() @@ -119,7 +118,6 @@ def test_goal_and_evidence_paths_survive_scoped_replan( goal_id="evidence-goal", agent_id="agent-a", runs=(), source_status={"registry": str(registry), "runtime_root": str(runtime), "run_history": {"runs": []}}, - stride_strategy=stride_strategy, ) assert context["core_goal"]["objective"] == objective assert context["core_goal"]["objective_source"] == source @@ -285,14 +283,28 @@ def test_truncated_display_cannot_make_an_old_blocker_new(count): "schema_version": "typed_progress_observation_v0", "result_class": "blocked", "blocker_id": f"blocker-{i}", "evidence_ids": [f"proof-{i}"], }) for i in range(count)] - obligation = {"obligation_id": "replan-a", "triggers": [{"kind": "typed_progress_repeat"}], + obligation = {"obligation_id": "replan-aaaaaaaaaaaaaaaa", "triggers": [{"kind": "typed_progress_repeat"}], "progress_baseline": rows[-1]["progress_observation"]} obligation["replan_context"] = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=rows, obligation=obligation) assert obligation["replan_context"]["coverage_truncated"] is True assert not any(row.get("blocker_id") == "blocker-0" for row in obligation["replan_context"]["coverage_ledger"]) + from loopx.control_plane.work_items.progress_observation import build_replan_action_packet + + packet = build_replan_action_packet(obligation, goal_id="evidence-goal", agent_id="agent-a") + stop_vision = { + "vision_patch": {"acceptance_summary": "Stop repeating already-recorded blockers."}, + "path_delta": {"outcome": "stop", "evidence_refs": ["proof-0"]}, + "stride_decision": packet["stride_control"]["minimal_example"], + } with pytest.raises(ValueError, match="complete evidence history"): - semantic_delta_from_writeback(obligation=obligation, progress_observation=rows[0]["progress_observation"]) - result = semantic_delta_from_writeback(obligation=obligation, progress_observation=rows[0]["progress_observation"], history_runs=rows) + semantic_delta_from_writeback( + obligation=obligation, progress_observation=rows[0]["progress_observation"], + agent_vision=stop_vision, + ) + result = semantic_delta_from_writeback( + obligation=obligation, progress_observation=rows[0]["progress_observation"], + agent_vision=stop_vision, history_runs=rows, + ) assert result["accepted"] is False assert result["reason_code"] == "progress_observation_replayed" diff --git a/tests/control_plane/test_replan_context_order.py b/tests/control_plane/test_replan_context_order.py index 22a7873b9f..61deececf4 100644 --- a/tests/control_plane/test_replan_context_order.py +++ b/tests/control_plane/test_replan_context_order.py @@ -48,13 +48,13 @@ def test_compact_status_newest_first_returns_latest_decision_and_later_work(shap rows = list(reversed(_rows())) history = {"runs": rows} if shape == "runs" else {"goals": [{"id": "evidence-goal", "latest_runs": rows}]} context = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=(), - source_status={"run_history": history}, stride_strategy="evidence_conditioned_v1") + source_status={"run_history": history}) assert _assert_followthrough(context)["source_history_complete"] is False def test_named_newest_first_builder_preserves_order_without_a_status_source(): context = build_replan_context({"obligation_id": "replan-fixture"}, goal_id="evidence-goal", - agent_id="agent-a", newest_first_runs=reversed(_rows()), stride_strategy="evidence_conditioned_v1") + agent_id="agent-a", newest_first_runs=reversed(_rows())) _assert_followthrough(context) @@ -74,16 +74,15 @@ def result(todo, index): return item rows = [decision, result("todo-comparison", 0), *[result("todo-busy", i + 1) for i in range(12)]] - for strategy in ("off", "evidence_conditioned_v1"): - context = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=rows, - history_newest_first=False, stride_strategy=strategy) - follow = context["decision_followthrough"] - observed = follow["observations"] if typed else follow["ordinary_work"]["evidence"] - assert len(observed) == 6 - assert {row["todo_id"] for row in observed} == {"todo-busy", "todo-comparison"} - planned = next(work for work in follow["planned_work"] if work["todo_id"] == "todo-comparison") - assert len(planned["observation_refs"] if typed else planned["ordinary_evidence_refs"]) == 1 - assert follow["execution_and_goal_gain"] == "unknown" + context = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=rows, + history_newest_first=False) + follow = context["decision_followthrough"] + observed = follow["observations"] if typed else follow["ordinary_work"]["evidence"] + assert len(observed) == 6 + assert {row["todo_id"] for row in observed} == {"todo-busy", "todo-comparison"} + planned = next(work for work in follow["planned_work"] if work["todo_id"] == "todo-comparison") + assert len(planned["observation_refs"] if typed else planned["ordinary_evidence_refs"]) == 1 + assert follow["execution_and_goal_gain"] == "unknown" def test_real_append_index_ignores_compact_display_order_and_clock_skew(tmp_path): @@ -95,7 +94,7 @@ def test_real_append_index_ignores_compact_display_order_and_clock_skew(tmp_path before = index.read_bytes() context = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=(), source_status={"registry": str(registry), "runtime_root": str(tmp_path), - "run_history": {"runs": [_rows()[0]]}}, stride_strategy="evidence_conditioned_v1") + "run_history": {"runs": [_rows()[0]]}}) assert _assert_followthrough(context)["source_history_complete"] is True assert index.read_bytes() == before @@ -357,20 +356,19 @@ def test_projected_work_uses_the_planned_todos_own_settlement(tmp_path, monkeypa @pytest.mark.parametrize("rows", [_rows(), list(reversed(_rows()))]) def test_unknown_order_does_not_fabricate_a_previous_decision_or_later_work(rows): - context = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=rows, - stride_strategy="evidence_conditioned_v1") + context = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=rows) assert "decision_followthrough" not in context assert context["evidence_count"] == 3 -def test_carrier_metadata_preserves_feature_off_parity_and_rejects_non_boolean_order(): +def test_carrier_metadata_preserves_unconditional_stride_and_rejects_non_boolean_order(): rows = list(reversed(_rows())) ordinary = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=rows) declared = project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=rows, - history_newest_first=True, stride_strategy="off") + history_newest_first=True) assert "decision_followthrough" not in ordinary _assert_followthrough(declared) - assert "stride_strategy" not in declared + assert declared["stride_strategy"] == "evidence_conditioned_v1" for invalid in [0, 1, "newest_first"]: with pytest.raises(ValueError, match="boolean or unknown"): project_replan_context(goal_id="evidence-goal", agent_id="agent-a", runs=rows, diff --git a/tests/control_plane/test_replan_history_policy.py b/tests/control_plane/test_replan_history_policy.py index 85b50f8093..a1b65cc1ec 100644 --- a/tests/control_plane/test_replan_history_policy.py +++ b/tests/control_plane/test_replan_history_policy.py @@ -204,7 +204,7 @@ def capture(method, params): assert requests[0][1]["todos"]["resume"] is None -def test_cadence_codec_transports_strategy_without_reclassifying_or_scaling(monkeypatch, tmp_path) -> None: +def test_cadence_codec_ignores_legacy_strategy_without_reclassifying_or_scaling(monkeypatch, tmp_path) -> None: from loopx.control_plane.work_items import replan_history_codec as codec requests = [] @@ -213,14 +213,15 @@ def project(params, context): return {"schema_version": "replan_history_result_v0", "trigger": None} monkeypatch.setattr(codec, "_project_admitted_replan_request", project) goal = {"id": "fixture", "execution_profile": {"replan_after_effective_turns": 6, - "stride_strategy": "evidence_conditioned_v1"}} + "stride_strategy": "off"}} context = codec.effective_turn_cadence_context(goal, tmp_path) codec.project_replan_history(effective_turn_cadence=context) assert requests[-1]["periodic_threshold"] == 6 - assert requests[-1]["stride_strategy"] == "evidence_conditioned_v1" + assert "stride_strategy" not in requests[-1] del goal["execution_profile"]["stride_strategy"] codec.project_replan_history(effective_turn_cadence=codec.effective_turn_cadence_context(goal, tmp_path)) - assert requests[-1]["stride_strategy"] == "off" + assert requests[-1]["periodic_threshold"] == 6 + assert "stride_strategy" not in requests[-1] def test_long_history_keeps_evidence_beyond_rpc_limit() -> None: diff --git a/tests/control_plane/test_replan_host_context_projection.py b/tests/control_plane/test_replan_host_context_projection.py index 5f77c2ade6..8f0b468449 100644 --- a/tests/control_plane/test_replan_host_context_projection.py +++ b/tests/control_plane/test_replan_host_context_projection.py @@ -72,7 +72,7 @@ def _obligation() -> dict[str, object]: ) -def _quota_payload(*, include_legacy_receipt: bool = False, stride_strategy: str = "off") -> dict[str, object]: +def _quota_payload(*, include_legacy_receipt: bool = False) -> dict[str, object]: obligation = _obligation() item_extra: dict[str, object] = { "autonomous_replan_obligation": obligation, @@ -109,7 +109,7 @@ def _quota_payload(*, include_legacy_receipt: bool = False, stride_strategy: str ], item_extra=item_extra, project_asset_extra={"autonomous_replan_obligation": obligation, - **({"execution_profile": {"stride_strategy": stride_strategy, "replan_after_effective_turns": 6}} if stride_strategy != "off" else {})}, + "execution_profile": {"replan_after_effective_turns": 6}}, ) return build_quota_should_run( status_payload, @@ -223,9 +223,10 @@ def test_quota_delivers_coverage_context_and_minimal_replan_action() -> None: } assert context["coverage_ledger"][0]["surface_id"] == "surface-existing" assert 0 < len(action["planning_guidance"]) <= 3 + assert action["stride_control"]["strategy_version"] == "evidence_conditioned_v1" assert { key: value for key, value in action.items() - if key not in {"planning_guidance", "writeback_contract"} + if key not in {"planning_guidance", "writeback_contract", "stride_control"} } == { "schema_version": "replan_action_packet_v0", "decision": "replan_required", @@ -347,8 +348,7 @@ def test_replan_guidance_survives_cli_and_host_compaction_without_new_authority( assert envelope["replan_action_packet"] == old_envelope["replan_action_packet"] -@pytest.mark.parametrize("enabled", [False, True]) -def test_outer_explore_reader_runs_only_for_enabled_replan_context(monkeypatch, enabled): +def test_outer_explore_reader_runs_unconditionally_for_live_replan_context(monkeypatch): from loopx.capabilities.explore import turn_context calls = [] @@ -357,11 +357,8 @@ def read_source(**kwargs): return {"ok": False, "goal_id": GOAL_ID, "agent_id": AGENT_ID} monkeypatch.setattr(turn_context, "read_replan_explore_context", read_source) - result = _quota_payload(stride_strategy="evidence_conditioned_v1" if enabled else "off") + result = _quota_payload() assert result["replan_action_packet"] - assert len(calls) == int(enabled) - if enabled: - assert calls[0]["goal_id"] == GOAL_ID and calls[0]["agent_id"] == AGENT_ID - assert result["replan_action_packet"]["stride_control"]["explore_basis"]["availability"] == "unavailable" - else: - assert "stride_control" not in result["replan_action_packet"] + assert len(calls) == 1 + assert calls[0]["goal_id"] == GOAL_ID and calls[0]["agent_id"] == AGENT_ID + assert result["replan_action_packet"]["stride_control"]["explore_basis"]["availability"] == "unavailable" diff --git a/tests/control_plane/test_replan_progress_native_cli.py b/tests/control_plane/test_replan_progress_native_cli.py index f7d0cdc046..0ec9627bf7 100644 --- a/tests/control_plane/test_replan_progress_native_cli.py +++ b/tests/control_plane/test_replan_progress_native_cli.py @@ -68,8 +68,6 @@ def make_progress_cli_fixture(root: Path, provider: str, scenario: str) -> dict: registry.write_text(json.dumps({"common_runtime_root": str(runtime), "goals": [{ "id": GOAL, "status": "active", "repo": str(project), "state_file": state.name, "domain": "synthetic-typed-progress", - # Individual comparison journeys explicitly enable Stride below. - "execution_profile": {"stride_strategy": "off"}, "adapter": {"kind": "fixture_connected_delivery_v0", "status": "connected-delivery"}, "quota": {"compute": 1.0, "window_hours": 24}, "coordination": {"agent_model": "peer_v1", "registered_agents": [AGENT]}, @@ -396,9 +394,28 @@ def read(command, expected=0): argv = shlex.split(delivered_writer) assert argv == shlex.split(original_writer) assert "--turn-instance-id" not in argv - values = {"": "advanced", - "": "surface-existing", "": "hypothesis-existing", - "": "probe-independent", "": "evidence-current"} + vision = tmp_path / "progressive-vision.json" + vision.write_text(json.dumps({ + "schema_version": "goal_vision_replan_contract_v0", + "agent_id": AGENT, + "state": "active", + "vision_patch": {"acceptance_summary": "Validate the original artifact."}, + "path_delta": { + "schema_version": "goal_path_delta_v0", + "outcome": "continue", + "prior_assumption": "Prior probe left the validation open.", + "observed_reality": "Independent probe supplies fresh evidence.", + "retained": ["Original validation scope."], + "evidence_refs": ["evidence-current"], + }, + "stride_decision": writer["stride_control"]["minimal_example"], + })) + values = { + "": str(vision), + "": "advanced", + "": "surface-existing", "": "hypothesis-existing", + "": "probe-independent", "": "evidence-current", + } index_before = fixture["index"].read_bytes() dry_run = read(shlex.join([sys.executable, "-m", "loopx.entrypoint", *[values.get(arg, arg) for arg in argv[1:]], "--dry-run", "--no-global-sync", @@ -497,7 +514,38 @@ def test_typed_progress_cli_preserves_replan_authority( original = {key: fixture[key].read_bytes() for key in ("registry", "state", "index")} original_events = _quota_events(fixture["runtime"]) authority = _authority(fixture) - result = call_progress_cli(fixture, *fixture["refresh"], + stride_decision = bound["replan_action_packet"]["stride_control"]["minimal_example"] + refresh = list(fixture["refresh"]) + if "--agent-vision-json" in refresh: + vision_path = Path(refresh[refresh.index("--agent-vision-json") + 1]) + vision_data = json.loads(vision_path.read_text()) + vision_data["stride_decision"] = stride_decision + vision_path.write_text(json.dumps(vision_data)) + else: + vision_path = tmp_path / "typed-progress-stride-vision.json" + inconsistent = scenario == "terminal_inconsistent" + vision_path.write_text(json.dumps({ + "schema_version": "goal_vision_replan_contract_v0", + "goal_id": GOAL, + "agent_id": AGENT, + "state": "active", + "vision_patch": {"acceptance_summary": "Review the stalled validation route."}, + "path_delta": { + "schema_version": "goal_path_delta_v0", + "outcome": "continue" if inconsistent else "stop", + "prior_assumption": "Prior probe left the validation unchanged.", + "observed_reality": "Reviewing typed progress under live stride.", + **({"retained": ["Keep probing while inconsistent terminal claim is checked."]} + if inconsistent else {"stopped": ["Stop repeating the unchanged probe."]}), + "evidence_refs": ["evidence-current"], + }, + "stride_decision": stride_decision, + })) + if "--vision-unchanged-reason" in refresh: + idx = refresh.index("--vision-unchanged-reason") + del refresh[idx:idx + 2] + refresh.extend(["--agent-vision-json", str(vision_path)]) + result = call_progress_cli(fixture, *refresh, expected_code=0 if expected_outcomes else 1) if expected_outcomes: assert result["ok"] is True and result["appended"] is True @@ -511,7 +559,7 @@ def test_typed_progress_cli_preserves_replan_authority( assert delta == { "schema_version": "replan_semantic_delta_v0", "accepted": True, "outcomes": expected_outcomes, "satisfying_outcomes": expected_outcomes, - "required_any_of": ["new_surface", "new_hypothesis", "new_probe_family", + "required_any_of": ["fresh_vision_path_outcome", "new_surface", "new_hypothesis", "new_probe_family", "new_runnable_successor", "coverage_backed_exploration_exhausted", "new_concrete_blocker", "coverage_backed_no_followup"], "observation_fingerprint": fingerprint, @@ -525,7 +573,7 @@ def test_typed_progress_cli_preserves_replan_authority( compact = json.loads(fixture["index"].read_text().splitlines()[-1]) assert compact["autonomous_replan_ack"]["semantic_delta"] == delta restart_effect_runtime(wait_for_exit=True) - replay = call_progress_cli(fixture, *fixture["refresh"]) + replay = call_progress_cli(fixture, *refresh) assert replay["appended"] is False and replay["idempotent_replay"] is True else: assert result["ok"] is False and result["appended"] is False @@ -541,7 +589,7 @@ def test_typed_progress_cli_preserves_replan_authority( assert "settlement_owed" not in recovery assert rejection["next_cli_actions"] == recovery["next_cli_actions"] restart_effect_runtime(wait_for_exit=True) - assert call_progress_cli(fixture, *fixture["refresh"], expected_code=1) == result + assert call_progress_cli(fixture, *refresh, expected_code=1) == result [command] = rejection["next_cli_actions"] code, recovered = _run_generated_cli( command, registry_path=fixture["registry"], cwd=fixture["project"]) @@ -594,8 +642,7 @@ def spend(turn: str, *, todo: str | None = TODO, obligation: str | None = None) "--slots", "1", "--source", "heartbeat", "--execute") try: - call("configure-goal", "--goal-id", GOAL, "--execution-replan-after-turns", "1", - "--execution-stride-strategy", "evidence_conditioned_v1", "--execute") + call("configure-goal", "--goal-id", GOAL, "--execution-replan-after-turns", "1", "--execute") if comparison_binding: call("configure-goal", "--goal-id", GOAL, "--explore-mode", "planning", "--execute") call("explore", "node", "--goal-id", GOAL, "--agent-id", AGENT, diff --git a/tests/control_plane/test_replan_staged_read.py b/tests/control_plane/test_replan_staged_read.py index 7e377791e9..1c080c71b5 100644 --- a/tests/control_plane/test_replan_staged_read.py +++ b/tests/control_plane/test_replan_staged_read.py @@ -30,16 +30,20 @@ def json_bytes(value): return len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) -def without_example(contract): +def without_example(contract, source=None): expected = copy.deepcopy(contract) + if "vision_authoring_ref" in expected and source is not None: + expected.pop("vision_authoring_ref") + steps = source["interaction_contract"]["cli_channel"]["settlement_plan"]["ordered_steps"] + step = next(row for row in steps if row.get("kind") == "durable_writeback" and "vision_authoring" in row) + expected["vision_authoring"] = copy.deepcopy(step["vision_authoring"]) if "vision_authoring" in expected: - expected["vision_authoring"].pop("minimal_example") + expected["vision_authoring"].pop("minimal_example", None) return expected -@pytest.mark.parametrize("stride", ["off", "evidence_conditioned_v1"]) -def test_staged_packet_budget_and_lossless_authority(stride): - source = _quota_payload(stride_strategy=stride) +def test_staged_packet_budget_and_lossless_authority(): + source = _quota_payload() legacy = build_turn_envelope(source) source["replan_read_path"] = "/synthetic/decision.json" original = copy.deepcopy(source) @@ -84,16 +88,13 @@ def test_staged_packet_budget_and_lossless_authority(stride): assert json_bytes(review) <= 16384 assert "guidance" not in review assert json_bytes(writer) <= 16384 - if stride != "off": - assert review["decision_value_review"] == source["replan_action_packet"]["stride_control"]["decision_value_review"] - control = writer["stride_control"] - assert control["previous_decision_ref"] == source["replan_action_packet"]["stride_control"]["previous_decision_ref"] - assert "decision_followthrough" not in control and "decision_value_review" not in control - assert control["minimal_example"] == source["replan_action_packet"]["stride_control"]["minimal_example"] - assert control["basis_options"] == ["supported_progress", "unexplained_gap", "uncertain_evidence", "useful_new_route", "decision_failure"] - assert {"basis", "action", "axes", "next_probe"} <= set(control["required_fields"]) - else: - assert "decision_value_review" not in review + assert review["decision_value_review"] == source["replan_action_packet"]["stride_control"]["decision_value_review"] + control = writer["stride_control"] + assert control["previous_decision_ref"] == source["replan_action_packet"]["stride_control"]["previous_decision_ref"] + assert "decision_followthrough" not in control and "decision_value_review" not in control + assert control["minimal_example"] == source["replan_action_packet"]["stride_control"]["minimal_example"] + assert control["basis_options"] == ["supported_progress", "unexplained_gap", "uncertain_evidence", "useful_new_route", "decision_failure"] + assert {"basis", "action", "axes", "next_probe"} <= set(control["required_fields"]) assert source == original @@ -521,7 +522,7 @@ def read(stage, expected_code=0, *, bind_capture=False): assert entry.get("action_portfolio") == source.get("action_portfolio") assert review["context_id"] == writer["context_id"] assert review["obligation_id"] == source["replan_action_packet"]["obligation_id"] - assert writer["writeback_contract"] == without_example(source["replan_action_packet"]["writeback_contract"]) + assert writer["writeback_contract"] == without_example(source["replan_action_packet"]["writeback_contract"], source) assert (capture / "decision.json").read_bytes() == saved assert {key: fixture[key].read_bytes() for key in original_files} == original_files assert not reader_fixture["registry"].exists() @@ -549,9 +550,32 @@ def read(stage, expected_code=0, *, bind_capture=False): assert shlex.split(bound_review.pop("next")["writeback"]) == [ *writer_args[:-2], "--capture-sha256", capture_sha256, *writer_args[-2:], ] - assert bound_review == {key: value for key, value in review.items() if key != "next"} + expected_review = copy.deepcopy({key: value for key, value in review.items() if key != "next"}) + explore_read = expected_review.get("capabilities", {}).get("explore", {}).pop("read_action", None) + if explore_read is not None: + explore_args = shlex.split(explore_read) + assert shlex.split(bound_review["capabilities"]["explore"].pop("read_action")) == [ + *explore_args[:-2], "--capture-sha256", capture_sha256, *explore_args[-2:], + ] + assert bound_review == expected_review # A valid next operation still reaches the existing writer and semantic gate. - result = call_progress_cli(fixture, *fixture["refresh"]) + vision_path = tmp_path / "staged-vision.json" + vision_path.write_text(json.dumps({ + "schema_version": "goal_vision_replan_contract_v0", + "state": "vision_patch_proposed", + "vision_patch": {"acceptance_summary": "Retain the current validation acceptance and verify the next probe."}, + "path_delta": { + "outcome": "replan", + "prior_assumption": "The previous validation probe stalled without fresh evidence.", + "observed_reality": "An independent validation probe produced current evidence.", + "retained": ["Original validation acceptance criteria"], + "evidence_refs": ["evidence-current"], + }, + "stride_decision": writer["stride_control"]["minimal_example"], + })) + refresh = [arg for idx, arg in enumerate(fixture["refresh"]) + if arg != "--vision-unchanged-reason" and (idx == 0 or fixture["refresh"][idx - 1] != "--vision-unchanged-reason")] + result = call_progress_cli(fixture, *refresh, "--agent-vision-json", str(vision_path)) assert result["autonomous_replan_ack"]["semantic_delta"]["accepted"] is True finally: restart_effect_runtime(wait_for_exit=True) @@ -785,7 +809,7 @@ def test_native_reader_keeps_its_installation_across_acceptance_and_writeback(tm monkeypatch.setenv("LOOPX_RELEASE_ROOT", str(release_root)) monkeypatch.setenv("PYTHONPATH", str(stale_root)) - source = _quota_payload(stride_strategy="evidence_conditioned_v1") + source = _quota_payload() outcome = {"id": "original-outcome", "objective": "Deliver the original accepted artifact.", "requirements": [{"id": "original-stop", "description": "Stop before publication."}]} source["autonomous_replan_obligation"]["replan_context"]["core_goal"]["acceptance_contract"] = { @@ -935,9 +959,6 @@ def test_measurement_groups_keep_bounded_replan_detail_and_reachable_remainder(t isolate_sqlite_runtime(tmp_path, monkeypatch) fixture = make_progress_cli_fixture(tmp_path, provider, "advanced") enable_explore(fixture) - registry = json.loads(fixture["registry"].read_text()) - registry["goals"][0]["execution_profile"]["stride_strategy"] = "evidence_conditioned_v1" - fixture["registry"].write_text(json.dumps(registry)) log = explore_result_log_path(fixture["runtime"], GOAL) append_explore_result_event(log, build_explore_node_event(goal_id=GOAL, agent_id=AGENT, node_id="question-measurement", node_kind="question", title="Does this candidate improve the outcome?")) diff --git a/tests/control_plane/test_replan_successor_guard_reentry.py b/tests/control_plane/test_replan_successor_guard_reentry.py index 6817cc1fda..7aff9e4e94 100644 --- a/tests/control_plane/test_replan_successor_guard_reentry.py +++ b/tests/control_plane/test_replan_successor_guard_reentry.py @@ -169,7 +169,6 @@ def test_projected_terminal_replan_fields_execute_without_guessed_flags(tmp_path from loopx.install_contract import render_host_cli_command call, _, index = _fixture(tmp_path, monkeypatch, provider, future_monitor=False) - call("configure-goal", "--goal-id", GOAL, "--execution-stride-strategy", "off", "--execute") # The complete delivery has no remaining Todo; retain its accepted mainline. rows = [json.loads(row) for row in index.read_text().splitlines()] vision = deepcopy(next(row["agent_vision"] for row in rows if "agent_vision" in row)) @@ -195,6 +194,9 @@ def test_projected_terminal_replan_fields_execute_without_guessed_flags(tmp_path "observed_reality": "Independent validation covers the complete source scope.", "stopped": ["Repeated source checks"], "evidence_refs": ["validation:complete-source"], } + vision["stride_decision"] = deepcopy( + original["replan_action_packet"]["stride_control"]["minimal_example"] + ) path = tmp_path / "author's terminal.json" path.write_text(json.dumps(vision), encoding="utf-8") command = next(action for action in original["interaction_contract"]["cli_channel"]["next_cli_actions"] diff --git a/tests/control_plane/test_replan_terminal_spend_ordering.py b/tests/control_plane/test_replan_terminal_spend_ordering.py index 75ffb6b962..6f6c293b75 100644 --- a/tests/control_plane/test_replan_terminal_spend_ordering.py +++ b/tests/control_plane/test_replan_terminal_spend_ordering.py @@ -64,23 +64,36 @@ def _coverage_backed_no_followup_refresh_args( ) -> tuple[str, ...]: """Fill the projected refresh template with a coverage-backed no_followup.""" - command = ( - command.replace( - "", - "no_followup", + if "" in command: + command = command.replace( + "", + shlex.quote(str(vision_path)), ) - .replace("", "surface-terminal") - .replace("", "hypothesis-terminal") - .replace("", "probe-terminal") - .replace("", "evidence-terminal") - ) + command += ( + " --progress-result-class no_followup" + " --progress-surface-id surface-terminal" + " --progress-hypothesis-id hypothesis-terminal" + " --progress-probe-kind probe-terminal" + " --progress-evidence-id evidence-terminal" + ) + else: + command = ( + command.replace( + "", + "no_followup", + ) + .replace("", "surface-terminal") + .replace("", "hypothesis-terminal") + .replace("", "probe-terminal") + .replace("", "evidence-terminal") + ) + command += f" --agent-vision-json {shlex.quote(str(vision_path))}" command += " --progress-coverage-scope-id coverage-terminal" command += " --progress-coverage-complete" - command += f" --agent-vision-json {shlex.quote(str(vision_path))}" return _projected_cli_args(command, turn_instance_id=TURN_INSTANCE_ID) -def _write_no_followup_vision(root: Path) -> Path: +def _write_no_followup_vision(root: Path, guard: dict[str, Any]) -> Path: vision = { "schema_version": "goal_vision_replan_contract_v0", "agent_id": AGENT_ID, @@ -98,6 +111,7 @@ def _write_no_followup_vision(root: Path) -> Path: "stopped": ["repeat probe of the covered frontier"], "evidence_refs": ["evidence-terminal"], }, + "stride_decision": guard["replan_action_packet"]["stride_control"]["minimal_example"], } vision_path = root / "coverage-backed-no-followup-vision.json" vision_path.write_text(json.dumps(vision), encoding="utf-8") @@ -160,12 +174,12 @@ def test_coverage_backed_no_followup_replan_does_not_strand_its_quota_spend( tmp_path: Path, ) -> None: project, runtime, registry_path = _write_fixture(tmp_path) - _configure_autonomous_replan_fixture(project, runtime, registry_path, stride_strategy="off") + _configure_autonomous_replan_fixture(project, runtime, registry_path) _write_terminal_frontier_state(project) _initialize_fixture_authority(project, runtime, provider="sqlite") - vision_path = _write_no_followup_vision(tmp_path) guard = _should_run(registry_path, runtime, project) + vision_path = _write_no_followup_vision(tmp_path, guard) assert guard["decision"] == "autonomous_replan_required", guard obligation_id = guard["replan_action_packet"]["obligation_id"] assert guard["heartbeat_receipt"]["settlement_identity"]["binding_kind"] == ( @@ -241,12 +255,12 @@ def test_unbound_terminal_spend_stays_rejected(tmp_path: Path) -> None: """The terminal guard keeps rejecting a spend that owns no settlement.""" project, runtime, registry_path = _write_fixture(tmp_path) - _configure_autonomous_replan_fixture(project, runtime, registry_path, stride_strategy="off") + _configure_autonomous_replan_fixture(project, runtime, registry_path) _write_terminal_frontier_state(project) _initialize_fixture_authority(project, runtime, provider="sqlite") - vision_path = _write_no_followup_vision(tmp_path) guard = _should_run(registry_path, runtime, project) + vision_path = _write_no_followup_vision(tmp_path, guard) actions = guard["interaction_contract"]["cli_channel"]["next_cli_actions"] refresh_command = next(action for action in actions if "refresh-state" in action) refresh_rc, refresh = _run_cli( diff --git a/tests/control_plane/test_replan_writeback_lease_scope.py b/tests/control_plane/test_replan_writeback_lease_scope.py index fd0396139d..5cd4e484c6 100644 --- a/tests/control_plane/test_replan_writeback_lease_scope.py +++ b/tests/control_plane/test_replan_writeback_lease_scope.py @@ -17,15 +17,13 @@ @pytest.mark.parametrize("provider", ["file", "sqlite"]) -@pytest.mark.parametrize("case,strategy", [ - ("planning", "off"), ("planning", "evidence_conditioned_v1"), - ("foreign_turn", "off"), ("explicit_execution", "off"), - ("prepared_execution", "off"), ("stopped", "off"), +@pytest.mark.parametrize("case", [ + "planning", "foreign_turn", "explicit_execution", "prepared_execution", "stopped", ]) -def test_planning_closeout_keeps_business_execution_authority(tmp_path, monkeypatch, provider, case, strategy): +def test_planning_closeout_keeps_business_execution_authority(tmp_path, monkeypatch, provider, case): isolate_sqlite_runtime(tmp_path, monkeypatch) project, runtime, registry = _write_fixture(tmp_path) - _configure_selected_todo_replan_fixture(project, registry, stride_strategy=strategy) + _configure_selected_todo_replan_fixture(project, registry) _initialize_git_checkout(project) _initialize_fixture_authority(project, runtime, provider=provider, handoff_mode="hard_lease") turn = "lease-scoped-planning" @@ -69,16 +67,15 @@ def test_planning_closeout_keeps_business_execution_authority(tmp_path, monkeypa prepared_lease_key_sha256=hashlib.sha256(b"unadmitted-execution").hexdigest(), prepared_lease_version=1, prepared_lease_epoch=1) log.write_text("".join(json.dumps(row) + "\n" for row in rows)) - if strategy != "off": - vision = {"schema_version": "goal_vision_replan_contract_v0", "state": "vision_patch_proposed", - "vision_patch": {"acceptance_summary": "Retain the original task and verify the complete planning scope."}, - "path_delta": {"outcome": "replan", "prior_assumption": "The next scope needed review.", - "observed_reality": "A bounded comparison identifies the next complete check.", - "retained": ["Original task and acceptance"], "evidence_refs": ["evidence:planning-scope"]}, - "stride_decision": guard["replan_action_packet"]["stride_control"]["minimal_example"]} - vision_path = tmp_path / "vision.json" - vision_path.write_text(json.dumps(vision)) - args += ["--agent-vision-json", str(vision_path)] + vision = {"schema_version": "goal_vision_replan_contract_v0", "state": "vision_patch_proposed", + "vision_patch": {"acceptance_summary": "Retain the original task and verify the complete planning scope."}, + "path_delta": {"outcome": "replan", "prior_assumption": "The next scope needed review.", + "observed_reality": "A bounded comparison identifies the next complete check.", + "retained": ["Original task and acceptance"], "evidence_refs": ["evidence:planning-scope"]}, + "stride_decision": guard["replan_action_packet"]["stride_control"]["minimal_example"]} + vision_path = tmp_path / "vision.json" + vision_path.write_text(json.dumps(vision)) + args += ["--agent-vision-json", str(vision_path)] rc, result = _run_cli(registry, runtime, *args, cwd=project) if case == "planning": assert rc == 0 and result["ok"], result.get("error") or result diff --git a/tests/control_plane/test_request_amendment_recovery.py b/tests/control_plane/test_request_amendment_recovery.py index ac35c046f5..6df2cc1905 100644 --- a/tests/control_plane/test_request_amendment_recovery.py +++ b/tests/control_plane/test_request_amendment_recovery.py @@ -14,7 +14,6 @@ from loopx.control_plane.collaboration.request_amendment import recover_request_amendment, control_request from loopx.control_plane.collaboration.inbox import _root, acknowledge from loopx.cli import main -from loopx.capabilities.todo_replan_cadence.machine_defaults import resolve_todo_replan_cadence_goal from loopx.collaboration_mcp import register_collaboration_tools from loopx.control_plane.projects.registry_codec import source_session_registry_transaction @@ -235,8 +234,8 @@ def test_real_request_reservation_goal_commit_and_terminal_linkage(source_goal, f = source_goal rid, commit = _proposal(f, tmp_path, capsys) before = {p.relative_to(_root(f["runtime"])): p.read_bytes() for p in _root(f["runtime"]).rglob("*.json")} - # The current Goal configuration reader must pass through both the public - # request wrapper and its reserved-effect caller after integration. + # Live stride is unconditional, so governed amendment preview/commit/replay + # do not depend on machine todo_replan_cadence configuration reads. from loopx.capabilities.todo_replan_cadence import machine_defaults def unavailable(*_args, **_kwargs): @@ -244,12 +243,9 @@ def unavailable(*_args, **_kwargs): with monkeypatch.context() as missing_config: missing_config.setattr(machine_defaults, "resolve_todo_replan_cadence_goal", unavailable) - code, refused = goal_call(f, tmp_path, capsys, "commit", commit, operation_id="commit-request", execute=False) - assert code == 1 and "configuration unavailable" in str(refused), refused - assert {p.relative_to(_root(f["runtime"])): p.read_bytes() for p in _root(f["runtime"]).rglob("*.json")} == before - code, preview = goal_call(f, tmp_path, capsys, "commit", commit, operation_id="commit-request", execute=False) - assert code == 0, preview - assert preview["goal_changed"] is False and preview["terminal_recorded"] is False + code, preview = goal_call(f, tmp_path, capsys, "commit", commit, operation_id="commit-request", execute=False) + assert code == 0, preview + assert preview["goal_changed"] is False and preview["terminal_recorded"] is False assert {p.relative_to(_root(f["runtime"])): p.read_bytes() for p in _root(f["runtime"]).rglob("*.json")} == before code, applied = goal_call(f, tmp_path, capsys, "commit", commit, operation_id="commit-request", execute=True) assert code == 0, applied @@ -272,7 +268,6 @@ def unavailable(*_args, **_kwargs): def _recover(f, rid, *, execute=True): return recover_request_amendment(registry_path=f["registry"], runtime_root=f["runtime"], goal_ref=f["ref"], - replan_configuration_reader=resolve_todo_replan_cadence_goal, receiver_agent_id="agent-a", request_id=rid, actor_agent_id="agent-b", execute=execute) @@ -613,7 +608,6 @@ def unknown(*args, **kwargs): assert goal_call(f, tmp_path, capsys, "commit", commit, operation_id="old-effect", execute=True)[0] == 1 current = _control(f, rid, "inspect")["view"] corrected = control_request(registry_path=f["registry"], runtime_root=f["runtime"], goal_ref=f["ref"], - replan_configuration_reader=resolve_todo_replan_cadence_goal, receiver_agent_id="agent-a", request_id=rid, actor_agent_id="agent-b", operation="revise", execute=True, parameters={"operation_id": "correct-unknown", **_basis(current), "brief": {**BRIEF, "context": "Continue from corrected source"}, "reason": "Use the new input"}) assert corrected["ok"] and corrected["view"]["control_state"] == "open", corrected diff --git a/tests/control_plane/test_research_comparison_cli.py b/tests/control_plane/test_research_comparison_cli.py index fa01876f26..9e5c017ffe 100644 --- a/tests/control_plane/test_research_comparison_cli.py +++ b/tests/control_plane/test_research_comparison_cli.py @@ -97,7 +97,7 @@ def cli(*arguments, code=0): return packet cli("configure-goal", "--goal-id", fixture.GOAL_ID, "--explore-mode", "planning", - "--execution-replan-after-turns", "3", "--execution-stride-strategy", "evidence_conditioned_v1", "--execute") + "--execution-replan-after-turns", "3", "--execute") # The owner defines three search families and a complete implementation # task, not a winning expression or a prewritten next-route Todo. Links are # part of that initial work declaration; later result capture adds evidence. diff --git a/tests/control_plane/test_research_context_adoption.py b/tests/control_plane/test_research_context_adoption.py index d6f1382c3d..69b22e3904 100644 --- a/tests/control_plane/test_research_context_adoption.py +++ b/tests/control_plane/test_research_context_adoption.py @@ -265,8 +265,7 @@ def lost_handoff(env, payload): def _ordinary_review_and_work(run, workspace, tmp_path, todo, digest, monkeypatch, work=None): """Real current-owner replan consumes inherited counterevidence, then work.""" monkeypatch.chdir(workspace) - run('configure-goal', '--goal-id', 'branch', '--execution-replan-after-turns', '1', - '--execution-stride-strategy', 'evidence_conditioned_v1', '--execute') + run('configure-goal', '--goal-id', 'branch', '--execution-replan-after-turns', '1', '--execute') actor = ['--goal-id', 'branch', '--agent-id', 'branch-actor'] def settle(turn, vision, *, review=False, lease_proof=None): path = tmp_path / (turn + '.json') diff --git a/tests/control_plane/test_research_execution_loop.py b/tests/control_plane/test_research_execution_loop.py index 50e0570ef3..2f61389885 100644 --- a/tests/control_plane/test_research_execution_loop.py +++ b/tests/control_plane/test_research_execution_loop.py @@ -333,8 +333,7 @@ def call(*args, expected=0): "ok", "error", "error_code", "effective_action", "reason", "blocker", "autonomous_replan_obligation")}) return result - call("configure-goal", "--goal-id", fixture.GOAL_ID, "--execution-replan-after-turns", "2", - "--execution-stride-strategy", "evidence_conditioned_v1", "--execute") + call("configure-goal", "--goal-id", fixture.GOAL_ID, "--execution-replan-after-turns", "2", "--execute") # The actor records requested work through ordinary Todo operations. The # observation producer neither creates these stages nor imposes a strategy. root = call("todo", "add", "--goal-id", fixture.GOAL_ID, "--role", "agent", @@ -513,7 +512,7 @@ async def upload_file(self, source, target): agent = harbor.BenchmarkCodex(logs_dir=tmp_path / "logs", model_name="fixture", goal_id=fixture.GOAL_ID, agent_id=fixture.AGENT_ID, - execution_observation="local_probe", stride_strategy="off") + execution_observation="local_probe") env = dict(os.environ) monkeypatch.setattr(agent, "_profile_env", lambda: env) environment = Environment() @@ -526,7 +525,7 @@ async def upload_file(self, source, target): assert [todo["todo_id"] for todo in listed["todos"]] == [fixture.TODO_ID] assert all(todo.get("target_key") != "research-continuation" for todo in listed["todos"]) configured = call("configure-goal", "--goal-id", fixture.GOAL_ID) - assert configured["after"]["execution_profile"]["stride_strategy"] == "off" + assert "stride_strategy" not in configured["after"]["execution_profile"] assert candidate.read_bytes() == original_candidate call("configure-goal", "--goal-id", fixture.GOAL_ID, "--explore-graph-enabled", "--execute") work_turn = "ordinary-local-observation" diff --git a/tests/control_plane/test_research_replan_basis_cli.py b/tests/control_plane/test_research_replan_basis_cli.py index 775b40cec6..7405bf4b4f 100644 --- a/tests/control_plane/test_research_replan_basis_cli.py +++ b/tests/control_plane/test_research_replan_basis_cli.py @@ -32,11 +32,6 @@ def test_formal_task_instruction_change_rearms_the_actual_worker( "index": index + 1, "source_section": "Agent Todo", "archive_state": "active", "claimed_by": AGENT, "updated_at": "2026-09-01T00:00:00Z"} for index in range(15)] call, runtime, history = _fixture(tmp_path, monkeypatch, provider, future_monitor=False, initial_todos=todos) - # This fixture isolates instruction changes from independent Stride review. - registry_path = tmp_path / "registry.json" - registry = json.loads(registry_path.read_text()) - registry["goals"][0]["execution_profile"] = {"stride_strategy": "off"} - registry_path.write_text(json.dumps(registry)) history.write_text("") calls = tmp_path / "review-calls" args = _args(fake_cli=Path(sys.executable).parent / "loopx", state_file=tmp_path / "scheduler.json", @@ -64,7 +59,8 @@ def test_formal_task_instruction_change_rearms_the_actual_worker( "outcome": "continue", "prior_assumption": "The finite sample review is the current first task.", "observed_reality": "The current canonical task still requests finite samples.", "retained": ["The requested work and its original limits."], - "evidence_refs": ["evidence:current-canonical-task-review"]}})) + "evidence_refs": ["evidence:current-canonical-task-review"]}, + "stride_decision": selected["replan_action_packet"]["stride_control"]["minimal_example"]})) binding = ("--goal-id", GOAL, "--agent-id", AGENT, "--turn-instance-id", turn, "--todo-id", identity["todo_id"]) refreshed = call("refresh-state", *binding, "--progress-scope", "agent_lane", diff --git a/tests/control_plane/test_selection_replan_reentry.py b/tests/control_plane/test_selection_replan_reentry.py index ec6142289b..2d243950c6 100644 --- a/tests/control_plane/test_selection_replan_reentry.py +++ b/tests/control_plane/test_selection_replan_reentry.py @@ -36,7 +36,7 @@ def test_replan_selection_recovers_inline_or_refuses_ineligible_choice_and_settl project, runtime, registry = _write_fixture(tmp_path) _configure_selectable_alternative(project) if initial_replan: - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) _initialize_fixture_authority(project, runtime, provider="sqlite") turn = "turn-selection-preempted" guard = ("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, @@ -54,10 +54,10 @@ def test_replan_selection_recovers_inline_or_refuses_ineligible_choice_and_settl trigger["kind"] for trigger in first["autonomous_replan_obligation"]["triggers"] } if binding == "todo": - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) selected_id = SELECTED_REPLAN_TODO_ID else: - _configure_autonomous_replan_fixture(project, runtime, registry, stride_strategy="off") + _configure_autonomous_replan_fixture(project, runtime, registry) selected_id = TODO_ID _advance_frontier(project, runtime, "fixture-frontier-after-selection") rc, selected = _run_cli(registry, runtime, *guard, "--todo-id", selected_id) @@ -123,7 +123,7 @@ def test_replan_selection_recovers_inline_or_refuses_ineligible_choice_and_settl assert replay_cli["replan_settlement_contract"] == cli["replan_settlement_contract"] assert _heartbeat_receipt_count(runtime, turn) == expected_after_resume refresh = next(c for c in cli["next_cli_actions"] if "refresh-state" in c) - if binding == "todo": + if "" in refresh: decision = tmp_path / "selection-replan-vision.json" decision.write_text( json.dumps( @@ -153,6 +153,9 @@ def test_replan_selection_recovers_inline_or_refuses_ineligible_choice_and_settl "changed": ["Proceed with the first validation slice"], "evidence_refs": ["evidence:selection-replan"], }, + "stride_decision": resumed["replan_action_packet"][ + "stride_control" + ]["minimal_example"], } ) + "\n", @@ -203,10 +206,12 @@ def test_replan_selection_recovers_inline_or_refuses_ineligible_choice_and_settl assert _spend_run_count(runtime) == 1 -def _settle_replan_from_captured_actions(project, registry, runtime, turn, actions, identity): +def _settle_replan_from_captured_actions( + project, registry, runtime, turn, actions, identity, *, stride_decision=None, +): refresh = next(c for c in actions if "refresh-state" in c) decision = project.parent / "retained-selection-replan.json" - decision.write_text(json.dumps({ + payload = { "schema_version": "goal_vision_replan_contract_v0", "state": "vision_patch_proposed", "vision_patch": { @@ -222,7 +227,10 @@ def _settle_replan_from_captured_actions(project, registry, runtime, turn, actio "changed": ["Complete the review before a fresh delivery Turn"], "evidence_refs": ["evidence:recommendation-drift"], }, - }) + "\n", encoding="utf-8") + } + if stride_decision is not None: + payload["stride_decision"] = stride_decision + decision.write_text(json.dumps(payload) + "\n", encoding="utf-8") refresh = refresh.replace("", str(decision)) for key, value in {"": "advanced", "": "accepted-artifact", "": "adoption", @@ -245,7 +253,7 @@ def test_reentry_never_replaces_retained_selection_with_recommended_todo(tmp_pat project, runtime, registry = _write_fixture(tmp_path) _configure_selectable_alternative(project) if initial_replan: - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) _initialize_fixture_authority(project, runtime, provider="sqlite") turn = "turn-selection-recommendation-drift" guard = ("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, @@ -264,7 +272,7 @@ def test_reentry_never_replaces_retained_selection_with_recommended_todo(tmp_pat # The original explicit choice leaves the refreshed frontier while a # different recommended Todo becomes visible under a hard replan. - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) _advance_frontier(project, runtime, "fixture-recommendation-drift") retained_todo_id = "todo_chain_000000000001" rc, resumed = _run_cli( @@ -297,6 +305,7 @@ def test_reentry_never_replaces_retained_selection_with_recommended_todo(tmp_pat _settle_replan_from_captured_actions( project, registry, runtime, turn, resumed["interaction_contract"]["cli_channel"]["next_cli_actions"], identity, + stride_decision=resumed["replan_action_packet"]["stride_control"]["minimal_example"], ) rc, conflict = _run_cli( registry, runtime, *guard, "--todo-id", SELECTED_REPLAN_TODO_ID @@ -543,7 +552,7 @@ def test_inline_replan_failure_reports_the_actual_receipt( isolate_sqlite_runtime(tmp_path, monkeypatch) project, runtime, registry = _write_fixture(tmp_path) - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) _initialize_fixture_authority(project, runtime, provider=provider) turn = "turn-inline-replan-publication" retained = "todo_chain_000000000001" @@ -758,7 +767,10 @@ def refuse_short_reference(*args, reference_file=None, **kwargs): assert _heartbeat_receipt_count(runtime, turn) == 1 # Use the captured settlement, without a replacement admission. - _settle_replan_from_captured_actions(project, registry, runtime, turn, actions, receipt["settlement_identity"]) + _settle_replan_from_captured_actions( + project, registry, runtime, turn, actions, receipt["settlement_identity"], + stride_decision=json.loads(original)["replan_action_packet"]["stride_control"]["minimal_example"], + ) assert _heartbeat_receipt_count(runtime, turn) == 1 @@ -825,7 +837,7 @@ def test_captured_direct_replan_command_composes_semantic_writeback_once(tmp_pat isolate_sqlite_runtime(tmp_path, monkeypatch) project, runtime, registry = _write_fixture(tmp_path) - _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _configure_selected_todo_replan_fixture(project, registry) _initialize_fixture_authority(project, runtime, provider=provider) turn = "turn-captured-composed-replan" retained = "todo_chain_000000000001" @@ -875,6 +887,7 @@ def run(command, expected=0): "path_delta": {"outcome": "replan", "prior_assumption": "The existing route was supported.", "observed_reality": "The validation found an independent alternate route.", "changed": ["Review before a fresh delivery."], "evidence_refs": ["evidence:independent-validation"]}, + "stride_decision": writer["stride_control"]["minimal_example"], })) placeholder = "" args = [str(vision) if token == placeholder else token for token in shlex.split(writer["settlement_command"])] diff --git a/tests/control_plane/test_settlement_input_discovery_cli.py b/tests/control_plane/test_settlement_input_discovery_cli.py index 1dd816819e..c732cc3f46 100644 --- a/tests/control_plane/test_settlement_input_discovery_cli.py +++ b/tests/control_plane/test_settlement_input_discovery_cli.py @@ -189,6 +189,9 @@ def run(*args): rc, envelope = run("quota", "should-run", "--codex-app", *current, "--turn-envelope") assert rc == 0 and envelope["replan_action_packet"]["writeback_contract"] == writeback, envelope vision = deepcopy(authoring["minimal_example"]) + vision["stride_decision"] = deepcopy( + guard["replan_action_packet"]["stride_control"]["minimal_example"] + ) vision["path_delta"].update( outcome="replan", observed_reality="The settled fixture has no runnable Todo.", retained=["Original acceptance"], evidence_refs=[]) @@ -200,7 +203,7 @@ def run(*args): path.write_text(json.dumps(vision)) rc, rejected = run(*command) assert rc != 0 and _spend_run_count(runtime) == 1, rejected - assert "typed semantic delta" in rejected["error"], rejected + assert "evidence" in rejected["error"].lower(), rejected vision["path_delta"]["evidence_refs"] = ["validation:no-runnable-fixture"] path.write_text(json.dumps(vision)) rc, accepted = run(*command) @@ -230,8 +233,7 @@ def run(*args): return _run_cli(registry, runtime, *args, cwd=project) rc, configured = run("configure-goal", "--goal-id", GOAL_ID, - "--execution-replan-after-turns", "1", - "--execution-stride-strategy", "off", "--execute") + "--execution-replan-after-turns", "1", "--execute") assert rc == 0, configured for stage in ("initial", "review", "subsequent"): binding = ("--goal-id", GOAL_ID, "--agent-id", AGENT_ID, @@ -264,6 +266,9 @@ def run(*args): vision["path_delta"].update( outcome="replan", observed_reality="Continue the admitted original work.", retained=["Original requirements"], evidence_refs=["validation:work-link"]) + vision["stride_decision"] = deepcopy( + staged["stride_control"]["minimal_example"] + ) path = tmp_path / "linked-vision.json" path.write_text(json.dumps(vision)) # Consume the replan-only binding, rather than inventing a Todo @@ -288,8 +293,7 @@ def run(*args): # Read the real immutable CLI history, not a hand-authored decision fixture. status = {"registry": str(registry), "runtime_root": str(runtime), "run_history": {"runs": []}} context = project_replan_context( - goal_id=GOAL_ID, agent_id=AGENT_ID, runs=(), source_status=status, - stride_strategy="evidence_conditioned_v1") + goal_id=GOAL_ID, agent_id=AGENT_ID, runs=(), source_status=status) follow = context["decision_followthrough"] assert [row["todo_id"] for row in follow["planned_work"]] == [TODO_ID] assert follow["ordinary_work"]["recorded_count"] == 1 @@ -297,12 +301,8 @@ def run(*args): assert evidence["todo_id"] == TODO_ID assert follow["planned_work"][0]["ordinary_evidence_refs"] == [evidence["evidence_ref"]] assert follow["execution_and_goal_gain"] == "unknown" - # Reading this view neither enables stride nor settles another Turn. - ordinary = project_replan_context( - goal_id=GOAL_ID, agent_id=AGENT_ID, runs=(), source_status=status, stride_strategy="off") - assert ordinary["decision_followthrough"] == follow - assert "stride_strategy" not in ordinary - assert "explore_basis" not in ordinary + assert context["stride_strategy"] == "evidence_conditioned_v1" + assert "explore_basis" not in context assert _spend_run_count(runtime) == 3 # Preserve compatibility without turning a descriptive or unsupported @@ -313,6 +313,6 @@ def run(*args): review["agent_vision"]["todo_delta"] = [f"action:{TODO_ID}", "Keep investigating."] unlinked = project_replan_context( goal_id=GOAL_ID, agent_id=AGENT_ID, runs=historical, - history_newest_first=False, stride_strategy="evidence_conditioned_v1") + history_newest_first=False) assert unlinked["decision_followthrough"]["planned_work"] == [] assert "ordinary_work" not in unlinked["decision_followthrough"] diff --git a/tests/control_plane/test_stride_comparison_followthrough_cli.py b/tests/control_plane/test_stride_comparison_followthrough_cli.py index 68e33604b7..a7929364c1 100644 --- a/tests/control_plane/test_stride_comparison_followthrough_cli.py +++ b/tests/control_plane/test_stride_comparison_followthrough_cli.py @@ -36,7 +36,7 @@ def cli(*arguments, expected=0): identity = ("--goal-id", fixture.GOAL_ID, "--agent-id", fixture.AGENT_ID) cli("configure-goal", "--goal-id", fixture.GOAL_ID, "--explore-mode", "planning", - "--execution-replan-after-turns", "1", "--execution-stride-strategy", "evidence_conditioned_v1", "--execute") + "--execution-replan-after-turns", "1", "--execute") cli("todo", "update", *identity, "--todo-id", fixture.TODO_ID, "--explore-result-node-ref", "comparison-retained") training = project / "training.json" @@ -166,7 +166,7 @@ def cli(*args, expected=0): identity = ("--goal-id", fixture.GOAL_ID, "--agent-id", fixture.AGENT_ID) cli("configure-goal", "--goal-id", fixture.GOAL_ID, "--explore-mode", "planning", - "--execution-replan-after-turns", "1", "--execution-stride-strategy", "evidence_conditioned_v1", "--execute") + "--execution-replan-after-turns", "1", "--execute") training = project / "training.json" training.write_text(json.dumps([{"x": 2, "y": 3, "observed": 6}])) request = {"project": str(project), "registry": str(registry), "runtime": str(runtime), diff --git a/tests/control_plane/test_turn_todoless_settlement.py b/tests/control_plane/test_turn_todoless_settlement.py index 5a873b3f78..589b0d06cf 100644 --- a/tests/control_plane/test_turn_todoless_settlement.py +++ b/tests/control_plane/test_turn_todoless_settlement.py @@ -27,7 +27,7 @@ def _fixture(tmp_path, monkeypatch, provider, *, replan=True, capture_dir=None): isolate_sqlite_runtime(tmp_path, monkeypatch) project, runtime, registry = _write_fixture(tmp_path) if replan: - _configure_autonomous_replan_fixture(project, runtime, registry, stride_strategy="off") + _configure_autonomous_replan_fixture(project, runtime, registry) else: state = project / f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md" state.write_text('---\nstatus: active\nowner_mode: goal\nobjective: "Answer the fixture request."\n---\n\n' @@ -56,10 +56,11 @@ def _fixture(tmp_path, monkeypatch, provider, *, replan=True, capture_dir=None): return project, runtime, registry, turn, guard, original -def _host(tmp_path, *, observation=True, changed=True, fail_once=False): +def _host(tmp_path, *, observation=True, changed=True, fail_once=False, stride_decision=None): # An explicit local process seam, no model or network. It consumes the # actual native prompt and produces an independently validated artifact. - source = ''' + stride_json = json.dumps(stride_decision) + source = f''' import json, pathlib, re, sys args = sys.argv[1:] prompt = sys.stdin.read() @@ -67,16 +68,19 @@ def _host(tmp_path, *, observation=True, changed=True, fail_once=False): counter = root / "host-count.txt" counter.write_text(str(int(counter.read_text()) + 1 if counter.exists() else 1)) (root / "received.txt").write_text(prompt) -(root / "plan.json").write_text(json.dumps({"inputs": [17, 25]})) -vision = {"schema_version": "goal_vision_replan_contract_v0", "state": "active", - "vision_patch": {"acceptance_summary": "Use the validated plan; retain the future monitor.", - "advancement_policy": "as_needed"}, - "path_delta": {"schema_version": "goal_path_delta_v0", "outcome": "replan", +(root / "plan.json").write_text(json.dumps({{"inputs": [17, 25]}})) +vision = {{"schema_version": "goal_vision_replan_contract_v0", "state": "active", + "vision_patch": {{"acceptance_summary": "Use the validated plan; retain the future monitor.", + "advancement_policy": "as_needed"}}, + "path_delta": {{"schema_version": "goal_path_delta_v0", "outcome": "replan", "prior_assumption": "Another unchanged probe might improve the plan.", "observed_reality": "The verified plan makes another probe unnecessary.", "changed": ["Use the verified plan instead of repeating the probe."], - "evidence_refs": ["fixture:validated-plan"]}} -candidate = {"schema_version": "loopx_turn_result_v0", + "evidence_refs": ["fixture:validated-plan"]}}}} +stride = {stride_json} +if stride is not None: + vision["stride_decision"] = stride +candidate = {{"schema_version": "loopx_turn_result_v0", "turn_key": re.search(r'"turn_key":"([^"]+)"', prompt).group(1), "completed_phases": ["host_execute", "typed_result"], "result_kind": "replan_required", "classification": "fixture_bound_planning", @@ -85,13 +89,13 @@ def _host(tmp_path, *, observation=True, changed=True, fail_once=False): "next_action": "Use the verified plan.", "delivery_batch_scale": "single_surface", "delivery_outcome": "outcome_progress", "path_delta_mode": "material_replan", "agent_vision_json": json.dumps(vision), "vision_unchanged_reason": "", - "progress_observation_json": json.dumps({"schema_version": "typed_progress_observation_v0", + "progress_observation_json": json.dumps({{"schema_version": "typed_progress_observation_v0", "result_class": "advanced", "surface_id": "surface-validated-plan", "hypothesis_id": "hypothesis-existing", "probe_kind": "probe-existing", - "evidence_ids": ["fixture:validated-plan"]}), - "work_evidence": ["artifact:plan.json"], "validation_evidence": ["check:plan-inputs"]} + "evidence_ids": ["fixture:validated-plan"]}}), + "work_evidence": ["artifact:plan.json"], "validation_evidence": ["check:plan-inputs"]}} pathlib.Path(args[args.index("--output-last-message") + 1]).write_text(json.dumps(candidate)) -print(json.dumps({"type": "thread.started", "thread_id": "bound-planning-session"}), flush=True) +print(json.dumps({{"type": "thread.started", "thread_id": "bound-planning-session"}}), flush=True) ''' if not observation: source = source.replace('pathlib.Path(args[args.index', 'candidate.pop("progress_observation_json")\npathlib.Path(args[args.index') @@ -129,7 +133,7 @@ def test_bound_todoless_planning_executes_and_settles_once(tmp_path, monkeypatch project, runtime, registry, turn, guard, original = _fixture(tmp_path, monkeypatch, provider) identity = guard["heartbeat_receipt"]["settlement_identity"] assert identity["binding_kind"] == "autonomous_replan" - host = _host(tmp_path) + host = _host(tmp_path, stride_decision=guard["replan_action_packet"]["stride_control"]["minimal_example"]) code, result = _run_turn(project, runtime, registry, host, turn=turn) assert code == 0 and result["status"] == "committed", json.dumps(result, indent=2) [journal_path] = (runtime / "goals" / GOAL_ID / "turns").glob("*.json") @@ -278,8 +282,8 @@ def test_unbound_request_does_not_gain_a_planning_binding(tmp_path, monkeypatch, @pytest.mark.parametrize("provider", ["file", "sqlite"]) def test_explicit_retry_keeps_the_bound_planning_session(tmp_path, monkeypatch, provider): - project, runtime, registry, turn, _guard, _original = _fixture(tmp_path, monkeypatch, provider) - host = _host(tmp_path, fail_once=True) + project, runtime, registry, turn, guard, _original = _fixture(tmp_path, monkeypatch, provider) + host = _host(tmp_path, fail_once=True, stride_decision=guard["replan_action_packet"]["stride_control"]["minimal_example"]) code, failed = _run_turn(project, runtime, registry, host, turn=turn) assert code == 1 and failed["result_kind"] == "host_failure", failed assert (project / "host-count.txt").read_text() == "1" diff --git a/tests/control_plane/test_vision_checkpoint_runtime.py b/tests/control_plane/test_vision_checkpoint_runtime.py index bdbe289fc9..d96e234b9e 100644 --- a/tests/control_plane/test_vision_checkpoint_runtime.py +++ b/tests/control_plane/test_vision_checkpoint_runtime.py @@ -81,7 +81,6 @@ def call(method: str, params: dict[str, object]) -> dict[str, object]: "existing_agent_vision": None, "merge_patch": True, "require_path_delta_for_durable_change": True, - "allow_terminal_stride_path": False, }, } diff --git a/tests/control_plane/test_work_yardstick_cli.py b/tests/control_plane/test_work_yardstick_cli.py index 00eb5fe4f2..6f75d5f02a 100644 --- a/tests/control_plane/test_work_yardstick_cli.py +++ b/tests/control_plane/test_work_yardstick_cli.py @@ -118,7 +118,7 @@ def test_bound_benchmark_replan_opening_shows_scoped_reversal(tmp_path, monkeypa project, runtime, path = setup(tmp_path, active=True, provider=provider, write_scope=scope) run(project, runtime, path, "configure-goal", "--goal-id", GOAL_ID, "--execution-replan-after-turns", "1", - "--execution-stride-strategy", "evidence_conditioned_v1", "--execute") + "--execute") finding = attachment() profiles = finding["work_yardstick_decision"] profiles["proxy"]["comparison_scope"] = "validation:screen-slice" @@ -878,7 +878,7 @@ def test_measured_yardstick_changes_next_work_from_local_screening_to_a_whole_go "--document", str(acceptance), "--operation-id", "declare-encoding", "--expected-provider-revision", before["provider_revision"], "--execute") run(project, runtime, path, "configure-goal", "--goal-id", GOAL_ID, "--execution-replan-after-turns", "2", - "--execution-stride-strategy", "evidence_conditioned_v1", "--execute") + "--execute") payload = ["repeated-entry"] * 24 + ["other-entry"] * 24 def encode(value): diff --git a/tests/control_plane_ts/progress_delta.test.ts b/tests/control_plane_ts/progress_delta.test.ts index 8ab41c1f88..71e2a80a5c 100644 --- a/tests/control_plane_ts/progress_delta.test.ts +++ b/tests/control_plane_ts/progress_delta.test.ts @@ -120,10 +120,24 @@ test("terminal class changes count, while no-followup ignores complete-flag chur {...terminal, coverage_complete: false})).accepted, false); }); +const testObligationId = "replan-" + "1".repeat(16); +const testContextId = "replan-context-" + "1".repeat(24); +const testStrideDecision = {schema_version: "stride_decision_v2", strategy_version: "evidence_conditioned_v1", + reference_context_id: testContextId, reference_obligation_id: testObligationId, basis: "uncertain_evidence", action: "verify", + axes: { + work_slice: {plan: "Run one bounded verification slice.", reason: "Need fresh evidence before expanding."}, + route_distance: {plan: "Keep current mechanism fixed while checking attribution.", reason: "Isolate the new hypothesis."}, + validation_scope: {plan: "Compare on the same baseline inputs.", reason: "Ensure comparable evidence."}}, + next_probe: {scope: "Single hypothesis check.", prediction: "New evidence confirms the hypothesis.", + adoption_criterion: "Distinct evidence id observed.", cost_bound: "One probe.", minimum_evidence: "Fresh attributed result."}}; +const strideStopVision = {vision_patch: {acceptance_summary: "Evidence review recorded"}, + path_delta: {outcome: "stop", evidence_refs: ["evidence-new"]}, stride_decision: testStrideDecision}; + test("the effect entrypoint consumes normalized source and refuses caller-supplied outcomes", () => { - const obligation = {triggers: [{kind: "external_progress_review_drift"}]}; + const obligation = {obligation_id: testObligationId, triggers: [{kind: "external_progress_review_drift"}], + replan_context: {context_id: testContextId}}; const qualify = (progress_source: JsonObject | null, patch: JsonObject = {}) => - projectReplanWriteback({operation: "qualify", obligation, progress_source, ...patch}); + projectReplanWriteback({operation: "qualify", obligation, progress_source, agent_vision: strideStopVision, ...patch}); const renamed = observation(2, {result_class: "advanced", hypothesis_id: "hypothesis-renamed"}); assert.equal(qualify(null).accepted, false); assert.equal(qualify(source(renamed, baseline)).reason_code, "progress_identity_without_new_evidence"); @@ -168,9 +182,10 @@ test("fresh Vision cannot bypass missing attribution, while a false coverage fla const carrier = {schema_version: "typed_progress_observation_v0", result_class: "unchanged", fingerprint: "0000000000000001"}; const qualify = (current: JsonObject) => projectReplanWriteback({operation: "qualify", - obligation: {triggers: [{kind: "external_progress_review_drift"}]}, progress_source: source(current), + obligation: {obligation_id: testObligationId, triggers: [{kind: "external_progress_review_drift"}], + replan_context: {context_id: testContextId}}, progress_source: source(current), agent_vision: {vision_patch: {acceptance_summary: "Retain the evidenced path"}, - path_delta: {outcome: "continue", evidence_refs: ["evidence-path"]}}}); + path_delta: {outcome: "continue", evidence_refs: ["evidence-path"]}, stride_decision: testStrideDecision}}); for (const current of [carrier, {...carrier, unknown_identity: "todo-progress"}]) { assert.throws(() => qualify(current), /stable work, coverage or evidence field/); } diff --git a/tests/control_plane_ts/replan_context.test.ts b/tests/control_plane_ts/replan_context.test.ts index 5584f95e6b..3c8592a3af 100644 --- a/tests/control_plane_ts/replan_context.test.ts +++ b/tests/control_plane_ts/replan_context.test.ts @@ -648,9 +648,11 @@ test("stall frontier projects its current strategy through the shared outcome ow const enabled = projectReplanContext({...request, obligation, stride_strategy: "evidence_conditioned_v1"}); assert.ok(((enabled.uncovered_frontier as JsonObject).required_any_of as string[]) .includes("fresh_vision_path_outcome")); + // Legacy "off" input is accepted on read/transport but cannot opt live contexts out of stride. const off = projectReplanContext({...request, obligation, stride_strategy: "off"}); + assert.equal(off.stride_strategy, "evidence_conditioned_v1"); assert.equal(((off.uncovered_frontier as JsonObject).required_any_of as string[]) - .includes("fresh_vision_path_outcome"), false); + .includes("fresh_vision_path_outcome"), true); const restricted = projectReplanContext({...request, stride_strategy: "evidence_conditioned_v1", obligation: {...obligation, satisfying_semantic_outcomes: ["new_runnable_successor"]}}); assert.deepEqual((restricted.uncovered_frontier as JsonObject).required_any_of, ["new_runnable_successor"]); @@ -674,7 +676,7 @@ test("generic followthrough is available with strategy off without enabling stri } assert.deepEqual(validateReplanContext({...enabled, stride_strategy: "off"}).decision_followthrough, enabled.decision_followthrough); - assert.notEqual(enabled.context_id, off.context_id); + assert.equal(enabled.context_id, off.context_id); for (const field of ["evidence", "coverage_ledger", "uncovered_frontier", "evidence_count"]) { assert.deepEqual(enabled[field], off[field]); } diff --git a/tests/control_plane_ts/replan_semantics.test.ts b/tests/control_plane_ts/replan_semantics.test.ts index 7b80c35726..177675986d 100644 --- a/tests/control_plane_ts/replan_semantics.test.ts +++ b/tests/control_plane_ts/replan_semantics.test.ts @@ -22,9 +22,26 @@ test("capability evidence is not a default exit or a generic progress claim", () import { visionAuthoringContract } from "../../loopx/control_plane/goals/vision_checkpoint.ts"; import type { JsonObject } from "../../loopx/control_plane/effect_program.ts"; -const obligation = {triggers: [{kind: "required_agent_vision_missing"}]}; +const defaultObligationId = "replan-1111111111111111"; +const defaultContextId = "replan-context-" + "1".repeat(24); +const obligation = {obligation_id: defaultObligationId, triggers: [{kind: "required_agent_vision_missing"}]}; +const strideDecision = (obligationId = defaultObligationId, contextId = defaultContextId) => ({ + schema_version: "stride_decision_v2", strategy_version: "evidence_conditioned_v1", + reference_context_id: contextId, reference_obligation_id: obligationId, + basis: "unexplained_gap", action: "switch", axes: { + work_slice: {plan: "Compare the bounded alternative.", reason: "Current evidence leaves the gap open."}, + route_distance: {plan: "Test a distinct mechanism.", reason: "Local tuning did not close the gap."}, + validation_scope: {plan: "Compare on the same inputs.", reason: "Controlled comparison separates mechanisms."}}, + next_probe: { + scope: "Run one bounded comparison.", prediction: "Alternative explains the gap.", + adoption_criterion: "Keep verified gain.", cost_bound: "One bounded run.", + minimum_evidence: "Executed controlled comparison."}}); const vision = {vision_patch: {acceptance_summary: "Observed permission boundary"}, - path_delta: {outcome: "continue", evidence_refs: ["evidence-permission"]}}; + path_delta: {outcome: "continue", evidence_refs: ["evidence-permission"]}, + stride_decision: strideDecision()}; +const strideStopVision = {vision_patch: {acceptance_summary: "Recorded stride review boundary"}, + path_delta: {outcome: "stop", evidence_refs: ["evidence-permission"]}, + stride_decision: strideDecision()}; test("open-work review guidance does not require configured checks or outcome declarations", () => { for (const kind of ["typed_progress_repeat", "periodic_review_due", "goal_outcome_uncovered"]) { @@ -69,13 +86,11 @@ test("autonomous checkpoints reuse owner review while ordinary checkpoints keep "never forces a pivot", "do not invent work or consume budget merely to stay active"]) { assert.ok(guidance.includes(clause), clause); } - if (stride_strategy === "evidence_conditioned_v1") { - const review = (projection.stride_control as JsonObject).decision_value_review as JsonObject; - const advice = Object.values(review).join(" "); - for (const clause of ["feasible alternative", "complete experiment", "headroom", - "artifact version, input conditions and original budget", "budget, feedback and permission limits"]) { - assert.ok(advice.includes(clause), clause); - } + const review = (projection.stride_control as JsonObject).decision_value_review as JsonObject; + const advice = Object.values(review).join(" "); + for (const clause of ["feasible alternative", "complete experiment", "headroom", + "artifact version, input conditions and original budget", "budget, feedback and permission limits"]) { + assert.ok(advice.includes(clause), clause); } } } @@ -113,7 +128,7 @@ test("a revalidated successor receipt settles only its exact original Turn guard test("receipt-bound reentry keeps original canonical proof separate from the next frontier", () => { const id = "replan-1111111111111111"; - const original = {required: true, obligation_id: id, triggers: [{kind: "periodic_review_due"}]}; + const original = {required: true, obligation_id: id, triggers: [{kind: "long_todo_chain"}]}; const current = {...original, obligation_id: "replan-2222222222222222", triggers: [{kind: "vision_acceptance_gap"}]}; const delta = {schema_version: "replan_semantic_delta_v0", accepted: true, obligation_id: id, successor_todo_id: "todo_independent_successor", @@ -399,7 +414,9 @@ test("missing evidence or acceptance cannot manufacture a fresh path outcome", ( for (const reviewKind of ["long_todo_chain", "periodic_review_due"]) { test(`${reviewKind} accepts its evidence-linked vision route and retains progress exits`, () => { - const chain = {triggers: [{kind: reviewKind}]}; + const chain = {obligation_id: defaultObligationId, triggers: [{kind: reviewKind}], + replan_context: {context_id: defaultContextId}}; + const requiresStride = reviewKind === "periodic_review_due"; const projection = projectReplanSemantics({operation: "requirements", obligation: chain}); assert.match(String(projection.cli_semantic_args), /--agent-vision-json/); assert.equal(projectReplanSemantics({operation: "qualify", obligation: chain, @@ -411,8 +428,15 @@ for (const reviewKind of ["long_todo_chain", "periodic_review_due"]) { observation_delta: {delta_kinds: [], evidence_novel: false}}).accepted, true); assert.match(String((projection.writeback_contract as JsonObject).rule), /First reuse observed evidence valid for current source\/acceptance/); for (const outcome of ["new_surface", "new_hypothesis", "new_probe_family", "new_runnable_successor"]) { - assert.equal(projectReplanSemantics({operation: "qualify", obligation: chain, - observation_delta: {delta_kinds: [outcome]}}).accepted, true); + if (requiresStride) { + assert.equal(projectReplanSemantics({operation: "qualify", obligation: chain, + observation_delta: {delta_kinds: [outcome]}}).reason_code, "stride_decision_required"); + assert.equal(projectReplanSemantics({operation: "qualify", obligation: chain, + agent_vision: strideStopVision, observation_delta: {delta_kinds: [outcome]}}).accepted, true); + } else { + assert.equal(projectReplanSemantics({operation: "qualify", obligation: chain, + observation_delta: {delta_kinds: [outcome]}}).accepted, true); + } } for (const incomplete of [{vision_patch: vision.vision_patch}, {...vision, path_delta: {outcome: "replan", evidence_refs: []}}, @@ -423,14 +447,14 @@ for (const reviewKind of ["long_todo_chain", "periodic_review_due"]) { // A stricter source, mixed vision duty or unrelated trigger keeps its policy. for (const restricted of [ {...chain, satisfying_semantic_outcomes: ["new_runnable_successor"]}, - {triggers: [...chain.triggers, {kind: "goal_acceptance_unbound"}]}, - {triggers: [{kind: "typed_progress_repeat", text: reviewKind}]}, + {...chain, triggers: [...chain.triggers, {kind: "goal_acceptance_unbound"}]}, + {...chain, triggers: [{kind: "monitor_no_change_streak", text: reviewKind}]}, ]) { assert.equal(projectReplanSemantics({operation: "qualify", obligation: restricted, agent_vision: vision}).accepted, false); } assert.equal(projectReplanSemantics({operation: "qualify", - obligation: {triggers: [...chain.triggers, ...obligation.triggers]}, + obligation: {...chain, triggers: [...chain.triggers, ...obligation.triggers]}, observation_delta: {delta_kinds: ["new_surface"]}}).accepted, false); }); @@ -439,10 +463,11 @@ for (const reviewKind of ["long_todo_chain", "periodic_review_due"]) { test("explicit outcome restriction remains authoritative; trigger prose is not", () => { assert.deepEqual(requiredSemanticOutcomes({satisfying_semantic_outcomes: ["new_runnable_successor", "new_runnable_successor"]}), ["new_runnable_successor"]); assert.throws(() => requiredSemanticOutcomes({satisfying_semantic_outcomes: ["unrecognized"]}), /unknown typed outcome/); - const prose = {triggers: [{kind: "typed_progress_repeat", text: "required_agent_vision_missing"}]}; + const prose = {obligation_id: defaultObligationId, replan_context: {context_id: defaultContextId}, + triggers: [{kind: "typed_progress_repeat", text: "required_agent_vision_missing"}]}; assert.equal(requiredSemanticOutcomes(prose).includes("new_surface"), true); assert.equal(projectReplanSemantics({operation: "qualify", obligation: prose, - observation_delta: {delta_kinds: ["new_surface"]}}).accepted, true); + agent_vision: strideStopVision, observation_delta: {delta_kinds: ["new_surface"]}}).accepted, true); }); test("stale Goal Acceptance cannot be discharged by unrelated progress or a vision patch", () => { @@ -482,20 +507,21 @@ test("terminal input projection supplies coverage and vision without widening re }); test("external progress review: renamed identifiers discharge only behind new evidence; the plan may stand on evidence", () => { - const review = {triggers: [{kind: "external_progress_review_drift", model_authority: "none"}]}; + const review = {obligation_id: defaultObligationId, replan_context: {context_id: defaultContextId}, + triggers: [{kind: "external_progress_review_drift", model_authority: "none"}]}; const projection = projectReplanSemantics({operation: "requirements", obligation: review}); const required = projection.required_any_of as string[]; assert.equal(required.includes("fresh_vision_path_outcome"), true); for (const outcome of ["new_surface", "new_hypothesis", "new_probe_family", "new_concrete_blocker", "coverage_backed_no_followup"]) { assert.equal(required.includes(outcome), true, outcome); } - assert.match(String(projection.cli_semantic_args), /--progress-hypothesis-id/); + assert.match(String(projection.cli_semantic_args), /--agent-vision-json/); const contract = projection.writeback_contract as Record; assert.equal(contract.identity_outcomes_require_new_evidence, true); assert.match(String(contract.alternative_cli_semantic_args), /--agent-vision-json/); assert.deepEqual(contract.vision_authoring, visionAuthoringContract(true)); - const qualify = (observation_delta?: Record, agent_vision?: Record) => + const qualify = (observation_delta?: Record, agent_vision: Record = strideStopVision) => projectReplanSemantics({operation: "qualify", obligation: review, observation_delta, agent_vision}); for (const identity of ["new_surface", "new_hypothesis", "new_probe_family"]) { const refused = qualify({delta_kinds: [identity], evidence_novel: false}); @@ -542,7 +568,9 @@ test("external progress review: renamed identifiers discharge only behind new ev test("known blockers cannot discharge any replan source; independent vision evidence can", () => { for (const kind of ["vision_acceptance_gap", "typed_progress_repeat", "external_progress_review_drift"]) { - const request = {operation: "qualify", obligation: {triggers: [{kind}]}, + const request = {operation: "qualify", obligation: {obligation_id: defaultObligationId, + replan_context: {context_id: defaultContextId}, triggers: [{kind}]}, + agent_vision: strideStopVision, observation_delta: {delta_kinds: ["new_concrete_blocker"], blocker_repeated: true, evidence_novel: true, observation_repeated: false}}; const rejected = projectReplanSemantics(request); @@ -551,35 +579,42 @@ test("known blockers cannot discharge any replan source; independent vision evid assert.deepEqual(rejected.outcomes, []); assert.equal(projectReplanSemantics({...request, observation_delta: {...request.observation_delta, blocker_repeated: false}}).accepted, true); - if (kind !== "typed_progress_repeat") { - const kept = projectReplanSemantics({...request, agent_vision: vision}); - assert.equal(kept.accepted, true); - assert.deepEqual(kept.satisfying_outcomes, ["fresh_vision_path_outcome"]); - } + const kept = projectReplanSemantics({...request, agent_vision: vision}); + assert.equal(kept.accepted, true); + assert.deepEqual(kept.satisfying_outcomes, ["fresh_vision_path_outcome"]); } }); test("the identity rule is scoped to the external review source", () => { - const fuse = {triggers: [{kind: "typed_progress_repeat"}]}; + const fuse = {obligation_id: defaultObligationId, replan_context: {context_id: defaultContextId}, + triggers: [{kind: "typed_progress_repeat"}]}; assert.equal(projectReplanSemantics({operation: "qualify", obligation: fuse, + agent_vision: strideStopVision, observation_delta: {delta_kinds: ["new_hypothesis"], evidence_novel: false}}).accepted, true); assert.equal(projectReplanSemantics({operation: "qualify", obligation: fuse, + agent_vision: strideStopVision, observation_delta: {delta_kinds: ["new_hypothesis"], observation_repeated: true}}).accepted, true); assert.equal((projectReplanSemantics({operation: "requirements", obligation: fuse}).required_any_of as string[]) - .includes("fresh_vision_path_outcome"), false); + .includes("fresh_vision_path_outcome"), true); // A vision duty on the same obligation keeps the stricter vision policy. - const withVision = {triggers: [{kind: "external_progress_review_drift"}, {kind: "required_agent_vision_missing"}]}; + const withVision = {obligation_id: defaultObligationId, replan_context: {context_id: defaultContextId}, + triggers: [{kind: "external_progress_review_drift"}, {kind: "required_agent_vision_missing"}]}; assert.equal(projectReplanSemantics({operation: "qualify", obligation: withVision, + agent_vision: strideStopVision, observation_delta: {delta_kinds: ["new_hypothesis"], evidence_novel: true}}).accepted, false); assert.equal(projectReplanSemantics({operation: "qualify", obligation: withVision, agent_vision: vision}).accepted, true); // An explicit outcome restriction stays authoritative over the source default. - const restricted = {triggers: [{kind: "external_progress_review_drift"}], satisfying_semantic_outcomes: ["new_concrete_blocker"]}; + const restricted = {obligation_id: defaultObligationId, replan_context: {context_id: defaultContextId}, + triggers: [{kind: "external_progress_review_drift"}], satisfying_semantic_outcomes: ["new_concrete_blocker"]}; assert.equal(projectReplanSemantics({operation: "qualify", obligation: restricted, + agent_vision: strideStopVision, observation_delta: {delta_kinds: ["new_hypothesis"], evidence_novel: true}}).accepted, false); assert.equal(projectReplanSemantics({operation: "qualify", obligation: restricted, agent_vision: vision}).accepted, false); // Trigger prose cannot opt into the external review policy. - const prose = {triggers: [{kind: "typed_progress_repeat", text: "external_progress_review_drift"}]}; + const prose = {obligation_id: defaultObligationId, replan_context: {context_id: defaultContextId}, + triggers: [{kind: "typed_progress_repeat", text: "external_progress_review_drift"}]}; assert.equal(projectReplanSemantics({operation: "qualify", obligation: prose, + agent_vision: strideStopVision, observation_delta: {delta_kinds: ["new_hypothesis"], evidence_novel: false}}).accepted, true); }); @@ -613,19 +648,17 @@ test("planning advice cannot discharge a replan or widen source-specific exits", }); -test("stride format replaces duplicate strategy advice and never discharges a semantic review", () => { +test("stride format is unconditional across plain and historical off contexts and never discharges a semantic review", () => { const plain = {triggers: [{kind: "typed_progress_repeat"}]}; const base = projectReplanSemantics({operation: "requirements", obligation: plain}); const off = projectReplanSemantics({operation: "requirements", obligation: { ...plain, replan_context: {stride_strategy: "off"}}}); - assert.deepEqual(off, base); const enabled = {...plain, replan_context: {stride_strategy: "evidence_conditioned_v1"}}; const withStrategy = projectReplanSemantics({operation: "requirements", obligation: enabled}); - assert.deepEqual(withStrategy.planning_guidance, base.planning_guidance); - assert.ok(withStrategy.stride_control); - assert.equal(base.stride_control, undefined); - assert.deepEqual(withStrategy.required_any_of, - ["fresh_vision_path_outcome", ...(base.required_any_of as string[])]); + assert.deepEqual(off, base); + assert.deepEqual(withStrategy, base); + assert.ok(base.stride_control); + assert.equal((base.required_any_of as string[]).includes("fresh_vision_path_outcome"), true); assert.equal(projectReplanSemantics({operation: "qualify", obligation: enabled, planning_guidance: withStrategy.planning_guidance}).accepted, false); for (const version of ["future_v2", null, 1]) { diff --git a/tests/control_plane_ts/stride_comparison_selection.test.ts b/tests/control_plane_ts/stride_comparison_selection.test.ts index 4bb8af244c..a842fbce5c 100644 --- a/tests/control_plane_ts/stride_comparison_selection.test.ts +++ b/tests/control_plane_ts/stride_comparison_selection.test.ts @@ -118,10 +118,10 @@ for (const kind of ["periodic_review_due", "typed_progress_repeat", "no_progress assert.equal(projectReplanSemantics({...request, obligation: {...obligation, satisfying_semantic_outcomes: ["new_runnable_successor"]}}).accepted, false, "An explicit source restriction still cannot be satisfied by a fresh path alone."); - const off = {...obligation, replan_context: {stride_strategy: "off"}}; - assert.equal(projectReplanSemantics({operation: "qualify", obligation: off, - observation_delta: successor}).accepted, true); - assert.equal(projectReplanSemantics({operation: "transition_eligibility", obligation: off}).allowed, true); + const legacyOff = {...obligation, replan_context: {stride_strategy: "off"}}; + assert.equal(projectReplanSemantics({operation: "qualify", obligation: legacyOff, + observation_delta: successor}).accepted, false); + assert.equal(projectReplanSemantics({operation: "transition_eligibility", obligation: legacyOff}).allowed, false); }); } @@ -139,11 +139,11 @@ test("explicit selection remains optional and cannot be turned into authority or const off = context(projectExploreTurnContext({...input, graph_enabled: false, harness_gate: {enabled: false}, plan: {}})); assert.equal(off.explore_basis, undefined); assert.equal(qualify(off, proposal).accepted, false); - const disabledStrategy = projectReplanContext({operation: "project", goal_id: goal, agent_id: agent, rows: [], + const legacyOffStrategy = projectReplanContext({operation: "project", goal_id: goal, agent_id: agent, rows: [], goal_facts: {}, obligation: {obligation_id: obligationId}, stride_strategy: "off", explore_context: projectExploreTurnContext(input)}); - assert.equal(disabledStrategy.explore_basis, undefined); - assert.equal(qualify(disabledStrategy, proposal).accepted, false); + assert.equal(legacyOffStrategy.stride_strategy, "evidence_conditioned_v1"); + assert.ok(legacyOffStrategy.explore_basis); const nonperiodic = {operation: "qualify", obligation: {obligation_id: obligationId, triggers: [{kind: "vision_acceptance_gap"}], replan_context: ctx}, agent_vision: {stride_decision: proposal, todo_delta: ["retain:todo_other"]}, diff --git a/tests/control_plane_ts/stride_explore_pagination.test.ts b/tests/control_plane_ts/stride_explore_pagination.test.ts index ae081568af..1d6fd17965 100644 --- a/tests/control_plane_ts/stride_explore_pagination.test.ts +++ b/tests/control_plane_ts/stride_explore_pagination.test.ts @@ -64,10 +64,14 @@ test("supplemental citations keep available evidence distinct from unreadable or assert.deepEqual(projectExploreTurnContext({...input, graph_enabled: false, review_pages: [page]}).review_pages, []); const withoutPages = {...proposal, explore_review: {...proposal.explore_review as JsonObject}}; delete (withoutPages.explore_review as JsonObject).result_pages; - const off = projectReplanContext({operation: "project", goal_id: goal, agent_id: agent, rows: [], + const legacyOff = projectReplanContext({operation: "project", goal_id: goal, agent_id: agent, rows: [], goal_facts: {}, obligation: null, stride_strategy: "off", explore_context: first}); - assert.equal(off.explore_basis, undefined); - assert.equal(off.explore_result_pages, undefined); + assert.equal(legacyOff.stride_strategy, "evidence_conditioned_v1"); + assert.ok(legacyOff.explore_basis); + const disabledExplore = projectReplanContext({operation: "project", goal_id: goal, agent_id: agent, rows: [], + goal_facts: {}, obligation: null, explore_context: projectExploreTurnContext({...input, graph_enabled: false, harness_gate: {enabled: false}, plan: {}})}); + assert.equal(disabledExplore.explore_basis, undefined); + assert.equal(disabledExplore.explore_result_pages, undefined); const [, before] = normalizeStrideDecision(withoutPages); const [, after] = normalizeStrideDecision(proposal); assert.equal(Object.values(after).reduce((a,b) => a+b, 0) - Object.values(before).reduce((a,b) => a+b, 0), diff --git a/tests/control_plane_ts/stride_policy.test.ts b/tests/control_plane_ts/stride_policy.test.ts index ca7412ea68..582826db32 100644 --- a/tests/control_plane_ts/stride_policy.test.ts +++ b/tests/control_plane_ts/stride_policy.test.ts @@ -38,8 +38,8 @@ test("an absent recorded decision roundtrips without satisfying an enabled strid assert.equal(missing.accepted, false, kind); assert.equal(missing.reason_code, "stride_decision_required", kind); assert.equal(projectReplanSemantics({operation: "qualify", obligation: { - ...obligation, replan_context: {stride_strategy: "off"}}, - observation_delta, agent_vision: vision}).accepted, true, kind); + ...obligation, replan_context: {stride_strategy: "off", context_id: contextId}}, + observation_delta, agent_vision: vision}).reason_code, "stride_decision_required", kind); } } for (const value of [false, 0, "", [], {}]) { @@ -119,8 +119,8 @@ test("concrete independent plans retain action choice and fit the shared vision assert.deepEqual(decision.axes, proposal.axes); assert.equal(decision.action, "switch"); } - assert.equal(strideControlContract({stride_strategy: "off"}), null); - const contract = strideControlContract({stride_strategy: "evidence_conditioned_v1"})!; + assert.equal(strideControlContract({stride_strategy: "off"}).strategy_version, "evidence_conditioned_v1"); + const contract = strideControlContract({stride_strategy: "evidence_conditioned_v1"}); assert.deepEqual(contract.actions, ["grow", "switch", "verify"]); assert.equal(Object.hasOwn(contract, "adjustments"), false); const prepared = buildVisionCheckpoint(request); @@ -131,8 +131,8 @@ test("concrete independent plans retain action choice and fit the shared vision }); test("goal-value questions are enabled review input, not persisted decisions or extra admission gates", () => { - assert.equal(strideControlContract({stride_strategy: "off"}), null); - const contract = strideControlContract({stride_strategy: "evidence_conditioned_v1"}, proposal.reference_obligation_id)!; + assert.equal(strideControlContract({stride_strategy: "off"}).strategy_version, "evidence_conditioned_v1"); + const contract = strideControlContract({stride_strategy: "evidence_conditioned_v1"}, proposal.reference_obligation_id); assert.deepEqual(Object.keys(contract.decision_value_review as object), ["work_slice", "route_distance", "validation_scope"]); const validation = (contract.decision_value_review as Record).validation_scope; @@ -205,7 +205,7 @@ test("an accepted schema and vector do not authorize work or certify gain; stale assert.equal(missing.accepted, false); assert.equal(missing.reason_code, "stride_decision_required"); assert.equal(projectReplanSemantics({operation: "qualify", obligation: {...obligation, - replan_context: {stride_strategy: "off"}}, agent_vision: legacyVision}).accepted, true); + replan_context: {stride_strategy: "off", context_id: contextId}}, agent_vision: legacyVision}).reason_code, "stride_decision_required"); assert.equal(stale.accepted, false); assert.equal(stale.reason_code, "stride_reference_obligation_mismatch"); assert.equal(projectReplanSemantics({operation: "qualify", obligation, stride_decision: proposal}).accepted, false); @@ -226,7 +226,7 @@ for (const kind of decisionReviewTriggers) test(`${kind} records stride even whe assert.equal(projectReplanSemantics({operation: "qualify", obligation, observation_delta, agent_vision: authored}).accepted, true, outcome); assert.equal(projectReplanSemantics({operation: "qualify", obligation: {...obligation, - replan_context: {stride_strategy: "off"}}, observation_delta}).accepted, true, outcome); + replan_context: {stride_strategy: "off", context_id: contextId}}, observation_delta}).reason_code, "stride_decision_required", outcome); } const stale = projectReplanSemantics({operation: "qualify", obligation, observation_delta: {delta_kinds: ["new_concrete_blocker"]}, @@ -258,10 +258,7 @@ for (const kind of decisionReviewTriggers) test(`${kind} records stride even whe for (const kind of decisionReviewTriggers) test(`${kind} can record a terminal decision without manufacturing a continuing path`, () => { const terminalPacket = {...packet, state: "no_followup", path_delta: {...packet.path_delta, outcome: "stop"}}; - assert.throws(() => buildVisionCheckpoint({...request, agent_vision_packet: terminalPacket}), /stride_decision requires/); - assert.throws(() => buildVisionCheckpoint({...request, allow_terminal_stride_path: "true", - agent_vision_packet: terminalPacket}), /allow_terminal_stride_path/); - const terminal = buildVisionCheckpoint({...request, allow_terminal_stride_path: true, + const terminal = buildVisionCheckpoint({...request, agent_vision_packet: terminalPacket}).agent_vision; const obligation = {obligation_id: proposal.reference_obligation_id, triggers: [{kind}], @@ -288,7 +285,7 @@ for (const kind of decisionReviewTriggers) test(`${kind} cannot be silently sett selected_obligation_id: proposal.reference_obligation_id, transition_candidates: [candidate]}; assert.equal(projectReplanSemantics({...transition, stride_strategy: "evidence_conditioned_v1"}).semantic_delta, null); - assert.deepEqual(projectReplanSemantics({...transition, stride_strategy: "off"}).semantic_delta, semantic_delta); + assert.equal(projectReplanSemantics({...transition, stride_strategy: "off"}).semantic_delta, null); const bound = projectReplanSemantics({operation: "receipt_bound_obligation", guard_scoped: true, selected_obligation_id: proposal.reference_obligation_id, current_obligation: obligation, transition_candidates: [candidate], replay_phase: "open", stride_strategy: "evidence_conditioned_v1"}); @@ -394,7 +391,7 @@ test("recorded fixed-vector decisions remain readable but cannot be newly author assert.equal(projectReplanSemantics({operation: "qualify", obligation: {obligation_id: proposal.reference_obligation_id, triggers: [{kind: "vision_acceptance_gap"}], replan_context: {stride_strategy: "evidence_conditioned_v1"}}, agent_vision: oldVision}).accepted, false); assert.equal(projectReplanSemantics({operation: "qualify", obligation: {obligation_id: proposal.reference_obligation_id, - triggers: [{kind: "vision_acceptance_gap"}], replan_context: {stride_strategy: "off"}}, agent_vision: oldVision}).accepted, true); + triggers: [{kind: "vision_acceptance_gap"}], replan_context: {stride_strategy: "off"}}, agent_vision: oldVision}).reason_code, "stride_decision_required"); assert.throws(() => normalizeRecordedStrideDecision({...recorded, axes: {work_slice: "grow"}}), /historical/); }); @@ -436,7 +433,7 @@ test("independent v1 records preserve their values but cannot satisfy a current assert.equal(projectReplanSemantics({operation: "qualify", obligation, agent_vision: {...packet, stride_decision: historical}}).reason_code, "stride_decision_required"); assert.equal(projectReplanSemantics({operation: "qualify", obligation: {...obligation, - replan_context: {stride_strategy: "off"}}, agent_vision: {...packet, stride_decision: historical}}).accepted, true); + replan_context: {stride_strategy: "off"}}, agent_vision: {...packet, stride_decision: historical}}).reason_code, "stride_decision_required"); assert.throws(() => normalizeStrideDecision({...historical, action: "verify"}), /unsupported/); const withReviews = {...proposal, previous_review: {reference_decision_ref: "replan-decision-" + "b".repeat(24), adoption: "executed", @@ -456,11 +453,10 @@ test("shared replan guidance retains stride-off isolation and bounded enabled au replan_context: {stride_strategy: strategy, context_id: contextId}}}); const off = requirements("off"); const enabled = requirements("evidence_conditioned_v1"); - assert.equal(Object.hasOwn(off, "stride_control"), false); - assert.deepEqual(off.planning_guidance, enabled.planning_guidance); + assert.deepEqual(off, enabled); assert.ok((off.planning_guidance as string[]).length > 0); - assert.equal(((off.writeback_contract as Record).required_fields as string[]) - .includes("agent_vision.stride_decision"), false); + assert.ok(((off.writeback_contract as Record).required_fields as string[]) + .includes("agent_vision.stride_decision")); assert.ok(((enabled.writeback_contract as Record).required_fields as string[]) .includes("agent_vision.stride_decision")); const contract = strideControlContract({stride_strategy: "evidence_conditioned_v1", context_id: contextId}, proposal.reference_obligation_id)!; diff --git a/tests/test_chat_goal_configuration_api.py b/tests/test_chat_goal_configuration_api.py index 4734f1fdd7..4fb46c0aeb 100644 --- a/tests/test_chat_goal_configuration_api.py +++ b/tests/test_chat_goal_configuration_api.py @@ -323,7 +323,6 @@ def test_machine_inheritable_goal_capabilities_can_clear_their_overrides() -> No assert _goal_capability_options("todo_replan_cadence", None) == { "clear_execution_replan_after_todos": True, "clear_execution_replan_after_turns": True, - "clear_execution_stride_strategy": True, "clear_execution_planning_horizon_goal": True, "clear_execution_yardstick_enabled": True, } diff --git a/tests/test_chat_machine_configuration_api.py b/tests/test_chat_machine_configuration_api.py index fc19e80717..efdd5967a8 100644 --- a/tests/test_chat_machine_configuration_api.py +++ b/tests/test_chat_machine_configuration_api.py @@ -463,7 +463,6 @@ def test_inspection_lists_registered_namespaces_without_local_refs( "schema_version": "todo_replan_cadence_machine_defaults_v2", "count_unit": "effective_turns", "count": 6, - "stride_strategy": "evidence_conditioned_v1", "planning_horizon_goal": True, "yardstick_enabled": False, } diff --git a/tests/test_host_vision_recovery.py b/tests/test_host_vision_recovery.py index bb795161ac..338ae2c4c0 100644 --- a/tests/test_host_vision_recovery.py +++ b/tests/test_host_vision_recovery.py @@ -153,9 +153,9 @@ def test_bad_vision_is_rejected_before_todo_completion_and_can_be_corrected(tmp_ assert len(spends(runtime)) == 1 -@pytest.mark.parametrize("machine_enabled", [False, True]) -def test_terminal_stride_preflight_uses_effective_strategy_before_todo_effects( - tmp_path, monkeypatch, machine_enabled, +@pytest.mark.parametrize("malformed_stride", [False, True]) +def test_terminal_stride_preflight_validates_before_todo_effects( + tmp_path, monkeypatch, malformed_stride, ): control, project, runtime = control_at(tmp_path) monkeypatch.chdir(project) @@ -165,8 +165,7 @@ def test_terminal_stride_preflight_uses_effective_strategy_before_todo_effects( owner = build_builtin_machine_configuration_registry() configuration = {"schema_version": "loopx_machine_configuration_v0", "namespaces": { "todo_replan_cadence": {"schema_version": "todo_replan_cadence_machine_defaults_v2", - "count_unit": "completed_todos", "count": 1, - "stride_strategy": "evidence_conditioned_v1" if machine_enabled else "off"}}} + "count_unit": "completed_todos", "count": 1}}} preview = configure_machine_configuration( runtime_root=runtime, registry=owner, configuration=configuration) configure_machine_configuration( @@ -188,6 +187,8 @@ def test_terminal_stride_preflight_uses_effective_strategy_before_todo_effects( "adoption_criterion": "Adopt only a verified source outcome.", "cost_bound": "One source and contrary case.", "minimum_evidence": "Source result and contrary-case result."}} + if malformed_stride: + authored["stride_decision"]["action"] = "invalid_action" state = project / "ACTIVE_GOAL_STATE.md" before = state.read_bytes() calls = [] @@ -198,13 +199,13 @@ def recorded(args, **kwargs): return original(args, **kwargs) monkeypatch.setattr(control, "run_cli", recorded) - if machine_enabled: + if not malformed_stride: result = json.loads(control.complete_task("todo_reducer", fixture.AGENT, "Synthetic acceptance", successor_todo_ids=["todo_cli"], agent_vision=authored)) assert result["ok"] is True, result assert len(spends(runtime)) == 1 else: - with pytest.raises(ValueError, match="stride_decision requires an evidence-linked path decision"): + with pytest.raises(ValueError, match="stride_decision"): control.complete_task("todo_reducer", fixture.AGENT, "Synthetic acceptance", successor_todo_ids=["todo_cli"], agent_vision=authored) assert calls == [] From 2290ff794115757ca605cdb6a61e6100231c53af Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:45:24 +0800 Subject: [PATCH 2/3] fix(stride): preserve pre-upgrade off turn settlement and v2 rollback readability Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../hierarchical-agent-stride-control-v0.md | 36 +- ...rarchical-agent-stride-control-v0.zh-CN.md | 26 +- docs/quota-allocation.md | 12 +- .../goal-vision-replan-contract-v0.md | 15 +- .../todo_replan_cadence/machine_defaults.py | 18 +- .../goals/goal_frontier/__init__.py | 16 + .../goals/goal_frontier/ack_policy.py | 4 + .../control_plane/quota/heartbeat_receipt.py | 24 ++ loopx/control_plane/quota/live_decision.py | 20 +- loopx/control_plane/quota/settlement.py | 9 + loopx/control_plane/quota/settlement_cli.py | 5 + .../quota/settlement_readback.ts | 15 + loopx/control_plane/quota/should_run.py | 2 + .../control_plane/quota/should_run_packet.py | 3 + .../control_plane/quota/should_run_prepare.py | 38 +++ .../autonomous_replan_obligation.py | 6 +- .../work_items/progress_observation.py | 41 ++- .../work_items/replan_semantics.ts | 54 +-- .../work_items/semantic_replan_writeback.py | 34 ++ .../work_items/stride_policy_codec.py | 63 ++++ loopx/quota.py | 17 +- loopx/state_refresh.py | 8 + ...est_machine_configuration_goal_defaults.py | 97 +++++- .../test_quota_settlement_cli.py | 1 + .../test_refresh_state_replan_gate.py | 309 ++++++++++++++++++ .../quota_settlement_readback.test.ts | 27 ++ .../control_plane_ts/replan_semantics.test.ts | 60 ++++ 27 files changed, 885 insertions(+), 75 deletions(-) diff --git a/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.md b/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.md index 3ab1d5625f..79f69c71c3 100644 --- a/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.md +++ b/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.md @@ -893,7 +893,7 @@ times separately. Check whether later work implemented the proposed mechanism; a decision record, saved snapshot or new identifier alone does not establish adoption, restoration or improved results. These are refinements of the existing Agent questions, not new decision fields, score thresholds or settlement gates; -the inherited capability default enables the strategy; explicit off and saved legacy configurations retain their meaning. Identify the remaining authoritative goal gap, its limiting +evidence-conditioned stride is unconditionally active for new Turns, while already-admitted pre-upgrade `off` Turns and saved historical records retain read/settlement semantics. Identify the remaining authoritative goal gap, its limiting component and plausible headroom before choosing the next mechanism. Compare continuation with plausible alternatives that change the limiting assumption or mechanism, including complete cost. A stalled route calls for a discriminating @@ -1055,22 +1055,24 @@ benchmark-specific additions are not installed as Core defaults or checkpoint requirements. This provider treatment must be revision-pinned in comparisons; it does not establish initial-quality parity or long-horizon research gain. -The activation vocabulary and existing Goal/device editor stay unchanged; no -second selectable strategy or policy database is added. Off retains ordinary -projection/review semantics. Both historical v1 decision shapes retain read -compatibility, but cannot discharge a fresh enabled review. Frozen workers retain -their exact source. Pin implementation revisions for comparisons; do not +With the live `stride_strategy` switch removed, `evidence_conditioned_v1` is +unconditionally live for new Turns; no second selectable strategy or policy +database is added. Already-admitted pre-upgrade Turns tied to explicit or +inherited `off` retain their original admitted settlement semantics and identity +across upgrade (File and SQLite), while new Turns on untouched legacy Goals +enter `evidence_conditioned_v1`. Historical v1 and `off` records remain +decodable on read, cannot discharge fresh `evidence_conditioned_v1` reviews, +and frozen workers retain their exact source. Pin implementation revisions for comparisons; do not reinterpret old decisions. The policy seam can evolve when evidence warrants it, without maintaining speculative variants. -For an enabled periodic review or an existing observed-stall review +For a live periodic review or an existing observed-stall review (`typed_progress_repeat`, `no_progress_streak`, `repeated_action_loop`, `external_progress_review_drift`), every settlement path requires a current, source-bound stride decision. Typed progress, successor and terminal results remain valid evidence/outcomes, while a bare Todo successor transition cannot stand in for the review. An evidenced path decision can retain unfinished useful work without a fabricated new progress identifier or Todo. Explicit acceptance -and capability outcome restrictions still apply; explicit off, saved legacy -cadence-only configurations and other sources -retain their prior exit policies. No new detector, threshold or action is added. +and capability outcome restrictions, as well as pre-upgrade receipt-bound `off` +settlement and other sources, retain their prior exit policies. No new detector, threshold or action is added. The frozen [EdgeBench diagnostic window](https://huggingface.co/datasets/songwells/loopxbench/blob/c5dd30bfaa2f5af42ccd7d0ca9ed59b865a81d42/public/edgebench-20261018-v1/diagnostic_windows.csv) reports 902 completed native turns and no submissions over one post-hoc selected @@ -1098,11 +1100,15 @@ Keep dependencies, acceptance, risk, authority and per-Turn settlement boundarie The next review must distinguish declared scope from actual execution, outcome quality and full cost; preserving a plan is not adoption or benefit. -Evidence-conditioned stride is the capability default for inherited configuration. -Explicit off, saved legacy cadence-only configurations and historical records -retain their semantics. Clear overrides to inherit, or select off to roll back; -no installed configuration, frozen worker or historical receipt is rewritten. -The codec's missing historical strategy remains off. Review questions and syntax +Evidence-conditioned stride (`evidence_conditioned_v1`) is unconditionally live +for all new Turns; the live on/off toggle is removed by maintainer authorization. +Already-admitted pre-upgrade `off` Turns retain their original settlement +semantics and identity across upgrade (File and SQLite), and persisted +`todo_replan_cadence_machine_defaults_v2` writes retain `"stride_strategy": "evidence_conditioned_v1"` +on disk so runtime rollback to earlier v2 readers remains readable, while public +APIs, CLI flags, and Dashboard views omit and reject `stride_strategy`. Frozen +workers, historical `off` decisions, and legacy v0/v1 files remain readable +without being rewritten. Review questions and syntax examples remain together; no extra decision fields, strategy versions or machine-enforced semantic classifier are added. Matched continuation must still qualify target benefit and full cost before promotion or synergy claims. diff --git a/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.zh-CN.md b/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.zh-CN.md index 592da2d76e..28b71b2510 100644 --- a/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.zh-CN.md +++ b/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.zh-CN.md @@ -729,7 +729,7 @@ switch(尝试不同机制)或 verify(解决决定扩大或切换的具体 比较须绑定产物版本、输入条件和原预算,区分提交时刻与反馈实际到达时刻,并检查 后续工作是否执行了提议的机制变化。决定记录、快照或新标识本身不证明采用、恢复 或结果改善。这些是既有Agent问题的细化,不增加决策字段、分数阈值或结算门槛; -继承能力配置时策略默认开启,显式关闭和已保存的旧配置保留原语义。先识别仍未满足的 +所有新 Turn 无条件启用依据证据的步幅策略,已准入的升级前 `off` Turn 与历史记录保持原有读取/结算语义。先识别仍未满足的 权威目标、当前瓶颈分量和可能的收益空间,再选择下一机制。比较原路线接续与 改变该瓶颈假设或机制的可行替代路线,并计入完整成本。路线停滞时,应以能区分 这些解释的完整实验推进,不能只继续局部调参。区分干预未执行、局部改善未迁移, @@ -838,17 +838,18 @@ Benchmark 的显式 `loopx-planned` provider 在未修改的规划 packet 外附 这些 benchmark 专用补充不进入 Core 默认值,也不是 checkpoint 要求。比较须固定 该 provider 处理的 revision;它不证明首次质量持平或长程研究收益。 -配置词表和既有 Goal/设备编辑器不变,不加第二个可选版本或策略数据库。off 保持 -普通投影/复盘;两种历史 v1 决策保留原义读取兼容,不能完成新的启用策略复盘; -新提案使用 v2 数据格式,仍只有同一个可选策略,冻结 worker 保持确切源码。比较固定 +移除在线 `stride_strategy` 开关后,`evidence_conditioned_v1` 对所有新 Turn 无条件生效, +不加第二个可选策略或策略数据库。升级前已在显式或继承 `off` 下准入的 Turn 在升级后 +(File 与 SQLite)继续按原结算语义与身份完成写回,未修改的旧 Goal 在新 Turn 起进入 +`evidence_conditioned_v1`。两种历史 v1 与 `off` 决定保留原义读取兼容,不能完成新的 +生效策略复盘;冻结 worker 保持确切源码。比较固定 实现 revision,不重释旧决定;有证据后迭代同一组件,避免维护假设性的策略变体。 -启用策略的周期复盘到期,或既有停滞复核触发时(`typed_progress_repeat`、 +周期复盘到期或既有停滞复核触发时(`typed_progress_repeat`、 `no_progress_streak`、`repeated_action_loop`、`external_progress_review_drift`), -任何结算路径都须留下绑定本次来源的 stride 决定。 +任何新 Turn 的结算路径都须留下绑定本次来源的 stride 决定。 类型化进展、后续任务和终止结果仍可作为证据与结果,但单独的 Todo 后续转换不能 代替复盘。有证据的路径决定可以保留尚未完成的有用工作,不必编造新进展标识或 -Todo。验收和能力 owner 显式限定的结果仍须遵守;显式关闭、已保存的旧版仅周期 -配置和其他来源保持原有 +Todo。验收、能力 owner 显式限定的结果,以及升级前已准入 `off` Turn 的结算和其他来源仍保持原有 出口规则。不增加检测器、阈值或动作。 冻结的 [EdgeBench 诊断窗口](https://huggingface.co/datasets/songwells/loopxbench/blob/c5dd30bfaa2f5af42ccd7d0ca9ed59b865a81d42/public/edgebench-20261018-v1/diagnostic_windows.csv) @@ -870,9 +871,12 @@ Todo。验收和能力 owner 显式限定的结果仍须遵守;显式关闭、 结算边界。下次复盘区分计划范围与实际执行、结果质量和完整成本;保存计划不等于 采用或收益。 -继承能力配置时,依据证据的步幅策略默认开启。显式关闭、已保存的旧版仅周期配置 -及历史记录保持原语义。清除覆盖可恢复继承,显式选择 off 可回退;不重写已安装 -配置、冻结 worker 或历史回执。历史解码中缺失的策略仍按 off 处理。复盘问题和 +经维护者授权移除在线开关后,`evidence_conditioned_v1` 对所有新 Turn 无条件生效。 +升级前已准入的 `off` Turn 在升级后(File 与 SQLite)保持原结算语义与身份;写入 +`todo_replan_cadence_machine_defaults_v2` 设备配置时磁盘上保留 +`"stride_strategy": "evidence_conditioned_v1"` 以保持向旧版 v2 reader 的运行时回退可读性, +而公开 API、CLI 参数与 Dashboard 投影移除且拒绝写入 `stride_strategy`。冻结 worker、 +历史 `off` 决定与旧版 v0/v1 配置保留读取语义而不重写作废。复盘问题和 语法示例仍一起交付,不新增决定字段、策略版本或机器强制语义分类器。目标收益、 完整成本与交互增益仍须通过匹配接续等实验验证后再作结论。 diff --git a/docs/quota-allocation.md b/docs/quota-allocation.md index b2af017427..9aec5b63e4 100644 --- a/docs/quota-allocation.md +++ b/docs/quota-allocation.md @@ -171,11 +171,15 @@ or `completed_todos`) and `count`. Existing v0/v1 configurations remain readable without migrating them on inspection. The stride strategy is not configurable: `evidence_conditioned_v1` is always on and adds evidence-conditioned scope and route advice, with unchanged admission and semantic exits. There is no -`--execution-stride-strategy` flag, Dashboard selector or device field. A +`--execution-stride-strategy` flag or Dashboard selector. A `stride_strategy` value saved by an earlier release (`off` or -`evidence_conditioned_v1`) in a v2 device file or Goal profile still loads, but -it is ignored and dropped the next time that configuration is written; new -writes that include `stride_strategy` are rejected. See the +`evidence_conditioned_v1`) in a v2 device file or Goal profile still loads and +is ignored for new Turns (while already-admitted pre-upgrade receipt-bound `off` +Turns retain their original settlement semantics across upgrade). Rewriting a +Goal profile drops legacy `stride_strategy`, whereas saving a v2 device file +persists `"stride_strategy": "evidence_conditioned_v1"` on disk so runtime rollback +to prior v2 readers stays readable while public projections omit it; new writes +that supply `stride_strategy` are rejected. See the [versioned strategy contract](reference/protocols/goal-vision-replan-contract-v0.md#configure-and-roll-back-the-stride-strategy). It is built into the control plane and needs no provider installation. The CLI, settings readback, quota decision and writeback validation use the same effective configuration. diff --git a/docs/reference/protocols/goal-vision-replan-contract-v0.md b/docs/reference/protocols/goal-vision-replan-contract-v0.md index c58727800f..8525da142a 100644 --- a/docs/reference/protocols/goal-vision-replan-contract-v0.md +++ b/docs/reference/protocols/goal-vision-replan-contract-v0.md @@ -556,8 +556,13 @@ and no separate stride timer. An explicit Goal review unit/count still pins that interval, and clearing the cadence restores live device defaults via the editor or `--clear-execution-replan-after-turns --clear-execution-replan-after-todos --execute`. Legacy saved `stride_strategy` fields in `registry.json` or -`machine_configuration.json` remain readable on load, are ignored at runtime, -and are dropped on rewrite. Activation cannot authorize experiments, spend +`machine/configuration.json` remain readable on load and are ignored for new Turns +(while already-admitted pre-upgrade receipt-bound `off` Turns retain their original +settlement semantics across upgrade). Rewriting a Goal profile drops legacy +`stride_strategy`, whereas saving v2 `machine/configuration.json` persists +`"stride_strategy": "evidence_conditioned_v1"` on disk for rollback compatibility +with prior v2 readers while public projections omit it and reject writes that supply +`stride_strategy`. Activation cannot authorize experiments, spend quota, clone a checkpoint, relax acceptance or rewrite a frozen experiment. 在既有「Goal 复盘与步幅」能力中心中选择设备默认值或明确的 Goal 来配置复盘周期 @@ -565,7 +570,11 @@ quota, clone a checkpoint, relax acceptance or rewrite a frozen experiment. 现为无条件生效的在线策略,不再提供在线开关,也没有第二个独立计时器。显式设置 Goal 计数依据和数量仍会固定该周期,可通过编辑器或 `--clear-execution-replan-after-turns --clear-execution-replan-after-todos --execute` 恢复设备默认值。旧配置文件中残留的 -`stride_strategy` 字段在读取时保持兼容、运行时忽略、重写时移除;历史引用仍可读取。 +`stride_strategy` 字段在读取时保持兼容,并对新 Turn 忽略(升级前已准入的 `off` +回执 Turn 在 File 与 SQLite 上保留原结算语义);重写 Goal 配置时移除旧字段,写入 v2 +`machine/configuration.json` 时磁盘上保留 `"stride_strategy": "evidence_conditioned_v1"` +以保住向旧版 v2 reader 的运行时回退可读性,同时公开投影不暴露且拒绝传入 +`stride_strategy`;历史引用仍可读取。 策略不会授权实验、消耗配额、复制 checkpoint、放宽验收或改写冻结实验。 ### Structured stride control diff --git a/loopx/capabilities/todo_replan_cadence/machine_defaults.py b/loopx/capabilities/todo_replan_cadence/machine_defaults.py index e11081a7c9..4029e76dcb 100644 --- a/loopx/capabilities/todo_replan_cadence/machine_defaults.py +++ b/loopx/capabilities/todo_replan_cadence/machine_defaults.py @@ -57,6 +57,15 @@ def _apply_public_update(_current: Any, update: Mapping[str, Any]) -> dict[str, return dict(update) +def _project_public_todo_replan_cadence(value: Mapping[str, Any]) -> dict[str, Any]: + """Hide persistence-only rollback compatibility fields from public surfaces.""" + return { + key: item + for key, item in value.items() + if key != LEGACY_STRIDE_STRATEGY_KEY + } + + def normalize_replan_cadence_configuration(raw: Mapping[str, Any]) -> dict[str, Any]: if set(raw) == {"completed_todos"}: return { @@ -115,12 +124,17 @@ def normalize_todo_replan_cadence_machine_defaults( expected.add("yardstick_enabled") if set(raw) != expected: raise ValueError("review configuration fields do not match its schema version") - return { + normalized = { "schema_version": version, **normalize_replan_cadence_configuration( {key: value for key, value in raw.items() if key != "schema_version"} ), } + if version == TODO_REPLAN_CADENCE_MACHINE_DEFAULTS_V2: + # Persist `stride_strategy` in v2 machine configuration so rolling back + # to prior releases with strict v2 field sets stays readable. + normalized[LEGACY_STRIDE_STRATEGY_KEY] = "evidence_conditioned_v1" + return normalized def cadence_configuration_value(raw: Mapping[str, Any]) -> dict[str, Any]: @@ -153,7 +167,7 @@ def todo_replan_cadence_machine_configuration_namespace() -> ( } ), normalize=normalize_todo_replan_cadence_machine_defaults, - project_public=lambda value: dict(value), + project_public=_project_public_todo_replan_cadence, apply_public_update=_apply_public_update, title="Goal review and stride", description=( diff --git a/loopx/control_plane/goals/goal_frontier/__init__.py b/loopx/control_plane/goals/goal_frontier/__init__.py index f83e84745e..582a0c37f7 100644 --- a/loopx/control_plane/goals/goal_frontier/__init__.py +++ b/loopx/control_plane/goals/goal_frontier/__init__.py @@ -1426,6 +1426,7 @@ def build_goal_frontier_projection_context_from_status( agent_profile: dict[str, Any] | None = None, receipt_bound_replan_obligation_id: str | None = None, receipt_bound_guard_recorded_at: str | None = None, + receipt_bound_admitted_stride_strategy: str | None = None, replan_explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None = None, ) -> dict[str, Any]: """Build the quota-facing goal-frontier read model. @@ -1591,11 +1592,22 @@ def build_goal_frontier_projection_context_from_status( acceptance_gaps=source_acceptance_gaps, goal_id=goal_id, agent_id=agent_id, runtime_root=status_payload.get("runtime_root"), ) + def _obligation_admitted_stride_strategy(target: dict[str, Any] | None) -> str | None: + target_id = str((target or {}).get("obligation_id") or "").strip() + if ( + receipt_bound_admitted_stride_strategy == "off" + and receipt_bound_replan_obligation_id + and target_id == receipt_bound_replan_obligation_id + ): + return "off" + return None + replan_transition_ack = replan_successor_transition_ack( agent_todo_summary, agent_id=agent_id, replan_obligation=replan_obligation, agent_todo_items=agent_todo_source_items, + admitted_stride_strategy=_obligation_admitted_stride_strategy(replan_obligation), ) # Keep the validated history-obligation transition distinct from any # successor frontier obligation derived below. Exact Turn settlement may @@ -1610,6 +1622,7 @@ def build_goal_frontier_projection_context_from_status( replan_obligation=replan_obligation, acceptance_gaps=source_acceptance_gaps, todo_succession_gap_open=todo_succession_gap_open, + admitted_stride_strategy=_obligation_admitted_stride_strategy(replan_obligation), ) and autonomous_replan_ack_matches_frontier( obligation_ack, @@ -1648,6 +1661,7 @@ def build_goal_frontier_projection_context_from_status( agent_id=agent_id, replan_obligation=frontier_replan_obligation, agent_todo_items=agent_todo_source_items, + admitted_stride_strategy=_obligation_admitted_stride_strategy(frontier_replan_obligation), ) frontier_obligation_ack = frontier_transition_ack or effective_replan_ack frontier_transition_candidate = {"obligation": frontier_replan_obligation, "ack": frontier_transition_ack} @@ -1690,6 +1704,7 @@ def build_goal_frontier_projection_context_from_status( source_ack = replan_successor_transition_ack( agent_todo_summary, agent_id=agent_id, replan_obligation=source, agent_todo_items=agent_todo_source_items, + admitted_stride_strategy=_obligation_admitted_stride_strategy(source), ) frontier_transition_candidate = { "obligation": source, @@ -1724,6 +1739,7 @@ def build_goal_frontier_projection_context_from_status( replan_obligation=frontier_replan_obligation, acceptance_gaps=source_acceptance_gaps, todo_succession_gap_open=todo_succession_gap_open, + admitted_stride_strategy=_obligation_admitted_stride_strategy(frontier_replan_obligation), ) and autonomous_replan_ack_matches_frontier( frontier_obligation_ack, diff --git a/loopx/control_plane/goals/goal_frontier/ack_policy.py b/loopx/control_plane/goals/goal_frontier/ack_policy.py index 9219fa372a..c91a053e5d 100644 --- a/loopx/control_plane/goals/goal_frontier/ack_policy.py +++ b/loopx/control_plane/goals/goal_frontier/ack_policy.py @@ -44,6 +44,7 @@ def autonomous_replan_ack_satisfies_obligation( replan_obligation: dict[str, Any] | None, acceptance_gaps: list[dict[str, Any]] | None, todo_succession_gap_open: bool = False, + admitted_stride_strategy: str | None = None, ) -> bool: """Reject ACKs that miss the obligation's typed semantic outcome.""" @@ -51,6 +52,7 @@ def autonomous_replan_ack_satisfies_obligation( return False if ack.get("source") == "todo_replan_successor_transition" and not replan_successor_transition_allowed( replan_obligation or {}, + admitted_stride_strategy=admitted_stride_strategy, ): return False semantic_delta = ack.get("semantic_delta") if isinstance(ack, dict) else {} @@ -89,6 +91,7 @@ def replan_successor_transition_ack( agent_id: str | None, replan_obligation: dict[str, Any] | None, agent_todo_items: Iterable[dict[str, Any]] | None = None, + admitted_stride_strategy: str | None = None, ) -> dict[str, Any] | None: """Project an exact runnable-successor Todo as the replan receipt. @@ -167,6 +170,7 @@ def replan_successor_transition_ack( return None if not replan_successor_transition_allowed( replan_obligation or {}, + admitted_stride_strategy=admitted_stride_strategy, ): return None if trigger_checkpoints is None: diff --git a/loopx/control_plane/quota/heartbeat_receipt.py b/loopx/control_plane/quota/heartbeat_receipt.py index fbe1fc6ef9..1f94368f4d 100644 --- a/loopx/control_plane/quota/heartbeat_receipt.py +++ b/loopx/control_plane/quota/heartbeat_receipt.py @@ -352,9 +352,24 @@ def ensure_turn_heartbeat_settlement_receipt( if task_lease_epoch is None: details.pop("prepared_lease_epoch", None) if semantic_replan_guard_scoped: + already_bound = ( + effective is not None + and isinstance(effective_details, dict) + and bool( + normalize_todo_replan_obligation_id( + effective_details.get("semantic_replan_obligation_id") + ) + ) + ) details["semantic_replan_obligation_id"] = ( normalized_semantic_replan_obligation_id or "" ) + if ( + normalized_semantic_replan_obligation_id + and not already_bound + and "semantic_replan_stride_strategy" not in details + ): + details["semantic_replan_stride_strategy"] = "evidence_conditioned_v1" if semantic_replan_capability_guard is not None: details["semantic_replan_capability_id"] = semantic_replan_capability_guard["capability_id"] details["semantic_replan_gap_id"] = semantic_replan_capability_guard["gap_id"] @@ -617,6 +632,15 @@ def upgrade_identityless_heartbeat_receipt( # correction explicitly replaces them. corrected_details = dict(effective_details) corrected_details.update(details) + if ( + normalize_todo_replan_obligation_id( + effective_details.get("semantic_replan_obligation_id") + ) + and "semantic_replan_stride_strategy" not in effective_details + ): + # Preserve pre-upgrade identityless replan receipts without injecting + # a post-upgrade stride strategy during binding upgrade. + corrected_details.pop("semantic_replan_stride_strategy", None) corrected_details.update( { "turn_instance_id": turn_instance_id, diff --git a/loopx/control_plane/quota/live_decision.py b/loopx/control_plane/quota/live_decision.py index d5d79f15c0..a23e0b53d0 100644 --- a/loopx/control_plane/quota/live_decision.py +++ b/loopx/control_plane/quota/live_decision.py @@ -8,6 +8,9 @@ from pathlib import Path from typing import Any +from ..work_items.stride_policy_codec import ( + resolve_receipt_bound_stride_strategy, +) from ...quota import build_quota_should_run from ...agent_registry import load_goal_from_registry, registered_agent_ids_for_goal from ...command_invocation import ( @@ -64,6 +67,9 @@ def _receipt_bound_guard_fields( readback: QuotaSettlementReadback | None, obligation_id: str | None, + *, + raw_goal: Mapping[str, Any] | None = None, + runtime_root: Path | None = None, ) -> dict[str, Any]: """Adapt the recorded guard identity and time for the shared decision owner.""" guard = getattr(readback, "semantic_replan_guard", None) @@ -85,6 +91,15 @@ def _receipt_bound_guard_fields( "receipt_bound_admission_event_id": getattr(readback, "admission_event_id", None), "receipt_bound_guard_turn_instance_id": identity.turn_instance_id if identity is not None else None, "receipt_bound_replan_review": guard.get("selected_review_source") if isinstance(guard, Mapping) else None, + "receipt_bound_admitted_stride_strategy": ( + resolve_receipt_bound_stride_strategy( + guard, + raw_goal=raw_goal, + runtime_root=runtime_root, + ) + if guard_scoped + else None + ), "receipt_bound_successor_replan": bool(getattr(readback, "successor_replan_pending", False)), } @@ -899,7 +914,10 @@ def build_live_quota_should_run_decision( settlement_readback.replay_phase if settlement_readback else None ) receipt_bound_guard_fields = _receipt_bound_guard_fields( - settlement_readback, receipt_bound_replan_obligation_id, + settlement_readback, + receipt_bound_replan_obligation_id, + raw_goal=registered_goal, + runtime_root=runtime_root, ) admission_event_id = receipt_bound_guard_fields.pop("receipt_bound_admission_event_id") if ( diff --git a/loopx/control_plane/quota/settlement.py b/loopx/control_plane/quota/settlement.py index d3a37e0fc5..5a76074283 100644 --- a/loopx/control_plane/quota/settlement.py +++ b/loopx/control_plane/quota/settlement.py @@ -367,6 +367,15 @@ def _semantic_replan_guard(value: Any) -> dict[str, Any] | None: raise RuntimeError("selected review source requires a typed object and obligation") # Semantic eligibility and scalar bounds belong to the TS owner. result["selected_review_source"] = dict(review) + if "admitted_stride_strategy" in guard: + admitted_stride = guard["admitted_stride_strategy"] + if ( + selected_obligation_id is None + or not isinstance(admitted_stride, str) + or admitted_stride not in {"evidence_conditioned_v1", "off"} + ): + raise RuntimeError("admitted stride strategy requires a legal strategy and obligation") + result["admitted_stride_strategy"] = admitted_stride return result diff --git a/loopx/control_plane/quota/settlement_cli.py b/loopx/control_plane/quota/settlement_cli.py index c22d45aa3e..cefd6fe61f 100644 --- a/loopx/control_plane/quota/settlement_cli.py +++ b/loopx/control_plane/quota/settlement_cli.py @@ -487,6 +487,11 @@ def quota_rollout_details( "selected_todo_id": normalize_todo_id(selected_todo.get("todo_id")) if selected_todo else None, "replan_obligation_id": replan_obligation_id or "", "semantic_replan_obligation_id": semantic_replan_obligation_id or "", + **( + {"semantic_replan_stride_strategy": "evidence_conditioned_v1"} + if semantic_replan_obligation_id + else {} + ), "target_key": payload.get("target_key") or "", "successor_todo_ids": ",".join( str(successor_id) diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts index 7548dafe24..6c92bf5dc0 100644 --- a/loopx/control_plane/quota/settlement_readback.ts +++ b/loopx/control_plane/quota/settlement_readback.ts @@ -568,11 +568,13 @@ export function projectSemanticReplanGuard( const hasReview = ["semantic_replan_review_kind", "semantic_replan_review_stop_condition", "semantic_replan_review_stop_condition_sha256", "semantic_replan_review_stop_contract_id"] .some(field => Object.hasOwn(receiptDetails, field)); + const hasAdmittedStride = Object.hasOwn(receiptDetails, "semantic_replan_stride_strategy"); if (hasCapability && hasReview) throw new EffectRuntimeRequestError( "a review source cannot replace a capability guard", "malformed_settlement_state"); if (!Object.hasOwn(receiptDetails, "semantic_replan_obligation_id")) { if (hasCapability) throw new EffectRuntimeRequestError("a capability guard requires a selected obligation", "malformed_settlement_state"); if (hasReview) throw new EffectRuntimeRequestError("a review source requires a selected obligation", "malformed_settlement_state"); + if (hasAdmittedStride) throw new EffectRuntimeRequestError("an admitted stride strategy requires a selected obligation", "malformed_settlement_state"); return { schema_version: SEMANTIC_REPLAN_GUARD_SCHEMA, scope: "legacy_unscoped", @@ -583,6 +585,7 @@ export function projectSemanticReplanGuard( if (rawObligationId === "" || rawObligationId === null) { if (hasCapability) throw new EffectRuntimeRequestError("a capability guard requires a selected obligation", "malformed_settlement_state"); if (hasReview) throw new EffectRuntimeRequestError("a review source requires a selected obligation", "malformed_settlement_state"); + if (hasAdmittedStride) throw new EffectRuntimeRequestError("an admitted stride strategy requires a selected obligation", "malformed_settlement_state"); return { schema_version: SEMANTIC_REPLAN_GUARD_SCHEMA, scope: "turn_guard", @@ -597,6 +600,17 @@ export function projectSemanticReplanGuard( ); } const reviewKind = hasReview ? requireNonEmptyString(receiptDetails.semantic_replan_review_kind, "receipt review kind") : null; + let admittedStrideStrategy: string | null = null; + if (hasAdmittedStride) { + const rawStride = receiptDetails.semantic_replan_stride_strategy; + if (rawStride !== "evidence_conditioned_v1" && rawStride !== "off") { + throw new EffectRuntimeRequestError( + "heartbeat receipt semantic_replan_stride_strategy is malformed", + "malformed_settlement_state", + ); + } + admittedStrideStrategy = rawStride; + } const stop = Object.hasOwn(receiptDetails, "semantic_replan_review_stop_condition") ? requireNonEmptyString(receiptDetails.semantic_replan_review_stop_condition, "receipt review stop condition") : null; const stopDigest = Object.hasOwn(receiptDetails, "semantic_replan_review_stop_condition_sha256") @@ -636,6 +650,7 @@ export function projectSemanticReplanGuard( capability_id: receiptDetails.semantic_replan_capability_id, gap_id: receiptDetails.semantic_replan_gap_id, frontier_revision: receiptDetails.semantic_replan_frontier_revision}), } : {}), + ...(admittedStrideStrategy !== null ? {admitted_stride_strategy: admittedStrideStrategy} : {}), }; } diff --git a/loopx/control_plane/quota/should_run.py b/loopx/control_plane/quota/should_run.py index 02694ed368..f77b564235 100644 --- a/loopx/control_plane/quota/should_run.py +++ b/loopx/control_plane/quota/should_run.py @@ -573,6 +573,7 @@ def build_quota_should_run( receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, receipt_bound_replan_review: Mapping[str, Any] | None = None, + receipt_bound_admitted_stride_strategy: str | None = None, turn_instance_id: str | None = None, runtime_root: str | Path | None = None, workspace_path: Path | None = None, @@ -674,6 +675,7 @@ def build_quota_should_run( receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id, receipt_bound_replan_review=receipt_bound_replan_review, + receipt_bound_admitted_stride_strategy=receipt_bound_admitted_stride_strategy, ) route = _resolve_quota_should_run_route(prepared) route = _apply_selected_todo_guards( diff --git a/loopx/control_plane/quota/should_run_packet.py b/loopx/control_plane/quota/should_run_packet.py index b5f7c0e8df..38e9e0ebc0 100644 --- a/loopx/control_plane/quota/should_run_packet.py +++ b/loopx/control_plane/quota/should_run_packet.py @@ -1679,6 +1679,9 @@ def _build_active_quota_payload( quota_decision_agent_id(payload) or prepared.requested_agent_id ), bounded_research_frontier=bounded_research_frontier, + admitted_stride_strategy=prepared.admitted_stride_strategy_for( + payload["autonomous_replan_obligation"] + ), ) return payload diff --git a/loopx/control_plane/quota/should_run_prepare.py b/loopx/control_plane/quota/should_run_prepare.py index 04caa7ff73..7bd2976b8e 100644 --- a/loopx/control_plane/quota/should_run_prepare.py +++ b/loopx/control_plane/quota/should_run_prepare.py @@ -150,6 +150,8 @@ class _QuotaDecisionPreparation: receipt_bound_monitor_phase: ReceiptBoundMonitorPhase | None receipt_bound_replay_phase: ReceiptBoundReplayPhase | None receipt_bound_replan_execution_pending: bool + receipt_bound_replan_obligation_id: str | None + receipt_bound_admitted_stride_strategy: str | None user_todo_summary: dict[str, Any] | None agent_todo_summary: dict[str, Any] | None agent_todo_planning_source_items: list[dict[str, Any]] @@ -191,6 +193,17 @@ class _QuotaDecisionPreparation: def inbox_priority_due(self) -> bool: return self.inbox_reply_due or self.inbox_material_review_due + def admitted_stride_strategy_for( + self, obligation: Mapping[str, Any] + ) -> str | None: + if ( + self.receipt_bound_replan_obligation_id + and obligation.get("obligation_id") + == self.receipt_bound_replan_obligation_id + ): + return self.receipt_bound_admitted_stride_strategy + return None + def _preserve_receipt_bound_replan_obligation( replan_obligation: Mapping[str, Any] | None, @@ -203,6 +216,7 @@ def _preserve_receipt_bound_replan_obligation( goal_id: str | None = None, guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None, + admitted_stride_strategy: str | None = None, ) -> dict[str, Any] | None: preserved_replan_id = normalize_todo_replan_obligation_id( receipt_bound_replan_obligation_id @@ -218,6 +232,11 @@ def _preserve_receipt_bound_replan_obligation( "replay_phase": replay_phase.value if replay_phase is not None else None, "transition_candidates": transition_candidates or [], "receipt_review": receipt_review, + **( + {"admitted_stride_strategy": admitted_stride_strategy} + if admitted_stride_strategy is not None + else {} + ), "goal_id": goal_id, "guard_recorded_at": guard_recorded_at, "guard_turn_instance_id": guard_turn_instance_id, @@ -256,6 +275,7 @@ def _prepare_quota_replan_context( receipt_bound_guard_recorded_at: str | None, receipt_bound_guard_turn_instance_id: str | None, receipt_bound_replan_review: Mapping[str, Any] | None, + receipt_bound_admitted_stride_strategy: str | None = None, replan_explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None, ) -> tuple[dict[str, Any], dict[str, Any] | None]: """Project the current frontier and contextualize its receipt-bound review.""" @@ -264,6 +284,11 @@ def _prepare_quota_replan_context( reconstruct_review = receipt_bound_replay_phase not in ( ReceiptBoundReplayPhase.SETTLEMENT_PENDING, ReceiptBoundReplayPhase.SETTLED, ) + admitted_stride_strategy = ( + receipt_bound_admitted_stride_strategy + if receipt_bound_replan_guard_scoped and receipt_bound_replan_obligation_id + else None + ) goal_frontier_context = build_goal_frontier_projection_context_from_status( replan_explore_reader=replan_explore_reader, goal_id=safe_goal_id, @@ -285,6 +310,7 @@ def _prepare_quota_replan_context( receipt_bound_replan_obligation_id if reconstruct_review else None ), receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, + receipt_bound_admitted_stride_strategy=admitted_stride_strategy, ) replan_obligation = ( None @@ -302,6 +328,7 @@ def _prepare_quota_replan_context( goal_id=safe_goal_id, guard_recorded_at=receipt_bound_guard_recorded_at, guard_turn_instance_id=receipt_bound_guard_turn_instance_id, + admitted_stride_strategy=admitted_stride_strategy, ) ) if replan_obligation and not replan_obligation.get("replan_context") and not replan_obligation.get("settlement_action_packet"): @@ -755,6 +782,7 @@ def _prepare_quota_should_run_item( receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, receipt_bound_replan_review: Mapping[str, Any] | None = None, + receipt_bound_admitted_stride_strategy: str | None = None, ) -> _QuotaDecisionPreparation: quota = cast(dict[str, Any], item.get("quota")) if isinstance(item.get("quota"), dict) else {} state = str(quota.get("state") or "unknown") @@ -1057,6 +1085,7 @@ def _prepare_quota_should_run_item( receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id, receipt_bound_replan_review=receipt_bound_replan_review, + receipt_bound_admitted_stride_strategy=receipt_bound_admitted_stride_strategy, replan_explore_reader=replan_explore_reader, ) replan_scope = goal_frontier_context.get("replan_scope") or {} @@ -1109,6 +1138,15 @@ def _prepare_quota_should_run_item( receipt_bound_monitor_phase=receipt_bound_monitor_phase, receipt_bound_replay_phase=receipt_bound_replay_phase, receipt_bound_replan_execution_pending=receipt_bound_replan_execution_pending, + receipt_bound_replan_obligation_id=normalize_todo_replan_obligation_id( + receipt_bound_replan_obligation_id + ), + receipt_bound_admitted_stride_strategy=( + receipt_bound_admitted_stride_strategy + if receipt_bound_replan_guard_scoped + and normalize_todo_replan_obligation_id(receipt_bound_replan_obligation_id) + else None + ), user_todo_summary=user_todo_summary, agent_todo_summary=agent_todo_summary, agent_todo_planning_source_items=agent_todo_planning_source_items, diff --git a/loopx/control_plane/work_items/autonomous_replan_obligation.py b/loopx/control_plane/work_items/autonomous_replan_obligation.py index 0023ae799f..86e9fbb9bf 100644 --- a/loopx/control_plane/work_items/autonomous_replan_obligation.py +++ b/loopx/control_plane/work_items/autonomous_replan_obligation.py @@ -136,6 +136,7 @@ def build_autonomous_replan_cli_actions( runtime_root: str | None = None, successor_closeout_guard: str | None = None, quota_guard_action: str | None = None, + admitted_stride_strategy: str | None = None, ) -> list[str]: lifecycle_reentry = project_todo_lifecycle_settlement_reentry( payload, @@ -183,7 +184,10 @@ def build_autonomous_replan_cli_actions( "" if preferred_input == "exact_historical_ack" else writeback_contract.get("cli_semantic_args") - or replan_writeback_requirements(obligation)["cli_semantic_args"] + or replan_writeback_requirements( + obligation, + admitted_stride_strategy=admitted_stride_strategy, + )["cli_semantic_args"] ) delivery_args = ( "--delivery-batch-scale single_surface " diff --git a/loopx/control_plane/work_items/progress_observation.py b/loopx/control_plane/work_items/progress_observation.py index 7149d938cf..f038cc3681 100644 --- a/loopx/control_plane/work_items/progress_observation.py +++ b/loopx/control_plane/work_items/progress_observation.py @@ -219,11 +219,19 @@ def _normalized_window( def replan_writeback_requirements( obligation: Mapping[str, Any], + *, + admitted_stride_strategy: str | None = None, ) -> dict[str, Any]: """Adapt the shared typed discharge policy for CLI and host projection.""" try: result = project_replan_semantics({ - "operation": "requirements", "obligation": dict(obligation), + "operation": "requirements", + "obligation": dict(obligation), + **( + {"admitted_stride_strategy": admitted_stride_strategy} + if admitted_stride_strategy is not None + else {} + ), }) except EffectRuntimeRejected as exc: raise ValueError(str(exc)) from None @@ -236,11 +244,20 @@ def required_semantic_outcomes(obligation: Mapping[str, Any]) -> list[str]: return list(replan_writeback_requirements(obligation)["required_any_of"]) -def replan_successor_transition_allowed(obligation: Mapping[str, Any]) -> bool: +def replan_successor_transition_allowed( + obligation: Mapping[str, Any], + *, + admitted_stride_strategy: str | None = None, +) -> bool: """Ask the typed owner whether a Todo transition can settle this review.""" try: result = project_replan_semantics({ "operation": "transition_eligibility", "obligation": dict(obligation), + **( + {"admitted_stride_strategy": admitted_stride_strategy} + if admitted_stride_strategy is not None + else {} + ), }) except EffectRuntimeRejected as exc: raise ValueError(str(exc)) from None @@ -252,6 +269,7 @@ def replan_successor_transition_allowed(obligation: Mapping[str, Any]) -> bool: def guarded_replan_transition_delta( *, guard_scoped: bool, selected_obligation_id: str | None, transition_candidates: list[dict[str, Any]], + admitted_stride_strategy: str | None = None, goal_id: str | None = None, agent_id: str | None = None, guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None, @@ -262,6 +280,11 @@ def guarded_replan_transition_delta( "operation": "turn_transition", "guard_scoped": guard_scoped, "selected_obligation_id": selected_obligation_id, "transition_candidates": transition_candidates, + **( + {"admitted_stride_strategy": admitted_stride_strategy} + if admitted_stride_strategy is not None + else {} + ), "goal_id": goal_id, "agent_id": agent_id, "guard_recorded_at": guard_recorded_at, @@ -315,6 +338,7 @@ def semantic_delta_from_writeback( progress_observation: Mapping[str, Any] | None, agent_vision: Mapping[str, Any] | None = None, history_runs: Iterable[Mapping[str, Any]] | None = None, + admitted_stride_strategy: str | None = None, ) -> dict[str, Any]: """Qualify concrete typed writeback evidence against one obligation. @@ -383,7 +407,7 @@ def semantic_delta_from_writeback( source_review = None stride = vision.get("stride_decision") review = stride.get("previous_review") if isinstance(stride, Mapping) else None - if (runs is not None and context is not None + if (runs is not None and context is not None and admitted_stride_strategy != "off" and context.get("decision_followthrough") and isinstance(review, Mapping)): from .replan_context_codec import replay_stride_review_evidence @@ -392,6 +416,11 @@ def semantic_delta_from_writeback( result = project_replan_semantics({ "operation": "qualify", "obligation": dict(obligation), "progress_source": progress_source, "agent_vision": vision, + **( + {"admitted_stride_strategy": admitted_stride_strategy} + if admitted_stride_strategy is not None + else {} + ), **({"stride_review_evidence": source_review} if source_review is not None else {}), }) except EffectRuntimeRejected as exc: @@ -429,6 +458,7 @@ def build_replan_action_packet( goal_id: str | None = None, agent_id: str | None = None, bounded_research_frontier: Mapping[str, Any] | None = None, + admitted_stride_strategy: str | None = None, ) -> dict[str, Any]: settlement_packet = obligation.get("settlement_action_packet") if isinstance(settlement_packet, Mapping): @@ -473,7 +503,10 @@ def build_replan_action_packet( "explore_result_node_refs" ), ) - requirements = replan_writeback_requirements(obligation) + requirements = replan_writeback_requirements( + obligation, + admitted_stride_strategy=admitted_stride_strategy, + ) writeback_contract = requirements["writeback_contract"] successor_summary = str( selected_gap_values.get("successor_summary") or "" diff --git a/loopx/control_plane/work_items/replan_semantics.ts b/loopx/control_plane/work_items/replan_semantics.ts index aeddeae4e2..3b1b15c5af 100644 --- a/loopx/control_plane/work_items/replan_semantics.ts +++ b/loopx/control_plane/work_items/replan_semantics.ts @@ -8,7 +8,7 @@ import { parseTodoTimestampMicros } from "../runtime_timestamp.ts"; import { TODO_COMPLETION_RECOVERIES } from "../todos/completion_state.ts"; import { id as todoId, readResume, taskClass } from "../todos/read_codec.ts"; import { indexInferredSuccessors } from "../todos/succession.ts"; -import {normalizeStrideDecision, STRIDE_DECISION_SCHEMA, strideControlContract, strideReviewMismatch} from "./stride_policy.ts"; +import {normalizeStrideDecision, normalizeStrideStrategy, STRIDE_DECISION_SCHEMA, strideControlContract, strideReviewMismatch} from "./stride_policy.ts"; import { projectProgressDelta } from "./progress_delta.ts"; const PROGRESS_OUTCOMES = [ @@ -110,8 +110,12 @@ function isExternalReview(obligation: JsonObject): boolean { // cannot opt an obligation out of the review. const STRIDE_REVIEW_TRIGGERS = new Set(["periodic_review_due", "typed_progress_repeat", "no_progress_streak", "repeated_action_loop", "external_progress_review_drift"]); -function requiresStrideDecision(obligation: JsonObject): boolean { - return triggerKinds(obligation).some(kind => STRIDE_REVIEW_TRIGGERS.has(kind)); +function requiresStrideDecision( + obligation: JsonObject, + admittedStrideStrategy: unknown = "evidence_conditioned_v1", +): boolean { + return normalizeStrideStrategy(admittedStrideStrategy) !== "off" && + triggerKinds(obligation).some(kind => STRIDE_REVIEW_TRIGGERS.has(kind)); } /** Route only a revalidated canonical transition to its original Turn guard. @@ -181,7 +185,7 @@ function projectTurnTransition(request: JsonObject): JsonObject { } const sourceObligation = object(candidateSource.obligation); if (sourceObligation.obligation_id !== selected) continue; - if (requiresStrideDecision(sourceObligation)) continue; + if (requiresStrideDecision(sourceObligation, request.admitted_stride_strategy)) continue; const ack = object(candidateSource.ack); const candidate = object(ack.semantic_delta); if (ack.schema_version === "autonomous_replan_ack_v0" && @@ -349,9 +353,11 @@ function preserveReceiptBoundObligation(request: JsonObject): JsonObject { openVisionReview = obligation; } } - if (!requiredSemanticOutcomes(obligation).includes("new_runnable_successor")) continue; + if (!requiredSemanticOutcomes(obligation, request.admitted_stride_strategy).includes("new_runnable_successor")) continue; const result = projectTurnTransition({guard_scoped: request.guard_scoped, selected_obligation_id: selected, transition_candidates: [candidate], + ...(request.admitted_stride_strategy !== undefined + ? {admitted_stride_strategy: request.admitted_stride_strategy} : {}), goal_id: request.goal_id, agent_id: request.agent_id, guard_recorded_at: request.guard_recorded_at, guard_turn_instance_id: request.guard_turn_instance_id}); @@ -473,7 +479,10 @@ function preserveReceiptBoundObligation(request: JsonObject): JsonObject { } /** One outcome policy for host projection and write-time discharge. */ -export function requiredSemanticOutcomes(obligation: JsonObject): SemanticOutcome[] { +export function requiredSemanticOutcomes( + obligation: JsonObject, + admittedStrideStrategy: unknown = "evidence_conditioned_v1", +): SemanticOutcome[] { const kinds = triggerKinds(obligation); const acceptanceHold = kinds.some(kind => ACCEPTANCE_HOLD_TRIGGERS.has(kind)); const declared = strings(obligation.satisfying_semantic_outcomes); @@ -498,12 +507,12 @@ export function requiredSemanticOutcomes(obligation: JsonObject): SemanticOutcom // An enabled stall review can also retain the unfinished useful experiment // after a current evidenced decision, without inventing progress or a Todo. // Explicit capability/acceptance outcome restrictions above still apply. - return requiresStrideDecision(obligation) || kinds.some(kind => kind === "long_todo_chain" || + return requiresStrideDecision(obligation, admittedStrideStrategy) || kinds.some(kind => kind === "long_todo_chain" || kind === "periodic_review_due" || EXTERNAL_REVIEW_TRIGGERS.has(kind)) ? ["fresh_vision_path_outcome", ...PROGRESS_OUTCOMES] : [...PROGRESS_OUTCOMES]; } -function writebackProjection(required: SemanticOutcome[], externalReview: boolean): JsonObject { +function writebackProjection(required: SemanticOutcome[], externalReview: boolean, strideEnabled: boolean): JsonObject { // This chooses a usable refresh path, not the only legal exit. Successor and // terminal alternatives still have their own typed transitions and gates. if (externalReview) { @@ -527,7 +536,7 @@ function writebackProjection(required: SemanticOutcome[], externalReview: boolea preferred_input: "evidence_linked_vision_path", vision_authoring: visionAuthoringContract(true), required_fields: ["vision_patch.acceptance_summary", "path_delta.outcome", "path_delta.evidence_refs", - "agent_vision.stride_decision"], + ...(strideEnabled ? ["agent_vision.stride_decision"] : [])], path_outcomes: [...FRESH_PATH_DISPOSITIONS], rule: "First reuse observed evidence valid for current source/acceptance; probe missing, stale or insufficient evidence. Write a JSON file with acceptance summary and evidence-linked path outcome, then run bound refresh and spend. An unchanged reason alone is insufficient. Explicit validation gates and other required_any_of contracts apply.", }, @@ -634,13 +643,16 @@ export function projectReplanSemantics(value: unknown): JsonObject { ? {kind, stop_condition: obligation.stop_condition} : null}; } if (request.operation === "transition_eligibility") { - return {allowed: !requiresStrideDecision(obligation)}; + return {allowed: !requiresStrideDecision(obligation, request.admitted_stride_strategy)}; } - const required = requiredSemanticOutcomes(obligation); + const required = requiredSemanticOutcomes(obligation, request.admitted_stride_strategy); const externalReview = isExternalReview(obligation); if (request.operation === "requirements") { - const strideControl = strideControlContract(object(obligation.replan_context), obligation.obligation_id); - const writeback = writebackProjection(required, externalReview); + const strideEnabled = normalizeStrideStrategy(request.admitted_stride_strategy) !== "off"; + const strideControl = strideEnabled + ? strideControlContract(object(obligation.replan_context), obligation.obligation_id) + : null; + const writeback = writebackProjection(required, externalReview, strideEnabled); if (required.includes("coverage_backed_no_followup")) { writeback.writeback_contract = {...object(writeback.writeback_contract), no_followup_requirements: { @@ -654,7 +666,7 @@ export function projectReplanSemantics(value: unknown): JsonObject { "Write back and spend with the original settlement_plan identity, not a later obligation.", }}; } - if (requiresStrideDecision(obligation)) { + if (requiresStrideDecision(obligation, request.admitted_stride_strategy)) { const contract = object(writeback.writeback_contract); writeback.cli_semantic_args = VISION_CLI_ARGS; writeback.writeback_contract = {...contract, @@ -665,7 +677,7 @@ export function projectReplanSemantics(value: unknown): JsonObject { String(contract.rule ?? "")}; } return {required_any_of: required, planning_guidance: REPLAN_PLANNING_GUIDANCE, - stride_control: strideControl, + ...(strideControl ? {stride_control: strideControl} : {}), ...writeback}; } if (request.operation !== "qualify") { @@ -679,21 +691,23 @@ export function projectReplanSemantics(value: unknown): JsonObject { const path = object(vision.path_delta); const context = object(obligation.replan_context); const [strideDecision] = normalizeStrideDecision(vision.stride_decision); + const admittedStrideStrategy = normalizeStrideStrategy(request.admitted_stride_strategy); + const structuredReview = admittedStrideStrategy !== "off"; const selectedComparison = object(strideDecision?.explore_review).selected_candidate != null; - const requiredStrideReview = requiresStrideDecision(obligation); + const requiredStrideReview = requiresStrideDecision(obligation, admittedStrideStrategy); const pathOutcome = String(path.outcome ?? "").trim(); const evidenceLinkedPath = Boolean(String(patch.acceptance_summary ?? "").trim() && (FRESH_PATH_DISPOSITIONS.has(pathOutcome) || pathOutcome === "stop") && strings(path.evidence_refs).length); const freshPath = evidenceLinkedPath && FRESH_PATH_DISPOSITIONS.has(pathOutcome); const independentStride = strideDecision?.schema_version === STRIDE_DECISION_SCHEMA; - const missingStride = (freshPath || requiredStrideReview) && + const missingStride = structuredReview && (freshPath || requiredStrideReview) && (!strideDecision || !independentStride); const missingStridePath = requiredStrideReview && !evidenceLinkedPath; - const staleStride = !!strideDecision && + const staleStride = !!strideDecision && (structuredReview || selectedComparison) && strideDecision.reference_obligation_id !== obligation.obligation_id; - const reviewContextChanged = !!strideDecision + const reviewContextChanged = !!strideDecision && (structuredReview || selectedComparison) && (requiredStrideReview || selectedComparison) && strideDecision.reference_context_id !== context.context_id; - const reviewMismatch = strideDecision + const reviewMismatch = strideDecision && (structuredReview || selectedComparison) ? reviewContextChanged ? "Stride decision references a different review context. Read the returned context_recovery before retrying the original writeback." : strideReviewMismatch(strideDecision, context, request.stride_review_evidence, vision.todo_delta) diff --git a/loopx/control_plane/work_items/semantic_replan_writeback.py b/loopx/control_plane/work_items/semantic_replan_writeback.py index bdadcfcaa1..b8c15ecede 100644 --- a/loopx/control_plane/work_items/semantic_replan_writeback.py +++ b/loopx/control_plane/work_items/semantic_replan_writeback.py @@ -77,10 +77,12 @@ def __init__( *, obligation: Mapping[str, Any], semantic_delta: Mapping[str, Any] | None, + admitted_stride_strategy: str | None = None, ) -> None: super().__init__(message) self.obligation = dict(obligation) self.semantic_delta = dict(semantic_delta or {}) + self.admitted_stride_strategy = admitted_stride_strategy def project_replan_writeback_rejection( @@ -133,6 +135,7 @@ def project_replan_writeback_rejection( settlement_chain_ready=False, lifecycle_actor_args=scoped_cli_args, runtime_root=runtime_root, + admitted_stride_strategy=rejection.admitted_stride_strategy, ) ) capability_guard = obligation.get("capability_guard") @@ -224,6 +227,7 @@ def _build_writeback_projection_context( replan_source_route: Mapping[str, Any] | None, guard_scoped: bool, guard_semantic_replan_obligation_id: str | None, + admitted_stride_strategy: str | None = None, receipt_bound_guard_recorded_at: str | None, receipt_bound_guard_turn_instance_id: str | None, goal_ref: Mapping[str, Any] | None, @@ -293,6 +297,9 @@ def _build_writeback_projection_context( goal_status=str((registry_goal or {}).get("status") or "active"), receipt_bound_replan_obligation_id=(guard_semantic_replan_obligation_id if guard_scoped else None), receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, + receipt_bound_admitted_stride_strategy=( + admitted_stride_strategy if guard_scoped and guard_semantic_replan_obligation_id else None + ), agent_profile=( cast(dict[str, Any], cast(dict[str, Any], agent_identity).get("agent_profile")) if isinstance(cast(dict[str, Any], agent_identity).get("agent_profile"), dict) @@ -319,6 +326,7 @@ def qualify_replan_writeback( effective_turn_cadence: dict[str, Any] | None = None, guard_scoped: bool = False, guard_semantic_replan_obligation_id: str | None = None, + admitted_stride_strategy: str | None = None, capability_evidence: CapabilityReplanEvidence | None = None, guard_capability: Mapping[str, Any] | None = None, receipt_bound_guard_recorded_at: str | None = None, @@ -386,6 +394,7 @@ def qualify_replan_writeback( replan_source_route=replan_source_route, guard_scoped=guard_scoped, guard_semantic_replan_obligation_id=guard_semantic_replan_obligation_id, + admitted_stride_strategy=admitted_stride_strategy, receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id, goal_ref=goal_ref, @@ -411,6 +420,7 @@ def qualify_replan_writeback( guard_scoped=guard_scoped, selected_obligation_id=guard_semantic_replan_obligation_id, transition_candidates=context.get("replan_transition_candidates", []), + admitted_stride_strategy=admitted_stride_strategy, goal_id=goal_id, agent_id=safe_agent_id, guard_recorded_at=receipt_bound_guard_recorded_at, @@ -444,6 +454,11 @@ def qualify_replan_writeback( "current_obligation": obligation, "receipt_review": receipt_bound_replan_review, "transition_candidates": context.get("replan_transition_candidates", []), + **( + {"admitted_stride_strategy": admitted_stride_strategy} + if admitted_stride_strategy is not None + else {} + ), "goal_id": goal_id, "guard_recorded_at": receipt_bound_guard_recorded_at, "guard_turn_instance_id": receipt_bound_guard_turn_instance_id, @@ -474,11 +489,18 @@ def qualify_replan_writeback( completion_turn_key=completion_turn_key, ): return None, None + obligation_id = str(obligation.get("obligation_id") or "").strip() + effective_stride_strategy = ( + admitted_stride_strategy + if (not guard_scoped or obligation_id == str(guard_semantic_replan_obligation_id or "").strip()) + else None + ) semantic_delta = semantic_delta_from_writeback( obligation=obligation, progress_observation=progress_observation, agent_vision=agent_vision, history_runs=newest_first_runs, + admitted_stride_strategy=effective_stride_strategy, ) if ( "coverage_backed_no_followup" @@ -512,6 +534,7 @@ def enforce_open_replan_writeback( completion_turn_key: str | None = None, guard_scoped: bool = False, guard_semantic_replan_obligation_id: str | None = None, + admitted_stride_strategy: str | None = None, receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, receipt_bound_replan_review: Mapping[str, Any] | None = None, @@ -549,6 +572,7 @@ def enforce_open_replan_writeback( todo_fields=todo_fields, guard_scoped=guard_scoped, guard_semantic_replan_obligation_id=guard_semantic_replan_obligation_id, + admitted_stride_strategy=admitted_stride_strategy, capability_evidence=capability_evidence, guard_capability=guard_capability, receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, @@ -571,11 +595,18 @@ def enforce_open_replan_writeback( return None if isinstance(semantic_delta, dict) and semantic_delta.get("accepted") is True: return semantic_delta + obligation_id = str(obligation.get("obligation_id") or "").strip() + effective_stride_strategy = ( + admitted_stride_strategy + if (not guard_scoped or obligation_id == str(guard_semantic_replan_obligation_id or "").strip()) + else None + ) if isinstance(semantic_delta, dict) and semantic_delta.get("reason_code"): raise ReplanWritebackRejected( str(semantic_delta.get("reason") or "invalid replan writeback"), obligation=obligation, semantic_delta=semantic_delta, + admitted_stride_strategy=effective_stride_strategy, ) raise ReplanWritebackRejected( ( @@ -587,6 +618,7 @@ def enforce_open_replan_writeback( ), obligation=obligation, semantic_delta=semantic_delta, + admitted_stride_strategy=effective_stride_strategy, ) @@ -602,6 +634,7 @@ def qualify_refresh_replan_writeback( settlement_todo_id: str | None, settlement_guard_scoped: bool, settlement_guard_semantic_replan_obligation_id: str | None, + admitted_stride_strategy: str | None = None, receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, receipt_bound_replan_review: Mapping[str, Any] | None = None, @@ -691,6 +724,7 @@ def qualify_refresh_replan_writeback( guard_semantic_replan_obligation_id=( settlement_guard_semantic_replan_obligation_id ), + admitted_stride_strategy=admitted_stride_strategy, receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id, receipt_bound_replan_review=receipt_bound_replan_review, diff --git a/loopx/control_plane/work_items/stride_policy_codec.py b/loopx/control_plane/work_items/stride_policy_codec.py index 7039d91439..7c8c005cea 100644 --- a/loopx/control_plane/work_items/stride_policy_codec.py +++ b/loopx/control_plane/work_items/stride_policy_codec.py @@ -6,14 +6,22 @@ from __future__ import annotations import json +from collections.abc import Mapping from functools import lru_cache from importlib.resources import files +from pathlib import Path from typing import Any # The only live stride strategy. There is no live switch: Goal profiles, # machine defaults and benchmark arms cannot select "off" for new decisions. LIVE_STRIDE_STRATEGY = "evidence_conditioned_v1" +_LEGACY_CADENCE_V0_V1_SCHEMAS = frozenset( + { + "todo_replan_cadence_machine_defaults_v0", + "todo_replan_cadence_machine_defaults_v1", + } +) @lru_cache(maxsize=1) @@ -28,3 +36,58 @@ def normalize_stride_strategy(value: Any) -> str: if not isinstance(value, str) or value not in stride_strategy_options(): raise ValueError("stride_strategy must be off or evidence_conditioned_v1") return value + + +def legacy_pre_upgrade_stride_strategy( + raw_goal: Mapping[str, Any] | None, + runtime_root: Path | None, +) -> str: + """Inspect un-stripped Goal/machine config to preserve pre-upgrade `off` Turns.""" + profile = raw_goal.get("execution_profile") if isinstance(raw_goal, Mapping) else None + if isinstance(profile, Mapping): + if "stride_strategy" in profile: + return normalize_stride_strategy(profile["stride_strategy"]) + if ( + "replan_after_completed_todos" in profile + or "replan_after_effective_turns" in profile + ): + # Matches legacy inheritance where an explicit cadence override without + # `stride_strategy` did not inherit the device default stride strategy. + return "off" + if runtime_root is not None: + config_path = Path(runtime_root).expanduser() / "machine" / "configuration.json" + if config_path.is_file(): + stored = json.loads(config_path.read_text(encoding="utf-8")) + if not isinstance(stored, Mapping): + raise ValueError("machine_configuration must be an object") + namespaces = stored.get("namespaces") + raw_ns = ( + namespaces.get("todo_replan_cadence") + if isinstance(namespaces, Mapping) + else None + ) + if isinstance(raw_ns, Mapping): + if "stride_strategy" in raw_ns: + return normalize_stride_strategy(raw_ns["stride_strategy"]) + if raw_ns.get("schema_version") in _LEGACY_CADENCE_V0_V1_SCHEMAS: + return "off" + return LIVE_STRIDE_STRATEGY + + +def resolve_receipt_bound_stride_strategy( + settlement_replan_guard: Mapping[str, Any] | None, + *, + raw_goal: Mapping[str, Any] | None, + runtime_root: Path | None, +) -> str: + """Return the stride strategy governing one receipt-bound replan Turn.""" + if ( + isinstance(settlement_replan_guard, Mapping) + and settlement_replan_guard.get("scope") == "turn_guard" + and settlement_replan_guard.get("selected_obligation_id") + ): + admitted = settlement_replan_guard.get("admitted_stride_strategy") + if isinstance(admitted, str): + return normalize_stride_strategy(admitted) + return legacy_pre_upgrade_stride_strategy(raw_goal, runtime_root) + return LIVE_STRIDE_STRATEGY diff --git a/loopx/quota.py b/loopx/quota.py index 0263c3ea4b..32090b815e 100644 --- a/loopx/quota.py +++ b/loopx/quota.py @@ -812,14 +812,12 @@ def build_quota_should_run( receipt_bound_replay_phase: ReceiptBoundReplayPhase | None = None, receipt_bound_terminal_phase: ReceiptBoundTerminalPhase | None = None, receipt_bound_replan_obligation_id: str | None = None, - receipt_bound_replan_guard_scoped: bool = False, - receipt_bound_replan_execution_pending: bool = False, - receipt_bound_successor_replan: bool = False, - receipt_bound_guard_recorded_at: str | None = None, + receipt_bound_replan_guard_scoped: bool = False, receipt_bound_replan_execution_pending: bool = False, + receipt_bound_successor_replan: bool = False, receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, receipt_bound_replan_review: Mapping[str, object] | None = None, - turn_instance_id: str | None = None, - runtime_root: str | Path | None = None, + receipt_bound_admitted_stride_strategy: str | None = None, + turn_instance_id: str | None = None, runtime_root: str | Path | None = None, workspace_path: Path | None = None, goal_ref: Mapping[str, object] | None = None, authoritative_fallback_todo_items: FallbackTodoSource = None, @@ -848,8 +846,7 @@ def read_explore_context(read_goal_id: str, read_agent_id: str | None) -> dict[s codex_app_automation_id=codex_app_automation_id, scheduler_execution_context=scheduler_execution_context, operator_inbox_urgency_projector=operator_inbox_urgency_projector, receipt_bound_todo_id=receipt_bound_todo_id, requested_action_todo_id=requested_action_todo_id, - receipt_bound_monitor_phase=receipt_bound_monitor_phase, - receipt_bound_replay_phase=receipt_bound_replay_phase, + receipt_bound_monitor_phase=receipt_bound_monitor_phase, receipt_bound_replay_phase=receipt_bound_replay_phase, receipt_bound_terminal_phase=receipt_bound_terminal_phase, receipt_bound_replan_obligation_id=receipt_bound_replan_obligation_id, receipt_bound_replan_guard_scoped=receipt_bound_replan_guard_scoped, @@ -857,7 +854,9 @@ def read_explore_context(read_goal_id: str, read_agent_id: str | None) -> dict[s receipt_bound_successor_replan=receipt_bound_successor_replan, receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at, receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id, - receipt_bound_replan_review=receipt_bound_replan_review, turn_instance_id=turn_instance_id, + receipt_bound_replan_review=receipt_bound_replan_review, + receipt_bound_admitted_stride_strategy=receipt_bound_admitted_stride_strategy, + turn_instance_id=turn_instance_id, runtime_root=runtime_root, workspace_path=workspace_path, goal_ref=goal_ref, authoritative_fallback_todo_items=authoritative_fallback_todo_items, replan_explore_reader=read_explore_context, app_scheduler_state_observer=app_scheduler_state_observer, diff --git a/loopx/state_refresh.py b/loopx/state_refresh.py index 64807c824a..2c40900245 100644 --- a/loopx/state_refresh.py +++ b/loopx/state_refresh.py @@ -67,6 +67,9 @@ qualify_refresh_replan_writeback, ) from .capabilities.progress_review.context import external_progress_review_context +from .control_plane.work_items.stride_policy_codec import ( + resolve_receipt_bound_stride_strategy, +) from .control_plane.work_items.refresh_recommendation import ( DEFAULT_REFRESH_ACTION as DEFAULT_REFRESH_ACTION, RECOMMENDED_ACTION_SOURCE_ACTIVE_NEXT_ACTION as RECOMMENDED_ACTION_SOURCE_ACTIVE_NEXT_ACTION, @@ -1161,6 +1164,11 @@ def read_explore_context(read_goal_id: str, read_agent_id: str | None): settlement_guard_scoped=( settlement_replan_guard.get("scope") == "turn_guard" ), + admitted_stride_strategy=resolve_receipt_bound_stride_strategy( + settlement_replan_guard, + raw_goal=registry_goal, + runtime_root=runtime_root, + ), receipt_bound_guard_recorded_at=( settlement_readback.admission_recorded_at if settlement_readback is not None and settlement_readback.admission_recorded_at diff --git a/tests/capabilities/test_machine_configuration_goal_defaults.py b/tests/capabilities/test_machine_configuration_goal_defaults.py index 709bb721d5..0ea54383e9 100644 --- a/tests/capabilities/test_machine_configuration_goal_defaults.py +++ b/tests/capabilities/test_machine_configuration_goal_defaults.py @@ -394,16 +394,23 @@ def test_legacy_machine_stride_strategy_loads_and_is_ignored(tmp_path: Path, leg assert store.read_bytes() == before, "reading must not migrate the stored device file" # A whole-document write of the same legacy shape is accepted (restore of an - # old backup) and persists without the removed field. + # old backup) and persists the v2 rollback key without exposing it publicly. owner = build_builtin_machine_configuration_registry() configuration = _machine_configuration() configuration["namespaces"]["todo_replan_cadence"] = dict(saved["namespaces"]["todo_replan_cadence"]) preview = configure_machine_configuration(runtime_root=runtime_root, registry=owner, configuration=configuration) - configure_machine_configuration(runtime_root=runtime_root, registry=owner, configuration=configuration, + applied = configure_machine_configuration(runtime_root=runtime_root, registry=owner, configuration=configuration, execute=True, expected_plan_revision=preview["plan_revision"]) stored = json.loads(store.read_text())["namespaces"]["todo_replan_cadence"] assert stored == {"schema_version": "todo_replan_cadence_machine_defaults_v2", - "count_unit": "effective_turns", "count": 4} + "count_unit": "effective_turns", "count": 4, + "stride_strategy": "evidence_conditioned_v1"} + assert "stride_strategy" not in ( + applied["machine_configuration"]["namespaces"]["todo_replan_cadence"] + ) + review_after = _cadence_review(registry_path, runtime_root) + assert "stride_strategy" not in review_after["machine_current"] + assert "stride_strategy" not in review_after["effective_configuration"]["configuration"] @pytest.mark.parametrize("legacy", ["off", "evidence_conditioned_v1"]) @@ -556,14 +563,22 @@ def test_legacy_stride_field_rejects_unsupported_or_ambiguous_versions(schema_ve @pytest.mark.parametrize("legacy", [None, "off", "evidence_conditioned_v1"]) def test_v2_machine_defaults_make_stride_strategy_optional_on_read(legacy): + from loopx.capabilities.todo_replan_cadence.machine_defaults import ( + todo_replan_cadence_machine_configuration_namespace, + ) + raw = {"schema_version": "todo_replan_cadence_machine_defaults_v2", "count_unit": "effective_turns", "count": 6, "yardstick_enabled": True} if legacy is not None: raw["stride_strategy"] = legacy - assert normalize_todo_replan_cadence_machine_defaults(raw) == { + normalized = normalize_todo_replan_cadence_machine_defaults(raw) + assert normalized == { "schema_version": "todo_replan_cadence_machine_defaults_v2", "count_unit": "effective_turns", "count": 6, "yardstick_enabled": True, + "stride_strategy": "evidence_conditioned_v1", } + ns = todo_replan_cadence_machine_configuration_namespace() + assert "stride_strategy" not in ns.project_public(normalized) def test_horizon_goal_defaults_on_with_explicit_overrides_and_clear(tmp_path): @@ -727,10 +742,82 @@ def test_legacy_cadence_keeps_yardstick_absent_and_default_off(version): legacy.update({"completed_todos": 2} if version == 0 else {"count_unit": "effective_turns", "count": 6}) expected = dict(legacy) if version == 2: - legacy["stride_strategy"] = "off" # legacy v2 files load; the field is dropped + legacy["stride_strategy"] = "off" # legacy v2 files load; persisted v2 writes keep rollback key + expected["stride_strategy"] = "evidence_conditioned_v1" assert normalize_todo_replan_cadence_machine_defaults(legacy) == expected machine = {"schema_version": "loopx_machine_configuration_v0", "namespaces": {"todo_replan_cadence": legacy}} assert "yardstick_enabled" not in apply_todo_replan_cadence_machine_default({}, machine)["execution_profile"] if version < 2: with pytest.raises(ValueError): normalize_todo_replan_cadence_machine_defaults({**legacy, "yardstick_enabled": True}) + + +def test_v2_machine_defaults_persist_stride_strategy_for_rollback_while_public_omits_it( + tmp_path: Path, +) -> None: + from loopx.capabilities.machine_configuration.contract import merge_machine_configuration_namespace + from loopx.capabilities.machine_configuration.store import ( + inspect_machine_configuration, + machine_configuration_store_path, + project_machine_configuration, + ) + + _repo, registry_path, runtime_root = _fixture(tmp_path) + owner = build_builtin_machine_configuration_registry() + store = machine_configuration_store_path(runtime_root) + pre_upgrade = json.loads(store.read_text(encoding="utf-8")) + pre_upgrade["namespaces"]["todo_replan_cadence"] = { + "schema_version": "todo_replan_cadence_machine_defaults_v2", + "count_unit": "effective_turns", + "count": 4, + "stride_strategy": "off", + } + store.write_text(json.dumps(pre_upgrade), encoding="utf-8") + + # Edit review cadence via public update; stride_strategy is not accepted in public writes. + updated = merge_machine_configuration_namespace( + _machine_configuration(), + namespace="todo_replan_cadence", + namespace_configuration={ + "schema_version": "todo_replan_cadence_machine_defaults_v2", + "count_unit": "effective_turns", + "count": 5, + }, + registry=owner, + ) + preview = configure_machine_configuration( + runtime_root=runtime_root, registry=owner, configuration=updated, + ) + applied = configure_machine_configuration( + runtime_root=runtime_root, + registry=owner, + configuration=updated, + execute=True, + expected_plan_revision=preview["plan_revision"], + ) + + # Raw persisted bytes satisfy the prior v2 reader's required schema keys. + persisted = json.loads(store.read_text(encoding="utf-8"))["namespaces"]["todo_replan_cadence"] + assert set(persisted) == { + "schema_version", "count_unit", "count", "stride_strategy", + } + assert persisted == { + "schema_version": "todo_replan_cadence_machine_defaults_v2", + "count_unit": "effective_turns", + "count": 5, + "stride_strategy": "evidence_conditioned_v1", + } + + # Public projections and capability views continue omitting the removed switch. + inspected = inspect_machine_configuration(runtime_root, registry=owner) + assert "stride_strategy" not in applied["machine_configuration"]["namespaces"]["todo_replan_cadence"] + assert "stride_strategy" not in inspected["machine_configuration"]["namespaces"]["todo_replan_cadence"] + assert "stride_strategy" not in project_machine_configuration( + json.loads(store.read_text(encoding="utf-8")), registry=owner, + )["namespaces"]["todo_replan_cadence"] + review = _cadence_review(registry_path, runtime_root) + assert review["machine_current"] == { + "schema_version": "todo_replan_cadence_machine_defaults_v2", + "count_unit": "effective_turns", + "count": 5, + } diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index 871778c457..3647104169 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -4873,6 +4873,7 @@ def test_legacy_todo_guard_keeps_current_replan_gate_strict( for event in events: if event.get("event_kind") == "quota_should_run": event["details"].pop("semantic_replan_obligation_id", None) + event["details"].pop("semantic_replan_stride_strategy", None) log_path.write_text( "".join(json.dumps(event) + "\n" for event in events), encoding="utf-8", diff --git a/tests/control_plane/test_refresh_state_replan_gate.py b/tests/control_plane/test_refresh_state_replan_gate.py index f0420a63e1..ed8d884e3b 100644 --- a/tests/control_plane/test_refresh_state_replan_gate.py +++ b/tests/control_plane/test_refresh_state_replan_gate.py @@ -1783,3 +1783,312 @@ def test_writeback_uses_configured_completion_cadence(threshold: int) -> None: ) with pytest.raises(ReplanWritebackRejected): enforce_open_replan_writeback(**arguments, registry_goal=goal) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("legacy_source", ["goal_profile", "machine_default"]) +def test_preupgrade_off_receipt_turn_settles_across_upgrade_and_new_turn_enforces_stride( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + provider: str, + legacy_source: str, +) -> None: + from loopx.control_plane.quota.effect_program import SettlementIdentity + from loopx.rollout_event_log import ( + append_rollout_event, + build_rollout_event, + load_rollout_events, + rollout_event_log_path, + ) + + project = tmp_path / "project" + state = project / ".codex" / "goals" / GOAL_ID / "ACTIVE_GOAL_STATE.md" + state.parent.mkdir(parents=True) + state.write_text(_state_with_scoped_blocker_todo(), encoding="utf-8") + goal_entry: dict = { + "id": GOAL_ID, + "status": "active", + "domain": "engineering", + "repo": str(project), + "state_file": str(state.relative_to(project)), + "adapter": { + "kind": "fixture_connected_delivery_v0", + "status": "connected-delivery", + }, + "coordination": { + "agent_model": "peer_v1", + "registered_agents": [AGENT_ID], + }, + } + if legacy_source == "goal_profile": + goal_entry["execution_profile"] = {"stride_strategy": "off"} + registry_path = tmp_path / "registry.json" + registry_path.write_text( + json.dumps({"goals": [goal_entry]}), + encoding="utf-8", + ) + runtime_root = tmp_path / "runtime" + runs_index = runtime_root / "goals" / GOAL_ID / "runs" / "index.jsonl" + runs_index.parent.mkdir(parents=True, exist_ok=True) + initialize_canonical_source_fixture(runtime_root, GOAL_ID, state_path=state, provider=provider) + + obs_a = { + "schema_version": "typed_progress_observation_v0", + "result_class": "blocked", + "blocker_id": "blocker-preupgrade-repeat", + "evidence_ids": ["evidence-preupgrade-repeat"], + } + runs = [] + for idx in range(2): + row = { + "generated_at": f"2026-08-13T12:0{idx}:00+08:00", + "goal_id": GOAL_ID, + "classification": "state_refreshed", + "agent_id": AGENT_ID, + "progress_scope": "agent_lane", + "delivery_outcome": "outcome_gap", + "progress_observation": dict(obs_a), + } + with runs_index.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(row) + "\n") + runs.append(row) + + if legacy_source == "machine_default": + machine_path = runtime_root / "machine" / "configuration.json" + machine_path.parent.mkdir(parents=True, exist_ok=True) + machine_path.write_text( + json.dumps( + { + "schema_version": "loopx_machine_configuration_v0", + "namespaces": { + "todo_replan_cadence": { + "schema_version": "todo_replan_cadence_machine_defaults_v2", + "count_unit": "effective_turns", + "count": 6, + "stride_strategy": "off", + } + }, + } + ), + encoding="utf-8", + ) + + newest_runs = list(reversed(runs)) + obligation, _ = qualify_replan_writeback( + newest_first_runs=newest_runs, + state_text=state.read_text(encoding="utf-8"), + agent_id=AGENT_ID, + goal_id=GOAL_ID, + registry_goal=goal_entry, + ) + assert obligation is not None + obligation_id = obligation["obligation_id"] + + # Append a pre-upgrade `quota_should_run` receipt (no `semantic_replan_stride_strategy`) + # admitted when raw configuration had `stride_strategy == "off"`. + preupgrade_turn = "turn-preupgrade-off" + preupgrade_identity = SettlementIdentity( + goal_id=GOAL_ID, + agent_id=AGENT_ID, + todo_id=None, + replan_obligation_id=obligation_id, + turn_instance_id=preupgrade_turn, + ) + append_rollout_event( + rollout_event_log_path(runtime_root, GOAL_ID), + build_rollout_event( + goal_id=GOAL_ID, + event_kind="quota_should_run", + agent_id=AGENT_ID, + run_id=preupgrade_turn, + summary="Pre-upgrade stride-off replan admission.", + details={ + "command": "quota", + "quota_command": "should-run", + "ok": True, + "should_run": True, + "appended": True, + "todo_id": "", + "replan_obligation_id": obligation_id, + "semantic_replan_obligation_id": obligation_id, + "settlement_effect_id": preupgrade_identity.effect_id, + "must_attempt_work": True, + "delivery_allowed": True, + "quiet_noop_allowed": False, + "closeout_required": False, + }, + ), + ) + + def _load_quota_should_run_decision(raw_stdout: str) -> dict: + out = json.loads(raw_stdout) + if "reference_file" in out: + nav = json.loads(Path(out["reference_file"]).read_text(encoding="utf-8")) + payload = json.loads(Path(nav["path"]).read_text(encoding="utf-8")) + else: + payload = out + packet = payload.get("replan_action_packet") + if isinstance(packet, dict) and isinstance(packet.get("writeback"), str): + tokens = shlex.split(packet["writeback"]) + if "--decision-file" in tokens: + dec_path = tokens[tokens.index("--decision-file") + 1] + return json.loads(Path(dec_path).read_text(encoding="utf-8")) + return payload + + # Replay `quota should-run` for `preupgrade_turn` before settlement: it must keep + # the pre-upgrade `"off"` packet shape and must not inject `semantic_replan_stride_strategy`. + capsys.readouterr() + rc = cli_main( + [ + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "--format", + "json", + "quota", + "should-run", + "--codex-app", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--turn-instance-id", + preupgrade_turn, + ] + ) + assert rc == 0 + replayed = _load_quota_should_run_decision(capsys.readouterr().out) + replayed_packet = replayed["replan_action_packet"] + assert "stride_control" not in replayed_packet + assert "agent_vision.stride_decision" not in ( + (replayed_packet.get("writeback_contract") or {}).get("required_fields") or [] + ) + preupgrade_events = [ + ev + for ev in load_rollout_events(rollout_event_log_path(runtime_root, GOAL_ID)) + if ev.get("event_kind") == "quota_should_run" and ev.get("run_id") == preupgrade_turn + ] + assert preupgrade_events + assert all( + "semantic_replan_stride_strategy" not in (ev.get("details") or {}) + for ev in preupgrade_events + ) + + # Original pre-upgrade writeback without stride_decision must succeed and preserve identity. + settled = refresh_state_run( + registry_path=registry_path, + runtime_root_override=str(runtime_root), + goal_id=GOAL_ID, + project=project, + state_file=None, + classification="state_refreshed", + recommended_action="Settle pre-upgrade off turn.", + delivery_batch_scale="single_surface", + delivery_outcome="outcome_gap", + agent_id=AGENT_ID, + turn_instance_id=preupgrade_turn, + replan_obligation_id=obligation_id, + autonomous_replan_recorded=True, + repair_delta_kinds=["blocker"], + progress_observation={ + "schema_version": "typed_progress_observation_v0", + "result_class": "blocked", + "blocker_id": "blocker-preupgrade-settled", + "evidence_ids": ["evidence-preupgrade-settled"], + "work_item_id": obligation_id, + }, + agent_vision_packet=None, + dry_run=False, + sync_global=False, + ) + assert settled.get("ok") is True + assert settled["settlement_identity"]["effect_id"] == preupgrade_identity.effect_id + assert settled["settlement_identity"]["replan_obligation_id"] == obligation_id + + # Now append a fresh repeated typed observation to trigger a new replan obligation, + # and verify that a newly admitted Turn on the same untouched legacy Goal stamps + # `semantic_replan_stride_strategy = "evidence_conditioned_v1"` and enforces stride. + obs_b = { + "schema_version": "typed_progress_observation_v0", + "result_class": "blocked", + "blocker_id": "blocker-postupgrade-repeat", + "evidence_ids": ["evidence-postupgrade-repeat"], + } + with runs_index.open("a", encoding="utf-8") as handle: + for idx in range(2): + handle.write( + json.dumps( + { + "generated_at": f"2099-08-13T13:0{idx}:00+08:00", + "goal_id": GOAL_ID, + "classification": "state_refreshed", + "agent_id": AGENT_ID, + "progress_scope": "agent_lane", + "delivery_outcome": "outcome_gap", + "progress_observation": dict(obs_b), + } + ) + + "\n" + ) + capsys.readouterr() + postupgrade_turn = "turn-postupgrade-enforced" + rc = cli_main( + [ + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "--format", + "json", + "quota", + "should-run", + "--codex-app", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--turn-instance-id", + postupgrade_turn, + ] + ) + assert rc == 0 + admitted = _load_quota_should_run_decision(capsys.readouterr().out) + assert "stride_control" in admitted["replan_action_packet"] + new_obligation_id = admitted["autonomous_replan_obligation"]["obligation_id"] + events = [ + ev + for ev in load_rollout_events(rollout_event_log_path(runtime_root, GOAL_ID)) + if ev.get("event_kind") == "quota_should_run" and ev.get("run_id") == postupgrade_turn + ] + assert events and events[-1]["details"]["semantic_replan_stride_strategy"] == "evidence_conditioned_v1" + + before_lines = runs_index.read_text(encoding="utf-8").splitlines() + with pytest.raises(ValueError, match="stride_decision"): + refresh_state_run( + registry_path=registry_path, + runtime_root_override=str(runtime_root), + goal_id=GOAL_ID, + project=project, + state_file=None, + classification="state_refreshed", + recommended_action="Must require stride_decision on new turn.", + delivery_batch_scale="single_surface", + delivery_outcome="outcome_gap", + agent_id=AGENT_ID, + turn_instance_id=postupgrade_turn, + replan_obligation_id=new_obligation_id, + autonomous_replan_recorded=True, + repair_delta_kinds=["blocker"], + progress_observation={ + "schema_version": "typed_progress_observation_v0", + "result_class": "blocked", + "blocker_id": "blocker-postupgrade-new", + "evidence_ids": ["evidence-postupgrade-new"], + "work_item_id": new_obligation_id, + }, + agent_vision_packet=None, + dry_run=False, + sync_global=False, + ) + assert runs_index.read_text(encoding="utf-8").splitlines() == before_lines diff --git a/tests/control_plane_ts/quota_settlement_readback.test.ts b/tests/control_plane_ts/quota_settlement_readback.test.ts index a7634d6793..aad38365ce 100644 --- a/tests/control_plane_ts/quota_settlement_readback.test.ts +++ b/tests/control_plane_ts/quota_settlement_readback.test.ts @@ -74,10 +74,37 @@ test("semantic replan guard distinguishes legacy, none, and exact selection", () scope: "turn_guard", selected_obligation_id: "replan-0000000000000001", }); + assert.deepEqual(projectSemanticReplanGuard({ + semantic_replan_obligation_id: "replan-0000000000000001", + semantic_replan_stride_strategy: "evidence_conditioned_v1", + }), { + schema_version: "semantic_replan_guard_v0", + scope: "turn_guard", + selected_obligation_id: "replan-0000000000000001", + admitted_stride_strategy: "evidence_conditioned_v1", + }); assert.throws( () => projectSemanticReplanGuard({ semantic_replan_obligation_id: "bad" }), /semantic replan guard is malformed/, ); + assert.throws( + () => projectSemanticReplanGuard({ semantic_replan_stride_strategy: "evidence_conditioned_v1" }), + /selected obligation/, + ); + assert.throws( + () => projectSemanticReplanGuard({ + semantic_replan_obligation_id: "", + semantic_replan_stride_strategy: "evidence_conditioned_v1", + }), + /selected obligation/, + ); + assert.throws( + () => projectSemanticReplanGuard({ + semantic_replan_obligation_id: "replan-0000000000000001", + semantic_replan_stride_strategy: "invalid_strategy", + }), + /semantic_replan_stride_strategy is malformed/, + ); }); test("capability guard survives scalar receipt transport and rejects missing scope facts", () => { diff --git a/tests/control_plane_ts/replan_semantics.test.ts b/tests/control_plane_ts/replan_semantics.test.ts index 177675986d..2c951248f3 100644 --- a/tests/control_plane_ts/replan_semantics.test.ts +++ b/tests/control_plane_ts/replan_semantics.test.ts @@ -1132,3 +1132,63 @@ test("pending lifecycle survives a new frontier without granting settlement or s assert.throws(() => projectReplanSemantics({...request, transition_candidates: [{...candidate, lifecycle_settled: true}]}), /identity conflicts/); }); + +test("pre-upgrade off turns preserve original transition and qualify semantics while live turns require stride_decision", () => { + const periodic = {obligation_id: defaultObligationId, triggers: [{kind: "periodic_review_due"}], + replan_context: {obligation_id: defaultObligationId, context_id: defaultContextId, stride_strategy: "off"}}; + const observation = {delta_kinds: ["new_surface"]}; + + // Unscoped/live defaults enforce evidence_conditioned_v1 even if historical context says off. + assert.deepEqual(projectReplanSemantics({operation: "transition_eligibility", obligation: periodic}), {allowed: false}); + const liveRejected = projectReplanSemantics({operation: "qualify", obligation: periodic, observation_delta: observation}); + assert.equal(liveRejected.accepted, false); + + // Explicit admitted_stride_strategy="off" preserves pre-upgrade settlement across qualify, transition, and requirements. + assert.deepEqual(projectReplanSemantics({ + operation: "transition_eligibility", obligation: periodic, admitted_stride_strategy: "off", + }), {allowed: true}); + const offQualify = projectReplanSemantics({ + operation: "qualify", obligation: periodic, observation_delta: observation, admitted_stride_strategy: "off", + }); + assert.equal(offQualify.accepted, true); + assert.deepEqual(offQualify.satisfying_outcomes, ["new_surface"]); + + const offReqs = projectReplanSemantics({ + operation: "requirements", obligation: periodic, admitted_stride_strategy: "off", + }); + assert.equal(Object.hasOwn(offReqs, "stride_control"), false); + assert.equal(((offReqs.writeback_contract as JsonObject).required_fields as string[]).includes("agent_vision.stride_decision"), false); + + const repeat = {obligation_id: defaultObligationId, triggers: [{kind: "typed_progress_repeat"}], + replan_context: {obligation_id: defaultObligationId, context_id: defaultContextId, stride_strategy: "off"}}; + const offRepeatReqs = projectReplanSemantics({ + operation: "requirements", obligation: repeat, admitted_stride_strategy: "off", + }); + assert.equal(Object.hasOwn(offRepeatReqs, "stride_control"), false); + assert.equal((offRepeatReqs.required_any_of as string[]).includes("fresh_vision_path_outcome"), false); + assert.equal((((offRepeatReqs.writeback_contract as JsonObject).required_fields as string[] | undefined) ?? []).includes("agent_vision.stride_decision"), false); + + const livePeriodicReqs = projectReplanSemantics({operation: "requirements", obligation: periodic}); + assert.equal(Object.hasOwn(livePeriodicReqs, "stride_control"), true); + assert.equal(((livePeriodicReqs.writeback_contract as JsonObject).required_fields as string[]).includes("agent_vision.stride_decision"), true); + + const liveRepeatReqs = projectReplanSemantics({ + operation: "requirements", obligation: repeat, admitted_stride_strategy: "evidence_conditioned_v1", + }); + assert.equal(Object.hasOwn(liveRepeatReqs, "stride_control"), true); + assert.equal(((liveRepeatReqs.writeback_contract as JsonObject).required_fields as string[]).includes("agent_vision.stride_decision"), true); + + const delta = {schema_version: "replan_semantic_delta_v0", accepted: true, + obligation_id: defaultObligationId, successor_todo_id: "todo_off_successor", + outcomes: ["new_runnable_successor"], satisfying_outcomes: ["new_runnable_successor"]}; + const ack = {schema_version: "autonomous_replan_ack_v0", recorded: true, + source: "todo_replan_successor_transition", semantic_delta: delta}; + assert.equal(projectReplanSemantics({ + operation: "turn_transition", guard_scoped: true, selected_obligation_id: defaultObligationId, + transition_candidates: [{obligation: periodic, ack}], + }).semantic_delta, null); + assert.deepEqual(projectReplanSemantics({ + operation: "turn_transition", guard_scoped: true, selected_obligation_id: defaultObligationId, + transition_candidates: [{obligation: periodic, ack}], admitted_stride_strategy: "off", + }).semantic_delta, delta); +}); From 5448ed57416b0606f1014aac4384b32e27438a08 Mon Sep 17 00:00:00 2001 From: huangruiteng Date: Mon, 23 Nov 2026 19:42:23 +0800 Subject: [PATCH 3/3] Complete the benchmark wake fixture used by runtime-root tests Signed-off-by: huangruiteng --- benchmark/tests/test_task_entry.py | 1 + 1 file changed, 1 insertion(+) diff --git a/benchmark/tests/test_task_entry.py b/benchmark/tests/test_task_entry.py index 86be3cc24d..24be01e1d1 100644 --- a/benchmark/tests/test_task_entry.py +++ b/benchmark/tests/test_task_entry.py @@ -1377,6 +1377,7 @@ def _fake_session_wake(wake_env, *a, **kw): receipt={"action": "start_new" if context == "fresh" else "resume", "session_id": "sess-" + context}, goal_ref=None, admission=None, + binding=None, observe=lambda *_: None, host_launch_decision=lambda *_: None, )