Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions docs/reference/required-work-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,9 @@ Unbound staged replans retain their existing review-owned original Goal read.
After a Host claim, the ready guard uses the private
`--prepared-capture-reference` route. It publishes the complete decision and
returns its writer digest with the fields needed to verify the same Todo and
Turn. The hook verifies that digest when it opens the original file. If the
Turn. The default guard and the `--turn-envelope` and `--complete-turn`
compatibility spellings use the same complete v1 capture. The hook verifies
that digest when it opens the original file. If the
file changed, the receipt preserves the claim and pins recovery to the original
bytes before work can continue.
The private native journal reserves automatic preparation before claiming a
Expand Down Expand Up @@ -1134,7 +1136,8 @@ Checkpoint Host 预检在显式开启 native JSON `should-run` 捕获时使用
读取。未绑定任务的分阶段重规划继续沿用 review 所属的原始 Goal 读取。

Host 领取 Todo 后,就绪检查使用内部 `--prepared-capture-reference` 路径。它保存完整决策,
只返回写入时的摘要和核对同一 Todo、Turn 所需的字段。hook 打开原文件时校验该摘要;
只返回写入时的摘要和核对同一 Todo、Turn 所需的字段。默认 guard 和 `--turn-envelope`、
`--complete-turn` 两个兼容别名均使用同一份完整 v1 捕获。hook 打开原文件时校验该摘要。
若文件已被替换,回执保留原领取记录,恢复原始内容后才能继续工作。

Goal adapter 仍完整读取文件、校验 UTF-8,并以全部字节计算修订摘要;关闭 native
Expand Down
2 changes: 1 addition & 1 deletion loopx/cli_commands/quota_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ def prepare_quota_capture(args: argparse.Namespace, directory: Path | None) -> P
if getattr(args, "prepared_capture_reference", False) and (
args.quota_command != "should-run" or args.format != "json"
or not getattr(args, "decision_output_dir", None) or not getattr(args, "turn_instance_id", None)
or getattr(args, "decision_handoff_socket", None) or getattr(args, "turn_envelope", False)
or getattr(args, "decision_handoff_socket", None)
or (native_context_activation(args)["enabled"] and not getattr(args, "defer_context_presentation", False))
):
raise QuotaCommandValidationError("prepared capture reference requires an explicit Turn and raw JSON capture")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,11 +173,12 @@ def register_heartbeat_control_commands(
turn_view.add_argument(
"--turn-envelope",
action="store_true",
help="Explicitly use the short TurnEnvelope dispatcher; requires --decision-output-root. Capture alone keeps the ordinary full decision.",
help="Keep the compatibility spelling in the generated thin guard. Requires --decision-output-root. "
"Current quota guards return the complete v1 work contract by default.",
)
turn_view.add_argument("--complete-turn", action="store_true",
help="Explicitly consume complete v1 Turn context on the generated thin host-owned heartbeat guard. "
"Retains the existing legacy --turn-envelope protocol when unselected.")
help="Keep the explicit complete-turn spelling in the generated thin host-owned guard. "
"Current quota guards return the complete v1 work contract by default.")

heartbeat_prompt_parser.add_argument(
"--decision-handoff-socket",
Expand Down
42 changes: 24 additions & 18 deletions tests/control_plane/test_heartbeat_command_authority.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
import pytest
import test_quota_settlement_cli as cli

from loopx.control_plane.quota.turn_envelope import build_turn_envelope, turn_plan_host_source
from loopx.control_plane.quota.turn_envelope import turn_plan_host_source
from loopx.control_plane.turn_driver.driver import build_loopx_turn_plan
from loopx.control_plane.work_items.interaction_contract import build_interaction_contract
from loopx.control_plane.turn_driver.host_candidate import extract_turn_authority

Expand Down Expand Up @@ -50,16 +51,18 @@ def test_current_selection_and_settlement_override_goal_command(tmp_path, provid
"--agent-id", cli.AGENT_ID, "--turn-instance-id", cli.TURN_ID)
binding = ("--todo-id", cli.TODO_ID)
captures = []
settlement_identities = []
receipt_counts = []
for name, view in (("compact", ()), ("detail", ("--include-detail", "all")),
("envelope", ("--turn-envelope",))):
for name, view in (("default", ()), ("detail", ("--include-detail", "all")),
("envelope-alias", ("--turn-envelope",)), ("complete-alias", ("--complete-turn",))):
capture = tmp_path / (name + "-capture")
code, current = cli._run_cli(registry, runtime, *args, *binding, *view,
"--decision-output-dir", str(capture), cwd=project)
assert code == 0, current
saved = capture / "decision.json"
original = saved.read_bytes()
full = json.loads(original)
assert current == full and full["schema_version"] == "loopx_turn_envelope_v1"
interaction = full["interaction_contract"]
recommendation = full["heartbeat_recommendation"]
assert interaction["agent_channel"]["delivery_allowed"] is True
Expand All @@ -69,31 +72,34 @@ def test_current_selection_and_settlement_override_goal_command(tmp_path, provid
assert recommendation["reason"] == interaction["agent_channel"]["primary_action"]
assert recommendation["spend_policy"] == interaction["cli_channel"]["spend_policy"]
assert full["selected_todo"]["todo_id"] == cli.TODO_ID
envelope = current if name == "envelope" else build_turn_envelope(current)
assert envelope["action_signature"]["matches"] is True
assert extract_turn_authority({"turn_envelope": envelope})["primary_action"] == interaction["agent_channel"]["primary_action"]
plan = build_loopx_turn_plan(full, host="generic-cli", execution_mode="isolated-headless",
turn_instance_id=cli.TURN_ID)
authority = extract_turn_authority(turn_plan_host_source(plan))
assert authority["primary_action"] == interaction["agent_channel"]["primary_action"]
settlement_identity = interaction["cli_channel"]["settlement_plan"]["identity"]
assert settlement_identity == full["heartbeat_receipt"]["settlement_identity"]
assert settlement_identity == plan["transaction"]["settlement_plan"]["identity"]
assert full["agent_command"] == COMMAND # Configuration remains source evidence.
if name != "envelope":
assert current["heartbeat_recommendation"] == recommendation
captures.append((saved, original))
settlement_identities.append(settlement_identity)
receipt_counts.append(cli._heartbeat_receipt_count(runtime, cli.TURN_ID))

identity = ("--goal-id", cli.GOAL_ID, "--agent-id", cli.AGENT_ID,
"--todo-id", cli.TODO_ID, "--turn-instance-id", cli.TURN_ID)
code, refresh = cli._run_cli(
registry, runtime, "refresh-state", *identity,
refresh_args = (
"refresh-state", *identity,
"--classification", "validated_intermediate_progress",
"--delivery-batch-scale", "implementation", "--delivery-outcome", "outcome_progress",
"--delivery-boundary", "in_flight_continuation",
"--no-global-sync", "--suppress-external-sinks", cwd=project,
"--no-global-sync", "--suppress-external-sinks", "--settle-turn", "--settlement-receipt",
)
assert code == 0, refresh
spend_args = ("quota", "spend-slot", *identity, "--slots", "1",
"--source", "heartbeat", "--execute")
code, spent = cli._run_cli(registry, runtime, *spend_args, cwd=project)
assert code == 0 and spent["appended"] is True, spent
code, retry = cli._run_cli(registry, runtime, *spend_args, cwd=project)
assert code == 0 and retry["appended"] is False, retry
code, refresh = cli._run_cli(registry, runtime, *refresh_args, cwd=project)
assert code == 0 and refresh["quota_spend"]["appended"], refresh
assert all(identity == refresh["settlement_identity"] for identity in settlement_identities)
assert refresh["settlement_progress"]["state"] == "settled"
code, retry = cli._run_cli(registry, runtime, *refresh_args, cwd=project)
assert code == 0 and retry["idempotent_replay"] and not retry["appended"], retry
assert retry["settlement_result"]["receipts"] == refresh["settlement_result"]["receipts"]
code, settled = cli._run_cli(registry, runtime, *args, *binding, cwd=project)
assert code == 0, settled
assert settled["interaction_contract"]["mode"] == "heartbeat_settled_skip"
Expand Down
51 changes: 50 additions & 1 deletion tests/control_plane/test_quota_decision_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def request(path, **overrides):

@pytest.mark.parametrize("overrides", [
{"turn_instance_id": None}, {"quota_command": "plan"}, {"format": "markdown"},
{"turn_envelope": True}, {"decision_handoff_socket": "/unused/socket"},
{"decision_handoff_socket": "/unused/socket"},
{"context_delivery": "on", "codex_app": True},
])
def test_prepared_reference_rejects_incompatible_delivery_before_guard(tmp_path, overrides):
Expand All @@ -41,6 +41,55 @@ def test_prepared_reference_rejects_incompatible_delivery_before_guard(tmp_path,
assert list(tmp_path.iterdir()) == []


@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("context_delivery", ["off", "on"])
@pytest.mark.parametrize("alias", [None, "--turn-envelope", "--complete-turn"])
def test_prepared_capture_verifies_the_same_complete_turn_with_compatibility_aliases(
tmp_path, monkeypatch, provider, context_delivery, alias,
):
from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime
from tests.control_plane.test_quota_settlement_cli import _spend_run_count

isolate_sqlite_runtime(tmp_path, monkeypatch)
_, runtime, registry = _write_fixture(tmp_path, provider=provider)
capture_dir = tmp_path / "capture"
context_dir = tmp_path / "context"
context_args = []
if context_delivery == "on":
context_dir.mkdir(mode=0o700)
monkeypatch.setenv("CODEX_THREAD_ID", "fixture-prepared-capture")
context_args = ["--codex-context-dir", str(context_dir), "--defer-context-presentation"]
code, prepared = _run_cli(
registry, runtime, "quota", "should-run", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID,
"--todo-id", TODO_ID, "--turn-instance-id", TURN_ID, "--codex-app",
"--context-delivery", context_delivery, *context_args, *([alias] if alias else []),
"--decision-output-dir", str(capture_dir), "--prepared-capture-reference",
)
assert code == 0, prepared
assert prepared["ok"] and prepared["normal_delivery_allowed"]
assert prepared["selected_todo"] == {"todo_id": TODO_ID}
assert prepared["heartbeat_receipt"] == {"turn_instance_id": TURN_ID}
saved = capture_dir / "decision.json"
original = saved.read_bytes()
digest = sha256(original).hexdigest()
assert prepared["capture_sha256"] == digest
source = json.loads(original)
assert source["schema_version"] == "loopx_turn_envelope_v1"
identity = source["heartbeat_receipt"]["settlement_identity"]
assert identity["turn_instance_id"] == TURN_ID and identity["todo_id"] == TODO_ID
identity_pointer = "/interaction_contract/cli_channel/settlement_plan/identity"
code, readback = _run_cli(
registry, runtime, "quota", "context-read", "--capture-file", str(saved),
"--capture-sha256", digest, "--select", identity_pointer,
)
assert code == 0 and readback["eof"]
assert json.loads(readback["content"])["selections"] == [{"pointer": identity_pointer, "value": identity}]
assert not context_dir.exists() or not list(context_dir.iterdir())
assert saved.read_bytes() == original
assert _heartbeat_receipt_count(runtime, TURN_ID) == 1
assert _spend_run_count(runtime) == 0


def test_disabled_capture_does_not_touch_disk(tmp_path):
assert prepare_decision_capture(request(None)) is None
capture_decision(None, {'not_serializable': object()})
Expand Down
8 changes: 7 additions & 1 deletion tests/control_plane/test_saved_context_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -708,7 +708,13 @@ def consume(wire):
assert list(source.parent.parent.glob("*/decision.json")) == [source]
if placement == "explicit-before-session":
assert bound["mode"] == "full", bound
assert machine_reference_oracle(cold)["recovery"]["sha256"] == hashlib.sha256(raw).hexdigest()
cold_source_digest = machine_reference_oracle(cold["navigation"])["capture_sha256"]
assert cold_source_digest == hashlib.sha256(raw).hexdigest()
rc, original = _run_cli(registry, runtime, "quota", "context-read", "--capture-file", str(source),
"--capture-sha256", cold_source_digest, "--select", "/contract_binding", cwd=project)
assert rc == 0 and original["eof"], original
[binding] = json.loads(original["content"])["selections"]
assert binding["value"] == json.loads(raw)["contract_binding"] == presented["contract_binding"]
for key in ("first_read_command", "command"):
rc, first_page = _run_cli(registry, runtime, *shlex.split(bound[key])[1:], cwd=project)
assert rc == 0 and first_page["ok"], first_page
Expand Down
Loading