diff --git a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md index 764d33c21a..650fa11916 100644 --- a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md +++ b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md @@ -20,16 +20,56 @@ unbound request keeps its original readiness route without inventing a Turn. This is a bounded Host handoff repair, not C1 cutover, installed adoption or qualification of model cost and long-horizon benefit. -The source already shares more than the output names suggest. `_emit_quota_result` -captures the complete decision **before** `_project_quota_cli_payload` chooses -ordinary CLI compaction or `buildTurnEnvelope`. The latter delegates to the -TypeScript owner; its Python module is a transport adapter. Both quota capture -and Turn journal capture call `write_decision_capture` in +The ordinary CLI cutover composes every decided `quota should-run` through the +existing TypeScript `composeCompleteTurnDecision` owner **before** capture. +Default calls and the compatibility aliases `--turn-envelope` / `--complete-turn` +share this source. Explicit context-delivery off returns that complete source +inline; it does not choose an older format or enable progressive delivery. +Full Goal material is collected independently of that presentation choice. +The active CLI selection between its compactor and `buildTurnEnvelope` is +removed. Status, plan and scheduler-observation retain their separate purposes; +historical readers and other remaining callers are not retired by this slice. +The current model-behavior portfolio also composes its should-run inputs through +this complete-source owner; it no longer exercises the retired CLI compactor as +the product default. Candidate context, planning relations, task continuation and +diagnostics stay intact. The crowded regression's pretty JSON changes from +86,172 compact bytes to 121,318 complete bytes (120,963 source bytes); its old +90,000-byte compact-output allowance characterizes the historical fixture, not +the new full carrier. Wire/page limits and the terminal actor's ten-call budget +do not change. Frozen raw/v0 model comparison controls remain separate. + +Todo completion, replan-successor return and blocked-completion recovery use the +existing TypeScript settlement composer for their current continuation plans. +They retain the original identity, route and supplied lease proof. JSON and +Markdown expose the runtime-owned debit with writeback, without a second model +spend command. The current terminal qualifier verifies committed receipts for +that original effect and rejects missing, foreign, unknown or uncommitted +receipts and duplicate model spend. A post-effect command failure still stops +the actor; independently committed writeback/debit receipts are not rolled back +or reported as absent. Historical plan rendering/decoding remains supported; +these engineering checks do not establish live-model adoption or cost benefit. +Both quota capture and Turn journal capture call `write_decision_capture` in [`decision_capture.py`](../../../../loopx/control_plane/turn_driver/decision_capture.py). Native context delivery and explicit host handoff also reuse that module and the existing context-delivery owner. C1 must converge the remaining composition and consumer assumptions, rather than introduce another capture service or -rewrite already shared delta/native-resume logic. +rewrite already shared delta/native-resume logic. When an original capture is +requested, its advertised `detail_ref.full_decision` uses the existing immutable +reader sidecar. The route is signed before capture and its final byte digest is +published afterward, avoiding a circular self-hash. Reader publication failure +retains the committed source and receipt; reads never re-admit or settle work. + +The same frozen `ef099ae3` small/crowded/multi-agent quota fixtures measure +JSON characters **23,289/42,965/25,514 → 24,984/53,441/29,574** and Markdown +**7,476/8,143/6,441 → 25,083/53,543/29,674**. Full Goal bytes previously required +a separate read, and the complete Markdown carrier preserves all source fields. +These are stdout measurements, not model cost, latency or accepted-outcome +results. Keep the original 25k/51k/26.5k JSON and 10k/17k/7k Markdown ceiling +failures. The bounded new ceilings are 26k/55k/31k for either format; line limits +stay unchanged. Crowded-minus-small JSON growth is 19,676 → 28,457 characters: +the per-Todo allowance becomes 600 while the fixed 9,700 allowance is unchanged. +This engineering calibration does not waive the independent matched single-session +outcome/full-cost gate, other Hosts, packaging, installed adoption or native Windows. Optional host polling is part of that original observation. The source-fidelity slice records `--record-host-poll` once before capture and reuses its receipt in diff --git a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md index 066e608259..59aa0d54ae 100644 --- a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md +++ b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md @@ -14,14 +14,45 @@ Turn 的 ready 决策。Host 将该原件交给既有 saved-capture 展示/reade readiness 路径,不补造 Turn。这只是有界的 Host 交接修复,不代表 C1 切换、已安装 采用,或模型费用与长程收益已取得资格。 -源码实际共享的部分比输出名称体现的更多。`_emit_quota_result` 在 -`_project_quota_cli_payload` 选择普通 CLI 压缩或 `buildTurnEnvelope` **之前**, -已经捕获完整决策。后者委托 TypeScript owner,Python 模块是传输 adapter。 +普通 CLI 切换让每个已形成决策的 `quota should-run` 在 capture **之前**复用既有 +TypeScript `composeCompleteTurnDecision` owner。默认调用及兼容别名 +`--turn-envelope` / `--complete-turn` 使用同一来源。显式关闭 context delivery 时, +完整来源以内联形式返回,不选择旧格式,也不打开渐进交付;完整 Goal 材料的取得与 +此展示选择分开。CLI 中选择 compactor 或 `buildTurnEnvelope` 的活跃分支删除。 +Status、plan 与 scheduler-observation 保留各自用途;本切片不退役历史 reader 或 +其他剩余调用方。 +当前 model-behavior portfolio 的 should-run 输入也复用该完整来源 owner,不再把 +已退役 CLI compactor 当作产品默认路径。候选上下文、规划关系、任务续接与诊断事实 +保留。Crowded 回归的 pretty JSON 从压缩后的 86,172 字节变为完整的 121,318 字节 +(原来源 120,963 字节);旧 90,000 字节压缩输出允许量只刻画历史 fixture,不约束 +新的完整 carrier。Wire/page 上限和终态 actor 的十次调用预算不变。冻结的 raw/v0 +模型对照继续独立保留。 + +Todo 验收完成、replan-successor 返回及 blocked-completion 恢复的当前续接计划复用 +既有 TypeScript 结算 composer,保留原身份、路由与已提供的 lease 证明。JSON 与 +Markdown 展示随写回执行的运行时扣额,不再要求模型执行第二条 spend 命令。 +当前终态 qualifier 校验原 effect 的已提交回执,拒绝缺失、其他身份、未知或未提交 +的回执及模型重复 spend。副作用之后的命令失败仍停止 actor;独立提交的写回/扣额 +回执不回滚,也不能报告为不存在。历史 plan 展示/解码继续支持;这些工程检查 +不代表真实模型采用或成本收益。 Quota capture 与 Turn journal capture 都调用 [`decision_capture.py`](../../../../loopx/control_plane/turn_driver/decision_capture.py) 中的 `write_decision_capture`。原生上下文交付与显式宿主 handoff 也复用该模块和既有 context-delivery owner。C1 应收敛剩余的组合逻辑与消费者假设,不另建 capture service, -也不重写已经共享的差分与 native-resume 逻辑。 +也不重写已经共享的差分与 native-resume 逻辑。请求保存原 capture 时,公布的 +`detail_ref.full_decision` 复用既有不可变 reader sidecar:先将路由纳入签名,再在 +capture 发布后写入最终字节摘要,避免循环自哈希。Reader 发布失败仍保留已提交 +来源和回执;读取不重新准入或结算工作。 + +同一份冻结的 `ef099ae3` small/crowded/multi-agent quota fixture,JSON 字符数为 +**23,289/42,965/25,514 → 24,984/53,441/29,574**,Markdown 为 +**7,476/8,143/6,441 → 25,083/53,543/29,674**。完整 Goal 字节此前需要另行读取, +完整 Markdown carrier 现保留所有来源字段。这些只是 stdout 测量,不代表模型费用、 +时延或验收成果。保留原 JSON 25k/51k/26.5k 与 Markdown 10k/17k/7k 上限失败。 +新有界上限两种格式均为 26k/55k/31k,行数限制不变。Crowded 减 small 的 JSON +增长为 19,676 → 28,457 字符:每 Todo 允许量调整为 600,固定 9,700 允许量不变。 +此工程校准不豁免独立的匹配单会话成果/完整成本 gate、其他 Host、打包、安装采用 +或原生 Windows 验收。 可选 host poll 也是该次原始观测的一部分。来源保真切片在 capture 前仅记录一次 `--record-host-poll`,普通 CLI、envelope 与原生上下文交付复用同一回执;恢复读取不再 diff --git a/examples/cli-control-plane-command-modularization-smoke.py b/examples/cli-control-plane-command-modularization-smoke.py index 2cdb180627..03308b91e8 100644 --- a/examples/cli-control-plane-command-modularization-smoke.py +++ b/examples/cli-control-plane-command-modularization-smoke.py @@ -64,7 +64,7 @@ def assert_source_shape() -> None: assert_contains(todo_text, "render_todo_markdown", "todo module") assert_contains(todo_text, "append_cli_rollout_event", "todo module") assert_contains(quota_text, "from .quota_presentation import", "quota module") - assert_contains(quota_presentation_text, "render_quota_should_run_markdown", "quota presentation") + assert_contains(quota_presentation_text, "render_turn_context_markdown", "quota presentation") assert_contains(quota_text, "append_cli_rollout_event", "quota module") diff --git a/examples/control_plane/cli-output-probe-runner.py b/examples/control_plane/cli-output-probe-runner.py index 38e2c44319..ec1315339f 100644 --- a/examples/control_plane/cli-output-probe-runner.py +++ b/examples/control_plane/cli-output-probe-runner.py @@ -8,6 +8,7 @@ import hashlib import shlex import json +import re import shutil import sys from pathlib import Path @@ -103,6 +104,113 @@ def _turn_plan_control_observation(value: Any, *, goal_state: dict[str, str] | N +def _quota_control_observation(value: Any, *, goal_state: dict[str, str] | None = None) -> dict[str, Any] | None: + """Observe the same current controls in the two declared quota carriers. + + This is a frozen fixture oracle, not full-source parity or an authority + decoder. Compare original values, including read/settlement prose; the + complete-source and real recovery suites retain their separate coverage. + """ + if not isinstance(value, dict) or value.get("mode") != "should-run": + return None + version = value.get("schema_version") + if version not in {None, "loopx_turn_envelope_v0", "loopx_turn_envelope_v1"}: + return None + if version == "loopx_turn_envelope_v1": + from loopx.control_plane.quota.turn_envelope import assert_complete_turn_decision + assert_complete_turn_decision(value) + legacy = version == "loopx_turn_envelope_v0" + channel = value["action"] if legacy else value["interaction_contract"]["agent_channel"] + cli = value["writeback"] if legacy else value["interaction_contract"]["cli_channel"] + capsule = value["contract_capsule"] if legacy else value + boundary = value["boundary"] if legacy else value["goal_boundary"] + selected = channel.get("selected_todo") if legacy else value.get("selected_todo") + selection = None + if isinstance(selected, dict): + selection = {key: selected.get(key) for key in ( + "todo_id", "priority", "status", "task_class", "action_kind", "claimed_by", + )} + # The historical codec's exact, local text reference is not a new + # selection. Unknown references must not be silently treated as text. + if legacy and "text_ref" in selected: + assert selected["text_ref"] == "action.recommended_action" + selection["text"] = channel["recommended_action"] + else: + selection["text"] = selected.get("text") + user = value["user"] if legacy else value["interaction_contract"]["user_channel"] + reads = value["required_reads"] if legacy else channel["required_reads"] + if goal_state is not None: + goal_read = {"command": goal_state["command"], "source": "goal_state", "ordering": "before_work", + "reason": "Read full Goal intent, acceptance, stops. No summaries; failed/changed sources need a fresh guard."} + reads = [row for row in reads if row != goal_read] + controls = { + "goal_id": value["goal_id"], + "agent_id": value["agent_id"] if legacy else value["agent_identity"]["agent_id"], + "decision": value["decision"], "should_run": value["should_run"], + "effective_action": value["effective_action"], "selected_todo": selection, + "execution": {key: channel[key] for key in ("must_attempt", "delivery_allowed", "quiet_noop_allowed")}, + "boundary": {key: boundary[key] for key in ("write_scope", "stop_condition", "rule")}, + "required_reads": {"pending": reads, "goal_material": goal_state}, + "next_cli_actions": cli["next_cli_actions"], + "spend": {key: cli[key] for key in ("spend_allowed_now", "spend_after_validation", "spend_policy")}, + "work_lane_contract": capsule["work_lane_contract"], + "execution_obligation": capsule["execution_obligation"], + "execution_profile": capsule["execution_profile"], "task_scope": capsule["task_scope"], + "replan_action_packet": value.get("replan_action_packet"), + "notify": user["notify"], "user_action_required": user["action_required"], + "scheduler_action": value["scheduler"]["action"] if legacy else value["scheduler_hint"]["action"], + } + def digest(child): + return hashlib.sha256(json.dumps(child, ensure_ascii=False, + sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest() + return {"source_schema": version, "controls_sha256": digest(controls), + "field_sha256": {key: digest(child) for key, child in controls.items()}} + + +def _quota_markdown_field_observations(text: str) -> dict[str, str]: + """Read the five scalar controls printed by the historical fixture renderer. + + Legacy narrative is not a complete source. Its paired JSON supplies the + remaining fixture controls only after these actually printed values match. + These observations never classify a live request or operator's authority. + """ + values: dict[str, Any] = {} + for field in ("goal_id", "decision", "should_run", "effective_action"): + matches = re.findall(rf"^- {field}: `([^`\n]*)`$", text, re.MULTILINE) + if len(matches) != 1: + return {} + values[field] = matches[0] + if values["should_run"] not in {"True", "False"}: + return {} + values["should_run"] = values["should_run"] == "True" + actors = re.findall(r"^- agent_id: `([^`\n]*)`$", text, re.MULTILINE) + actors += re.findall(r"^- agent_identity: agent_id=(\S+) agent_model=\S+$", text, re.MULTILINE) + if len(actors) != 1: + return {} + values["agent_id"] = actors[0] + return {key: hashlib.sha256(json.dumps(child, ensure_ascii=False, + sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest() + for key, child in values.items()} + + +def _quota_goal_material(source: dict) -> dict[str, str] | None: + """Compare delivered full bytes with the original fixture's pending cat.""" + channel = source.get("action") if source.get("schema_version") == "loopx_turn_envelope_v0" else source.get("interaction_contract", {}).get("agent_channel", {}) + reads = source.get("required_reads", []) if source.get("schema_version") == "loopx_turn_envelope_v0" else channel.get("required_reads", []) + for row in channel.get("work_context", {}).get("sources", []): + content = row.get("content", {}) + if row.get("source") == "goal_state" and content.get("full_source") is True: + revision = "sha256:" + hashlib.sha256(content["text"].encode("utf-8")).hexdigest() + assert revision == content["revision"] and row["ordering"] == "before_work" + return {"command": row["command"], "ordering": row["ordering"], "revision": revision} + for row in reads: + words = shlex.split(row.get("command", "")) + if row.get("source") == "goal_state" and row.get("ordering") == "before_work" and words[:2] == ["cat", "--"] and len(words) == 3: + return {"command": row["command"], "ordering": row["ordering"], + "revision": "sha256:" + hashlib.sha256(Path(words[2]).read_bytes()).hexdigest()} + return None + + def _receipt_row( *, semantics: ModuleType, @@ -119,6 +227,11 @@ def _receipt_row( output_contract_version: str | None = None, ) -> dict: payload = measurement.get("resolved_payload", measurement.get("payload")) + quota_source = payload + if surface_id == "quota_should_run" and payload is None and "```json\n" in text: + decoded = json.loads(text.split("```json\n", 1)[1].split("\n```", 1)[0]) + quota_source = decoded if decoded.get("schema_version") == "loopx_turn_envelope_v1" else None + quota_material = _quota_goal_material(quota_source) if surface_id == "quota_should_run" and isinstance(quota_source, dict) else None plan, material, detail_cost = payload, None, None if isinstance(plan, dict) and plan.get("schema_version") == "loopx_turn_plan_v1": if "detail_ref" in plan: @@ -147,7 +260,9 @@ def _receipt_row( "scenario": scenario, "format": output_format, "qualification_policy": qualification_policy, - "output_contract_version": output_contract_version, + "output_contract_version": ("loopx_turn_envelope_v1" if surface_id == "quota_should_run" + and isinstance(quota_source, dict) and quota_source.get("schema_version") == "loopx_turn_envelope_v1" + else output_contract_version), "chars": measurement["chars"], "utf8_bytes": measurement["utf8_bytes"], "lines": measurement["lines"], @@ -165,6 +280,10 @@ def _receipt_row( "markdown_headings": semantics.markdown_headings(text), "markdown_anchor": markdown_anchor, "turn_plan_controls": _turn_plan_control_observation(plan, goal_state=material), + **({"quota_controls": _quota_control_observation(quota_source, goal_state=quota_material)} + if surface_id == "quota_should_run" and isinstance(quota_source, dict) else {}), + **({"quota_markdown_fields": _quota_markdown_field_observations(text)} + if surface_id == "quota_should_run" and output_format == "markdown" and quota_source is None else {}), **({"inspection_source_read": detail_cost} if detail_cost is not None else {}), "action_signature_sha256": ( semantics.action_signature_semantic_sha256(payload) @@ -212,7 +331,8 @@ def _receipt_row( else [] ), "projection_envelope_schema_versions": ( - semantics.projection_envelope_schema_versions(payload if isinstance(payload, dict) else text) + semantics.projection_envelope_schema_versions(quota_source if surface_id == 'quota_should_run' + and isinstance(quota_source, dict) else payload if isinstance(payload, dict) else text) ), "todo_work_counts_schema_versions": ( semantics.todo_work_counts_schema_versions(payload) @@ -239,6 +359,10 @@ def _link_turn_warning_basis(rows: list[dict]) -> list[dict]: paired = by_id.get(row["row_id"].removesuffix("markdown") + "json") if paired is not None: row["turn_envelope_cost_basis"] = paired["continuation_instructions"] + visible, controls = row.get("quota_markdown_fields"), paired.get("quota_controls") + if visible and controls: + assert all(controls["field_sha256"].get(key) == digest for key, digest in visible.items()), "Markdown quota controls differ from paired JSON" + row["quota_controls"] = controls return rows diff --git a/examples/control_plane/quota-scheduler-registry-route-smoke.py b/examples/control_plane/quota-scheduler-registry-route-smoke.py index d5ec6e189f..8b465132a3 100644 --- a/examples/control_plane/quota-scheduler-registry-route-smoke.py +++ b/examples/control_plane/quota-scheduler-registry-route-smoke.py @@ -112,10 +112,10 @@ def main() -> None: "external_write", "--codex-app-current-rrule", "FREQ=MINUTELY;INTERVAL=3", - "--turn-envelope", cwd=project, ) - ack_cli_args = decision["scheduler"]["codex_app"]["ack_cli_args"] + assert decision["schema_version"] == "loopx_turn_envelope_v1", decision + ack_cli_args = decision["scheduler_hint"]["app_automation"]["ack_hint"]["cli_args"] assert ack_cli_args[:4] == [ "--registry", str(global_registry.resolve()), @@ -148,7 +148,7 @@ def main() -> None: "--codex-app", cwd=project, ) - stateful = follow_up["scheduler_hint"]["codex_app"]["stateful_backoff"] + stateful = follow_up["scheduler_hint"]["app_automation"]["stateful_backoff"] assert stateful["state_status"] == "same_identity", follow_up print("quota scheduler registry route smoke passed") diff --git a/loopx/cli_commands/quota.py b/loopx/cli_commands/quota.py index d69dad950d..b98b9b1ef5 100644 --- a/loopx/cli_commands/quota.py +++ b/loopx/cli_commands/quota.py @@ -17,7 +17,6 @@ from ..usage_goal import observe_quota_result as observe_quota_result # noqa: PLC0414 from .quota_capture import handle_native_context_command, prepare_quota_capture from .quota_presentation import ( - _compose_explicit_turn_context as _compose_explicit_turn_context, _project_native_cli_settlement as _project_native_cli_settlement, _project_quota_cli_payload as _project_quota_cli_payload, _quota_renderer as _quota_renderer, diff --git a/loopx/cli_commands/quota_capture.py b/loopx/cli_commands/quota_capture.py index aea6b32011..ee21bae681 100644 --- a/loopx/cli_commands/quota_capture.py +++ b/loopx/cli_commands/quota_capture.py @@ -15,6 +15,9 @@ from ..control_plane.effect_runtime import EffectRuntimeRemoteError, EffectRuntimeStartupError from ..control_plane.quota.effective_action import EffectiveAction from ..control_plane.quota.error_codes import QuotaCommandValidationError, QuotaDecisionTransportError +from ..control_plane.quota.turn_envelope import ( + COMPLETE_TURN_DECISION_VERSION, TURN_ENVELOPE_SCHEMA_VERSION, +) from ..control_plane.turn_driver.decision_capture import ( context_index_fields as _context_index_fields, write_initial_context_read_reference, @@ -221,6 +224,16 @@ def view(kind: str, ref: dict[str, Any], body: bytes) -> dict[str, Any]: return result +def quota_context_surface(payload: dict[str, Any]) -> str: + """Transport the captured schema; compatibility flags do not choose a source.""" + version = payload.get("schema_version") + if version == COMPLETE_TURN_DECISION_VERSION: + return "complete_turn" + if "contract_binding" in payload or ("schema_version" in payload and version != TURN_ENVELOPE_SCHEMA_VERSION): + raise QuotaDecisionTransportError("Unsupported saved quota decision version or mixed Turn binding.") + return "turn_envelope" if version == TURN_ENVELOPE_SCHEMA_VERSION else "quota_packet" + + def project_native_quota_context(payload: dict[str, Any], args: argparse.Namespace, *, capture_directory: Path, capture_id: str, decision_identity: tuple[str, str], progressive_enabled: bool, reader_argv: list[str] | None) -> dict[str, Any]: @@ -235,8 +248,7 @@ def project_native_quota_context(payload: dict[str, Any], args: argparse.Namespa directory = None # Current full input, no fabricated native journal. prepared = prepare_codex_context(payload, directory=directory, capture_directory=capture_directory, goal_id=decision_identity[0], agent_id=decision_identity[1], - surface=("complete_turn" if getattr(args, "complete_turn", False) - else "turn_envelope" if getattr(args, "turn_envelope", False) else "quota_packet"), + surface=quota_context_surface(payload), capture_id=capture_id, continuity_generation=getattr(args, "_context_delivery_generation", None), progressive_enabled=progressive_enabled) recovery = prepared.delivery.get("recovery") @@ -251,9 +263,10 @@ def progressive_context_or_current(payload: dict[str, Any], args: argparse.Names runtime_root: Path, directory: Path | None, reader_argv: list[str] | None) -> dict[str, Any]: """Optional stateless IO falls back to this complete decided input/receipt.""" + surface = quota_context_surface(payload) try: return progressive_context_capture_view(payload, args, runtime_root=runtime_root, - directory=directory, surface="turn_envelope" if getattr(args, "turn_envelope", False) else "quota_packet", + directory=directory, surface=surface, reader_argv=reader_argv) except (QuotaDecisionTransportError, OSError, ValueError, EffectRuntimeRemoteError, EffectRuntimeStartupError): return payload @@ -402,14 +415,19 @@ def capture_decision(directory: Path | None, payload: dict[str, object], *, try: digest = write_decision_capture(directory / "decision.json", payload, publish=os.replace) + if record_capture is not None: + record_capture(payload, digest) + if isinstance(payload.get("detail_ref"), dict) and "full_decision" in payload["detail_ref"]: + from ..command_invocation import current_loopx_cli_argv + + write_context_read_reference(directory / "decision.json", digest, + reader_argv=current_loopx_cli_argv()) except (OSError, ValueError) as exc: raise QuotaDecisionTransportError( "Decision capture failed after guard evaluation; the Turn receipt may " "already exist. Do not treat this as missing admission or blindly rerun " f"the guard. Inspect the existing Turn receipt. Capture directory: {directory}" ) from exc - if record_capture is not None: - record_capture(payload, digest) if native_context and args is not None and args.quota_command == "should-run" and payload.get("ok") is True: from ..control_plane.turn_driver.codex_context import record_native_claim_source diff --git a/loopx/cli_commands/quota_presentation.py b/loopx/cli_commands/quota_presentation.py index 3da2407b4d..8069f612b0 100644 --- a/loopx/cli_commands/quota_presentation.py +++ b/loopx/cli_commands/quota_presentation.py @@ -5,18 +5,17 @@ from collections.abc import Callable, Mapping from pathlib import Path -from ..control_plane.effect_runtime import EffectRuntimeRejected -from ..control_plane.quota.turn_envelope import build_turn_envelope, project_captured_replan_cli_view +from ..control_plane.quota.turn_envelope import COMPLETE_TURN_DECISION_VERSION from ..control_plane.scheduler.execution_context import SchedulerExecutionContextResolution -def _compose_explicit_turn_context(payload: dict[str, object], args: argparse.Namespace, *, +def compose_quota_work_contract(payload: dict[str, object], args: argparse.Namespace, *, scheduler_context: Mapping[str, object] | SchedulerExecutionContextResolution | None, capture_directory: Path | None, native_context: bool, record_capture: Callable[[dict[str, object], str], None] | None = None) -> dict[str, object]: - """Select the existing complete source before capture, preserving a failed guard.""" - if not getattr(args, "complete_turn", False) or not isinstance(payload.get("interaction_contract"), Mapping): + """Compose every decided should-run source once before capture and display.""" + if args.quota_command != "should-run" or not isinstance(payload.get("interaction_contract"), Mapping): return payload from ..control_plane.effect_runtime import EffectRuntimeRemoteError, EffectRuntimeStartupError from ..control_plane.quota.error_codes import QuotaDecisionTransportError @@ -111,17 +110,15 @@ def _quota_renderer( render_quota_markdown, render_quota_scheduler_ack_markdown, render_quota_scheduler_failure_markdown, - render_quota_should_run_markdown, ) from ..presentation.renderers.turn_envelope_markdown import ( - render_turn_envelope_markdown, + render_turn_context_markdown, ) command = args.quota_command - if not failure and bool(getattr(args, "turn_envelope", False)): - return render_turn_envelope_markdown + if command == "should-run": + return render_turn_context_markdown return { - "should-run": render_quota_should_run_markdown, "monitor-poll": render_quota_monitor_poll_markdown, "scheduler-ack": render_quota_scheduler_ack_markdown, "scheduler-ack-current": render_quota_scheduler_ack_markdown, @@ -148,15 +145,13 @@ def _project_quota_cli_payload( from ..control_plane.quota.cli_projection import ( compact_quota_monitor_poll_cli_payload, compact_quota_plan_cli_payload, - compact_quota_should_run_cli_payload, ) reject_retired_quota_format(payload) - if getattr(args, "complete_turn", False) and payload.get("schema_version") == "loopx_turn_envelope_v1": + if payload.get("schema_version") == COMPLETE_TURN_DECISION_VERSION: return payload if payload.get("ok") is False and not isinstance(payload.get("interaction_contract"), Mapping): - if (not bool(getattr(args, "turn_envelope", False)) - and getattr(args, "quota_command", None) == "monitor-poll" + if (getattr(args, "quota_command", None) == "monitor-poll" and isinstance(payload.get("before"), Mapping)): # A refused poll still has its decided before snapshot. Its # existing compaction is pure and does not reenter the runtime. @@ -166,34 +161,11 @@ def _project_quota_cli_payload( # A collection failure has no decided contract and must not reenter # its unavailable runtime. Decided refusals still need signed views. # Keep the decided diagnostic, including its original recovery/receipt. - if bool(getattr(args, "turn_envelope", False)): - return {**payload, "turn_envelope_skipped": "quota request failed; original diagnostic retained"} return payload - if not bool(getattr(args, "turn_envelope", False)): - if args.quota_command in {"status", "plan"}: - return compact_quota_plan_cli_payload(payload, detail_sections=detail_sections) - if args.quota_command == "should-run": - if captured_decision_path and "vision" not in detail_sections: - payload = project_captured_replan_cli_view(payload) - return compact_quota_should_run_cli_payload( - payload, - include_todo_summary_detail="agent-todos" in detail_sections, - include_user_todo_summary_detail="user-todos" in detail_sections, - include_goal_boundary_detail="goal-boundary" in detail_sections, - include_vision_detail="vision" in detail_sections, - ) - if args.quota_command == "monitor-poll": - return compact_quota_monitor_poll_cli_payload( - payload, include_decision_detail="decisions" in detail_sections, - ) - return payload - try: - return build_turn_envelope( - payload, - scheduler_execution_context=scheduler_context, - captured_decision_path=captured_decision_path, + if args.quota_command in {"status", "plan"}: + return compact_quota_plan_cli_payload(payload, detail_sections=detail_sections) + if args.quota_command == "monitor-poll": + return compact_quota_monitor_poll_cli_payload( + payload, include_decision_detail="decisions" in detail_sections, ) - except EffectRuntimeRejected as envelope_error: - degraded = dict(payload) - degraded["turn_envelope_skipped"] = str(envelope_error)[:200] - return degraded + return payload diff --git a/loopx/cli_commands/quota_registration.py b/loopx/cli_commands/quota_registration.py index 17bced3560..fb37037076 100644 --- a/loopx/cli_commands/quota_registration.py +++ b/loopx/cli_commands/quota_registration.py @@ -221,13 +221,13 @@ def register_quota_command( "--turn-envelope", action="store_true", help=( - "For `quota should-run`, return the additive bounded TurnEnvelope view. " - "The default full decision remains unchanged." + "Compatibility alias: quota should-run already returns the complete v1 work contract. " + "Context and Delta delivery remain independent." ), ) turn_view.add_argument("--complete-turn", action="store_true", - help="For JSON quota should-run, explicitly consume the complete v1 Turn contract and its shared exact-Turn settlement. " - "The legacy --turn-envelope and unselected output keep their existing versions. Context/Delta delivery remain independent.") + help="Compatibility alias: quota should-run already returns the complete v1 work contract " + "and its shared exact-Turn settlement. Context and Delta delivery remain independent.") capture_group = quota_parser.add_mutually_exclusive_group() capture_group.add_argument( "--decision-output-dir", diff --git a/loopx/cli_commands/quota_result_delivery.py b/loopx/cli_commands/quota_result_delivery.py index c26568d1ed..8a967607d1 100644 --- a/loopx/cli_commands/quota_result_delivery.py +++ b/loopx/cli_commands/quota_result_delivery.py @@ -14,6 +14,7 @@ QuotaDecisionTransportError, ) from ..control_plane.turn_driver.decision_capture import ( + context_capture_read_command, project_captured_context, ) from .quota_capture import ( @@ -24,10 +25,11 @@ native_context_activation, progressive_context_or_current, project_native_quota_context, + quota_context_surface, settlement_capture_failure_view, ) from .quota_presentation import ( - _compose_explicit_turn_context, + compose_quota_work_contract, _project_native_cli_settlement, _project_quota_cli_payload, _quota_renderer, @@ -106,7 +108,6 @@ def prepare_quota_result_context( getattr(args, "codex_context_dir", None) or getattr(args, "codex_context_root", None) ) - and not getattr(args, "turn_envelope", False) and payload.get("ok") is True and payload.get("effective_action") == EffectiveAction.NORMAL_RUN.value and payload.get("normal_delivery_allowed") is True @@ -330,7 +331,17 @@ def _publish_quota_result( or getattr(args, "codex_context_root", None) ) scheduler_context = context.scheduler_context if context is not None else None - payload = _compose_explicit_turn_context( + if (capture_directory is not None and args.quota_command == "should-run" + and isinstance(payload.get("interaction_contract"), Mapping)): + # Bind the existing immutable reader route before signing. Its sidecar + # receives the final byte digest after publication, avoiding a self-hash. + source = capture_directory / "decision.json" + payload = {**payload, "detail_ref": { + **payload.get("detail_ref", {}), + "full_decision": context_capture_read_command(source, "", + reference_file=source.with_suffix(".reader.json"), reader_argv=reader_argv), + }} + payload = compose_quota_work_contract( payload, args, scheduler_context=scheduler_context, @@ -406,10 +417,6 @@ def _publish_quota_result( else None ), ) - if args.quota_command == "should-run" and "host_poll_receipt" in captured_payload: - # Legacy envelope presentation omits this source field. Preserve its - # existing visible receipt by copying the observation, not polling. - payload["host_poll_receipt"] = captured_payload["host_poll_receipt"] succeeded = bool(payload.get("ok")) # Handoff releases the immutable original before any presentation. Native # actual-input observation owns its projection when explicitly selected; @@ -430,9 +437,7 @@ def _publish_quota_result( capture_id=delivery_request[1], goal_id=decision_identity[0], agent_id=decision_identity[1], - surface="turn_envelope" - if getattr(args, "turn_envelope", False) - else "quota_packet", + surface=quota_context_surface(captured_payload), ) if ( not deferred_context diff --git a/loopx/cli_commands/quota_should_run.py b/loopx/cli_commands/quota_should_run.py index 7369220845..dd79c10c7a 100644 --- a/loopx/cli_commands/quota_should_run.py +++ b/loopx/cli_commands/quota_should_run.py @@ -20,7 +20,6 @@ ) from ..file_lock import LockAcquireTimeoutError from ..rollout_event_log import RolloutAppendPreconditionChanged -from .quota_capture import native_context_activation if TYPE_CHECKING: from .quota_action_selection import RequestedQuotaActionSelection @@ -96,10 +95,7 @@ def dispatch_quota_turn_start_hooks( ) # A preview still needs the current local Inbox and preferences. These # hooks observe existing context without recording reads or delivery. - model_read = ( - not getattr(args, "scheduler_observation", False) - and native_context_activation(args)["progressive_enabled"] - ) + model_read = not getattr(args, "scheduler_observation", False) context_dispatch = dispatch_turn_start_hooks( ( turn_start_hook( @@ -370,21 +366,15 @@ def execute_quota_should_run( agent_id=args.agent_id, todo_id=args.todo_id, ) - progressive = ( - not getattr(args, "scheduler_observation", False) - and native_context_activation(args)["progressive_enabled"] - ) + complete_context = not getattr(args, "scheduler_observation", False) payload = export("build_live_quota_should_run_decision")( status_payload, goal_id=args.goal_id, agent_id=args.agent_id, - inline_goal_source=progressive, + inline_goal_source=complete_context, available_capabilities=args.available_capabilities, include_scheduler_detail="scheduler" in detail_sections, - include_agent_todo_detail=( - "agent-todos" in detail_sections - and not bool(getattr(args, "turn_envelope", False)) - ), + include_agent_todo_detail="agent-todos" in detail_sections, codex_app_current_rrule=args.app_automation_current_rrule, registry_path=registry_path, runtime_root=runtime_root, @@ -406,9 +396,7 @@ def execute_quota_should_run( interaction_projection_hooks=interaction_projection_hooks, turn_start_hook_dispatch=turn_start_hook_dispatch, turn_context_projector=context_projector, - context_navigation=( - progressive and not bool(getattr(args, "turn_envelope", False)) - ), + context_navigation=complete_context, goal_ref=goal_ref, ) execution.payload = payload diff --git a/loopx/cli_commands/todo_settlement.py b/loopx/cli_commands/todo_settlement.py index 0b46fe57a3..d63bc765f0 100644 --- a/loopx/cli_commands/todo_settlement.py +++ b/loopx/cli_commands/todo_settlement.py @@ -131,6 +131,7 @@ def _todo_settlement_plan( writeback_path_args=path_args, goal_ref=goal_ref, quota_spend_source=quota_spend_source, + composed_settlement=True, ).as_dict() from ..capabilities.explore.turn_context import project_settlement_attachment diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index 648fb9bbd8..a96846a9e7 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -815,8 +815,8 @@ export function createEffectRuntimeHandlers( "settlement.plan_payload", (params) => settlementPlanPayload(settlementPlanInput(params.plan, "plan")), ], - ["settlement.turn_scoped_cli_plan", lazyHandler(() => import("./quota/settlement_plan.ts"), ({turnScopedCliSettlementPlan}) => (params) => - settlementPlanPayload(turnScopedCliSettlementPlan(params)))], + ["settlement.turn_scoped_cli_plan", lazyHandler(() => import("./quota/settlement_plan.ts"), + ({turnScopedCliSettlementPlanPayload}) => turnScopedCliSettlementPlanPayload)], ["settlement.native_cli_projection", lazyHandler(() => import("./quota/settlement_plan.ts"), ({nativeCliSettlementProjection}) => nativeCliSettlementProjection)], [ diff --git a/loopx/control_plane/heartbeat/builder.py b/loopx/control_plane/heartbeat/builder.py index 2f1e587d57..967bf44202 100644 --- a/loopx/control_plane/heartbeat/builder.py +++ b/loopx/control_plane/heartbeat/builder.py @@ -563,14 +563,12 @@ def build_heartbeat_prompt( compact_prompt_command=str(commands["compact_prompt_command"]), brief_prompt_command=str(commands["brief_prompt_command"]), thin_prompt_command=str(commands["thin_prompt_command"]), - **({"captured_envelope": True} if turn_envelope else {}), **({"captured_context": True} if native_goal_host and effective_context_delivery == "on" else {}), **reward_memory_rule_kwargs, ) task_body = bind_exact_turn_settlement_task_body( task_body, turn_instance_id=normalized_turn_instance_id, - captured_envelope=turn_envelope, ) if fine_grained: task_body = f"{task_body}\n\n{FINE_GRAINED_TURN_RULE}" @@ -651,7 +649,6 @@ def build_heartbeat_prompt( brief=brief, thin=thin, native_goal_host=native_goal_host, - captured_envelope=turn_envelope, ), "task_body": task_body, } diff --git a/loopx/control_plane/quota/effect_program.py b/loopx/control_plane/quota/effect_program.py index 9b315733dd..741ede25e3 100644 --- a/loopx/control_plane/quota/effect_program.py +++ b/loopx/control_plane/quota/effect_program.py @@ -237,6 +237,7 @@ def build_turn_scoped_cli_settlement_plan( goal_ref: Mapping[str, object] | None = None, autonomous_replan: bool = False, handoff_mode: str | None = None, + composed_settlement: bool = False, ) -> SettlementPlan: if sum(bool(value) for value in (todo_id, replan_obligation_id, request_subject)) != 1: raise ValueError( @@ -325,6 +326,7 @@ def writeback_command(boundary: str) -> str: ) payload = _render_cli_settlement_plan({ "identity": identity.as_dict(), "delivery_boundary": delivery_boundary, + "composed_settlement": composed_settlement, "autonomous_replan": autonomous_replan, "handoff_mode": handoff_mode, "completion_proof_supplied": completion_proof_supplied, diff --git a/loopx/control_plane/quota/settlement_plan.ts b/loopx/control_plane/quota/settlement_plan.ts index a05686198b..b2f36e91c0 100644 --- a/loopx/control_plane/quota/settlement_plan.ts +++ b/loopx/control_plane/quota/settlement_plan.ts @@ -1,7 +1,7 @@ /** CLI guidance for the existing completion -> writeback -> spend protocol. * This is a projection, not a validation, lease or receipt authorization. */ import { - settlementIdentity, type JsonObject, type SettlementIdentityInput, + settlementIdentity, settlementPlanPayload, type JsonObject, type SettlementIdentityInput, SETTLEMENT_PLAN_SCHEMA_VERSION, type SettlementPlan, type SettlementStep, } from "../effect_program.ts"; import {isDeepStrictEqual} from "node:util"; @@ -92,6 +92,21 @@ export function completeCliSettlementChannel(payload: JsonObject): JsonObject { return composed ?? cli; } +/** Current continuation commands share the complete source's composition. + * Historical callers retain the original plan unless explicitly migrated. */ +export function turnScopedCliSettlementPlanPayload(params: JsonObject): JsonObject { + const plan = settlementPlanPayload(turnScopedCliSettlementPlan(params)); + if (params.composed_settlement === undefined + || !requireBoolean(params.composed_settlement, "composed_settlement")) return plan; + const steps = plan.ordered_steps as JsonObject[]; + const cli = composedCliSettlementChannel({settlement_plan: plan, + next_cli_actions: steps.filter(step => step.kind === "durable_writeback" || step.kind === "quota_spend") + .map(step => step.command_template)}); + if (jsonObject(cli.settlement_plan)?.schema_version !== COMPOSED_CLI_SETTLEMENT_PLAN_SCHEMA_VERSION) + throw new Error("current CLI continuation requires a composed settlement plan"); + return cli.settlement_plan as JsonObject; +} + export function turnScopedCliSettlementPlan(params: JsonObject): SettlementPlan { const identity = settlementIdentity( requireJsonObject(params.identity, "identity") as unknown as SettlementIdentityInput, diff --git a/loopx/control_plane/testing/actual_default_model_behavior_portfolio.py b/loopx/control_plane/testing/actual_default_model_behavior_portfolio.py index 226084aa7d..0b60565ade 100644 --- a/loopx/control_plane/testing/actual_default_model_behavior_portfolio.py +++ b/loopx/control_plane/testing/actual_default_model_behavior_portfolio.py @@ -10,8 +10,7 @@ from typing import Any from ...bootstrap_command_pack import build_start_goal_guided_packet -from ..quota.cli_projection import compact_quota_should_run_cli_payload -from ..quota.turn_envelope import quota_action_signature_document +from ..quota.turn_envelope import assert_complete_turn_decision, compose_turn_decision, quota_action_signature_document from ..work_items.interaction_contract import build_interaction_contract from .action_portfolio_scenarios import ( turn_scenario_source as _turn_scenario_source, @@ -64,7 +63,8 @@ "actual_default_model_behavior_scenario_catalog_v0" ) ACTUAL_DEFAULT_MODEL_BEHAVIOR_REPEAT_ATTEMPTS = 2 -# Synthetic pretty-JSON regression allowance, not a production transport limit. +# Historical compact-output threshold: characterizes the crowded fixture only. +# Current actors receive the complete source; production wire/page limits are separate. ACTUAL_DEFAULT_MODEL_BEHAVIOR_HOT_PATH_JSON_BUDGET = 90_000 ACTUAL_DEFAULT_MODEL_BEHAVIOR_CONTRAST_SCHEMA_VERSION = ( "actual_default_model_behavior_contrast_v0" @@ -755,12 +755,12 @@ def _build_actual_default_model_behavior_scenario_sources( return packets -def _compact_actual_default_model_behavior_scenario_sources( +def _compose_actual_default_model_behavior_scenario_sources( sources: Mapping[str, Mapping[str, Any]], ) -> dict[str, dict[str, Any]]: return { scenario_id: ( - compact_quota_should_run_cli_payload(deepcopy(dict(packet))) + compose_turn_decision(packet, composed_settlement=True) if packet.get("mode") == "should-run" else deepcopy(dict(packet)) ) @@ -774,7 +774,7 @@ def build_actual_default_model_behavior_scenario_inputs( """Build paired source and actual-default actor packets from one fixture.""" sources = _build_actual_default_model_behavior_scenario_sources(root) - return sources, _compact_actual_default_model_behavior_scenario_sources(sources) + return sources, _compose_actual_default_model_behavior_scenario_sources(sources) def build_actual_default_model_behavior_scenario_packets( @@ -839,8 +839,7 @@ def _validate_quota_hot_path_compaction_regression( ) -> None: if _pretty_json_size(source) <= ACTUAL_DEFAULT_MODEL_BEHAVIOR_HOT_PATH_JSON_BUDGET: raise ValueError("compaction-regression source must exceed the hot-path budget") - if _pretty_json_size(packet) > ACTUAL_DEFAULT_MODEL_BEHAVIOR_HOT_PATH_JSON_BUDGET: - raise ValueError("compaction-regression packet exceeds the hot-path budget") + assert_complete_turn_decision(packet) if packet.get("capability_gate") != source.get("capability_gate"): raise ValueError("compaction regression must preserve complete capability candidate context") if contract.get("selected_todo_id") != expected_selected_todo_id: diff --git a/loopx/control_plane/testing/cli_output_budget.py b/loopx/control_plane/testing/cli_output_budget.py index 0e54894cd7..c32c1228b2 100644 --- a/loopx/control_plane/testing/cli_output_budget.py +++ b/loopx/control_plane/testing/cli_output_budget.py @@ -141,53 +141,29 @@ class CliOutputCommandClassification: "selectors for scheduler, agent-todos, user-todos, goal-boundary, " "or all" ), - semantic_json_keys=("interaction_contract", "scheduler_hint", "selected_todo"), - markdown_anchor="# LoopX Quota Should Run", - max_chars={ - # The same explicitly imported fixture on base/head emits 24,099 - # JSON chars. Keep canonical provenance and complete User context. - "small": {"json": 25_000, "markdown": 10_000}, - # Same 36-Todo / 12-run source: 38,432 -> 39,101 chars with - # objective/evidence guidance; small and multi-agent paths unchanged. - # Per-Todo and fixed semantic growth are accounted for separately. - # Canonical source witnesses use the full Markdown context carrier; - # the unchanged 36-Todo fixture emits 10,225 chars / 166 lines. - # Native Windows paired base/head both emit 40,701 JSON chars. - # Retain complete routes/context and bounded host-path headroom; - # line, per-Todo/fixed growth and all other ceilings stay unchanged. - # Inherited Stride adds its complete decision/axis/source contract: - # the same native fixture measures 35,597 -> 42,281 characters on POSIX - # and 42,501 characters on native Windows due to drive and backslash paths. - # Preserve the original 42,000 failure and the required semantics; - # calibrate this regression allowance to 43,000, leaving bounded headroom - # (~499 chars on Windows, ~719 chars on POSIX) without widening collection - # or production transport limits. - # The progressive oracle now also bounds the complete recovered body. - # The same fixture measures 50,795 JSON body chars and 16,857 - # Markdown chars. Preserve the original 43,000 / 10,500 failures and - # calibrate only these two presentation ceilings to measured values - # plus bounded headroom. - "crowded": {"json": 51_000, "markdown": 17_000}, - # The unchanged 18-Todo / 3-Agent fixture on main ffc90182b and - # this candidate both emit 25,836 JSON characters (96 matched - # surface/mode measurements, no semantic or route differences). - # Preserve complete decision facts; calibrate only this synthetic - # presentation ceiling. The historical 25,500 failure remains; - # line/growth guards and production transport limits are unchanged. - "multi_agent": {"json": 26_500, "markdown": 7_000}, - }, + semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), + markdown_anchor="# LoopX Turn Envelope", + # Matched ef099ae3 frozen small/crowded/multi-agent fixtures: + # JSON 23,289/42,965/25,514 -> 24,984/53,441/29,574; + # Markdown 7,476/8,143/6,441 -> 25,083/53,543/29,674. + # Full Goal bytes formerly required a separate cat; Markdown now also + # carries every source field. Retain the original 25k/51k/26.5k JSON + # and 10k/17k/7k Markdown misses; this is a measured cost increase, + # not model/outcome qualification. Line and other-route limits stay. + max_chars={"small": {"json": 26_000, "markdown": 26_000}, + "crowded": {"json": 55_000, "markdown": 55_000}, + "multi_agent": {"json": 31_000, "markdown": 31_000}}, max_lines={ "small": {"json": 600, "markdown": 190}, "crowded": {"json": 950, "markdown": 180}, "multi_agent": {"json": 650, "markdown": 80}, }, + output_contract_version="loopx_turn_envelope_v1", scale_axis="todo_count", - max_json_growth_chars_per_unit=300, - # Required replan carries dense decision evidence from the full index. - # Required authoring and objective/evidence advice are fixed packets. - # Paired crowded-minus-small growth: 19,236 -> 19,905 chars; the - # new advice adds 669. Small and multi-agent paths stay identical. - # This fixed decision packet must not relax per-Todo growth or other routes. + max_json_growth_chars_per_unit=600, + # Matched crowded-minus-small: 19,676 -> 28,457. Full Goal material + # includes the original Todo text as well as structured current work. + # Attribute this collection cost per Todo; keep the fixed allowance. max_json_fixed_semantic_growth_chars=9_700, ), CliOutputBudgetSpec( @@ -444,76 +420,84 @@ class CliOutputCommandClassification: parent_surface_id="quota_should_run", command="quota should-run --context-delivery off --include-detail scheduler", output_formats=("json", "markdown"), - semantic_json_keys=("interaction_contract", "scheduler_hint", "selected_todo"), - markdown_anchor="# LoopX Quota Should Run", - max_chars={"json": 31_000, "markdown": 10_000}, + semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), + markdown_anchor="# LoopX Turn Envelope", + max_chars={'json': 31000, 'markdown': 26000}, max_lines={"json": 820, "markdown": 190}, + output_contract_version="loopx_turn_envelope_v1", ), CliOutputModeVariantSpec( variant_id="quota_should_run_todo_summary_detail", parent_surface_id="quota_should_run", command="quota should-run --context-delivery off --include-detail agent-todos", output_formats=("json", "markdown"), - semantic_json_keys=("interaction_contract", "scheduler_hint", "selected_todo"), - markdown_anchor="# LoopX Quota Should Run", - max_chars={"json": 55_000, "markdown": 10_000}, + semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), + markdown_anchor="# LoopX Turn Envelope", + max_chars={'json': 55000, 'markdown': 27000}, max_lines={"json": 1_350, "markdown": 190}, + output_contract_version="loopx_turn_envelope_v1", ), CliOutputModeVariantSpec( variant_id="quota_should_run_user_todo_summary_detail", parent_surface_id="quota_should_run", command="quota should-run --context-delivery off --include-detail user-todos", output_formats=("json", "markdown"), - semantic_json_keys=("interaction_contract", "scheduler_hint", "selected_todo"), - markdown_anchor="# LoopX Quota Should Run", - max_chars={"json": 35_000, "markdown": 10_000}, + semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), + markdown_anchor="# LoopX Turn Envelope", + max_chars={'json': 35000, 'markdown': 27000}, max_lines={"json": 900, "markdown": 190}, + output_contract_version="loopx_turn_envelope_v1", ), CliOutputModeVariantSpec( variant_id="quota_should_run_goal_boundary_detail", parent_surface_id="quota_should_run", command="quota should-run --context-delivery off --include-detail goal-boundary", output_formats=("json", "markdown"), - semantic_json_keys=("interaction_contract", "scheduler_hint", "selected_todo"), - markdown_anchor="# LoopX Quota Should Run", - max_chars={"json": 35_000, "markdown": 10_000}, + semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), + markdown_anchor="# LoopX Turn Envelope", + max_chars={'json': 35000, 'markdown': 26000}, max_lines={"json": 900, "markdown": 190}, + output_contract_version="loopx_turn_envelope_v1", ), CliOutputModeVariantSpec( variant_id="quota_should_run_vision_detail", parent_surface_id="quota_should_run", command="quota should-run --context-delivery off --include-detail vision", output_formats=("json", "markdown"), - semantic_json_keys=("interaction_contract", "scheduler_hint", "selected_todo"), - markdown_anchor="# LoopX Quota Should Run", + semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), + markdown_anchor="# LoopX Turn Envelope", # The complete captured Vision projection measures 58,393 JSON chars. # Preserve the original 55,000 failure; keep a 607-character allowance. - max_chars={"json": 59_000, "markdown": 10_000}, + max_chars={'json': 59000, 'markdown': 26000}, max_lines={"json": 1_350, "markdown": 190}, + output_contract_version="loopx_turn_envelope_v1", ), CliOutputModeVariantSpec( variant_id="quota_should_run_all_detail", parent_surface_id="quota_should_run", command="quota should-run --context-delivery off --include-detail all", output_formats=("json", "markdown"), - semantic_json_keys=("interaction_contract", "scheduler_hint", "selected_todo"), - markdown_anchor="# LoopX Quota Should Run", - max_chars={"json": 85_000, "markdown": 10_000}, + semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), + markdown_anchor="# LoopX Turn Envelope", + max_chars={'json': 85000, 'markdown': 27000}, max_lines={"json": 2_100, "markdown": 190}, + output_contract_version="loopx_turn_envelope_v1", ), CliOutputModeVariantSpec( variant_id="quota_should_run_turn_envelope", parent_surface_id="quota_should_run", command="quota should-run --context-delivery off --turn-envelope", output_formats=("json", "markdown"), - semantic_json_keys=("schema_version", "contract_capsule", "action_signature"), + semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), markdown_anchor="# LoopX Turn Envelope", - # The same canonical fixture costs 10,681 JSON chars (12,268 with - # multi-subagent) on base/head. Rendering the instruction once reduces - # Markdown 4,996 -> 4,521 chars without removing source content. - # These stdout guards do not change the envelope's wire byte limit. - max_chars={"json": 13_000, "markdown": 4_800}, + # The alias now carries the same full source. Matched small JSON: + # 9,113 -> 24,984; blocking User gate 6,914 -> 22,917 (23,029 UTF-8 + # bytes); enabled multi-subagent 10,727 -> 26,561. Markdown is + # 2,425 -> 25,083. Retain the old 13k/4.8k misses. Production wire + # limits and all independent authority/semantic checks stay unchanged. + max_chars={'json': 31000, 'markdown': 31000}, max_lines={"json": 300, "markdown": 140}, + output_contract_version="loopx_turn_envelope_v1", ), CliOutputModeVariantSpec( variant_id="loopx_turn_plan_transaction_detail", diff --git a/loopx/control_plane/testing/cli_output_differential.py b/loopx/control_plane/testing/cli_output_differential.py index 491205a2b9..cd34e1c428 100644 --- a/loopx/control_plane/testing/cli_output_differential.py +++ b/loopx/control_plane/testing/cli_output_differential.py @@ -709,6 +709,85 @@ def _complete_turn_plan_migration(base: dict[str, Any], candidate: dict[str, Any and candidate.get("output_contract_version") == ("loopx_turn_plan_v1" if row.startswith("variant/") else None)) +def _matching_quota_controls(base: dict[str, Any], candidate: dict[str, Any]) -> bool: + before, after = base.get("quota_controls"), candidate.get("quota_controls") + if not isinstance(before, dict) or not isinstance(after, dict): + return False + fields = before.get("field_sha256") + # The frozen probe owns the source-field inventory; its independent tests + # pin every field and mutation. Compare its bounded witness here without + # creating another inventory/consumer of retired source fields. + return bool(isinstance(fields, dict) and len(fields) == 19 + and all(isinstance(key, str) and key for key in fields) + and all(isinstance(value, str) and len(value) == 64 for value in fields.values()) + and fields == after.get("field_sha256") + and isinstance(before.get("controls_sha256"), str) and len(before["controls_sha256"]) == 64 + and before["controls_sha256"] == after.get("controls_sha256")) + + +def _complete_quota_source_migration(base: dict[str, Any], candidate: dict[str, Any]) -> bool: + """Qualify this declared carrier transition, not arbitrary or later growth. + + The fixture compares 19 original control values, not a schema name alone. + This does not certify full instruction equivalence, recovery or model use. + """ + formats = {"json", "markdown"} + variants = { + "quota_should_run_scheduler_detail", "quota_should_run_todo_summary_detail", + "quota_should_run_user_todo_summary_detail", "quota_should_run_goal_boundary_detail", + "quota_should_run_vision_detail", "quota_should_run_all_detail", + } + aliases = { + "quota_should_run_turn_envelope": {"json", "markdown"}, + "quota_should_run_turn_envelope_blocking_user_gate": {"json"}, + "quota_should_run_turn_envelope_multi_subagent": {"json"}, + } + scenario, output_format = base.get("scenario"), base.get("format") + variant = base.get("variant_id") + legacy = variant in aliases + allowed_variant = variant in variants or (legacy and output_format in aliases[variant]) + policy = "explicit_opt_in_cold_path" if variant else "absolute_hot_path" + row = (f"variant/{variant}/{scenario}/{output_format}" if variant + else f"surface/quota_should_run/{scenario}/{output_format}") + if not (base.get("row_id") == candidate.get("row_id") == row + and base.get("surface_id") == candidate.get("surface_id") == "quota_should_run" + and base.get("variant_id") == candidate.get("variant_id") + and scenario == candidate.get("scenario") and scenario in {"small", "crowded", "multi_agent"} + and (scenario == "small" if variant else True) + and output_format == candidate.get("format") and output_format in formats + and (not variant or allowed_variant) + and base.get("qualification_policy") == candidate.get("qualification_policy") == policy + and base.get("output_contract_version") is None + and candidate.get("output_contract_version") == "loopx_turn_envelope_v1" + and tuple(base.get("projection_envelope_schema_versions") or []) + == (() if legacy else ("loopx_projection_envelope_v0",)) + and tuple(candidate.get("projection_envelope_schema_versions") or []) + == ("loopx_projection_envelope_v0",) + and base.get("markdown_anchor") == ("# LoopX Turn Envelope" if legacy else "# LoopX Quota Should Run") + and candidate.get("markdown_anchor") == "# LoopX Turn Envelope" + and _matching_quota_controls(base, candidate)): + return False + return (base["quota_controls"].get("source_schema") == ("loopx_turn_envelope_v0" if legacy else None) + and candidate["quota_controls"].get("source_schema") == "loopx_turn_envelope_v1") + + +def _complete_quota_source_allowance(base: dict[str, Any], candidate: dict[str, Any]) -> dict[Metric, int]: + if not _complete_quota_source_migration(base, candidate): + return {} + # Same frozen ef099ae3 caller: full Goal material moves into this source; + # Markdown carries every field. Absolute ceilings still apply. A v1 -> v1 + # change, altered control/material witness or unrelated row gets no waiver. + legacy = base["quota_controls"]["source_schema"] == "loopx_turn_envelope_v0" + if legacy: + chars = 16_640 if base["format"] == "json" else 23_296 + elif base["format"] == "json": + chars = {"small": 2_048, "crowded": 11_264, "multi_agent": 4_608}[base["scenario"]] + else: + chars = 19_456 if base.get("variant_id") else {"small": 18_432, "crowded": 46_336, "multi_agent": 24_064}[base["scenario"]] + return {"chars": chars, "utf8_bytes": chars, + **({"compact_payload_chars": chars} if base["format"] == "json" else {"lines": 6})} + + def _projection_envelope_migration( base: dict[str, Any], candidate: dict[str, Any], *, output_format: str, ) -> tuple[dict[Metric, int], list[str], list[str]]: @@ -719,6 +798,8 @@ def _projection_envelope_migration( return {}, [], [] if _complete_turn_plan_migration(base, candidate): return {}, [], ["complete Turn plan exposes the full source projection metadata"] + if _complete_quota_source_migration(base, candidate): + return {}, [], ["complete quota source retains its original projection metadata"] surface_id = str(base.get("surface_id") or "") row_surface = str(base.get("row_id") or "").partition("/")[2].partition("/")[0] if (surface_id == "todo_list" and row_surface in { @@ -1031,6 +1112,7 @@ def _compare_row_growth( context_allowance = {metric: max(context_allowance.get(metric, 0), bound) for metric in ("chars", "utf8_bytes", "compact_payload_chars")} review_signals.append("Turn plan v0 -> v1: unchanged current controls; full-source costs require review") + quota_allowance = _complete_quota_source_allowance(base, candidate) deltas: dict[str, int | None] = {} allowances: dict[str, int | None] = {} for metric in ("chars", "utf8_bytes", "lines", "compact_payload_chars"): @@ -1074,6 +1156,7 @@ def _compare_row_growth( authoring_allowance.get(metric, 0), continuation_allowance.get(metric, 0), context_allowance.get(metric, 0), + quota_allowance.get(metric, 0), ) # Thin installed prompts contain bilingual lifecycle instructions. A # small character-level clarification can cost three bytes per CJK @@ -1141,6 +1224,7 @@ def _compare_row(base: dict[str, Any], candidate: dict[str, Any]) -> dict[str, A changed = sorted(key for key in old.keys() | new.keys() if old.get(key) != new.get(key)) failures.append("Turn plan current controls changed: " + ", ".join(changed)) + quota_migration = _complete_quota_source_migration(base, candidate) base_output_contract = base.get("output_contract_version") candidate_output_contract = candidate.get("output_contract_version") heartbeat_agent_input_migration = bool( @@ -1153,6 +1237,7 @@ def _compare_row(base: dict[str, Any], candidate: dict[str, Any]) -> dict[str, A candidate_output_contract != base_output_contract and not heartbeat_agent_input_migration and not _complete_turn_plan_migration(base, candidate) + and not quota_migration ): failures.append("output_contract_version changed") @@ -1178,7 +1263,7 @@ def _compare_row(base: dict[str, Any], candidate: dict[str, Any]) -> dict[str, A preview = ", ".join(missing[:5]) suffix = f" (+{len(missing) - 5} more)" if len(missing) > 5 else "" message = f"semantic_json_keys removed: {preview}{suffix}" - if heartbeat_agent_input_migration or _complete_turn_plan_migration(base, candidate): + if heartbeat_agent_input_migration or _complete_turn_plan_migration(base, candidate) or quota_migration: review_signals.append(message) else: failures.append(message) @@ -1196,11 +1281,11 @@ def _compare_row(base: dict[str, Any], candidate: dict[str, Any]) -> dict[str, A review_signals.append(f"{field} removed: {preview}{suffix}") base_anchor = base.get("markdown_anchor") - if base_anchor and candidate.get("markdown_anchor") != base_anchor: + if base_anchor and candidate.get("markdown_anchor") != base_anchor and not quota_migration: failures.append("markdown_anchor changed") if migration.signature_changed: if migration.signature_migration is None: - if _complete_turn_plan_migration(base, candidate): + if _complete_turn_plan_migration(base, candidate) or quota_migration: review_signals.append("historical action signature replaced by the checked complete source") else: failures.append("action_signature semantic digest changed") diff --git a/loopx/control_plane/testing/terminal_settlement_tool_behavior.py b/loopx/control_plane/testing/terminal_settlement_tool_behavior.py index 8f938eeb4b..12218c2e9f 100644 --- a/loopx/control_plane/testing/terminal_settlement_tool_behavior.py +++ b/loopx/control_plane/testing/terminal_settlement_tool_behavior.py @@ -12,6 +12,7 @@ from typing import Any, cast from ..coordination.goal_storage_initialization import initialize_goal_storage_target +from ..effect_program import SETTLEMENT_RECEIPT_SCHEMA_VERSION from ...heartbeat_prompt import build_heartbeat_prompt from ...control_plane.todos.mutation_api import add_goal_todo, complete_goal_todo from ..quota.turn_envelope import quota_action_signature_document @@ -654,6 +655,8 @@ def _quota_contract(packet: Mapping[str, Any]) -> dict[str, Any]: for item in settlement_plan.get("ordered_steps", []) if isinstance(item, Mapping) ] + spend = next((item for item in settlement_plan.get("ordered_steps", []) + if isinstance(item, Mapping) and item.get("kind") == "quota_spend"), {}) contract = { "decision": "execute", "selected_todo_id": selected.get("todo_id"), @@ -670,22 +673,38 @@ def _quota_contract(packet: Mapping[str, Any]) -> dict[str, Any]: or not contract["delivery_allowed"] or contract["quiet_noop_allowed"] or ordered_steps != _EXPECTED_RECEIPT_STEPS + or settlement_plan.get("schema_version") != "quota_settlement_plan_v2" + or spend.get("owner") != "runtime" + or "command_template" in spend ): - raise ValueError("real quota packet did not expose terminal settlement v1") + raise ValueError("real quota packet did not expose runtime-owned terminal settlement") return contract -def _settlement_receipt_steps(payload: Mapping[str, Any]) -> list[str]: +def _settlement_receipt_steps( + payload: Mapping[str, Any], state: _QualificationState, +) -> list[str]: settlement = payload.get("settlement_result") if not isinstance(settlement, Mapping) or settlement.get("ok") is not True: raise _TerminalToolViolation("settlement result is missing or failed") receipts = settlement.get("receipts") if not isinstance(receipts, list): raise _TerminalToolViolation("settlement receipts are missing") + identity = payload.get("settlement_identity") + heartbeat = (state.quota_packet or {}).get("heartbeat_receipt") + original = heartbeat.get("settlement_identity") if isinstance(heartbeat, Mapping) else None + effect_id = identity.get("effect_id") if isinstance(identity, Mapping) else None + if settlement.get("failure") is not None or not isinstance(original, Mapping) or identity != original or not isinstance(effect_id, str) or not effect_id or any( + not isinstance(item, Mapping) + or item.get("schema_version") != SETTLEMENT_RECEIPT_SCHEMA_VERSION + or item.get("status") != "committed" + or item.get("effect_id") != effect_id + for item in receipts + ): + return [] return [ str(item.get("step_kind")) for item in receipts - if isinstance(item, Mapping) and item.get("status") == "committed" ] @@ -918,7 +937,7 @@ def _execute_todo_completion( if not _matches_identity(tokens, state): raise _TerminalToolViolation("completion_identity_mismatch") payload = _execute_cli(command, state) - receipt_steps = _settlement_receipt_steps(payload) + receipt_steps = _settlement_receipt_steps(payload, state) expected_steps = _EXPECTED_RECEIPT_STEPS if terminal else _EXPECTED_RECEIPT_STEPS[:1] if receipt_steps != expected_steps: raise _TerminalToolViolation("terminal_closeout_receipt_mismatch" if terminal @@ -964,30 +983,20 @@ def _execute_terminal_cli( if payload.get("error_code") == "progress_observation_invalid_arguments" else "fixture_unchanged_cli_rejection") return json.dumps(payload, ensure_ascii=False, sort_keys=True), kind - receipt_steps = _settlement_receipt_steps(payload) - if receipt_steps != _EXPECTED_RECEIPT_STEPS[:2]: + receipt_steps = _settlement_receipt_steps(payload, state) + if receipt_steps != _EXPECTED_RECEIPT_STEPS[:3]: raise _TerminalToolViolation("writeback_receipt_mismatch") state.writeback_committed = True + state.spend_committed = True state.receipt_steps = receipt_steps kind = "durable_writeback" output = json.dumps(payload, ensure_ascii=False, sort_keys=True) elif command_kind == "quota" and command_action == "spend-slot": if not state.writeback_committed: raise _TerminalToolViolation("quota_spend_before_writeback") - if not tokens or not _matches_identity(tokens, state): - raise _TerminalToolViolation("quota_spend_identity_mismatch") - if "--execute" not in tokens or argument_value( - tokens, "--source" - ) != "heartbeat": - raise _TerminalToolViolation("quota_spend_contract_mismatch") - payload = _execute_cli(command, state) - receipt_steps = _settlement_receipt_steps(payload) - if receipt_steps != _EXPECTED_RECEIPT_STEPS[:3]: - raise _TerminalToolViolation("quota_spend_receipt_mismatch") - state.spend_committed = True - state.receipt_steps = receipt_steps - kind = "quota_spend" - output = json.dumps(payload, ensure_ascii=False, sort_keys=True) + # The current complete plan makes this a runtime-owned writeback + # effect. A model must not issue a second debit after that receipt. + raise _TerminalToolViolation("quota_spend_contract_mismatch") elif command_kind == "todo" and command_action == "complete": return _execute_todo_completion(command, tokens, state) else: @@ -1094,6 +1103,8 @@ def qualify( "identity and settlement plan. A later same-Turn " "settlement_plan supplies remaining commands and authoring " "schema; use committed receipts to choose the next step. " + "The runtime commits quota_spend with durable_writeback; " + "observe those receipts and do not issue another spend. " "A receipt without command templates does not replace " "that plan. " f"{QUOTA_FIRST_TOOL_INSTRUCTION}" diff --git a/loopx/control_plane/todos/markdown.py b/loopx/control_plane/todos/markdown.py index 4a14fc3bbb..4fcfd1f0ea 100644 --- a/loopx/control_plane/todos/markdown.py +++ b/loopx/control_plane/todos/markdown.py @@ -43,7 +43,9 @@ def _render_lease_recovery(payload: dict[str, Any]) -> list[str]: def _render_settlement_plan(plan: object) -> list[str]: """Project the TS-owned recovery plan without adding admission decisions.""" - if not isinstance(plan, dict) or plan.get("schema_version") != "quota_settlement_plan_v1": + if not isinstance(plan, dict) or plan.get("schema_version") not in { + "quota_settlement_plan_v1", "quota_settlement_plan_v2", + }: return [] lines = ["", "## Same-Turn settlement plan", ""] for step in plan.get("ordered_steps", []): @@ -354,7 +356,8 @@ def render_todo_markdown(payload: dict[str, Any]) -> str: marker = todo_marker_for_status(payload.get("status") or TODO_STATUS_OPEN) lines.extend(["", "## Todo", "", f"- [{marker}] {payload.get('todo')}"]) if (not payload.get("error") and payload.get("settlement_plan") - and (payload.get("replan_transition") or {}).get("turn_boundary") == "settle_original_turn_before_end"): + and ((payload.get("replan_transition") or {}).get("turn_boundary") == "settle_original_turn_before_end" + or (payload.get("settlement_progress") or {}).get("next_step") == "durable_writeback")): if payload.get("instruction"): lines.extend(["", str(payload["instruction"])]) lines.extend(_render_settlement_plan(payload["settlement_plan"])) diff --git a/loopx/presentation/renderers/turn_envelope_markdown.py b/loopx/presentation/renderers/turn_envelope_markdown.py index 6edc454532..5da2dce068 100644 --- a/loopx/presentation/renderers/turn_envelope_markdown.py +++ b/loopx/presentation/renderers/turn_envelope_markdown.py @@ -42,10 +42,22 @@ def turn_envelope_budget_warning_lines(payload: dict[str, Any]) -> list[str]: ] +def render_turn_context_markdown(payload: dict[str, Any]) -> str: + """Render the complete carrier or its same-source recovery reference.""" + fields = ",\n".join( + json.dumps(key, ensure_ascii=False) + ":" + + json.dumps(value, ensure_ascii=False, separators=(",", ":")) + for key, value in payload.items() + ) + return "# LoopX Turn Envelope\n\n```json\n{\n" + fields + "\n}\n```" + + def render_turn_envelope_markdown(payload: dict[str, Any]) -> str: from ...control_plane.effect_program import reject_retired_quota_format reject_retired_quota_format(payload) + if payload.get("schema_version") == "loopx_turn_envelope_v1": + return render_turn_context_markdown(payload) action_value = payload.get("action") user_value = payload.get("user") writeback_value = payload.get("writeback") diff --git a/tests/control_plane/test_actual_default_model_behavior_portfolio.py b/tests/control_plane/test_actual_default_model_behavior_portfolio.py index c11a03573e..7ca3c6f1ba 100644 --- a/tests/control_plane/test_actual_default_model_behavior_portfolio.py +++ b/tests/control_plane/test_actual_default_model_behavior_portfolio.py @@ -15,10 +15,12 @@ context_reading_transport, latest_quota_payload, ) -from loopx.control_plane.quota.cli_projection import ( - compact_quota_should_run_cli_payload, +from loopx.control_plane.quota.turn_envelope import ( + COMPLETE_TURN_DECISION_VERSION, + assert_complete_turn_decision, + compose_turn_decision, + quota_action_signature_document, ) -from loopx.control_plane.quota.turn_envelope import quota_action_signature_document from loopx.control_plane.scheduler.execution_context import ( scheduler_execution_context_for_runtime_profile, ) @@ -39,7 +41,6 @@ DoubaoActorTransportError, ) from loopx.control_plane.testing.model_behavior_qualification import ( - FULL_QUOTA_DECISION_PACKET_SCHEMA_VERSION, MODEL_BEHAVIOR_ACTOR_RESULT_SCHEMA_VERSION, MODEL_BEHAVIOR_DECISION_SCHEMA_VERSION, model_behavior_semantic_contract_from_packet, @@ -535,7 +536,7 @@ def _capability_reentry_action( request: Mapping[str, Any], ) -> ScriptedExecToolAction: payload = _latest_tool_payload(request) - reentry = payload["runtime_capability_reentry"] + reentry = payload["interaction_contract"]["cli_channel"]["runtime_capability_reentry"] return ScriptedExecToolAction(str(reentry["candidates"][0]["command"])) @@ -555,17 +556,6 @@ def _terminal_writeback_action( ) -def _terminal_spend_action(request: Mapping[str, Any]) -> ScriptedExecToolAction: - payload = _latest_tool_payload(request) - command = payload["interaction_contract"]["cli_channel"]["next_cli_actions"][1] - return ScriptedExecToolAction( - command=command.replace( - '"${LOOPX_TURN:?}"', - "turn-portfolio-terminal", - ) - ) - - def _terminal_closeout_action( request: Mapping[str, Any], ) -> ScriptedExecToolAction: @@ -684,7 +674,6 @@ def terminal_settlement_actor(run_id: str) -> Mapping[str, Any]: ScriptedExecToolAction(fixture.quota_guard_command), ScriptedExecToolAction("cat fixture/settlement-proof.json"), _terminal_writeback_action, - _terminal_spend_action, _terminal_closeout_action, ] ) @@ -707,6 +696,11 @@ def terminal_settlement_actor(run_id: str) -> Mapping[str, Any]: def test_live_packet_builder_preserves_gate_and_vision_contracts(tmp_path: Path) -> None: sources, packets = build_actual_default_model_behavior_scenario_inputs(tmp_path) + for name, source in sources.items(): + if source.get("mode") == "should-run": + assert packets[name]["schema_version"] == "loopx_turn_envelope_v1" + assert_complete_turn_decision(packets[name]) + assert packets[name].get("selected_todo") == source.get("selected_todo") selected = packets["turn_selected_todo"] assert selected["selected_todo"]["todo_id"] == "todo_portfolio001" @@ -747,12 +741,7 @@ def test_live_packet_builder_preserves_gate_and_vision_contracts(tmp_path: Path) } replan = packets["turn_required_vision_replan"] assert replan["mode"] == "should-run" - assert replan["vision_continuation_audit"]["payload_compaction"] == { - "schema_version": "quota_cli_vision_continuation_compaction_v0", - "mode": "compact_hot_path", - "omitted_fields": [], - "full_detail_cold_path": "quota should-run --include-detail vision", - } + assert replan["vision_continuation_audit"] == sources["turn_required_vision_replan"]["vision_continuation_audit"] assert model_behavior_semantic_contract_from_packet( replan, arm="full_packet" ) == model_behavior_semantic_contract_from_packet( @@ -793,11 +782,8 @@ def test_live_packet_builder_preserves_gate_and_vision_contracts(tmp_path: Path) assert continuation["selected_todo"]["continuation_hint"] == ( "Next run the restart canary." ) - assert "active_state_next_action" not in continuation - assert "latest_run_recommended_action" not in continuation - assert continuation["next_action_projection_warning"]["shadowed_by"] == ( - "$.selected_todo" - ) + for field in ("active_state_next_action", "latest_run_recommended_action", "next_action_projection_warning"): + assert continuation[field] == continuation_source[field] scoped = packets["turn_scoped_gate_successor_replan"] scoped_signature = quota_action_signature_document(scoped) assert scoped_signature["user"]["action_required"] is True @@ -900,7 +886,7 @@ def test_live_packet_builder_preserves_gate_and_vision_contracts(tmp_path: Path) indent=2, ).encode("utf-8") ) - <= ACTUAL_DEFAULT_MODEL_BEHAVIOR_HOT_PATH_JSON_BUDGET + > ACTUAL_DEFAULT_MODEL_BEHAVIOR_HOT_PATH_JSON_BUDGET ) assert model_behavior_semantic_contract_from_packet( regression_source, @@ -914,13 +900,8 @@ def test_live_packet_builder_preserves_gate_and_vision_contracts(tmp_path: Path) "todo_c0ffee123456" ) assert regression["capability_gate"] == regression_source["capability_gate"] - assert set(regression["next_action_projection_warning"]["projection_refs"]) == { - "active_state_next_action", - "latest_run_recommended_action", - "agent_lane_next_action", - } - assert "title" not in regression["agent_lane_next_action"] - assert regression["goal_route_hint"]["other_agent_next_action_count"] == 24 + for field in ("next_action_projection_warning", "agent_lane_next_action", "goal_route_hint"): + assert regression.get(field) == regression_source.get(field) invariant_pairs = ( ( "turn_selected_todo", @@ -956,7 +937,7 @@ def test_live_packet_builder_preserves_gate_and_vision_contracts(tmp_path: Path) "utf-8" ) ) - <= ACTUAL_DEFAULT_MODEL_BEHAVIOR_HOT_PATH_JSON_BUDGET + > ACTUAL_DEFAULT_MODEL_BEHAVIOR_HOT_PATH_JSON_BUDGET ) clean_decision = _turn_decision({"packet": packets[clean_id]}) noisy_decision = _turn_decision({"packet": packets[noisy_id]}) @@ -1049,8 +1030,8 @@ def test_external_wait_preflight_rejects_shared_projection_drift( blocked = source["agent_todo_summary"]["resume_blocked_items"][0] blocked["resume_condition"]["baseline_generation"] = 3 sources["turn_external_wait_fallback"] = source - packets["turn_external_wait_fallback"] = compact_quota_should_run_cli_payload( - source + packets["turn_external_wait_fallback"] = compose_turn_decision( + source, composed_settlement=True ) calls = 0 @@ -1080,7 +1061,9 @@ def test_planning_horizon_preflight_rejects_missing_compact_projection( tmp_path: Path, ) -> None: sources, packets = _scenario_inputs(tmp_path) - packets["turn_planning_horizon_strategic_context"].pop("planning_horizon") + candidate = deepcopy(sources["turn_planning_horizon_strategic_context"]) + candidate.pop("planning_horizon") + packets["turn_planning_horizon_strategic_context"] = compose_turn_decision(candidate, composed_settlement=True) calls = 0 def turn_actor(request: Mapping[str, Any]) -> Mapping[str, Any]: @@ -1109,7 +1092,8 @@ def test_planning_horizon_preflight_rejects_a_broken_middle_relation( tmp_path: Path, ) -> None: sources, packets = _scenario_inputs(tmp_path) - horizon = packets["turn_planning_horizon_strategic_context"]["planning_horizon"] + candidate = deepcopy(sources["turn_planning_horizon_strategic_context"]) + horizon = candidate["planning_horizon"] horizon["relations"] = [ relation for relation in horizon["relations"] @@ -1118,6 +1102,7 @@ def test_planning_horizon_preflight_rejects_a_broken_middle_relation( and relation["relation"] == "successor" ) ] + packets["turn_planning_horizon_strategic_context"] = compose_turn_decision(candidate, composed_settlement=True) calls = 0 def turn_actor(request: Mapping[str, Any]) -> Mapping[str, Any]: @@ -1146,19 +1131,11 @@ def test_planning_horizon_fixed_facts_oracle_rejects_shared_relation_drift( tmp_path: Path, ) -> None: sources, packets = _scenario_inputs(tmp_path) - for packet in ( - sources["turn_planning_horizon_strategic_context"], - packets["turn_planning_horizon_strategic_context"], - ): - horizon = packet["planning_horizon"] - horizon["relations"] = [ - relation - for relation in horizon["relations"] - if not ( - relation["from_todo_id"] == "todo_runtime_admission" - and relation["relation"] == "successor" - ) - ] + source = sources["turn_planning_horizon_strategic_context"] + horizon = source["planning_horizon"] + horizon["relations"] = [relation for relation in horizon["relations"] + if not (relation["from_todo_id"] == "todo_runtime_admission" and relation["relation"] == "successor")] + packets["turn_planning_horizon_strategic_context"] = compose_turn_decision(source, composed_settlement=True) calls = 0 def turn_actor(request: Mapping[str, Any]) -> Mapping[str, Any]: @@ -1189,11 +1166,13 @@ def test_portfolio_rejects_candidate_context_loss_before_actor_call( tmp_path: Path, lane: str, mutation: str, ) -> None: sources, packets = _scenario_inputs(tmp_path) - candidates = packets["turn_quota_hot_path_compaction_regression"]["capability_gate"][lane] + candidate = deepcopy(sources["turn_quota_hot_path_compaction_regression"]) + candidates = candidate["capability_gate"][lane] if mutation == "drop": candidates.pop() else: candidates[0]["text"] = "Shortened candidate context." + packets["turn_quota_hot_path_compaction_regression"] = compose_turn_decision(candidate, composed_settlement=True) def unexpected_actor(*_args: Any, **_kwargs: Any) -> Mapping[str, Any]: pytest.fail("candidate context must be validated before any actor call") @@ -1214,9 +1193,11 @@ def test_portfolio_source_oracle_rejects_mutated_compact_user_action( tmp_path: Path, ) -> None: sources, packets = _scenario_inputs(tmp_path) - packets["turn_quota_hot_path_compaction_regression"]["interaction_contract"][ + candidate = deepcopy(sources["turn_quota_hot_path_compaction_regression"]) + candidate["interaction_contract"][ "user_channel" ]["action_required"] = True + packets["turn_quota_hot_path_compaction_regression"] = compose_turn_decision(candidate, composed_settlement=True) calls = 0 def turn_actor(request: Mapping[str, Any]) -> Mapping[str, Any]: @@ -1247,7 +1228,7 @@ def test_portfolio_rejects_mutated_blocking_gate_response_plan(tmp_path: Path) - source = deepcopy(sources["turn_human_gate"]) source["interaction_contract"]["response_plan"]["action_sequence"] = ["wait"] sources["turn_human_gate"] = source - packets["turn_human_gate"] = compact_quota_should_run_cli_payload(source) + packets["turn_human_gate"] = compose_turn_decision(source, composed_settlement=True) with pytest.raises( ValueError, @@ -1465,8 +1446,8 @@ def test_portfolio_preflight_rejects_wrong_same_agent_route(tmp_path: Path) -> N source = deepcopy(sources["turn_same_agent_continuation"]) source["selected_todo"]["claimed_by"] = "codex-wrong-peer" sources["turn_same_agent_continuation"] = source - packets["turn_same_agent_continuation"] = compact_quota_should_run_cli_payload( - source + packets["turn_same_agent_continuation"] = compose_turn_decision( + source, composed_settlement=True ) calls = 0 @@ -1528,7 +1509,7 @@ def turn_actor(request: Mapping[str, Any]) -> dict[str, Any]: assert all(request["arm"] == "full_packet" for request in requests) assert all(request["packet"]["mode"] == "should-run" for request in requests) assert all( - request["packet_schema_version"] == FULL_QUOTA_DECISION_PACKET_SCHEMA_VERSION + request["packet_schema_version"] == COMPLETE_TURN_DECISION_VERSION for request in requests ) required_requests = [ @@ -1703,7 +1684,7 @@ def test_portfolio_preflight_rejects_invalid_contrast_before_actor_spend( source["interaction_contract"]["user_channel"]["action_required"] = True source["action_required"] = True sources["turn_selected_todo"] = source - packets["turn_selected_todo"] = compact_quota_should_run_cli_payload(source) + packets["turn_selected_todo"] = compose_turn_decision(source, composed_settlement=True) calls = 0 def turn_actor(request: Mapping[str, Any]) -> Mapping[str, Any]: diff --git a/tests/control_plane/test_cli_output_differential.py b/tests/control_plane/test_cli_output_differential.py index 6942daece2..3bcd88222f 100644 --- a/tests/control_plane/test_cli_output_differential.py +++ b/tests/control_plane/test_cli_output_differential.py @@ -147,6 +147,85 @@ def _receipt(*rows: dict[str, object]) -> dict[str, object]: } +@pytest.mark.parametrize('damage', [None, 'missing', 'changed', 'material', 'unknown', 'later', 'row', 'growth']) +def test_complete_quota_migration_requires_original_controls_and_bounded_scope(tmp_path, damage): + import runpy + from pathlib import Path + from tests.control_plane import test_cli_output_budget as probe + + runner = runpy.run_path(str(Path(__file__).resolve().parents[2] / + 'examples/control_plane/cli-output-probe-runner.py')) + project, runtime, registry, state = probe._write_fixture(tmp_path, probe.SCENARIOS[0]) + probe.import_fixture_authority(registry, probe.GOAL_ID) + command = probe._surface_commands(project=project, runtime=runtime, registry_path=registry, + state_file=state, output_format='json')['quota_should_run'] + code, text = probe._invoke_cli(command) + assert code == 0, text + source = json.loads(text) + raw = {k: v for k, v in source.items() if k not in {'schema_version', 'contract_binding'}} + material = runner['_quota_goal_material'](source) + observe = runner['_quota_control_observation'] + before, after = observe(raw, goal_state=material), observe(source, goal_state=material) + assert before['controls_sha256'] == after['controls_sha256'] + assert set(before['field_sha256']) == { + 'goal_id', 'agent_id', 'decision', 'should_run', 'effective_action', 'selected_todo', + 'execution', 'boundary', 'required_reads', 'next_cli_actions', 'spend', 'work_lane_contract', + 'execution_obligation', 'execution_profile', 'task_scope', 'replan_action_packet', + 'notify', 'user_action_required', 'scheduler_action', + } + base = _row(row_id='surface/quota_should_run/small/json', surface_id='quota_should_run', + chars=1000, utf8_bytes=1000, compact_payload_chars=1000, lines=1, + semantic_json_keys=['interaction_contract'], markdown_anchor='# LoopX Quota Should Run', + projection_envelope_schema_versions=['loopx_projection_envelope_v0'], quota_controls=before) + candidate = {**copy.deepcopy(base), 'chars': 2500, 'utf8_bytes': 2500, 'compact_payload_chars': 2500, + 'output_contract_version': 'loopx_turn_envelope_v1', 'markdown_anchor': '# LoopX Turn Envelope', + 'quota_controls': after} + if damage == 'missing': + del candidate['quota_controls']['field_sha256']['boundary'] + elif damage in {'changed', 'material'}: + key = 'spend' if damage == 'changed' else 'required_reads' + candidate['quota_controls']['field_sha256'][key] = 'f' * 64 + elif damage == 'unknown': + candidate['quota_controls']['source_schema'] = 'future_contract' + elif damage == 'later': + base['quota_controls']['source_schema'] = 'loopx_turn_envelope_v1' + elif damage == 'row': + candidate['row_id'] = base['row_id'] = 'surface/status/small/json' + elif damage == 'growth': + candidate.update(chars=100_000, utf8_bytes=100_000, compact_payload_chars=100_000) + result = compare_cli_output_receipts(_receipt(base), _receipt(candidate)) + assert result['ok'] is (damage is None), result + + +def test_quota_goal_material_checks_exact_bytes_order_and_full_source(tmp_path): + import hashlib + import runpy + from pathlib import Path + + reader = runpy.run_path(str(Path(__file__).resolve().parents[2] / + 'examples/control_plane/cli-output-probe-runner.py'))['_quota_goal_material'] + path = tmp_path / 'goal.md' + path.write_text('Goal intent.\nStop before private publication.\n') + command = 'cat -- ' + str(path) + expected = {'command': command, 'ordering': 'before_work', + 'revision': 'sha256:' + hashlib.sha256(path.read_bytes()).hexdigest()} + pending = {'interaction_contract': {'agent_channel': {'required_reads': [ + {'source': 'goal_state', 'command': command, 'ordering': 'before_work'}]}}} + assert reader(pending) == expected + row = {'source': 'goal_state', 'command': command, 'ordering': 'before_work', + 'content': {'full_source': True, 'revision': expected['revision'], 'text': path.read_text()}} + inline = {'interaction_contract': {'agent_channel': {'work_context': {'sources': [row]}}}} + assert reader(inline) == expected + row['content']['text'] = 'Goal intent.' + with pytest.raises(AssertionError): + reader(inline) + row['content']['revision'] = 'sha256:' + hashlib.sha256(b'Goal intent.').hexdigest() + assert reader(inline) != expected + row['ordering'] = 'after_work' + with pytest.raises(AssertionError): + reader(inline) + + def test_base_ceiling_observation_is_bounded_and_contains_only_metrics(): import runpy from pathlib import Path @@ -588,6 +667,7 @@ def git(*args): git("init", "-b", "main") packet = repo / "packet.json" common_payload = { + "schema_version": "loopx_turn_envelope_v1", "contract_binding": {}, "interaction_contract": {}, "scheduler_hint": {}, "selected_todo": {}, "note": "x" * 4000, } @@ -1659,7 +1739,7 @@ def test_inline_context_transition_is_bounded_one_time_and_fixture_scoped(): assert not compare_cli_output_receipts(_receipt(candidate), _receipt(grown))["ok"] -def test_public_multi_subagent_probe_reaches_v4_producer(tmp_path): +def test_public_multi_subagent_probe_reaches_complete_source(tmp_path): import runpy from pathlib import Path from tests.control_plane import test_cli_output_budget as probe @@ -1674,9 +1754,9 @@ def test_public_multi_subagent_probe_reaches_v4_producer(tmp_path): with probe._stable_budget_fixture_root(tmp_path) as root: rows = runner["_multi_subagent_rows"](probe, semantics, root) assert len(rows) == 1 - assert rows[0]["action_signature_coverages"] == [ - "turn_envelope_action_dimensions_v4" - ] + assert rows[0]["quota_controls"]["source_schema"] == "loopx_turn_envelope_v1" + assert len(rows[0]["quota_controls"]["field_sha256"]) == 19 + assert rows[0]["action_signature_coverages"] == [] assert any("agent_context" in path for path in rows[0]["json_shape_paths"]) diff --git a/tests/control_plane/test_contract_health.py b/tests/control_plane/test_contract_health.py index 6cfe65c3de..533cef355a 100644 --- a/tests/control_plane/test_contract_health.py +++ b/tests/control_plane/test_contract_health.py @@ -7,7 +7,6 @@ from canonical_authority_fixture import initialize_canonical_source_fixture from loopx.cli_runtime import report_json_text -from loopx.paths import display_report_text from loopx.contract import check_contract, display_report_value from loopx.control_plane.goals.contract_health import ( contract_error_diagnostic, diff --git a/tests/control_plane/test_heartbeat_envelope_transport.py b/tests/control_plane/test_heartbeat_envelope_transport.py index f7d1bc3d50..7b0c834860 100644 --- a/tests/control_plane/test_heartbeat_envelope_transport.py +++ b/tests/control_plane/test_heartbeat_envelope_transport.py @@ -67,7 +67,7 @@ def test_shared_native_root_keeps_dynamic_turn_binding_and_bootstrap_options(tmp assert binding is not None and binding["context_delivery"] == "on" and binding["turn_envelope"] is True -def test_capture_preserves_full_dispatcher_and_envelope_needs_explicit_opt_in(tmp_path): +def test_capture_preserves_full_dispatcher_with_complete_source_alias(tmp_path): args = dict(goal_id=GOAL_ID, agent_id=AGENT_ID, runtime_profile="generic_cli", turn_instance_id=TURN_ID, thin=True) assert build_heartbeat_prompt(**args) == build_heartbeat_prompt(**args, decision_output_root=None) @@ -82,12 +82,8 @@ def test_capture_preserves_full_dispatcher_and_envelope_needs_explicit_opt_in(tm payload = build_heartbeat_prompt(**args, decision_output_root=tmp_path, turn_envelope=True) assert payload['interface_budget']['within_budget'], payload['interface_budget'] assert '--turn-envelope --decision-output-root' in payload['quota_guard_command'] - assert 'writeback.settlement_plan.ordered_steps' in payload['task_body'] - assert 'When present, read inline `agent_context` before planning.' in payload['task_body'] - assert 'an `agent_context.detail_ref`' in payload['task_body'] - assert 'using inline ACK argv' in payload['task_body'] - assert 'needed missing/truncated/referenced command' in payload['task_body'] - assert 'failure argv only after host update failure' in payload['task_body'] + assert 'interaction_contract.cli_channel.settlement_plan.ordered_steps' in payload['task_body'] + assert payload['task_body'].replace(' --turn-envelope', '') == captured['task_body'] assert '--decision-output-root' in payload['thin_prompt_command'] assert '--turn-envelope' in payload['thin_prompt_command'] # The captured allowance must neither leak into ordinary thin nor disable @@ -99,9 +95,9 @@ def test_capture_preserves_full_dispatcher_and_envelope_needs_explicit_opt_in(tm assert captured_only['interface_budget']['max_chars'] == 5_100 oversized = build_heartbeat_prompt( **no_memory, decision_output_root=tmp_path, turn_envelope=True, - agent_scopes=[letter * 320 for letter in 'stuv'], + agent_scopes=[letter * 320 for letter in 'stuvwx'], ) - assert oversized['interface_budget']['max_chars'] == 5_500 + assert oversized['interface_budget']['max_chars'] == 5_100 assert oversized['interface_budget']['within_budget'] is False for overrides in (dict(turn_instance_id=None), dict(thin=False, full=True), dict(runtime_profile='codex_app_ssh_goal')): @@ -128,16 +124,12 @@ def test_captured_scheduler_ack_is_inline_and_failure_detail_stays_on_original_s assert code == 0, envelope original = (capture / 'decision.json').read_bytes() source = json.loads(original)['scheduler_hint']['app_automation'] - projected = envelope['scheduler']['app_automation'] - assert projected['ack_cli_args'] == source['ack_hint']['cli_args'] - assert 'ack_cli_args_detail_ref' not in projected - assert projected['failure_cli_args_detail_ref']['detail_ref'] == ( - 'full_decision.scheduler_hint.app_automation.failure_hint.cli_args' - ) + assert envelope['schema_version'] == 'loopx_turn_envelope_v1' + assert envelope['scheduler_hint']['app_automation'] == source before = _heartbeat_receipt_count(runtime, TURN_ID) - read = subprocess.run(shlex.split(envelope['detail_ref']['full_decision']), - capture_output=True, check=True).stdout - assert read == original + from tests.control_plane.cli_output_fixture import read_pinned_cli_body + read, _, _ = read_pinned_cli_body(envelope['detail_ref']['full_decision']) + assert read.encode() == original assert _heartbeat_receipt_count(runtime, TURN_ID) == before @@ -176,13 +168,11 @@ def test_bound_captured_prompt_fits_budget_without_reward_memory( assert '--reward-memory-reflection-json' not in body assert str(runtime) in body and str(capture) in body assert payload['turn_instance_id'] == TURN_ID - assert payload['interface_budget']['max_chars'] == 5_500 + assert payload['interface_budget']['max_chars'] == 5_100 assert payload['interface_budget']['within_budget'], payload['interface_budget'] assert len(result.stdout) <= 5_400 # Shipped Agent JSON, not generator metadata. - assert 'using inline ACK argv' in body - assert 'needed missing/truncated/referenced command' in body - assert 'failure argv only after host update failure' in body - assert 'same-invocation observation, not fresh admission' in body + assert 'interaction_contract.cli_channel.settlement_plan.ordered_steps' in body + assert 'work_context' in body and 'required_reads' in body assert 'goal_acceptance' in body # Retain the complete outcome guidance too. @@ -304,14 +294,13 @@ def complete_page(value): captures = list(root.glob('*/decision.json')) assert len(captures) == 1 full = json.loads(captures[0].read_text()) + assert first == full and first['schema_version'] == 'loopx_turn_envelope_v1' if enabled: - assert first['action_signature']['matches'] detail = shlex.split(first['detail_ref']['full_decision']) - assert detail[:2] == ['cat', '--'] # Depends on the saved-detail reader contract. receipts = _heartbeat_receipt_count(runtime, TURN_ID) readback = subprocess.run(detail, env=env, cwd=project, capture_output=True, text=True, check=True) - assert json.loads(readback.stdout) == full + assert complete_page(json.loads(readback.stdout)) == full assert _heartbeat_receipt_count(runtime, TURN_ID) == receipts else: assert first['interaction_contract'] == full['interaction_contract'] @@ -332,12 +321,7 @@ def complete_page(value): assert len(paths) == 2 assert json.loads(captures[0].read_text()) == full selected_full = json.loads(next(p for p in paths if p != captures[0]).read_text()) - if enabled: - assert selected['action_signature']['matches'] - assert selected['writeback']['settlement_plan'] == selected_full['interaction_contract']['cli_channel']['settlement_plan'] - else: - assert selected['interaction_contract'] == selected_full['interaction_contract'] - assert 'action_signature' not in selected + assert selected == selected_full and selected['schema_version'] == 'loopx_turn_envelope_v1' else: selected_full = selected identity = selected_full['heartbeat_receipt']['settlement_identity'] @@ -463,7 +447,9 @@ def test_ssh_goal_capture_keeps_native_begin_turn_and_off_boundary(tmp_path, tur assert enabled["interface_budget"]["within_budget"] if turn_envelope: assert "--turn-envelope" in guard - assert "detail_ref.full_decision" in enabled["task_body"] + ordinary = build_heartbeat_prompt(**args, context_delivery="on", decision_output_root=tmp_path, + codex_context_root=str(tmp_path)) + assert enabled["task_body"].replace(" --turn-envelope", "") == ordinary["task_body"] @pytest.mark.parametrize("turn_envelope", [False, True]) @@ -500,7 +486,9 @@ def test_ssh_goal_capture_fits_host_with_full_command_paths(tmp_path, turn_envel assert "--begin-turn" in command and "--heartbeat-turn-receipt" not in command assert "--context-delivery" in command and "LOOPX_TURN=" not in body if turn_envelope: - assert "detail_ref.full_decision" in body + source = build_heartbeat_prompt(**args, context_delivery="on", decision_output_root=captures, + codex_context_root=str(context)) + assert body.replace(" --turn-envelope", "") == source["task_body"] with pytest.raises(ValueError, match="4000-character"): build_heartbeat_prompt(**args, context_delivery="on", decision_output_root=captures, codex_context_root=str(context), turn_envelope=turn_envelope, agent_scopes=[c * 320 for c in "stu"]) diff --git a/tests/control_plane/test_quota_decision_capture.py b/tests/control_plane/test_quota_decision_capture.py index 471384ce5b..88a36aa8c1 100644 --- a/tests/control_plane/test_quota_decision_capture.py +++ b/tests/control_plane/test_quota_decision_capture.py @@ -10,7 +10,7 @@ import pytest from loopx.cli_commands.quota_capture import capture_decision, prepare_decision_capture -from loopx.control_plane.quota.error_codes import QuotaCommandValidationError +from loopx.control_plane.quota.error_codes import QuotaCommandValidationError, QuotaDecisionTransportError from tests.control_plane.canonical_authority_fixture import ( initialize_canonical_source_fixture, read_fixture_todos, ) @@ -47,6 +47,25 @@ def test_disabled_capture_does_not_touch_disk(tmp_path): assert list(tmp_path.iterdir()) == [] +def test_reader_publication_failure_keeps_the_committed_capture(tmp_path, monkeypatch): + from loopx.cli_commands import quota_capture + + payload = {'ok': True, 'heartbeat_receipt': {'turn_instance_id': TURN_ID}, + 'detail_ref': {'full_decision': 'original reader'}} + observed = [] + + def fail_reader(*args, **kwargs): + raise OSError('fixture reader publication failure') + + monkeypatch.setattr(quota_capture, 'write_context_read_reference', fail_reader) + with pytest.raises(QuotaDecisionTransportError, match='already exist'): + capture_decision(tmp_path, payload, record_capture=lambda source, digest: observed.append((source, digest))) + raw = (tmp_path / 'decision.json').read_bytes() + assert json.loads(raw) == payload + assert observed == [(payload, sha256(raw).hexdigest())] + assert not (tmp_path / 'decision.reader.json').exists() + + @pytest.mark.parametrize('overrides', [ {'context_delivery': 'off'}, {'format': 'markdown'}, {'quota_command': 'plan'}, {'decision_output_dir': None}, {'decision_handoff_socket': '/unused/socket'}, @@ -200,8 +219,8 @@ def test_real_cli_fallback_reference_keeps_capture_and_turn_effects(tmp_path, mo fallback = full['blocked_priority_fallback'] assert full['heartbeat_recommendation']['blocked_priority_fallback'] == fallback assert ordinary['blocked_priority_fallback'] == fallback - assert ordinary['heartbeat_recommendation']['blocked_priority_fallback_ref'] == '$.blocked_priority_fallback' - assert 'blocked_priority_fallback' not in ordinary['heartbeat_recommendation'] + assert ordinary['schema_version'] == 'loopx_turn_envelope_v1' + assert ordinary == full # Off delivers the complete captured source. assert ordinary['heartbeat_receipt'] == full['heartbeat_receipt'] assert ordinary['interaction_contract']['cli_channel']['settlement_plan'] == full[ 'interaction_contract']['cli_channel']['settlement_plan'] @@ -216,9 +235,14 @@ def test_real_cli_fallback_reference_keeps_capture_and_turn_effects(tmp_path, mo @pytest.mark.parametrize('provider', ['file', 'sqlite']) -def test_real_cli_boundary_clauses_reach_shared_host_without_loss(tmp_path, monkeypatch, provider): +@pytest.mark.parametrize('alias', [None, '--turn-envelope', '--complete-turn']) +def test_real_cli_boundary_clauses_reach_shared_host_without_loss(tmp_path, monkeypatch, provider, alias): from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection from loopx.control_plane.turn_driver.host_candidate import extract_turn_authority, render_prompt + from loopx.control_plane.turn_driver.driver import build_loopx_turn_plan + from loopx.control_plane.turn_driver.executor import build_loopx_turn_host_request + from loopx.control_plane.turn_driver.codex_cli import _prompt + from tests.control_plane.host_process_fixture import assert_host_task_context from tests.control_plane.canonical_authority_fixture import ( initialize_canonical_authority, isolate_sqlite_runtime, ) @@ -246,34 +270,37 @@ def test_real_cli_boundary_clauses_reach_shared_host_without_loss(tmp_path, monk '--todo-id', TODO_ID, '--turn-instance-id', TURN_ID, '--codex-app', '--available-capability', 'shell', '--available-capability', 'filesystem_read'] capture = tmp_path / 'boundary-decision' - code, envelope = _run_cli(registry, runtime, *args, '--turn-envelope', '--decision-output-dir', str(capture)) + code, envelope = _run_cli(registry, runtime, *args, *([alias] if alias else []), + '--decision-output-dir', str(capture)) assert code == 0, envelope saved = capture / 'decision.json' original_bytes = saved.read_bytes() full = json.loads(original_bytes) assert full['goal_boundary']['write_scope'] == scopes assert full['goal_boundary']['guards'] == guards - for field in ('write_scope', 'guards', 'requires_parent_approval'): - assert envelope['boundary'][field] == full['goal_boundary'][field], field - authority = extract_turn_authority({'turn_envelope': envelope}) - assert authority['write_scope'] == scopes - assert authority['boundary']['guards'] == guards - assert authority['boundary']['requires_parent_approval'] == ['publish', 'production-action'] - assert 'write_scope' not in authority['boundary'] # Existing aliases carry these facts once. + assert envelope == full and full['schema_version'] == 'loopx_turn_envelope_v1' + plan = build_loopx_turn_plan(full, host='generic-cli', execution_mode='isolated-headless', + session_scope='todo', turn_instance_id=TURN_ID) + request = build_loopx_turn_host_request(plan) + authority = extract_turn_authority(request) prompt = render_prompt(authority) - transported, _ = json.JSONDecoder().raw_decode(prompt.split('Turn authority JSON:\n', 1)[1]) - assert transported == authority - altered = json.loads(json.dumps(envelope)) - altered['boundary']['guards'][-1] = 'Continue without the final restriction.' - with pytest.raises(ValueError, match='action signature'): - extract_turn_authority({'turn_envelope': altered}) + transported, _ = json.JSONDecoder().raw_decode(prompt.split('Turn request:\n', 1)[1]) + assert json.loads(_prompt(request).split('Turn request:\n', 1)[1]) == transported + task = assert_host_task_context(transported, full) + assert task['goal_boundary']['write_scope'] == scopes + assert task['goal_boundary']['guards'] == guards + assert task['goal_boundary']['requires_parent_approval'] == ['publish', 'production-action'] + altered = json.loads(json.dumps(request)) + altered['work_contract']['goal_boundary']['guards'][-1] = 'Continue without the final restriction.' + with pytest.raises(ValueError): + extract_turn_authority(altered) before = _heartbeat_receipt_count(runtime, TURN_ID) code, replay = _run_cli(registry, runtime, *args) assert code == 0, replay assert _heartbeat_receipt_count(runtime, TURN_ID) == before assert _spend_run_count(runtime) == 0 assert saved.read_bytes() == original_bytes - assert envelope['action']['delivery_allowed'] == full['interaction_contract']['agent_channel']['delivery_allowed'] + assert task['normal_delivery_allowed'] == full['interaction_contract']['agent_channel']['delivery_allowed'] @pytest.mark.parametrize('provider', ['file', 'sqlite']) @@ -306,25 +333,23 @@ def test_real_guard_saved_before_envelope_and_read_without_reexecution(tmp_path, code, envelope = _run_cli(registry, runtime, *args, '--turn-envelope', '--decision-output-dir', str(capture)) assert code == 0, envelope - assert envelope['schema_version'] == 'loopx_turn_envelope_v0' + assert envelope['schema_version'] == 'loopx_turn_envelope_v1' saved = capture / 'decision.json' full = json.loads(saved.read_text()) - app = envelope['scheduler']['app_automation'] - assert 'ack_cli_args' not in app - ref = app['ack_cli_args_detail_ref'] - assert ref['detail_ref'] == 'full_decision.scheduler_hint.app_automation.ack_hint.cli_args' - assert 'request' not in ref - assert shlex.split(envelope['detail_ref']['full_decision']) == ['cat', '--', str(saved)] + assert envelope == full + ack = full['scheduler_hint']['app_automation']['ack_hint']['cli_args'] + assert ack[ack.index('--registry') + 1] == str(registry) + assert ack[ack.index('--turn-instance-id') + 1] == TURN_ID + command = envelope['detail_ref']['full_decision'] + assert shlex.split(command)[-1] != str(saved) # Uses the original digest-bound sidecar. + reader = json.loads(saved.with_suffix('.reader.json').read_text()) + assert reader['path'] == str(saved) and reader['sha256'] == sha256(saved.read_bytes()).hexdigest() assert full['ok'] is True identity = full['interaction_contract']['cli_channel']['settlement_plan']['identity'] assert identity['turn_instance_id'] == TURN_ID assert identity['todo_id'] == TODO_ID assert 'interaction_contract' in full - observed = envelope['detail_ref']['captured_decision'] - assert (observed['goal_id'], observed['agent_id'], observed['turn_instance_id']) == (GOAL_ID, AGENT_ID, TURN_ID) - assert observed['path'] == str(saved) - from loopx.control_plane.quota.turn_envelope import build_turn_envelope - assert envelope['action_signature'] == build_turn_envelope(full)['action_signature'] + assert (full['goal_id'], full['agent_identity']['agent_id']) == (GOAL_ID, AGENT_ID) before = _heartbeat_receipt_count(runtime, TURN_ID) assert before >= 1 # Deliberately unusable displayed JSON does not require a new CLI evaluation. @@ -333,20 +358,31 @@ def test_real_guard_saved_before_envelope_and_read_without_reexecution(tmp_path, before_files = {p: p.read_bytes() for p in runtime.rglob('*') if p.is_file()} # Execute the actual advertised POSIX read command, including hostile path characters. if os.name != 'nt': - readback = subprocess.run(envelope['detail_ref']['full_decision'], shell=True, - cwd=tmp_path, capture_output=True, text=True, check=True) - assert json.loads(readback.stdout) == full - value = json.loads(readback.stdout) - for key in ref['detail_ref'].split('.')[1:]: - value = value[key] - assert value == full['scheduler_hint']['app_automation']['ack_hint']['cli_args'] - assert value[value.index('--registry') + 1] == str(registry) - assert value[value.index('--turn-instance-id') + 1] == TURN_ID + content, offset = [], 0 + while command: + readback = subprocess.run(command, shell=True, cwd=tmp_path, + capture_output=True, text=True, check=True) + page = json.loads(readback.stdout) + assert page['ok'] and page['offset'] == offset + content.append(page['content']) + offset = page['next_offset'] + command = page.get('next_command') + assert json.loads(''.join(content)) == full else: assert json.loads(saved.read_text()) == full assert not (tmp_path / 'INJECTED').exists() assert {p: p.read_bytes() for p in runtime.rglob('*') if p.is_file()} == before_files assert _heartbeat_receipt_count(runtime, TURN_ID) == before + original_bytes = saved.read_bytes() + if os.name != 'nt': + try: + saved.write_bytes(original_bytes + b'\n') + failed = subprocess.run(envelope['detail_ref']['full_decision'], shell=True, + cwd=tmp_path, capture_output=True, text=True) + assert failed.returncode != 0 and json.loads(failed.stdout)['ok'] is False + assert _heartbeat_receipt_count(runtime, TURN_ID) == before + finally: + saved.write_bytes(original_bytes) # Reject accidental reuse before any new guard evaluation. code, rejected = _run_cli(registry, runtime, *args, '--decision-output-dir', str(capture)) assert code == 1 and rejected['ok'] is False @@ -359,7 +395,7 @@ def test_real_guard_saved_before_envelope_and_read_without_reexecution(tmp_path, assert json.loads((second / 'decision.json').read_text())['heartbeat_receipt']['status'] == 'replayed' assert json.loads(saved.read_text()) == full - assert shlex.split(fresh['detail_ref']['full_decision']) == ['cat', '--', str(second / 'decision.json')] + assert fresh['detail_ref']['full_decision'] != envelope['detail_ref']['full_decision'] # Missing old evidence fails locally; it never substitutes a new guard observation. saved.unlink() before = _heartbeat_receipt_count(runtime, TURN_ID) @@ -747,7 +783,8 @@ def typed_host(observed): 'execution_authority_granted': False, } assert code == 0 and selected['ok'] is True, selected - assert selected['schema_version'] == 'loopx_turn_envelope_v0' + assert selected['schema_version'] == 'loopx_turn_envelope_v1' + assert selected == observed['decision'] assert len(saved) == 1 and json.loads(saved[0].read_text()) == observed['decision'] @@ -855,3 +892,20 @@ def test_unexpected_collection_failure_names_typed_runtime_cause_only(): error=ValueError('/private/runtime/secret.json')) assert private['reason'] == 'quota collection failed' and private['error_class'] == 'ValueError' assert 'secret' not in json.dumps(private) and 'diagnostic_code' not in private + + +@pytest.mark.parametrize('source', [ + {'schema_version': 'loopx_turn_envelope_v99'}, + {'contract_binding': {}}, + {'schema_version': 'loopx_turn_envelope_v0', 'contract_binding': {}}, +]) +def test_unknown_source_cannot_enter_optional_delivery_fallback(tmp_path, monkeypatch, source): + from loopx.cli_commands import quota_capture + + def unexpected_io(*args, **kwargs): + pytest.fail('Unknown source must be refused before optional delivery IO') + + monkeypatch.setattr(quota_capture, 'progressive_context_capture_view', unexpected_io) + with pytest.raises(QuotaDecisionTransportError, match='Unsupported saved quota decision'): + quota_capture.progressive_context_or_current(source, argparse.Namespace(), + runtime_root=tmp_path, directory=None, reader_argv=None) diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index b6097877a9..bc08f87f36 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -341,6 +341,20 @@ def _heartbeat_receipt_count(runtime: Path, turn_instance_id: str) -> int: ) +def _assert_composed_spend_source(cli: dict, runtime: Path, turn: str, source: str) -> None: + from loopx.control_plane.quota.heartbeat_receipt import find_heartbeat_receipt + + plan = cli['settlement_plan'] + assert plan['schema_version'] == 'quota_settlement_plan_v2' + spend = next(step for step in plan['ordered_steps'] if step['kind'] == 'quota_spend') + assert spend['owner'] == 'runtime' and 'command_template' not in spend + writeback = next(step for step in plan['ordered_steps'] if step['kind'] == 'durable_writeback') + assert '--settle-turn --settlement-receipt' in writeback['command_template'] + assert writeback['command_template'] in cli['next_cli_actions'] + receipt = find_heartbeat_receipt(runtime, goal_id=GOAL_ID, agent_id=AGENT_ID, turn_instance_id=turn) + assert receipt['details']['quota_spend_source'] == source + + def _configure_read_only_todo(project: Path) -> Path: state_path = project / f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md" state_text = state_path.read_text(encoding="utf-8") @@ -4313,10 +4327,7 @@ def test_guided_start_begins_one_turn_and_executes_returned_selection( assert settlement_plan["identity"] == receipt_identity assert f"--turn-instance-id {turn_instance_id}" in json.dumps(settlement_plan) expected_source = "heartbeat" if host_surface == "codex-app" else "visible-goal" - assert any( - f"--source {expected_source}" in action - for action in cli_channel["next_cli_actions"] - ) + _assert_composed_spend_source(cli_channel, runtime, turn_instance_id, expected_source) assert _heartbeat_receipt_count(runtime, turn_instance_id) == 2 @@ -4373,9 +4384,7 @@ def test_visible_goal_continuation_begins_turn_and_executes_returned_selection( assert settlement_plan["identity"] == selected["heartbeat_receipt"][ "settlement_identity" ] - assert any( - "--source visible-goal" in action for action in cli_channel["next_cli_actions"] - ) + _assert_composed_spend_source(cli_channel, runtime, turn_instance_id, 'visible-goal') assert _heartbeat_receipt_count(runtime, turn_instance_id) == 2 @@ -4485,11 +4494,8 @@ def test_single_claimed_todo_guided_start_keeps_direct_delivery_semantics( ] assert settlement_plan["identity"] == identity expected_source = "heartbeat" if host_surface == "codex-app" else "visible-goal" - assert expected_source in next( - step["command_template"] - for step in settlement_plan["ordered_steps"] - if step["kind"] == "quota_spend" - ) + _assert_composed_spend_source(guard['interaction_contract']['cli_channel'], _runtime, + identity['turn_instance_id'], expected_source) @pytest.mark.parametrize("profile", ["codex_app_heartbeat", "codex_app_ssh_goal"]) @@ -4586,11 +4592,8 @@ def test_visible_goal_refresh_and_spend_preserve_selected_todo_causality( ) plan = guard["interaction_contract"]["cli_channel"]["settlement_plan"] assert plan["identity"] == identity - assert "--source visible-goal" in next( - step["command_template"] - for step in plan["ordered_steps"] - if step["kind"] == "quota_spend" - ) + _assert_composed_spend_source(guard['interaction_contract']['cli_channel'], runtime, + turn_instance_id, 'visible-goal') refresh_rc, refresh = _run_cli( registry_path, @@ -4695,6 +4698,7 @@ def test_host_runtime_profile_selects_spend_source_through_real_settlement( assert spend_rc == 0, spend assert spend["turn_instance_id"] == turn_instance_id assert spend["settlement_identity"] == plan["identity"] + assert spend['source'] == expected_source assert _spend_run_count(runtime) == 1 @@ -7293,12 +7297,13 @@ def test_unbound_visible_goal_todoless_replan_reenters_through_guided_turn( assert identity["replan_obligation_id"] == obligation_id assert identity["turn_instance_id"].startswith("guided-start:") cli_channel = bound["interaction_contract"]["cli_channel"] - assert cli_channel["settlement_identity"] == identity - assert cli_channel["settlement_read_ref"] == "$.replan_action_packet.writeback" - assert "settlement_plan" not in cli_channel - # Native admission defers the plan; consume its exact captured reader - # without another guard or a second guided-start Turn. - reader_argv = shlex.split(bound["replan_action_packet"]["writeback"]) + assert cli_channel["settlement_plan"]["identity"] == identity + assert 'settlement_read_ref' not in cli_channel + # The current source carries the whole plan. The public saved-source reader + # must return that same original plan without another admission or mutation. + reader_argv = [*bound['replan_read_argv'], '--format', 'json', 'quota', 'replan-view', + '--decision-file', bound['replan_read_path'], + '--source-hash', bound['contract_binding']['content_hash'], '--replan-stage', 'writeback'] source_paths = ( registry_path, project / f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md", @@ -7318,6 +7323,7 @@ def test_unbound_visible_goal_todoless_replan_reenters_through_guided_turn( writeback = json.loads(reader.stdout) assert writeback["obligation_id"] == obligation_id plan = writeback["writeback"]["settlement_plan"] + assert plan == cli_channel['settlement_plan'] assert plan["identity"] == identity assert [step["kind"] for step in plan["ordered_steps"]] == [ "validation", "durable_writeback", "quota_spend", diff --git a/tests/control_plane/test_refresh_settle_turn.py b/tests/control_plane/test_refresh_settle_turn.py index 4941264756..e98a0224fb 100644 --- a/tests/control_plane/test_refresh_settle_turn.py +++ b/tests/control_plane/test_refresh_settle_turn.py @@ -87,34 +87,28 @@ def test_ready_native_guard_publishes_a_runnable_settlement_plan(tmp_path, monke validate, writeback, spend, terminal = plan["ordered_steps"] assert validate["command_condition"] == "todo_deliverable_complete" assert terminal["conditional"] is True and terminal["owner"] == "agent" - if not off or complete: - assert plan["schema_version"] == "quota_settlement_plan_v2" - assert "--settle-turn --settlement-receipt" in writeback["semantic_closeout_command_template"] - assert spend["owner"] == "runtime" and "command_template" not in spend - assert cli["next_cli_actions"] == [writeback["command_template"]] - if not off: - _, recovery = read_context_read_reference(guard["recovery"]["reference_file"]) - projected = json.loads(Path(recovery["path"]).read_bytes()) - assert projected["interaction_contract"]["cli_channel"]["settlement_plan"] == plan - if case in {"combined", "after_claim"}: - from tests.control_plane.codex_checkpoint_fixture import selected_context_values - - command, pages = guard["first_read_command"], [] - while command: - words = shlex.split(command) - rc, page = _run_cli(registry, runtime, *words[words.index("quota"):], cwd=project) - assert rc == 0 and page["ok"] and page["offset"] == sum(len(body.encode()) for body in pages) - pages.append(page["content"]) - command = page.get("next_command") - values = selected_context_values("".join(pages)) - cli_path = "/interaction_contract/cli_channel" - assert cli_path + "/next_cli_actions" not in values - assert values[cli_path + "/settlement_plan/ordered_steps/1/command_template"] == writeback["command_template"] - else: - assert plan["schema_version"] == "quota_settlement_plan_v1" - assert "--settle-turn" not in writeback["semantic_closeout_command_template"] - assert cli["next_cli_actions"] == [writeback["command_template"], spend["command_template"]] - assert spend["owner"] == "agent" + assert plan["schema_version"] == "quota_settlement_plan_v2" + assert "--settle-turn --settlement-receipt" in writeback["semantic_closeout_command_template"] + assert spend["owner"] == "runtime" and "command_template" not in spend + assert cli["next_cli_actions"] == [writeback["command_template"]] + if not off: + _, recovery = read_context_read_reference(guard["recovery"]["reference_file"]) + projected = json.loads(Path(recovery["path"]).read_bytes()) + assert projected["interaction_contract"]["cli_channel"]["settlement_plan"] == plan + if case in {"combined", "after_claim"}: + from tests.control_plane.codex_checkpoint_fixture import selected_context_values + + command, pages = guard["first_read_command"], [] + while command: + words = shlex.split(command) + rc, page = _run_cli(registry, runtime, *words[words.index("quota"):], cwd=project) + assert rc == 0 and page["ok"] and page["offset"] == sum(len(body.encode()) for body in pages) + pages.append(page["content"]) + command = page.get("next_command") + values = selected_context_values("".join(pages)) + cli_path = "/interaction_contract/cli_channel" + assert cli_path + "/next_cli_actions" not in values + assert values[cli_path + "/settlement_plan/ordered_steps/1/command_template"] == writeback["command_template"] vision = tmp_path / "vision.json" vision.write_text(json.dumps({ @@ -154,10 +148,6 @@ def fail_child(argv, **kwargs): else: rc, result = _run_generated_cli(command, registry_path=registry, cwd=project) assert rc == 0 and result["ok"] and result["settlement_identity"] == identity, result - if off and not complete: - assert result["settlement_owed"]["kind"] == "quota_spend" and _spend_run_count(runtime) == 0 - rc, result = _run_generated_cli(spend["command_template"], registry_path=registry, cwd=project) - assert rc == 0 and result["ok"], result assert result["settlement_progress"]["state"] == "settled" assert result["settlement_identity"] == identity # Claim re-entry appends the readiness upgrade under the original Turn. @@ -478,26 +468,26 @@ def test_complete_turn_rejects_other_routes_before_authority_io(tmp_path, comman @pytest.mark.parametrize("provider", ["file", "sqlite"]) -def test_explicit_complete_soft_claim_reuses_the_original_legacy_receipt(tmp_path, provider): +def test_compatibility_alias_soft_claim_reuses_the_original_default_receipt(tmp_path, provider): project, runtime, registry = _write_fixture(tmp_path) _initialize_fixture_authority(project, runtime, provider=provider, handoff_mode="soft_claim") command = ["quota", "should-run", "--runtime-profile", "generic_cli", "--context-delivery", "off", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID, "--turn-instance-id", TURN_ID] - rc, legacy = _run_cli(registry, runtime, *command, cwd=project) - assert rc == 0 and legacy.get("schema_version") is None - original_cli = legacy["interaction_contract"]["cli_channel"] - assert original_cli["settlement_plan"]["schema_version"] == "quota_settlement_plan_v1" + rc, original = _run_cli(registry, runtime, *command, cwd=project) + assert rc == 0 and original.get("schema_version") == "loopx_turn_envelope_v1" + original_cli = original["interaction_contract"]["cli_channel"] + assert original_cli["settlement_plan"]["schema_version"] == "quota_settlement_plan_v2" rc, complete = _run_cli(registry, runtime, *command, "--complete-turn", cwd=project) assert rc == 0 and complete["schema_version"] == "loopx_turn_envelope_v1", complete cli = complete["interaction_contract"]["cli_channel"] assert "execution_preparation" not in cli # A soft claim never becomes a fabricated ready lease. assert cli["settlement_plan"]["schema_version"] == "quota_settlement_plan_v2" - assert cli["settlement_plan"]["identity"] == legacy["heartbeat_receipt"]["settlement_identity"] - assert complete["goal_boundary"] == legacy["goal_boundary"] - assert complete["normal_delivery_allowed"] == legacy["normal_delivery_allowed"] + assert cli["settlement_plan"]["identity"] == original["heartbeat_receipt"]["settlement_identity"] + assert complete["goal_boundary"] == original["goal_boundary"] + assert complete["normal_delivery_allowed"] == original["normal_delivery_allowed"] assert len(cli["next_cli_actions"]) == 1 assert _heartbeat_receipt_count(runtime, TURN_ID) == 1 and _spend_run_count(runtime) == 0 - assert original_cli["settlement_plan"]["schema_version"] == "quota_settlement_plan_v1" + assert original_cli["settlement_plan"]["schema_version"] == "quota_settlement_plan_v2" def _read_selected_result(command): @@ -811,7 +801,8 @@ def test_same_turn_progress_or_completion_and_replay_without_extra_guard( command = command.replace(key, value) words = shlex.split(command) assert words[words.index("--delivery-boundary") + 1] == "semantic_closeout" - command += " " + shlex.join(["--settle-turn", "--no-global-sync", "--suppress-external-sinks", + assert '--settle-turn' in words and '--settlement-receipt' in words + command += " " + shlex.join(["--no-global-sync", "--suppress-external-sinks", "--delivery-workspace-path", str(project)]) # A hostile ambient executable must not select another checkout/accounting owner. trap = tmp_path / "bin" @@ -830,8 +821,8 @@ def test_same_turn_progress_or_completion_and_replay_without_extra_guard( for row in receipts) assert _spend_run_count(runtime) == 1 assert result.get("idempotent_replay", False) is replay - ordinary_args = shlex.split(command) - ordinary_args.remove("--settle-turn") + ordinary_args = [word for word in shlex.split(command) + if word not in {'--settle-turn', '--settlement-receipt'}] rc, ordinary = _run_generated_cli(shlex.join(ordinary_args), registry_path=registry) assert rc == 0 and ordinary["settlement_progress"]["state"] == "settled", ordinary assert [row["step_kind"] for row in ordinary["settlement_result"]["receipts"]] == [ diff --git a/tests/control_plane/test_replan_host_context_projection.py b/tests/control_plane/test_replan_host_context_projection.py index 5ba9f83d7f..5f77c2ade6 100644 --- a/tests/control_plane/test_replan_host_context_projection.py +++ b/tests/control_plane/test_replan_host_context_projection.py @@ -223,19 +223,32 @@ 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 {key: value for key, value in action.items() if key != "planning_guidance"} == { + assert { + key: value for key, value in action.items() + if key not in {"planning_guidance", "writeback_contract"} + } == { "schema_version": "replan_action_packet_v0", "decision": "replan_required", "obligation_id": obligation["obligation_id"], "uncovered_frontier": context["uncovered_frontier"], "required_outcome": "semantic_delta", - "writeback_contract": {}, "allowed_terminal": [ "exploration_exhausted", "blocked", "no_followup", ], } + no_followup = action["writeback_contract"]["no_followup_requirements"] + assert no_followup["cli_args"] == [ + "--progress-result-class", "no_followup", + "--progress-coverage-scope-id", "", + "--progress-evidence-id", "", + "--agent-vision-json", "", + ] + assert no_followup["vision_fields"] == { + "state": "no_followup", "path_delta.outcome": "stop", + } + assert no_followup["preserve"] == ["vision_patch"] assert payload["interaction_contract"]["agent_channel"][ "primary_action" ] == "produce one typed outcome from the host-projected replan action packet" diff --git a/tests/control_plane/test_settlement_command_guidance_cli.py b/tests/control_plane/test_settlement_command_guidance_cli.py index 95d0420e50..bbbd2f9f29 100644 --- a/tests/control_plane/test_settlement_command_guidance_cli.py +++ b/tests/control_plane/test_settlement_command_guidance_cli.py @@ -10,7 +10,7 @@ from loopx.control_plane.quota.turn_envelope import build_turn_envelope from test_quota_settlement_cli import ( AGENT_ID, GOAL_ID, TODO_ID, _initialize_fixture_authority, - _run_cli, _run_generated_cli, _write_fixture, + _run_cli, _run_generated_cli, _spend_run_count, _write_fixture, ) @@ -111,16 +111,28 @@ def test_returned_writeback_can_record_progress_and_settle_once( registry_path=registry, ) assert rc != 0, refused - spend = next(s["command_template"] for s in plan["ordered_steps"] if s["kind"] == "quota_spend") - rc, premature = _run_generated_cli(spend, registry_path=registry) + spend = next(s for s in plan["ordered_steps"] if s["kind"] == "quota_spend") + assert plan["schema_version"] == "quota_settlement_plan_v2" + assert spend["owner"] == "runtime" and "command_template" not in spend + assert "--settle-turn" in shlex.split(command) + # Deliberately unprojected: accounting still rejects an early model debit. + rc, premature = _run_cli(registry, runtime, "quota", "spend-slot", "--goal-id", GOAL_ID, + "--agent-id", AGENT_ID, "--todo-id", TODO_ID, "--turn-instance-id", "command-guidance", + "--source", "heartbeat", "--execute") assert rc != 0, premature + assert _spend_run_count(runtime) == 0 rc, writeback = _run_generated_cli(command, registry_path=registry) assert rc == 0, writeback assert writeback["progress_observation"]["result_class"] == "advanced" - rc, spent = _run_generated_cli(spend, registry_path=registry) - assert rc == 0, spent - rc, replay = _run_generated_cli(spend, registry_path=registry) + assert writeback["settlement_identity"] == guard["heartbeat_receipt"]["settlement_identity"] + assert writeback["settlement_progress"]["state"] == "settled" + assert [row["step_kind"] for row in writeback["settlement_result"]["receipts"]] == [ + "validation", "durable_writeback", "quota_spend", + ] + assert _spend_run_count(runtime) == 1 + rc, replay = _run_generated_cli(command, registry_path=registry) assert rc == 0 and replay["idempotent_replay"] is True, replay + assert _spend_run_count(runtime) == 1 rc, todo = _run_cli(registry, runtime, "todo", "list", "--goal-id", GOAL_ID, "--todo-id", TODO_ID) assert rc == 0 and todo["todo"]["status"] == "open", todo diff --git a/tests/control_plane/test_terminal_settlement_tool_behavior.py b/tests/control_plane/test_terminal_settlement_tool_behavior.py index df2505fa1a..122ad53011 100644 --- a/tests/control_plane/test_terminal_settlement_tool_behavior.py +++ b/tests/control_plane/test_terminal_settlement_tool_behavior.py @@ -65,12 +65,15 @@ def _writeback_action(request: Mapping[str, Any]) -> ScriptedExecToolAction: return ScriptedExecToolAction(command=command) -def _spend_action(request: Mapping[str, Any]) -> ScriptedExecToolAction: +def _unprojected_spend_action(request: Mapping[str, Any]) -> ScriptedExecToolAction: packet = _latest_quota_packet(request) - command = packet["interaction_contract"]["cli_channel"]["next_cli_actions"][1] - return ScriptedExecToolAction( - command=command.replace('"${LOOPX_TURN:?}"', "turn-test-001") - ) + identity = packet["heartbeat_receipt"]["settlement_identity"] + return ScriptedExecToolAction(command=shlex.join([ + "loopx", "--format", "json", "quota", "spend-slot", + "--goal-id", identity["goal_id"], "--agent-id", identity["agent_id"], + "--todo-id", identity["todo_id"], "--turn-instance-id", identity["turn_instance_id"], + "--source", "heartbeat", "--execute", + ])) def _completion_action( @@ -160,7 +163,6 @@ def test_real_tool_loop_settles_final_todo_after_spend( )), *([partial(_completion_action, kind="validation")] if ordinary_completion else []), _writeback_action, - _spend_action, _completion_action, ] ) @@ -180,7 +182,6 @@ def test_real_tool_loop_settles_final_todo_after_spend( "delivery_validation", *(["todo_completion"] if ordinary_completion else []), "durable_writeback", - "quota_spend", "terminal_closeout", ] assert receipt["settlement_receipt_steps"] == [ @@ -475,7 +476,7 @@ def completion(request): ScriptedExecToolAction(command="cat > " + shlex.quote(target) + " <<'JSON'\n" + json.dumps(vision) + "\nJSON"), *([partial(writeback, omit_scope=True)] if correct_input else []), - writeback, _spend_action, _completion_action, + writeback, _completion_action, ]) def next_action(request): @@ -497,8 +498,8 @@ def next_action(request): # changes which planned settlement actions fit, never when EOF is reached. budgeted_steps = [("validation", initial_page_count + 4), ("durable_writeback", initial_page_count + 7), - ("quota_spend", initial_page_count + 8), - ("terminal_closeout", initial_page_count + 9)] + ("quota_spend", initial_page_count + 7), + ("terminal_closeout", initial_page_count + 8)] assert receipt["settlement_receipt_steps"] == ( ["validation", "durable_writeback", "quota_spend", "terminal_closeout"] if passed else [kind for kind, ordinal in budgeted_steps @@ -508,7 +509,10 @@ def next_action(request): assert (tmp_path / "actor/project/fixture/settlement-proof.json").read_bytes() == fixture.proof_target.read_bytes() assert outside.read_text() == "Owner artifact.\n" if correct_input: - assert receipt["tool_call_count"] == (10 if page_bytes is not None else 8) + assert receipt["tool_call_count"] == min( + initial_page_count + 8 if page_bytes is not None else 7, + TERMINAL_SETTLEMENT_TOOL_BEHAVIOR_MAX_CALLS, + ) assert receipt["observed_tool_sequence"].count("progress_observation_invalid_arguments") == ( int(initial_page_count + 6 <= TERMINAL_SETTLEMENT_TOOL_BEHAVIOR_MAX_CALLS) if page_bytes == 12000 else 1 @@ -586,13 +590,13 @@ def writeback(request): ScriptedExecToolAction(command=fixture.quota_guard_command), ScriptedExecToolAction(command="cat fixture/settlement-proof.json"), partial(_completion_action, kind="validation"), draft, writeback, - partial(draft, corrected=True), writeback, _spend_action, _completion_action, + partial(draft, corrected=True), writeback, _completion_action, ]) receipt = DoubaoTerminalSettlementToolBehaviorActor( api_key="test-only-placeholder", transport=transport, ).qualify(qualification_id="native-vision-input-correction", fixture_root=tmp_path / "actor") assert receipt["qualification_passed"] is True, receipt - assert receipt["tool_call_count"] == len(transport.requests) == 9 + assert receipt["tool_call_count"] == len(transport.requests) == 8 assert receipt["settlement_receipt_steps"] == [ "validation", "durable_writeback", "quota_spend", "terminal_closeout", ] @@ -667,13 +671,13 @@ def writeback(request): ScriptedExecToolAction(command=fixture.quota_guard_command), initial_read, ScriptedExecToolAction(command="cat fixture/settlement-proof.json"), vision_read, partial(_completion_action, kind="validation"), missing_writeback, draft, - writeback, _spend_action, _completion_action, + writeback, _completion_action, ]) receipt = DoubaoTerminalSettlementToolBehaviorActor( api_key="test-only-placeholder", transport=transport, ).qualify(qualification_id="missing-draft-correction", fixture_root=tmp_path / "actor") assert receipt["qualification_passed"] is True, receipt - assert receipt["tool_call_count"] == len(transport.requests) == TERMINAL_SETTLEMENT_TOOL_BEHAVIOR_MAX_CALLS + assert receipt["tool_call_count"] == len(transport.requests) == 9 assert receipt["settlement_receipt_steps"] == [ "validation", "durable_writeback", "quota_spend", "terminal_closeout", ] @@ -753,14 +757,14 @@ def writeback(request): f"print({private_output!r}); raise SystemExit(7)" ) ))] * failed_drafts), - corrected_draft, writeback, _spend_action, _completion_action, + corrected_draft, writeback, _completion_action, ]) receipt = DoubaoTerminalSettlementToolBehaviorActor( api_key="test-only-placeholder", transport=transport, ).qualify(qualification_id="terminal-shell-correction", fixture_root=tmp_path / "actor") assert receipt["qualification_passed"] is (failed_drafts == 1), receipt - assert receipt["tool_call_count"] == (8 if failed_drafts == 1 else 10) + assert receipt["tool_call_count"] == (7 if failed_drafts == 1 else 10) assert receipt["observed_tool_sequence"].count("shell_nonzero") == failed_drafts assert receipt["settlement_receipt_steps"] == ( ["validation", "durable_writeback", "quota_spend", "terminal_closeout"] @@ -795,7 +799,7 @@ def faulty_host(shell, command): ScriptedExecToolAction(command="cat fixture/settlement-proof.json"), partial(_completion_action, kind="validation"), ScriptedExecToolAction(command="python3 -c 'raise SystemExit(7)'"), - _writeback_action, _spend_action, _completion_action, + _writeback_action, _completion_action, ]) receipt = DoubaoTerminalSettlementToolBehaviorActor( api_key="test-only-placeholder", transport=transport, @@ -831,7 +835,7 @@ def rejected_writeback(request): @pytest.mark.parametrize(("payload_ok", "payload_appended"), [(False, True), (True, True), (False, False)]) -def test_nonzero_after_actual_writeback_cannot_advance_to_spend( +def test_nonzero_after_composed_writeback_cannot_advance_to_terminal( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, payload_ok: bool, payload_appended: bool, ) -> None: from loopx.control_plane.quota.settlement import read_heartbeat_settlement @@ -860,7 +864,7 @@ def fail_after_writeback(argv, *args, **kwargs): ScriptedExecToolAction(command=fixture.quota_guard_command), ScriptedExecToolAction(command="cat fixture/settlement-proof.json"), partial(_completion_action, kind="validation"), _writeback_action, - _spend_action, _completion_action, + _completion_action, ]) receipt = DoubaoTerminalSettlementToolBehaviorActor( api_key="test-only-placeholder", transport=transport, @@ -871,14 +875,100 @@ def fail_after_writeback(argv, *args, **kwargs): assert receipt["settlement_receipt_steps"] == ["validation"] assert "synthetic post-effect" not in json.dumps(receipt) # Independent canonical readback proves that the failure did not roll back - # the real write; neither a debit nor terminal effect followed it. + # the real write and its runtime-owned debit; no terminal effect followed. readback = read_heartbeat_settlement( tmp_path / "actor/runtime", goal_id=committed["goal_id"], agent_id=committed["agent_id"], todo_id=committed["todo_id"], turn_instance_id=committed["turn_instance_id"], ) assert readback is not None - assert readback.progress["next_step"] == "quota_spend" + assert readback.progress["state"] == "settled" + assert readback.spend.failure is None + assert readback.terminal_closeout.failure is not None + + +@pytest.mark.parametrize("damage", ["missing_spend", "foreign_receipt", "foreign_identity", + "unknown_receipt", "uncommitted", "reported_failure"]) +def test_composed_writeback_requires_original_committed_spend_receipt( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, damage: str, +) -> None: + from loopx.control_plane.testing import terminal_settlement_tool_behavior as terminal + from loopx.control_plane.quota.settlement import read_heartbeat_settlement + + fixture = _build_fixture(tmp_path / "oracle") + execute = terminal._execute_cli + committed = {} + + def damaged_receipt(command, state): + payload = execute(command, state) + if "refresh-state" in command: + committed.update(payload["settlement_identity"]) + receipts = payload["settlement_result"]["receipts"] + spend = next(row for row in receipts if row["step_kind"] == "quota_spend") + if damage == "missing_spend": + receipts.remove(spend) + elif damage == "foreign_identity": + payload["settlement_identity"]["effect_id"] = "foreign-effect" + for row in receipts: + row["effect_id"] = "foreign-effect" + elif damage == "foreign_receipt": + spend["effect_id"] = "foreign-effect" + elif damage == "unknown_receipt": + spend["schema_version"] = "quota_settlement_receipt_v99" + elif damage == "uncommitted": + spend["status"] = "pending" + else: + payload["settlement_result"]["failure"] = {"reason": "synthetic contradictory failure"} + return payload + + monkeypatch.setattr(terminal, "_execute_cli", damaged_receipt) + transport = ScriptedDoubaoExecTransport([ + ScriptedExecToolAction(command=fixture.quota_guard_command), + ScriptedExecToolAction(command="cat fixture/settlement-proof.json"), + partial(_completion_action, kind="validation"), _writeback_action, _completion_action, + ]) + receipt = DoubaoTerminalSettlementToolBehaviorActor( + api_key="test-only-placeholder", transport=transport, + ).qualify(qualification_id="original-composed-receipts", fixture_root=tmp_path / "actor") + assert receipt["qualification_passed"] is False + assert receipt["failure_code"] == "writeback_receipt_mismatch" + assert receipt["tool_call_count"] == len(transport.requests) == 4 + assert receipt["settlement_receipt_steps"] == ["validation"] + readback = read_heartbeat_settlement( + tmp_path / "actor/runtime", goal_id=committed["goal_id"], + agent_id=committed["agent_id"], todo_id=committed["todo_id"], + turn_instance_id=committed["turn_instance_id"], + ) + assert readback is not None and readback.progress["state"] == "settled" + assert readback.spend.failure is None + assert readback.terminal_closeout.failure is not None + + +def test_model_cannot_spend_again_after_runtime_writeback(tmp_path: Path, monkeypatch) -> None: + from loopx.control_plane.testing import terminal_settlement_tool_behavior as terminal + + fixture = _build_fixture(tmp_path / "oracle") + execute = terminal._execute_cli + commands = [] + + def observed_execute(command, state): + commands.append(command) + return execute(command, state) + + monkeypatch.setattr(terminal, "_execute_cli", observed_execute) + transport = ScriptedDoubaoExecTransport([ + ScriptedExecToolAction(command=fixture.quota_guard_command), + ScriptedExecToolAction(command="cat fixture/settlement-proof.json"), + partial(_completion_action, kind="validation"), _writeback_action, + _unprojected_spend_action, _completion_action, + ]) + receipt = DoubaoTerminalSettlementToolBehaviorActor( + api_key="test-only-placeholder", transport=transport, + ).qualify(qualification_id="no-second-runtime-spend", fixture_root=tmp_path / "actor") + assert receipt["failure_code"] == "quota_spend_contract_mismatch" + assert receipt["tool_call_count"] == len(transport.requests) == 5 + assert receipt["settlement_receipt_steps"] == ["validation", "durable_writeback", "quota_spend"] + assert not any("spend-slot" in command for command in commands) @pytest.mark.parametrize("change", [ @@ -936,7 +1026,7 @@ def reject(request): transport = ScriptedDoubaoExecTransport([ ScriptedExecToolAction(command=fixture.quota_guard_command), ScriptedExecToolAction(command="cat fixture/settlement-proof.json"), - partial(_completion_action, kind="validation"), reject, _spend_action, + partial(_completion_action, kind="validation"), reject, _completion_action, ]) receipt = DoubaoTerminalSettlementToolBehaviorActor( api_key="test-only-placeholder", transport=transport, @@ -1050,7 +1140,7 @@ def test_tool_loop_rejects_spend_before_writeback( "fixture/settlement-proof.json" if batch_read else "cat fixture/settlement-proof.json" )), - _spend_action, + _unprojected_spend_action, ] ) diff --git a/tests/control_plane/test_todo_settlement_markdown.py b/tests/control_plane/test_todo_settlement_markdown.py index 147db0ec55..4104fa21cc 100644 --- a/tests/control_plane/test_todo_settlement_markdown.py +++ b/tests/control_plane/test_todo_settlement_markdown.py @@ -12,11 +12,12 @@ from loopx.control_plane.todos.markdown import render_todo_markdown -def test_settlement_recovery_preserves_order_conditions_and_commands() -> None: +@pytest.mark.parametrize("version", ["quota_settlement_plan_v1", "quota_settlement_plan_v2"]) +def test_settlement_recovery_preserves_order_conditions_and_commands(version: str) -> None: payload = { "error": "same-Turn settlement is incomplete", "settlement_plan": { - "schema_version": "quota_settlement_plan_v1", + "schema_version": version, "ordered_steps": [ None, { @@ -75,10 +76,13 @@ def test_empty_typed_settlement_plan_keeps_its_heading() -> None: @pytest.mark.parametrize("handoff_mode", ["soft_claim", "hard_lease"]) -def test_real_cli_recovery_markdown_exposes_the_same_semantic_command(tmp_path, monkeypatch, handoff_mode): - isolate_sqlite_runtime(tmp_path, monkeypatch) +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("terminal", [False, True]) +def test_real_cli_recovery_markdown_exposes_the_same_semantic_command(tmp_path, monkeypatch, handoff_mode, provider, terminal): + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) project, runtime, registry = fixture._write_fixture(tmp_path) - fixture._initialize_fixture_authority(project, runtime, provider="sqlite", handoff_mode=handoff_mode) + fixture._initialize_fixture_authority(project, runtime, provider=provider, handoff_mode=handoff_mode) binding = ["--goal-id", fixture.GOAL_ID, "--agent-id", fixture.AGENT_ID, "--todo-id", fixture.TODO_ID, "--turn-instance-id", "markdown-feedback"] if handoff_mode == "hard_lease": @@ -89,16 +93,23 @@ def test_real_cli_recovery_markdown_exposes_the_same_semantic_command(tmp_path, code, guard = fixture._run_cli(registry, runtime, "quota", "should-run", *binding, "--runtime-profile", "generic_cli", cwd=project) assert code == 0 and guard["should_run"], guard - complete = ["todo", "complete", *binding, "--no-follow-up", "--evidence", "evidence:route-feedback"] + complete = ["todo", "complete", *binding, "--evidence", "evidence:route-feedback"] + if terminal: + complete.append("--no-follow-up") if handoff_mode == "hard_lease": complete += ["--claim-operation-id", "markdown-execution"] code, recovery = fixture._run_cli(registry, runtime, *complete, cwd=project) - assert code == 1, recovery + assert code == int(terminal), recovery + plan = recovery["settlement_plan"] + assert plan["schema_version"] == "quota_settlement_plan_v2" + assert plan["identity"] == guard["heartbeat_receipt"]["settlement_identity"] + assert plan["ordered_steps"][2]["owner"] == "runtime" + assert "command_template" not in plan["ordered_steps"][2] expected = recovery["settlement_plan"]["ordered_steps"][1]["semantic_closeout_command_template"] markdown = subprocess.run([sys.executable, "-m", "loopx.entrypoint", "--registry", str(registry), "--runtime-root", str(runtime), "--format", "markdown", *complete], cwd=project, env={**os.environ, "PYTHONPATH": str(fixture.REPO_ROOT)}, capture_output=True, text=True) - assert markdown.returncode == 1, markdown.stdout + assert markdown.returncode == int(terminal), markdown.stdout assert "semantic closeout: `" + expected + "`" in markdown.stdout spend_precondition = recovery["settlement_plan"]["ordered_steps"][2]["precondition"] assert "fresh open-Todo semantic checkpoint" in spend_precondition diff --git a/tests/control_plane_ts/quota_settlement_plan.test.ts b/tests/control_plane_ts/quota_settlement_plan.test.ts index 15badf52d8..4ef030a059 100644 --- a/tests/control_plane_ts/quota_settlement_plan.test.ts +++ b/tests/control_plane_ts/quota_settlement_plan.test.ts @@ -3,7 +3,7 @@ import test from "node:test"; import {settlementPlanPayload} from "../../loopx/control_plane/effect_program.ts"; import {visionAuthoringContract} from "../../loopx/control_plane/goals/vision_checkpoint.ts"; import {projectMcpInteraction} from "../../loopx/control_plane/turn_driver/host_interaction.ts"; -import {completeCliSettlementChannel, composedCliSettlementChannel, nativeCliSettlementProjection, turnScopedCliSettlementPlan} +import {completeCliSettlementChannel, composedCliSettlementChannel, nativeCliSettlementProjection, turnScopedCliSettlementPlan, turnScopedCliSettlementPlanPayload} from "../../loopx/control_plane/quota/settlement_plan.ts"; import {EXECUTION_PREPARATION_SCHEMA_VERSION} from "../../loopx/control_plane/work_items/execution_preparation.ts"; import {DELIVERY_OUTCOMES, decodeOptionalDeliveryOutcome, isTurnScopedSettlementOutcome} @@ -19,6 +19,29 @@ const input = { }, }; +test("current Todo continuation composes the same plan and preserves historical rendering", () => { + const original = settlementPlanPayload(turnScopedCliSettlementPlan(input)); + assert.deepEqual(turnScopedCliSettlementPlanPayload(input), original); + assert.deepEqual(turnScopedCliSettlementPlanPayload({...input, composed_settlement: false}), original); + const request = {...input, composed_settlement: true, + command_templates: {...input.command_templates, semantic_closeout: "semantic writeback"}}; + const before = structuredClone(request); + const plan = turnScopedCliSettlementPlanPayload(request); + assert.equal(plan.schema_version, "quota_settlement_plan_v2"); + assert.deepEqual(plan.identity, original.identity); + const steps = plan.ordered_steps as Record[]; + assert.deepEqual(steps.map(step => step.kind), ["validation", "durable_writeback", "quota_spend", "terminal_closeout"]); + assert.deepEqual(steps[0], (original.ordered_steps as object[])[0]); + assert.deepEqual(steps[3], (original.ordered_steps as object[])[3]); + assert.equal(steps[1].command_template, "writeback --settle-turn --settlement-receipt"); + assert.equal(steps[1].semantic_closeout_command_template, "semantic writeback --settle-turn --settlement-receipt"); + assert.equal(steps[2].owner, "runtime"); + assert.equal(steps[2].command_template, undefined); + assert.deepEqual(request, before); + for (const composed_settlement of [null, "true", 1]) + assert.throws(() => turnScopedCliSettlementPlanPayload({...input, composed_settlement}), /must be a boolean/); +}); + test("native settlement only replaces matching executable steps on the original ready Turn", () => { const plan = settlementPlanPayload(turnScopedCliSettlementPlan(input)); const preparation = {schema_version: EXECUTION_PREPARATION_SCHEMA_VERSION, state: "ready",