diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index c87c645eca..9f57aa581e 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -4234,3 +4234,26 @@ File/SQLite negative cases guard this boundary without changing valid activation progressive controls, comparable complete costs, full V1–V5/V10, R1/M3 and C1 cutover remain unqualified. Preserve original requirements and earlier negative evidence; run full original-goal regression before completion. + +### 2026-11-15 — Native Tasks consume existing owner Goal checks + +- **Gap:** a managed Native Task refused to execute with owner-configured Goal + acceptance alone, requiring a duplicate Task argv declaration. +- **Delta:** the existing canonical Task validation plan now serves Native and + Delegation. Native reads current Goal scope and private Task declarations from + their existing owners, runs cumulative Goal and required Task checks, and + rechecks definition, work, claim, lifecycle and checker assets before and after + validation. Required declarations, applicable unbound/stale checks and changed + sources cannot fall back to a weaker check. Task argv keeps typed-result stdin + and the existing Turn receipt; legacy non-argv declarations retain refusal. +- **Evidence:** the Goal-only refusal is reproduced on the prior Native consumer. + Shared TypeScript behavior matches the immutable baseline in 54 compatibility + vectors. Real isolated Chat/Core/canonical tests cover Goal-only and combined + execution, HTTP readback/replay, independent failures, corrupt declarations, + source changes before and after checks, and unrelated progress observations. +- **Boundary:** this removes duplicate validation setup for already configured + Goal checks on V2/V4/R1. It does not install a trusted checker for a new natural + language Goal, authorize model/browser commands, or complete automatic first + Task adoption. Full V1–V5/V10, native-model/context retention, D2/D5 closure, + progressive controls, comparable complete costs, R1/M3 and C1 cutover remain + unqualified; preserve original acceptance and full-goal regression gates. diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md index 59523d6f25..7f61d428c7 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -3288,3 +3288,21 @@ R1/M3、C1 切换和原目标回归仍未完成资格验证。 原 Task、选定 D2/D5 闭包、原生 App/模型与 compaction 保留、渐进控制、 可比完整成本、完整 V1–V5/V10、R1/M3 和 C1 切换仍未通过资格验证。原要求 与此前负面证据保留;完成目标前仍需完整原目标回归。 + +### 2026-11-15 — Native Task 消费既有 owner Goal 检查 + +- **缺口:**managed Native Task 即使有 owner 配置的 Goal 验收,也会拒绝执行, + 要求重复声明 Task argv 校验器。 +- **增量:**既有 canonical Task 验证计划由 Native 和 Delegation 共用。Native + 从既有 owner 读取当前 Goal 范围和私有 Task 声明,累加执行 Goal 与必需 Task + 检查;验证前后复核定义、工作、认领、生命周期和检查器资产。必需声明缺失、 + 适用但未绑定或过期的检查,以及来源变化,都不能降级为更弱的检查。Task argv + 保留 typed-result stdin 和既有 Turn receipt;旧非 argv 声明继续拒绝。 +- **证据:**原 Native 消费路径已复现 Goal-only 拒绝;共享 TypeScript 在 54 组 + 兼容向量上与不可变基线一致。真实隔离 Chat/Core/canonical 测试覆盖 Goal-only + 与组合执行、HTTP 读回与重放、独立检查失败、声明损坏、检查前后来源变更和 + 无关进展观察。 +- **边界:**本次消除 V2/V4/R1 中既有 Goal 检查的重复配置,不为新的自然语言 + Goal 安装可信检查器,不授权模型或 browser 命令,也不完成首个 Task 自动采用。 + 完整 V1–V5/V10、原生模型与 context 保留、D2/D5 闭包、渐进控制、可比完整成本、 + R1/M3 和 C1 切换仍未通过资格验证;原验收与完整目标回归门继续保留。 diff --git a/loopx/capabilities/native_chat/steward_managed_mode.py b/loopx/capabilities/native_chat/steward_managed_mode.py index 1fe8028c5c..5eea668732 100644 --- a/loopx/capabilities/native_chat/steward_managed_mode.py +++ b/loopx/capabilities/native_chat/steward_managed_mode.py @@ -180,7 +180,7 @@ def health(self, binding_id: str) -> dict[str, Any]: class ManagedTaskValidationUnavailable(ValueError): - """A native selection has no usable caller-declared independent validator.""" + """A native selection has no usable owner-declared independent validator.""" def managed_session_identity(controller: Any, *, goal_id: str, agent_id: str, workspace: Path, @@ -434,19 +434,40 @@ def submit(self, session_id: str, *, agent_id: str, operation_id: str, return accepted.turn, accepted.created def _validation_source(self, request: dict[str, Any], todo_id: str) -> dict[str, Any]: - from ...control_plane.todos.list_readback import list_goal_todos - readback = list_goal_todos(registry_path=self.controller.registry_path, goal_id=request["actor"]["goal_id"], - todo_id=todo_id, role="agent", runtime_root_arg=str(self.controller.coordination_runtime_root)) - rows = [readback["todo"]] if readback.get("todo") else [] - if len(rows) != 1 or rows[0].get("completion_validation_required") is not True: + from ...control_plane.effect_runtime import effect_runtime_result + from ...control_plane.goals.acceptance import inspect_goal_acceptance, validation_effect_files_current + from ...control_plane.todos.completion_validation import resolve_private_completion_validation_declaration + from ...materials import goal_state_path + actor = request["actor"] + workspace = Path(actor["workspace_path"]) + basis = inspect_goal_acceptance(registry_path=self.controller.registry_path, + runtime_root=str(self.controller.coordination_runtime_root), goal_id=actor["goal_id"], + agent_id=actor["agent_id"], todo_id=todo_id, validation_workspace_path=workspace) + todo = basis.get("todo") + goal = load_goal_from_registry(self.controller.registry_path, actor["goal_id"]) + if not isinstance(todo, dict) or goal is None: + raise ManagedTaskValidationUnavailable("the selected task's canonical validation source is unavailable") + declaration = resolve_private_completion_validation_declaration(canonical_todo=todo, + state_file=goal_state_path(goal), runtime_root=self.controller.coordination_runtime_root, + registry_path=self.controller.registry_path, goal_id=actor["goal_id"], todo_id=todo_id, + role=todo.get("role"), persist_if_resolved=False) + # Only the existing owner can resolve acceptance to explicit null. + # Applicable unbound/stale checks and failed reads must never fall back. + plan = effect_runtime_result("goal.task.validation_plan", { + "todo_id": todo_id, "basis": basis, "declaration": declaration}) + if plan["state"] != "ready": raise ManagedTaskValidationUnavailable("the selected task needs its existing independent argv validation declaration") - return rows[0] + if not validation_effect_files_current(effects=plan["effects"], + registry_path=self.controller.registry_path, goal_id=actor["goal_id"], + validation_workspace_path=workspace): + raise ManagedTaskValidationUnavailable("the selected task's declared verifier files changed or are unavailable") + return {**todo, "plan": plan} def prepare_validation(self, request: dict[str, Any], native_request: dict[str, Any], *, _checked_work_identity: dict[str, str] | None = None) -> None: from ...control_plane.turn_driver.driver import selected_turn_todo, turn_host_lineage from ...control_plane.turn_driver.command_validation import build_loopx_turn_command_validator - from ...control_plane.todos.completion_validation_store import read_completion_validation_declaration + from ...control_plane.goals.acceptance import run_goal_acceptance_validation_effect # Dispatch can reuse its just-checked identity within this invocation; # direct callers still check the complete source through the same owner. if "work_contract" in native_request: @@ -460,20 +481,47 @@ def prepare_validation(self, request: dict[str, Any], native_request: dict[str, self.validation_basis = self._validation_source(request, selected["todo_id"]) if re.fullmatch(r"cadence_[a-f0-9]{64}", self.validation_basis.get("target_key") or "") and request.get("work_kind") != "scheduled_task": raise ValueError("the original calendar Task must execute through its scheduled Session admission") - declaration = read_completion_validation_declaration(runtime_root=self.controller.coordination_runtime_root, - goal_id=request["actor"]["goal_id"], todo_id=selected["todo_id"], - expected_digest=self.validation_basis["completion_validation_sha256"]) - if not declaration or not declaration.get("validation_command_argv"): - raise ManagedTaskValidationUnavailable("the selected task requires its existing argv validation declaration") - self.task_validator = build_loopx_turn_command_validator(declaration["validation_command_argv"], - project=Path(request["actor"]["workspace_path"]), timeout_seconds=declaration.get("validation_timeout_seconds") or 20) + actor = request["actor"] + workspace = Path(actor["workspace_path"]) + validators = [] + for effect in self.validation_basis["plan"]["effects"]: + if "criterion_id" not in effect: + if not effect.get("validation_argv"): + raise ManagedTaskValidationUnavailable("the selected task requires its existing argv validation declaration") + # Preserve raw typed model-result JSON on the command's stdin, + # plus its existing receipt and optional reflection attestation. + validators.append(build_loopx_turn_command_validator(effect["validation_argv"], + project=workspace, timeout_seconds=effect["validation_timeout_seconds"] or 20)) + else: + def goal_check(_plan, _result, effect=effect): + receipt = run_goal_acceptance_validation_effect(effect=effect, + registry_path=self.controller.registry_path, goal_id=actor["goal_id"], + validation_workspace_path=workspace) + return {"status": "passed" if receipt["passed"] else "failed", + "validator_kind": "command", "summary": receipt.get("summary") or + ("independent Goal acceptance check passed" if receipt["passed"] else + "independent Goal acceptance check failed"), + "exit_code": receipt["exit_code"], + **({"recovery_kind": "repair_required"} if not receipt["passed"] else {})} + validators.append(goal_check) + + def validate_checks(plan, result): + receipts = [check(plan, result) for check in validators] + if len(receipts) == 1: + return receipts[0] + failed = next((row for row in receipts if row["status"] != "passed"), None) + # Keep the existing receipt contract and the caller's optional + # reflection attestation. Every required check has executed. + return failed or {**receipts[-1], "summary": f"{len(receipts)} independent task checks passed"} + + self.task_validator = validate_checks def validator(self, request: dict[str, Any], *, turn_id: str): - """Resolve only the native selection's immutable, caller-declared argv. + """Execute the current owner-resolved Goal and required Todo checks. No browser or model argument may install a host validation command. - The captured canonical digest and fresh source must agree before and - after the existing command validator reads the task's real artifact. + Definition, work, claim and lifecycle must agree before and after the + existing validators read the task's real artifact. """ from ...control_plane.turn_driver.driver import ( COMPLETE_TURN_PLAN_SCHEMA_VERSION, selected_turn_todo, turn_host_lineage, @@ -486,15 +534,15 @@ def validate(plan, result): selected = (turn_host_lineage(plan) if "work_contract" in plan or plan.get("schema_version") == COMPLETE_TURN_PLAN_SCHEMA_VERSION else selected_turn_todo(plan.get("turn_envelope") or {})) basis = self.validation_basis - if not basis or not self.task_validator or basis["todo_id"] != selected["todo_id"]: + if not basis or not self.task_validator or basis["plan"]["todo_id"] != selected["todo_id"]: raise ValueError("the original task validation source was not captured before model work") def current(): self.admit(request, turn=self.store.load_turn(actor["session_id"], turn_id)) fresh = self._validation_source(request, selected["todo_id"]) - if any(fresh.get(key) != basis.get(key) for key in - ("completion_validation_sha256", "completion_validation_revision")): - raise ValueError("the selected task's validation declaration changed") + if (fresh["plan"]["task_basis_sha256"] != basis["plan"]["task_basis_sha256"] + or fresh["plan"]["observation"]["basis_sha256"] != basis["plan"]["observation"]["basis_sha256"]): + raise ValueError("the selected task's validation source or work changed") current() receipt = self.task_validator(plan, result) diff --git a/loopx/control_plane/collaboration/delegation.ts b/loopx/control_plane/collaboration/delegation.ts index 0d98cb7cc1..b07f402b96 100644 --- a/loopx/control_plane/collaboration/delegation.ts +++ b/loopx/control_plane/collaboration/delegation.ts @@ -4,7 +4,7 @@ import {executionRequestSubject, type JsonObject} from "../effect_program.ts"; import {requireInteger, requireJsonObject, requireStringArray} from "../runtime_decode.ts"; import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; import {canonicalAuthoritySha256} from "../coordination/authority_store_codec.ts"; -import {acceptanceValidationEffects, goalAcceptanceTodoDigest, type AcceptanceCompletionRequirements} from "../goals/acceptance_contract.ts"; +import {canonicalTaskValidationPlan} from "../goals/task_validation_plan.ts"; import {normalizeTodoCompletionValidationDeclaration} from "../todos/completion_validation_declaration.ts"; import {readTurnSelectionRejection, turnSelectionRejectionState} from "../turn_driver/selection_rejection.ts"; import { BARE_SHA256_PATTERN } from "../content_digest.ts"; @@ -43,57 +43,27 @@ export function delegationValidationPlan(params: JsonObject): JsonObject { observation: {source: "request_validation", basis_sha256: canonicalAuthoritySha256({binding, effects}), check_count: effects.length, pinned_file_count: 0}}; } - const basis = requireJsonObject(params.basis, "canonical validation basis"); - const todo = requireJsonObject(basis.todo, "canonical delegation Todo"); - requireThat(basis.status === "loaded" && text(basis.provider_revision) - && todo.todo_id === binding.todo_id, "delegation requires a current matching canonical Todo"); - requireThat(Object.hasOwn(basis, "completion_requirements"), "canonical acceptance scope required"); - const requirements = basis.completion_requirements === null ? null - : requireJsonObject(basis.completion_requirements, "canonical acceptance requirements"); - if (requirements !== null) requireThat(requirements.todo_id === todo.todo_id - && Array.isArray(requirements.criteria) && requirements.criteria.length > 0, - "delegation requires matching owner acceptance criteria"); - const unavailable = (reason: string) => ({todo_id: todo.todo_id, state: "unbound", - source: null, reason, effects: [], canonical_done: false}); - const effects: JsonObject[] = requirements === null ? [] - : acceptanceValidationEffects(requirements as AcceptanceCompletionRequirements, todo) - .map(row => ({...requireJsonObject(row.effect, "acceptance validation effect"), criterion_id: row.criterion_id})); - if (todo.completion_validation_required === true) { - if (params.declaration === null) return unavailable("completion_validation_declaration_unavailable"); - const declaration = requireJsonObject(params.declaration, "private validation declaration"); - const normalized = normalizeTodoCompletionValidationDeclaration(declaration, { - strict_fields: true, require_command: true, require_canonical_input: true, - }); - if (!normalized.ok || canonicalAuthoritySha256(declaration) !== todo.completion_validation_sha256) - return unavailable("completion_validation_declaration_mismatch"); - effects.push({kind: "caller_validation", validation_command: normalized.value.validation_command, - validation_argv: normalized.value.validation_command_argv, - validation_label: normalized.value.validation_label, - validation_timeout_seconds: normalized.value.validation_timeout_seconds, - validation_declaration_sha256: todo.completion_validation_sha256, - task_repository: todo.task_repository ?? null}); - } else { - requireThat(params.declaration === null && todo.completion_validation_sha256 == null, - "Todo without canonical validation authority cannot supply a declaration"); - if (requirements === null) return unavailable("independent_delegation_validation_required"); + let plan: JsonObject; + try { + plan = canonicalTaskValidationPlan({todo_id: binding.todo_id, + basis: params.basis, declaration: params.declaration}); + } catch (error) { + if (!(error instanceof EffectRuntimeRequestError)) throw error; + // Retain the established delegation diagnostics at this compatibility entry. + const message = error.message === "canonical task Todo must be an object" + ? "canonical delegation Todo must be an object" + : error.message === "canonical task requires a current matching canonical Todo" + ? "delegation requires a current matching canonical Todo" + : error.message === "canonical task requires matching owner acceptance criteria" + ? "delegation requires matching owner acceptance criteria" : null; + if (message === null) throw error; + throw new EffectRuntimeRequestError(message, error.code, error.details); } - const source = requirements === null ? "todo_validation" : "goal_acceptance"; - // Definition identity, not a stored success or independent-verifier receipt. - // Host validation must pass before exposing this path-free current observation. - const observation = {source, - basis_sha256: canonicalAuthoritySha256({todo_id: todo.todo_id, requirements, effects}), - check_count: effects.length, - pinned_file_count: effects.reduce((count, effect) => count - + (Array.isArray(effect.validation_files) ? effect.validation_files.length : 0), 0), - ...currentOracleChecks(basis, effects)}; - // Reuse the acceptance owner's work classification. Scheduling/progress - // metadata and unrelated provider commits are not a new task declaration; - // current claim/lifecycle still fence this particular validation attempt. - const task_basis_sha256 = canonicalAuthoritySha256({work: goalAcceptanceTodoDigest(todo), - claimed_by: todo.claimed_by ?? null, role: todo.role ?? null, - status: todo.status, done: todo.done, archive_state: todo.archive_state ?? null}); - return {todo_id: todo.todo_id, state: "ready", source, observation, task_basis_sha256, - effects, canonical_done: todo.done === true && todo.status === "done"}; + if (plan.reason === "no_declaration") + return {...plan, reason: "independent_delegation_validation_required"}; + if (plan.state !== "ready") return plan; + return {...plan, observation: {...requireJsonObject(plan.observation, "current validation observation"), + ...currentOracleChecks(requireJsonObject(params.basis, "canonical validation basis"), plan.effects as JsonObject[])}}; } /** Consume only the acceptance owner's current exact-source observation. */ diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index 862f1b739d..c4f9f80b2e 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -362,6 +362,7 @@ export function createEffectRuntimeHandlers( ["goal.source_session.turn_effect.gate", lazyHandler(() => import("./goals/source_session_lifetime.ts"), ({decideSourceTurnEffectGate}) => decideSourceTurnEffectGate)], ["goal.first_party_host_runtime.decide", lazyHandler(() => import("./goals/first_party_host_runtime.ts"), ({decideFirstPartyHostRuntime}) => decideFirstPartyHostRuntime)], ["goal.chat_session.lifecycle.decide", lazyHandler(() => import("./goals/chat_session_lifecycle.ts"), ({decideChatSessionLifecycle}) => decideChatSessionLifecycle)], + ["goal.task.validation_plan", lazyHandler(() => import("./goals/task_validation_plan.ts"), ({canonicalTaskValidationPlan}) => canonicalTaskValidationPlan)], ["goal.acceptance.oracle.plan", lazyHandler(() => import("./goals/acceptance_oracle.ts"), ({planAcceptanceOracle}) => planAcceptanceOracle)], ["goal.acceptance.oracle.observe", lazyHandler(() => import("./goals/acceptance_oracle.ts"), ({observeAcceptanceOracles}) => observeAcceptanceOracles)], ["goal.acceptance.refine", lazyHandler(() => import("./goals/acceptance_authority.ts"), ({refineLocalGoalAcceptanceOutcome}) => refineLocalGoalAcceptanceOutcome)], diff --git a/loopx/control_plane/goals/task_validation_plan.ts b/loopx/control_plane/goals/task_validation_plan.ts new file mode 100644 index 0000000000..895e573f68 --- /dev/null +++ b/loopx/control_plane/goals/task_validation_plan.ts @@ -0,0 +1,73 @@ +/** Read-only composition of checks for a canonical Todo. The host must read the + * basis and private declaration from their current owners before calling this + * pure plan; caller/model input is not authority and the plan grants no execution + * or write permission. */ +import type {JsonObject} from "../effect_program.ts"; +import {requireJsonObject} from "../runtime_decode.ts"; +import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; +import {canonicalAuthoritySha256} from "../coordination/authority_store_codec.ts"; +import {acceptanceValidationEffects, type AcceptanceCompletionRequirements} from "./acceptance_contract.ts"; +import {goalAcceptanceTodoDigest} from "./acceptance_work_basis.ts"; +import {normalizeTodoCompletionValidationDeclaration} from "../todos/completion_validation_declaration.ts"; + +function requireThat(ok: unknown, message: string): asserts ok { + if (!ok) throw new EffectRuntimeRequestError(message); +} + +/** An explicit null requirement means owner-resolved out-of-scope/disabled + * checks. Missing, unbound or stale owner acceptance must never fall back to a + * Todo-only declaration. Required Todo checks remain cumulative with Goal checks. */ +export function canonicalTaskValidationPlan(params: JsonObject): JsonObject { + const basis = requireJsonObject(params.basis, "canonical validation basis"); + const todo = requireJsonObject(basis.todo, "canonical task Todo"); + requireThat(typeof params.todo_id === "string" && params.todo_id.length > 0 && params.todo_id.length <= 4096 + && basis.status === "loaded" && typeof basis.provider_revision === "string" + && basis.provider_revision.length > 0 && basis.provider_revision.length <= 4096 + && todo.todo_id === params.todo_id, "canonical task requires a current matching canonical Todo"); + requireThat(Object.hasOwn(basis, "completion_requirements"), "canonical acceptance scope required"); + const requirements = basis.completion_requirements === null ? null + : requireJsonObject(basis.completion_requirements, "canonical acceptance requirements"); + if (requirements !== null) requireThat(requirements.todo_id === todo.todo_id + && Array.isArray(requirements.criteria) && requirements.criteria.length > 0, + "canonical task requires matching owner acceptance criteria"); + const unavailable = (reason: string) => ({todo_id: todo.todo_id, state: "unbound", + source: null, reason, effects: [], canonical_done: false}); + const effects: JsonObject[] = requirements === null ? [] + : acceptanceValidationEffects(requirements as AcceptanceCompletionRequirements, todo) + .map(row => ({...requireJsonObject(row.effect, "acceptance validation effect"), criterion_id: row.criterion_id})); + if (todo.completion_validation_required === true) { + if (params.declaration === null) return unavailable("completion_validation_declaration_unavailable"); + const declaration = requireJsonObject(params.declaration, "private validation declaration"); + const normalized = normalizeTodoCompletionValidationDeclaration(declaration, { + strict_fields: true, require_command: true, require_canonical_input: true, + }); + if (!normalized.ok || canonicalAuthoritySha256(declaration) !== todo.completion_validation_sha256) + return unavailable("completion_validation_declaration_mismatch"); + effects.push({kind: "caller_validation", validation_command: normalized.value.validation_command, + validation_argv: normalized.value.validation_command_argv, + validation_label: normalized.value.validation_label, + validation_timeout_seconds: normalized.value.validation_timeout_seconds, + validation_declaration_sha256: todo.completion_validation_sha256, + task_repository: todo.task_repository ?? null}); + } else { + requireThat(params.declaration === null && todo.completion_validation_sha256 == null, + "Todo without canonical validation authority cannot supply a declaration"); + if (requirements === null) return unavailable("no_declaration"); + } + const source = requirements === null ? "todo_validation" : "goal_acceptance"; + // Definition identity only; host checks must pass before this observation is + // exposed as a current check. Complete requirements and effects stay hashed. + const observation = {source, + basis_sha256: canonicalAuthoritySha256({todo_id: todo.todo_id, requirements, effects}), + check_count: effects.length, + pinned_file_count: effects.reduce((count, effect) => count + + (Array.isArray(effect.validation_files) ? effect.validation_files.length : 0), 0)}; + // The acceptance owner classifies work. Unknown future work fields remain + // inputs; progress/provider changes do not replace the task, while the current + // claim and lifecycle fence this particular validation attempt. + const task_basis_sha256 = canonicalAuthoritySha256({work: goalAcceptanceTodoDigest(todo), + claimed_by: todo.claimed_by ?? null, role: todo.role ?? null, + status: todo.status, done: todo.done, archive_state: todo.archive_state ?? null}); + return {todo_id: todo.todo_id, state: "ready", source, observation, task_basis_sha256, + effects, canonical_done: todo.done === true && todo.status === "done"}; +} diff --git a/tests/control_plane_ts/canonical_task_validation_plan.test.ts b/tests/control_plane_ts/canonical_task_validation_plan.test.ts new file mode 100644 index 0000000000..f6576a434c --- /dev/null +++ b/tests/control_plane_ts/canonical_task_validation_plan.test.ts @@ -0,0 +1,136 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import type {JsonObject} from "../../loopx/control_plane/effect_program.ts"; +import {canonicalTaskValidationPlan} from "../../loopx/control_plane/goals/task_validation_plan.ts"; +import {delegationValidationPlan} from "../../loopx/control_plane/collaboration/delegation.ts"; +import {createEffectRuntimeHandlers, dispatchEffectRuntimeMethod} from "../../loopx/control_plane/effect_runtime_handlers.ts"; + +const declaration = {validation_command: null, validation_command_argv: ["node", "check.mjs"], + validation_label: "Check", validation_timeout_seconds: 5}; +// Independent canonical-JSON vector: sorted keys, compact UTF-8, bare SHA-256. +const declarationSha256 = "c7fe398d608e3fa26ac76304e63f2ae0cc29ac5f192d03fd77ab1aa1ec563a22"; +const todo = {todo_id: "todo_check", text: "Deliver checked output", status: "open", done: false, + claimed_by: "agent", role: "agent", archive_state: "active", completion_validation_required: true, + completion_validation_sha256: declarationSha256, task_repository: "git:example.invalid/project"}; +const criteria = [{id: "result", description: "Result matches its contract", validation_argv: ["node", "owner.mjs"], + validation_timeout_seconds: 5, validation_files: [{path: "owner.mjs", sha256: "a".repeat(64)}]}]; +const requirements = {todo_id: todo.todo_id, contract_revision: 3, contract_digest: "b".repeat(64), + todo_semantic_digest: "c".repeat(64), criterion_ids: ["result"], criteria}; +const basis = {status: "loaded", provider_revision: "sqlite:1", todo, completion_requirements: requirements}; +const input = {todo_id: todo.todo_id, basis, declaration}; +const observation = (plan: JsonObject) => plan.observation as JsonObject; + +test("canonical Goal and required Todo checks are cumulative without any delegation binding", () => { + const before = structuredClone(input); + const combined = canonicalTaskValidationPlan(input); + const goalOnly = canonicalTaskValidationPlan({...input, declaration: null, + basis: {...basis, todo: {todo_id: todo.todo_id, status: "open", done: false}}}); + const todoOnly = canonicalTaskValidationPlan({...input, basis: {...basis, completion_requirements: null}}); + assert.deepEqual((combined.effects as JsonObject[]).map(effect => effect.validation_argv), + [["node", "owner.mjs"], ["node", "check.mjs"]]); + assert.deepEqual((goalOnly.effects as JsonObject[]).map(effect => effect.validation_argv), [["node", "owner.mjs"]]); + assert.deepEqual((todoOnly.effects as JsonObject[]).map(effect => effect.validation_argv), [["node", "check.mjs"]]); + assert.equal(combined.source, "goal_acceptance"); + assert.equal(goalOnly.source, "goal_acceptance"); + assert.equal(todoOnly.source, "todo_validation"); + assert.equal(observation(combined).check_count, 2); + assert.equal(observation(combined).pinned_file_count, 1); + assert.equal(combined.canonical_done, false); + assert.deepEqual(input, before, "planning cannot rewrite canonical input"); + assert.equal(Object.hasOwn(combined, "binding"), false); + assert.equal(Object.hasOwn(combined, "execution_allowed"), false); +}); + +test("full definition and work/claim/lifecycle hashes match independent canonical vectors", () => { + const plan = canonicalTaskValidationPlan(input); + assert.equal(observation(plan).basis_sha256, "1c562801d51c28829aa8e8cf5fad728a7841406a70aae47a896af86f3e0b5480"); + assert.equal(plan.task_basis_sha256, "fac35dba171637f39235e8f441da527336f9887923d1835371fbb78d553f7676"); + for (const delta of [{contract_revision: 4}, {contract_digest: "d".repeat(64)}, + {todo_semantic_digest: "e".repeat(64)}, {owner_requirement_extension: "New definition"}, + {criteria: [{...criteria[0], description: "Another result boundary"}]}, + {criteria: [{...criteria[0], validation_files: [{path: "owner.mjs", sha256: "f".repeat(64)}]}]}]) { + assert.notEqual(observation(canonicalTaskValidationPlan({...input, + basis: {...basis, completion_requirements: {...requirements, ...delta}}})).basis_sha256, + observation(plan).basis_sha256, "complete requirements, including unknown definition fields, stay hashed"); + } + for (const delta of [{note: "Observed progress"}, {priority: "P1"}, {evidence: "Checked"}, + {updated_at: "2026-01-01T00:00:00Z"}]) { + assert.deepEqual(canonicalTaskValidationPlan({...input, + basis: {...basis, provider_revision: "sqlite:99", todo: {...todo, ...delta}}}), plan); + } + for (const delta of [{future_work_field: "New obligation"}, {text: "Other work"}, + {claimed_by: "another-agent"}, {role: "user"}, {archive_state: "archived"}, + {status: "blocked"}, {done: true}, {task_repository: "git:example.invalid/other-project"}]) { + assert.notEqual(canonicalTaskValidationPlan({...input, basis: {...basis, todo: {...todo, ...delta}}}).task_basis_sha256, + plan.task_basis_sha256, "work and current claim/lifecycle fence the attempt"); + } +}); + +test("required private Todo declarations cannot be omitted or repaired by Goal checks", () => { + for (const completion_requirements of [requirements, null]) { + const current = {...input, basis: {...basis, completion_requirements}}; + assert.deepEqual(canonicalTaskValidationPlan({...current, declaration: null}), { + todo_id: todo.todo_id, state: "unbound", source: null, + reason: "completion_validation_declaration_unavailable", effects: [], canonical_done: false}); + for (const corrupt of [{}, {...declaration, extra_authority: true}, + {...declaration, validation_command_argv: ["node", "other.mjs"]}, + {...declaration, validation_timeout_seconds: "5"}, {...declaration, validation_command_argv: []}]) { + const rejected = canonicalTaskValidationPlan({...current, declaration: corrupt}); + assert.equal(rejected.reason, "completion_validation_declaration_mismatch"); + assert.deepEqual(rejected.effects, []); + } + for (const declaration of [undefined, []]) + assert.throws(() => canonicalTaskValidationPlan({...current, declaration}), /private validation declaration/); + } +}); + +test("missing, unavailable, foreign or applicable unbound Goal basis cannot fall back", () => { + const {completion_requirements: _scope, ...missingScope} = basis; + for (const corruptBasis of [missingScope, {...basis, completion_requirements: undefined}, + {...basis, completion_requirements: {}}, {...basis, completion_requirements: []}, + {...basis, completion_requirements: {...requirements, todo_id: "other"}}, + {...basis, completion_requirements: {...requirements, criteria: []}}, + {...basis, completion_requirements: {...requirements, criteria: [null]}}, + {...basis, status: "unavailable"}, {...basis, provider_revision: null}, + {...basis, todo: {...todo, todo_id: "other"}}, {...basis, todo: null}]) { + assert.throws(() => canonicalTaskValidationPlan({...input, basis: corruptBasis})); + } + for (const todo_id of [undefined, null, "", "other"]) + assert.throws(() => canonicalTaskValidationPlan({...input, todo_id}), /matching canonical Todo/); + assert.throws(() => canonicalTaskValidationPlan({basis: {...basis, todo: {}, completion_requirements: null}, declaration: null})); +}); + +test("only explicit null can resolve absent checks; shared no_declaration retains delegation parity", () => { + const noChecks = {...input, declaration: null, + basis: {...basis, completion_requirements: null, todo: {todo_id: todo.todo_id, status: "done", done: true}}}; + assert.deepEqual(canonicalTaskValidationPlan(noChecks), {todo_id: todo.todo_id, state: "unbound", + source: null, reason: "no_declaration", effects: [], canonical_done: false}); + assert.deepEqual(delegationValidationPlan({...noChecks, binding: {todo_id: todo.todo_id}}), + {...canonicalTaskValidationPlan(noChecks), reason: "independent_delegation_validation_required"}); + for (const declaration of [undefined, {}, input.declaration]) + assert.throws(() => canonicalTaskValidationPlan({...noChecks, declaration}), /without canonical validation authority/); + assert.throws(() => canonicalTaskValidationPlan({...noChecks, + basis: {...noChecks.basis, todo: {...noChecks.basis.todo, completion_validation_sha256: declarationSha256}}})); +}); + +test("shared observation stays definition-only while delegation retains current oracle provenance", () => { + const evidence = {check_id: "current", output_versions: [{ref: "output.json", sha256: "d".repeat(64)}]}; + const current = {...input, basis: {...basis, goal_acceptance_contract: { + criteria: [{id: "result", oracle: {state: "current"}}], + verification: {results: [{criterion_id: "result", oracle_evidence: evidence}]}}}}; + const shared = canonicalTaskValidationPlan(current); + assert.deepEqual(Object.keys(observation(shared)).sort(), ["basis_sha256", "check_count", "pinned_file_count", "source"]); + assert.deepEqual(delegationValidationPlan({...current, binding: {todo_id: todo.todo_id}}), { + ...shared, observation: {...observation(shared), oracle_checks: [{criterion_id: "result", ...evidence}]}}); + assert.equal(canonicalTaskValidationPlan({...input, basis: {...basis, todo: {...todo, done: true}}}).canonical_done, false); + assert.equal(canonicalTaskValidationPlan({...input, basis: {...basis, todo: {...todo, status: "done", done: true}}}).canonical_done, true); +}); + +test("internal runtime dispatch serves the shared plan and rejects corrupt basis without IO", async () => { + let shutdown = false; + const handlers = createEffectRuntimeHandlers({fingerprint: "canonical-task-test", requestShutdown() { shutdown = true; }}); + assert.deepEqual(await dispatchEffectRuntimeMethod(handlers, "goal.task.validation_plan", input), canonicalTaskValidationPlan(input)); + await assert.rejects(() => dispatchEffectRuntimeMethod(handlers, "goal.task.validation_plan", { + ...input, basis: {...basis, completion_requirements: undefined}}), /canonical acceptance requirements/); + assert.equal(shutdown, false); +}); diff --git a/tests/test_native_steward_turn_host.py b/tests/test_native_steward_turn_host.py index e4f272f0f2..4d0deb96d6 100644 --- a/tests/test_native_steward_turn_host.py +++ b/tests/test_native_steward_turn_host.py @@ -1,5 +1,6 @@ """Original Chat + native kernel + File/SQLite; only the model/provider are synthetic.""" import contextlib +import hashlib import io import json import sys @@ -22,7 +23,8 @@ steward = steward_fixture -def managed_fixture(steward, tmp_path, monkeypatch, provider="file", *, validator=True): +def managed_fixture(steward, tmp_path, monkeypatch, provider="file", *, validator=True, + validation_argv=None, legacy_command=None): isolate_sqlite_runtime(tmp_path, monkeypatch) sid, managed = original(steward) storage(steward[1], provider) @@ -43,11 +45,12 @@ def managed_fixture(steward, tmp_path, monkeypatch, provider="file", *, validato assert finish(runtime, turn)["status"] == "completed" observation = workspace / "managed-source.txt" observation.write_text("ready") - declaration = [sys.executable, "-c", "from pathlib import Path; assert Path('managed-source.txt').read_text() == 'ready'"] + declaration = validation_argv or [sys.executable, "-c", "from pathlib import Path; assert Path('managed-source.txt').read_text() == 'ready'"] added = cli(runtime, "todo", "add", "--goal-id", actor["goal_id"], "--role", "agent", "--text", "Validate the readiness source before completing this task.", "--claimed-by", actor["agent_id"], "--action-kind", "validate", "--continuation-policy", "same_agent_non_delivery", - *(["--validation-command-json", json.dumps(declaration)] if validator else []), "--execute") + *(["--validation-command", legacy_command] if legacy_command else + ["--validation-command-json", json.dumps(declaration)] if validator else []), "--execute") fake = Path(runtime.codex_bin) candidate = {"result_kind": "validated_completion", "classification": "implementation", "summary": "The synthetic readiness source is ready.", "next_action": "Continue the original authorized work.", @@ -61,6 +64,249 @@ def managed_fixture(steward, tmp_path, monkeypatch, provider="file", *, validato return ManagedSessionTurn(runtime), session, actor, added["todo_id"], observation, capture +def configure_native_goal_check(runtime, actor, todo_id, observation, *, bindings=True, reject=False): + """Use the local owner in the isolated fixture, before any output check.""" + from loopx.control_plane.goals.acceptance import ( + configure_goal_acceptance, inspect_goal_acceptance, + ) + checker = observation.parent / "goal-check.py" + checker.write_text( + "from pathlib import Path\n" + "assert Path('managed-source.txt').read_text() == 'ready'\n" + + ("raise SystemExit(1)\n" if reject else "") + ) + document = {"scope": {"kind": "selected_work", "todo_ids": [todo_id]}, + "objective": "Check the original readiness source", "non_goals": [], + "criteria": [{"id": "readiness", "description": "The source is ready", + "validation_argv": [sys.executable, "goal-check.py"], + "validation_timeout_seconds": 5, + "validation_files": [{"path": "goal-check.py", + "sha256": hashlib.sha256(checker.read_bytes()).hexdigest()}]}], + "bindings": [{"todo_id": todo_id, "criterion_ids": ["readiness"]}] if bindings else []} + basis = inspect_goal_acceptance(registry_path=runtime.registry_path, + runtime_root=str(runtime.coordination_runtime_root), goal_id=actor["goal_id"]) + configured = configure_goal_acceptance(registry_path=runtime.registry_path, + runtime_root=str(runtime.coordination_runtime_root), goal_id=actor["goal_id"], + expected_provider_revision=basis["provider_revision"], document=document, execute=True) + assert configured["status"] == "applied", configured + return checker, document + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("todo_check", [False, True], ids=["goal-only", "combined"]) +def test_native_task_consumes_owner_goal_checks(steward, tmp_path, monkeypatch, provider, todo_check): + service, session, actor, todo_id, observation, capture = managed_fixture( + steward, tmp_path, monkeypatch, provider, validator=todo_check) + store, runtime, *_ = steward + configure_native_goal_check(runtime, actor, todo_id, observation) + before = capture.read_bytes() + accepted, created = service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="owner-goal-check", todo_id=todo_id) + assert created + completed = finish(runtime, accepted) + result = completed["response"]["native_loopx"] + assert result["status"] == "committed", json.dumps(result) + assert result["effects"]["host_invoked"] and result["effects"]["quota_spent"] + assert result["validation"]["status"] == "passed" + calls = [json.loads(line) for line in capture.read_bytes()[len(before):].splitlines()] + assert len([row for row in calls if row["method"] == "turn/start"]) == 1 + assert store.load_session(session["session_id"])["upstream_thread_id"] == session["upstream_thread_id"] + current = capture.read_bytes() + assert not service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="owner-goal-check", todo_id=todo_id)[1] + assert capture.read_bytes() == current + + +@pytest.mark.parametrize("fault", ["unbound", "changed-checker", "corrupt-required"]) +def test_native_goal_checks_cannot_bypass_unavailable_sources(steward, tmp_path, monkeypatch, fault): + service, session, actor, todo_id, observation, capture = managed_fixture(steward, tmp_path, monkeypatch) + runtime = steward[1] + checker, _ = configure_native_goal_check(runtime, actor, todo_id, observation, bindings=fault != "unbound") + if fault == "changed-checker": + checker.write_text("raise SystemExit(0)\n") + elif fault == "corrupt-required": + from loopx.control_plane.todos.completion_validation_store import completion_validation_declaration_path + todo = cli(runtime, "todo", "list", "--goal-id", actor["goal_id"], "--todo-id", todo_id)["todo"] + sidecar = completion_validation_declaration_path(runtime_root=runtime.coordination_runtime_root, + goal_id=actor["goal_id"], todo_id=todo_id) + blob = sidecar.parent / "blobs" / (todo["completion_validation_sha256"] + ".json") + # The selected immutable source is corrupt. A valid projected/sidecar + # declaration cannot make that selected source trustworthy again. + blob.write_text("{}") + before = capture.read_bytes() + accepted, _ = service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="unavailable-owner-check", todo_id=todo_id) + completed = finish(runtime, accepted) + native = (completed.get("response") or {}).get("native_loopx") + if native is None: + assert fault == "unbound" and completed["status"] == "failed", json.dumps(completed) + assert completed["error_code"] == "runtime_error", completed + else: + assert native["status"] in {"failed", "stopped"}, native + assert not native["effects"]["state_written"] and not native["effects"]["quota_spent"] + current = cli(runtime, "todo", "list", "--goal-id", actor["goal_id"], "--todo-id", todo_id)["todo"] + assert current["status"] == "open" and not current["done"] + calls = [json.loads(line) for line in capture.read_bytes()[len(before):].splitlines()] + assert not [row for row in calls if row["method"] == "turn/start"] + + +@pytest.mark.parametrize("goal_checks", [False, True], ids=["todo-only", "combined"]) +def test_native_legacy_command_keeps_argv_unavailable_boundary(steward, tmp_path, monkeypatch, goal_checks): + service, session, actor, todo_id, observation, capture = managed_fixture( + steward, tmp_path, monkeypatch, legacy_command="legacy-checker") + runtime = steward[1] + if goal_checks: + configure_native_goal_check(runtime, actor, todo_id, observation) + before = capture.read_bytes() + accepted, _ = service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="legacy-argv-boundary", todo_id=todo_id) + native = finish(runtime, accepted)["response"]["native_loopx"] + assert native["status"] == "stopped", native + assert not native["effects"]["state_written"] and not native["effects"]["quota_spent"] + calls = [json.loads(line) for line in capture.read_bytes()[len(before):].splitlines()] + assert not [row for row in calls if row["method"] == "turn/start"] + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("fault", ["goal-failed", "definition", "checker-after", "todo-work", "goal-work", "progress"]) +def test_native_check_reentry_rejects_changes_but_accepts_progress(steward, tmp_path, monkeypatch, provider, fault): + from loopx.capabilities.native_chat.steward_managed_mode import ManagedSessionTurn + from loopx.control_plane.goals import acceptance + service, session, actor, todo_id, observation, capture = managed_fixture(steward, tmp_path, monkeypatch, provider) + runtime = steward[1] + if fault != "todo-work": + checker, document = configure_native_goal_check(runtime, actor, todo_id, observation, reject=fault == "goal-failed") + create = ManagedSessionTurn.validator + + def interrupted(self, *args, **kwargs): + validate = create(self, *args, **kwargs) + + def after_model(plan, result): + if fault == "definition": + document["objective"] = "Owner changed the acceptance definition" + basis = acceptance.inspect_goal_acceptance(registry_path=runtime.registry_path, + runtime_root=str(runtime.coordination_runtime_root), goal_id=actor["goal_id"]) + changed = acceptance.configure_goal_acceptance(registry_path=runtime.registry_path, + runtime_root=str(runtime.coordination_runtime_root), goal_id=actor["goal_id"], + expected_provider_revision=basis["provider_revision"], document=document, execute=True) + assert changed["status"] == "applied", changed + elif fault == "checker-after": + checker.write_text("raise SystemExit(0)\n") + elif fault in {"todo-work", "goal-work", "progress"}: + cli(runtime, "todo", "update", "--goal-id", actor["goal_id"], "--todo-id", todo_id, + "--agent-id", actor["agent_id"], "--update-operation-id", "post-model-source", + "--note" if fault == "progress" else "--text", + "Independent progress observation" if fault == "progress" else "The owner changed the work") + fresh = cli(runtime, "todo", "list", "--goal-id", actor["goal_id"], "--todo-id", todo_id)["todo"] + assert fresh["note" if fault == "progress" else "text"] == ( + "Independent progress observation" if fault == "progress" else "The owner changed the work") + return validate(plan, result) + + return after_model + + monkeypatch.setattr(ManagedSessionTurn, "validator", interrupted) + accepted, _ = service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="owner-reentry", todo_id=todo_id) + native = finish(runtime, accepted)["response"]["native_loopx"] + if fault == "progress": + assert native["status"] == "committed" and native["effects"]["quota_spent"], native + else: + assert native["status"] == "failed", native + assert not native["effects"]["state_written"] and not native["effects"]["quota_spent"] + if fault == "goal-failed": + assert native["validation"]["status"] == "failed", native + + +@pytest.mark.parametrize("fault", ["checker", "todo-work"]) +def test_native_postcheck_source_fence_rejects_a_successful_old_check(steward, tmp_path, monkeypatch, fault): + from loopx.capabilities.native_chat.steward_managed_mode import ManagedSessionTurn + service, session, actor, todo_id, observation, _ = managed_fixture(steward, tmp_path, monkeypatch) + runtime = steward[1] + if fault == "checker": + checker, _ = configure_native_goal_check(runtime, actor, todo_id, observation) + create = ManagedSessionTurn.validator + observed = [] + + def interrupted(self, *args, **kwargs): + validate = create(self, *args, **kwargs) + + def after_model(plan, result): + checks = self.task_validator + + def changed_after_checks(plan, result): + receipt = checks(plan, result) + assert receipt["status"] == "passed", receipt + if fault == "checker": + checker.write_text("raise SystemExit(0)\n") + else: + cli(runtime, "todo", "update", "--goal-id", actor["goal_id"], "--todo-id", todo_id, + "--agent-id", actor["agent_id"], "--update-operation-id", "after-check-work", + "--text", "A different task after successful validation") + observed.append(receipt["status"]) + return receipt + + self.task_validator = changed_after_checks + return validate(plan, result) + + return after_model + + monkeypatch.setattr(ManagedSessionTurn, "validator", interrupted) + accepted, _ = service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="post-check-fence", todo_id=todo_id) + native = finish(runtime, accepted)["response"]["native_loopx"] + assert observed == ["passed"] + assert native["status"] == "failed", native + assert not native["effects"]["state_written"] and not native["effects"]["quota_spent"] + + +def test_native_combined_checks_keep_raw_result_stdin_and_required_todo_failure(steward, tmp_path, monkeypatch): + argv = [sys.executable, "-c", "import json,sys; from pathlib import Path; " + "v=json.load(sys.stdin); assert v['classification'] == 'implementation'; " + "Path('stdin-checked').write_text('checked'); raise SystemExit(1)"] + service, session, actor, todo_id, observation, _ = managed_fixture( + steward, tmp_path, monkeypatch, validation_argv=argv) + runtime = steward[1] + configure_native_goal_check(runtime, actor, todo_id, observation) + accepted, _ = service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="required-stdin", todo_id=todo_id) + native = finish(runtime, accepted)["response"]["native_loopx"] + assert (observation.parent / "stdin-checked").read_text() == "checked" + assert native["status"] == "failed" and native["validation"]["status"] == "failed", native + assert not native["effects"]["state_written"] and not native["effects"]["quota_spent"] + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_native_selected_goal_scope_keeps_future_work_independent_and_recovers(steward, tmp_path, monkeypatch, provider): + service, session, actor, todo_id, observation, capture = managed_fixture(steward, tmp_path, monkeypatch, provider) + runtime = steward[1] + configure_native_goal_check(runtime, actor, todo_id, observation, reject=True) + blocked, _ = service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="covered-failure", todo_id=todo_id) + rejected = finish(runtime, blocked)["response"]["native_loopx"] + assert rejected["validation"]["status"] == "failed" + assert not rejected["effects"]["quota_spent"] and not rejected["effects"]["state_written"] + argv = [sys.executable, "-c", "from pathlib import Path; assert Path('managed-source.txt').read_text() == 'ready'"] + # This new Task is in the same Goal after check activation, but outside the + # owner's selected-work scope. It must keep its own required check and work. + later = cli(runtime, "todo", "add", "--goal-id", actor["goal_id"], "--role", "agent", + "--text", "An independent later task", "--claimed-by", actor["agent_id"], + "--action-kind", "validate", "--continuation-policy", "same_agent_non_delivery", + "--validation-command-json", json.dumps(argv), "--execute")["todo_id"] + accepted, _ = service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="outside-selected-scope", todo_id=later) + independent = finish(runtime, accepted)["response"]["native_loopx"] + assert independent["status"] == "committed" and independent["effects"]["quota_spent"], independent + configure_native_goal_check(runtime, actor, todo_id, observation) + recovered, _ = service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="owner-repaired-check", todo_id=todo_id) + resumed = finish(runtime, recovered)["response"]["native_loopx"] + assert resumed["status"] == "committed" and resumed["effects"]["quota_spent"], resumed + current = capture.read_bytes() + assert not service.submit(session["session_id"], agent_id=actor["agent_id"], + operation_id="owner-repaired-check", todo_id=todo_id)[1] + assert capture.read_bytes() == current + + @pytest.mark.parametrize("provider", ["file", "sqlite"]) def test_registered_agents_have_distinct_durable_sessions_without_adopting_legacy_history(steward, tmp_path, monkeypatch, provider): service, first, actor, _, _, capture = managed_fixture(steward, tmp_path, monkeypatch, provider) @@ -396,13 +642,17 @@ def after_model(plan, result): @pytest.mark.parametrize("provider", ["file", "sqlite"]) -def test_managed_turn_http_correlates_readback_without_accepting_commands(steward, tmp_path, monkeypatch, provider): +@pytest.mark.parametrize("goal_only", [False, True], ids=["todo", "owner-goal"]) +def test_managed_turn_http_correlates_readback_without_accepting_commands(steward, tmp_path, monkeypatch, provider, goal_only): import http.client import threading from loopx.chat_server import ChatHTTPServer, ChatRequestHandler - service, session, actor, todo_id, _, capture = managed_fixture(steward, tmp_path, monkeypatch, provider) + service, session, actor, todo_id, observation, capture = managed_fixture( + steward, tmp_path, monkeypatch, provider, validator=not goal_only) store, runtime, *_ = steward + if goal_only: + configure_native_goal_check(runtime, actor, todo_id, observation) server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) server.runtime_controller, server.chat_store, server.verbose = runtime, store, False server.registry_path, server.selected_goal_id = runtime.registry_path, actor["goal_id"]