From 73aaf8b4dcdb9e478a76b0a4688fa6f79708d90f Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:36:55 +0800 Subject: [PATCH 1/4] feat(control-plane,dsh-plugin): wire real Todo settlement semantic-unit fold Wires opt-in Todo semantic-unit anchoring, verified settlement FoldToReceipt commitment, KeepRaw fail-closed rollback, and subsequent-Todo prompt/surface replacement across Core Turn execution, Core CLI --include-settlement receipt readback, and the DSH driver. Reuses Stage-then-Swap's evaluate_epoch_prefetch_prompt_gate and audit stripping helpers so subsequent-Todo replacement enforces the active min_net_savings_tokens floor against stabilized rendered prompts without inflating host wire payloads. Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/cli_commands/quota_receipt.py | 170 ++- loopx/cli_commands/quota_registration.py | 5 + loopx/cli_commands/turn_registration.py | 6 + loopx/cli_commands/turn_run_once.py | 1 + loopx/control_plane/turn_driver/codex_cli.py | 23 + .../turn_driver/epoch_prefetch.py | 77 +- loopx/control_plane/turn_driver/executor.py | 33 +- .../turn_driver/host_candidate.py | 36 +- .../turn_driver/quiet_turn_store.py | 34 +- .../turn_driver/todo_unit_settlement.py | 999 ++++++++++++++ packages/dsh-loopx-plugin/src/driver.ts | 237 +++- .../dsh-loopx-plugin/src/todo-unit-fold.ts | 119 ++ .../tests/todo-unit-fold.spec.ts | 510 ++++++- .../test_semantic_unit_fold_hooks.py | 1177 ++++++++++++++++- 14 files changed, 3355 insertions(+), 72 deletions(-) create mode 100644 loopx/control_plane/turn_driver/todo_unit_settlement.py diff --git a/loopx/cli_commands/quota_receipt.py b/loopx/cli_commands/quota_receipt.py index 4a83b2a436..3a7d26c00a 100644 --- a/loopx/cli_commands/quota_receipt.py +++ b/loopx/cli_commands/quota_receipt.py @@ -4,16 +4,160 @@ import argparse from collections.abc import Callable, Mapping +import hashlib import json from pathlib import Path -from ..control_plane.quota.heartbeat_receipt import find_heartbeat_receipt, heartbeat_receipt_view +from ..control_plane.quota.heartbeat_receipt import ( + find_heartbeat_receipt, + heartbeat_receipt_view, +) +from ..control_plane.quota.settlement import QuotaSettlementReadback, read_heartbeat_settlement from ..history import load_registry from ..paths import resolve_runtime_root, validate_goal_id_path_segment from ..registry import find_registry_goal +from ..rollout_event_log import rollout_event_log_path from ..turn_identity import normalize_turn_instance_id +def _clean_text_list(value: object, *, limit: int) -> list[str]: + if not isinstance(value, (list, tuple)): + return [] + out: list[str] = [] + seen: set[str] = set() + for item in value: + if not isinstance(item, str): + continue + trimmed = item.strip() + if not trimmed or trimmed in seen: + continue + seen.add(trimmed) + out.append(trimmed[:512]) + if len(out) >= limit: + break + return out + + +def _verified_settlement_projection( + *, + runtime_root: Path, + registry_path: Path, + goal_id: str, + agent_id: str, + turn_id: str, + heartbeat_receipt: Mapping[str, object] | None, + goal_ref: Mapping[str, object] | None, +) -> dict[str, object]: + identity = ( + heartbeat_receipt.get("settlement_identity") + if isinstance(heartbeat_receipt, Mapping) + else None + ) + bound_todo_id = ( + str(identity.get("todo_id") or "").strip() + if isinstance(identity, Mapping) + else "" + ) + settlement: QuotaSettlementReadback | None = read_heartbeat_settlement( + runtime_root, + goal_id=goal_id, + agent_id=agent_id, + todo_id=bound_todo_id or None, + turn_instance_id=turn_id, + infer_turn_instance_id=False, + resolve_original_binding=True, + registry_path=registry_path, + goal_ref=goal_ref, + ) + if settlement is None: + return { + "settlement_verified": False, + "settlement_conflict_reason": "settlement_readback_unavailable", + "completion_receipt": None, + } + if settlement.successor_replan_pending or settlement.replan_execution_pending: + return { + "settlement_verified": False, + "settlement_conflict_reason": "replan_conflict", + "completion_receipt": None, + } + if ( + isinstance(settlement.refresh_recovery, Mapping) + and settlement.refresh_recovery.get("decision") == "reject" + ): + return { + "settlement_verified": False, + "settlement_conflict_reason": "recovery_rejected", + "completion_receipt": None, + } + if (settlement.progress or {}).get("checkpoint_recovery_required") is True: + return { + "settlement_verified": False, + "settlement_conflict_reason": "checkpoint_recovery_required", + "completion_receipt": None, + } + completion_ev = settlement.completion_event + if not isinstance(completion_ev, Mapping): + return { + "settlement_verified": False, + "settlement_conflict_reason": "missing_completion_event", + "completion_receipt": None, + } + replay_phase = settlement.replay_phase.value if settlement.replay_phase else None + settlement_ok = ( + settlement.settlement.failure is None + and settlement.settlement.value is not None + ) or replay_phase == "settled" + writeback_ok = settlement.writeback_event is not None or ( + settlement.writeback.failure is None and settlement.writeback.value is not None + ) + spend_ok = settlement.spend_event is not None or ( + settlement.spend.failure is None and settlement.spend.value is not None + ) + if not (settlement_ok and writeback_ok and spend_ok): + return { + "settlement_verified": False, + "settlement_conflict_reason": "unsettled_turn", + "completion_receipt": None, + } + ev_todo_id = str(completion_ev.get("todo_id") or bound_todo_id).strip() + if not ev_todo_id or (bound_todo_id and ev_todo_id != bound_todo_id): + return { + "settlement_verified": False, + "settlement_conflict_reason": "todo_id_mismatch", + "completion_receipt": None, + } + receipt_id = str(completion_ev.get("event_id") or "").strip() or turn_id + log_path = rollout_event_log_path(runtime_root, goal_id) + if not log_path.is_file(): + return { + "settlement_verified": False, + "settlement_conflict_reason": "missing_source_ref", + "completion_receipt": None, + } + source_sha = hashlib.sha256(log_path.read_bytes()).hexdigest() + raw_details = completion_ev.get("details") + details: Mapping[str, object] = raw_details if isinstance(raw_details, Mapping) else {} + failure_facts = _clean_text_list(details.get("failure_facts"), limit=32) + open_obligations = _clean_text_list(details.get("open_obligations"), limit=64) + completion_digest = hashlib.sha256( + json.dumps(dict(completion_ev), sort_keys=True, ensure_ascii=False).encode("utf-8") + ).hexdigest() + return { + "settlement_verified": True, + "settlement_conflict_reason": None, + "completion_receipt": { + "todo_id": ev_todo_id, + "completion_receipt_id": receipt_id, + "exit_code": 0, + "sha256": completion_digest, + "failure_facts": failure_facts, + "open_obligations": open_obligations, + "source_ref": {"path": str(log_path), "sha256": source_sha}, + }, + } + + def read_quota_receipt( args: argparse.Namespace, *, @@ -32,17 +176,31 @@ def read_quota_receipt( if find_registry_goal(registry, goal_id) is None: raise ValueError("quota receipt requires a registered Goal") runtime_root = resolve_runtime_root(registry, runtime_root_arg, registry_path=registry_path) + goal_ref = goal_ref_resolver() event = find_heartbeat_receipt( runtime_root, goal_id=goal_id, agent_id=args.agent_id, turn_instance_id=turn_id, - goal_ref=goal_ref_resolver(), + goal_ref=goal_ref, + ) + receipt_view = ( + heartbeat_receipt_view(event, turn_instance_id=turn_id, status="committed") + if event is not None else None ) payload.update( ok=True, goal_id=goal_id, agent_id=args.agent_id, turn_instance_id=turn_id, - heartbeat_receipt=( - heartbeat_receipt_view(event, turn_instance_id=turn_id, status="committed") - if event is not None else None - ), + heartbeat_receipt=receipt_view, ) + if getattr(args, "include_settlement", False): + payload.update( + _verified_settlement_projection( + runtime_root=runtime_root, + registry_path=registry_path, + goal_id=goal_id, + agent_id=args.agent_id, + turn_id=turn_id, + heartbeat_receipt=receipt_view, + goal_ref=goal_ref, + ) + ) except (OSError, RuntimeError, ValueError) as exc: payload["error"] = str(exc) return payload diff --git a/loopx/cli_commands/quota_registration.py b/loopx/cli_commands/quota_registration.py index a4dd4927d6..ca81dac12c 100644 --- a/loopx/cli_commands/quota_registration.py +++ b/loopx/cli_commands/quota_registration.py @@ -443,4 +443,9 @@ def register_quota_command( default=120, help="Freshness window for --use-projection-cache. Defaults to 120 seconds.", ) + quota_parser.add_argument( + "--include-settlement", + action="store_true", + help="For `quota receipt`, also verify committed Todo completion settlement readback (default-off).", + ) quota_parser.add_argument("--limit", type=int, default=5) diff --git a/loopx/cli_commands/turn_registration.py b/loopx/cli_commands/turn_registration.py index 0ed943b201..ad751cbc7b 100644 --- a/loopx/cli_commands/turn_registration.py +++ b/loopx/cli_commands/turn_registration.py @@ -367,6 +367,12 @@ def register_turn_commands( action="store_true", help="Opt-in Quiet-Turn zero-tax skip metadata evaluation when Turn state is unchanged (default-off).", ) + run_once.add_argument( + "--semantic-unit-fold-json", + type=json.loads, + default=None, + help="Opt-in Todo semantic-unit fold & prefetch policy JSON (default-off).", + ) run_once.add_argument("--limit", type=int, default=5) diff --git a/loopx/cli_commands/turn_run_once.py b/loopx/cli_commands/turn_run_once.py index e8a6155fc0..e41ff955ce 100644 --- a/loopx/cli_commands/turn_run_once.py +++ b/loopx/cli_commands/turn_run_once.py @@ -955,6 +955,7 @@ def on_managed_start_admitted() -> None: ) if raw_argv is not None and goal_admission is not None else None), epoch_prefetch=getattr(args, "epoch_prefetch_json", None), quiet_turn=quiet_turn_option, + semantic_unit_fold=getattr(args, "semantic_unit_fold_json", None), **({"host_input_renderer": None} if unmeasurable_operation_host else {}), ) if args.execute: diff --git a/loopx/control_plane/turn_driver/codex_cli.py b/loopx/control_plane/turn_driver/codex_cli.py index 5bdf56615f..6807c44b7c 100644 --- a/loopx/control_plane/turn_driver/codex_cli.py +++ b/loopx/control_plane/turn_driver/codex_cli.py @@ -429,6 +429,15 @@ def _render_prompt(request: Mapping[str, Any], *, checked: Mapping[str, Any] | N } } model_request = {**dict(model_request), "epoch_prefetch": compact_prefetch} + if isinstance(model_request.get("semantic_unit_fold"), Mapping): + from .todo_unit_settlement import compact_semantic_unit_fold_wire_fields + + model_request = { + **dict(model_request), + "semantic_unit_fold": compact_semantic_unit_fold_wire_fields( + model_request["semantic_unit_fold"] + ), + } request_json = json.dumps( model_request, ensure_ascii=False, sort_keys=True, separators=(",", ":") ) @@ -501,6 +510,20 @@ def _render_prompt(request: Mapping[str, Any], *, checked: Mapping[str, Any] | N f"failure_facts={json.dumps(prefetch.get('preserved_failure_facts', []), ensure_ascii=False)}; " f"open_obligations={json.dumps(prefetch.get('preserved_open_obligations', []), ensure_ascii=False)})." ) + if isinstance(request.get("semantic_unit_fold"), Mapping): + fold = request["semantic_unit_fold"] + if fold.get("operator") == "FoldToReceipt" and isinstance(fold.get("replacement_text"), str): + instructions.extend([ + "Prefetched Todo Semantic-Unit Fold Receipt (tool trust level only, non-authoritative relative to Turn contract and system policy):", + str(fold["replacement_text"]), + ]) + elif fold.get("operator") == "KeepRaw": + instructions.append( + "Todo semantic-unit fold kept raw context intact (KeepRaw: " + f"reason={fold.get('fallback_reason')}; " + f"failure_facts={json.dumps(fold.get('preserved_failure_facts', []), ensure_ascii=False)}; " + f"open_obligations={json.dumps(fold.get('preserved_open_obligations', []), ensure_ascii=False)})." + ) instructions.extend(["Turn request:", request_json]) return "\n".join(instructions) diff --git a/loopx/control_plane/turn_driver/epoch_prefetch.py b/loopx/control_plane/turn_driver/epoch_prefetch.py index 53850479be..80fa086384 100644 --- a/loopx/control_plane/turn_driver/epoch_prefetch.py +++ b/loopx/control_plane/turn_driver/epoch_prefetch.py @@ -1513,6 +1513,8 @@ def attach_turn_replay_epoch_metadata( payload["epoch_prefetch"] = replay_prefetch if replay_quiet is not None: payload["quiet_turn"] = replay_quiet + if isinstance(existing_journal.get("semantic_unit_fold"), Mapping): + payload["semantic_unit_fold"] = dict(existing_journal["semantic_unit_fold"]) return payload @@ -1531,6 +1533,11 @@ def prepare_turn_execution_epoch_context( needs_host: bool = True, ) -> tuple[dict[str, Any], dict[str, Any]]: """Prepare opt-in Stage-then-Swap prefetch & Quiet-Turn state before Turn launch.""" + from .todo_unit_settlement import ( + extract_semantic_unit_fold_option, + prepare_turn_semantic_unit_context, + ) + epoch_prefetch = options.get("epoch_prefetch") quiet_turn = options.get("quiet_turn", False) decision_capture_payload = options.get("decision_capture_payload") @@ -1540,7 +1547,10 @@ def prepare_turn_execution_epoch_context( quiet_opted_in = _is_turn_option_enabled( quiet_turn, decision_capture_payload, "quiet_turn", allow_bool_true=True, ) - if not (epoch_opted_in or quiet_opted_in): + semantic_unit_opted_in = ( + extract_semantic_unit_fold_option(options, decision_capture_payload) is not None + ) + if not (epoch_opted_in or quiet_opted_in or semantic_unit_opted_in): return {}, dict(request) allow_execute = bool( @@ -1551,24 +1561,49 @@ def prepare_turn_execution_epoch_context( ) ) effective_agent_id = _effective_agent_id(plan, settlement_lineage) - prefetch_receipt, quiet_meta, updated_request = prepare_turn_epoch_context( - plan=plan, - request=request, - journal_path=journal_path, - goal_id=goal_id, - agent_id=effective_agent_id, - turn_key=turn_key, - project=project, - epoch_prefetch=epoch_prefetch, - quiet_turn=quiet_turn, - decision_capture_payload=decision_capture_payload, - existing_journal=existing_journal, - capture=capture, - allow_execute=allow_execute, - host=options.get("host"), - host_input_renderer=options.get("host_input_renderer", UNSET_HOST_INPUT_RENDERER), - ) - return {"epoch_prefetch": prefetch_receipt, "quiet_turn": quiet_meta}, updated_request + prefetch_receipt: dict[str, Any] | None = None + quiet_meta: dict[str, Any] | None = None + updated_request = dict(request) + if epoch_opted_in or quiet_opted_in: + prefetch_receipt, quiet_meta, updated_request = prepare_turn_epoch_context( + plan=plan, + request=updated_request, + journal_path=journal_path, + goal_id=goal_id, + agent_id=effective_agent_id, + turn_key=turn_key, + project=project, + epoch_prefetch=epoch_prefetch, + quiet_turn=quiet_turn, + decision_capture_payload=decision_capture_payload, + existing_journal=existing_journal, + capture=capture, + allow_execute=allow_execute, + host=options.get("host"), + host_input_renderer=options.get("host_input_renderer", UNSET_HOST_INPUT_RENDERER), + ) + semantic_meta: dict[str, Any] | None = None + if semantic_unit_opted_in: + semantic_meta, updated_request = prepare_turn_semantic_unit_context( + plan=plan, + request=updated_request, + journal_path=journal_path, + goal_id=goal_id, + agent_id=effective_agent_id, + turn_key=turn_key, + settlement_lineage=settlement_lineage, + options=options, + existing_journal=existing_journal, + needs_host=needs_host, + ) + metadata: dict[str, Any] = {} + if prefetch_receipt is not None or quiet_meta is not None: + metadata["epoch_prefetch"] = prefetch_receipt + metadata["quiet_turn"] = quiet_meta + if isinstance(semantic_meta, Mapping): + for key, value in semantic_meta.items(): + metadata[str(key)] = value + return metadata, updated_request def attach_epoch_metadata_to_journal( @@ -1584,6 +1619,10 @@ def attach_epoch_metadata_to_journal( journal["epoch_prefetch"] = dict(prefetch_receipt) if isinstance(quiet_meta, Mapping): journal["quiet_turn"] = dict(quiet_meta) + for key in ("semantic_unit_anchor", "semantic_unit_fold"): + value = epoch_metadata.get(key) + if isinstance(value, Mapping) and key not in journal: + journal[key] = dict(value) def reset_failed_turn_journal_with_epoch_metadata( diff --git a/loopx/control_plane/turn_driver/executor.py b/loopx/control_plane/turn_driver/executor.py index 748c8612c1..5214d9a3a2 100644 --- a/loopx/control_plane/turn_driver/executor.py +++ b/loopx/control_plane/turn_driver/executor.py @@ -898,10 +898,11 @@ def serialize_generic_cli_host_input(request: Mapping[str, Any]) -> str: """Serialize the exact JSON payload delivered on stdin to a generic-cli host.""" host_input: Mapping[str, Any] = captured_turn_host_input(request) if "work_contract" in request else request if isinstance(host_input.get("epoch_prefetch"), Mapping): - host_input = { - **dict(host_input), - "epoch_prefetch": strip_internal_epoch_prefetch_audit_fields(host_input["epoch_prefetch"]), - } + host_input = {**dict(host_input), "epoch_prefetch": strip_internal_epoch_prefetch_audit_fields(host_input["epoch_prefetch"])} + if isinstance(host_input.get("semantic_unit_fold"), Mapping): + from .todo_unit_settlement import strip_internal_semantic_unit_fold_audit_fields + + host_input = {**dict(host_input), "semantic_unit_fold": strip_internal_semantic_unit_fold_audit_fields(host_input["semantic_unit_fold"])} return json.dumps(host_input, ensure_ascii=False, separators=(",", ":")) @@ -1648,21 +1649,16 @@ def run_loopx_turn_once( host_launch_guard: Callable[[], AbstractContextManager[None]] | None = None, epoch_prefetch: Mapping[str, Any] | None = None, quiet_turn: bool | Mapping[str, Any] = False, + semantic_unit_fold: Mapping[str, Any] | None = None, host_input_renderer: HostInputRenderer | None | object = UNSET_HOST_INPUT_RENDERER, ) -> dict[str, Any]: - argv, host_projection = _prepare_host_invocation( - plan, host_argv=host_argv, host_runner=host_runner, - resume_existing_turn=resume_existing_turn, - ) - transaction_plan = ( - plan.get("transaction") if isinstance(plan.get("transaction"), dict) else {} - ) + argv, host_projection = _prepare_host_invocation(plan, host_argv=host_argv, host_runner=host_runner, resume_existing_turn=resume_existing_turn) + transaction_plan = plan.get("transaction") if isinstance(plan.get("transaction"), dict) else {} settlement_lineage = _ensure_turn_settlement_plan(plan, transaction_plan) planned_host = plan.get("host") if isinstance(plan.get("host"), Mapping) else {} quiet_options = { - "epoch_prefetch": epoch_prefetch, - "quiet_turn": quiet_turn, - "decision_capture_payload": decision_capture_payload, + "epoch_prefetch": epoch_prefetch, "quiet_turn": quiet_turn, + "semantic_unit_fold": semantic_unit_fold, "decision_capture_payload": decision_capture_payload, "host": "generic-cli" if argv is not None else str(planned_host.get("kind") or ""), "host_input_renderer": host_input_renderer, } @@ -1864,12 +1860,8 @@ def persist_source_journal(source_admission: Mapping[str, Any]) -> None: if capture is not None: plan, request = capture.publish_for_host(request) epoch_metadata, request = prepare_turn_execution_epoch_context( - plan=plan, request=request, journal_path=journal_path, - goal_id=goal_id, turn_key=turn_key, project=project, - settlement_lineage=settlement_lineage, - options=quiet_options, - existing_journal=journal, capture=capture, needs_host=needs_host, - ) + plan=plan, request=request, journal_path=journal_path, goal_id=goal_id, turn_key=turn_key, + project=project, settlement_lineage=settlement_lineage, options=quiet_options, existing_journal=journal, capture=capture, needs_host=needs_host) if journal is not None and recovery_decision is not None: journal["recovery_audit"] = build_turn_recovery_audit( recovery_decision, journal, status="started", host_invoked=None, @@ -1995,5 +1987,6 @@ def finish_recovery(payload: dict[str, Any]) -> dict[str, Any]: settled=settled, epoch_metadata=epoch_metadata, plan=plan, journal_path=journal_path, goal_id=goal_id, settlement_lineage=settlement_lineage, options=quiet_options, + result=result, journal=journal, ) return finish_recovery(settled) diff --git a/loopx/control_plane/turn_driver/host_candidate.py b/loopx/control_plane/turn_driver/host_candidate.py index 21eb004f7b..9f317de720 100644 --- a/loopx/control_plane/turn_driver/host_candidate.py +++ b/loopx/control_plane/turn_driver/host_candidate.py @@ -329,15 +329,35 @@ def render_prompt(authority: Mapping[str, Any], *, allow_completion: bool = Fals """ model_input = authority.get("_model_input") - if isinstance(model_input, Mapping) and isinstance(model_input.get("epoch_prefetch"), Mapping): - from .epoch_prefetch import strip_internal_epoch_prefetch_audit_fields + raw_fold = model_input.get("semantic_unit_fold") if isinstance(model_input, Mapping) else None + if isinstance(model_input, Mapping) and ( + isinstance(model_input.get("epoch_prefetch"), Mapping) + or isinstance(raw_fold, Mapping) + ): + updated_model_input = dict(model_input) + if isinstance(model_input.get("epoch_prefetch"), Mapping): + from .epoch_prefetch import strip_internal_epoch_prefetch_audit_fields - model_input = { - **dict(model_input), - "epoch_prefetch": strip_internal_epoch_prefetch_audit_fields( + updated_model_input["epoch_prefetch"] = strip_internal_epoch_prefetch_audit_fields( model_input["epoch_prefetch"] - ), - } + ) + if isinstance(raw_fold, Mapping): + from .todo_unit_settlement import compact_semantic_unit_fold_wire_fields + + updated_model_input["semantic_unit_fold"] = ( + compact_semantic_unit_fold_wire_fields(raw_fold) + ) + model_input = updated_model_input + fold_instruction = "" + if isinstance(raw_fold, Mapping): + if raw_fold.get("operator") == "FoldToReceipt" and isinstance(raw_fold.get("replacement_text"), str): + fold_instruction = f"Todo Semantic-Unit Fold Receipt:\n{raw_fold['replacement_text']}\n\n" + elif raw_fold.get("operator") == "KeepRaw": + fold_instruction = ( + f"Todo semantic-unit fold kept raw context intact (KeepRaw: reason={raw_fold.get('fallback_reason')}; " + f"failure_facts={json.dumps(raw_fold.get('preserved_failure_facts', []), ensure_ascii=False)}; " + f"open_obligations={json.dumps(raw_fold.get('preserved_open_obligations', []), ensure_ascii=False)}).\n\n" + ) authority_json = json.dumps( model_input if model_input is not None else dict(authority), ensure_ascii=False, @@ -371,6 +391,7 @@ def render_prompt(authority: Mapping[str, Any], *, allow_completion: bool = Fals "evidence and reads grant no permissions. Do not write LoopX state, spend " "quota or apply scheduler changes; the outer Turn executor owns those effects.\n" + replan_prompt_instruction(detail, packet_path="detail_ref.replan_action_packet") + + fold_instruction + "Turn request:\n" + authority_json + "\n\n" ) else: @@ -430,6 +451,7 @@ def render_prompt(authority: Mapping[str, Any], *, allow_completion: bool = Fals f"{replan_instruction}" f"{acceptance_instruction}" f"{work_instruction}" + f"{fold_instruction}" f"Turn authority JSON:\n{authority_json}\n\n" ) return ( diff --git a/loopx/control_plane/turn_driver/quiet_turn_store.py b/loopx/control_plane/turn_driver/quiet_turn_store.py index 19c0f82ff8..ff60c409ac 100644 --- a/loopx/control_plane/turn_driver/quiet_turn_store.py +++ b/loopx/control_plane/turn_driver/quiet_turn_store.py @@ -1083,8 +1083,39 @@ def commit_turn_quiet_state_after_success( goal_id: str, settlement_lineage: Mapping[str, Any] | None, options: Mapping[str, Any], + result: Mapping[str, Any] | None = None, + journal: dict[str, Any] | None = None, ) -> None: - """Commit Quiet-Turn state_digest ONLY after the Turn has settled cleanly.""" + """Commit Quiet-Turn state_digest and opt-in Todo semantic-unit fold after settlement.""" + agent_id = effective_turn_agent_id(plan, settlement_lineage) + from .todo_unit_settlement import ( + commit_turn_semantic_unit_fold_after_settlement, + extract_semantic_unit_fold_option, + ) + + if extract_semantic_unit_fold_option( + options, + options.get("decision_capture_payload") + if isinstance(options.get("decision_capture_payload"), Mapping) + else None, + ) is not None: + raw_tx_obj = plan.get("transaction") + raw_tx = dict(raw_tx_obj) if isinstance(raw_tx_obj, Mapping) else {} + fold_outcome = commit_turn_semantic_unit_fold_after_settlement( + settled=settled, + result=result, + journal=journal, + plan=plan, + journal_path=journal_path, + goal_id=goal_id, + agent_id=agent_id, + turn_key=str(raw_tx.get("turn_key") or journal_path.stem), + settlement_lineage=settlement_lineage, + options=options, + ) + if fold_outcome is not None and isinstance(settled, dict): + settled["semantic_unit_fold"] = fold_outcome + if not epoch_metadata: return if settled.get("ok") is not True or settled.get("status") not in { @@ -1102,7 +1133,6 @@ def commit_turn_quiet_state_after_success( options.get("quiet_turn", False), options.get("decision_capture_payload"), ) - agent_id = effective_turn_agent_id(plan, settlement_lineage) goal_state_root = journal_path.parent.parent target = quiet_turn_target_params( plan=plan, diff --git a/loopx/control_plane/turn_driver/todo_unit_settlement.py b/loopx/control_plane/turn_driver/todo_unit_settlement.py new file mode 100644 index 0000000000..52ada5299f --- /dev/null +++ b/loopx/control_plane/turn_driver/todo_unit_settlement.py @@ -0,0 +1,999 @@ +"""Runtime Turn lifecycle wiring for opt-in Todo semantic-unit anchor, settlement fold, and prompt swap.""" +from __future__ import annotations + +from collections.abc import Callable, Mapping +from contextlib import closing +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import sqlite3 + +from ...file_lock import exclusive_file_lock +from ..quota.turn_envelope import record_semantic_unit_anchor +from .driver import selected_turn_todo +from .epoch_prefetch import ( + DEFAULT_TOKENIZER_ENCODING, + _HOST_WIRE_EXCLUDED_PREFETCH_FIELDS, + HostInputRenderer, + UNSET_HOST_INPUT_RENDERER, + _adjudicate_candidate_prompt_gate, + _apply_prompt_gate_audit_fields, + _resolve_active_host_renderer, + _safe_rendered_prompt, +) +from .quiet_turn_store import init_turn_prefetch_sqlite_db +from .semantic_unit_hook import _evaluate_semantic_unit_fold + + +SEMANTIC_UNIT_STORE_SCHEMA = "loopx_semantic_unit_settlement_store_v0" + + +def _now_iso() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _sha256_text(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def _stable_json(value: object) -> str: + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def _as_dict(value: object) -> dict[str, object]: + return {str(k): v for k, v in value.items()} if isinstance(value, Mapping) else {} + + +def _as_str_list(value: object) -> list[str]: + if not isinstance(value, (list, tuple)): + return [] + return [item for item in value if isinstance(item, str) and item.strip()] + + +def extract_semantic_unit_fold_option( + options: Mapping[str, object] | None, + decision_capture_payload: Mapping[str, object] | None = None, +) -> dict[str, object] | None: + """Return active opt-in semantic-unit fold configuration, or None when disabled.""" + candidates: list[object] = [] + if isinstance(options, Mapping): + candidates.append(options.get("semantic_unit_fold")) + ep = options.get("epoch_prefetch") + if isinstance(ep, Mapping): + candidates.append(ep.get("semantic_unit_fold")) + dc = options.get("decision_capture_payload") + if isinstance(dc, Mapping): + candidates.append(dc.get("semantic_unit_fold")) + dc_ep = dc.get("epoch_prefetch") + if isinstance(dc_ep, Mapping): + candidates.append(dc_ep.get("semantic_unit_fold")) + if isinstance(decision_capture_payload, Mapping): + candidates.append(decision_capture_payload.get("semantic_unit_fold")) + dc_ep = decision_capture_payload.get("epoch_prefetch") + if isinstance(dc_ep, Mapping): + candidates.append(dc_ep.get("semantic_unit_fold")) + for raw in candidates: + if isinstance(raw, Mapping) and raw.get("enabled") is True: + return _as_dict(raw) + return None + + +def _resolve_todo_and_epoch( + *, + plan: Mapping[str, object], + request: Mapping[str, object], + settlement_lineage: Mapping[str, object] | None, + goal_id: str, + turn_key: str, + fold_cfg: Mapping[str, object], +) -> tuple[str, str, str]: + envelope = _as_dict(plan.get("turn_envelope") or request.get("turn_envelope")) + selected = selected_turn_todo(envelope) if envelope else {} + todo_id = str( + fold_cfg.get("todo_id") + or (settlement_lineage or {}).get("todo_id") + or selected.get("todo_id") + or "" + ).strip() + turn_instance_id = str( + fold_cfg.get("turn_instance_id") + or (settlement_lineage or {}).get("turn_instance_id") + or turn_key + ).strip() + session = _as_dict(plan.get("session")) + context_epoch = str( + fold_cfg.get("context_epoch") + or session.get("context_epoch") + or f"goal:{goal_id}" + ).strip() + return todo_id, turn_instance_id, context_epoch + + +def compute_turn_parent_prefix_digest( + request: Mapping[str, object], + *, + goal_id: str, + agent_id: str, + context_epoch: str, + fold_cfg: Mapping[str, object] | None = None, + ignore_exploratory_todo_id: str | None = None, +) -> str: + """Compute a deterministic digest of the clean parent KV prefix Q before a Todo suffix.""" + if isinstance(fold_cfg, Mapping) and isinstance(fold_cfg.get("prefix_digest"), str): + candidate = str(fold_cfg["prefix_digest"]).strip() + if len(candidate) == 64: + return candidate + parent_prefix = ( + fold_cfg.get("parent_prefix") + if isinstance(fold_cfg, Mapping) and "parent_prefix" in fold_cfg + else request.get("parent_prefix") + ) + retained_items: list[object] = [] + raw_exp = request.get("exploratory_context") + if isinstance(raw_exp, list): + for item in raw_exp: + if isinstance(item, Mapping): + item_todo = str(item.get("todo_id") or "").strip() + if ignore_exploratory_todo_id and item_todo == ignore_exploratory_todo_id: + break + retained_items.append(item) + return _sha256_text( + _stable_json( + { + "goal_id": goal_id, + "agent_id": agent_id, + "context_epoch": context_epoch, + "parent_prefix": parent_prefix, + "retained_items": retained_items, + } + ) + ) + + +def _store_paths(goal_state_root: Path, scope_key: str) -> tuple[Path, Path]: + store_dir = goal_state_root / "semantic_unit_fold" + file_path = store_dir / f"{_sha256_text(scope_key)}.json" + sqlite_path = goal_state_root / "turn_prefetch_state.sqlite" + return file_path, sqlite_path + + +def _ensure_sqlite_table(connection: sqlite3.Connection) -> None: + init_turn_prefetch_sqlite_db(connection) + connection.execute( + """ + CREATE TABLE IF NOT EXISTS semantic_unit_fold_records ( + scope_key TEXT PRIMARY KEY, + state_json TEXT NOT NULL, + state_sha256 TEXT NOT NULL, + updated_at TEXT NOT NULL + ) + """ + ) + + +def _read_store_state(file_path: Path, sqlite_path: Path, scope_key: str) -> tuple[dict[str, object], bool]: + """Read File & SQLite semantic-unit state; fail closed on conflicting non-equal digests.""" + file_state: dict[str, object] | None = None + if file_path.exists(): + raw = json.loads(file_path.read_text(encoding="utf-8")) + if isinstance(raw, Mapping): + file_state = _as_dict(raw) + sqlite_state: dict[str, object] | None = None + if sqlite_path.exists(): + with closing(sqlite3.connect(sqlite_path, timeout=5.0)) as conn: + _ensure_sqlite_table(conn) + row = conn.execute( + "SELECT state_json, state_sha256 FROM semantic_unit_fold_records WHERE scope_key = ?", + (scope_key,), + ).fetchone() + if row is not None: + parsed = json.loads(row[0]) + if isinstance(parsed, Mapping) and _sha256_text(_stable_json(parsed)) == row[1]: + sqlite_state = _as_dict(parsed) + else: + return {}, True + if file_state is not None and sqlite_state is not None: + if _sha256_text(_stable_json(file_state)) != _sha256_text(_stable_json(sqlite_state)): + return {}, True + return file_state, False + if file_state is not None: + _write_sqlite_state(sqlite_path, scope_key, file_state) + return file_state, False + if sqlite_state is not None: + _write_file_state(file_path, sqlite_state) + return sqlite_state, False + return { + "schema_version": SEMANTIC_UNIT_STORE_SCHEMA, + "scope_key": scope_key, + "anchors": {}, + "folds": {}, + "latest_committed_fold": None, + }, False + + +def _write_file_state(file_path: Path, state: Mapping[str, object]) -> None: + file_path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = file_path.with_name(f".{file_path.name}.tmp.{os.getpid()}") + tmp_path.write_text(json.dumps(dict(state), ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8") + os.chmod(tmp_path, 0o600) + os.replace(tmp_path, file_path) + + +def _write_sqlite_state(sqlite_path: Path, scope_key: str, state: Mapping[str, object]) -> None: + sqlite_path.parent.mkdir(parents=True, exist_ok=True) + encoded = _stable_json(dict(state)) + digest = _sha256_text(encoded) + with closing(sqlite3.connect(sqlite_path, timeout=5.0, isolation_level=None)) as conn: + _ensure_sqlite_table(conn) + conn.execute("BEGIN IMMEDIATE") + try: + conn.execute( + """ + INSERT INTO semantic_unit_fold_records (scope_key, state_json, state_sha256, updated_at) + VALUES (?, ?, ?, ?) + ON CONFLICT(scope_key) DO UPDATE SET + state_json = excluded.state_json, + state_sha256 = excluded.state_sha256, + updated_at = excluded.updated_at + """, + (scope_key, encoded, digest, _now_iso()), + ) + conn.execute("COMMIT") + except BaseException: + if conn.in_transaction: + conn.execute("ROLLBACK") + raise + + +def _save_store_state( + file_path: Path, sqlite_path: Path, scope_key: str, state: Mapping[str, object], +) -> None: + _write_file_state(file_path, state) + _write_sqlite_state(sqlite_path, scope_key, state) + + +def _sync_codex_context_if_configured( + *, + plan: Mapping[str, object], + fold_cfg: Mapping[str, object], + event_fields: Mapping[str, object], +) -> None: + codex_dir = fold_cfg.get("codex_context_dir") or plan.get("codex_context_dir") + session_id = fold_cfg.get("session_id") or _as_dict(plan.get("session")).get("session_id") + cwd = fold_cfg.get("cwd") or _as_dict(plan.get("session")).get("cwd") + if not (isinstance(codex_dir, str) and codex_dir and isinstance(session_id, str) and session_id): + return + if not (isinstance(cwd, str) and cwd): + return + from .codex_context import codex_context_hook + + codex_context_hook( + codex_dir, + { + "session_id": session_id, + "cwd": cwd, + "hook_event_name": "PostToolUse", + **dict(event_fields), + }, + ) + + +_HOST_WIRE_EXCLUDED_FOLD_TEXT_FIELDS = frozenset({ + "replacement_text", + "receipt_mu", + "obs_next_cmd", + "preserved_failure_facts", + "preserved_open_obligations", + "error_observation", +}) + + +def strip_internal_semantic_unit_fold_audit_fields( + fold_receipt: Mapping[str, object], +) -> dict[str, object]: + """Keep host model-input semantic_unit_fold free of internal persistence audit blobs.""" + excluded = { + "persistence", + "anchor_recorded", + "covered_exploratory_digests", + *_HOST_WIRE_EXCLUDED_PREFETCH_FIELDS, + } + return { + str(k): v + for k, v in fold_receipt.items() + if str(k) not in excluded + } + + +def compact_semantic_unit_fold_wire_fields( + fold_receipt: Mapping[str, object], +) -> dict[str, object]: + """Strip internal audit telemetry and large text blobs before JSON wire rendering.""" + return { + key: value + for key, value in strip_internal_semantic_unit_fold_audit_fields(fold_receipt).items() + if key not in _HOST_WIRE_EXCLUDED_FOLD_TEXT_FIELDS + } + + +def _is_bound_exploratory_item(item: object, folded_todo_id: str) -> bool: + return ( + bool(folded_todo_id) + and isinstance(item, Mapping) + and item.get("replaced_by_semantic_unit_fold") is not True + and str(item.get("todo_id") or "").strip() == folded_todo_id + ) + + +def _partition_exploratory_context_for_fold( + request: Mapping[str, object], + folded_todo_id: str, +) -> tuple[bool, object, str]: + """Return `(has_folded_inline, replaced_exploratory_context, baseline_inline_text)`.""" + if "exploratory_context" not in request: + return False, None, "" + raw_exp = request["exploratory_context"] + if not folded_todo_id: + return False, raw_exp, "" + if isinstance(raw_exp, list): + folded_items = [item for item in raw_exp if _is_bound_exploratory_item(item, folded_todo_id)] + if not folded_items: + return False, raw_exp, "" + retained_items = [item for item in raw_exp if not _is_bound_exploratory_item(item, folded_todo_id)] + return True, retained_items, _stable_json(folded_items) + if isinstance(raw_exp, Mapping): + if _is_bound_exploratory_item(raw_exp, folded_todo_id): + return True, None, _stable_json(raw_exp) + return False, raw_exp, "" + return False, raw_exp, "" + + +def _covered_exploratory_digests( + *, + recorded_baseline: object, + request: Mapping[str, object], + todo_id: str, +) -> list[str]: + """Return ordered SHA-256 digests for Turn 1 exploratory items bound to todo_id.""" + source_json = recorded_baseline if isinstance(recorded_baseline, str) and recorded_baseline else "" + if not source_json: + has_inline, _, inline_text = _partition_exploratory_context_for_fold(request, todo_id) + if not has_inline or not inline_text: + return [] + source_json = inline_text + try: + parsed = json.loads(source_json) + except json.JSONDecodeError: + return [] + if isinstance(parsed, list): + return [_sha256_text(_stable_json(item)) for item in parsed] + if isinstance(parsed, Mapping): + return [_sha256_text(_stable_json(parsed))] + return [] + + +def _partition_for_covered_fold_span( + request: Mapping[str, object], + folded_todo_id: str, + covered_digests_raw: object, +) -> tuple[bool, object, str, bool]: + """Replace only the exact ordered span covered by Turn 1's receipt; flag unclear/late mismatches.""" + if "exploratory_context" not in request: + return False, None, "", False + raw_exp = request["exploratory_context"] + if not folded_todo_id: + return False, raw_exp, "", False + covered_digests: list[str] | None = ( + [ + digest + for digest in covered_digests_raw + if isinstance(digest, str) and len(digest) == 64 + ] + if isinstance(covered_digests_raw, list) + else None + ) + if ( + covered_digests is not None + and isinstance(covered_digests_raw, list) + and len(covered_digests) != len(covered_digests_raw) + ): + covered_digests = None + if isinstance(raw_exp, list): + bound_positions = [ + idx for idx, item in enumerate(raw_exp) if _is_bound_exploratory_item(item, folded_todo_id) + ] + if not bound_positions: + return False, raw_exp, "", False + if not covered_digests: + return True, raw_exp, "", True + span_len = len(covered_digests) + start = bound_positions[0] + end = start + span_len + if end > len(raw_exp) or any( + not _is_bound_exploratory_item(raw_exp[i], folded_todo_id) for i in range(start, end) + ): + return True, raw_exp, "", True + span_items = raw_exp[start:end] + if [_sha256_text(_stable_json(item)) for item in span_items] != covered_digests: + return True, raw_exp, "", True + retained_items = [*raw_exp[:start], *raw_exp[end:]] + return True, retained_items, _stable_json(span_items), False + if isinstance(raw_exp, Mapping): + if not _is_bound_exploratory_item(raw_exp, folded_todo_id): + return False, raw_exp, "", False + if ( + covered_digests is not None + and len(covered_digests) == 1 + and _sha256_text(_stable_json(raw_exp)) == covered_digests[0] + ): + return True, None, _stable_json(raw_exp), False + return True, raw_exp, "", True + return False, raw_exp, "", False + + +def _render_candidate_prompt( + request: Mapping[str, object], + *, + renderer: HostInputRenderer | None, +) -> str | None: + return _safe_rendered_prompt(request, renderer=renderer) + + +def _semantic_unit_prompt_gate_policy( + fold_cfg: Mapping[str, object], + latest_fold: Mapping[str, object], + *, + encoding_name: str, + replace_inline: bool, +) -> dict[str, object]: + """Build Stage-then-Swap prompt gate policy using current turn overrides and settled floor.""" + policy: dict[str, object] = { + "enabled": True, + "replace_exploratory_context": replace_inline, + "tokenizer_encoding": encoding_name, + } + for key in ("min_net_savings_bytes", "min_net_savings_tokens", "cold_prefill_amortization_tokens"): + if key in fold_cfg and fold_cfg.get(key) is not None: + policy[key] = fold_cfg[key] + elif key == "min_net_savings_tokens" and latest_fold.get(key) is not None: + policy[key] = latest_fold[key] + return policy + + +def _apply_fold_to_next_request( + *, + request: Mapping[str, object], + latest_fold: Mapping[str, object], + fold_cfg: Mapping[str, object], + goal_id: str, + agent_id: str, + context_epoch: str, + conflict_reason: str | None, + renderer: HostInputRenderer | None, + token_counter: Callable[[str], int] | None = None, +) -> tuple[dict[str, object], dict[str, object]]: + """Project verified FoldToReceipt into Turn 2's request or fail closed to KeepRaw.""" + folded_todo = str(latest_fold.get("todo_id") or "") + has_inline, retained_exp, inline_text, scope_mismatch = _partition_for_covered_fold_span( + request, + folded_todo, + latest_fold.get("covered_exploratory_digests"), + ) + failure_facts = _as_str_list(latest_fold.get("preserved_failure_facts")) + open_obligations = _as_str_list(latest_fold.get("preserved_open_obligations")) + + def keep_raw( + reason: str, + *, + gate_audit: Mapping[str, object] | None = None, + ) -> tuple[dict[str, object], dict[str, object]]: + receipt_mu = _as_dict(latest_fold.get("receipt_mu")) + keep_payload: dict[str, object] = { + "schema_version": str(latest_fold.get("schema_version") or "loopx_semantic_unit_fold_swap_v0"), + "operator": "KeepRaw", + "status": "fallback_keep_raw", + "fallback_reason": reason, + "preserves_raw_state": True, + "preserves_prefix_kv": True, + "todo_id": folded_todo, + "turn_instance_id": str(latest_fold.get("turn_instance_id") or ""), + "context_epoch": context_epoch, + "prefix_digest": latest_fold.get("prefix_digest"), + "preserved_failure_facts": failure_facts or _as_str_list(receipt_mu.get("failure_facts")), + "preserved_open_obligations": open_obligations or _as_str_list(receipt_mu.get("open_obligations")), + "error_observation": ( + str(gate_audit["error_observation"]) + if isinstance(gate_audit, Mapping) and isinstance(gate_audit.get("error_observation"), str) and gate_audit.get("error_observation") + else f"Todo semantic-unit fold kept raw context ({reason})." + ), + } + if isinstance(gate_audit, Mapping): + _apply_prompt_gate_audit_fields(keep_payload, gate_audit, include_delivered_metrics=False) + updated = dict(request) + updated["semantic_unit_fold"] = keep_payload + return keep_payload, updated + + if conflict_reason is not None: + return keep_raw(conflict_reason) + if latest_fold.get("operator") != "FoldToReceipt": + return keep_raw(str(latest_fold.get("fallback_reason") or "fold_not_committed")) + if latest_fold.get("context_epoch") != context_epoch: + return keep_raw("context_epoch_mismatch") + live_prefix = compute_turn_parent_prefix_digest( + request, + goal_id=goal_id, + agent_id=agent_id, + context_epoch=context_epoch, + fold_cfg=fold_cfg, + ignore_exploratory_todo_id=folded_todo, + ) + if live_prefix != latest_fold.get("prefix_digest"): + return keep_raw("prefix_digest_mismatch") + if scope_mismatch: + return keep_raw("source_digest_mismatch") + + replace_inline = fold_cfg.get("replace_exploratory_context", True) is not False + if has_inline and not replace_inline: + return keep_raw("negative_net_savings") + + receipt_mu = _as_dict(latest_fold.get("receipt_mu")) + fold_marker = { + "replaced_by_semantic_unit_fold": True, + "todo_id": folded_todo, + "completion_receipt_id": receipt_mu.get("completion_receipt_id"), + "source_ref": receipt_mu.get("source_ref"), + } + candidate = dict(request) + if has_inline: + if isinstance(retained_exp, list): + candidate["exploratory_context"] = [*retained_exp, fold_marker] + else: + candidate["exploratory_context"] = fold_marker + projected_fold: dict[str, object] = { + "schema_version": latest_fold.get("schema_version"), + "operator": "FoldToReceipt", + "status": "committed", + "trust_level": "tool", + "preserves_raw_state": False, + "preserves_prefix_kv": True, + "todo_id": folded_todo, + "turn_instance_id": latest_fold.get("turn_instance_id"), + "context_epoch": context_epoch, + "prefix_digest": live_prefix, + "reclaim_range": latest_fold.get("reclaim_range"), + "receipt_mu": receipt_mu, + "obs_next_cmd": latest_fold.get("obs_next_cmd"), + "replacement_text": latest_fold.get("replacement_text"), + "preserved_failure_facts": failure_facts, + "preserved_open_obligations": open_obligations, + "receipt_sha256": latest_fold.get("receipt_sha256"), + "replayed": True, + } + candidate["semantic_unit_fold"] = projected_fold + + encoding_name = str(fold_cfg.get("tokenizer_encoding") or DEFAULT_TOKENIZER_ENCODING) + raw_prompt = _render_candidate_prompt(request, renderer=renderer) + folded_prompt = _render_candidate_prompt(candidate, renderer=renderer) + if has_inline: + gate_policy = _semantic_unit_prompt_gate_policy( + fold_cfg, + latest_fold, + encoding_name=encoding_name, + replace_inline=replace_inline, + ) + adjudicated: dict[str, object] | None = None + stabilized = False + for _ in range(3): + adjudicated_raw, _, _ = _adjudicate_candidate_prompt_gate( + policy_cfg=gate_policy, + encoding_name=encoding_name, + token_counter=token_counter, + raw_prompt=raw_prompt, + epoch_prompt=folded_prompt, + has_inline_exploratory=True, + replace_exploratory_context=replace_inline, + ext_bytes=None, + ext_tokens=None, + potential_saved=0, + host_input_measurable=raw_prompt is not None and folded_prompt is not None, + ) + adjudicated = _as_dict(adjudicated_raw) + if adjudicated.get("operator") != "EpochReset": + return keep_raw( + str(adjudicated.get("fallback_reason") or "negative_net_savings"), + gate_audit=adjudicated, + ) + _apply_prompt_gate_audit_fields(projected_fold, adjudicated) + final_prompt = _render_candidate_prompt(candidate, renderer=renderer) + if final_prompt is None: + folded_prompt = None + continue + if final_prompt == folded_prompt: + stabilized = True + break + folded_prompt = final_prompt + if not stabilized: + return keep_raw("host_input_unmeasurable", gate_audit=adjudicated) + elif inline_text: + projected_fold["net_savings_tokens"] = latest_fold.get("net_savings_tokens") + return projected_fold, candidate + + +def prepare_turn_semantic_unit_context( + *, + plan: Mapping[str, object], + request: Mapping[str, object], + journal_path: Path, + goal_id: str, + agent_id: str, + turn_key: str, + settlement_lineage: Mapping[str, object] | None, + options: Mapping[str, object], + existing_journal: Mapping[str, object] | None, + needs_host: bool, +) -> tuple[dict[str, object] | None, dict[str, object]]: + """Opt-in Turn-launch seam: apply prior committed Todo fold cleanly & anchor current Todo.""" + fold_cfg = extract_semantic_unit_fold_option( + options, + _as_dict(options.get("decision_capture_payload")) or None, + ) + if fold_cfg is None: + return None, dict(request) + + todo_id, turn_instance_id, context_epoch = _resolve_todo_and_epoch( + plan=plan, + request=request, + settlement_lineage=settlement_lineage, + goal_id=goal_id, + turn_key=turn_key, + fold_cfg=fold_cfg, + ) + scope_key = f"turn_driver:{goal_id}:{agent_id}:{context_epoch}" + goal_state_root = journal_path.parent.parent + file_path, sqlite_path = _store_paths(goal_state_root, scope_key) + + conflict_reason: str | None = None + if isinstance(existing_journal, Mapping) and existing_journal.get("status") in {"failed", "scheduler_action_required"}: + conflict_reason = "recovery_conflict" + elif isinstance(plan.get("unsettled_host_turn_recovery"), Mapping): + conflict_reason = "recovery_conflict" + elif fold_cfg.get("quiescent_boundary") is False or fold_cfg.get("tool_in_flight") or fold_cfg.get("unpaired_tool_calls"): + conflict_reason = "non_quiescent_boundary" + + host = str(options.get("host") or _as_dict(plan.get("host")).get("kind") or "") + host_renderer_opt = options.get("host_input_renderer", UNSET_HOST_INPUT_RENDERER) + renderer = _resolve_active_host_renderer( + host=host, + host_input_renderer=host_renderer_opt, + ) + updated_request = dict(request) + if "parent_prefix" not in updated_request: + if "parent_prefix" in fold_cfg: + updated_request["parent_prefix"] = fold_cfg["parent_prefix"] + elif "parent_prefix" in plan: + updated_request["parent_prefix"] = plan["parent_prefix"] + if "exploratory_context" not in updated_request: + if "exploratory_context" in fold_cfg: + updated_request["exploratory_context"] = fold_cfg["exploratory_context"] + elif "exploratory_context" in plan: + updated_request["exploratory_context"] = plan["exploratory_context"] + metadata: dict[str, object] = {} + + with exclusive_file_lock(file_path, operation="semantic_unit_prepare"): + state, store_conflict = _read_store_state(file_path, sqlite_path, scope_key) + if store_conflict and conflict_reason is None: + conflict_reason = "store_digest_conflict" + existing_fold = ( + _as_dict(existing_journal.get("semantic_unit_fold")) + if isinstance(existing_journal, Mapping) and isinstance(existing_journal.get("semantic_unit_fold"), Mapping) + else None + ) + latest_fold = existing_fold or ( + _as_dict(state.get("latest_committed_fold")) + if isinstance(state.get("latest_committed_fold"), Mapping) + else None + ) + if latest_fold is not None and ( + not todo_id or str(latest_fold.get("todo_id") or "") != todo_id + ): + projected_fold, updated_request = _apply_fold_to_next_request( + request=updated_request, + latest_fold=latest_fold, + fold_cfg=fold_cfg, + goal_id=goal_id, + agent_id=agent_id, + context_epoch=context_epoch, + conflict_reason=conflict_reason, + renderer=renderer, + ) + metadata["semantic_unit_fold"] = projected_fold + + if needs_host and todo_id and conflict_reason is None: + anchor_step_raw = fold_cfg.get("anchor_step_index") + anchors_map = _as_dict(state.get("anchors")) + baselines_map = _as_dict(state.get("anchor_baselines")) + next_step_guess = ( + int(anchor_step_raw) + if isinstance(anchor_step_raw, int) and not isinstance(anchor_step_raw, bool) and anchor_step_raw >= 0 + else len(anchors_map) + 1 + ) + anchor_digest = compute_turn_parent_prefix_digest( + updated_request, + goal_id=goal_id, + agent_id=agent_id, + context_epoch=context_epoch, + fold_cfg=fold_cfg, + ignore_exploratory_todo_id=todo_id, + ) + anchor = record_semantic_unit_anchor( + todo_id=todo_id, + turn_instance_id=turn_instance_id, + anchor_step_index=next_step_guess, + prefix_digest=anchor_digest, + context_epoch=context_epoch, + goal_id=goal_id, + agent_id=agent_id, + ) + _, _, inline_exp_text = _partition_exploratory_context_for_fold(updated_request, todo_id) + if inline_exp_text: + baselines_map[todo_id] = inline_exp_text + state["anchor_baselines"] = baselines_map + anchors_map[todo_id] = anchor + state["anchors"] = anchors_map + _save_store_state(file_path, sqlite_path, scope_key, state) + metadata["semantic_unit_anchor"] = anchor + _sync_codex_context_if_configured( + plan=plan, + fold_cfg=fold_cfg, + event_fields={"semantic_unit_anchor": anchor}, + ) + return metadata or None, updated_request + + +def _write_immutable_completion_source_file( + goal_state_root: Path, + *, + turn_key: str, + completion_record: Mapping[str, object], +) -> dict[str, str]: + receipts_dir = goal_state_root / "semantic_unit_fold" / "receipts" + receipts_dir.mkdir(parents=True, exist_ok=True) + receipt_path = receipts_dir / f"{_sha256_text(turn_key)}.json" + if not receipt_path.exists(): + tmp = receipt_path.with_name(f".{receipt_path.name}.tmp.{os.getpid()}") + tmp.write_text(json.dumps(dict(completion_record), ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8") + os.chmod(tmp, 0o600) + os.replace(tmp, receipt_path) + return {"path": str(receipt_path), "sha256": hashlib.sha256(receipt_path.read_bytes()).hexdigest()} + + +def _build_settlement_fold_request( + *, + fold_cfg: Mapping[str, object], + settled: Mapping[str, object], + result: Mapping[str, object], + journal: Mapping[str, object], + goal_state_root: Path, + goal_id: str, + agent_id: str, + todo_id: str, + turn_instance_id: str, + turn_key: str, + context_epoch: str, + anchor: Mapping[str, object] | None, + recorded_baseline: object, +) -> tuple[dict[str, object], str, str]: + writeback = _as_dict(journal.get("writeback")) + completion = _as_dict(writeback.get("completion")) + receipt_id = str( + completion.get("event_id") + or _as_dict(journal.get("settlement_result")).get("effect_id") + or turn_key + ).strip() + completion_record = { + "goal_id": goal_id, + "agent_id": agent_id, + "todo_id": todo_id, + "turn_instance_id": turn_instance_id, + "turn_key": turn_key, + "completion_receipt_id": receipt_id, + "summary": result.get("summary"), + "work_evidence": result.get("work_evidence"), + "validation_evidence": result.get("validation_evidence"), + } + explicit_source = fold_cfg.get("source_ref") + source_ref = ( + {str(k): str(v) for k, v in explicit_source.items()} + if isinstance(explicit_source, Mapping) + and isinstance(explicit_source.get("path"), str) + and isinstance(explicit_source.get("sha256"), str) + else _write_immutable_completion_source_file( + goal_state_root, turn_key=turn_key, completion_record=completion_record, + ) + ) + failure_facts = _as_str_list(fold_cfg.get("failure_facts")) + open_obligations = _as_str_list(fold_cfg.get("open_obligations")) + completion_receipt: dict[str, object] | None = ( + None + if fold_cfg.get("completion_receipt") is False + else _as_dict(fold_cfg["completion_receipt"]) + if isinstance(fold_cfg.get("completion_receipt"), Mapping) + else { + "todo_id": todo_id, + "completion_receipt_id": receipt_id, + "exit_code": 0, + "sha256": _sha256_text(_stable_json(completion_record)), + "failure_facts": failure_facts, + "open_obligations": open_obligations, + "source_ref": source_ref, + } + ) + baseline_text = fold_cfg.get("baseline_text") + if not isinstance(baseline_text, str): + baseline_text = _stable_json( + { + "anchored_baseline": recorded_baseline if isinstance(recorded_baseline, str) else "", + "summary": result.get("summary") or "", + "work_evidence": result.get("work_evidence") or [], + "validation_evidence": result.get("validation_evidence") or [], + "exploratory_suffix": fold_cfg.get("exploratory_suffix") or "", + } + ) + anchor_step_raw = anchor.get("anchor_step_index") if anchor else None + anchor_step = ( + anchor_step_raw + if isinstance(anchor_step_raw, int) and not isinstance(anchor_step_raw, bool) + else 0 + ) + now_step_raw = fold_cfg.get("now_step_index") + now_step = ( + int(now_step_raw) + if isinstance(now_step_raw, int) and not isinstance(now_step_raw, bool) + else anchor_step + 1 + ) + prefix_digest = ( + str(anchor["prefix_digest"]) + if anchor and isinstance(anchor.get("prefix_digest"), str) + else compute_turn_parent_prefix_digest( + _as_dict(journal.get("request")), + goal_id=goal_id, + agent_id=agent_id, + context_epoch=context_epoch, + fold_cfg=fold_cfg, + ignore_exploratory_todo_id=todo_id, + ) + ) + fold_eval_req: dict[str, object] = { + **dict(fold_cfg), + "todo_id": todo_id, + "turn_instance_id": turn_instance_id, + "prefix_digest": prefix_digest, + "now_step_index": now_step, + "baseline_text": baseline_text, + "completion_receipt": completion_receipt, + } + return fold_eval_req, receipt_id, f"{todo_id}:{turn_instance_id}:{receipt_id}:{context_epoch}" + + +def commit_turn_semantic_unit_fold_after_settlement( + *, + settled: Mapping[str, object], + result: Mapping[str, object] | None, + journal: dict[str, object] | None, + plan: Mapping[str, object], + journal_path: Path, + goal_id: str, + agent_id: str, + turn_key: str, + settlement_lineage: Mapping[str, object] | None, + options: Mapping[str, object], +) -> dict[str, object] | None: + """Commit Todo FoldToReceipt only after real Todo completion settlement succeeds cleanly.""" + fold_cfg = extract_semantic_unit_fold_option( + options, + _as_dict(options.get("decision_capture_payload")) or None, + ) + if fold_cfg is None: + return None + if not ( + settled.get("ok") is True + and settled.get("status") in {"committed", "scheduler_action_required"} + and isinstance(result, Mapping) + and result.get("result_kind") == "validated_completion" + and isinstance(journal, dict) + and isinstance(journal.get("writeback"), Mapping) + and _as_dict(journal.get("writeback")).get("ok") is True + and _as_dict(settled.get("effects")).get("quota_spent") is True + and not journal.get("host_recovery") + and not journal.get("host_failure") + ): + return None + + todo_id, turn_instance_id, context_epoch = _resolve_todo_and_epoch( + plan=plan, + request=_as_dict(journal.get("request")), + settlement_lineage=settlement_lineage, + goal_id=goal_id, + turn_key=turn_key, + fold_cfg=fold_cfg, + ) + if not todo_id: + return None + + scope_key = f"turn_driver:{goal_id}:{agent_id}:{context_epoch}" + goal_state_root = journal_path.parent.parent + file_path, sqlite_path = _store_paths(goal_state_root, scope_key) + + with exclusive_file_lock(file_path, operation="semantic_unit_settle"): + state, store_conflict = _read_store_state(file_path, sqlite_path, scope_key) + if store_conflict: + return None + anchors_map = _as_dict(state.get("anchors")) + baselines_map = _as_dict(state.get("anchor_baselines")) + anchor = _as_dict(anchors_map.get(todo_id)) if isinstance(anchors_map.get(todo_id), Mapping) else None + recorded_baseline = baselines_map.get(todo_id) + fold_eval_req, _, replay_key = _build_settlement_fold_request( + fold_cfg=fold_cfg, + settled=settled, + result=result, + journal=journal, + goal_state_root=goal_state_root, + goal_id=goal_id, + agent_id=agent_id, + todo_id=todo_id, + turn_instance_id=turn_instance_id, + turn_key=turn_key, + context_epoch=context_epoch, + anchor=anchor, + recorded_baseline=recorded_baseline, + ) + covered_digests = _covered_exploratory_digests( + recorded_baseline=recorded_baseline, + request=_as_dict(journal.get("request")), + todo_id=todo_id, + ) + folds_map = _as_dict(state.get("folds")) + if isinstance(folds_map.get(replay_key), Mapping): + outcome = {**_as_dict(folds_map[replay_key]), "replayed": True, "executed": False} + return outcome + + quiescent = ( + fold_cfg.get("quiescent_boundary", True) is not False + and not bool(fold_cfg.get("tool_in_flight")) + and not bool(fold_cfg.get("unpaired_tool_calls")) + ) + outcome = _evaluate_semantic_unit_fold( + fold_req=fold_eval_req, + anchor=anchor, + todo_id=todo_id, + turn_instance_id=turn_instance_id, + context_epoch=context_epoch, + quiescent=quiescent, + cwd=fold_cfg.get("cwd") or _as_dict(plan.get("session")).get("cwd"), + token_counter=None, + ) + if outcome.get("operator") == "FoldToReceipt": + outcome = {**outcome, "covered_exploratory_digests": covered_digests} + state["latest_committed_fold"] = outcome + if outcome.get("operator") == "FoldToReceipt": + folds_map[replay_key] = outcome + state["folds"] = folds_map + anchors_map.pop(todo_id, None) + baselines_map.pop(todo_id, None) + state["anchors"] = anchors_map + state["anchor_baselines"] = baselines_map + _sync_codex_context_if_configured( + plan=plan, + fold_cfg=fold_cfg, + event_fields={ + "semantic_unit_fold": { + **fold_eval_req, + "anchor": anchor, + "obs_next_cmd": outcome.get("obs_next_cmd"), + } + }, + ) + _save_store_state(file_path, sqlite_path, scope_key, state) + return outcome diff --git a/packages/dsh-loopx-plugin/src/driver.ts b/packages/dsh-loopx-plugin/src/driver.ts index 0bae1167e2..8905e8a0d5 100644 --- a/packages/dsh-loopx-plugin/src/driver.ts +++ b/packages/dsh-loopx-plugin/src/driver.ts @@ -6,12 +6,13 @@ import type { Agent, AgentStatus, PreStepDecision } from '@deepseek-ai/dsh-agent import type {} from '@deepseek-ai/dsh-commands' import type {} from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-session' -import type { SessionEvent, UserMessage } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionSeq, UserMessage } from '@deepseek-ai/dsh-session' import { LoopXCliError, cliErrorFields, coreRouteBin, resolveLoopXCommand, + runFile, runJsonCommand, supportedLoopXVersion, } from './cli.ts' @@ -30,6 +31,9 @@ import type { } from './goalbar/protocol.ts' import { applyTodoUnitFoldAndPrefetch, + createDefaultDshObsRunner, + decodeQuotaSettlementReadback, + extractTodoIdFromQuotaAndHeartbeat, hasValidDshToolCallPairing, recordDshTodoUnitAnchor, validateTodoUnitObsForExecution, @@ -121,12 +125,28 @@ interface Reservation extends Binding { preserveAcrossPause: boolean } +interface ActiveTodoUnitState { + readonly goalId: string + readonly agentId: string + readonly todoId?: string | undefined + readonly turnInstanceId: string + readonly contextEpoch: string + readonly startStepIndex: number + endStepIndex: number + anchor?: TodoUnitAnchor | undefined + admittedSeq?: SessionSeq | undefined + completedCleanly?: boolean | undefined +} + interface SessionDriverRetention { readonly agent: Agent paused: boolean goalBarPaused?: boolean admissionFailure?: GoalBarAdmissionFailureCategoryV1 | undefined reservation?: Reservation | undefined + todoUnitContextEpoch?: string | undefined + todoUnitStepCount?: number | undefined + activeTodoUnit?: ActiveTodoUnitState | undefined todoUnitAnchors?: Map | undefined todoUnitFolds?: Map | undefined } @@ -187,6 +207,7 @@ interface QueuePlan extends Binding { readonly turnInstanceId: string readonly taskBody: string readonly selectionRequired: boolean + readonly todoId?: string | undefined } interface WaitPlan { @@ -635,6 +656,7 @@ async function readQuotaCapture( reference: string, options: QuotaReadOptions, revalidateOnly: boolean, + includeSelectedTodo = false, ): Promise> { // Entering a queued step requires the original Turn receipt. The scheduler // and reward memory are only used when first deciding whether to queue work. @@ -651,7 +673,10 @@ async function readQuotaCapture( if (!QUOTA_REQUIRED_POINTERS.every(pointer => present.has(pointer))) { throw new LoopXCliError('invalid_schema', 'LoopX quota capture lacks admission fields', false) } - pointers = [...QUOTA_REQUIRED_POINTERS, ...QUOTA_OPTIONAL_POINTERS.filter(pointer => present.has(pointer))] + const optional = includeSelectedTodo + ? [...QUOTA_OPTIONAL_POINTERS, '/selected_todo'] + : QUOTA_OPTIONAL_POINTERS + pointers = [...QUOTA_REQUIRED_POINTERS, ...optional.filter(pointer => present.has(pointer))] } const selected = await readQuotaSelections( command, reference, pointers.flatMap(pointer => ['--select', pointer]), QUOTA_SELECTION_SCHEMA, options, @@ -889,11 +914,15 @@ export class LoopXContinuationDriver { this.onAdmissionChange = options.onAdmissionChange this.todoUnitFold = options.todoUnitFold this.runObsCommand = options.runObsCommand + ?? (options.todoUnitFold?.enabled === true + ? createDefaultDshObsRunner(options.runner ?? runFile) + : undefined) } /** Record a Todo semantic-unit anchor pinning parent KV prefix Q before exploratory steps. */ anchorTodoUnit(agent: Agent, input: TodoUnitAnchorInput): TodoUnitAnchor | null { if (this.todoUnitFold?.enabled !== true) return null + if (typeof agent.session.deriveMessages !== 'function') return null const anchor = recordDshTodoUnitAnchor(agent.session, input) const retained = retainedState(agent, agent.session) retained.todoUnitAnchors ??= new Map() @@ -1004,8 +1033,12 @@ export class LoopXContinuationDriver { state.schedulerToken = '' state.unchangedPolls = 0 state.commands.clear() - retainedState(agent, agent.session).todoUnitAnchors?.clear() - retainedState(agent, agent.session).todoUnitFolds?.clear() + const retained = retainedState(agent, agent.session) + retained.todoUnitAnchors?.clear() + retained.todoUnitFolds?.clear() + retained.activeTodoUnit = undefined + retained.todoUnitContextEpoch = undefined + retained.todoUnitStepCount = 0 state.activation = foldSessionActivation(agent.session) this.requestEvaluation(state) } @@ -1163,12 +1196,30 @@ export class LoopXContinuationDriver { && state.reservation !== undefined && event.data.id === state.reservation.messageId) { state.reservation.phase = 'admitted' + const retained = retainedState(agent, agent.session) + if (retained.activeTodoUnit?.turnInstanceId === state.reservation.turnInstanceId) { + retained.activeTodoUnit.admittedSeq = event.seq + } return } - if (event.type === 'turn/end' - && (event.data.reason.kind === 'max-tokens' || event.data.reason.kind === 'aborted')) { - this.setErrorPause(state, true) - this.cancelPending(state) + if (event.type === 'user/message' && event.data.source?.kind === 'user') { + retainedState(agent, agent.session).activeTodoUnit = undefined + } + if (event.type === 'step/start') { + const retained = retainedState(agent, agent.session) + retained.todoUnitStepCount = (retained.todoUnitStepCount ?? 0) + 1 + } + if (event.type === 'turn/end') { + const retained = retainedState(agent, agent.session) + const active = retained.activeTodoUnit + if (active !== undefined && active.completedCleanly === undefined) { + active.endStepIndex = Math.max(active.startStepIndex, retained.todoUnitStepCount ?? active.startStepIndex) + active.completedCleanly = event.data.reason.kind === 'completed' + } + if (event.data.reason.kind === 'max-tokens' || event.data.reason.kind === 'aborted') { + this.setErrorPause(state, true) + this.cancelPending(state) + } } } @@ -1462,6 +1513,30 @@ export class LoopXContinuationDriver { this.clearAdmissionFailure(state) if (!this.ready(state) || state.agent.session !== plan.session) return true const message = automaticMessage(plan) + if (this.todoUnitFold?.enabled === true) { + const retained = retainedState(state.agent, plan.session) + const contextEpoch = retained.todoUnitContextEpoch + ??= `dsh:${plan.session.header.id}:${randomUUID()}` + const startStepIndex = retained.todoUnitStepCount ?? 0 + const anchor = plan.todoId !== undefined + ? this.anchorTodoUnit(state.agent, { + todoId: plan.todoId, + turnInstanceId: plan.turnInstanceId, + contextEpoch, + anchorStepIndex: startStepIndex, + }) + : null + retained.activeTodoUnit = { + goalId: plan.goalId, + agentId: plan.agentId, + todoId: plan.todoId, + turnInstanceId: plan.turnInstanceId, + contextEpoch, + startStepIndex, + endStepIndex: startStepIndex, + anchor: anchor ?? undefined, + } + } const reservation: Reservation = { messageId: message.id, content: message.content, @@ -1477,6 +1552,15 @@ export class LoopXContinuationDriver { try { state.agent.followup(message) } catch (error: unknown) { + if (this.todoUnitFold?.enabled === true) { + const retained = retainedState(state.agent, plan.session) + if (retained.activeTodoUnit?.turnInstanceId === plan.turnInstanceId) { + if (retained.activeTodoUnit.todoId !== undefined) { + retained.todoUnitAnchors?.delete(retained.activeTodoUnit.todoId) + } + retained.activeTodoUnit = undefined + } + } this.retireReservation(state) this.warn(`dsh-loopx-driver: could not queue same-session work: ${renderThrown(error)}`) } @@ -1540,7 +1624,13 @@ export class LoopXContinuationDriver { } state.retrySelection = false turnInstanceId ??= this.makeTurnInstanceId() - const quota = await this.readQuota(command, state.agent, binding, turnInstanceId, { signal }) + const quota = await this.readQuota( + command, + state.agent, + binding, + turnInstanceId, + { signal, includeSelectedTodo: this.todoUnitFold?.enabled === true }, + ) this.ensureReady(state, signal, session) if (quota.ok !== true) { throw new LoopXCliError( @@ -1557,6 +1647,10 @@ export class LoopXContinuationDriver { false, ) } + if (this.todoUnitFold?.enabled === true) { + await this.tryFoldSettledActiveTodoUnit(command, state, binding, quota, signal) + this.ensureReady(state, signal, session) + } if (quota.should_run !== true) { const wait = schedulerWait(quota, state.schedulerToken, state.unchangedPolls) const recovery = record(quota.unsettled_host_turn_recovery) @@ -1594,6 +1688,9 @@ export class LoopXContinuationDriver { ) } const receipt = record(quota.heartbeat_receipt) + const todoId = this.todoUnitFold?.enabled === true + ? extractTodoIdFromQuotaAndHeartbeat(quota, heartbeat) + : undefined return { kind: 'queue', ...binding, @@ -1602,6 +1699,7 @@ export class LoopXContinuationDriver { taskBody: taskBodyWithRewardMemory(taskBody, quota), selectionRequired: (receipt?.status === 'committed' || receipt?.status === 'replayed') && receipt.selection_required === true && receipt.settlement_binding_owed === true, + ...(todoId !== undefined ? { todoId } : {}), } } @@ -1720,7 +1818,11 @@ export class LoopXContinuationDriver { agent: Agent, binding: Binding, turnInstanceId: string, - { signal, revalidateOnly = false }: { signal: AbortSignal; revalidateOnly?: boolean }, + { + signal, + revalidateOnly = false, + includeSelectedTodo = false, + }: { signal: AbortSignal; revalidateOnly?: boolean; includeSelectedTodo?: boolean }, ): Promise> { // The 2.3 CLI supplies immutable navigation and its bounded reader. Older // supported CLIs continue to answer this Host-only call with raw JSON. @@ -1756,13 +1858,106 @@ export class LoopXContinuationDriver { const reference = progressive ? quotaNavigationReference(quota) : undefined if (reference === undefined) return quota // Retry the exact saved page on transport loss, outside the guard retry. - const decision = await readQuotaCapture(command, reference, options, revalidateOnly) + const decision = await readQuotaCapture( + command, reference, options, revalidateOnly, includeSelectedTodo, + ) if (!rawAdmission(decision)) { throw new LoopXCliError('invalid_schema', 'LoopX quota capture did not match the bound Goal', false) } return decision } + private async tryFoldSettledActiveTodoUnit( + command: LoopXCommand, + state: DriverState, + binding: Binding, + quota: Record, + signal: AbortSignal, + ): Promise { + const policy = this.todoUnitFold + if (policy?.enabled !== true) return + const retained = retainedState(state.agent, state.activation.session) + const active = retained.activeTodoUnit + if ( + active === undefined + || active.goalId !== binding.goalId + || active.agentId !== binding.agentId + || active.completedCleanly !== true + || state.activation.pendingSelection !== undefined + || state.pauseAfterTurnError + ) { + return + } + const recovery = record(quota.unsettled_host_turn_recovery) + if ( + recovery?.schema_version === 'unsettled_host_turn_recovery_v0' + && recovery.state === 'attention_required' + ) { + retained.activeTodoUnit = undefined + return + } + try { + const readback = await runJsonCommand(command, [ + '--registry', '.loopx/registry.json', '--format', 'json', 'quota', 'receipt', + '--include-settlement', + '--goal-id', binding.goalId, '--agent-id', binding.agentId, + '--turn-instance-id', active.turnInstanceId, + ], { + runner: this.runner, + cwd: state.agent.session.header.cwd, + signal, + }) + this.ensureReady(state, signal, state.activation.session) + const decoded = decodeQuotaSettlementReadback( + readback, + binding.goalId, + binding.agentId, + active.turnInstanceId, + active.todoId, + ) + if (!decoded.verified) { + retained.activeTodoUnit = undefined + return + } + const receipt = decoded.completionReceipt + if (active.anchor === undefined && active.admittedSeq !== undefined) { + this.anchorTodoUnit(state.agent, { + todoId: receipt.todoId, + turnInstanceId: active.turnInstanceId, + contextEpoch: active.contextEpoch, + anchorStepIndex: active.startStepIndex, + anchorSurfaceSeq: active.admittedSeq, + }) + } + const nextTodoId = extractTodoIdFromQuotaAndHeartbeat(quota) + const obsNextCmd = policy.resolveObsNextCmd?.({ + goalId: binding.goalId, + agentId: binding.agentId, + settledTodoId: receipt.todoId, + nextTodoId, + quota, + }) ?? policy.obsNextCmd + await this.onTodoUnitSettled(state.agent, { + todoId: receipt.todoId, + turnInstanceId: active.turnInstanceId, + contextEpoch: active.contextEpoch, + nowStepIndex: Math.max(active.startStepIndex, active.endStepIndex), + completionReceipt: receipt, + obsNextCmd, + failureFacts: [...receipt.failureFacts, ...(policy.defaultFailureFacts ?? [])], + openObligations: [...receipt.openObligations, ...(policy.defaultOpenObligations ?? [])], + quiescentBoundary: true, + }) + } catch (error: unknown) { + if (error instanceof LoopXCliError && error.kind === 'aborted') throw error + this.warn(`dsh-loopx-driver: todo_unit_fold_kept_raw error=${renderThrown(error)}`) + } finally { + if (retained.activeTodoUnit === active) { + retained.activeTodoUnit = undefined + } + } + } + private async readSelectionReceipt( command: LoopXCommand, agent: Agent, @@ -1877,8 +2072,18 @@ export class LoopXContinuationDriver { } private retireReservation(state: DriverState): void { - if (state.reservation === undefined) return - state.reservation.phase = 'retired' + const reservation = state.reservation + if (reservation === undefined) return + if (reservation.phase !== 'admitted') { + const retained = retainedState(state.agent, state.activation.session) + if (retained.activeTodoUnit?.turnInstanceId === reservation.turnInstanceId) { + if (retained.activeTodoUnit.todoId !== undefined) { + retained.todoUnitAnchors?.delete(retained.activeTodoUnit.todoId) + } + retained.activeTodoUnit = undefined + } + } + reservation.phase = 'retired' state.reservation = undefined } @@ -1963,13 +2168,17 @@ function watchReplacementUnload(ctx: Context): () => boolean { return () => moduleReplacement || (fiber !== undefined && fiber.uid !== null) } -export function apply(ctx: Context): void { +export function apply( + ctx: Context, + config?: { readonly todoUnitFold?: TodoUnitFoldPolicy | undefined }, +): void { const driver = new LoopXContinuationDriver({ isLiveAgent: agent => ctx.agents.get(agent.id) === agent, resolveCommand: signal => resolvePluginLoopXCommand({ signal }), runDetached: operation => ctx.agents.withoutInitiator(operation), warn: message => { ctx.logger.warn(message) }, onAdmissionChange: session => { goalBarCoordinator.publishAdmissionChange(session) }, + ...(config?.todoUnitFold !== undefined ? { todoUnitFold: config.todoUnitFold } : {}), }) const replacementUnload = watchReplacementUnload(ctx) diff --git a/packages/dsh-loopx-plugin/src/todo-unit-fold.ts b/packages/dsh-loopx-plugin/src/todo-unit-fold.ts index d8d2117731..419e7c9c71 100644 --- a/packages/dsh-loopx-plugin/src/todo-unit-fold.ts +++ b/packages/dsh-loopx-plugin/src/todo-unit-fold.ts @@ -39,6 +39,16 @@ export interface TodoUnitFoldPolicy { readonly coldPrefillAmortizationTokens?: number | undefined readonly maxObsOutputBytes?: number | undefined readonly rejectOnTruncation?: boolean | undefined + readonly obsNextCmd?: TodoUnitObsNextCommand | undefined + readonly resolveObsNextCmd?: ((context: { + readonly goalId: string + readonly agentId: string + readonly settledTodoId: string + readonly nextTodoId?: string | undefined + readonly quota: Record + }) => TodoUnitObsNextCommand | undefined) | undefined + readonly defaultFailureFacts?: readonly string[] | undefined + readonly defaultOpenObligations?: readonly string[] | undefined } export interface TodoUnitAnchorInput { @@ -677,4 +687,113 @@ export function validateTodoUnitObsForExecution( return safety.allowed ? safety.argv : null } +function asObj(value: unknown): Record | undefined { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : undefined +} + +export function extractTodoIdFromQuotaAndHeartbeat( + quota: Record, + heartbeat?: Record, +): string | undefined { + const receiptIdentity = asObj(asObj(quota.heartbeat_receipt)?.settlement_identity) + const candidates = [ + receiptIdentity?.todo_id, + asObj(quota.selected_todo)?.todo_id, + asObj(heartbeat?.selected_todo)?.todo_id, + heartbeat?.todo_id, + ] + for (const candidate of candidates) { + if (typeof candidate === 'string' && candidate.trim().length > 0) { + return candidate.trim() + } + } + return undefined +} + +export type DecodedQuotaSettlement = + | { readonly verified: true; readonly completionReceipt: TodoUnitCompletionReceipt } + | { readonly verified: false; readonly reason: string } + +export function decodeQuotaSettlementReadback( + payload: Record, + expectedGoalId: string, + expectedAgentId: string, + expectedTurnInstanceId: string, + expectedTodoId?: string, +): DecodedQuotaSettlement { + if ( + payload.schema_version !== 'quota_receipt_readback_v0' + || payload.ok !== true + || payload.goal_id !== expectedGoalId + || payload.agent_id !== expectedAgentId + || payload.turn_instance_id !== expectedTurnInstanceId + ) { + return { verified: false, reason: 'invalid_settlement_identity' } + } + if (payload.settlement_verified !== true) { + return { + verified: false, + reason: typeof payload.settlement_conflict_reason === 'string' + ? payload.settlement_conflict_reason + : 'unsettled_turn', + } + } + const raw = asObj(payload.completion_receipt) + const rawSource = asObj(raw?.source_ref) + const todoId = typeof raw?.todo_id === 'string' ? raw.todo_id.trim() : '' + const receiptId = typeof raw?.completion_receipt_id === 'string' ? raw.completion_receipt_id.trim() : '' + const sha256 = typeof raw?.sha256 === 'string' ? raw.sha256 : '' + const sourcePath = typeof rawSource?.path === 'string' ? rawSource.path.trim() : '' + const sourceSha = typeof rawSource?.sha256 === 'string' ? rawSource.sha256 : '' + if ( + !todoId + || (expectedTodoId !== undefined && expectedTodoId !== todoId) + || !receiptId + || raw?.exit_code !== 0 + || !BARE_SHA256_RE.test(sha256) + || !sourcePath + || !BARE_SHA256_RE.test(sourceSha) + ) { + return { verified: false, reason: 'invalid_completion_receipt' } + } + return { + verified: true, + completionReceipt: { + todoId, + completionReceiptId: receiptId, + exitCode: 0, + sha256, + failureFacts: cleanFacts(Array.isArray(raw?.failure_facts) ? raw.failure_facts as string[] : undefined, 32), + openObligations: cleanFacts(Array.isArray(raw?.open_obligations) ? raw.open_obligations as string[] : undefined, 64), + sourceRef: { path: sourcePath, sha256: sourceSha }, + }, + } +} + +export function createDefaultDshObsRunner(runner: FileRunner): TodoUnitObsRunner { + return async (argv, cwd) => { + const file = argv[0] + if (!file) { + return { exitCode: 127, output: '' } + } + try { + const res = await runner(file, argv.slice(1), { + cwd, + timeoutMs: 5_000, + maxOutputBytes: DEFAULT_TODO_FOLD_MAX_OBS_BYTES, + }) + return { + exitCode: res.exitCode, + output: res.stdout, + timedOut: false, + truncated: Buffer.byteLength(res.stdout, 'utf8') > DEFAULT_TODO_FOLD_MAX_OBS_BYTES, + } + } catch { + return { exitCode: null, output: '', timedOut: true } + } + } +} + export type { FileRunner, LoopXCommand } diff --git a/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts b/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts index e25f051ffb..1c8b88fccc 100644 --- a/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts +++ b/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm } from 'node:fs/promises' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' @@ -10,6 +10,7 @@ import type { Session, SessionSeq, } from '@deepseek-ai/dsh-session' +import type { FileRunner } from '../src/cli.ts' import { LoopXContinuationDriver } from '../src/driver.ts' import type { TodoUnitCompletionReceipt, @@ -23,18 +24,34 @@ async function createRealSessionHarness(cwd: string) { const sessionId = 'session-todo-fold-real' as Agent['id'] const session = storeFiber.ctx.sessions.create(sessionId, { meta: { cwd } }) let status: AgentStatus = 'idle' + const queued: UserMessage[] = [] + const nextStep: UserMessage[] = [] const agent = { id: sessionId, options: {}, session, - inbox: { nextTurn: [], nextStep: [], hasPending: false, remove: () => false }, + inbox: { + nextTurn: queued, + nextStep, + get hasPending() { return queued.length > 0 || nextStep.length > 0 }, + remove: (id: UserMessage['id']) => { + for (const list of [nextStep, queued]) { + const idx = list.findIndex(m => m.id === id) + if (idx >= 0) { + list.splice(idx, 1) + return true + } + } + return false + }, + }, ctx, get status() { return status }, cancel() {}, whenIdle: async () => {}, runMaintenance: async (fn: (signal: AbortSignal) => Promise) => fn(new AbortController().signal), send() {}, - followup() {}, + followup(msg: UserMessage) { queued.push(msg) }, steer() {}, inject() {}, } as unknown as Agent @@ -43,6 +60,7 @@ async function createRealSessionHarness(cwd: string) { ctx, session, agent, + queued, setStatus(next: AgentStatus) { status = next }, async dispose() { await storeFiber.dispose() @@ -419,4 +437,490 @@ describe('dsh-loopx-plugin Todo semantic-unit FoldAndPrefetch', () => { await rm(cwd, { recursive: true, force: true }) } }) + + it('keeps automatic multi-Todo execution strictly default-off with zero settlement calls or surface rewrites', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'dsh-auto-fold-off-')) + const harness = await createRealSessionHarness(cwd) + try { + const prefixSeqs = appendPrefixQ(harness.session) + const cliLog: string[] = [] + let currentTodo = 'todo_1' + let stepSeq = 0 + const runner: FileRunner = async (_file, args) => { + cliLog.push(args.join(' ')) + if (args.includes('resolve-agent-thread')) { + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + schema_version: 'loopx_thread_agent_binding_resolution_v0', + ok: true, + status: 'bound', + host_surface: 'deepseek-harness-native', + thread_id: harness.agent.id, + goal_id: 'goal-auto', + agent_id: 'agent-auto', + matches: [{ goal_id: 'goal-auto', agent_id: 'agent-auto' }], + }), + } + } + if (args.includes('quota') && args.includes('should-run')) { + const turnIdx = args.indexOf('--turn-instance-id') + const turnId = turnIdx >= 0 ? args[turnIdx + 1]! : 'turn-x' + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + ok: true, + mode: 'should-run', + goal_id: 'goal-auto', + should_run: true, + agent_identity: { agent_id: 'agent-auto', registered: true }, + heartbeat_receipt: { + schema_version: 'heartbeat_receipt_v0', + status: 'committed', + turn_instance_id: turnId, + settlement_identity: { goal_id: 'goal-auto', agent_id: 'agent-auto', turn_instance_id: turnId, todo_id: currentTodo }, + }, + }), + } + } + if (args.includes('heartbeat-prompt')) { + const turnIdx = args.indexOf('--turn-instance-id') + const turnId = turnIdx >= 0 ? args[turnIdx + 1]! : 'turn-x' + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + schema_version: 'heartbeat_agent_input_v1', + ok: true, + goal_id: 'goal-auto', + agent_id: 'agent-auto', + turn_instance_id: turnId, + task_body: `LOOPX_TURN=${turnId} work=${currentTodo}`, + }), + } + } + throw new Error(`unexpected cli call: ${args.join(' ')}`) + } + + const queued = harness.queued + let turnCounter = 0 + const driver = new LoopXContinuationDriver({ + isLiveAgent: () => true, + runner, + resolveCommand: async () => ({ file: 'loopx', prefix: [], skillCommand: 'loopx', version: 'loopx 2.4.0' }), + makeTurnInstanceId: () => `turn-off-${++turnCounter}`, + }) + + // Activate driver cleanly inside session. + const actEvent = harness.session.append('user/message', { + id: 'act-off' as UserMessage['id'], + role: 'user', + content: [{ type: 'text', text: 'loopx' }], + source: { kind: 'skill-invocation', name: 'loopx', form: 'instructions' } as never, + }, { surfaceOp: 'append' }) + driver.observeAgent(harness.agent) + await vi.waitFor(() => expect(queued.length).toBe(1)) + + // Execute Turn 1 (exploratory bloat remains raw after turn ends). + const msg1 = queued.shift()! + driver.onInboxClaimed(harness.agent, msg1) + await driver.onPreStep(harness.agent, [msg1], new AbortController().signal, async () => ({ kind: 'proceed', messages: [msg1] } as never)) + harness.setStatus('running') + const ev1 = harness.session.append('user/message', msg1, { surfaceOp: 'append' }) + driver.onSessionEvent(harness.agent, ev1) + driver.onSessionEvent(harness.agent, harness.session.append('step/start', { turn: 2, step: ++stepSeq } as never)) + const todo1Nodes = appendTodoExploratorySuffix(harness.session, 'auto-off') + driver.onSessionEvent(harness.agent, harness.session.append('turn/end', { turn: 2, reason: { kind: 'completed' } } as never)) + currentTodo = 'todo_2' + harness.setStatus('idle') + driver.onAgentStatus(harness.agent, 'idle') + + await vi.waitFor(() => expect(queued.length).toBe(1)) + // Default-off must NOT call `quota receipt --include-settlement`, and surface keeps all raw nodes! + expect(cliLog.some(line => line.includes('receipt'))).toBe(false) + expect(harness.session.surface.nodes.length).toBe(prefixSeqs.length + 1 + 1 + todo1Nodes.length) + expect(actEvent.seq).toBeGreaterThan(0) + } finally { + await harness.dispose() + await rm(cwd, { recursive: true, force: true }) + } + }) + + it('automatically anchors, folds upon verified Core settlement, prefetches obs_next_cmd, and swaps next step context while preserving KV prefix', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'dsh-auto-fold-on-')) + const harness = await createRealSessionHarness(cwd) + try { + const sourcePath = join(cwd, 'rollout.jsonl') + const sourceContent = '{"event":"todo_complete","todo_id":"todo_real_1"}\n' + await writeFile(sourcePath, sourceContent, 'utf8') + const { createHash } = await import('node:crypto') + const sourceSha = createHash('sha256').update(sourceContent, 'utf8').digest('hex') + + const prefixSeqs = appendPrefixQ(harness.session) + const prefixMessagesBefore = harness.session.deriveMessages() + const prefixDigestBefore = deriveMessagesPrefixDigest(harness.session, prefixSeqs.length) + + let activeTodo = 'todo_real_1' + let settledTurn1 = false + let stepSeq = 0 + const settlementCalls: string[] = [] + const obsRunner = vi.fn(async argv => ({ + exitCode: 0, + output: `OBS_OUTPUT cmd=${argv.join(' ')} status=clean`, + })) + + const runner: FileRunner = async (_file, args) => { + if (args.includes('resolve-agent-thread')) { + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + schema_version: 'loopx_thread_agent_binding_resolution_v0', + ok: true, + status: 'bound', + host_surface: 'deepseek-harness-native', + thread_id: harness.agent.id, + goal_id: 'goal-real', + agent_id: 'agent-real', + matches: [{ goal_id: 'goal-real', agent_id: 'agent-real' }], + }), + } + } + if (args.includes('quota') && args.includes('should-run')) { + const turnIdx = args.indexOf('--turn-instance-id') + const turnId = turnIdx >= 0 ? args[turnIdx + 1]! : 'turn-x' + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + ok: true, + mode: 'should-run', + goal_id: 'goal-real', + should_run: true, + agent_identity: { agent_id: 'agent-real', registered: true }, + selected_todo: { todo_id: activeTodo, text: `Execute ${activeTodo}` }, + heartbeat_receipt: { + schema_version: 'heartbeat_receipt_v0', + status: 'committed', + turn_instance_id: turnId, + settlement_identity: { goal_id: 'goal-real', agent_id: 'agent-real', turn_instance_id: turnId, todo_id: activeTodo }, + }, + }), + } + } + if (args.includes('quota') && args.includes('receipt') && args.includes('--include-settlement')) { + const turnIdx = args.indexOf('--turn-instance-id') + const turnId = turnIdx >= 0 ? args[turnIdx + 1]! : 'turn-x' + settlementCalls.push(turnId) + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + ok: true, + schema_version: 'quota_receipt_readback_v0', + goal_id: 'goal-real', + agent_id: 'agent-real', + turn_instance_id: turnId, + settlement_verified: settledTurn1, + settlement_conflict_reason: settledTurn1 ? null : 'missing_completion_event', + completion_receipt: settledTurn1 + ? { + todo_id: 'todo_real_1', + completion_receipt_id: `ev-${turnId}`, + exit_code: 0, + sha256: 'c'.repeat(64), + failure_facts: ['todo_real_1 initial lint note'], + open_obligations: ['verify todo_real_2 downstream'], + source_ref: { path: sourcePath, sha256: sourceSha }, + } + : null, + }), + } + } + if (args.includes('heartbeat-prompt')) { + const turnIdx = args.indexOf('--turn-instance-id') + const turnId = turnIdx >= 0 ? args[turnIdx + 1]! : 'turn-x' + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + schema_version: 'heartbeat_agent_input_v1', + ok: true, + goal_id: 'goal-real', + agent_id: 'agent-real', + turn_instance_id: turnId, + selected_todo: { todo_id: activeTodo }, + task_body: `LOOPX_TURN=${turnId} work=${activeTodo}`, + }), + } + } + throw new Error(`unexpected cli call: ${args.join(' ')}`) + } + + const queued = harness.queued + let turnCounter = 0 + const driver = new LoopXContinuationDriver({ + isLiveAgent: () => true, + runner, + resolveCommand: async () => ({ file: 'loopx', prefix: [], skillCommand: 'loopx', version: 'loopx 2.4.0' }), + makeTurnInstanceId: () => `turn-on-${++turnCounter}`, + todoUnitFold: { + enabled: true, + minNetSavingsTokens: 64, + resolveObsNextCmd: ({ settledTodoId, nextTodoId }) => { + expect(settledTodoId).toBe('todo_real_1') + expect(nextTodoId).toBe('todo_real_2') + return { + command: ['git', 'status', '--short'], + initiator: 'turn_driver', + rejectOnTruncation: true, + } + }, + }, + runObsCommand: obsRunner, + }) + + // Activate LoopX (still part of parent prefix Q before Todo 1 anchors!). + const actEvent = harness.session.append('user/message', { + id: 'act-on' as UserMessage['id'], + role: 'user', + content: [{ type: 'text', text: 'loopx' }], + source: { kind: 'skill-invocation', name: 'loopx', form: 'instructions' } as never, + }, { surfaceOp: 'append' }) + const qLenWithActivation = harness.session.surface.nodes.length + const qMessagesWithActivation = harness.session.deriveMessages() + const qDigestWithActivation = deriveMessagesPrefixDigest(harness.session, qLenWithActivation) + expect(qMessagesWithActivation.slice(0, prefixSeqs.length)).toEqual(prefixMessagesBefore) + expect(deriveMessagesPrefixDigest(harness.session, prefixSeqs.length)).toBe(prefixDigestBefore) + expect(actEvent.seq).toBeGreaterThan(0) + + driver.observeAgent(harness.agent) + await vi.waitFor(() => expect(queued.length).toBe(1)) + + // Execute Turn 1 (todo_real_1) with bloated exploratory tool output, then settle Turn 1! + const msg1 = queued.shift()! + driver.onInboxClaimed(harness.agent, msg1) + await driver.onPreStep(harness.agent, [msg1], new AbortController().signal, async () => ({ kind: 'proceed', messages: [msg1] } as never)) + harness.setStatus('running') + const ev1 = harness.session.append('user/message', msg1, { surfaceOp: 'append' }) + driver.onSessionEvent(harness.agent, ev1) + driver.onSessionEvent(harness.agent, harness.session.append('step/start', { turn: 2, step: ++stepSeq } as never)) + appendTodoExploratorySuffix(harness.session, 'todo_real_1_bloat') + expect(harness.session.deriveMessages().some(m => JSON.stringify(m).includes('exploratory search output for todo_real_1_bloat'))).toBe(true) + + driver.onSessionEvent(harness.agent, harness.session.append('turn/end', { turn: 2, reason: { kind: 'completed' } } as never)) + settledTurn1 = true + activeTodo = 'todo_real_2' + harness.setStatus('idle') + driver.onAgentStatus(harness.agent, 'idle') + + // Driver wakes, settles fold automatically via Core receipt readback, runs obsNextCmd, and queues Todo 2! + await vi.waitFor(() => expect(queued.length).toBe(1)) + const msg2 = queued.shift()! + expect(String((msg2.content[0] as { text: string }).text)).toContain('work=todo_real_2') + expect(settlementCalls).toEqual(['turn-on-1']) + expect(obsRunner).toHaveBeenCalledTimes(1) + + // Next model step context (`deriveMessages()`) physically popped Todo 1 bloat while preserving parent KV prefix Q! + const msgsBeforeTodo2 = harness.session.deriveMessages() + expect(deriveMessagesPrefixDigest(harness.session, qLenWithActivation)).toBe(qDigestWithActivation) + expect(msgsBeforeTodo2.slice(0, qLenWithActivation)).toEqual(qMessagesWithActivation) + expect(msgsBeforeTodo2.some(m => JSON.stringify(m).includes('exploratory search output for todo_real_1_bloat'))).toBe(false) + expect(msgsBeforeTodo2.length).toBe(qLenWithActivation + 1) + + const foldMsg = msgsBeforeTodo2.at(-1) as UserMessage + const foldText = (foldMsg.content[0] as { type: 'text'; text: string }).text + expect(foldMsg.source.kind).toBe('loopx-todo-fold') + expect(foldText).toContain('[Semantic-Unit Fold Receipt mu | trust=tool]') + expect(foldText).toContain('todo_id: todo_real_1') + expect(foldText).toContain('completion_receipt_id: ev-turn-on-1') + expect(foldText).toContain('OBS_OUTPUT cmd=git status --short status=clean') + expect(foldText).toContain('verify todo_real_2 downstream') + } finally { + await harness.dispose() + await rm(cwd, { recursive: true, force: true }) + } + }) + + it.each(['unsettled_progress', 'obs_command_error', 'recovery_conflict', 'aborted_turn'] as const)( + 'automatically fails closed to KeepRaw on real %s during multi-Todo driver lifecycle', + async mode => { + const cwd = await mkdtemp(join(tmpdir(), `dsh-auto-fail-${mode}-`)) + const harness = await createRealSessionHarness(cwd) + try { + const sourcePath = join(cwd, 'rollout.jsonl') + await writeFile(sourcePath, '{"event":"ok"}\n', 'utf8') + const { createHash } = await import('node:crypto') + const sourceSha = createHash('sha256').update('{"event":"ok"}\n', 'utf8').digest('hex') + + appendPrefixQ(harness.session) + harness.session.append('user/message', { + id: `act-${mode}` as UserMessage['id'], + role: 'user', + content: [{ type: 'text', text: 'loopx' }], + source: { kind: 'skill-invocation', name: 'loopx', form: 'instructions' } as never, + }, { surfaceOp: 'append' }) + + let stepSeq = 0 + let firstCall = true + const obsRunner = vi.fn(async () => ({ + exitCode: mode === 'obs_command_error' ? 2 : 0, + output: mode === 'obs_command_error' ? 'boom' : 'OK', + })) + const runner: FileRunner = async (_file, args) => { + if (args.includes('resolve-agent-thread')) { + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + schema_version: 'loopx_thread_agent_binding_resolution_v0', + ok: true, + status: 'bound', + host_surface: 'deepseek-harness-native', + thread_id: harness.agent.id, + goal_id: 'goal-fail', + agent_id: 'agent-fail', + matches: [{ goal_id: 'goal-fail', agent_id: 'agent-fail' }], + }), + } + } + if (args.includes('quota') && args.includes('should-run')) { + const turnIdx = args.indexOf('--turn-instance-id') + const turnId = turnIdx >= 0 ? args[turnIdx + 1]! : 'turn-x' + const recovering = !firstCall && mode === 'recovery_conflict' + firstCall = false + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + ok: true, + mode: 'should-run', + goal_id: 'goal-fail', + should_run: !recovering, + ...(recovering + ? { + unsettled_host_turn_recovery: { + schema_version: 'unsettled_host_turn_recovery_v0', + state: 'attention_required', + }, + } + : {}), + agent_identity: { agent_id: 'agent-fail', registered: true }, + selected_todo: { todo_id: 'todo_fail_auto' }, + heartbeat_receipt: { + schema_version: 'heartbeat_receipt_v0', + status: 'committed', + turn_instance_id: turnId, + settlement_identity: { goal_id: 'goal-fail', agent_id: 'agent-fail', turn_instance_id: turnId, todo_id: 'todo_fail_auto' }, + }, + }), + } + } + if (args.includes('quota') && args.includes('receipt') && args.includes('--include-settlement')) { + const turnIdx = args.indexOf('--turn-instance-id') + const turnId = turnIdx >= 0 ? args[turnIdx + 1]! : 'turn-x' + const verified = mode !== 'unsettled_progress' + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + ok: true, + schema_version: 'quota_receipt_readback_v0', + goal_id: 'goal-fail', + agent_id: 'agent-fail', + turn_instance_id: turnId, + settlement_verified: verified, + settlement_conflict_reason: verified ? null : 'missing_completion_event', + completion_receipt: verified + ? { + todo_id: 'todo_fail_auto', + completion_receipt_id: `ev-${turnId}`, + exit_code: 0, + sha256: 'd'.repeat(64), + failure_facts: ['preserved failure fact'], + open_obligations: ['preserved obligation'], + source_ref: { path: sourcePath, sha256: sourceSha }, + } + : null, + }), + } + } + if (args.includes('heartbeat-prompt')) { + const turnIdx = args.indexOf('--turn-instance-id') + const turnId = turnIdx >= 0 ? args[turnIdx + 1]! : 'turn-x' + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + schema_version: 'heartbeat_agent_input_v1', + ok: true, + goal_id: 'goal-fail', + agent_id: 'agent-fail', + turn_instance_id: turnId, + task_body: `LOOPX_TURN=${turnId}`, + }), + } + } + throw new Error(`unexpected cli call: ${args.join(' ')}`) + } + + const queued = harness.queued + let turnCounter = 0 + const driver = new LoopXContinuationDriver({ + isLiveAgent: () => true, + runner, + resolveCommand: async () => ({ file: 'loopx', prefix: [], skillCommand: 'loopx', version: 'loopx 2.4.0' }), + makeTurnInstanceId: () => `turn-fail-${++turnCounter}`, + todoUnitFold: { + enabled: true, + minNetSavingsTokens: 64, + obsNextCmd: { command: ['git', 'status', '--short'] }, + }, + runObsCommand: obsRunner, + }) + + driver.observeAgent(harness.agent) + await vi.waitFor(() => expect(queued.length).toBe(1)) + const msg1 = queued.shift()! + driver.onInboxClaimed(harness.agent, msg1) + await driver.onPreStep(harness.agent, [msg1], new AbortController().signal, async () => ({ kind: 'proceed', messages: [msg1] } as never)) + harness.setStatus('running') + driver.onSessionEvent(harness.agent, harness.session.append('user/message', msg1, { surfaceOp: 'append' })) + driver.onSessionEvent(harness.agent, harness.session.append('step/start', { turn: 2, step: ++stepSeq } as never)) + appendTodoExploratorySuffix(harness.session, `raw-${mode}`) + const rawNodesBeforeSettle = [...harness.session.surface.nodes] + const rawMsgsBeforeSettle = harness.session.deriveMessages() + + driver.onSessionEvent(harness.agent, harness.session.append('turn/end', { + turn: 2, + reason: { kind: mode === 'aborted_turn' ? 'aborted' : 'completed' }, + } as never)) + harness.setStatus('idle') + driver.onAgentStatus(harness.agent, 'idle') + + if (mode === 'recovery_conflict') { + await driver.evaluateActivatedSession({ agent: harness.agent, session: harness.agent.session }) + } else if (mode === 'aborted_turn') { + // Aborted turn holds pause until human resumes; verify raw messages stayed intact immediately. + await Promise.resolve() + } else { + await vi.waitFor(() => expect(queued.length).toBe(1)) + } + + expect(harness.session.surface.nodes).toEqual(rawNodesBeforeSettle) + expect(harness.session.deriveMessages()).toEqual(rawMsgsBeforeSettle) + expect(harness.session.deriveMessages().some(m => JSON.stringify(m).includes(`exploratory search output for raw-${mode}`))).toBe(true) + if (mode !== 'obs_command_error') { + expect(obsRunner).not.toHaveBeenCalled() + } else { + expect(obsRunner).toHaveBeenCalledTimes(1) + } + } finally { + await harness.dispose() + await rm(cwd, { recursive: true, force: true }) + } + }, + ) }) diff --git a/tests/control_plane/test_semantic_unit_fold_hooks.py b/tests/control_plane/test_semantic_unit_fold_hooks.py index dc63ee7941..7aff46653c 100644 --- a/tests/control_plane/test_semantic_unit_fold_hooks.py +++ b/tests/control_plane/test_semantic_unit_fold_hooks.py @@ -1,16 +1,36 @@ -"""Tests for S1-A Todo semantic-unit anchor, FoldToReceipt, KeepRaw rollback, and codex_context hooks.""" +"""Tests for S1-A Todo semantic-unit anchor, FoldToReceipt, KeepRaw rollback, and real Turn wiring.""" from __future__ import annotations from collections.abc import Mapping +from contextlib import redirect_stdout +import io +import json from pathlib import Path import pytest +from loopx.cli import main as cli_main from loopx.control_plane.quota.turn_envelope import ( build_semantic_unit_fold_swap, record_semantic_unit_anchor, ) from loopx.control_plane.turn_driver import codex_context +from loopx.control_plane.turn_driver.codex_cli import _prompt as codex_cli_prompt +from loopx.control_plane.turn_driver.epoch_prefetch import ( + _HOST_WIRE_EXCLUDED_PREFETCH_FIELDS, +) +from loopx.control_plane.turn_driver.executor import ( + run_loopx_turn_once, + serialize_generic_cli_host_input, +) +from loopx.control_plane.turn_driver.host_candidate import render_dsh_host_prompt +from loopx.control_plane.turn_driver.todo_unit_settlement import ( + _HOST_WIRE_EXCLUDED_FOLD_TEXT_FIELDS, +) +from loopx.rollout_event_log import rollout_event_log_path +from loopx.todos import add_goal_todo, complete_goal_todo +from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime +from tests.test_loopx_turn_driver import _write_live_fixture def _write_source_file(path: Path, text: str) -> dict[str, str]: @@ -288,3 +308,1158 @@ def spy_exec(argv: list[str], *, timeout_ms: int, max_output_bytes: int, cwd: st saved_state = codex_context._state(ctx_dir) assert "todo_fail_1" in saved_state["semantic_unit_anchors"] assert not saved_state.get("semantic_unit_folds") + + +def _invoke_cli_json(route: list[str], args: list[str]) -> tuple[int, dict]: + buf = io.StringIO() + with redirect_stdout(buf): + code = cli_main([*route, "--format", "json", *args]) + return code, json.loads(buf.getvalue()) + + +def _plan_turn(route: list[str], turn_instance_id: str, *, host: str = "codex-cli") -> dict: + code, payload = _invoke_cli_json( + route, + [ + "turn", + "plan", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + turn_instance_id, + "--host", + host, + "--execution-mode", + "isolated-headless", + "--scheduler-owner", + "outer_controller", + "--include-transaction-detail", + ], + ) + assert code == 0, payload + return payload + + +def _completion_callbacks(todo_id: str, observed_requests: list[dict], *, result_kind: str = "validated_completion"): + def host_runner(req: dict) -> dict: + observed_requests.append(dict(req)) + is_complete = result_kind == "validated_completion" + return { + "schema_version": "loopx_turn_result_v0", + "turn_key": req["turn_key"], + "result_kind": result_kind, + "completed_phases": ["host_execute", "typed_result"], + "classification": "todo_fold_fixture", + "recommended_action": "continue next todo" if is_complete else "keep working", + "next_action": "continue next todo" if is_complete else "keep working", + "delivery_batch_scale": "single_surface", + "delivery_outcome": "primary_goal_outcome" if is_complete else "outcome_progress", + "vision_unchanged_reason": "Goal acceptance remains unchanged.", + "summary": f"Turn executed for {todo_id} with {result_kind}.", + "work_evidence": [f"artifact:{todo_id}"], + "validation_evidence": [f"check:{todo_id}"], + } + + def completion_writeback(result: dict, *, effect_ref: str) -> dict: + return { + "ok": True, + "appended": True, + "effect_ref": effect_ref, + "completion": { + "event_id": f"ev-{result['turn_key']}", + "todo_id": todo_id, + "continuation": "active_goal", + }, + } + + def completion_intent(*_a, **_k) -> dict: + return {"todo_id": todo_id, "continuation": "active_goal"} + + def writeback(result: dict, *, effect_ref: str) -> dict: + return {"ok": True, "appended": True, "effect_ref": effect_ref, "turn_key": result["turn_key"]} + + def spend(*_a, **_k) -> dict: + return {"ok": True, "appended": True, "receipt": {"status": "committed"}} + + def scheduler(*_a, **_k) -> dict: + return {"ok": True, "completed": True, "acknowledged": True} + + def noop(*_a, **_k) -> dict: + return {"ok": True, "appended": True} + + return { + "host_runner": host_runner, + "task_validator": lambda _p, _r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + "writeback": writeback, + "completion_writeback": completion_writeback, + "completion_intent": completion_intent, + "terminal_closeout": noop, + "spend": spend, + "scheduler": scheduler, + } + + +def test_quota_receipt_cli_include_settlement_default_off_and_verified_readback( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + project, runtime, registry = _write_live_fixture(tmp_path, provider="file") + monkeypatch.chdir(tmp_path) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + code_sr, payload_sr = _invoke_cli_json( + route, + [ + "quota", + "should-run", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "turn-qr-1", + "--todo-id", + "todo_fixture0001", + ], + ) + assert code_sr == 0, payload_sr + + # Default `quota receipt` stays untouched (no settlement projection fields). + c_def, p_def = _invoke_cli_json( + route, + ["quota", "receipt", "--goal-id", "loopx-turn-fixture", "--agent-id", "codex-fixture", "--turn-instance-id", "turn-qr-1"], + ) + assert c_def == 0 + assert "settlement_verified" not in p_def + assert "completion_receipt" not in p_def + + # Before completion + spend commit, `--include-settlement` fails closed. + c_un, p_un = _invoke_cli_json( + route, + [ + "quota", + "receipt", + "--include-settlement", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "turn-qr-1", + ], + ) + assert c_un == 0 + assert p_un["settlement_verified"] is False + assert p_un["completion_receipt"] is None + + # After canonical refresh-state settlement + todo completion, `--include-settlement` verifies receipt. + c_ws, p_ws = _invoke_cli_json( + route, + [ + "refresh-state", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--delivery-workspace-path", + str(project), + "--todo-id", + "todo_fixture0001", + "--turn-instance-id", + "turn-qr-1", + "--settle-turn", + "--classification", + "validated_progress", + "--recommended-action", + "continue_goal", + "--delivery-batch-scale", + "single_surface", + "--delivery-outcome", + "outcome_progress", + "--vision-unchanged-reason", + "same", + "--no-global-sync", + "--suppress-external-sinks", + ], + ) + assert c_ws == 0, p_ws + assert p_ws["ok"] is True + + c_done, p_done = _invoke_cli_json( + route, + [ + "todo", + "complete", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--todo-id", + "todo_fixture0001", + "--turn-instance-id", + "turn-qr-1", + "--claimed-by", + "codex-fixture", + "--evidence", + "Completed fixture todo.", + "--no-follow-up", + ], + ) + assert c_done == 0, p_done + assert p_done["ok"] is True + + log_path = rollout_event_log_path(runtime, "loopx-turn-fixture") + c_ok, p_ok = _invoke_cli_json( + route, + [ + "quota", + "receipt", + "--include-settlement", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "turn-qr-1", + ], + ) + assert c_ok == 0, p_ok + assert p_ok["settlement_verified"] is True, p_ok + assert p_ok["completion_receipt"]["todo_id"] == "todo_fixture0001" + assert p_ok["completion_receipt"]["completion_receipt_id"] + assert p_ok["completion_receipt"]["exit_code"] == 0 + assert p_ok["completion_receipt"]["source_ref"]["path"] == str(log_path) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_run_loopx_turn_once_multi_todo_fold_and_next_turn_prompt_swap( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_live_fixture(tmp_path, provider=provider) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + next_obs = tmp_path / "next-todo-obs.txt" + next_obs.write_text("NEXT_TODO_PREFETCH_OK=true\n", encoding="utf-8") + + from loopx.control_plane.turn_driver import semantic_unit_hook as hook_mod + + obs_calls: list[list[str]] = [] + orig_exec = hook_mod.run_bounded_prefetch_subprocess + + def spy_exec(argv: list[str], *, timeout_ms: int, max_output_bytes: int, cwd: str | None = None) -> Mapping[str, object]: + obs_calls.append(list(argv)) + return orig_exec(argv, timeout_ms=timeout_ms, max_output_bytes=max_output_bytes, cwd=cwd) + + monkeypatch.setattr(hook_mod, "run_bounded_prefetch_subprocess", spy_exec) + + shared_parent_prefix = {"goal_policy": "preserve parent KV prefix Q verbatim", "repo": "loopx"} + bloat_suffix = "verbose exploratory grep output for todo_fixture0001 " * 260 + turn1_exploratory = [ + {"todo_id": "todo_fixture0001", "step": 1, "output": bloat_suffix}, + ] + + # Turn 1 executes Todo 1 (`todo_fixture0001`) and settles `validated_completion`. + plan1 = _plan_turn(route, "turn-fold-1") + seen1: list[dict] = [] + cb1 = _completion_callbacks("todo_fixture0001", seen1, result_kind="validated_completion") + fold_cfg_1 = { + "enabled": True, + "todo_id": "todo_fixture0001", + "context_epoch": "epoch-multi-todo-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": turn1_exploratory, + "baseline_text": bloat_suffix, + "obs_next_cmd": {"command": ["cat", str(next_obs)], "max_output_bytes": 4096}, + "failure_facts": ["earlier smoke caught stale assumption"], + "open_obligations": ["run todo_two verification after swap"], + } + res1 = run_loopx_turn_once( + plan1, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold=fold_cfg_1, + **cb1, + ) + assert res1["ok"] is True + assert res1["status"] == "committed" + fold1 = res1["semantic_unit_fold"] + assert fold1["operator"] == "FoldToReceipt" + assert fold1["status"] == "committed" + assert fold1["preserves_prefix_kv"] is True + assert fold1["executed"] is True + assert len(obs_calls) == 1 + + # Add Todo 2 and settle Todo 1 in Core so `turn plan` selects Todo 2. + added = add_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + role="agent", + text="Execute downstream verification todo_two.", + priority="P1", + ) + todo2_id = str(added["todo"]["todo_id"]) + complete_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + todo_id="todo_fixture0001", + agent_id="codex-fixture", + evidence="Todo 1 verified.", + ) + + plan2 = _plan_turn(route, "turn-fold-2") + turn2_exploratory = [ + {"todo_id": "todo_fixture0001", "step": 1, "output": bloat_suffix}, + {"todo_id": todo2_id, "step": 0, "output": "fresh todo2 kickoff note"}, + ] + seen2: list[dict] = [] + cb2 = _completion_callbacks(todo2_id, seen2, result_kind="validated_progress") + fold_cfg_2 = { + "enabled": True, + "todo_id": todo2_id, + "context_epoch": "epoch-multi-todo-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": turn2_exploratory, + "min_net_savings_tokens": 64, + } + res2 = run_loopx_turn_once( + plan2, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold=fold_cfg_2, + **cb2, + ) + assert res2["ok"] is True + assert len(seen2) == 1 + # Replay/Turn-2 preparation MUST NOT re-spawn Todo 1's obs_next_cmd. + assert len(obs_calls) == 1 + + delivered_req2 = seen2[0] + assert delivered_req2["parent_prefix"] == shared_parent_prefix + assert delivered_req2["semantic_unit_fold"]["operator"] == "FoldToReceipt" + assert delivered_req2["semantic_unit_fold"]["preserves_prefix_kv"] is True + assert delivered_req2["semantic_unit_fold"]["rendered_prompt_delivered_tokens"] < delivered_req2["semantic_unit_fold"]["rendered_prompt_baseline_tokens"] + + # Raw Todo 1 bloat was genuinely replaced; parent prefix, Todo 2 note, receipt mu, and obs_next_cmd are present. + delivered_exp = delivered_req2["exploratory_context"] + assert all(not (isinstance(row, Mapping) and row.get("output") == bloat_suffix) for row in delivered_exp) + assert any(isinstance(row, Mapping) and row.get("todo_id") == todo2_id for row in delivered_exp) + assert any(isinstance(row, Mapping) and row.get("replaced_by_semantic_unit_fold") is True and row.get("todo_id") == "todo_fixture0001" for row in delivered_exp) + + rendered_prompt2 = codex_cli_prompt(delivered_req2) + assert "verbose exploratory grep output for todo_fixture0001" not in rendered_prompt2 + assert "[Semantic-Unit Fold Receipt mu | trust=tool]" in rendered_prompt2 + assert "NEXT_TODO_PREFETCH_OK=true" in rendered_prompt2 + assert "preserve parent KV prefix Q verbatim" in rendered_prompt2 + assert "fresh todo2 kickoff note" in rendered_prompt2 + assert "Semantic-Unit Fold Receipt mu" in serialize_generic_cli_host_input(delivered_req2) + + +@pytest.mark.parametrize( + "failure_case", + ["progress_not_settled", "obs_command_error", "prefix_drift", "recovery_conflict", "negative_savings"], +) +def test_run_loopx_turn_once_todo_fold_fails_closed_keep_raw( + tmp_path: Path, failure_case: str, +) -> None: + project, runtime, registry = _write_live_fixture(tmp_path, provider="file") + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + obs_ok = tmp_path / "obs-ok.txt" + obs_ok.write_text("OBS_OK=1\n", encoding="utf-8") + + parent_prefix = {"goal_policy": "stable Q"} + raw_bloat = "raw exploratory step record to keep intact " * 220 + turn1_exp = [{"todo_id": "todo_fixture0001", "step": 1, "output": raw_bloat}] + + plan1 = _plan_turn(route, "turn-fail-1") + seen1: list[dict] = [] + turn1_result_kind = "validated_progress" if failure_case == "progress_not_settled" else "validated_completion" + cb1 = _completion_callbacks("todo_fixture0001", seen1, result_kind=turn1_result_kind) + fold_cfg_1: dict[str, object] = { + "enabled": True, + "todo_id": "todo_fixture0001", + "context_epoch": "epoch-fail-turn", + "parent_prefix": parent_prefix, + "exploratory_context": turn1_exp, + "baseline_text": "tiny" if failure_case == "negative_savings" else raw_bloat, + "obs_next_cmd": {"command": ["cat", str(tmp_path / "missing.txt" if failure_case == "obs_command_error" else obs_ok)]}, + "failure_facts": ["keep raw failure fact"], + "open_obligations": ["keep raw open obligation"], + } + res1 = run_loopx_turn_once( + plan1, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold=fold_cfg_1, + **cb1, + ) + assert res1["ok"] is True + + if failure_case in {"obs_command_error", "negative_savings"}: + assert res1["semantic_unit_fold"]["operator"] == "KeepRaw" + assert res1["semantic_unit_fold"]["preserves_raw_state"] is True + elif failure_case == "progress_not_settled": + assert "semantic_unit_fold" not in res1 + + added = add_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + role="agent", + text="Next todo after fail-closed check.", + priority="P1", + ) + todo2_id = str(added["todo"]["todo_id"]) + complete_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + todo_id="todo_fixture0001", + agent_id="codex-fixture", + evidence="Todo 1 closed before Turn 2.", + ) + + plan2 = _plan_turn(route, "turn-fail-2") + if failure_case == "recovery_conflict": + plan2["unsettled_host_turn_recovery"] = {"state": "attention_required"} + seen2: list[dict] = [] + cb2 = _completion_callbacks(todo2_id, seen2, result_kind="validated_progress") + res2 = run_loopx_turn_once( + plan2, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": todo2_id, + "context_epoch": "epoch-fail-turn", + "parent_prefix": {"goal_policy": "mutated Q!"} if failure_case == "prefix_drift" else parent_prefix, + "exploratory_context": turn1_exp, + }, + **cb2, + ) + assert res2["ok"] is True + assert len(seen2) == 1 + delivered2 = seen2[0] + # Every fail-closed case MUST preserve raw exploratory_context intact! + assert delivered2["exploratory_context"] == turn1_exp + if failure_case != "progress_not_settled": + fold2 = delivered2["semantic_unit_fold"] + assert fold2["operator"] == "KeepRaw" + assert fold2["preserves_raw_state"] is True + assert "keep raw failure fact" in fold2["preserved_failure_facts"] + assert "keep raw open obligation" in fold2["preserved_open_obligations"] + assert "KeepRaw" in codex_cli_prompt(delivered2) + else: + assert "semantic_unit_fold" not in delivered2 + + +def test_run_loopx_turn_once_todo_fold_default_off_zero_drift(tmp_path: Path) -> None: + project, runtime, registry = _write_live_fixture(tmp_path, provider="file") + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + plan = _plan_turn(route, "turn-off-1") + seen: list[dict] = [] + cb = _completion_callbacks("todo_fixture0001", seen, result_kind="validated_completion") + res = run_loopx_turn_once( + plan, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + **cb, + ) + assert res["ok"] is True + assert "semantic_unit_fold" not in res + assert "semantic_unit_fold" not in seen[0] + assert not (runtime / "goals" / "loopx-turn-fixture" / "semantic_unit_fold").exists() + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_run_loopx_turn_once_next_turn_enforces_effective_min_net_savings_tokens( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_live_fixture(tmp_path, provider=provider) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + next_obs = tmp_path / "obs-savings.txt" + next_obs.write_text("NEXT_OBS_THRESHOLD_OK=true\n", encoding="utf-8") + + from loopx.control_plane.turn_driver import semantic_unit_hook as hook_mod + + obs_calls: list[list[str]] = [] + orig_exec = hook_mod.run_bounded_prefetch_subprocess + + def spy_exec( + argv: list[str], *, timeout_ms: int, max_output_bytes: int, cwd: str | None = None, + ) -> Mapping[str, object]: + obs_calls.append(list(argv)) + return orig_exec(argv, timeout_ms=timeout_ms, max_output_bytes=max_output_bytes, cwd=cwd) + + monkeypatch.setattr(hook_mod, "run_bounded_prefetch_subprocess", spy_exec) + + shared_parent_prefix = {"goal_policy": "preserve Q across min_net_savings threshold checks", "repo": "loopx"} + bloat_suffix = "verbose exploratory grep output for todo_fixture0001 " * 260 + turn1_exp = [{"todo_id": "todo_fixture0001", "step": 1, "output": bloat_suffix}] + + plan1 = _plan_turn(route, "turn-thresh-1") + seen1: list[dict] = [] + cb1 = _completion_callbacks("todo_fixture0001", seen1, result_kind="validated_completion") + res1 = run_loopx_turn_once( + plan1, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": "todo_fixture0001", + "context_epoch": "epoch-thresh-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": turn1_exp, + "baseline_text": bloat_suffix, + "obs_next_cmd": {"command": ["cat", str(next_obs)], "max_output_bytes": 4096}, + "min_net_savings_tokens": 1600, + }, + **cb1, + ) + assert res1["ok"] is True + assert res1["semantic_unit_fold"]["operator"] == "FoldToReceipt" + assert len(obs_calls) == 1 + + added = add_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + role="agent", + text="Execute downstream verification under explicit threshold.", + priority="P1", + ) + todo2_id = str(added["todo"]["todo_id"]) + complete_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + todo_id="todo_fixture0001", + agent_id="codex-fixture", + evidence="Todo 1 verified before Turn 2 savings gate checks.", + ) + + turn2_exp = [ + {"todo_id": "todo_fixture0001", "step": 1, "output": bloat_suffix}, + {"todo_id": todo2_id, "step": 0, "output": "fresh todo2 kickoff note"}, + ] + + def _run_turn2(turn_id: str, **extra_fold: object) -> tuple[dict, dict]: + seen: list[dict] = [] + cb = _completion_callbacks(todo2_id, seen, result_kind="validated_progress") + plan = _plan_turn(route, turn_id) + fold_opt: dict[str, object] = { + "enabled": True, + "todo_id": todo2_id, + "context_epoch": "epoch-thresh-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": turn2_exp, + **extra_fold, + } + res = run_loopx_turn_once( + plan, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold=fold_opt, + **cb, + ) + assert res["ok"] is True + assert len(seen) == 1 + assert len(obs_calls) == 1 + return res, seen[0] + + # 1. Explicit min_net_savings_tokens=64 commits FoldToReceipt and replaces Todo 1 bloat. + _, req_64 = _run_turn2("turn-thresh-01", min_net_savings_tokens=64) + fold_64 = req_64["semantic_unit_fold"] + assert fold_64["operator"] == "FoldToReceipt" + assert req_64["exploratory_context"] != turn2_exp + assert "verbose exploratory grep output for todo_fixture0001" not in codex_cli_prompt(req_64) + measured_amort = int(fold_64["cold_prefill_amortization_tokens"]) + measured_amortized = int(fold_64["amortized_net_savings_tokens"]) + assert 64 < measured_amortized < 10000 + + # 2. Explicit min_net_savings_tokens=10000 (> ~1.2k amortized) fails closed KeepRaw & retains Todo 1 bloat. + _, req_10k = _run_turn2("turn-thresh-02", min_net_savings_tokens=10000) + assert req_10k["semantic_unit_fold"]["operator"] == "KeepRaw" + assert req_10k["semantic_unit_fold"]["fallback_reason"] == "negative_net_savings" + assert req_10k["semantic_unit_fold"]["preserves_raw_state"] is True + assert req_10k["exploratory_context"] == turn2_exp + assert "verbose exploratory grep output for todo_fixture0001" in codex_cli_prompt(req_10k) + + # 3. Exact 1-token amortized equality boundary (pinned amortization avoids multi-turn quota float drift). + _, req_eq = _run_turn2( + "turn-thresh-03", + min_net_savings_tokens=measured_amortized, + cold_prefill_amortization_tokens=measured_amort, + ) + assert req_eq["semantic_unit_fold"]["operator"] == "FoldToReceipt" + assert int(req_eq["semantic_unit_fold"]["amortized_net_savings_tokens"]) == measured_amortized + assert "verbose exploratory grep output for todo_fixture0001" not in codex_cli_prompt(req_eq) + + _, req_above = _run_turn2( + "turn-thresh-04", + min_net_savings_tokens=measured_amortized + 1, + cold_prefill_amortization_tokens=measured_amort, + ) + assert req_above["semantic_unit_fold"]["operator"] == "KeepRaw" + assert req_above["semantic_unit_fold"]["fallback_reason"] == "negative_net_savings" + assert req_above["exploratory_context"] == turn2_exp + assert "verbose exploratory grep output for todo_fixture0001" in codex_cli_prompt(req_above) + + # 3b. Auto-amortization tight bracket below and above measured savings. + _, req_auto_below = _run_turn2("turn-thresh-09", min_net_savings_tokens=measured_amortized - 10) + assert req_auto_below["semantic_unit_fold"]["operator"] == "FoldToReceipt" + _, req_auto_above = _run_turn2("turn-thresh-10", min_net_savings_tokens=measured_amortized + 10) + assert req_auto_above["semantic_unit_fold"]["operator"] == "KeepRaw" + assert req_auto_above["semantic_unit_fold"]["fallback_reason"] == "negative_net_savings" + assert req_auto_above["exploratory_context"] == turn2_exp + + # 4. Omitting min_net_savings_tokens in Turn 2 inherits Turn 1's effective 1600-token threshold -> KeepRaw. + _, req_inherited = _run_turn2("turn-thresh-05") + assert req_inherited["semantic_unit_fold"]["operator"] == "KeepRaw" + assert req_inherited["semantic_unit_fold"]["min_net_savings_tokens"] == 1600 + assert req_inherited["exploratory_context"] == turn2_exp + + # 5. Zero-amortization raw-savings boundary (cold_prefill_amortization_tokens=0): == raw_net passes, +1 keeps raw. + _, req_zero_amort = _run_turn2( + "turn-thresh-06", min_net_savings_tokens=64, cold_prefill_amortization_tokens=0, + ) + fold_zero = req_zero_amort["semantic_unit_fold"] + assert fold_zero["operator"] == "FoldToReceipt" + raw_net = int(fold_zero["net_savings_tokens"]) + assert int(fold_zero["amortized_net_savings_tokens"]) == raw_net + + _, req_raw_eq = _run_turn2( + "turn-thresh-07", min_net_savings_tokens=raw_net, cold_prefill_amortization_tokens=0, + ) + assert req_raw_eq["semantic_unit_fold"]["operator"] == "FoldToReceipt" + + _, req_raw_above = _run_turn2( + "turn-thresh-08", min_net_savings_tokens=raw_net + 1, cold_prefill_amortization_tokens=0, + ) + assert req_raw_above["semantic_unit_fold"]["operator"] == "KeepRaw" + assert req_raw_above["semantic_unit_fold"]["fallback_reason"] == "negative_net_savings" + assert req_raw_above["exploratory_context"] == turn2_exp + + +def _extract_dsh_turn_request_payload(prompt: str) -> dict[str, object]: + marker = "Turn request:\n" + idx = prompt.index(marker) + len(marker) + json_line = prompt[idx:].splitlines()[0] + payload = json.loads(json_line) + assert isinstance(payload, dict) + return payload + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_run_loopx_turn_once_dsh_host_strips_internal_fold_telemetry_and_preserves_threshold( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + from loopx.control_plane.turn_driver import host_binding + + monkeypatch.setattr(host_binding, "dsh_runtime_importable", lambda *_a, **_kw: True) + monkeypatch.setenv("DEEPSEEK_API_KEY", "fixture-placeholder-not-a-secret") + project, runtime, registry = _write_live_fixture(tmp_path, provider=provider) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + next_obs = tmp_path / "obs-dsh.txt" + next_obs.write_text("DSH_OBS_OK=true\n", encoding="utf-8") + + shared_parent_prefix = {"goal_policy": "preserve DSH host prefix stability", "repo": "loopx"} + bloat_suffix = "verbose exploratory grep output for todo_fixture0001 " * 260 + turn1_exp = [{"todo_id": "todo_fixture0001", "step": 1, "output": bloat_suffix}] + + seen1: list[dict] = [] + cb1 = _completion_callbacks("todo_fixture0001", seen1, result_kind="validated_completion") + res1 = run_loopx_turn_once( + _plan_turn(route, "turn-dsh-1", host="dsh"), + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": "todo_fixture0001", + "context_epoch": "epoch-dsh-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": turn1_exp, + "baseline_text": bloat_suffix, + "obs_next_cmd": {"command": ["cat", str(next_obs)], "max_output_bytes": 4096}, + "min_net_savings_tokens": 64, + }, + **cb1, + ) + assert res1["ok"] is True + assert res1["semantic_unit_fold"]["operator"] == "FoldToReceipt" + + added = add_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + role="agent", + text="Execute DSH Turn 2 exact-threshold verification.", + priority="P1", + ) + todo2_id = str(added["todo"]["todo_id"]) + complete_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + todo_id="todo_fixture0001", + agent_id="codex-fixture", + evidence="Todo 1 verified for DSH exact-threshold test.", + ) + + turn2_exp = [ + {"todo_id": "todo_fixture0001", "step": 1, "output": bloat_suffix}, + {"todo_id": todo2_id, "step": 0, "output": "fresh todo2 kickoff note"}, + ] + + def _run_dsh_turn2(turn_id: str, **extra_fold: object) -> tuple[dict, str]: + seen: list[dict] = [] + cb = _completion_callbacks(todo2_id, seen, result_kind="validated_progress") + res = run_loopx_turn_once( + _plan_turn(route, turn_id, host="dsh"), + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": todo2_id, + "context_epoch": "epoch-dsh-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": turn2_exp, + **extra_fold, + }, + **cb, + ) + assert res["ok"] is True + assert len(seen) == 1 + dsh_prompt = render_dsh_host_prompt(seen[0]) + assert dsh_prompt is not None + rendered_payload = _extract_dsh_turn_request_payload(dsh_prompt) + rendered_fold = rendered_payload.get("semantic_unit_fold") + assert isinstance(rendered_fold, dict) + forbidden = ( + set(_HOST_WIRE_EXCLUDED_PREFETCH_FIELDS) + | set(_HOST_WIRE_EXCLUDED_FOLD_TEXT_FIELDS) + | {"persistence", "anchor_recorded"} + ) + assert forbidden.isdisjoint(rendered_fold.keys()) + return seen[0], dsh_prompt + + req_64, prompt_64 = _run_dsh_turn2("turn-dsh-01", min_net_savings_tokens=64) + fold_64 = req_64["semantic_unit_fold"] + assert fold_64["operator"] == "FoldToReceipt" + assert "verbose exploratory grep output for todo_fixture0001" not in prompt_64 + assert "Todo Semantic-Unit Fold Receipt:" in prompt_64 + for leaked_key in ( + "net_savings_tokens", + "rendered_prompt_baseline_tokens", + "rendered_prompt_candidate_tokens", + "rendered_prompt_savings_tokens", + "rendered_prompt_amortized_savings_tokens", + "tokenizer", + ): + assert f'"{leaked_key}"' not in prompt_64 + + measured_amort = int(fold_64["cold_prefill_amortization_tokens"]) + measured_amortized = int(fold_64["amortized_net_savings_tokens"]) + assert 64 < measured_amortized < 10000 + + req_eq, prompt_eq = _run_dsh_turn2( + "turn-dsh-02", + min_net_savings_tokens=measured_amortized, + cold_prefill_amortization_tokens=measured_amort, + ) + assert req_eq["semantic_unit_fold"]["operator"] == "FoldToReceipt" + assert int(req_eq["semantic_unit_fold"]["amortized_net_savings_tokens"]) == measured_amortized + assert "verbose exploratory grep output for todo_fixture0001" not in prompt_eq + + req_above, prompt_above = _run_dsh_turn2( + "turn-dsh-03", + min_net_savings_tokens=measured_amortized + 1, + cold_prefill_amortization_tokens=measured_amort, + ) + assert req_above["semantic_unit_fold"]["operator"] == "KeepRaw" + assert req_above["semantic_unit_fold"]["fallback_reason"] == "negative_net_savings" + assert req_above["exploratory_context"] == turn2_exp + assert "verbose exploratory grep output for todo_fixture0001" in prompt_above + + req_10k, prompt_10k = _run_dsh_turn2("turn-dsh-04", min_net_savings_tokens=10000) + assert req_10k["semantic_unit_fold"]["operator"] == "KeepRaw" + assert req_10k["semantic_unit_fold"]["fallback_reason"] == "negative_net_savings" + assert "verbose exploratory grep output for todo_fixture0001" in prompt_10k + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_run_loopx_turn_once_preserves_unbound_exploratory_items_across_todo_fold( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_live_fixture(tmp_path, provider=provider) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + next_obs = tmp_path / "obs-unbound.txt" + next_obs.write_text("UNBOUND_OBS_OK=true\n", encoding="utf-8") + + shared_parent_prefix = {"goal_policy": "preserve unbound Turn 2 records", "repo": "loopx"} + bloat_suffix = "verbose exploratory grep output for todo_fixture0001 " * 260 + turn1_exp = [{"todo_id": "todo_fixture0001", "step": 1, "output": bloat_suffix}] + + seen1: list[dict] = [] + cb1 = _completion_callbacks("todo_fixture0001", seen1, result_kind="validated_completion") + res1 = run_loopx_turn_once( + _plan_turn(route, "turn-unbound-1"), + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": "todo_fixture0001", + "context_epoch": "epoch-unbound-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": turn1_exp, + "baseline_text": bloat_suffix, + "obs_next_cmd": {"command": ["cat", str(next_obs)], "max_output_bytes": 4096}, + "min_net_savings_tokens": 64, + }, + **cb1, + ) + assert res1["ok"] is True + assert res1["semantic_unit_fold"]["operator"] == "FoldToReceipt" + + added = add_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + role="agent", + text="Verify Todo 2 while retaining newly introduced unbound exploratory records.", + priority="P1", + ) + todo2_id = str(added["todo"]["todo_id"]) + complete_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + todo_id="todo_fixture0001", + agent_id="codex-fixture", + evidence="Todo 1 verified before mixed unbound Turn 2 check.", + ) + + unbound_dict = {"step": 2, "output": "NEW_UNBOUND_EVIDENCE_KEEP_INTACT"} + blank_todo_dict = {"todo_id": " ", "step": 3, "output": "BLANK_TODO_ID_KEEP_INTACT"} + unbound_str = "PLAIN_TEXT_UNBOUND_ENTRY_KEEP_INTACT" + todo2_item = {"todo_id": todo2_id, "step": 0, "output": "TODO2_BOUND_EVIDENCE_KEEP_INTACT"} + mixed_exp = [ + {"todo_id": "todo_fixture0001", "step": 1, "output": bloat_suffix}, + unbound_dict, + blank_todo_dict, + unbound_str, + todo2_item, + ] + + seen2: list[dict] = [] + cb2 = _completion_callbacks(todo2_id, seen2, result_kind="validated_progress") + res2 = run_loopx_turn_once( + _plan_turn(route, "turn-unbound-2"), + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": todo2_id, + "context_epoch": "epoch-unbound-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": mixed_exp, + "min_net_savings_tokens": 64, + }, + **cb2, + ) + assert res2["ok"] is True + assert len(seen2) == 1 + req2 = seen2[0] + assert req2["semantic_unit_fold"]["operator"] == "FoldToReceipt" + delivered_exp = req2["exploratory_context"] + assert unbound_dict in delivered_exp + assert blank_todo_dict in delivered_exp + assert unbound_str in delivered_exp + assert todo2_item in delivered_exp + assert all( + not (isinstance(row, Mapping) and row.get("output") == bloat_suffix) + for row in delivered_exp + ) + rendered2 = codex_cli_prompt(req2) + assert "NEW_UNBOUND_EVIDENCE_KEEP_INTACT" in rendered2 + assert "BLANK_TODO_ID_KEEP_INTACT" in rendered2 + assert "PLAIN_TEXT_UNBOUND_ENTRY_KEEP_INTACT" in rendered2 + assert "TODO2_BOUND_EVIDENCE_KEEP_INTACT" in rendered2 + assert "verbose exploratory grep output for todo_fixture0001" not in rendered2 + + # Unbound entry preceding Todo A shifts parent prefix -> KeepRaw preserves all records verbatim. + seen3: list[dict] = [] + cb3 = _completion_callbacks(todo2_id, seen3, result_kind="validated_progress") + preceding_exp = [unbound_dict, {"todo_id": "todo_fixture0001", "step": 1, "output": bloat_suffix}, todo2_item] + res3 = run_loopx_turn_once( + _plan_turn(route, "turn-unbound-3"), + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": todo2_id, + "context_epoch": "epoch-unbound-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": preceding_exp, + "min_net_savings_tokens": 64, + }, + **cb3, + ) + assert res3["ok"] is True + assert seen3[0]["semantic_unit_fold"]["operator"] == "KeepRaw" + assert seen3[0]["semantic_unit_fold"]["fallback_reason"] == "prefix_digest_mismatch" + assert seen3[0]["exploratory_context"] == preceding_exp + + # Single untagged mapping or raw string without todo_id cannot be dropped as Todo A evidence. + seen4: list[dict] = [] + cb4 = _completion_callbacks(todo2_id, seen4, result_kind="validated_progress") + res4 = run_loopx_turn_once( + _plan_turn(route, "turn-unbound-4"), + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": todo2_id, + "context_epoch": "epoch-unbound-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": unbound_dict, + "min_net_savings_tokens": 64, + }, + **cb4, + ) + assert res4["ok"] is True + assert seen4[0]["exploratory_context"] == unbound_dict + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_run_loopx_turn_once_constrains_fold_to_covered_turn1_records_across_providers( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_live_fixture(tmp_path, provider=provider) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + next_obs = tmp_path / "obs-covered.txt" + next_obs.write_text("COVERED_SPAN_OBS_OK=true\n", encoding="utf-8") + + shared_parent_prefix = {"goal_policy": "constrain replacement to covered span", "repo": "loopx"} + bloat_suffix = "verbose exploratory grep output for todo_fixture0001 " * 260 + covered_a1 = {"todo_id": "todo_fixture0001", "step": 1, "output": bloat_suffix} + turn1_exp = [covered_a1] + + seen1: list[dict] = [] + cb1 = _completion_callbacks("todo_fixture0001", seen1, result_kind="validated_completion") + res1 = run_loopx_turn_once( + _plan_turn(route, "turn-covered-1"), + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": "todo_fixture0001", + "context_epoch": "epoch-covered-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": turn1_exp, + "baseline_text": bloat_suffix, + "obs_next_cmd": {"command": ["cat", str(next_obs)], "max_output_bytes": 4096}, + "min_net_savings_tokens": 64, + }, + **cb1, + ) + assert res1["ok"] is True + assert res1["semantic_unit_fold"]["operator"] == "FoldToReceipt" + assert len(res1["semantic_unit_fold"]["covered_exploratory_digests"]) == 1 + + added = add_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + role="agent", + text="Verify Todo 2 retains late/rewritten/unverified Todo A observations.", + priority="P1", + ) + todo2_id = str(added["todo"]["todo_id"]) + complete_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + todo_id="todo_fixture0001", + agent_id="codex-fixture", + evidence="Todo 1 verified before covered-span Turn 2 checks.", + ) + + todo2_item = {"todo_id": todo2_id, "step": 0, "output": "TODO2_BOUND_EVIDENCE_KEEP"} + unbound_item = {"step": 2, "output": "UNBOUND_RECORD_KEEP"} + late_a_item = {"todo_id": "todo_fixture0001", "step": 2, "output": "POST_SETTLEMENT_A_OBSERVATION " * 140} + rewritten_a_item = {"todo_id": "todo_fixture0001", "step": 1, "output": "REWRITTEN_A_OBSERVATION " * 140} + + def _run_case(turn_id: str, exploratory: object) -> dict: + seen: list[dict] = [] + cb = _completion_callbacks(todo2_id, seen, result_kind="validated_progress") + res = run_loopx_turn_once( + _plan_turn(route, turn_id), + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": todo2_id, + "context_epoch": "epoch-covered-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": exploratory, + "min_net_savings_tokens": 64, + }, + **cb, + ) + assert res["ok"] is True + assert len(seen) == 1 + assert "covered_exploratory_digests" not in codex_cli_prompt(seen[0]) + return seen[0] + + # 1. Post-settlement A item alone (original covered A1 absent): prefix/tokens pass, receipt does NOT cover late_a_item -> KeepRaw. + req_late_only = _run_case("turn-covered-2a", [late_a_item, todo2_item, unbound_item]) + assert req_late_only["semantic_unit_fold"]["operator"] == "KeepRaw" + assert req_late_only["semantic_unit_fold"]["fallback_reason"] == "source_digest_mismatch" + assert req_late_only["semantic_unit_fold"]["preserves_raw_state"] is True + assert req_late_only["exploratory_context"] == [late_a_item, todo2_item, unbound_item] + assert "POST_SETTLEMENT_A_OBSERVATION" in codex_cli_prompt(req_late_only) + + # 2. Rewritten A item: digest mismatches Turn 1 snapshot -> KeepRaw preserves rewritten A, B, unbound verbatim. + req_rewritten = _run_case("turn-covered-2b", [rewritten_a_item, todo2_item, unbound_item]) + assert req_rewritten["semantic_unit_fold"]["operator"] == "KeepRaw" + assert req_rewritten["semantic_unit_fold"]["fallback_reason"] == "source_digest_mismatch" + assert req_rewritten["exploratory_context"] == [rewritten_a_item, todo2_item, unbound_item] + + # 3. Covered A1 intact + post-settlement late A2 + B + unbound -> replaces ONLY covered A1; preserves late_a_item, B, unbound! + req_covered_plus_late = _run_case("turn-covered-2c", [covered_a1, late_a_item, todo2_item, unbound_item]) + assert req_covered_plus_late["semantic_unit_fold"]["operator"] == "FoldToReceipt" + delivered_plus_late = req_covered_plus_late["exploratory_context"] + assert late_a_item in delivered_plus_late + assert todo2_item in delivered_plus_late + assert unbound_item in delivered_plus_late + assert covered_a1 not in delivered_plus_late + prompt_plus_late = codex_cli_prompt(req_covered_plus_late) + assert "POST_SETTLEMENT_A_OBSERVATION" in prompt_plus_late + assert "TODO2_BOUND_EVIDENCE_KEEP" in prompt_plus_late + assert "UNBOUND_RECORD_KEEP" in prompt_plus_late + assert "verbose exploratory grep output for todo_fixture0001" not in prompt_plus_late + + # 4. Turn 1 settled without any inline exploratory_context -> Turn 2 A observation has uncovered scope -> KeepRaw! + sub_root = tmp_path / "uncovered-scope" + sub_root.mkdir() + if provider == "sqlite": + isolate_sqlite_runtime(sub_root, monkeypatch) + sub_proj, sub_runtime, sub_registry = _write_live_fixture(sub_root, provider=provider) + sub_route = ["--registry", str(sub_registry), "--runtime-root", str(sub_runtime)] + sub_seen1: list[dict] = [] + sub_res1 = run_loopx_turn_once( + _plan_turn(sub_route, "turn-uncov-1"), + project=sub_proj, + runtime_root=sub_runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": "todo_fixture0001", + "context_epoch": "epoch-uncov-1", + "parent_prefix": shared_parent_prefix, + "baseline_text": bloat_suffix, + "obs_next_cmd": {"command": ["cat", str(next_obs)], "max_output_bytes": 4096}, + "min_net_savings_tokens": 64, + }, + **_completion_callbacks("todo_fixture0001", sub_seen1, result_kind="validated_completion"), + ) + assert sub_res1["ok"] is True + assert sub_res1["semantic_unit_fold"]["operator"] == "FoldToReceipt" + assert sub_res1["semantic_unit_fold"]["covered_exploratory_digests"] == [] + sub_added = add_goal_todo( + registry_path=sub_registry, + runtime_root_arg=str(sub_runtime), + goal_id="loopx-turn-fixture", + role="agent", + text="Todo 2 under empty Turn 1 baseline.", + priority="P1", + ) + sub_todo2 = str(sub_added["todo"]["todo_id"]) + complete_goal_todo( + registry_path=sub_registry, + runtime_root_arg=str(sub_runtime), + goal_id="loopx-turn-fixture", + todo_id="todo_fixture0001", + agent_id="codex-fixture", + evidence="Todo 1 verified without inline exploratory items.", + ) + sub_seen2: list[dict] = [] + sub_res2 = run_loopx_turn_once( + _plan_turn(sub_route, "turn-uncov-2"), + project=sub_proj, + runtime_root=sub_runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + semantic_unit_fold={ + "enabled": True, + "todo_id": sub_todo2, + "context_epoch": "epoch-uncov-1", + "parent_prefix": shared_parent_prefix, + "exploratory_context": [late_a_item, {"todo_id": sub_todo2, "output": "B_KEEP"}, unbound_item], + "min_net_savings_tokens": 64, + }, + **_completion_callbacks(sub_todo2, sub_seen2, result_kind="validated_progress"), + ) + assert sub_res2["ok"] is True + assert sub_seen2[0]["semantic_unit_fold"]["operator"] == "KeepRaw" + assert sub_seen2[0]["semantic_unit_fold"]["fallback_reason"] == "source_digest_mismatch" + assert sub_seen2[0]["exploratory_context"] == [late_a_item, {"todo_id": sub_todo2, "output": "B_KEEP"}, unbound_item] From 54fe81a2fc2c36aecbfccf61869f90e980793fe0 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:30:38 +0800 Subject: [PATCH 2/4] fix(dsh-plugin): preserve mid-prefetch user corrections in fold driver Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- packages/dsh-loopx-plugin/src/driver.ts | 182 +++++++++- .../dsh-loopx-plugin/src/todo-unit-fold.ts | 13 +- .../tests/todo-unit-fold.spec.ts | 336 +++++++++++++++++- 3 files changed, 507 insertions(+), 24 deletions(-) diff --git a/packages/dsh-loopx-plugin/src/driver.ts b/packages/dsh-loopx-plugin/src/driver.ts index 8905e8a0d5..7ba49b413d 100644 --- a/packages/dsh-loopx-plugin/src/driver.ts +++ b/packages/dsh-loopx-plugin/src/driver.ts @@ -210,6 +210,103 @@ interface QueuePlan extends Binding { readonly todoId?: string | undefined } +interface TodoUnitPrefetchPin { + readonly session: Agent['session'] + readonly activationSession: Agent['session'] + readonly activeUnit: ActiveTodoUnitState | undefined + readonly anchor: TodoUnitAnchor | undefined + readonly storedAnchor: TodoUnitAnchor | undefined + readonly stepCount: number + readonly nodes: readonly SessionSeq[] + readonly tailSeqs: readonly SessionSeq[] + readonly eventCount: number + readonly lastEventSeq: number +} + +function isTodoUnitDriverQuiescent(agent: Agent, state: DriverState): boolean { + return agent.status === 'idle' + && !state.competing + && state.commands.size === 0 + && !inboxHasPending(agent.inbox) + && state.activation.pendingModelCalls.size === 0 + && agent.id === agent.session.id + && agent.id === agent.session.header.id +} + +function captureTodoUnitPrefetchPin( + agent: Agent, + state: DriverState, + retained: SessionDriverRetention, + todoId: string, + anchor: TodoUnitAnchor | undefined, +): TodoUnitPrefetchPin { + const session = agent.session + const nodes = [...session.surface.nodes] + const events = session.snapshotEvents() + const prefixCount = anchor?.prefixNodeCount ?? 0 + return { + session, + activationSession: state.activation.session, + activeUnit: retained.activeTodoUnit, + anchor, + storedAnchor: todoId ? retained.todoUnitAnchors?.get(todoId) : undefined, + stepCount: retained.todoUnitStepCount ?? 0, + nodes, + tailSeqs: nodes.slice(prefixCount), + eventCount: events.length, + lastEventSeq: Number(events.at(-1)?.seq ?? 0), + } +} + +function detectTodoUnitPrefetchInterference( + driverDisposed: boolean, + agent: Agent, + state: DriverState, + retained: SessionDriverRetention, + todoId: string, + anchorOverride: TodoUnitAnchor | undefined, + pin: TodoUnitPrefetchPin, +): string | null { + if ( + driverDisposed || state.stopping || agent.session !== pin.session + || state.activation.session !== pin.activationSession + || agent.id !== agent.session.id || agent.id !== agent.session.header.id + ) { + return 'session_changed_during_prefetch' + } + if (retained.activeTodoUnit !== pin.activeUnit) { + return 'active_unit_changed_during_prefetch' + } + const currentStoredAnchor = todoId ? retained.todoUnitAnchors?.get(todoId) : undefined + const currentAnchor = anchorOverride ?? currentStoredAnchor + if ( + currentAnchor !== pin.anchor + || currentStoredAnchor !== pin.storedAnchor + || (retained.todoUnitStepCount ?? 0) !== pin.stepCount + ) { + return 'segment_advanced_during_prefetch' + } + const events = pin.session.snapshotEvents() + const newEvents = events.filter((ev, idx) => idx >= pin.eventCount || Number(ev.seq) > pin.lastEventSeq) + if (newEvents.some(ev => ev.type === 'user/message')) { + return 'user_message_during_prefetch' + } + if (newEvents.some(ev => ( + ev.type === 'step/start' || ev.type === 'turn/start' + || ev.type === 'assistant/message' || ev.type === 'tool/call' || ev.type === 'tool/result' + ))) { + return 'segment_advanced_during_prefetch' + } + const liveNodes = pin.session.surface.nodes + if (liveNodes.length !== pin.nodes.length || liveNodes.some((seq, idx) => seq !== pin.nodes[idx])) { + return 'tail_changed_during_prefetch' + } + if (!isTodoUnitDriverQuiescent(agent, state)) { + return 'non_quiescent_boundary' + } + return null +} + interface WaitPlan { readonly kind: 'wait' readonly delayMs?: number | undefined @@ -949,22 +1046,18 @@ export class LoopXContinuationDriver { if (cached !== undefined) { return cached } - const quiescent = agent.status === 'idle' - && state.commands.size === 0 - && !inboxHasPending(agent.inbox) - && state.activation.pendingModelCalls.size === 0 - && agent.id === agent.session.id - && agent.id === agent.session.header.id + const quiescent = isTodoUnitDriverQuiescent(agent, state) && typeof agent.session.header.cwd === 'string' && agent.session.header.cwd.length > 0 && request.quiescentBoundary !== false const sessionCwd = agent.session.header.cwd - const storedAnchor = retained.todoUnitAnchors?.get(request.todoId) + let storedAnchor = retained.todoUnitAnchors?.get(request.todoId) const activeAnchor = request.anchor ?? storedAnchor let effectiveRequest: TodoUnitFoldRequest = { ...request, quiescentBoundary: quiescent, } + let foldSession = agent.session if ( quiescent && typeof sessionCwd === 'string' @@ -980,21 +1073,52 @@ export class LoopXContinuationDriver { ) { const safeArgv = validateTodoUnitObsForExecution(request.obsNextCmd) if (safeArgv !== null && request.obsNextCmd !== undefined) { + const prefetchPin = captureTodoUnitPrefetchPin(agent, state, retained, request.todoId, activeAnchor) const obsRes = await this.runObsCommand(safeArgv, sessionCwd) - effectiveRequest = { - ...effectiveRequest, - obsNextCmd: { - ...request.obsNextCmd, - command: safeArgv, - exitCode: obsRes.exitCode, - output: obsRes.output, - timedOut: obsRes.timedOut, - truncated: obsRes.truncated, - }, + const interferenceReason = detectTodoUnitPrefetchInterference( + this.disposed, + agent, + state, + retained, + request.todoId, + request.anchor, + prefetchPin, + ) + const obsNextCmd = { + ...request.obsNextCmd, + command: safeArgv, + exitCode: obsRes.exitCode, + output: obsRes.output, + timedOut: obsRes.timedOut, + truncated: obsRes.truncated, + } + if (interferenceReason !== null) { + if ( + interferenceReason === 'user_message_during_prefetch' + || interferenceReason === 'active_unit_changed_during_prefetch' + || interferenceReason === 'tail_changed_during_prefetch' + ) { + retained.todoUnitAnchors?.delete(request.todoId) + } + foldSession = prefetchPin.session + storedAnchor = prefetchPin.storedAnchor + effectiveRequest = { + ...effectiveRequest, + quiescentBoundary: false, + nonQuiescentReason: interferenceReason, + expectedTailSeqs: prefetchPin.tailSeqs, + obsNextCmd, + } + } else { + effectiveRequest = { + ...effectiveRequest, + expectedTailSeqs: prefetchPin.tailSeqs, + obsNextCmd, + } } } } - const outcome = applyTodoUnitFoldAndPrefetch(agent.session, policy, effectiveRequest, storedAnchor) + const outcome = applyTodoUnitFoldAndPrefetch(foldSession, policy, effectiveRequest, storedAnchor) if (outcome.operator === 'FoldToReceipt') { retained.todoUnitAnchors?.delete(request.todoId) if (foldKey !== undefined) { @@ -1896,6 +2020,15 @@ export class LoopXContinuationDriver { retained.activeTodoUnit = undefined return } + const receiptAnchor = active.anchor + ?? (active.todoId !== undefined ? retained.todoUnitAnchors?.get(active.todoId) : undefined) + const receiptPin = captureTodoUnitPrefetchPin( + state.agent, + state, + retained, + active.todoId ?? '', + receiptAnchor, + ) try { const readback = await runJsonCommand(command, [ '--registry', '.loopx/registry.json', '--format', 'json', 'quota', 'receipt', @@ -1908,6 +2041,19 @@ export class LoopXContinuationDriver { signal, }) this.ensureReady(state, signal, state.activation.session) + if ( + detectTodoUnitPrefetchInterference( + this.disposed, + state.agent, + state, + retained, + active.todoId ?? '', + active.anchor, + receiptPin, + ) !== null + ) { + return + } const decoded = decodeQuotaSettlementReadback( readback, binding.goalId, diff --git a/packages/dsh-loopx-plugin/src/todo-unit-fold.ts b/packages/dsh-loopx-plugin/src/todo-unit-fold.ts index 419e7c9c71..c21e4bce00 100644 --- a/packages/dsh-loopx-plugin/src/todo-unit-fold.ts +++ b/packages/dsh-loopx-plugin/src/todo-unit-fold.ts @@ -109,6 +109,8 @@ export interface TodoUnitFoldRequest { readonly baselineTokens?: number | undefined readonly replacementTokens?: number | undefined readonly quiescentBoundary?: boolean | undefined + readonly nonQuiescentReason?: string | undefined + readonly expectedTailSeqs?: readonly SessionSeq[] | undefined readonly failureFacts?: readonly string[] | undefined readonly openObligations?: readonly string[] | undefined } @@ -432,7 +434,7 @@ export function applyTodoUnitFoldAndPrefetch( return keepRawOutcome('disabled', 'disabled') } if (request.quiescentBoundary === false) { - return keepRawOutcome('fallback_keep_raw', 'non_quiescent_boundary') + return keepRawOutcome('fallback_keep_raw', request.nonQuiescentReason ?? 'non_quiescent_boundary') } const anchor = request.anchor ?? storedAnchor @@ -483,6 +485,15 @@ export function applyTodoUnitFoldAndPrefetch( } const shadowedSeqs = nodes.slice(anchor.prefixNodeCount) + if ( + request.expectedTailSeqs !== undefined + && ( + shadowedSeqs.length !== request.expectedTailSeqs.length + || shadowedSeqs.some((seq, i) => seq !== request.expectedTailSeqs![i]) + ) + ) { + return keepRawOutcome('fallback_keep_raw', 'tail_changed_during_prefetch', undefined, undefined, livePrefixDigest) + } const startSeq = shadowedSeqs[0] const endSeq = shadowedSeqs.at(-1) if (startSeq === undefined || endSeq === undefined) { diff --git a/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts b/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts index 1c8b88fccc..10c27e4f3e 100644 --- a/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts +++ b/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts @@ -122,7 +122,7 @@ function appendPrefixQ(session: Session): SessionSeq[] { return [...session.surface.nodes] } -function appendTodoExploratorySuffix(session: Session, suffixTag: string): SessionSeq[] { +function appendTodoExploratorySuffix(session: Session, suffixTag: string, turn = 2): SessionSeq[] { const before = session.surface.nodes.length const callId = `call-${suffixTag}-1` as ToolCallId const bloat = `exploratory search output for ${suffixTag} `.repeat(80) @@ -133,14 +133,14 @@ function appendTodoExploratorySuffix(session: Session, suffixTag: string): Sessi source: { kind: 'user' }, }, { surfaceOp: 'append' }) session.append('tool/call', { - turn: 2, + turn, step: 1, callId, name: 'search', arguments: '{"q":"loopx"}', }) session.append('assistant/message', { - turn: 2, + turn, step: 1, message: { id: `asst-${suffixTag}-1` as MessageId, @@ -151,7 +151,7 @@ function appendTodoExploratorySuffix(session: Session, suffixTag: string): Sessi stream: [], }, { surfaceOp: 'append' }) session.append('tool/result', { - turn: 2, + turn, step: 1, message: { id: `res-${suffixTag}-1` as MessageId, @@ -162,7 +162,7 @@ function appendTodoExploratorySuffix(session: Session, suffixTag: string): Sessi }, }, { surfaceOp: 'append' }) session.append('assistant/message', { - turn: 2, + turn, step: 2, message: { id: `asst-${suffixTag}-2` as MessageId, @@ -923,4 +923,330 @@ describe('dsh-loopx-plugin Todo semantic-unit FoldAndPrefetch', () => { } }, ) + + it('keeps settled tail and mid-prefetch user corrections intact across real DSH inbox and continuation interleavings while running prefetch once', async () => { + const runCase = async (mode: 'clean' | 'session_correction_mid_prefetch' | 'inbox_correction_mid_prefetch') => { + const cwd = await mkdtemp(join(tmpdir(), `dsh-race-${mode}-`)) + const harness = await createRealSessionHarness(cwd) + try { + const sourcePath = join(cwd, 'rollout.jsonl') + const sourceContent = `{"event":"settled","mode":"${mode}"}\n` + await writeFile(sourcePath, sourceContent, 'utf8') + const { createHash } = await import('node:crypto') + const sourceSha = createHash('sha256').update(sourceContent, 'utf8').digest('hex') + + appendPrefixQ(harness.session) + harness.session.append('user/message', { + id: `act-${mode}` as UserMessage['id'], + role: 'user', + content: [{ type: 'text', text: 'loopx' }], + source: { kind: 'skill-invocation', name: 'loopx', form: 'instructions' } as never, + }, { surfaceOp: 'append' }) + + let settledTurn1 = false + let activeTodo = 'todo_real_1' + let stepSeq = 0 + let obsStartedResolve!: () => void + const obsStarted = new Promise(resolve => { obsStartedResolve = resolve }) + let obsReleaseResolve!: () => void + const obsRelease = new Promise(resolve => { obsReleaseResolve = resolve }) + + const obsRunner = vi.fn(async () => { + obsStartedResolve() + if (mode !== 'clean') { + await obsRelease + } + return { exitCode: 0, output: 'OBS_OUTPUT status=clean' } + }) + + const runner: FileRunner = async (_file, args) => { + if (args.includes('resolve-agent-thread')) { + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + schema_version: 'loopx_thread_agent_binding_resolution_v0', + ok: true, + status: 'bound', + host_surface: 'deepseek-harness-native', + thread_id: harness.agent.id, + goal_id: 'goal-race', + agent_id: 'agent-race', + matches: [{ goal_id: 'goal-race', agent_id: 'agent-race' }], + }), + } + } + if (args.includes('quota') && args.includes('should-run')) { + const turnIdx = args.indexOf('--turn-instance-id') + const turnId = turnIdx >= 0 ? args[turnIdx + 1]! : 'turn-x' + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + ok: true, + mode: 'should-run', + goal_id: 'goal-race', + should_run: true, + agent_identity: { agent_id: 'agent-race', registered: true }, + selected_todo: { todo_id: activeTodo, text: `Execute ${activeTodo}` }, + heartbeat_receipt: { + schema_version: 'heartbeat_receipt_v0', + status: 'committed', + turn_instance_id: turnId, + settlement_identity: { goal_id: 'goal-race', agent_id: 'agent-race', turn_instance_id: turnId, todo_id: activeTodo }, + }, + }), + } + } + if (args.includes('quota') && args.includes('receipt') && args.includes('--include-settlement')) { + const turnIdx = args.indexOf('--turn-instance-id') + const turnId = turnIdx >= 0 ? args[turnIdx + 1]! : 'turn-x' + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + ok: true, + schema_version: 'quota_receipt_readback_v0', + goal_id: 'goal-race', + agent_id: 'agent-race', + turn_instance_id: turnId, + settlement_verified: settledTurn1, + settlement_conflict_reason: settledTurn1 ? null : 'missing_completion_event', + completion_receipt: settledTurn1 + ? { + todo_id: 'todo_real_1', + completion_receipt_id: `ev-${turnId}`, + exit_code: 0, + sha256: 'e'.repeat(64), + failure_facts: [], + open_obligations: ['verify selected scope'], + source_ref: { path: sourcePath, sha256: sourceSha }, + } + : null, + }), + } + } + if (args.includes('heartbeat-prompt')) { + const turnIdx = args.indexOf('--turn-instance-id') + const turnId = turnIdx >= 0 ? args[turnIdx + 1]! : 'turn-x' + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + schema_version: 'heartbeat_agent_input_v1', + ok: true, + goal_id: 'goal-race', + agent_id: 'agent-race', + turn_instance_id: turnId, + selected_todo: { todo_id: activeTodo }, + task_body: `LOOPX_TURN=${turnId} work=${activeTodo}`, + }), + } + } + throw new Error(`unexpected cli call: ${args.join(' ')}`) + } + + const queued = harness.queued + let turnCounter = 0 + const driver = new LoopXContinuationDriver({ + isLiveAgent: () => true, + runner, + resolveCommand: async () => ({ file: 'loopx', prefix: [], skillCommand: 'loopx', version: 'loopx 2.4.0' }), + makeTurnInstanceId: () => `turn-race-${++turnCounter}`, + todoUnitFold: { + enabled: true, + minNetSavingsTokens: 64, + obsNextCmd: { command: ['git', 'status', '--short'] }, + }, + runObsCommand: obsRunner, + }) + + driver.observeAgent(harness.agent) + await vi.waitFor(() => expect(queued.length).toBe(1)) + const msg1 = queued.shift()! + driver.onInboxClaimed(harness.agent, msg1) + await driver.onPreStep(harness.agent, [msg1], new AbortController().signal, async () => ({ kind: 'proceed', messages: [msg1] } as never)) + harness.setStatus('running') + driver.onSessionEvent(harness.agent, harness.session.append('user/message', msg1, { surfaceOp: 'append' })) + driver.onSessionEvent(harness.agent, harness.session.append('step/start', { turn: 2, step: ++stepSeq } as never)) + appendTodoExploratorySuffix(harness.session, `race-${mode}`) + driver.onSessionEvent(harness.agent, harness.session.append('turn/end', { turn: 2, reason: { kind: 'completed' } } as never)) + + settledTurn1 = true + activeTodo = 'todo_real_2' + harness.setStatus('idle') + driver.onAgentStatus(harness.agent, 'idle') + + await obsStarted + + const correctionText = `USER_CORRECTION_${mode}: preserve selected todo_real_2 scope` + const correctionMessage: UserMessage = { + id: `corr-${mode}` as UserMessage['id'], + role: 'user', + content: [{ type: 'text', text: correctionText }], + source: { kind: 'user' }, + } + + if (mode === 'clean') { + await vi.waitFor(() => expect(queued.length).toBe(1)) + const derived = harness.session.deriveMessages() + expect(obsRunner).toHaveBeenCalledTimes(1) + expect(derived.some(m => m.role === 'user' && m.source.kind === 'loopx-todo-fold')).toBe(true) + expect(derived.some(m => JSON.stringify(m).includes(`exploratory search output for race-${mode}`))).toBe(false) + return + } + + if (mode === 'session_correction_mid_prefetch') { + const corrEv = harness.session.append('user/message', correctionMessage, { surfaceOp: 'append' }) + driver.onSessionEvent(harness.agent, corrEv) + obsReleaseResolve() + + await vi.waitFor(() => expect(queued.length).toBe(1)) + expect(String((queued[0]!.content[0] as { text: string }).text)).toContain('work=todo_real_2') + } else { + queued.push(correctionMessage) + driver.onInboxInserted(harness.agent, correctionMessage) + obsReleaseResolve() + + // Automatic continuation stays fenced while user inbox correction is pending, and raw tail stays un-folded. + await vi.waitFor(() => expect(obsRunner).toHaveBeenCalledTimes(1)) + await Promise.resolve() + expect(queued).toEqual([correctionMessage]) + expect(harness.session.deriveMessages().some(m => m.role === 'user' && m.source.kind === 'loopx-todo-fold')).toBe(false) + + // Now claim and execute the inbox user correction turn, then return idle so todo_real_2 continues. + const claimedCorrection = queued.shift()! + driver.onInboxClaimed(harness.agent, claimedCorrection) + harness.setStatus('running') + driver.onSessionEvent(harness.agent, harness.session.append('user/message', claimedCorrection, { surfaceOp: 'append' })) + driver.onSessionEvent(harness.agent, harness.session.append('step/start', { turn: 3, step: ++stepSeq } as never)) + driver.onSessionEvent(harness.agent, harness.session.append('turn/end', { turn: 3, reason: { kind: 'completed' } } as never)) + harness.setStatus('idle') + driver.onAgentStatus(harness.agent, 'idle') + + await vi.waitFor(() => expect(queued.length).toBe(1)) + expect(String((queued[0]!.content[0] as { text: string }).text)).toContain('work=todo_real_2') + } + + const finalMessages = harness.session.deriveMessages() + const finalSerialized = JSON.stringify(finalMessages) + expect(obsRunner).toHaveBeenCalledTimes(1) + expect(finalMessages.some(m => m.role === 'user' && m.source.kind === 'loopx-todo-fold')).toBe(false) + expect(finalSerialized).toContain(correctionText) + expect(finalSerialized).toContain(`exploratory search output for race-${mode}`) + expect(harness.session.snapshotEvents().some(ev => JSON.stringify(ev).includes(correctionText))).toBe(true) + } finally { + await harness.dispose() + await rm(cwd, { recursive: true, force: true }) + } + } + + await runCase('clean') + await runCase('session_correction_mid_prefetch') + await runCase('inbox_correction_mid_prefetch') + }) + + it('aborts FoldToReceipt to KeepRaw if a user message or segment advance lands during foldAndPrefetch', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'dsh-fold-segment-')) + const harness = await createRealSessionHarness(cwd) + try { + appendPrefixQ(harness.session) + + let obsStartedResolve!: () => void + let obsStarted = new Promise(resolve => { obsStartedResolve = resolve }) + let obsReleaseResolve!: () => void + let obsRelease = new Promise(resolve => { obsReleaseResolve = resolve }) + const obsRunner = vi.fn(async () => { + obsStartedResolve() + await obsRelease + return { exitCode: 0, output: 'NEXT_OK' } + }) + + const driver = new LoopXContinuationDriver({ + isLiveAgent: () => true, + todoUnitFold: { enabled: true, minNetSavingsTokens: 64 }, + runObsCommand: obsRunner, + }) + + driver.anchorTodoUnit(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-dsh-1', + anchorStepIndex: 2, + }) + appendTodoExploratorySuffix(harness.session, 'mid-fold') + + const settlePromise1 = driver.foldAndPrefetch(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-dsh-1', + nowStepIndex: 5, + completionReceipt: VALID_RECEIPT, + obsNextCmd: { command: ['git', 'status', '--short'] }, + }) + await obsStarted + + // User sends a correction while obsNextCmd is awaiting. + harness.session.append('user/message', { + id: 'corr-direct' as UserMessage['id'], + role: 'user', + content: [{ type: 'text', text: 'Keep this raw correction' }], + source: { kind: 'user' }, + }, { surfaceOp: 'append' }) + obsReleaseResolve() + + const res1 = await settlePromise1 + expect(res1.operator).toBe('KeepRaw') + expect(res1.status).toBe('fallback_keep_raw') + expect(res1.fallbackReason).toBe('user_message_during_prefetch') + expect(obsRunner).toHaveBeenCalledTimes(1) + const msgsAfter1 = JSON.stringify(harness.session.deriveMessages()) + expect(msgsAfter1).toContain('Keep this raw correction') + expect(msgsAfter1).toContain('exploratory search output for mid-fold') + + // Segment advance (new anchor for next Todo) during await also falls back cleanly without removing the new anchor. + obsStarted = new Promise(resolve => { obsStartedResolve = resolve }) + obsRelease = new Promise(resolve => { obsReleaseResolve = resolve }) + driver.anchorTodoUnit(harness.agent, { + todoId: 'todo-s1-2', + turnInstanceId: 'turn-s1-2', + contextEpoch: 'epoch-dsh-1', + anchorStepIndex: 6, + }) + appendTodoExploratorySuffix(harness.session, 'mid-seg', 3) + + const receipt2: TodoUnitCompletionReceipt = { + ...VALID_RECEIPT, + todoId: 'todo-s1-2', + completionReceiptId: 'cqr-s1-2', + } + const settlePromise2 = driver.foldAndPrefetch(harness.agent, { + todoId: 'todo-s1-2', + turnInstanceId: 'turn-s1-2', + contextEpoch: 'epoch-dsh-1', + nowStepIndex: 8, + completionReceipt: receipt2, + obsNextCmd: { command: ['git', 'status', '--short'] }, + }) + await obsStarted + + driver.onSessionEvent(harness.agent, harness.session.append('step/start', { turn: 3, step: 9 } as never)) + driver.anchorTodoUnit(harness.agent, { + todoId: 'todo-s1-2', + turnInstanceId: 'turn-s1-2b', + contextEpoch: 'epoch-dsh-1', + anchorStepIndex: 9, + }) + obsReleaseResolve() + + const res2 = await settlePromise2 + expect(res2.operator).toBe('KeepRaw') + expect(res2.status).toBe('fallback_keep_raw') + expect(res2.fallbackReason).toBe('segment_advanced_during_prefetch') + expect(obsRunner).toHaveBeenCalledTimes(2) + } finally { + await harness.dispose() + await rm(cwd, { recursive: true, force: true }) + } + }) }) From 4cbc2c4b5baed71a7280d8a33a31dcc550b86e1b Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:53:22 +0800 Subject: [PATCH 3/4] fix(dsh-plugin): coalesce concurrent same-foldKey prefetch calls Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- packages/dsh-loopx-plugin/src/driver.ts | 37 +++++++- .../tests/todo-unit-fold.spec.ts | 95 +++++++++++++++++++ 2 files changed, 129 insertions(+), 3 deletions(-) diff --git a/packages/dsh-loopx-plugin/src/driver.ts b/packages/dsh-loopx-plugin/src/driver.ts index 7ba49b413d..87a8da2817 100644 --- a/packages/dsh-loopx-plugin/src/driver.ts +++ b/packages/dsh-loopx-plugin/src/driver.ts @@ -149,6 +149,7 @@ interface SessionDriverRetention { activeTodoUnit?: ActiveTodoUnitState | undefined todoUnitAnchors?: Map | undefined todoUnitFolds?: Map | undefined + todoUnitFoldsInFlight?: Map> | undefined } // HMR can replace this module while the same Agent and Session keep running. @@ -1032,10 +1033,10 @@ export class LoopXContinuationDriver { * atomically pops contiguous suffix `[anchor..now] -> [mu + Obs(next_cmd)]` on * quiescent boundaries while keeping parent prefix Q byte-identical and tool pairing valid. */ - async onTodoUnitSettled(agent: Agent, request: TodoUnitFoldRequest): Promise { + onTodoUnitSettled(agent: Agent, request: TodoUnitFoldRequest): Promise { const policy = this.todoUnitFold if (policy?.enabled !== true) { - return applyTodoUnitFoldAndPrefetch(agent.session, policy, request) + return Promise.resolve(applyTodoUnitFoldAndPrefetch(agent.session, policy, request)) } const state = this.stateFor(agent) const retained = retainedState(agent, agent.session) @@ -1044,8 +1045,38 @@ export class LoopXContinuationDriver { : undefined const cached = foldKey !== undefined ? retained.todoUnitFolds?.get(foldKey) : undefined if (cached !== undefined) { - return cached + return Promise.resolve(cached) } + if (foldKey !== undefined) { + const inFlight = retained.todoUnitFoldsInFlight?.get(foldKey) + if (inFlight !== undefined) { + return inFlight + } + const inFlightMap = retained.todoUnitFoldsInFlight ??= new Map() + let execution!: Promise + execution = (async (): Promise => { + try { + return await this.executeTodoUnitSettled(agent, state, retained, policy, request, foldKey) + } finally { + if (inFlightMap.get(foldKey) === execution) { + inFlightMap.delete(foldKey) + } + } + })() + inFlightMap.set(foldKey, execution) + return execution + } + return this.executeTodoUnitSettled(agent, state, retained, policy, request, undefined) + } + + private async executeTodoUnitSettled( + agent: Agent, + state: DriverState, + retained: SessionDriverRetention, + policy: TodoUnitFoldPolicy, + request: TodoUnitFoldRequest, + foldKey: string | undefined, + ): Promise { const quiescent = isTodoUnitDriverQuiescent(agent, state) && typeof agent.session.header.cwd === 'string' && agent.session.header.cwd.length > 0 diff --git a/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts b/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts index 10c27e4f3e..b73d27b320 100644 --- a/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts +++ b/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts @@ -1249,4 +1249,99 @@ describe('dsh-loopx-plugin Todo semantic-unit FoldAndPrefetch', () => { await rm(cwd, { recursive: true, force: true }) } }) + + it('coalesces concurrent same-foldKey invocations in flight and allows sequential retry only after failure or KeepRaw', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'dsh-fold-coalesce-')) + const harness = await createRealSessionHarness(cwd) + try { + appendPrefixQ(harness.session) + + let obsStartedResolve!: () => void + let obsStarted = new Promise(resolve => { obsStartedResolve = resolve }) + let obsReleaseResolve!: () => void + let obsRelease = new Promise(resolve => { obsReleaseResolve = resolve }) + let failMode: 'throw' | 'error_code' | 'ok' = 'throw' + + const obsRunner = vi.fn(async () => { + obsStartedResolve() + await obsRelease + if (failMode === 'throw') throw new Error('transient obs failure') + if (failMode === 'error_code') return { exitCode: 2, output: 'transient obs exit 2' } + return { exitCode: 0, output: 'NEXT_COALESCED_OK' } + }) + + const driver = new LoopXContinuationDriver({ + isLiveAgent: () => true, + todoUnitFold: { enabled: true, minNetSavingsTokens: 64 }, + runObsCommand: obsRunner, + }) + + driver.anchorTodoUnit(harness.agent, { + todoId: VALID_RECEIPT.todoId, + turnInstanceId: 'turn-coalesce-1', + contextEpoch: 'epoch-coalesce-1', + anchorStepIndex: 2, + }) + appendTodoExploratorySuffix(harness.session, 'coalesce', 2) + + const req = { + todoId: VALID_RECEIPT.todoId, + turnInstanceId: 'turn-coalesce-1', + contextEpoch: 'epoch-coalesce-1', + nowStepIndex: 5, + completionReceipt: VALID_RECEIPT, + obsNextCmd: { command: ['git', 'status', '--short'] as const }, + } + + // 1. Concurrent failure rejects both callers once and cleans up in-flight map for retry. + const concurrentErr = Promise.allSettled([ + driver.onTodoUnitSettled(harness.agent, req), + driver.foldAndPrefetch(harness.agent, req), + ]) + await obsStarted + obsReleaseResolve() + const errResults = await concurrentErr + expect(obsRunner).toHaveBeenCalledTimes(1) + expect(errResults.map(r => r.status)).toEqual(['rejected', 'rejected']) + + // 2. Concurrent KeepRaw (exitCode != 0) coalesces to 1 obs invocation and remains retryable. + obsStarted = new Promise(resolve => { obsStartedResolve = resolve }) + obsRelease = new Promise(resolve => { obsReleaseResolve = resolve }) + failMode = 'error_code' + const concurrentKeepRaw = Promise.all([ + driver.onTodoUnitSettled(harness.agent, req), + driver.foldAndPrefetch(harness.agent, req), + ]) + await obsStarted + obsReleaseResolve() + const [kr1, kr2] = await concurrentKeepRaw + expect(obsRunner).toHaveBeenCalledTimes(2) + expect(kr1.operator).toBe('KeepRaw') + expect(kr2).toEqual(kr1) + + // 3. Concurrent success across both public entrypoints executes obs once, writes one FoldToReceipt, and replays cached thereafter. + obsStarted = new Promise(resolve => { obsStartedResolve = resolve }) + obsRelease = new Promise(resolve => { obsReleaseResolve = resolve }) + failMode = 'ok' + const p1 = driver.onTodoUnitSettled(harness.agent, req) + const p2 = driver.foldAndPrefetch(harness.agent, req) + await obsStarted + obsReleaseResolve() + const [ok1, ok2] = await Promise.all([p1, p2]) + expect(obsRunner).toHaveBeenCalledTimes(3) + expect(ok1.operator).toBe('FoldToReceipt') + expect(ok2).toEqual(ok1) + expect(ok1.foldedEventSeq).not.toBeNull() + expect( + harness.session.deriveMessages().filter(m => m.role === 'user' && m.source.kind === 'loopx-todo-fold'), + ).toHaveLength(1) + + const replay = await driver.foldAndPrefetch(harness.agent, req) + expect(replay).toEqual(ok1) + expect(obsRunner).toHaveBeenCalledTimes(3) + } finally { + await harness.dispose() + await rm(cwd, { recursive: true, force: true }) + } + }) }) From 817e67ab32a0b7c2535e699bb50c55d0fc167c77 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:18:19 +0800 Subject: [PATCH 4/4] fix(dsh-plugin): register in-flight fold before re-entrant execution Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- packages/dsh-loopx-plugin/src/driver.ts | 28 ++++-- .../tests/todo-unit-fold.spec.ts | 87 +++++++++++++++++++ 2 files changed, 107 insertions(+), 8 deletions(-) diff --git a/packages/dsh-loopx-plugin/src/driver.ts b/packages/dsh-loopx-plugin/src/driver.ts index 87a8da2817..b6e2ec1dec 100644 --- a/packages/dsh-loopx-plugin/src/driver.ts +++ b/packages/dsh-loopx-plugin/src/driver.ts @@ -1053,17 +1053,29 @@ export class LoopXContinuationDriver { return inFlight } const inFlightMap = retained.todoUnitFoldsInFlight ??= new Map() - let execution!: Promise - execution = (async (): Promise => { - try { - return await this.executeTodoUnitSettled(agent, state, retained, policy, request, foldKey) - } finally { + let resolveExecution!: (outcome: TodoUnitFoldOutcome) => void + let rejectExecution!: (reason: unknown) => void + const execution = new Promise((resolve, reject) => { + resolveExecution = resolve + rejectExecution = reject + }) + // Register before invoking executeTodoUnitSettled so synchronous re-entry + // inside runObsCommand joins the single in-flight observation execution. + inFlightMap.set(foldKey, execution) + void this.executeTodoUnitSettled(agent, state, retained, policy, request, foldKey).then( + outcome => { if (inFlightMap.get(foldKey) === execution) { inFlightMap.delete(foldKey) } - } - })() - inFlightMap.set(foldKey, execution) + resolveExecution(outcome) + }, + reason => { + if (inFlightMap.get(foldKey) === execution) { + inFlightMap.delete(foldKey) + } + rejectExecution(reason) + }, + ) return execution } return this.executeTodoUnitSettled(agent, state, retained, policy, request, undefined) diff --git a/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts b/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts index b73d27b320..196b8aed4f 100644 --- a/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts +++ b/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts @@ -17,6 +17,7 @@ import type { TodoUnitObsRunner, } from '../src/driver.ts' import { deriveMessagesPrefixDigest } from '../src/todo-unit-fold.ts' +import type { TodoUnitFoldOutcome } from '../src/todo-unit-fold.ts' async function createRealSessionHarness(cwd: string) { const ctx = new Context() @@ -1344,4 +1345,90 @@ describe('dsh-loopx-plugin Todo semantic-unit FoldAndPrefetch', () => { await rm(cwd, { recursive: true, force: true }) } }) + + it('coalesces synchronous re-entrant calls inside obsRunner before the outer promise returns', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'dsh-fold-reentrant-')) + const harness = await createRealSessionHarness(cwd) + try { + appendPrefixQ(harness.session) + + let driver!: LoopXContinuationDriver + let reentrantPromise: Promise | undefined + let mode: 'throw' | 'error_code' | 'ok' = 'throw' + + const req = { + todoId: VALID_RECEIPT.todoId, + turnInstanceId: 'turn-reentrant-1', + contextEpoch: 'epoch-reentrant-1', + nowStepIndex: 5, + completionReceipt: VALID_RECEIPT, + obsNextCmd: { command: ['git', 'status', '--short'] as const }, + } + + const obsRunner = vi.fn(() => { + // Trigger a synchronous re-entrant settlement before obsRunner even returns a Promise. + if (reentrantPromise === undefined) { + reentrantPromise = driver.foldAndPrefetch(harness.agent, req) + } + if (mode === 'throw') { + return Promise.reject(new Error('transient reentrant failure')) + } + if (mode === 'error_code') { + return Promise.resolve({ exitCode: 2, output: 'reentrant obs exit 2' }) + } + return Promise.resolve({ exitCode: 0, output: 'NEXT_REENTRANT_OK' }) + }) + + driver = new LoopXContinuationDriver({ + isLiveAgent: () => true, + todoUnitFold: { enabled: true, minNetSavingsTokens: 64 }, + runObsCommand: obsRunner, + }) + + driver.anchorTodoUnit(harness.agent, { + todoId: VALID_RECEIPT.todoId, + turnInstanceId: 'turn-reentrant-1', + contextEpoch: 'epoch-reentrant-1', + anchorStepIndex: 2, + }) + appendTodoExploratorySuffix(harness.session, 'reentrant', 2) + + // 1. Synchronous re-entry on a failing observation rejects both callers once and cleans up for retry. + const errOuter = driver.onTodoUnitSettled(harness.agent, req) + expect(reentrantPromise).toBe(errOuter) + const [errRes1, errRes2] = await Promise.allSettled([errOuter, reentrantPromise!]) + expect(obsRunner).toHaveBeenCalledTimes(1) + expect([errRes1.status, errRes2.status]).toEqual(['rejected', 'rejected']) + + // 2. Synchronous re-entry on KeepRaw (exitCode != 0) runs obsRunner once, returns identical KeepRaw, and allows retry. + reentrantPromise = undefined + mode = 'error_code' + const krOuter = driver.onTodoUnitSettled(harness.agent, req) + expect(reentrantPromise).toBe(krOuter) + const [krOuterRes, krInnerRes] = await Promise.all([krOuter, reentrantPromise!]) + expect(obsRunner).toHaveBeenCalledTimes(2) + expect(krOuterRes.operator).toBe('KeepRaw') + expect(krInnerRes).toEqual(krOuterRes) + + // 3. Retry with synchronous re-entry invokes obsRunner once and yields identical FoldToReceipt to both callers. + reentrantPromise = undefined + mode = 'ok' + const okOuter = driver.onTodoUnitSettled(harness.agent, req) + expect(reentrantPromise).toBe(okOuter) + const [okOuterRes, okInnerRes] = await Promise.all([okOuter, reentrantPromise!]) + expect(obsRunner).toHaveBeenCalledTimes(3) + expect(okOuterRes.operator).toBe('FoldToReceipt') + expect(okInnerRes).toEqual(okOuterRes) + expect( + harness.session.deriveMessages().filter(m => m.role === 'user' && m.source.kind === 'loopx-todo-fold'), + ).toHaveLength(1) + + const replay = await driver.foldAndPrefetch(harness.agent, req) + expect(replay).toEqual(okOuterRes) + expect(obsRunner).toHaveBeenCalledTimes(3) + } finally { + await harness.dispose() + await rm(cwd, { recursive: true, force: true }) + } + }) })