diff --git a/benchmark/runtime/session_observation.py b/benchmark/runtime/session_observation.py index b1dd0b3a1c..0186bf7f44 100644 --- a/benchmark/runtime/session_observation.py +++ b/benchmark/runtime/session_observation.py @@ -197,6 +197,173 @@ def observe_codex_session_tail( } +def collect_context_policy_telemetry( + runtime_root: Path | None = None, + *, + goal_id: str | None = None, + context_dir: Path | None = None, + usage: dict | None = None, +) -> dict: + """Collect {KeepRaw, FoldToReceipt, EpochReset}, prefetch, quiet-turn, and cold/warm KV telemetry.""" + operator_counts = {"KeepRaw": 0, "FoldToReceipt": 0, "EpochReset": 0} + quiet_turn_skips = 0 + prefetch_attempts = 0 + prefetch_latency_ms = 0 + prefetch_bytes = 0 + prefetch_bytes_saved = 0 + round_trips_saved = 0 + seen_receipts: set[str] = set() + seen_quiet_turns: set[str] = set() + + def _consume_prefetch(entry: object) -> None: + nonlocal prefetch_attempts, prefetch_latency_ms, prefetch_bytes, prefetch_bytes_saved, round_trips_saved + if not isinstance(entry, dict): + return + receipt_id = entry.get("receipt_sha256") + if isinstance(receipt_id, str) and receipt_id: + if receipt_id in seen_receipts: + return + seen_receipts.add(receipt_id) + prefetch_attempts += 1 + op = entry.get("operator") + if op in operator_counts: + operator_counts[op] += 1 + if isinstance(entry.get("latency_ms"), int) and entry["latency_ms"] >= 0: + prefetch_latency_ms += entry["latency_ms"] + if isinstance(entry.get("retained_bytes"), int) and entry["retained_bytes"] >= 0: + prefetch_bytes += entry["retained_bytes"] + if isinstance(entry.get("bytes_saved"), int) and entry["bytes_saved"] >= 0: + prefetch_bytes_saved += entry["bytes_saved"] + if isinstance(entry.get("round_trips_saved"), int) and entry["round_trips_saved"] >= 0: + round_trips_saved += entry["round_trips_saved"] + + def _consume_quiet(entry: object, dedup_key: str | None = None) -> None: + nonlocal quiet_turn_skips + if not isinstance(entry, dict) or entry.get("skipped") is not True: + return + if dedup_key: + if dedup_key in seen_quiet_turns: + return + seen_quiet_turns.add(dedup_key) + quiet_turn_skips += 1 + + if runtime_root is not None and goal_id: + goal_root = Path(runtime_root) / "goals" / goal_id + turns_dir = goal_root / "turns" + if turns_dir.is_dir(): + for path in sorted(turns_dir.glob("*.json")): + try: + journal = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + if isinstance(journal, dict): + _consume_prefetch(journal.get("epoch_prefetch")) + turn_id = str(journal.get("turn_key") or path.stem) + _consume_quiet(journal.get("quiet_turn"), turn_id) + quiet_skips_dir = goal_root / "quiet_turn" / "skips" + if quiet_skips_dir.is_dir(): + for path in sorted(quiet_skips_dir.glob("*.json")): + try: + receipt = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + if isinstance(receipt, dict): + turn_id = str(receipt.get("turn_key") or path.stem) + _consume_quiet(receipt.get("quiet_turn") or receipt, turn_id) + sqlite_path = goal_root / "turn_prefetch_state.sqlite" + if sqlite_path.is_file(): + import sqlite3 + from contextlib import closing + + try: + with closing(sqlite3.connect(sqlite_path, timeout=2.0)) as conn: + rows = conn.execute( + "SELECT turn_key, receipt_json FROM quiet_turn_skips ORDER BY recorded_at" + ).fetchall() + for row_key, row_json in rows: + try: + receipt = json.loads(row_json) + except (TypeError, ValueError): + continue + if isinstance(receipt, dict): + _consume_quiet(receipt.get("quiet_turn") or receipt, str(row_key)) + except sqlite3.Error: + pass + + if context_dir is not None: + session_file = Path(context_dir) / "session.json" + if session_file.is_file(): + try: + session_data = json.loads(session_file.read_text(encoding="utf-8")) + except (OSError, ValueError): + session_data = {} + if isinstance(session_data, dict): + _consume_prefetch(session_data.get("epoch_prefetch")) + _consume_quiet(session_data.get("quiet_turn"), "__codex_session__") + + cold = {"requests": 0, "uncached_prefix_kv_tokens": 0, "cached_prefix_kv_tokens": 0} + warm = {"requests": 0, "uncached_prefix_kv_tokens": 0, "cached_prefix_kv_tokens": 0} + if isinstance(usage, dict): + embedded = usage.get("context_policy_telemetry") + embedded_kv = embedded.get("prefix_kv") if isinstance(embedded, dict) else None + if ( + isinstance(embedded_kv, dict) + and isinstance(embedded_kv.get("cold"), dict) + and isinstance(embedded_kv.get("warm"), dict) + ): + for dst, src in ((cold, embedded_kv["cold"]), (warm, embedded_kv["warm"])): + for key in ("requests", "uncached_prefix_kv_tokens", "cached_prefix_kv_tokens"): + val = src.get(key) + if isinstance(val, int) and not isinstance(val, bool) and val >= 0: + dst[key] = val + else: + coverage = usage.get("request_coverage") + requests = coverage.get("requests") if isinstance(coverage, dict) else None + if isinstance(requests, list): + for req in requests: + if not isinstance(req, dict): + continue + inp = req.get("input_tokens") + cached = req.get("cached_input_tokens") + if not isinstance(inp, int) or not isinstance(cached, int) or inp < cached: + continue + uncached = inp - cached + is_cold = ( + cached == 0 + or req.get("cache_regime") == "cold" + or req.get("compacted") is True + ) + bucket = cold if is_cold else warm + bucket["requests"] += 1 + bucket["uncached_prefix_kv_tokens"] += uncached + bucket["cached_prefix_kv_tokens"] += cached + elif isinstance(usage.get("input_tokens"), int) and isinstance(usage.get("cached_input_tokens"), int): + cached = usage["cached_input_tokens"] + uncached = max(0, usage["input_tokens"] - cached) + bucket = cold if cached == 0 else warm + bucket["requests"] = int(usage.get("completed_turns") or 1) + bucket["uncached_prefix_kv_tokens"] = uncached + bucket["cached_prefix_kv_tokens"] = cached + + return { + "schema_version": "loopx_context_policy_telemetry_v0", + "operator_counts": operator_counts, + "quiet_turn_skips": quiet_turn_skips, + "prefetch_latency_ms": prefetch_latency_ms, + "prefetch_bytes": prefetch_bytes, + "prefetch_bytes_saved": prefetch_bytes_saved, + "round_trips_saved": round_trips_saved, + "prefetch": { + "attempts": prefetch_attempts, + "latency_ms": prefetch_latency_ms, + "output_bytes": prefetch_bytes, + "bytes_saved": prefetch_bytes_saved, + "round_trips_saved": round_trips_saved, + }, + "prefix_kv": {"cold": cold, "warm": warm}, + } + + def main(argv: list[str] | None = None) -> int: """Print one bounded observation for an explicitly selected rollout.""" parser = argparse.ArgumentParser( diff --git a/loopx/capabilities/benchmark_toolkit/experiment_board.py b/loopx/capabilities/benchmark_toolkit/experiment_board.py index 26453c50b2..e5cde4c201 100644 --- a/loopx/capabilities/benchmark_toolkit/experiment_board.py +++ b/loopx/capabilities/benchmark_toolkit/experiment_board.py @@ -17,6 +17,10 @@ build_benchmark_factorial_contrasts, build_benchmark_metric_delta, ) +from .token_capacity import ( + CONTEXT_POLICY_EFFORT_TELEMETRY_FIELDS, + normalize_operator_counts, +) Payload = dict[str, object] PayloadView = Mapping[str, object] @@ -204,25 +208,26 @@ def _countability(value: object) -> dict[str, bool]: return result -def _effort(value: object) -> dict[str, float | int]: +def _effort(value: object) -> Payload: if value in (None, {}): return {} if not isinstance(value, Mapping): raise TypeError("effort must be an object") view = _as_map(value) + int_fields = ( + "duration_ms", + "agent_steps", + "goal_turns", + "token_count", + *CONTEXT_POLICY_EFFORT_TELEMETRY_FIELDS, + ) _reject_unknown_fields( view, - allowed={ - "duration_ms", - "agent_steps", - "goal_turns", - "token_count", - "estimated_cost_usd", - }, + allowed={*int_fields, "estimated_cost_usd", "operator_counts"}, field="effort", ) - result: dict[str, float | int] = {} - for field in ("duration_ms", "agent_steps", "goal_turns", "token_count"): + result: Payload = {} + for field in int_fields: if field in view: result[field] = _non_negative_int(view[field], field=f"effort.{field}") if "estimated_cost_usd" in view: @@ -231,6 +236,12 @@ def _effort(value: object) -> dict[str, float | int]: field="effort.estimated_cost_usd", non_negative=True, ) + if "operator_counts" in view: + result["operator_counts"] = normalize_operator_counts( + view["operator_counts"], + field="effort.operator_counts", + validate_int=lambda v, f: _non_negative_int(v, field=f), + ) return result diff --git a/loopx/capabilities/benchmark_toolkit/study_projection.py b/loopx/capabilities/benchmark_toolkit/study_projection.py index 4c5acbb57b..ed08d392bb 100644 --- a/loopx/capabilities/benchmark_toolkit/study_projection.py +++ b/loopx/capabilities/benchmark_toolkit/study_projection.py @@ -35,6 +35,7 @@ BENCHMARK_RUNTIME_OBSERVATION_SCHEMA_VERSION, build_benchmark_runtime_observation, ) +from .token_capacity import aggregate_context_policy_effort Payload = dict[str, object] PayloadView = Mapping[str, object] @@ -1007,6 +1008,7 @@ def _effort_aggregate(rows: Sequence[PayloadView]) -> Payload: "mean": statistics.fmean(values) if values else None, "median": statistics.median(values) if values else None, } + output.update(aggregate_context_policy_effort(rows)) return output diff --git a/loopx/capabilities/benchmark_toolkit/token_capacity.py b/loopx/capabilities/benchmark_toolkit/token_capacity.py index bcd1cddeb7..3fdc5eb90a 100644 --- a/loopx/capabilities/benchmark_toolkit/token_capacity.py +++ b/loopx/capabilities/benchmark_toolkit/token_capacity.py @@ -1,9 +1,10 @@ from __future__ import annotations import json -from collections.abc import Mapping +from collections.abc import Callable, Mapping, Sequence from datetime import datetime, timedelta from pathlib import Path +import statistics from typing import Any from ...domain_state import default_domain_state_file_path @@ -38,6 +39,73 @@ "evaluator_reserve_tokens_per_minute", "cooldown_seconds", } +_CACHE_REGIMES = {"cold", "warm"} +_CONTEXT_POLICY_OPERATORS = ("KeepRaw", "FoldToReceipt", "EpochReset") +CONTEXT_POLICY_OPERATORS = _CONTEXT_POLICY_OPERATORS +CONTEXT_POLICY_EFFORT_TELEMETRY_FIELDS = ( + "cached_prefix_kv_tokens", + "uncached_prefix_kv_tokens", + "cold_uncached_prefix_kv_tokens", + "cold_cached_prefix_kv_tokens", + "warm_uncached_prefix_kv_tokens", + "warm_cached_prefix_kv_tokens", + "prefetch_latency_ms", + "prefetch_bytes", + "prefetch_bytes_saved", + "quiet_turn_skips", +) + + +def normalize_operator_counts( + value: object, + *, + field: str, + validate_int: Callable[[object, str], int], +) -> dict[str, int]: + """Validate optional context-policy operator counts cleanly across benchmark contracts.""" + if not isinstance(value, Mapping): + raise TypeError(f"{field} must be an object") + _reject_unknown_fields( + value, + allowed=set(_CONTEXT_POLICY_OPERATORS), + field=field, + ) + return { + op: validate_int(value[op], f"{field}.{op}") + for op in _CONTEXT_POLICY_OPERATORS + if op in value + } + + +def aggregate_context_policy_effort(rows: Sequence[Mapping[str, object]]) -> dict[str, object]: + """Aggregate optional context-policy effort telemetry and operator counts when present.""" + output: dict[str, object] = {} + for field in CONTEXT_POLICY_EFFORT_TELEMETRY_FIELDS: + values = [ + float(val) + for row in rows + if isinstance(effort := row.get("effort"), Mapping) + and isinstance(val := effort.get(field), (int, float)) + and not isinstance(val, bool) + ] + if values: + output[field] = { + "denominator": len(values), + "mean": statistics.fmean(values), + "median": statistics.median(values), + } + operator_rows = [ + effort["operator_counts"] + for row in rows + if isinstance(effort := row.get("effort"), Mapping) + and isinstance(effort.get("operator_counts"), Mapping) + ] + if operator_rows: + output["operator_counts"] = { + op: sum(int(ops.get(op, 0)) for ops in operator_rows) + for op in _CONTEXT_POLICY_OPERATORS + } + return output _SAMPLE_FIELDS = { "schema_version", "sample_id", @@ -47,6 +115,12 @@ "uncached_input_tokens", "cached_input_tokens", "output_tokens", + "cache_regime", + "operator_counts", + "quiet_turn_skips", + "prefetch_latency_ms", + "prefetch_bytes", + "prefetch_bytes_saved", } _RESERVATION_FIELDS = { "run_id", @@ -196,6 +270,27 @@ def normalize_benchmark_token_usage_sample( raise ValueError("unmetered samples cannot claim token counts") elif sample["request_count"] == 0 and token_total != 0: raise ValueError("token counts require at least one observed request") + if "cache_regime" in value and value["cache_regime"] is not None: + regime = _token(value.get("cache_regime"), field="cache_regime") + if regime not in _CACHE_REGIMES: + raise ValueError("cache_regime must be cold or warm") + sample["cache_regime"] = regime + if "operator_counts" in value and value["operator_counts"] is not None: + sample["operator_counts"] = normalize_operator_counts( + value["operator_counts"], + field="operator_counts", + validate_int=lambda v, f: _bounded_token_int(v, field=f), + ) + for telemetry_field in ( + "quiet_turn_skips", + "prefetch_latency_ms", + "prefetch_bytes", + "prefetch_bytes_saved", + ): + if telemetry_field in value and value[telemetry_field] is not None: + sample[telemetry_field] = _bounded_token_int( + value[telemetry_field], field=telemetry_field + ) return sample @@ -350,6 +445,57 @@ def _usage_projection( + totals["cached_input_tokens"] + totals["output_tokens"] ) + telemetry: dict[str, Any] = {} + has_regime = any("cache_regime" in item for item in window) + if has_regime: + prefix_kv: dict[str, dict[str, int]] = {} + for regime in ("cold", "warm"): + subset = [item for item in window if item.get("cache_regime") == regime] + prefix_kv[regime] = { + "request_count": sum(item["request_count"] for item in subset), + "uncached_prefix_kv_tokens": sum( + item["uncached_input_tokens"] for item in subset + ), + "cached_prefix_kv_tokens": sum( + item["cached_input_tokens"] for item in subset + ), + } + telemetry["prefix_kv"] = prefix_kv + has_policy = any( + any( + key in item + for key in ( + "operator_counts", + "quiet_turn_skips", + "prefetch_latency_ms", + "prefetch_bytes", + "prefetch_bytes_saved", + ) + ) + for item in window + ) + if has_policy: + op_counts = { + op: sum( + int((item.get("operator_counts") or {}).get(op, 0)) for item in window + ) + for op in _CONTEXT_POLICY_OPERATORS + } + telemetry["context_policy"] = { + "operator_counts": op_counts, + "quiet_turn_skips": sum( + int(item.get("quiet_turn_skips", 0)) for item in window + ), + "prefetch_latency_ms": sum( + int(item.get("prefetch_latency_ms", 0)) for item in window + ), + "prefetch_bytes": sum( + int(item.get("prefetch_bytes", 0)) for item in window + ), + "prefetch_bytes_saved": sum( + int(item.get("prefetch_bytes_saved", 0)) for item in window + ), + } return { "window_seconds": int(_WINDOW.total_seconds()), "window_started_at": (datetime.fromisoformat(observed_at) - _WINDOW) @@ -360,6 +506,7 @@ def _usage_projection( "reason_codes": reason_codes, "sample_count": len(window), **totals, + **telemetry, } diff --git a/loopx/cli_commands/turn_registration.py b/loopx/cli_commands/turn_registration.py index 51cf7d55a3..0ed943b201 100644 --- a/loopx/cli_commands/turn_registration.py +++ b/loopx/cli_commands/turn_registration.py @@ -356,6 +356,17 @@ def register_turn_commands( action="store_true", help="Invoke the host and commit validated writeback/quota effects.", ) + run_once.add_argument( + "--epoch-prefetch-json", + type=json.loads, + default=None, + help="Opt-in Stage-then-Swap EpochReset prefetch configuration JSON (default-off).", + ) + run_once.add_argument( + "--quiet-turn", + action="store_true", + help="Opt-in Quiet-Turn zero-tax skip metadata evaluation when Turn state is unchanged (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 903cd37b2d..e8a6155fc0 100644 --- a/loopx/cli_commands/turn_run_once.py +++ b/loopx/cli_commands/turn_run_once.py @@ -43,6 +43,7 @@ run_codex_cli_host, run_loopx_turn_once, ) +from ..control_plane.turn_driver.quiet_turn_store import build_cli_quiet_turn_option from ..quota import spend_quota_slot from ..state_refresh import refresh_state_run from ..control_plane.todos.path_resolution import resolve_todo_state_path @@ -902,7 +903,17 @@ def on_managed_start_admitted() -> None: ) else None, ) + quiet_turn_option: bool | dict[str, Any] = False + if getattr(args, "quiet_turn", False): + quiet_turn_option = build_cli_quiet_turn_option( + payload, goal_id=args.goal_id, agent_id=args.agent_id, + ) + execution_started = bool(args.execute) + unmeasurable_operation_host = ( + (args.host == "codex-cli" and bool(getattr(args, "codex_operation_tools", False))) + or (args.host == "dsh" and bool(getattr(args, "dsh_operation_module", None))) + ) result = run_loopx_turn_once( payload, decision_capture_payload=decision, @@ -942,6 +953,9 @@ def on_managed_start_admitted() -> None: goal_admission.with_launch_decision(current_launch_decision).launch_lifetime, operation="turn_external_host_launch", ) 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, + **({"host_input_renderer": None} if unmeasurable_operation_host else {}), ) if args.execute: result.update(drain_committed_turn_post_writeback_hooks( diff --git a/loopx/control_plane/capabilities/trajectory_assessment_types.ts b/loopx/control_plane/capabilities/trajectory_assessment_types.ts index 651a6fd461..567e41ce23 100644 --- a/loopx/control_plane/capabilities/trajectory_assessment_types.ts +++ b/loopx/control_plane/capabilities/trajectory_assessment_types.ts @@ -90,6 +90,41 @@ export interface TrajectoryPartialTurnUsage { uncached_input_tokens: number; output_tokens: number} | null; } +export type ContextPolicyOperatorName = 'KeepRaw' | 'FoldToReceipt' | 'EpochReset'; + +export interface ContextPolicyOperatorCounts { + KeepRaw: number; + FoldToReceipt: number; + EpochReset: number; +} + +export interface PrefetchTelemetrySummary { + attempts: number; + latency_ms: number; + output_bytes: number; + bytes_saved: number; + round_trips_saved: number; +} + +export interface PrefixKvRegimeStats { + requests: number; + uncached_prefix_kv_tokens: number; + cached_prefix_kv_tokens: number; +} + +export interface PrefixKvRegimeBreakdown { + cold: PrefixKvRegimeStats; + warm: PrefixKvRegimeStats; +} + +export interface ContextPolicyTelemetry { + schema_version: 'loopx_context_policy_telemetry_v0'; + operator_counts: ContextPolicyOperatorCounts; + quiet_turn_skips: number; + prefetch: PrefetchTelemetrySummary; + prefix_kv?: PrefixKvRegimeBreakdown; +} + export interface TrajectorySolverUsage { session_id: string; method: 'codex_complete_session_counters_v1' | 'codex_observed_session_counters_v1'; incomplete_turn?: TrajectoryPartialTurnUsage | null; @@ -110,6 +145,8 @@ export interface TrajectorySolverUsage { tool_context?: TrajectoryToolContext; /** Whole requests issuing recognized commands, never control-text attribution. */ loopx_requests?: TrajectoryLoopXRequests; + /** Optional context-policy operator, prefetch, quiet-turn, and cold/warm KV regime telemetry. */ + context_policy_telemetry?: ContextPolicyTelemetry; } export type TrajectoryLoopXRequests = {method: 'codex_ordered_loopx_requests_v1'} & ( diff --git a/loopx/control_plane/capabilities/trajectory_codex_usage.ts b/loopx/control_plane/capabilities/trajectory_codex_usage.ts index 17c1a96b16..6d011e6473 100644 --- a/loopx/control_plane/capabilities/trajectory_codex_usage.ts +++ b/loopx/control_plane/capabilities/trajectory_codex_usage.ts @@ -1,6 +1,12 @@ /** Read-only Codex session adapter for benchmark-toolkit, separate from model judgments. */ import {EffectRuntimeRequestError} from '../effect_runtime_errors.ts'; -import type {TrajectoryPartialTurnUsage, TrajectorySolverUsage} from './trajectory_assessment_types.ts'; +import type { + ContextPolicyOperatorName, + ContextPolicyTelemetry, + PrefixKvRegimeBreakdown, + TrajectoryPartialTurnUsage, + TrajectorySolverUsage, +} from './trajectory_assessment_types.ts'; import {isIdentifiedTurnAbort, reconcileTrajectoryRequests, summarizeTrajectoryLoopXInput} from './trajectory_request_usage.ts'; import {estimateTrajectoryLoopXInput} from './trajectory_input_usage.ts'; import {summarizeTrajectoryToolContext} from './trajectory_tool_context.ts'; @@ -41,6 +47,8 @@ export function summarizeTrajectoryCodexUsage(params: Record): let active: ActiveTurn | null = null, interruptedSeconds = 0; const turns: TrajectorySolverUsage['turns'] = []; const interruptedTurns: TrajectoryPartialTurnUsage[] = []; + const tokenCountDeltas: Array<{input_tokens: number; cached_input_tokens: number; compacted?: boolean}> = []; + let pendingCompaction = false; const started = new Set(); let previousLine = 0; for (const event of rows) { @@ -54,6 +62,10 @@ export function summarizeTrajectoryCodexUsage(params: Record): continue; } if (!sessionSeen) return fail('session header missing'); + if (event.type === 'compacted' || (event.type === 'event_msg' && p?.type === 'compacted')) { + pendingCompaction = true; + continue; + } if (event.type !== 'event_msg') continue; const interrupted = isIdentifiedTurnAbort(p); if (!interrupted && !['task_started', 'task_complete', 'token_count'].includes(p?.type)) continue; @@ -82,6 +94,14 @@ export function summarizeTrajectoryCodexUsage(params: Record): // Repeated observations are legal. A changed total must represent exactly // the newly observed request, including the first request after zero. if (counterKeys.some(k => delta[k] !== 0) && counterKeys.some(k => delta[k] !== last[k])) return fail('missing usage prefix or counter gap'); + if (counterKeys.some(k => delta[k] !== 0)) { + tokenCountDeltas.push({ + input_tokens: delta.input_tokens, + cached_input_tokens: delta.cached_input_tokens, + ...(pendingCompaction ? {compacted: true} : {}), + }); + pendingCompaction = false; + } previous = total; samples++; active.samples++; } else if (p.type === 'task_complete') { if (!active || p.turn_id !== active.turn_id || !active.samples) return fail('unmatched or unmeasured completed Turn'); @@ -105,11 +125,13 @@ export function summarizeTrajectoryCodexUsage(params: Record): const loopxRequests = toolContext?.status === 'unavailable' ? {method: 'codex_ordered_loopx_requests_v1' as const, status: 'unavailable' as const, reason: toolContext.reason} : summarizeTrajectoryLoopXRequests(rows, params.tool_context, requestCoverage); + const contextPolicyTelemetry = summarizeContextPolicyTelemetryIfRequested(rows, params, requestCoverage, tokenCountDeltas); return {session_id: params.session_id, method: observed ? 'codex_observed_session_counters_v1' : 'codex_complete_session_counters_v1', ...(requestCoverage ? {request_coverage: requestCoverage} : {}), ...(loopxInput ? {loopx_input: loopxInput} : {}), ...(toolContext ? {tool_context: toolContext} : {}), ...(loopxRequests ? {loopx_requests: loopxRequests} : {}), + ...(contextPolicyTelemetry ? {context_policy_telemetry: contextPolicyTelemetry} : {}), ...(observed ? {incomplete_turn: incomplete} : {}), ...(interruptedTurns.length ? {interrupted_turns: interruptedTurns} : {}), start, end, completed_turns: turns.length, counter_observations: samples, @@ -126,3 +148,134 @@ export function summarizeTrajectoryCodexUsage(params: Record): 'Elapsed time includes tools and orchestration; it does not measure CPU time or avoidable overhead.', 'Registered operator binding identifies the case; this does not independently prove run provenance.']}; } + +function nonNegativeInt(value: unknown): number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0; +} + +export function summarizeContextPolicyTelemetry(params: { + policy_events?: unknown; + rows?: ReadonlyArray<{type?: unknown; payload?: any}>; + request_coverage?: TrajectorySolverUsage['request_coverage']; + token_count_deltas?: ReadonlyArray<{input_tokens: number; cached_input_tokens: number; compacted?: boolean}>; +}): ContextPolicyTelemetry { + const operator_counts: Record = { + KeepRaw: 0, + FoldToReceipt: 0, + EpochReset: 0, + }; + let quiet_turn_skips = 0; + let attempts = 0; + let latency_ms = 0; + let output_bytes = 0; + let bytes_saved = 0; + let round_trips_saved = 0; + + const eventsList = Array.isArray(params.policy_events) ? params.policy_events : []; + for (const raw of eventsList) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue; + const item = raw as Record; + const op = item.operator; + if (op === 'KeepRaw' || op === 'FoldToReceipt' || op === 'EpochReset') { + operator_counts[op] += 1; + } + if (item.quiet_turn_skipped === true || item.skipped === true) quiet_turn_skips += 1; + else quiet_turn_skips += nonNegativeInt(item.quiet_turn_skips); + if (item.prefetch_attempted === true || typeof item.latency_ms === 'number' || typeof item.prefetch_latency_ms === 'number') { + attempts += 1; + } + latency_ms += nonNegativeInt(item.latency_ms ?? item.prefetch_latency_ms); + output_bytes += nonNegativeInt(item.output_bytes ?? item.retained_bytes ?? item.prefetch_bytes); + bytes_saved += nonNegativeInt(item.bytes_saved ?? item.prefetch_bytes_saved); + round_trips_saved += nonNegativeInt(item.round_trips_saved); + } + + let prefix_kv: PrefixKvRegimeBreakdown | undefined; + const rows = Array.isArray(params.rows) ? params.rows : []; + const requestRows = rows.filter(r => r?.type === 'token_usage_record' && r.payload && typeof r.payload.usage === 'object'); + if (requestRows.length) { + const cold = {requests: 0, uncached_prefix_kv_tokens: 0, cached_prefix_kv_tokens: 0}; + const warm = {requests: 0, uncached_prefix_kv_tokens: 0, cached_prefix_kv_tokens: 0}; + const compactions = new Set(rows.filter(r => r?.type === 'compacted').map(r => r.payload?.compaction_response_id)); + let nextIsColdRebase = true; + const seen = new Set(); + for (const row of requestRows) { + const p = row.payload!; + if (typeof p.response_id === 'string') { + if (seen.has(p.response_id)) continue; + seen.add(p.response_id); + } + if (compactions.has(p.response_id)) { + nextIsColdRebase = true; + continue; + } + const usage = p.usage as Record; + const inputTokens = nonNegativeInt(usage.input_tokens); + const cachedTokens = nonNegativeInt(usage.cached_input_tokens); + const uncachedTokens = Math.max(0, inputTokens - cachedTokens); + const explicitRegime = p.cache_regime; + const isCold = explicitRegime === 'cold' || (explicitRegime !== 'warm' && (cachedTokens === 0 || nextIsColdRebase)); + const target = isCold ? cold : warm; + target.requests += 1; + target.uncached_prefix_kv_tokens += uncachedTokens; + target.cached_prefix_kv_tokens += cachedTokens; + nextIsColdRebase = false; + } + prefix_kv = {cold, warm}; + } else if (Array.isArray(params.token_count_deltas) && params.token_count_deltas.length) { + const cold = {requests: 0, uncached_prefix_kv_tokens: 0, cached_prefix_kv_tokens: 0}; + const warm = {requests: 0, uncached_prefix_kv_tokens: 0, cached_prefix_kv_tokens: 0}; + params.token_count_deltas.forEach((delta, index) => { + const inp = nonNegativeInt(delta.input_tokens); + const cached = Math.min(inp, nonNegativeInt(delta.cached_input_tokens)); + const uncached = Math.max(0, inp - cached); + const target = index === 0 || delta.compacted === true || cached === 0 ? cold : warm; + target.requests += 1; + target.uncached_prefix_kv_tokens += uncached; + target.cached_prefix_kv_tokens += cached; + }); + prefix_kv = {cold, warm}; + } else if (params.request_coverage && params.request_coverage.status === 'verified') { + const all = params.request_coverage.all_requests; + const uncached = Math.max(0, all.input_tokens - all.cached_input_tokens); + prefix_kv = { + cold: { + requests: all.cached_input_tokens === 0 ? params.request_coverage.unique_requests : 0, + uncached_prefix_kv_tokens: all.cached_input_tokens === 0 ? uncached : 0, + cached_prefix_kv_tokens: 0, + }, + warm: { + requests: all.cached_input_tokens > 0 ? params.request_coverage.unique_requests : 0, + uncached_prefix_kv_tokens: all.cached_input_tokens > 0 ? uncached : 0, + cached_prefix_kv_tokens: all.cached_input_tokens, + }, + }; + } + return { + schema_version: 'loopx_context_policy_telemetry_v0', + operator_counts, + quiet_turn_skips, + prefetch: {attempts, latency_ms, output_bytes, bytes_saved, round_trips_saved}, + ...(prefix_kv ? {prefix_kv} : {}), + }; +} + +function summarizeContextPolicyTelemetryIfRequested( + rows: ReadonlyArray<{type?: unknown; payload?: any}>, + params: Record, + requestCoverage: TrajectorySolverUsage['request_coverage'], + tokenCountDeltas: ReadonlyArray<{input_tokens: number; cached_input_tokens: number; compacted?: boolean}>, +): ContextPolicyTelemetry | undefined { + const inlineEvents = rows + .filter(r => r?.type === 'loopx_context_policy' && r.payload && typeof r.payload === 'object') + .map(r => r.payload); + const supplied = Array.isArray(params.context_policy) ? params.context_policy : undefined; + const includeKv = params.include_prefix_kv_regimes === true; + if (!supplied && !inlineEvents.length && !includeKv) return undefined; + return summarizeContextPolicyTelemetry({ + policy_events: [...(supplied ?? []), ...inlineEvents], + rows, + request_coverage: requestCoverage, + token_count_deltas: tokenCountDeltas, + }); +} diff --git a/loopx/control_plane/quota/native_context_lifecycle.ts b/loopx/control_plane/quota/native_context_lifecycle.ts index b11b3b0d29..c17c58718b 100644 --- a/loopx/control_plane/quota/native_context_lifecycle.ts +++ b/loopx/control_plane/quota/native_context_lifecycle.ts @@ -47,8 +47,16 @@ export function updateNativeContextLifecycle(request: JsonObject): JsonObject { const invalidate = () => { // Reset is idempotent while already invalid. Pre/PostCompact and the // subsequent SessionStart(compact) therefore do not rotate three epochs. - if (!state.context_epoch || state.candidate || state.pending || fileEpochCurrent) + if (!state.context_epoch || state.candidate || state.pending || fileEpochCurrent) { + const previousEpoch = state.context_epoch; state.context_epoch = requireNonEmptyString(request.new_epoch, "new native context epoch"); + if (state.context_epoch !== previousEpoch) { + delete state.epoch_prefetch; + delete state.quiet_turn; + delete state.semantic_unit_anchors; + delete state.semantic_unit_folds; + } + } delete state.candidate; delete state.pending; delete state.active_call; // retire legacy diagnostic-call binding @@ -57,6 +65,20 @@ export function updateNativeContextLifecycle(request: JsonObject): JsonObject { delete state.section_reads; delete state.selected_resume; }; + const applySemanticUnitEventState = () => { + const rawAnchor = jsonObject(request.semantic_unit_anchor); + if (rawAnchor && typeof rawAnchor.todo_id === "string" && rawAnchor.todo_id + && rawAnchor.context_epoch === state.context_epoch) { + const anchors = jsonObject(state.semantic_unit_anchors) ?? {}; + state.semantic_unit_anchors = {...anchors, [rawAnchor.todo_id]: rawAnchor}; + } + const rawFold = jsonObject(request.semantic_unit_fold); + if (rawFold && typeof rawFold.todo_id === "string" && rawFold.todo_id + && rawFold.context_epoch === state.context_epoch) { + const folds = jsonObject(state.semantic_unit_folds) ?? {}; + state.semantic_unit_folds = {...folds, [rawFold.todo_id]: rawFold}; + } + }; if (name === "SessionStart") { // The provider may qualify the native-selected replay source against the // completed read checkpoint. @@ -104,10 +126,12 @@ export function updateNativeContextLifecycle(request: JsonObject): JsonObject { return state; } invalidate(); + applySemanticUnitEventState(); return state; } if (name === "PreCompact" || name === "PostCompact") { invalidate(); + applySemanticUnitEventState(); return state; } if (name === "Interrupt") { @@ -115,6 +139,9 @@ export function updateNativeContextLifecycle(request: JsonObject): JsonObject { return state; } if (name !== "PostToolUse") return state; + if (same && (request.semantic_unit_anchor !== undefined || request.semantic_unit_fold !== undefined)) { + applySemanticUnitEventState(); + } const recovery = jsonObject(state.recovery), pending = jsonObject(state.pending); if (!recovery || !jsonObject(recovery.target)) return state; const pages = Array.isArray(request.pages) ? request.pages : []; diff --git a/loopx/control_plane/quota/stage_then_swap.ts b/loopx/control_plane/quota/stage_then_swap.ts new file mode 100644 index 0000000000..a89ac33f7f --- /dev/null +++ b/loopx/control_plane/quota/stage_then_swap.ts @@ -0,0 +1,1706 @@ +import {createHash} from "node:crypto"; + +import {BARE_SHA256_PATTERN} from "../content_digest.ts"; +import type {JsonObject} from "../effect_program.ts"; +import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; +import { + jsonObject, + optionalNonEmptyString, + requireBoolean, + requireJsonObject, + requireNonEmptyString, +} from "../runtime_decode.ts"; + +export const STAGE_THEN_SWAP_POLICY_SCHEMA_VERSION = "loopx_stage_then_swap_policy_v0"; +export const EPOCH_PREFETCH_RECEIPT_SCHEMA_VERSION = "loopx_epoch_prefetch_receipt_v0"; +export const QUIET_TURN_METADATA_SCHEMA_VERSION = "loopx_quiet_turn_v0"; +export const SEMANTIC_UNIT_ANCHOR_SCHEMA_VERSION = "loopx_semantic_unit_anchor_v0"; +export const SEMANTIC_UNIT_FOLD_SWAP_SCHEMA_VERSION = "loopx_semantic_unit_fold_swap_v0"; +export const CONTEXT_POLICY_OPERATORS = ["KeepRaw", "FoldToReceipt", "EpochReset"] as const; + +export const DEFAULT_PREFETCH_TIMEOUT_MS = 5000; +export const MAX_PREFETCH_TIMEOUT_MS = 60000; +export const DEFAULT_PREFETCH_MAX_OUTPUT_BYTES = 16384; +export const MIN_PREFETCH_MAX_OUTPUT_BYTES = 128; +export const MAX_PREFETCH_MAX_OUTPUT_BYTES = 65536; +export const DEFAULT_MIN_NET_SAVINGS_TOKENS = 64; +export const DEFAULT_COLD_PREFILL_AMORTIZATION_DIVISOR = 20; +export const DEFAULT_TOKENIZER_ENCODING = "o200k_base"; +const SUPPORTED_TOKENIZER_ENCODINGS = new Set([ + "o200k_base", + "cl100k_base", + "o200k_harmony", + "p50k_base", + "r50k_base", +]); + +export type ContextPolicyOperator = (typeof CONTEXT_POLICY_OPERATORS)[number]; + +export interface PrefetchSafetyDecision { + allowed: boolean; + reason: string | null; + argv: string[]; + command_sha256: string | null; +} + +export interface NormalizedStageThenSwapPolicy { + schema_version: typeof STAGE_THEN_SWAP_POLICY_SCHEMA_VERSION; + enabled: boolean; + initiator: string; + prefetch_command: string | string[] | null; + timeout_ms: number; + max_output_bytes: number; + min_net_savings_bytes: number | null; + min_net_savings_tokens: number; + cold_prefill_amortization_tokens: number | null; + tokenizer_encoding: string; + reject_on_truncation: boolean; + replace_exploratory_context: boolean; +} + +const DISALLOWED_SHELL_OPERATORS = new Set([";", "|", "&", "&&", "||", ">", ">>", "<", "<<", "<<<", "(", ")"]); +const READ_ONLY_PROBES = new Set(["cat", "head", "tail", "wc", "ls", "stat", "pwd", "rg", "grep"]); +const GIT_READ_ONLY_SUBCOMMANDS = new Set(["status", "diff", "log", "show", "rev-parse", "ls-files", "grep", "branch"]); +const GIT_READ_ONLY_BRANCH_FLAGS = new Set(["--list", "--show-current", "-a", "--all", "-r", "--remotes", "-v", "--verbose", "-vv"]); +const GIT_FORBIDDEN_OUTPUT_FLAGS = new Set(["--output", "--ext-diff", "--open-files-in-pager", "-O", "--exec"]); +const FIND_MUTATING_PREDICATES = new Set(["-exec", "-execdir", "-ok", "-okdir", "-delete", "-fls", "-fprint", "-fprint0", "-fprintf"]); +const LOOPX_READ_ONLY_SUBCOMMANDS = new Set(["status", "doctor", "version"]); +const LOOPX_QUOTA_READ_SUBCOMMANDS = new Set(["context-read", "receipt"]); +const DISALLOWED_LOOPX_FLAGS = new Set(["--execute"]); +const PASSIVE_PLUGIN_INITIATORS = new Set([ + "history_view_policy", + "plugin", + "passive_policy", + "external_policy_plugin", +]); + +function sha256Hex(value: string): string { + return createHash("sha256").update(value, "utf8").digest("hex"); +} + +function optionalObject(value: unknown, label: string): JsonObject | null { + if (value === undefined || value === null) return null; + return requireJsonObject(value, label); +} + +function optionalInt(value: unknown, label: string, min: number, max: number): number | null { + if (value === undefined || value === null) return null; + if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) { + throw new EffectRuntimeRequestError(`${label} must be an integer between ${min} and ${max}`); + } + return value; +} + +function cleanTextList(value: unknown, limit = 32): string[] { + if (!Array.isArray(value)) return []; + const seen = new Set(); + const items: string[] = []; + for (const raw of value) { + let text = ""; + if (typeof raw === "string") text = raw.trim(); + else if (raw && typeof raw === "object") text = JSON.stringify(raw); + if (!text) continue; + const bounded = text.length > 512 ? `${text.slice(0, 509)}...` : text; + if (seen.has(bounded)) continue; + seen.add(bounded); + items.push(bounded); + if (items.length >= limit) break; + } + return items; +} + +export function normalizeStageThenSwapConfig(value: unknown): NormalizedStageThenSwapPolicy { + if (value === undefined || value === null || value === false) { + return { + schema_version: STAGE_THEN_SWAP_POLICY_SCHEMA_VERSION, + enabled: false, + initiator: "turn_driver", + prefetch_command: null, + timeout_ms: DEFAULT_PREFETCH_TIMEOUT_MS, + max_output_bytes: DEFAULT_PREFETCH_MAX_OUTPUT_BYTES, + min_net_savings_bytes: null, + min_net_savings_tokens: DEFAULT_MIN_NET_SAVINGS_TOKENS, + cold_prefill_amortization_tokens: null, + tokenizer_encoding: DEFAULT_TOKENIZER_ENCODING, + reject_on_truncation: false, + replace_exploratory_context: false, + }; + } + if (typeof value !== "object" || Array.isArray(value)) { + throw new EffectRuntimeRequestError("epoch_prefetch configuration must be an object or boolean"); + } + const config = value as JsonObject; + const enabled = config.enabled === undefined ? false : requireBoolean(config.enabled, "epoch_prefetch.enabled"); + const initiator = optionalNonEmptyString(config.initiator, "epoch_prefetch.initiator") ?? "turn_driver"; + const timeout_ms = + optionalInt(config.timeout_ms, "epoch_prefetch.timeout_ms", 1, MAX_PREFETCH_TIMEOUT_MS) + ?? DEFAULT_PREFETCH_TIMEOUT_MS; + const max_output_bytes = + optionalInt( + config.max_output_bytes, + "epoch_prefetch.max_output_bytes", + MIN_PREFETCH_MAX_OUTPUT_BYTES, + MAX_PREFETCH_MAX_OUTPUT_BYTES, + ) ?? DEFAULT_PREFETCH_MAX_OUTPUT_BYTES; + const min_net_savings_bytes = optionalInt( + config.min_net_savings_bytes, + "epoch_prefetch.min_net_savings_bytes", + 0, + 10_000_000, + ); + const min_net_savings_tokens = + optionalInt( + config.min_net_savings_tokens, + "epoch_prefetch.min_net_savings_tokens", + 0, + 10_000_000, + ) ?? DEFAULT_MIN_NET_SAVINGS_TOKENS; + const cold_prefill_amortization_tokens = optionalInt( + config.cold_prefill_amortization_tokens, + "epoch_prefetch.cold_prefill_amortization_tokens", + 0, + 10_000_000, + ); + const tokenizer_encoding = + optionalNonEmptyString(config.tokenizer_encoding, "epoch_prefetch.tokenizer_encoding") + ?? DEFAULT_TOKENIZER_ENCODING; + if (!SUPPORTED_TOKENIZER_ENCODINGS.has(tokenizer_encoding)) { + throw new EffectRuntimeRequestError("epoch_prefetch.tokenizer_encoding is unsupported"); + } + const reject_on_truncation = + config.reject_on_truncation === undefined + ? false + : requireBoolean(config.reject_on_truncation, "epoch_prefetch.reject_on_truncation"); + const replace_exploratory_context = + config.replace_exploratory_context === undefined + ? false + : requireBoolean(config.replace_exploratory_context, "epoch_prefetch.replace_exploratory_context"); + + let prefetch_command: string | string[] | null = null; + if (config.prefetch_command !== undefined && config.prefetch_command !== null) { + if (typeof config.prefetch_command === "string") { + prefetch_command = config.prefetch_command; + } else if ( + Array.isArray(config.prefetch_command) + && config.prefetch_command.every((part) => typeof part === "string") + ) { + prefetch_command = [...config.prefetch_command]; + } else { + throw new EffectRuntimeRequestError("epoch_prefetch.prefetch_command must be string or string[]"); + } + } + return { + schema_version: STAGE_THEN_SWAP_POLICY_SCHEMA_VERSION, + enabled, + initiator, + prefetch_command, + timeout_ms, + max_output_bytes, + min_net_savings_bytes, + min_net_savings_tokens, + cold_prefill_amortization_tokens, + tokenizer_encoding, + reject_on_truncation, + replace_exploratory_context, + }; +} + +function parsePosixWords(command: string): {ok: true; argv: string[]} | {ok: false; reason: string} { + if (/[\r\n\0]/.test(command)) return {ok: false, reason: "policy_violation:multiline_or_nul"}; + const argv: string[] = []; + let current = ""; + let inToken = false; + let quote: "'" | '"' | null = null; + for (let i = 0; i < command.length; i += 1) { + const ch = command[i]!; + if (quote === "'") { + if (ch === "'") quote = null; + else current += ch; + continue; + } + if (quote === '"') { + if (ch === '"') { + quote = null; + } else if (ch === "\\") { + if (i + 1 >= command.length) return {ok: false, reason: "policy_violation:dangling_escape"}; + current += command[++i]!; + } else if (ch === "$" || ch === "`") { + return {ok: false, reason: "policy_violation:shell_expansion"}; + } else { + current += ch; + } + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + inToken = true; + } else if (ch === "\\") { + if (i + 1 >= command.length) return {ok: false, reason: "policy_violation:dangling_escape"}; + current += command[++i]!; + inToken = true; + } else if (/\s/.test(ch)) { + if (inToken) { + argv.push(current); + current = ""; + inToken = false; + } + } else if (";|&><()$ `*?[]{}".includes(ch)) { + return {ok: false, reason: "policy_violation:shell_metacharacter"}; + } else { + current += ch; + inToken = true; + } + } + if (quote !== null) return {ok: false, reason: "policy_violation:unterminated_quote"}; + if (inToken) argv.push(current); + if (!argv.length) return {ok: false, reason: "policy_violation:empty_command"}; + return {ok: true, argv}; +} + +function normalizePrefetchArgv(command: unknown): {ok: true; argv: string[]} | {ok: false; reason: string} { + if (typeof command === "string") { + return parsePosixWords(command.trim()); + } + if (Array.isArray(command)) { + if (!command.length || command.some((part) => typeof part !== "string" || !part)) { + return {ok: false, reason: "policy_violation:empty_command"}; + } + for (const part of command) { + if (/[\r\n\0]/.test(part)) return {ok: false, reason: "policy_violation:multiline_or_nul"}; + if (DISALLOWED_SHELL_OPERATORS.has(part) || part.includes("$(") || part.includes("`")) { + return {ok: false, reason: "policy_violation:shell_metacharacter"}; + } + } + return {ok: true, argv: [...command]}; + } + return {ok: false, reason: "policy_violation:missing_command"}; +} + +function isLoopxReadOnlyArgs(args: readonly string[]): PrefetchSafetyDecision | null { + let cursor = 0; + while (cursor < args.length && args[cursor]!.startsWith("-")) { + const flag = args[cursor]!; + if (DISALLOWED_LOOPX_FLAGS.has(flag)) { + return null; + } + if (["--registry", "--runtime-root", "--format"].includes(flag)) { + cursor += 2; + continue; + } + if (flag.startsWith("--registry=") || flag.startsWith("--runtime-root=") || flag.startsWith("--format=")) { + cursor += 1; + continue; + } + return null; + } + if (args.some((arg) => DISALLOWED_LOOPX_FLAGS.has(arg))) return null; + const remaining = args.slice(cursor); + if (!remaining.length) return null; + if (remaining[0] === "quota") { + const sub = remaining[1]; + if (!sub || !LOOPX_QUOTA_READ_SUBCOMMANDS.has(sub)) return null; + return {allowed: true, reason: null, argv: [], command_sha256: null}; + } + if (remaining[0] === "turn" && remaining[1] === "inspect") { + return {allowed: true, reason: null, argv: [], command_sha256: null}; + } + if (remaining[0] === "todo" && remaining[1] === "list") { + return {allowed: true, reason: null, argv: [], command_sha256: null}; + } + if (remaining[0] === "task-lease" && remaining[1] === "inspect") { + return {allowed: true, reason: null, argv: [], command_sha256: null}; + } + if (LOOPX_READ_ONLY_SUBCOMMANDS.has(remaining[0]!)) { + return {allowed: true, reason: null, argv: [], command_sha256: null}; + } + return null; +} + +export function validatePrefetchCommandSafety(params: { + prefetch_command: unknown; + initiator?: unknown; +}): PrefetchSafetyDecision { + const initiator = typeof params.initiator === "string" && params.initiator.trim() + ? params.initiator.trim() + : "turn_driver"; + if (PASSIVE_PLUGIN_INITIATORS.has(initiator)) { + return { + allowed: false, + reason: "policy_violation:passive_policy_cannot_emit_command", + argv: [], + command_sha256: null, + }; + } + const parsed = normalizePrefetchArgv(params.prefetch_command); + if (!parsed.ok) { + return {allowed: false, reason: parsed.reason, argv: [], command_sha256: null}; + } + const argv = parsed.argv; + const cmdHash = sha256Hex(JSON.stringify(argv)); + const exe = argv[0]!.split(/[/\\]/).pop() ?? ""; + const args = argv.slice(1); + + if (exe === "loopx") { + if (isLoopxReadOnlyArgs(args)?.allowed) { + return {allowed: true, reason: null, argv, command_sha256: cmdHash}; + } + return { + allowed: false, + reason: "policy_violation:loopx_subcommand_not_read_only", + argv, + command_sha256: cmdHash, + }; + } + if (/^python(?:\d+(?:\.\d+)?)?$/.test(exe)) { + if (args[0] === "-m" && (args[1] === "loopx" || args[1] === "loopx.cli" || args[1] === "loopx.entrypoint")) { + if (isLoopxReadOnlyArgs(args.slice(2))?.allowed) { + return {allowed: true, reason: null, argv, command_sha256: cmdHash}; + } + return { + allowed: false, + reason: "policy_violation:loopx_subcommand_not_read_only", + argv, + command_sha256: cmdHash, + }; + } + if (args[0] === "-m" && args[1] === "pytest" && args.includes("--collect-only")) { + return {allowed: true, reason: null, argv, command_sha256: cmdHash}; + } + return { + allowed: false, + reason: "policy_violation:executable_not_read_only_allowlisted", + argv, + command_sha256: cmdHash, + }; + } + if (exe === "git") { + let idx = 0; + while (idx < args.length && (args[idx] === "-C" || args[idx] === "--git-dir" || args[idx] === "--work-tree")) { + idx += 2; + } + const sub = args[idx]; + if (!sub || !GIT_READ_ONLY_SUBCOMMANDS.has(sub)) { + return { + allowed: false, + reason: "policy_violation:git_subcommand_not_read_only", + argv, + command_sha256: cmdHash, + }; + } + const gitSubArgs = args.slice(idx + 1); + if ( + gitSubArgs.some( + (flag) => + GIT_FORBIDDEN_OUTPUT_FLAGS.has(flag) + || flag.startsWith("-O") + || flag.startsWith("--output=") + || flag.startsWith("--ext-diff=") + || flag.startsWith("--open-files-in-pager=") + || flag.startsWith("--exec="), + ) + ) { + return { + allowed: false, + reason: "policy_violation:git_output_or_external_diff_forbidden", + argv, + command_sha256: cmdHash, + }; + } + if (sub === "branch") { + const hasListFlag = gitSubArgs.includes("--list"); + const branchAllowed = gitSubArgs.every((arg) => + arg.startsWith("-") ? GIT_READ_ONLY_BRANCH_FLAGS.has(arg) : hasListFlag + ); + if (!branchAllowed) { + return { + allowed: false, + reason: "policy_violation:git_branch_mutation_forbidden", + argv, + command_sha256: cmdHash, + }; + } + } + return {allowed: true, reason: null, argv, command_sha256: cmdHash}; + } + if (exe === "find") { + if (args.some((arg) => FIND_MUTATING_PREDICATES.has(arg))) { + return { + allowed: false, + reason: "policy_violation:find_mutation_forbidden", + argv, + command_sha256: cmdHash, + }; + } + return {allowed: true, reason: null, argv, command_sha256: cmdHash}; + } + if (READ_ONLY_PROBES.has(exe)) { + if ((exe === "rg" || exe === "grep") && args.some((a) => a === "--pre" || a.startsWith("--pre="))) { + return { + allowed: false, + reason: "policy_violation:probe_preprocessor_forbidden", + argv, + command_sha256: cmdHash, + }; + } + return {allowed: true, reason: null, argv, command_sha256: cmdHash}; + } + return { + allowed: false, + reason: "policy_violation:executable_not_read_only_allowlisted", + argv, + command_sha256: cmdHash, + }; +} + +export function planStageThenSwapPrefetch(rawRequest: JsonObject): JsonObject { + const config = normalizeStageThenSwapConfig(rawRequest.epoch_prefetch); + if (!config.enabled) { + return { + schema_version: STAGE_THEN_SWAP_POLICY_SCHEMA_VERSION, + enabled: false, + eligible: false, + fallback_operator: "KeepRaw", + }; + } + const safety = validatePrefetchCommandSafety({ + prefetch_command: config.prefetch_command, + initiator: config.initiator, + }); + return { + schema_version: STAGE_THEN_SWAP_POLICY_SCHEMA_VERSION, + enabled: true, + eligible: safety.allowed, + safety, + timeout_ms: config.timeout_ms, + max_output_bytes: config.max_output_bytes, + min_net_savings_bytes: config.min_net_savings_bytes, + min_net_savings_tokens: config.min_net_savings_tokens, + cold_prefill_amortization_tokens: config.cold_prefill_amortization_tokens, + tokenizer_encoding: config.tokenizer_encoding, + reject_on_truncation: config.reject_on_truncation, + replace_exploratory_context: config.replace_exploratory_context, + initiator: config.initiator, + fallback_operator: "KeepRaw", + }; +} + +function normalizeSourceRef(raw: unknown): {path: string; sha256: string} | null { + if (raw === undefined || raw === null) return null; + const obj = requireJsonObject(raw, "source_ref"); + const path = requireNonEmptyString(obj.path, "source_ref.path"); + const sha256 = requireNonEmptyString(obj.sha256, "source_ref.sha256"); + if (!BARE_SHA256_PATTERN.test(sha256)) { + throw new EffectRuntimeRequestError("source_ref.sha256 must be a bare sha256 digest"); + } + return {path, sha256}; +} + +export function buildAntiWhitewashingReceiptHeader(params: { + context_epoch: string; + reclaimed_turns: number; + dropped_failures: number; + failure_facts: string[]; + open_obligations: string[]; + exit_code: number | null; + truncated: boolean; + source_ref: {path: string; sha256: string} | null; +}): {header: string; fields: JsonObject} { + const sourceRefText = params.source_ref + ? `${params.source_ref.path} (sha256:${params.source_ref.sha256})` + : "none"; + const fields: JsonObject = { + trust_level: "tool", + context_epoch: params.context_epoch, + reclaimed_turns: params.reclaimed_turns, + dropped_failures: params.dropped_failures, + exit_code: params.exit_code, + truncated: params.truncated, + source_ref: params.source_ref, + failure_facts: params.failure_facts, + open_obligations: params.open_obligations, + }; + const header = [ + "[Stage-then-Swap EpochReset Receipt | trust=tool]", + `context_epoch: ${params.context_epoch}`, + `reclaimed_turns: ${params.reclaimed_turns}`, + `dropped_failures: ${params.dropped_failures}`, + `exit_code: ${params.exit_code === null ? "null" : String(params.exit_code)}`, + `truncated: ${params.truncated ? "true" : "false"}`, + `source_ref: ${sourceRefText}`, + `failure_facts: ${JSON.stringify(params.failure_facts)}`, + `open_obligations: ${JSON.stringify(params.open_obligations)}`, + "--- prefetched_output ---", + ].join("\n"); + return {header, fields}; +} + +function isContextReadCommand(command: readonly string[]): boolean { + for (let idx = 0; idx < command.length; idx++) { + if (command[idx] === "quota" && command[idx + 1] === "context-read") return true; + } + return false; +} + +function inspectStructuredPrefetchOutput( + output: string, + sourceRef: {path: string; sha256: string} | null = null, + requiresVerifiedPage = false, +): { + failed: boolean; + incomplete: boolean; + sourceMismatch: boolean; +} { + const trimmed = output.trim(); + if (!trimmed.startsWith("{")) { + return {failed: false, incomplete: requiresVerifiedPage, sourceMismatch: false}; + } + try { + const parsed = JSON.parse(trimmed) as unknown; + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + return {failed: false, incomplete: requiresVerifiedPage, sourceMismatch: false}; + } + const obj = parsed as Record; + const failed = obj.ok === false; + const schema = typeof obj.schema_version === "string" ? obj.schema_version : ""; + const isTypedCapturePage = + schema === "context_capture_page_v1" || schema === "context_capture_selection_page_v1"; + const isPageSchema = + isTypedCapturePage + || "eof" in obj + || "offset" in obj + || "next_offset" in obj + || "total_bytes" in obj; + if (requiresVerifiedPage && !failed && !isTypedCapturePage) { + return {failed: false, incomplete: true, sourceMismatch: false}; + } + if (!isPageSchema) { + return {failed, incomplete: false, sourceMismatch: false}; + } + let incomplete = obj.eof === false || obj.truncated === true; + if (!failed && (isTypedCapturePage || requiresVerifiedPage)) { + const hasZeroOffset = + typeof obj.offset === "number" + && Number.isInteger(obj.offset) + && obj.offset === 0; + const hasClosedNextOffset = obj.next_offset === null; + const hasCompleteEof = obj.eof === true && obj.truncated !== true; + const hasContiguousLength = + typeof obj.total_bytes === "number" + && Number.isInteger(obj.total_bytes) + && typeof obj.content === "string" + && Buffer.byteLength(obj.content, "utf8") === obj.total_bytes; + if (!hasZeroOffset || !hasClosedNextOffset || !hasCompleteEof || !hasContiguousLength) { + incomplete = true; + } + } else { + if (typeof obj.offset === "number" && (!Number.isInteger(obj.offset) || obj.offset !== 0)) { + incomplete = true; + } + if (obj.next_offset !== null && obj.next_offset !== undefined) { + incomplete = true; + } + } + const reportedDigest = + typeof obj.sha256 === "string" + ? obj.sha256 + : typeof obj.capture_sha256 === "string" + ? obj.capture_sha256 + : null; + const sourceMismatch = Boolean( + !failed + && sourceRef?.sha256 + && ( + (reportedDigest !== null && reportedDigest !== sourceRef.sha256) + || ( + (isTypedCapturePage || requiresVerifiedPage) + && reportedDigest === null + ) + ), + ); + return {failed, incomplete, sourceMismatch}; + } catch { + if ( + requiresVerifiedPage + || trimmed.includes("context_capture_page_v1") + || trimmed.includes("context_capture_selection_page_v1") + ) { + return {failed: false, incomplete: true, sourceMismatch: false}; + } + return {failed: false, incomplete: false, sourceMismatch: false}; + } +} + +function normalizeTokenizerProvenance( + value: unknown, + expectedEncoding?: string, +): {name: string; encoding: string; version?: string} | null { + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const obj = value as JsonObject; + const name = typeof obj.name === "string" ? obj.name.trim() : ""; + const encoding = typeof obj.encoding === "string" ? obj.encoding.trim() : ""; + if (!name || !encoding) return null; + if (expectedEncoding && encoding !== expectedEncoding) return null; + const version = typeof obj.version === "string" && obj.version.trim() ? obj.version.trim() : undefined; + return {name, encoding, ...(version ? {version} : {})}; +} + +interface TokenSavingsGateResult { + evaluated: boolean; + passed: boolean; + fallback_reason: string | null; + baseline_tokens: number | null; + delivered_tokens: number | null; + raw_net_savings_tokens: number | null; + cold_prefill_amortization_tokens: number | null; + amortized_net_savings_tokens: number | null; + min_net_savings_tokens: number; + tokenizer: {name: string; encoding: string; version?: string} | null; +} + +function evaluateNetTokenSavingsGate(params: { + min_net_savings_tokens: number; + cold_prefill_amortization_tokens: number | null; + tokenizer_encoding: string; + baseline_tokens: number | null; + delivered_tokens: number | null; + rebased_prompt_tokens: number | null; + tokenizer: unknown; + require_token_gate: boolean; +}): TokenSavingsGateResult { + const tokenizer = normalizeTokenizerProvenance(params.tokenizer, params.tokenizer_encoding); + const {baseline_tokens, delivered_tokens, rebased_prompt_tokens} = params; + if ( + baseline_tokens === null + || delivered_tokens === null + || (params.require_token_gate && tokenizer === null) + ) { + if (!params.require_token_gate && baseline_tokens === null && delivered_tokens === null) { + return { + evaluated: false, + passed: true, + fallback_reason: null, + baseline_tokens: null, + delivered_tokens: null, + raw_net_savings_tokens: null, + cold_prefill_amortization_tokens: null, + amortized_net_savings_tokens: null, + min_net_savings_tokens: params.min_net_savings_tokens, + tokenizer, + }; + } + return { + evaluated: true, + passed: false, + fallback_reason: "token_estimation_unavailable", + baseline_tokens, + delivered_tokens, + raw_net_savings_tokens: null, + cold_prefill_amortization_tokens: null, + amortized_net_savings_tokens: null, + min_net_savings_tokens: params.min_net_savings_tokens, + tokenizer, + }; + } + const rawNet = baseline_tokens - delivered_tokens; + const rebasedTokens = rebased_prompt_tokens ?? delivered_tokens; + const amortization = + params.cold_prefill_amortization_tokens + ?? Math.ceil(rebasedTokens / DEFAULT_COLD_PREFILL_AMORTIZATION_DIVISOR); + const amortizedNet = rawNet - amortization; + const passed = rawNet > 0 && amortizedNet >= params.min_net_savings_tokens; + return { + evaluated: true, + passed, + fallback_reason: passed ? null : "negative_net_savings", + baseline_tokens, + delivered_tokens, + raw_net_savings_tokens: rawNet, + cold_prefill_amortization_tokens: amortization, + amortized_net_savings_tokens: amortizedNet, + min_net_savings_tokens: params.min_net_savings_tokens, + tokenizer, + }; +} + +export function evaluateEpochPrefetchSwap(rawRequest: JsonObject): JsonObject { + const config = normalizeStageThenSwapConfig(rawRequest.epoch_prefetch); + const context_epoch = requireNonEmptyString(rawRequest.context_epoch, "context_epoch"); + const reclaimed_turns = + optionalInt(rawRequest.reclaimed_turns, "reclaimed_turns", 0, 1_000_000) ?? 0; + const failure_facts = cleanTextList(rawRequest.failure_facts, 32); + const raw_dropped_failures = + optionalInt(rawRequest.dropped_failures, "dropped_failures", 0, 1_000_000) ?? 0; + const dropped_failures = Math.max(raw_dropped_failures, failure_facts.length); + const open_obligations = cleanTextList(rawRequest.open_obligations, 64); + const source_ref = normalizeSourceRef(rawRequest.source_ref); + const baseline_bytes = optionalInt(rawRequest.baseline_bytes, "baseline_bytes", 0, 100_000_000); + const baseline_tokens = optionalInt(rawRequest.baseline_tokens, "baseline_tokens", 0, 100_000_000); + const hydrated_tokens = optionalInt(rawRequest.hydrated_tokens, "hydrated_tokens", 0, 100_000_000); + const require_token_gate = rawRequest.require_token_gate === undefined + ? false + : requireBoolean(rawRequest.require_token_gate, "require_token_gate"); + const latency_ms = optionalInt(rawRequest.latency_ms, "latency_ms", 0, 3_600_000) ?? 0; + const timed_out = rawRequest.timed_out === undefined + ? false + : requireBoolean(rawRequest.timed_out, "timed_out"); + const truncated = rawRequest.truncated === undefined + ? false + : requireBoolean(rawRequest.truncated, "truncated"); + const exit_code = + rawRequest.exit_code === undefined || rawRequest.exit_code === null + ? null + : optionalInt(rawRequest.exit_code, "exit_code", -128, 255); + const prefetched_output = typeof rawRequest.prefetched_output === "string" + ? rawRequest.prefetched_output + : ""; + const raw_bytes_read = + optionalInt(rawRequest.raw_bytes_read, "raw_bytes_read", 0, 100_000_000) + ?? Buffer.byteLength(prefetched_output, "utf8"); + const retained_bytes = Buffer.byteLength(prefetched_output, "utf8"); + + if (!config.enabled) { + throw new EffectRuntimeRequestError("Stage-then-Swap epoch prefetch is disabled"); + } + + const safety = validatePrefetchCommandSafety({ + prefetch_command: config.prefetch_command, + initiator: config.initiator, + }); + const requiresVerifiedPage = source_ref !== null || isContextReadCommand(safety.argv); + const pageStatus = inspectStructuredPrefetchOutput(prefetched_output, source_ref, requiresVerifiedPage); + const effectiveTruncated = truncated || pageStatus.incomplete; + + const {header, fields} = buildAntiWhitewashingReceiptHeader({ + context_epoch, + reclaimed_turns, + dropped_failures, + failure_facts, + open_obligations, + exit_code, + truncated: effectiveTruncated, + source_ref, + }); + const hydrated_text = prefetched_output ? `${header}\n${prefetched_output}` : header; + const hydrated_bytes = Buffer.byteLength(hydrated_text, "utf8"); + const net_savings_bytes = baseline_bytes === null ? null : baseline_bytes - hydrated_bytes; + const minNetSavings = config.min_net_savings_bytes ?? (baseline_bytes === null ? 0 : 1); + const tokenGate = evaluateNetTokenSavingsGate({ + min_net_savings_tokens: config.min_net_savings_tokens, + cold_prefill_amortization_tokens: config.cold_prefill_amortization_tokens, + tokenizer_encoding: config.tokenizer_encoding, + baseline_tokens, + delivered_tokens: hydrated_tokens, + rebased_prompt_tokens: hydrated_tokens, + tokenizer: rawRequest.tokenizer, + require_token_gate, + }); + + let fallback_reason: string | null = null; + if (!safety.allowed) { + fallback_reason = safety.reason; + } else if (timed_out) { + fallback_reason = "timeout"; + } else if (exit_code === null || exit_code !== 0 || pageStatus.failed) { + fallback_reason = "command_failed"; + } else if (config.reject_on_truncation && truncated) { + fallback_reason = "output_truncated"; + } else if (pageStatus.incomplete) { + fallback_reason = "incomplete_output"; + } else if (pageStatus.sourceMismatch) { + fallback_reason = "source_digest_mismatch"; + } else if (config.reject_on_truncation && effectiveTruncated) { + fallback_reason = "output_truncated"; + } else if (retained_bytes > config.max_output_bytes) { + fallback_reason = "output_overflow"; + } else if (baseline_bytes !== null && (net_savings_bytes ?? -1) < minNetSavings) { + fallback_reason = "negative_net_savings"; + } else if (tokenGate.evaluated && !tokenGate.passed) { + fallback_reason = tokenGate.fallback_reason; + } + + const tokenReceiptFields: JsonObject = tokenGate.evaluated + ? { + baseline_tokens: tokenGate.baseline_tokens, + hydrated_tokens: tokenGate.delivered_tokens, + net_savings_tokens: tokenGate.raw_net_savings_tokens, + cold_prefill_amortization_tokens: tokenGate.cold_prefill_amortization_tokens, + amortized_net_savings_tokens: tokenGate.amortized_net_savings_tokens, + min_net_savings_tokens: tokenGate.min_net_savings_tokens, + tokenizer: tokenGate.tokenizer, + } + : {}; + + const output_sha256 = sha256Hex(prefetched_output); + if (fallback_reason !== null) { + const errorNote = optionalNonEmptyString(rawRequest.error_observation, "error_observation") + ?? `Prefetch aborted atomically to KeepRaw (${fallback_reason}).`; + const baseReceipt: JsonObject = { + schema_version: EPOCH_PREFETCH_RECEIPT_SCHEMA_VERSION, + operator: "KeepRaw", + status: "fallback_keep_raw", + fallback_reason, + trust_level: "tool", + preserves_raw_state: true, + context_epoch, + command_sha256: safety.command_sha256, + source_ref, + reclaimed_turns: 0, + dropped_failures: 0, + exit_code, + timed_out, + truncated: effectiveTruncated, + raw_bytes_read, + retained_bytes: 0, + baseline_bytes, + hydrated_bytes: baseline_bytes ?? 0, + net_savings_bytes: 0, + bytes_saved: 0, + round_trips_saved: 0, + latency_ms, + header, + header_fields: fields, + preserved_failure_facts: failure_facts, + preserved_open_obligations: open_obligations, + prefetched_output: "", + hydrated_text: null, + output_sha256, + error_observation: errorNote.slice(0, 512), + ...tokenReceiptFields, + }; + return { + ...baseReceipt, + receipt_sha256: sha256Hex(JSON.stringify(baseReceipt)), + }; + } + + const bytes_saved = net_savings_bytes !== null && net_savings_bytes > 0 ? net_savings_bytes : 0; + const committedReceipt: JsonObject = { + schema_version: EPOCH_PREFETCH_RECEIPT_SCHEMA_VERSION, + operator: "EpochReset", + status: "committed", + fallback_reason: null, + trust_level: "tool", + preserves_raw_state: false, + context_epoch, + command_sha256: safety.command_sha256, + source_ref, + reclaimed_turns, + dropped_failures, + exit_code, + timed_out: false, + truncated: effectiveTruncated, + raw_bytes_read, + retained_bytes, + baseline_bytes, + hydrated_bytes, + net_savings_bytes, + bytes_saved, + round_trips_saved: 1, + latency_ms, + header, + header_fields: fields, + preserved_failure_facts: failure_facts, + preserved_open_obligations: open_obligations, + prefetched_output, + hydrated_text, + output_sha256, + error_observation: null, + ...tokenReceiptFields, + }; + return { + ...committedReceipt, + receipt_sha256: sha256Hex(JSON.stringify(committedReceipt)), + }; +} + +export function evaluateEpochPrefetchPromptGate(rawRequest: JsonObject): JsonObject { + const config = + rawRequest.epoch_prefetch === undefined || rawRequest.epoch_prefetch === null + ? normalizeStageThenSwapConfig(false) + : normalizeStageThenSwapConfig(rawRequest.epoch_prefetch); + const hasInline = requireBoolean(rawRequest.has_inline_exploratory, "has_inline_exploratory"); + const replaceInline = requireBoolean(rawRequest.replace_exploratory_context, "replace_exploratory_context"); + const hostInputMeasurable = + rawRequest.host_input_measurable === undefined + ? true + : requireBoolean(rawRequest.host_input_measurable, "host_input_measurable"); + const beforeBytes = optionalInt(rawRequest.rendered_prompt_baseline_bytes, "rendered_prompt_baseline_bytes", 0, 100_000_000); + const afterBytes = optionalInt(rawRequest.rendered_prompt_delivered_bytes, "rendered_prompt_delivered_bytes", 0, 100_000_000); + const beforeTokens = optionalInt(rawRequest.rendered_prompt_baseline_tokens, "rendered_prompt_baseline_tokens", 0, 100_000_000); + const afterTokens = optionalInt(rawRequest.rendered_prompt_delivered_tokens, "rendered_prompt_delivered_tokens", 0, 100_000_000); + const externalBaselineBytes = optionalInt(rawRequest.external_baseline_bytes, "external_baseline_bytes", 0, 100_000_000); + const externalBaselineTokens = optionalInt(rawRequest.external_baseline_tokens, "external_baseline_tokens", 0, 100_000_000); + const potentialSaved = optionalInt(rawRequest.potential_bytes_saved, "potential_bytes_saved", 0, 100_000_000) ?? 0; + + const promptDeltaBytes = beforeBytes !== null && afterBytes !== null ? afterBytes - beforeBytes : null; + const promptDeltaTokens = beforeTokens !== null && afterTokens !== null ? afterTokens - beforeTokens : null; + + const abortKeepRaw = (params: { + fallback_reason: string; + net_savings_bytes: number; + tokenGate: TokenSavingsGateResult; + error_observation: string; + }): JsonObject => ({ + operator: "KeepRaw", + status: "fallback_keep_raw", + fallback_reason: params.fallback_reason, + preserves_raw_state: true, + bytes_saved: 0, + net_savings_bytes: params.net_savings_bytes, + net_savings_tokens: params.tokenGate.raw_net_savings_tokens, + cold_prefill_amortization_tokens: params.tokenGate.cold_prefill_amortization_tokens, + amortized_net_savings_tokens: params.tokenGate.amortized_net_savings_tokens, + min_net_savings_tokens: params.tokenGate.min_net_savings_tokens, + round_trips_saved: 0, + rendered_prompt_baseline_bytes: beforeBytes, + rendered_prompt_delivered_bytes: afterBytes, + rendered_prompt_delta_bytes: promptDeltaBytes, + rendered_prompt_baseline_tokens: beforeTokens, + rendered_prompt_delivered_tokens: afterTokens, + rendered_prompt_delta_tokens: promptDeltaTokens, + tokenizer: params.tokenGate.tokenizer, + error_observation: params.error_observation, + }); + + if (!hostInputMeasurable) { + const unmeasurableGate = evaluateNetTokenSavingsGate({ + min_net_savings_tokens: config.min_net_savings_tokens, + cold_prefill_amortization_tokens: config.cold_prefill_amortization_tokens, + tokenizer_encoding: config.tokenizer_encoding, + baseline_tokens: hasInline ? beforeTokens : externalBaselineTokens, + delivered_tokens: null, + rebased_prompt_tokens: afterTokens, + tokenizer: rawRequest.tokenizer, + require_token_gate: true, + }); + return abortKeepRaw({ + fallback_reason: "host_input_unmeasurable", + net_savings_bytes: 0, + tokenGate: unmeasurableGate, + error_observation: + "Prefetch aborted atomically to KeepRaw (host_input_unmeasurable: actual host input cannot be measured before launch).", + }); + } + + if (hasInline && !replaceInline) { + const emptyGate = evaluateNetTokenSavingsGate({ + min_net_savings_tokens: config.min_net_savings_tokens, + cold_prefill_amortization_tokens: config.cold_prefill_amortization_tokens, + tokenizer_encoding: config.tokenizer_encoding, + baseline_tokens: beforeTokens, + delivered_tokens: afterTokens, + rebased_prompt_tokens: afterTokens, + tokenizer: rawRequest.tokenizer, + require_token_gate: true, + }); + return abortKeepRaw({ + fallback_reason: "negative_net_savings", + net_savings_bytes: promptDeltaBytes !== null ? -Math.max(0, promptDeltaBytes) : 0, + tokenGate: emptyGate, + error_observation: "Prefetch aborted atomically to KeepRaw (append mode does not replace exploratory_context).", + }); + } + + if ( + beforeBytes === null + || afterBytes === null + || beforeTokens === null + || afterTokens === null + || (!hasInline && externalBaselineTokens === null) + ) { + const missingGate = evaluateNetTokenSavingsGate({ + min_net_savings_tokens: config.min_net_savings_tokens, + cold_prefill_amortization_tokens: config.cold_prefill_amortization_tokens, + tokenizer_encoding: config.tokenizer_encoding, + baseline_tokens: hasInline ? beforeTokens : externalBaselineTokens, + delivered_tokens: hasInline ? afterTokens : null, + rebased_prompt_tokens: afterTokens, + tokenizer: rawRequest.tokenizer, + require_token_gate: true, + }); + return abortKeepRaw({ + fallback_reason: "token_estimation_unavailable", + net_savings_bytes: 0, + tokenGate: missingGate, + error_observation: + "Prefetch aborted atomically to KeepRaw (verifiable prompt/source token estimation unavailable).", + }); + } + + const netSavingsBytes = hasInline + ? beforeBytes - afterBytes + : externalBaselineBytes !== null + ? externalBaselineBytes - Math.max(0, afterBytes - beforeBytes) + : 0; + const minBytesRequired = config.min_net_savings_bytes ?? (hasInline || externalBaselineBytes !== null ? 1 : 0); + const baselineTokensForGate = hasInline ? beforeTokens : externalBaselineTokens!; + const deliveredTokensForGate = hasInline ? afterTokens : Math.max(0, afterTokens - beforeTokens); + const tokenGate = evaluateNetTokenSavingsGate({ + min_net_savings_tokens: config.min_net_savings_tokens, + cold_prefill_amortization_tokens: config.cold_prefill_amortization_tokens, + tokenizer_encoding: config.tokenizer_encoding, + baseline_tokens: baselineTokensForGate, + delivered_tokens: deliveredTokensForGate, + rebased_prompt_tokens: afterTokens, + tokenizer: rawRequest.tokenizer, + require_token_gate: true, + }); + + if (!tokenGate.passed) { + const reason = tokenGate.fallback_reason ?? "negative_net_savings"; + return abortKeepRaw({ + fallback_reason: reason, + net_savings_bytes: netSavingsBytes, + tokenGate, + error_observation: + reason === "token_estimation_unavailable" + ? "Prefetch aborted atomically to KeepRaw (verifiable tokenizer provenance missing)." + : `Prefetch aborted atomically to KeepRaw (amortized net token savings ${tokenGate.amortized_net_savings_tokens} < ${tokenGate.min_net_savings_tokens}; raw token delta ${tokenGate.raw_net_savings_tokens}, cold prefill amortization ${tokenGate.cold_prefill_amortization_tokens}).`, + }); + } + + if ((hasInline || externalBaselineBytes !== null) && netSavingsBytes < minBytesRequired) { + return abortKeepRaw({ + fallback_reason: "negative_net_savings", + net_savings_bytes: netSavingsBytes, + tokenGate, + error_observation: `Prefetch aborted atomically to KeepRaw (rendered prompt net byte savings ${netSavingsBytes}B < ${minBytesRequired}B).`, + }); + } + + const bytesSaved = potentialSaved > 0 ? Math.min(potentialSaved, Math.max(0, netSavingsBytes)) : Math.max(0, netSavingsBytes); + return { + operator: "EpochReset", + status: "committed", + fallback_reason: null, + preserves_raw_state: false, + bytes_saved: bytesSaved, + net_savings_bytes: netSavingsBytes, + net_savings_tokens: tokenGate.raw_net_savings_tokens, + cold_prefill_amortization_tokens: tokenGate.cold_prefill_amortization_tokens, + amortized_net_savings_tokens: tokenGate.amortized_net_savings_tokens, + min_net_savings_tokens: tokenGate.min_net_savings_tokens, + round_trips_saved: 1, + rendered_prompt_baseline_bytes: beforeBytes, + rendered_prompt_delivered_bytes: afterBytes, + rendered_prompt_delta_bytes: promptDeltaBytes, + rendered_prompt_baseline_tokens: beforeTokens, + rendered_prompt_delivered_tokens: afterTokens, + rendered_prompt_delta_tokens: promptDeltaTokens, + tokenizer: tokenGate.tokenizer, + error_observation: null, + }; +} + +function optionalBooleanField(obj: JsonObject | null, key: string): boolean | null { + if (!obj || !Object.hasOwn(obj, key)) return null; + return typeof obj[key] === "boolean" ? obj[key] : null; +} + +function resolveSingleContractQuietEligibility(contract: JsonObject): { + must_attempt: boolean; + explicitly_forbidden: boolean; + explicitly_allowed: boolean; +} { + const decision = jsonObject(contract.decision); + const interaction = jsonObject(contract.interaction_contract) ?? jsonObject(decision?.interaction_contract); + const agentChannel = jsonObject(interaction?.agent_channel); + const action = jsonObject(contract.action) ?? jsonObject(decision?.action); + + const mustAttempt = + optionalBooleanField(contract, "must_attempt") === true + || optionalBooleanField(decision, "must_attempt") === true + || agentChannel?.must_attempt === true + || action?.must_attempt === true; + + const flags = [ + optionalBooleanField(agentChannel, "quiet_noop_allowed"), + optionalBooleanField(action, "quiet_noop_allowed"), + optionalBooleanField(decision, "quiet_noop_allowed"), + optionalBooleanField(contract, "quiet_noop_allowed"), + ]; + return { + must_attempt: mustAttempt, + explicitly_forbidden: flags.some((flag) => flag === false), + explicitly_allowed: flags.some((flag) => flag === true), + }; +} + +export function resolvePlanQuietNoopEligibility(plan: JsonObject): { + must_attempt: boolean; + quiet_noop_allowed: boolean; + source: "work_contract" | "turn_envelope" | "none"; +} { + const workContract = jsonObject(plan.work_contract); + const turnEnvelope = jsonObject(plan.turn_envelope); + if (!workContract && !turnEnvelope) { + return {must_attempt: false, quiet_noop_allowed: false, source: "none"}; + } + const source = workContract ? "work_contract" : "turn_envelope"; + const workCheck = workContract ? resolveSingleContractQuietEligibility(workContract) : null; + const envCheck = turnEnvelope ? resolveSingleContractQuietEligibility(turnEnvelope) : null; + const mustAttempt = (workCheck?.must_attempt ?? false) || (envCheck?.must_attempt ?? false); + const explicitlyForbidden = + (workCheck?.explicitly_forbidden ?? false) || (envCheck?.explicitly_forbidden ?? false); + const explicitlyAllowed = + (workCheck?.explicitly_allowed ?? false) || (envCheck?.explicitly_allowed ?? false); + const quietNoopAllowed = !mustAttempt && !explicitlyForbidden && explicitlyAllowed; + return {must_attempt: mustAttempt, quiet_noop_allowed: quietNoopAllowed, source}; +} + +const QUIET_VOLATILE_STATE_KEYS = new Set([ + "projection_envelope", + "contract_binding", + "heartbeat_receipt", + "turn_instance_id", + "source_decision_hash", + "detail_ref", + "cold_path_detail", + "recheck_after_seconds", + "frontier_recheck_after_seconds", + "seconds_until_due", + "observed_at", + "served_at", + "last_read_at", + "age_seconds", + "staleness_seconds", +]); + +function stripVolatileQuietFields(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(stripVolatileQuietFields); + } + if (value && typeof value === "object") { + const obj = value as Record; + const sorted: Record = {}; + for (const key of Object.keys(obj).sort()) { + if (QUIET_VOLATILE_STATE_KEYS.has(key)) continue; + sorted[key] = stripVolatileQuietFields(obj[key]); + } + return sorted; + } + return value; +} + +export function computeQuietTurnStateDigest(rawRequest: JsonObject): JsonObject { + const goalId = requireNonEmptyString(rawRequest.goal_id, "goal_id"); + const agentId = typeof rawRequest.agent_id === "string" ? rawRequest.agent_id : ""; + const workContract = jsonObject(rawRequest.work_contract); + const turnEnvelope = jsonObject(rawRequest.turn_envelope); + const route = jsonObject(rawRequest.route); + const contractForDigest = workContract ?? turnEnvelope ?? {}; + const eligibility = resolvePlanQuietNoopEligibility({ + ...(workContract !== null ? {work_contract: workContract} : {}), + ...(turnEnvelope !== null ? {turn_envelope: turnEnvelope} : {}), + }); + const canonicalPayload = stripVolatileQuietFields({ + goal_id: goalId, + agent_id: agentId, + route, + work_contract: contractForDigest, + }); + const state_digest = sha256Hex(JSON.stringify(canonicalPayload)); + return { + state_digest, + must_attempt: eligibility.must_attempt, + quiet_noop_allowed: eligibility.quiet_noop_allowed, + source: eligibility.source, + }; +} + +export function evaluateQuietTurn(rawRequest: JsonObject): JsonObject { + const enabled = rawRequest.enabled === undefined ? true : requireBoolean(rawRequest.enabled, "quiet_turn.enabled"); + const requestedQuietNoop = + rawRequest.quiet_noop_allowed === undefined + ? true + : requireBoolean(rawRequest.quiet_noop_allowed, "quiet_noop_allowed"); + const requestedMustAttempt = + rawRequest.must_attempt === undefined + ? false + : requireBoolean(rawRequest.must_attempt, "must_attempt"); + let contractMustAttempt = requestedMustAttempt; + let contractAllowsQuiet = true; + if (rawRequest.work_contract !== undefined || rawRequest.turn_envelope !== undefined) { + const eligibility = resolvePlanQuietNoopEligibility({ + ...(rawRequest.work_contract !== undefined ? {work_contract: rawRequest.work_contract} : {}), + ...(rawRequest.turn_envelope !== undefined ? {turn_envelope: rawRequest.turn_envelope} : {}), + }); + contractMustAttempt = contractMustAttempt || eligibility.must_attempt; + contractAllowsQuiet = eligibility.quiet_noop_allowed; + } + const quietNoopAllowed = requestedQuietNoop && !contractMustAttempt && contractAllowsQuiet; + const currentStateDigest = optionalNonEmptyString(rawRequest.current_state_digest, "current_state_digest"); + const previousStateDigest = optionalNonEmptyString(rawRequest.previous_state_digest, "previous_state_digest"); + let stateChanged = rawRequest.state_changed === undefined + ? null + : requireBoolean(rawRequest.state_changed, "state_changed"); + if (stateChanged === null) { + if (currentStateDigest !== null && previousStateDigest !== null) { + stateChanged = currentStateDigest !== previousStateDigest; + } else { + stateChanged = true; + } + } + const skipped = enabled && quietNoopAllowed && !stateChanged; + return { + schema_version: QUIET_TURN_METADATA_SCHEMA_VERSION, + enabled, + quiet_noop_allowed: quietNoopAllowed, + state_changed: stateChanged, + skipped, + zero_tax: skipped, + reason: !enabled + ? "disabled" + : !quietNoopAllowed + ? "quiet_noop_disallowed" + : skipped + ? "unchanged_state" + : "state_changed", + context_delivery_skipped: skipped, + prefetch_skipped: skipped, + state_digest: currentStateDigest ?? previousStateDigest ?? null, + operator: skipped ? "KeepRaw" : null, + }; +} + +function requireBareSha256(value: unknown, label: string): string { + const text = requireNonEmptyString(value, label); + if (!BARE_SHA256_PATTERN.test(text)) { + throw new EffectRuntimeRequestError(`${label} must be a bare sha256 digest`); + } + return text; +} + +function requireNonNegativeInt(value: unknown, label: string, max = 1_000_000_000): number { + const parsed = optionalInt(value, label, 0, max); + if (parsed === null) { + throw new EffectRuntimeRequestError(`${label} is required`); + } + return parsed; +} + +export function recordSemanticUnitAnchor(rawRequest: JsonObject): JsonObject { + const todo_id = requireNonEmptyString(rawRequest.todo_id, "todo_id"); + const turn_instance_id = requireNonEmptyString(rawRequest.turn_instance_id, "turn_instance_id"); + const anchor_step_index = requireNonNegativeInt(rawRequest.anchor_step_index, "anchor_step_index", 1_000_000); + const prefix_digest = requireBareSha256(rawRequest.prefix_digest, "prefix_digest"); + const context_epoch = requireNonEmptyString(rawRequest.context_epoch, "context_epoch"); + const anchor_surface_seq = optionalInt(rawRequest.anchor_surface_seq, "anchor_surface_seq", 0, 1_000_000_000); + const goal_id = optionalNonEmptyString(rawRequest.goal_id, "goal_id"); + const agent_id = optionalNonEmptyString(rawRequest.agent_id, "agent_id"); + const anchorCore: JsonObject = { + schema_version: SEMANTIC_UNIT_ANCHOR_SCHEMA_VERSION, + todo_id, + turn_instance_id, + anchor_step_index, + anchor_surface_seq, + prefix_digest, + context_epoch, + ...(goal_id !== null ? {goal_id} : {}), + ...(agent_id !== null ? {agent_id} : {}), + }; + return { + ...anchorCore, + anchor_sha256: sha256Hex(JSON.stringify(anchorCore)), + }; +} + +function normalizeObsNextCommand(rawObs: unknown): { + ok: boolean; + reason: string | null; + command: string[]; + command_sha256: string | null; + exit_code: number | null; + truncated: boolean; + output: string; + latency_ms: number; +} | null { + if (rawObs === undefined || rawObs === null) return null; + const obj = jsonObject(rawObs); + if (!obj) { + return { + ok: false, + reason: "invalid_obs_next_cmd", + command: [], + command_sha256: null, + exit_code: null, + truncated: false, + output: "", + latency_ms: 0, + }; + } + const initiator = optionalNonEmptyString(obj.initiator, "obs_next_cmd.initiator") ?? "turn_driver"; + const rawCommand = obj.prefetch_command ?? obj.command; + const safety = validatePrefetchCommandSafety({prefetch_command: rawCommand, initiator}); + const timedOut = obj.timed_out === true; + const truncated = obj.truncated === true; + const rejectOnTruncation = obj.reject_on_truncation === undefined ? true : obj.reject_on_truncation === true; + const maxBytes = optionalInt( + obj.max_output_bytes, + "obs_next_cmd.max_output_bytes", + MIN_PREFETCH_MAX_OUTPUT_BYTES, + MAX_PREFETCH_MAX_OUTPUT_BYTES, + ) ?? DEFAULT_PREFETCH_MAX_OUTPUT_BYTES; + const exitCode = obj.exit_code === undefined || obj.exit_code === null + ? null + : optionalInt(obj.exit_code, "obs_next_cmd.exit_code", -128, 255); + const output = typeof obj.output === "string" ? obj.output : ""; + const latencyMs = optionalInt(obj.latency_ms, "obs_next_cmd.latency_ms", 0, 3_600_000) ?? 0; + let reason: string | null = null; + if (!safety.allowed) reason = safety.reason; + else if (timedOut) reason = "obs_command_timeout"; + else if (exitCode === null || exitCode !== 0) reason = "command_error"; + else if (rejectOnTruncation && truncated) reason = "output_truncated"; + else if (Buffer.byteLength(output, "utf8") > maxBytes) reason = "output_overflow"; + return { + ok: reason === null, + reason, + command: safety.argv, + command_sha256: safety.command_sha256, + exit_code: exitCode, + truncated, + output: reason === null ? output : "", + latency_ms: latencyMs, + }; +} + +function buildSemanticUnitReceiptText(params: { + mu: JsonObject; + sourceRefText: string; + obsOutput: string | null; +}): string { + const mu = params.mu; + const range = mu.reclaim_range as number[]; + const lines = [ + "[Semantic-Unit Fold Receipt mu | trust=tool]", + `todo_id: ${String(mu.todo_id)}`, + `completion_receipt_id: ${String(mu.completion_receipt_id)}`, + `completion_sha256: ${String(mu.sha256)}`, + `turn_instance_id: ${String(mu.turn_instance_id)}`, + `context_epoch: ${String(mu.context_epoch)}`, + `prefix_digest: ${String(mu.prefix_digest)}`, + `reclaim_range: [${range[0]}..${range[1]}]`, + `exit_code: ${String(mu.exit_code)}`, + `source_ref: ${params.sourceRefText}`, + `failure_facts: ${JSON.stringify(mu.failure_facts)}`, + `open_obligations: ${JSON.stringify(mu.open_obligations)}`, + ]; + if (params.obsOutput !== null && params.obsOutput.length > 0) { + lines.push("--- obs_next_cmd ---", params.obsOutput); + } + return lines.join("\n"); +} + +export function buildSemanticUnitFoldSwap(rawRequest: JsonObject): JsonObject { + const enabled = rawRequest.enabled === undefined ? false : requireBoolean(rawRequest.enabled, "enabled"); + const todo_id = requireNonEmptyString(rawRequest.todo_id, "todo_id"); + const turn_instance_id = requireNonEmptyString(rawRequest.turn_instance_id, "turn_instance_id"); + const context_epoch = requireNonEmptyString(rawRequest.context_epoch, "context_epoch"); + const rawReceipt = jsonObject(rawRequest.completion_receipt); + const receiptFailureFacts = cleanTextList(rawReceipt?.failure_facts ?? rawRequest.failure_facts, 32); + const receiptOpenObligations = cleanTextList(rawReceipt?.open_obligations ?? rawRequest.open_obligations, 64); + + const minSavingsTokens = + optionalInt(rawRequest.min_net_savings_tokens, "min_net_savings_tokens", 1, 1_000_000) + ?? DEFAULT_MIN_NET_SAVINGS_TOKENS; + const coldAmortizationTokens = optionalInt( + rawRequest.cold_prefill_amortization_tokens, + "cold_prefill_amortization_tokens", + 0, + 1_000_000, + ); + const tokenizerEncoding = + optionalNonEmptyString(rawRequest.tokenizer_encoding, "tokenizer_encoding") ?? DEFAULT_TOKENIZER_ENCODING; + if (!SUPPORTED_TOKENIZER_ENCODINGS.has(tokenizerEncoding)) { + throw new EffectRuntimeRequestError(`unsupported tokenizer_encoding ${tokenizerEncoding}`); + } + const baselineTokens = optionalInt(rawRequest.baseline_tokens, "baseline_tokens", 0, 100_000_000); + const replacementTokens = optionalInt(rawRequest.replacement_tokens, "replacement_tokens", 0, 100_000_000); + + if (!enabled) { + const disabledPayload: JsonObject = { + schema_version: SEMANTIC_UNIT_FOLD_SWAP_SCHEMA_VERSION, + enabled: false, + operator: "KeepRaw", + status: "disabled", + fallback_reason: "disabled", + trust_level: "tool", + preserves_raw_state: true, + preserves_prefix_kv: true, + todo_id, + turn_instance_id, + context_epoch, + prefix_digest: typeof rawRequest.prefix_digest === "string" ? rawRequest.prefix_digest : null, + reclaim_range: null, + reclaim_bounds: null, + receipt_mu: null, + obs_next_cmd: null, + replacement_text: null, + preserved_failure_facts: receiptFailureFacts, + preserved_open_obligations: receiptOpenObligations, + round_trips_saved: 0, + bytes_saved: 0, + net_savings_tokens: null, + cold_prefill_amortization_tokens: null, + amortized_net_savings_tokens: null, + min_net_savings_tokens: minSavingsTokens, + error_observation: null, + }; + return { + ...disabledPayload, + receipt_sha256: sha256Hex(JSON.stringify(disabledPayload)), + }; + } + + let anchor: JsonObject | null = null; + let anchorValidError: string | null = null; + const rawAnchor = jsonObject(rawRequest.anchor); + if (!rawAnchor) { + anchorValidError = "missing_anchor"; + } else { + try { + const normalizedAnchor = recordSemanticUnitAnchor(rawAnchor); + if ( + typeof rawAnchor.anchor_sha256 === "string" + && rawAnchor.anchor_sha256 !== normalizedAnchor.anchor_sha256 + ) { + anchorValidError = "anchor_digest_mismatch"; + } else { + anchor = normalizedAnchor; + } + } catch { + anchorValidError = "invalid_anchor"; + } + } + + const nowStepIndex = optionalInt(rawRequest.now_step_index, "now_step_index", 0, 1_000_000); + const nowSurfaceSeq = optionalInt(rawRequest.now_surface_seq, "now_surface_seq", 0, 1_000_000_000); + const surfacePrefixIntact = + rawRequest.surface_prefix_intact === undefined + ? true + : requireBoolean(rawRequest.surface_prefix_intact, "surface_prefix_intact"); + const toolPairingValid = + rawRequest.tool_pairing_valid === undefined + ? true + : requireBoolean(rawRequest.tool_pairing_valid, "tool_pairing_valid"); + const quiescentBoundary = + rawRequest.quiescent_boundary === undefined + ? true + : requireBoolean(rawRequest.quiescent_boundary, "quiescent_boundary"); + + let prefixDigest: string | null = null; + let prefixDigestInvalid = false; + if (typeof rawRequest.prefix_digest === "string" && BARE_SHA256_PATTERN.test(rawRequest.prefix_digest)) { + prefixDigest = rawRequest.prefix_digest; + } else { + prefixDigestInvalid = true; + } + + let sourceRef: {path: string; sha256: string} | null = null; + let sourceRefInvalid = false; + if (rawReceipt && rawReceipt.source_ref !== undefined && rawReceipt.source_ref !== null) { + try { + sourceRef = normalizeSourceRef(rawReceipt.source_ref); + } catch { + sourceRefInvalid = true; + } + } else { + sourceRefInvalid = rawReceipt !== null; + } + + const receiptTodoId = + rawReceipt && typeof rawReceipt.todo_id === "string" && rawReceipt.todo_id.trim() + ? rawReceipt.todo_id.trim() + : null; + const receiptId = + rawReceipt && typeof rawReceipt.completion_receipt_id === "string" && rawReceipt.completion_receipt_id.trim() + ? rawReceipt.completion_receipt_id.trim() + : null; + const receiptExitCode = + rawReceipt && rawReceipt.exit_code !== undefined && rawReceipt.exit_code !== null + && typeof rawReceipt.exit_code === "number" && Number.isSafeInteger(rawReceipt.exit_code) + && rawReceipt.exit_code >= -128 && rawReceipt.exit_code <= 255 + ? rawReceipt.exit_code + : null; + const receiptSha = + rawReceipt && typeof rawReceipt.sha256 === "string" && BARE_SHA256_PATTERN.test(rawReceipt.sha256) + ? rawReceipt.sha256 + : null; + + const obsCheck = normalizeObsNextCommand(rawRequest.obs_next_cmd); + + let fallbackReason: string | null = null; + if (!quiescentBoundary) fallbackReason = "non_quiescent_boundary"; + else if (anchorValidError !== null || anchor === null) fallbackReason = anchorValidError ?? "missing_anchor"; + else if (prefixDigestInvalid || prefixDigest === null) fallbackReason = "invalid_prefix_digest"; + else if (anchor.todo_id !== todo_id) fallbackReason = "todo_id_mismatch"; + else if (anchor.turn_instance_id !== turn_instance_id) fallbackReason = "turn_instance_mismatch"; + else if (anchor.context_epoch !== context_epoch) fallbackReason = "context_epoch_mismatch"; + else if (anchor.prefix_digest !== prefixDigest) fallbackReason = "prefix_digest_mismatch"; + else if (!surfacePrefixIntact) fallbackReason = "prefix_kv_not_preserved"; + else if (!toolPairingValid) fallbackReason = "unpaired_tool_calls"; + else if (nowStepIndex === null || nowStepIndex < (anchor.anchor_step_index as number)) { + fallbackReason = "invalid_reclaim_range"; + } else if ( + anchor.anchor_surface_seq !== null + && anchor.anchor_surface_seq !== undefined + && (nowSurfaceSeq === null || nowSurfaceSeq < (anchor.anchor_surface_seq as number)) + ) { + fallbackReason = "invalid_reclaim_range"; + } else if (rawReceipt === null) fallbackReason = "missing_completion_receipt"; + else if (receiptTodoId === null || receiptId === null) fallbackReason = "invalid_completion_receipt"; + else if (receiptTodoId !== todo_id) fallbackReason = "receipt_todo_mismatch"; + else if (receiptSha === null) fallbackReason = "invalid_completion_sha256"; + else if (sourceRefInvalid || sourceRef === null) fallbackReason = "missing_source_ref"; + else if (receiptExitCode === null || receiptExitCode !== 0) fallbackReason = "command_error"; + else if (obsCheck !== null && !obsCheck.ok) fallbackReason = obsCheck.reason; + + const anchorStep = anchor ? (anchor.anchor_step_index as number) : 0; + const anchorSurfaceSeq = anchor ? ((anchor.anchor_surface_seq as number | null) ?? null) : null; + const reclaimRange = fallbackReason === null && nowStepIndex !== null ? [anchorStep, nowStepIndex] : null; + const reclaimBounds: JsonObject | null = reclaimRange + ? { + start_step: anchorStep, + end_step: nowStepIndex, + start_surface_seq: anchorSurfaceSeq, + end_surface_seq: nowSurfaceSeq, + } + : null; + + const receiptMu: JsonObject | null = + fallbackReason === null && reclaimRange !== null && sourceRef !== null + ? { + trust_level: "tool", + todo_id, + completion_receipt_id: receiptId, + sha256: receiptSha, + turn_instance_id, + context_epoch, + prefix_digest: prefixDigest, + reclaim_range: reclaimRange, + exit_code: receiptExitCode, + failure_facts: receiptFailureFacts, + open_obligations: receiptOpenObligations, + source_ref: sourceRef, + } + : null; + + const obsOutputText = obsCheck && obsCheck.ok && obsCheck.output ? obsCheck.output : null; + const replacementText = + receiptMu !== null && sourceRef !== null + ? buildSemanticUnitReceiptText({ + mu: receiptMu, + sourceRefText: `${sourceRef.path} (sha256:${sourceRef.sha256})`, + obsOutput: obsOutputText, + }) + : null; + + const tokenGate = evaluateNetTokenSavingsGate({ + min_net_savings_tokens: minSavingsTokens, + cold_prefill_amortization_tokens: coldAmortizationTokens, + tokenizer_encoding: tokenizerEncoding, + baseline_tokens: baselineTokens, + delivered_tokens: replacementTokens, + rebased_prompt_tokens: replacementTokens, + tokenizer: rawRequest.tokenizer, + require_token_gate: fallbackReason === null, + }); + + if (fallbackReason === null && !tokenGate.passed) { + fallbackReason = tokenGate.fallback_reason ?? "negative_net_savings"; + } + + const tokenReceiptFields: JsonObject = { + baseline_tokens: tokenGate.baseline_tokens, + replacement_tokens: tokenGate.delivered_tokens, + net_savings_tokens: tokenGate.raw_net_savings_tokens, + cold_prefill_amortization_tokens: tokenGate.cold_prefill_amortization_tokens, + amortized_net_savings_tokens: tokenGate.amortized_net_savings_tokens, + min_net_savings_tokens: tokenGate.min_net_savings_tokens, + tokenizer: tokenGate.tokenizer, + }; + + if (fallbackReason !== null) { + const rollbackPayload: JsonObject = { + schema_version: SEMANTIC_UNIT_FOLD_SWAP_SCHEMA_VERSION, + enabled: true, + operator: "KeepRaw", + status: "fallback_keep_raw", + fallback_reason: fallbackReason, + trust_level: "tool", + preserves_raw_state: true, + preserves_prefix_kv: true, + todo_id, + turn_instance_id, + context_epoch, + prefix_digest: prefixDigest, + reclaim_range: null, + reclaim_bounds: null, + receipt_mu: null, + obs_next_cmd: obsCheck + ? { + allowed: obsCheck.reason === null, + command_sha256: obsCheck.command_sha256, + exit_code: obsCheck.exit_code, + truncated: obsCheck.truncated, + latency_ms: obsCheck.latency_ms, + } + : null, + replacement_text: null, + preserved_failure_facts: receiptFailureFacts, + preserved_open_obligations: receiptOpenObligations, + round_trips_saved: 0, + bytes_saved: 0, + ...tokenReceiptFields, + error_observation: `Semantic-unit fold rolled back atomically to KeepRaw (${fallbackReason}).`, + }; + return { + ...rollbackPayload, + receipt_sha256: sha256Hex(JSON.stringify(rollbackPayload)), + }; + } + + const baselineBytes = optionalInt(rawRequest.baseline_bytes, "baseline_bytes", 0, 100_000_000); + const replacementBytes = Buffer.byteLength(replacementText ?? "", "utf8"); + const bytesSaved = baselineBytes !== null && baselineBytes > replacementBytes + ? baselineBytes - replacementBytes + : 0; + const committedPayload: JsonObject = { + schema_version: SEMANTIC_UNIT_FOLD_SWAP_SCHEMA_VERSION, + enabled: true, + operator: "FoldToReceipt", + status: "committed", + fallback_reason: null, + trust_level: "tool", + preserves_raw_state: false, + preserves_prefix_kv: true, + todo_id, + turn_instance_id, + context_epoch, + prefix_digest: prefixDigest, + reclaim_range: reclaimRange, + reclaim_bounds: reclaimBounds, + receipt_mu: receiptMu, + obs_next_cmd: obsCheck + ? { + allowed: true, + command_sha256: obsCheck.command_sha256, + exit_code: obsCheck.exit_code, + truncated: obsCheck.truncated, + latency_ms: obsCheck.latency_ms, + output: obsOutputText, + } + : null, + replacement_text: replacementText, + preserved_failure_facts: receiptFailureFacts, + preserved_open_obligations: receiptOpenObligations, + round_trips_saved: obsCheck ? 1 : 0, + bytes_saved: bytesSaved, + ...tokenReceiptFields, + error_observation: null, + }; + return { + ...committedPayload, + receipt_sha256: sha256Hex(JSON.stringify(committedPayload)), + }; +} diff --git a/loopx/control_plane/quota/turn_envelope.py b/loopx/control_plane/quota/turn_envelope.py index dd061dcd1e..1294052695 100644 --- a/loopx/control_plane/quota/turn_envelope.py +++ b/loopx/control_plane/quota/turn_envelope.py @@ -505,12 +505,16 @@ def update_native_context_lifecycle(state: Mapping[str, Any], event: Mapping[str new_epoch: str, pages: list[dict[str, Any]], pages_verified: bool = False, resume_verified: bool = False, - resume_sections: Mapping[str, str] | None = None) -> dict[str, Any]: + resume_sections: Mapping[str, str] | None = None, + semantic_unit_anchor: Mapping[str, Any] | None = None, + semantic_unit_fold: Mapping[str, Any] | None = None) -> dict[str, Any]: """Native IO adapter; the shared typed owner reduces continuity assumptions.""" source = dict(state) result = _turn_envelope_result("native_context_lifecycle", state=source, source_edits=True, event=dict(event), new_epoch=new_epoch, pages=pages, pages_verified=pages_verified, - resume_verified=resume_verified, **({"resume_sections": dict(resume_sections)} if resume_sections else {})) + resume_verified=resume_verified, **({"resume_sections": dict(resume_sections)} if resume_sections else {}), + **({"semantic_unit_anchor": dict(semantic_unit_anchor)} if semantic_unit_anchor is not None else {}), + **({"semantic_unit_fold": dict(semantic_unit_fold)} if semantic_unit_fold is not None else {})) try: return _apply_context_projection_changes(source, result) except RuntimeError as error: @@ -527,3 +531,233 @@ def restore_context_delivery( current=dict(current)) result = _turn_envelope_result("context_recovery", **source, source_edits=True) return _apply_context_projection_changes(source, result) + + +def plan_stage_then_swap_prefetch( + *, + epoch_prefetch: Any = None, +) -> dict[str, Any]: + """Validate default-off Stage-then-Swap EpochReset prefetch configuration via TS.""" + return _turn_envelope_result( + "stage_then_swap_plan", + epoch_prefetch=dict(epoch_prefetch) if isinstance(epoch_prefetch, Mapping) else epoch_prefetch, + ) + + +def evaluate_epoch_prefetch_swap( + *, + epoch_prefetch: Mapping[str, Any], + context_epoch: str, + reclaimed_turns: int = 0, + dropped_failures: int = 0, + failure_facts: list[str] | tuple[str, ...] = (), + open_obligations: list[str] | tuple[str, ...] = (), + source_ref: Mapping[str, str] | None = None, + exit_code: int | None = None, + timed_out: bool = False, + truncated: bool = False, + raw_bytes_read: int = 0, + prefetched_output: str = "", + baseline_bytes: int | None = None, + baseline_tokens: int | None = None, + hydrated_tokens: int | None = None, + tokenizer: Mapping[str, Any] | None = None, + require_token_gate: bool = False, + latency_ms: int = 0, + error_observation: str | None = None, +) -> dict[str, Any]: + """Evaluate bounded prefetch output and anti-whitewashing receipt via TS.""" + payload: dict[str, Any] = { + "epoch_prefetch": dict(epoch_prefetch), + "context_epoch": context_epoch, + "reclaimed_turns": reclaimed_turns, + "dropped_failures": dropped_failures, + "failure_facts": list(failure_facts), + "open_obligations": list(open_obligations), + "source_ref": dict(source_ref) if source_ref is not None else None, + "exit_code": exit_code, + "timed_out": timed_out, + "truncated": truncated, + "raw_bytes_read": raw_bytes_read, + "prefetched_output": prefetched_output, + "baseline_bytes": baseline_bytes, + "latency_ms": latency_ms, + "require_token_gate": require_token_gate, + } + if baseline_tokens is not None: + payload["baseline_tokens"] = baseline_tokens + if hydrated_tokens is not None: + payload["hydrated_tokens"] = hydrated_tokens + if tokenizer is not None: + payload["tokenizer"] = dict(tokenizer) + if error_observation: + payload["error_observation"] = error_observation + return _turn_envelope_result("stage_then_swap_evaluate", **payload) + + +def evaluate_epoch_prefetch_prompt_gate( + *, + epoch_prefetch: Mapping[str, Any] | None = None, + has_inline_exploratory: bool, + replace_exploratory_context: bool, + host_input_measurable: bool = True, + rendered_prompt_baseline_bytes: int | None, + rendered_prompt_delivered_bytes: int | None, + rendered_prompt_baseline_tokens: int | None, + rendered_prompt_delivered_tokens: int | None, + external_baseline_bytes: int | None = None, + external_baseline_tokens: int | None = None, + potential_bytes_saved: int | None = None, + tokenizer: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + """Adjudicate EpochReset vs KeepRaw on delivered prompt bytes, tokens, and cold prefill.""" + payload: dict[str, Any] = { + "has_inline_exploratory": has_inline_exploratory, + "replace_exploratory_context": replace_exploratory_context, + "host_input_measurable": host_input_measurable, + "rendered_prompt_baseline_bytes": rendered_prompt_baseline_bytes, + "rendered_prompt_delivered_bytes": rendered_prompt_delivered_bytes, + "rendered_prompt_baseline_tokens": rendered_prompt_baseline_tokens, + "rendered_prompt_delivered_tokens": rendered_prompt_delivered_tokens, + "external_baseline_bytes": external_baseline_bytes, + "external_baseline_tokens": external_baseline_tokens, + "potential_bytes_saved": potential_bytes_saved, + "tokenizer": dict(tokenizer) if tokenizer is not None else None, + } + if epoch_prefetch is not None: + payload["epoch_prefetch"] = dict(epoch_prefetch) + return _turn_envelope_result("stage_then_swap_prompt_gate", **payload) + + +def compute_quiet_turn_state_digest( + *, + goal_id: str, + agent_id: str, + route: Mapping[str, Any] | None = None, + work_contract: Mapping[str, Any] | None = None, + turn_envelope: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + """Compute canonical volatile-free Quiet-Turn state digest and contract eligibility via TS.""" + payload: dict[str, Any] = { + "goal_id": goal_id, + "agent_id": agent_id, + "route": dict(route) if isinstance(route, Mapping) else None, + "work_contract": dict(work_contract) if isinstance(work_contract, Mapping) else None, + "turn_envelope": dict(turn_envelope) if isinstance(turn_envelope, Mapping) else None, + } + return _turn_envelope_result("quiet_turn_state_digest", **payload) + + +def evaluate_quiet_turn( + *, + enabled: bool = True, + quiet_noop_allowed: bool = True, + must_attempt: bool = False, + state_changed: bool | None = None, + current_state_digest: str | None = None, + previous_state_digest: str | None = None, + work_contract: Mapping[str, Any] | None = None, + turn_envelope: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + """Evaluate Quiet-Turn zero-tax skip metadata via TS.""" + payload: dict[str, Any] = { + "enabled": enabled, + "quiet_noop_allowed": quiet_noop_allowed, + "must_attempt": must_attempt, + } + if state_changed is not None: + payload["state_changed"] = state_changed + if current_state_digest is not None: + payload["current_state_digest"] = current_state_digest + if previous_state_digest is not None: + payload["previous_state_digest"] = previous_state_digest + if work_contract is not None: + payload["work_contract"] = dict(work_contract) + if turn_envelope is not None: + payload["turn_envelope"] = dict(turn_envelope) + return _turn_envelope_result("quiet_turn_evaluate", **payload) + + +def record_semantic_unit_anchor( + *, + todo_id: str, + turn_instance_id: str, + anchor_step_index: int, + prefix_digest: str, + context_epoch: str, + anchor_surface_seq: int | None = None, + goal_id: str | None = None, + agent_id: str | None = None, +) -> dict[str, Any]: + """Bind a Todo semantic-unit anchor to an exact parent KV prefix digest and epoch via TS.""" + payload: dict[str, Any] = { + "todo_id": todo_id, + "turn_instance_id": turn_instance_id, + "anchor_step_index": anchor_step_index, + "prefix_digest": prefix_digest, + "context_epoch": context_epoch, + } + if anchor_surface_seq is not None: + payload["anchor_surface_seq"] = anchor_surface_seq + if goal_id is not None: + payload["goal_id"] = goal_id + if agent_id is not None: + payload["agent_id"] = agent_id + return _turn_envelope_result("semantic_unit_anchor_record", **payload) + + +def build_semantic_unit_fold_swap( + *, + enabled: bool = False, + anchor: Mapping[str, Any] | None = None, + todo_id: str, + turn_instance_id: str, + context_epoch: str, + prefix_digest: str | None = None, + now_step_index: int | None = None, + now_surface_seq: int | None = None, + completion_receipt: Mapping[str, Any] | None = None, + baseline_tokens: int | None = None, + replacement_tokens: int | None = None, + baseline_bytes: int | None = None, + min_net_savings_tokens: int | None = None, + cold_prefill_amortization_tokens: int | None = None, + tokenizer_encoding: str | None = None, + tokenizer: Mapping[str, Any] | None = None, + obs_next_cmd: Mapping[str, Any] | None = None, + surface_prefix_intact: bool = True, + tool_pairing_valid: bool = True, + quiescent_boundary: bool = True, + failure_facts: list[str] | tuple[str, ...] = (), + open_obligations: list[str] | tuple[str, ...] = (), +) -> dict[str, Any]: + """Evaluate a receipt-gated Todo-unit suffix fold swap or fail closed to KeepRaw via TS.""" + payload: dict[str, Any] = { + "enabled": enabled, + "anchor": dict(anchor) if anchor is not None else None, + "todo_id": todo_id, + "turn_instance_id": turn_instance_id, + "context_epoch": context_epoch, + "prefix_digest": prefix_digest, + "now_step_index": now_step_index, + "completion_receipt": dict(completion_receipt) if completion_receipt is not None else None, + "baseline_tokens": baseline_tokens, + "replacement_tokens": replacement_tokens, + "baseline_bytes": baseline_bytes, + "tokenizer": dict(tokenizer) if tokenizer is not None else None, + "obs_next_cmd": dict(obs_next_cmd) if obs_next_cmd is not None else None, + "surface_prefix_intact": surface_prefix_intact, + "tool_pairing_valid": tool_pairing_valid, + "quiescent_boundary": quiescent_boundary, + "failure_facts": list(failure_facts), + "open_obligations": list(open_obligations), + } + if now_surface_seq is not None: + payload["now_surface_seq"] = now_surface_seq + if min_net_savings_tokens is not None: + payload["min_net_savings_tokens"] = min_net_savings_tokens + if cold_prefill_amortization_tokens is not None: + payload["cold_prefill_amortization_tokens"] = cold_prefill_amortization_tokens + if tokenizer_encoding is not None: + payload["tokenizer_encoding"] = tokenizer_encoding + return _turn_envelope_result("semantic_unit_fold_swap", **payload) diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index 9e31ec2309..3ed18242a2 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -15,6 +15,15 @@ import { } from "../capabilities/explore_context_delivery.ts"; import { prepareContextDelivery, restoreContextDelivery } from "./context_delivery.ts"; import { updateNativeContextLifecycle } from "./native_context_lifecycle.ts"; +import { + buildSemanticUnitFoldSwap, + computeQuietTurnStateDigest, + evaluateEpochPrefetchPromptGate, + evaluateEpochPrefetchSwap, + evaluateQuietTurn, + planStageThenSwapPrefetch, + recordSemanticUnitAnchor, +} from "./stage_then_swap.ts"; import { contextProjectionChanges, contextSourceIdentity, omitEmptyTaskTodoLanes, projectQuotaDiagnostics, referenceQuotaSummaryLanes, resolveQuotaSummaryLanes, @@ -1755,6 +1764,13 @@ export function evaluateTurnEnvelope(value: unknown): JsonObject { ? contextProjectionChanges(requireJsonObject(request.state, "native context journal"), journal) : journal; } + if (operation === "stage_then_swap_plan") return planStageThenSwapPrefetch(request); + if (operation === "stage_then_swap_evaluate") return evaluateEpochPrefetchSwap(request); + if (operation === "stage_then_swap_prompt_gate") return evaluateEpochPrefetchPromptGate(request); + if (operation === "semantic_unit_anchor_record") return recordSemanticUnitAnchor(request); + if (operation === "semantic_unit_fold_swap") return buildSemanticUnitFoldSwap(request); + if (operation === "quiet_turn_evaluate") return evaluateQuietTurn(request); + if (operation === "quiet_turn_state_digest") return computeQuietTurnStateDigest(request); if (operation === "context_recovery") return restoreContextDelivery(request, LEGACY_QUOTA_CONTEXT_FIELDS); if (operation === "bind_capture") return bindTurnDecisionCapture(request); if (operation === "scoped_settlement_identity") return {identity: turnEnvelopeScopedSettlementIdentity( diff --git a/loopx/control_plane/turn_driver/codex_cli.py b/loopx/control_plane/turn_driver/codex_cli.py index ff093b0d5d..5bdf56615f 100644 --- a/loopx/control_plane/turn_driver/codex_cli.py +++ b/loopx/control_plane/turn_driver/codex_cli.py @@ -413,6 +413,22 @@ def _render_prompt(request: Mapping[str, Any], *, checked: Mapping[str, Any] | N # its verified authority and immutable readers, not a second executor. model_request = {key: value for key, value in request.items() if key != "turn_envelope"} model_request["turn_authority"] = authority + if isinstance(model_request.get("epoch_prefetch"), Mapping): + from .epoch_prefetch import strip_internal_epoch_prefetch_audit_fields + + stripped = strip_internal_epoch_prefetch_audit_fields(model_request["epoch_prefetch"]) + compact_prefetch = { + key: value + for key, value in stripped.items() + if key not in { + "hydrated_text", + "header_fields", + "preserved_failure_facts", + "preserved_open_obligations", + "error_observation", + } + } + model_request = {**dict(model_request), "epoch_prefetch": compact_prefetch} request_json = json.dumps( model_request, ensure_ascii=False, sort_keys=True, separators=(",", ":") ) @@ -471,6 +487,20 @@ def _render_prompt(request: Mapping[str, Any], *, checked: Mapping[str, Any] | N "Use one or more opaque evidence_refs such as artifact:child-result. Receipt identifiers and evidence refs must contain no spaces, prose, URLs, or local paths.", "If a child deviates from that packet, stop or quarantine only that child and its evidence. Do not let the child write LoopX state or block the parent agent; the parent may retry fresh, replace the child, take over serially, or ignore an optional result.", ]) + if isinstance(request.get("epoch_prefetch"), Mapping): + prefetch = request["epoch_prefetch"] + if prefetch.get("operator") == "EpochReset" and isinstance(prefetch.get("hydrated_text"), str): + instructions.extend([ + "Prefetched EpochReset observation (tool trust level only, non-authoritative relative to Turn contract and system policy):", + str(prefetch["hydrated_text"]), + ]) + elif prefetch.get("operator") == "KeepRaw": + instructions.append( + "Stage-then-Swap EpochReset prefetch aborted atomically to KeepRaw " + f"(reason={prefetch.get('fallback_reason')}; original context and obligations preserved; " + 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)})." + ) instructions.extend(["Turn request:", request_json]) return "\n".join(instructions) diff --git a/loopx/control_plane/turn_driver/codex_context.py b/loopx/control_plane/turn_driver/codex_context.py index d7a9a8a857..3d1be0df1a 100644 --- a/loopx/control_plane/turn_driver/codex_context.py +++ b/loopx/control_plane/turn_driver/codex_context.py @@ -390,6 +390,8 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str observe_completed_native_reread, observe_native_read, ) + from .semantic_unit_hook import run_locked_semantic_unit_hook, semantic_unit_event_active + if directory is None: return {} name, session = event.get("hook_event_name"), event.get("session_id") @@ -399,9 +401,11 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str return {} # no parent recovery reference may escape to a subagent pages = _context_pages(event.get("tool_response")) if name == "PostToolUse" else [] raw_pages = pages - if name == "PostToolUse" and not pages: + if name == "PostToolUse" and not pages and not semantic_unit_event_active(event): return {} # ordinary tool use neither invalidates nor rewrites the journal + state: dict[str, Any] = {} recovery = None + semantic_unit_output: dict[str, Any] | None = None try: with _locked(directory) as root: try: @@ -431,23 +435,16 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str checkpoint_native_read(read_state, updated, event, full_pages) observe_completed_native_reread(read_state, updated, event, full_pages) checkpoint_native_selection(state, updated, event, raw_pages, pages) - previous = updated.get("host_execution_preparation") - ready = previous.get("ready_capture") if isinstance(previous, dict) else None - ready_digest = ready.get("sha256") if isinstance(ready, dict) else None - if isinstance(previous, dict) and isinstance(ready_digest, str) and not previous.get("retired_context_readback") and any( - page.get("ok") is True - and ready_digest in (page.get("sha256"), page.get("source_sha256")) - for page in pages - ): - # These bytes were checked against the recorded ready - # capture. An earlier guard read or Hook stdout does not - # show that this recovery path reached the caller. - updated["host_execution_preparation"] = { - **previous, - "ready_read_observed": True, - } + _mark_ready_read_observed(updated, pages) if updated != state: _save(root, updated) + before_semantic_state = (updated.get("semantic_unit_anchors"), updated.get("semantic_unit_folds")) + semantic_unit_output = run_locked_semantic_unit_hook( + hook_name=name, session=session, + state=state, updated=updated, event=event, + ) + if (updated.get("semantic_unit_anchors"), updated.get("semantic_unit_folds")) != before_semantic_state: + _save(root, updated) saved = updated.get("recovery") current_file_epoch = (isinstance(saved, dict) and saved.get("continuity_basis") == "captured_file" @@ -463,15 +460,70 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str raise except (OSError, ValueError, TypeError, RecursionError, EffectRuntimeRemoteError, EffectRuntimeStartupError): recovery_needed = True - if (name == "SessionStart" and recovery_needed - and isinstance(recovery, dict) and recovery.get("command")): - return {"hookSpecificOutput": {"hookEventName": name, "additionalContext": + return _resolve_codex_context_hook_output( + directory=directory, name=name, state=state, event=event, + recovery=recovery, recovery_needed=recovery_needed, + semantic_unit_output=semantic_unit_output, + ) + + +def _mark_ready_read_observed(updated: dict[str, Any], pages: list[dict[str, Any]]) -> None: + previous = updated.get("host_execution_preparation") + ready = previous.get("ready_capture") if isinstance(previous, dict) else None + ready_digest = ready.get("sha256") if isinstance(ready, dict) else None + if isinstance(previous, dict) and isinstance(ready_digest, str) and not previous.get("retired_context_readback") and any( + page.get("ok") is True and ready_digest in (page.get("sha256"), page.get("source_sha256")) + for page in pages + ): + updated["host_execution_preparation"] = {**previous, "ready_read_observed": True} + + +def _resolve_codex_context_hook_output( + *, + directory: str, + name: Any, + state: Mapping[str, Any], + event: Mapping[str, Any], + recovery: Any, + recovery_needed: bool, + semantic_unit_output: dict[str, Any] | None, +) -> dict[str, Any]: + from .epoch_prefetch import resolve_codex_context_epoch_prefetch_hook, resolve_codex_context_quiet_turn_hook + from .semantic_unit_hook import merge_semantic_unit_hook_output + + if name == "SessionStart" and recovery_needed and isinstance(recovery, dict) and recovery.get("command"): + prefetch_hook = resolve_codex_context_epoch_prefetch_hook( + directory=directory, + hook_name=name, + state=state, + event=event, + recovery=recovery, + lock_ctx=_locked, + read_state_fn=_state, + save_state_fn=_save, + continuation_text=_context_continuation_instructions(recovery["command"]), + raw_guidance_text=( + CONTEXT_CAPTURE_SELECTION_GUIDANCE + + _NATIVE_CONTEXT_OUTPUT_GUIDANCE + + "If you choose to read an entire file: " + + CONTEXT_CAPTURE_PAGE_GUIDANCE + ), + ) + if prefetch_hook is not None: + return merge_semantic_unit_hook_output(prefetch_hook, semantic_unit_output) + fallback_out: dict[str, Any] = {"hookSpecificOutput": {"hookEventName": name, "additionalContext": "LoopX model-context baseline invalidated. Saved files remain available. " + _context_continuation_instructions(recovery["command"]) + CONTEXT_CAPTURE_SELECTION_GUIDANCE + _NATIVE_CONTEXT_OUTPUT_GUIDANCE + "If you choose to read an entire file: " + CONTEXT_CAPTURE_PAGE_GUIDANCE}} - return {} + return merge_semantic_unit_hook_output(fallback_out, semantic_unit_output) + if semantic_unit_output is not None: + return semantic_unit_output + quiet_hook = resolve_codex_context_quiet_turn_hook( + hook_name=name, state=state, event=event, recovery=recovery, root_dir=_private_root(directory), + ) + return quiet_hook if quiet_hook is not None else {} def _preparation_readback(action: dict[str, Any], previous: dict[str, Any], *, diff --git a/loopx/control_plane/turn_driver/epoch_prefetch.py b/loopx/control_plane/turn_driver/epoch_prefetch.py new file mode 100644 index 0000000000..53850479be --- /dev/null +++ b/loopx/control_plane/turn_driver/epoch_prefetch.py @@ -0,0 +1,1711 @@ +"""Bounded Stage-then-Swap EpochReset prefetch, File+SQLite persistence, and Quiet-Turn IO. + +Semantic admission, anti-whitewashing receipt construction, net-gain gating, and +fail-closed KeepRaw decisions stay owned by TypeScript (`quota/stage_then_swap.ts`). +This module owns bounded subprocess execution and durable File + SQLite replay IO. +""" +from __future__ import annotations + +from collections.abc import Callable, Mapping +from contextlib import closing +import hashlib +import json +import os +from pathlib import Path +import selectors +import signal +import sqlite3 +import subprocess +import time +from typing import Any, cast + +from ...file_lock import exclusive_file_lock +from ..quota.turn_envelope import ( + evaluate_epoch_prefetch_prompt_gate, + evaluate_epoch_prefetch_swap, + plan_stage_then_swap_prefetch, +) +from .quiet_turn_store import ( + QUIET_TURN_SKIP_SCHEMA_VERSION as QUIET_TURN_SKIP_SCHEMA_VERSION, + QUIET_TURN_STATE_SCHEMA_VERSION as QUIET_TURN_STATE_SCHEMA_VERSION, + atomic_write_json as _atomic_write_json, + commit_quiet_turn_state as commit_quiet_turn_state, + commit_turn_quiet_state_after_success as commit_turn_quiet_state_after_success, + effective_turn_agent_id as _effective_agent_id, + init_turn_prefetch_sqlite_db as _init_sqlite_db, + is_turn_option_enabled as _is_turn_option_enabled, + maybe_skip_quiet_turn_before_admission as maybe_skip_quiet_turn_before_admission, + now_iso as _now_iso, + quiet_turn_target_params as _quiet_turn_target_params, + resolve_codex_context_quiet_turn_hook as resolve_codex_context_quiet_turn_hook, + resolve_quiet_turn_metadata as resolve_quiet_turn_metadata, + sha256_text as _sha256_text, +) + +EPOCH_PREFETCH_SCHEMA_VERSION = "loopx_epoch_prefetch_state_v0" +_HARD_WIRE_DRAIN_MULTIPLIER = 4 +_MIN_HARD_WIRE_DRAIN_BYTES = 262_144 +_MAX_VERIFIED_SOURCE_BYTES = 10 * 1024 * 1024 +DEFAULT_TOKENIZER_ENCODING = "o200k_base" + + +def count_verifiable_tokens( + text: str, + *, + encoding_name: str = DEFAULT_TOKENIZER_ENCODING, + token_counter: Callable[[str], int] | None = None, +) -> tuple[int, dict[str, Any]] | None: + """Count tokens using an inspectable tokenizer (`tiktoken` or explicit callable).""" + if token_counter is not None: + try: + count = token_counter(text) + except Exception: # noqa: BLE001 - fail closed if configured counter raises + return None + if isinstance(count, bool) or not isinstance(count, int) or count < 0: + return None + return count, {"name": "configured_tokenizer", "encoding": encoding_name} + try: + from importlib.metadata import version + import tiktoken + + encoding = tiktoken.get_encoding(encoding_name) + count = len(encoding.encode_ordinary(text)) + try: + pkg_version = version("tiktoken") + except Exception: # noqa: BLE001 + pkg_version = "unknown" + return count, {"name": "tiktoken", "version": pkg_version, "encoding": encoding_name} + except Exception: # noqa: BLE001 - missing/unavailable tokenizer fails closed + return None + + +def _measure_verified_source_ref_tokens( + source_ref: Mapping[str, Any] | None, + *, + encoding_name: str = DEFAULT_TOKENIZER_ENCODING, + token_counter: Callable[[str], int] | None = None, +) -> tuple[int, int, dict[str, Any]] | None: + """Verify `source_ref` on disk by sha256 and count UTF-8 baseline tokens.""" + if not isinstance(source_ref, Mapping): + return None + raw_path = source_ref.get("path") + expected_sha = source_ref.get("sha256") + if ( + not isinstance(raw_path, str) + or not raw_path + or not isinstance(expected_sha, str) + or len(expected_sha) != 64 + ): + return None + path = Path(raw_path) + try: + if not path.is_file(): + return None + if path.stat().st_size > _MAX_VERIFIED_SOURCE_BYTES: + return None + raw_bytes = path.read_bytes() + except OSError: + return None + if hashlib.sha256(raw_bytes).hexdigest() != expected_sha: + return None + try: + text = raw_bytes.decode("utf-8") + except UnicodeDecodeError: + return None + counted = count_verifiable_tokens( + text, encoding_name=encoding_name, token_counter=token_counter, + ) + if counted is None: + return None + tokens, tokenizer_meta = counted + return len(raw_bytes), tokens, tokenizer_meta + + +def _utf8_prefix(data: bytes, max_bytes: int) -> tuple[str, bool]: + if len(data) <= max_bytes: + return data.decode("utf-8", errors="replace"), False + clipped = data[:max_bytes] + # Back off past any split UTF-8 continuation bytes so output stays valid text. + while clipped and (clipped[-1] & 0xC0) == 0x80: + clipped = clipped[:-1] + return clipped.decode("utf-8", errors="replace"), True + + +def _terminate_process_group(process: subprocess.Popen[bytes]) -> None: + try: + if os.name == "posix": + os.killpg(process.pid, signal.SIGKILL) + else: + process.kill() + except OSError: + try: + process.kill() + except OSError: + pass + + +def run_bounded_prefetch_subprocess( + argv: list[str], + *, + timeout_ms: int, + max_output_bytes: int, + cwd: str | Path | None = None, +) -> dict[str, Any]: + """Execute one bounded single-shot read-only command under timeout and byte caps.""" + start = time.monotonic() + hard_cap = max(max_output_bytes * _HARD_WIRE_DRAIN_MULTIPLIER, _MIN_HARD_WIRE_DRAIN_BYTES) + deadline = start + (timeout_ms / 1000.0) + stdout_kept = bytearray() + stderr_kept = bytearray() + raw_stdout_bytes = 0 + truncated = False + timed_out = False + hard_overflow = False + + process = subprocess.Popen( + argv, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.DEVNULL, + shell=False, + cwd=str(cwd) if cwd is not None else None, + start_new_session=(os.name == "posix"), + ) + assert process.stdout is not None and process.stderr is not None + selector = selectors.DefaultSelector() + try: + for stream, kind in ((process.stdout, "stdout"), (process.stderr, "stderr")): + os.set_blocking(stream.fileno(), False) + selector.register(stream, selectors.EVENT_READ, data=kind) + + while selector.get_map(): + remaining = deadline - time.monotonic() + if remaining <= 0: + timed_out = True + _terminate_process_group(process) + break + events = selector.select(timeout=min(remaining, 0.1)) + if not events and process.poll() is not None and time.monotonic() >= deadline: + timed_out = True + _terminate_process_group(process) + break + for key, _ in events: + stream = key.fileobj + assert hasattr(stream, "fileno") + try: + chunk = os.read(stream.fileno(), 4096) + except BlockingIOError: + continue + if not chunk: + selector.unregister(stream) + continue + if key.data == "stdout": + raw_stdout_bytes += len(chunk) + if len(stdout_kept) < max_output_bytes: + take = max_output_bytes - len(stdout_kept) + stdout_kept.extend(chunk[:take]) + if raw_stdout_bytes > max_output_bytes: + truncated = True + if raw_stdout_bytes > hard_cap: + hard_overflow = True + _terminate_process_group(process) + selector.unregister(stream) + break + else: + if len(stderr_kept) < 1024: + stderr_kept.extend(chunk[: 1024 - len(stderr_kept)]) + if hard_overflow: + break + + if not timed_out and not hard_overflow: + remaining = max(0.0, deadline - time.monotonic()) + try: + exit_code: int | None = process.wait(timeout=remaining) + except subprocess.TimeoutExpired: + timed_out = True + _terminate_process_group(process) + process.wait() + exit_code = None + else: + process.wait() + exit_code = None if timed_out else -1 + finally: + selector.close() + process.stdout.close() + process.stderr.close() + + latency_ms = max(0, int(round((time.monotonic() - start) * 1000))) + output_text, utf8_truncated = _utf8_prefix(bytes(stdout_kept), max_output_bytes) + truncated = truncated or utf8_truncated + stderr_text = stderr_kept.decode("utf-8", errors="replace").strip() + error_observation = None + if timed_out: + error_observation = f"prefetch_command timed out after {timeout_ms}ms" + elif hard_overflow: + error_observation = f"prefetch_command exceeded hard output ceiling ({hard_cap} bytes)" + elif exit_code != 0: + detail = f": {stderr_text[:256]}" if stderr_text else "" + error_observation = f"prefetch_command failed with exit_code={exit_code}{detail}" + return { + "exit_code": None if (timed_out or hard_overflow) else exit_code, + "timed_out": timed_out, + "truncated": truncated, + "raw_bytes_read": raw_stdout_bytes, + "prefetched_output": "" if hard_overflow else output_text, + "latency_ms": latency_ms, + "error_observation": error_observation, + } + + +def _record_identity_key( + *, + scope_key: str, + context_epoch: str, + command_sha256: str, + source_sha256: str, +) -> str: + payload = json.dumps( + { + "scope_key": scope_key, + "context_epoch": context_epoch, + "command_sha256": command_sha256, + "source_sha256": source_sha256, + }, + sort_keys=True, + separators=(",", ":"), + ) + return _sha256_text(payload) + + +def _read_sqlite_record( + sqlite_path: Path, + *, + scope_key: str, + context_epoch: str, + command_sha256: str, + source_sha256: str, +) -> dict[str, Any] | None: + if not sqlite_path.exists(): + return None + with closing(sqlite3.connect(sqlite_path, timeout=5.0)) as connection: + _init_sqlite_db(connection) + row = connection.execute( + """ + SELECT record_json, receipt_sha256 + FROM epoch_prefetch_records + WHERE scope_key = ? AND context_epoch = ? AND command_sha256 = ? AND source_sha256 = ? + """, + (scope_key, context_epoch, command_sha256, source_sha256), + ).fetchone() + if row is None: + return None + record = json.loads(row[0]) + if not isinstance(record, dict) or record.get("receipt_sha256") != row[1]: + return None + return record + + +def _write_sqlite_record( + sqlite_path: Path, + *, + scope_key: str, + context_epoch: str, + command_sha256: str, + source_sha256: str, + record: Mapping[str, Any], +) -> None: + sqlite_path.parent.mkdir(parents=True, exist_ok=True) + receipt_sha256 = str(record.get("receipt_sha256") or "") + operator = str(record.get("operator") or "KeepRaw") + encoded = json.dumps(dict(record), ensure_ascii=False, sort_keys=True) + with closing(sqlite3.connect(sqlite_path, timeout=5.0, isolation_level=None)) as connection: + _init_sqlite_db(connection) + connection.execute("BEGIN IMMEDIATE") + try: + existing = connection.execute( + """ + SELECT receipt_sha256 + FROM epoch_prefetch_records + WHERE scope_key = ? AND context_epoch = ? AND command_sha256 = ? AND source_sha256 = ? + """, + (scope_key, context_epoch, command_sha256, source_sha256), + ).fetchone() + if existing is None: + connection.execute( + """ + INSERT INTO epoch_prefetch_records ( + scope_key, context_epoch, command_sha256, source_sha256, + receipt_sha256, operator, record_json, created_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + scope_key, + context_epoch, + command_sha256, + source_sha256, + receipt_sha256, + operator, + encoded, + _now_iso(), + ), + ) + elif existing[0] != receipt_sha256: + raise ValueError("Conflicting SQLite epoch_prefetch receipt") + connection.execute("COMMIT") + except BaseException: + if connection.in_transaction: + connection.execute("ROLLBACK") + raise + + +def _read_file_record( + file_path: Path, + *, + scope_key: str, + context_epoch: str, + command_sha256: str, + source_sha256: str, +) -> dict[str, Any] | None: + if not file_path.is_file(): + return None + try: + envelope = json.loads(file_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + if not isinstance(envelope, dict) or envelope.get("schema_version") != EPOCH_PREFETCH_SCHEMA_VERSION: + return None + identity = envelope.get("identity") + record = envelope.get("record") + if ( + not isinstance(identity, dict) + or identity.get("scope_key") != scope_key + or identity.get("context_epoch") != context_epoch + or identity.get("command_sha256") != command_sha256 + or identity.get("source_sha256") != source_sha256 + or not isinstance(record, dict) + ): + return None + return record + + +def _write_file_record( + file_path: Path, + *, + scope_key: str, + context_epoch: str, + command_sha256: str, + source_sha256: str, + record: Mapping[str, Any], +) -> None: + _atomic_write_json( + file_path, + { + "schema_version": EPOCH_PREFETCH_SCHEMA_VERSION, + "identity": { + "scope_key": scope_key, + "context_epoch": context_epoch, + "command_sha256": command_sha256, + "source_sha256": source_sha256, + }, + "record": dict(record), + "recorded_at": _now_iso(), + }, + ) + + +def _matching_inline_record( + candidate: Any, + *, + context_epoch: str, + command_sha256: str, + source_sha256: str, +) -> dict[str, Any] | None: + if not isinstance(candidate, Mapping): + return None + if candidate.get("context_epoch") != context_epoch: + return None + if candidate.get("command_sha256") != command_sha256: + return None + ref = candidate.get("source_ref") + candidate_source_sha = str(ref.get("sha256") or "") if isinstance(ref, Mapping) else "" + if candidate_source_sha != source_sha256: + return None + if not isinstance(candidate.get("receipt_sha256"), str): + return None + return dict(candidate) + + +def _conflict_keep_raw_receipt( + *, + epoch_prefetch: Mapping[str, Any], + context_epoch: str, + failure_facts: list[str] | tuple[str, ...], + open_obligations: list[str] | tuple[str, ...], + source_ref: Mapping[str, str] | None, + baseline_bytes: int | None, +) -> dict[str, Any]: + return evaluate_epoch_prefetch_swap( + epoch_prefetch=epoch_prefetch, + context_epoch=context_epoch, + reclaimed_turns=0, + dropped_failures=0, + failure_facts=failure_facts, + open_obligations=open_obligations, + source_ref=source_ref, + exit_code=None, + timed_out=False, + truncated=False, + raw_bytes_read=0, + prefetched_output="", + baseline_bytes=baseline_bytes, + latency_ms=0, + error_observation="Prefetch aborted atomically to KeepRaw (file_sqlite_state_conflict).", + ) + + +def _evaluate_swap_with_token_gate( + *, + epoch_prefetch: Mapping[str, Any], + context_epoch: str, + reclaimed_turns: int, + dropped_failures: int, + failure_facts: list[str] | tuple[str, ...], + open_obligations: list[str] | tuple[str, ...], + source_ref: Mapping[str, str] | None, + exit_code: int | None, + timed_out: bool, + truncated: bool, + raw_bytes_read: int, + prefetched_output: str, + baseline_bytes: int | None, + latency_ms: int, + error_observation: str | None, + require_token_gate: bool, + token_counter: Callable[[str], int] | None, +) -> dict[str, Any]: + evaluated = evaluate_epoch_prefetch_swap( + epoch_prefetch=epoch_prefetch, + context_epoch=context_epoch, + reclaimed_turns=reclaimed_turns, + dropped_failures=dropped_failures, + failure_facts=failure_facts, + open_obligations=open_obligations, + source_ref=source_ref, + exit_code=exit_code, + timed_out=timed_out, + truncated=truncated, + raw_bytes_read=raw_bytes_read, + prefetched_output=prefetched_output, + baseline_bytes=baseline_bytes, + latency_ms=latency_ms, + error_observation=error_observation, + ) + if evaluated.get("operator") != "EpochReset" or (source_ref is None and not require_token_gate): + return evaluated + encoding_name = str(epoch_prefetch.get("tokenizer_encoding") or DEFAULT_TOKENIZER_ENCODING) + measured_source = _measure_verified_source_ref_tokens( + source_ref, encoding_name=encoding_name, token_counter=token_counter, + ) + measured_hydrated = count_verifiable_tokens( + str(evaluated.get("hydrated_text") or ""), + encoding_name=encoding_name, + token_counter=token_counter, + ) + tokenizer_meta = ( + measured_hydrated[1] + if measured_hydrated is not None + else (measured_source[2] if measured_source is not None else None) + ) + gated = evaluate_epoch_prefetch_swap( + epoch_prefetch=epoch_prefetch, + context_epoch=context_epoch, + reclaimed_turns=reclaimed_turns, + dropped_failures=dropped_failures, + failure_facts=failure_facts, + open_obligations=open_obligations, + source_ref=source_ref, + exit_code=exit_code, + timed_out=timed_out, + truncated=truncated, + raw_bytes_read=raw_bytes_read, + prefetched_output=prefetched_output, + baseline_bytes=measured_source[0] if measured_source is not None else baseline_bytes, + baseline_tokens=measured_source[1] if measured_source is not None else None, + hydrated_tokens=measured_hydrated[0] if measured_hydrated is not None else None, + tokenizer=tokenizer_meta, + require_token_gate=True, + latency_ms=latency_ms, + error_observation=error_observation, + ) + if measured_source is not None and gated.get("operator") == "EpochReset": + return {**gated, "baseline_tokens_verified": True} + return gated + + +def resolve_or_execute_epoch_prefetch( + *, + epoch_prefetch: Mapping[str, Any] | None, + scope_key: str, + context_epoch: str, + file_store_dir: Path, + sqlite_path: Path, + reclaimed_turns: int = 0, + dropped_failures: int = 0, + failure_facts: list[str] | tuple[str, ...] = (), + open_obligations: list[str] | tuple[str, ...] = (), + source_ref: Mapping[str, str] | None = None, + baseline_bytes: int | None = None, + cwd: str | Path | None = None, + existing_inline_record: Mapping[str, Any] | None = None, + runner: Callable[..., dict[str, Any]] | None = None, + allow_execute: bool = True, + require_token_gate: bool = False, + token_counter: Callable[[str], int] | None = None, +) -> dict[str, Any] | None: + """Resolve once-only Stage-then-Swap EpochReset prefetch or fail closed to KeepRaw. + + Persists completion/output across both File (`file_store_dir`) and SQLite + (`sqlite_path`) keyed by `(scope_key, context_epoch, command_sha256, source_sha256)` + so replay never re-executes `prefetch_command`. + """ + plan = plan_stage_then_swap_prefetch(epoch_prefetch=epoch_prefetch) + if not plan.get("enabled"): + return None + assert isinstance(epoch_prefetch, Mapping) + + safety = plan.get("safety") if isinstance(plan.get("safety"), Mapping) else {} + command_sha256 = str( + safety.get("command_sha256") + or _sha256_text(json.dumps(epoch_prefetch.get("prefetch_command"), sort_keys=True, default=str)) + ) + source_sha256 = str(source_ref.get("sha256") or "") if isinstance(source_ref, Mapping) else "" + key_hash = _record_identity_key( + scope_key=scope_key, + context_epoch=context_epoch, + command_sha256=command_sha256, + source_sha256=source_sha256, + ) + file_path = file_store_dir / f"{key_hash}.json" + + with exclusive_file_lock(file_path, operation="epoch_prefetch_resolve"): + inline_record = _matching_inline_record( + existing_inline_record, + context_epoch=context_epoch, + command_sha256=command_sha256, + source_sha256=source_sha256, + ) + file_record = _read_file_record( + file_path, + scope_key=scope_key, + context_epoch=context_epoch, + command_sha256=command_sha256, + source_sha256=source_sha256, + ) + sqlite_record = _read_sqlite_record( + sqlite_path, + scope_key=scope_key, + context_epoch=context_epoch, + command_sha256=command_sha256, + source_sha256=source_sha256, + ) + + observed = [rec for rec in (inline_record, file_record, sqlite_record) if rec is not None] + if observed: + receipts = {str(rec.get("receipt_sha256") or "") for rec in observed} + if len(receipts) != 1: + conflict = _conflict_keep_raw_receipt( + epoch_prefetch=epoch_prefetch, + context_epoch=context_epoch, + failure_facts=failure_facts, + open_obligations=open_obligations, + source_ref=source_ref, + baseline_bytes=baseline_bytes, + ) + return { + **conflict, + "fallback_reason": "state_conflict", + "replayed": True, + "executed": False, + "persistence": { + "file_path": str(file_path), + "sqlite_path": str(sqlite_path), + "state_conflict": True, + }, + } + reused = dict(observed[0]) + if file_record is None: + _write_file_record( + file_path, + scope_key=scope_key, + context_epoch=context_epoch, + command_sha256=command_sha256, + source_sha256=source_sha256, + record=reused, + ) + if sqlite_record is None: + _write_sqlite_record( + sqlite_path, + scope_key=scope_key, + context_epoch=context_epoch, + command_sha256=command_sha256, + source_sha256=source_sha256, + record=reused, + ) + return { + **reused, + "replayed": True, + "executed": False, + "persistence": { + "file_path": str(file_path), + "sqlite_path": str(sqlite_path), + "healed_file": file_record is None, + "healed_sqlite": sqlite_record is None, + }, + } + + if not allow_execute: + return None + + if not plan.get("eligible"): + evaluated = evaluate_epoch_prefetch_swap( + epoch_prefetch=epoch_prefetch, + context_epoch=context_epoch, + reclaimed_turns=reclaimed_turns, + dropped_failures=dropped_failures, + failure_facts=failure_facts, + open_obligations=open_obligations, + source_ref=source_ref, + exit_code=None, + timed_out=False, + truncated=False, + raw_bytes_read=0, + prefetched_output="", + baseline_bytes=baseline_bytes, + latency_ms=0, + ) + executed = False + else: + argv = [str(part) for part in safety.get("argv", [])] + exec_runner = runner or run_bounded_prefetch_subprocess + probe = exec_runner( + argv, + timeout_ms=int(plan["timeout_ms"]), + max_output_bytes=int(plan["max_output_bytes"]), + cwd=cwd, + ) + evaluated = _evaluate_swap_with_token_gate( + epoch_prefetch=epoch_prefetch, + context_epoch=context_epoch, + reclaimed_turns=reclaimed_turns, + dropped_failures=dropped_failures, + failure_facts=failure_facts, + open_obligations=open_obligations, + source_ref=source_ref, + exit_code=probe.get("exit_code"), + timed_out=bool(probe.get("timed_out")), + truncated=bool(probe.get("truncated")), + raw_bytes_read=int(probe.get("raw_bytes_read") or 0), + prefetched_output=str(probe.get("prefetched_output") or ""), + baseline_bytes=baseline_bytes, + latency_ms=int(probe.get("latency_ms") or 0), + error_observation=probe.get("error_observation"), + require_token_gate=require_token_gate, + token_counter=token_counter, + ) + executed = True + + # Persist in BOTH File and SQLite before returning so crash/replay is strictly once-only. + _write_sqlite_record( + sqlite_path, + scope_key=scope_key, + context_epoch=context_epoch, + command_sha256=command_sha256, + source_sha256=source_sha256, + record=evaluated, + ) + _write_file_record( + file_path, + scope_key=scope_key, + context_epoch=context_epoch, + command_sha256=command_sha256, + source_sha256=source_sha256, + record=evaluated, + ) + return { + **evaluated, + "replayed": False, + "executed": executed, + "persistence": { + "file_path": str(file_path), + "sqlite_path": str(sqlite_path), + "healed_file": False, + "healed_sqlite": False, + }, + } + + +def _turn_epoch_inputs( + *, + plan: Mapping[str, Any], + request: Mapping[str, Any], + epoch_prefetch: Mapping[str, Any], + capture: Any = None, +) -> dict[str, Any]: + work_contract = ( + plan.get("work_contract") + if isinstance(plan.get("work_contract"), Mapping) + else request.get("work_contract") + if isinstance(request.get("work_contract"), Mapping) + else {} + ) + envelope = ( + plan.get("turn_envelope") + if isinstance(plan.get("turn_envelope"), Mapping) + else request.get("turn_envelope") + if isinstance(request.get("turn_envelope"), Mapping) + else {} + ) + session = plan.get("session") if isinstance(plan.get("session"), Mapping) else {} + context_epoch = str( + epoch_prefetch.get("context_epoch") + or session.get("context_epoch") + or f"turn:{request.get('turn_key') or 'default'}" + ) + source_ref = epoch_prefetch.get("source_ref") + if not isinstance(source_ref, Mapping) and capture is not None: + capture_path = getattr(capture, "path", None) + capture_sha256 = getattr(capture, "sha256", None) + if isinstance(capture_path, (str, Path)) and isinstance(capture_sha256, str) and len(capture_sha256) == 64: + source_ref = {"path": str(capture_path), "sha256": capture_sha256} + open_obligations: list[str] = list(epoch_prefetch.get("open_obligations") or ()) + route = plan.get("route") if isinstance(plan.get("route"), Mapping) else {} + selected_todo = route.get("selected_todo") if isinstance(route.get("selected_todo"), Mapping) else {} + if isinstance(selected_todo.get("todo_id"), str) and selected_todo["todo_id"]: + label = f"todo:{selected_todo['todo_id']}" + if isinstance(selected_todo.get("text"), str) and selected_todo["text"].strip(): + label = f"{selected_todo['todo_id']}: {selected_todo['text'].strip()[:160]}" + if label not in open_obligations: + open_obligations.append(label) + replan_id = envelope.get("replan_obligation_id") or work_contract.get("replan_obligation_id") + if isinstance(replan_id, str) and replan_id and replan_id not in open_obligations: + open_obligations.append(f"replan_obligation:{replan_id}") + failure_facts = list(epoch_prefetch.get("failure_facts") or ()) + baseline_bytes = epoch_prefetch.get("baseline_bytes") + if baseline_bytes is None and isinstance(request.get("exploratory_context"), (str, Mapping, list)): + raw_exploratory = ( + request["exploratory_context"] + if isinstance(request["exploratory_context"], str) + else json.dumps(request["exploratory_context"], ensure_ascii=False, sort_keys=True) + ) + baseline_bytes = len(raw_exploratory.encode("utf-8")) + return { + "context_epoch": context_epoch, + "reclaimed_turns": int(epoch_prefetch.get("reclaimed_turns") or 0), + "dropped_failures": int(epoch_prefetch.get("dropped_failures") or len(failure_facts)), + "failure_facts": failure_facts, + "open_obligations": open_obligations, + "source_ref": dict(source_ref) if isinstance(source_ref, Mapping) else None, + "baseline_bytes": baseline_bytes, + } + + +HostInputRenderer = Callable[[Mapping[str, Any]], str | None] +UNSET_HOST_INPUT_RENDERER: object = object() + + +def _render_codex_cli_host_input(request: Mapping[str, Any]) -> str: + from .codex_cli import _prompt + + return _prompt(request) + + +def _render_generic_cli_host_input(request: Mapping[str, Any]) -> str: + from .executor import serialize_generic_cli_host_input + + return serialize_generic_cli_host_input(request) + + +def _render_dsh_host_input(request: Mapping[str, Any]) -> str | None: + from .host_candidate import render_dsh_host_prompt + + return render_dsh_host_prompt(request) + + +def resolve_host_input_renderer(host: str | None) -> HostInputRenderer | None: + """Return the actual delivered host-input serializer for measurable hosts, or None.""" + normalized = (host or "").strip() + if normalized in {"codex", "codex-cli"}: + return _render_codex_cli_host_input + if normalized == "generic-cli": + return _render_generic_cli_host_input + if normalized == "dsh": + return _render_dsh_host_input + return None + + +def _safe_rendered_prompt( + request: Mapping[str, Any], + *, + renderer: HostInputRenderer | None = _render_codex_cli_host_input, +) -> str | None: + """Render the exact delivered host input when the host adapter is measurable.""" + if renderer is None: + return None + try: + return renderer(request) + except (ValueError, RuntimeError, TypeError, KeyError): + return None + + +_PROMPT_GATE_AUDIT_FIELDS = ( + "net_savings_tokens", + "cold_prefill_amortization_tokens", + "amortized_net_savings_tokens", + "min_net_savings_tokens", + "rendered_prompt_baseline_bytes", + "rendered_prompt_delivered_bytes", + "rendered_prompt_delta_bytes", + "rendered_prompt_baseline_tokens", + "rendered_prompt_delivered_tokens", + "rendered_prompt_delta_tokens", + "tokenizer", +) + +_DELIVERED_PROMPT_TELEMETRY_FIELDS = frozenset({ + "rendered_prompt_delivered_bytes", + "rendered_prompt_delta_bytes", + "rendered_prompt_delivered_tokens", + "rendered_prompt_delta_tokens", +}) + +_HOST_WIRE_EXCLUDED_PREFETCH_FIELDS = frozenset({ + "potential_bytes_saved", + "bytes_saved", + "net_savings_bytes", + "baseline_tokens", + "hydrated_tokens", + "baseline_tokens_verified", + *_PROMPT_GATE_AUDIT_FIELDS, +}) + + +def strip_internal_epoch_prefetch_audit_fields( + epoch_prefetch: Mapping[str, Any], +) -> dict[str, Any]: + """Strip internal prompt-gate audit telemetry before serializing host-wire payloads.""" + return { + key: value + for key, value in epoch_prefetch.items() + if key not in _HOST_WIRE_EXCLUDED_PREFETCH_FIELDS + } + + +def _apply_prompt_gate_audit_fields( + target: dict[str, Any], + adjudicated: Mapping[str, Any], + *, + include_delivered_metrics: bool = True, +) -> None: + for field in _PROMPT_GATE_AUDIT_FIELDS: + if not include_delivered_metrics and field in _DELIVERED_PROMPT_TELEMETRY_FIELDS: + continue + if field in adjudicated and adjudicated[field] is not None: + target[field] = adjudicated[field] + + +def _clear_delivered_prompt_telemetry(payload: dict[str, Any]) -> None: + for field in _DELIVERED_PROMPT_TELEMETRY_FIELDS: + payload.pop(field, None) + + +def _keep_raw_prefetch_payload( + request: Mapping[str, Any], + receipt: Mapping[str, Any], + *, + fallback_reason: str, + net_savings_bytes: int | None, + rendered_baseline_bytes: int | None, + rendered_delivered_bytes: int | None, + error_observation: str | None = None, + adjudicated: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + header_fields = receipt.get("header_fields") if isinstance(receipt.get("header_fields"), Mapping) else {} + facts = list(receipt.get("preserved_failure_facts") or header_fields.get("failure_facts") or ()) + obligations = list(receipt.get("preserved_open_obligations") or header_fields.get("open_obligations") or ()) + payload: dict[str, Any] = { + "schema_version": receipt["schema_version"], + "operator": "KeepRaw", + "status": "fallback_keep_raw", + "fallback_reason": fallback_reason, + "trust_level": receipt.get("trust_level", "tool"), + "context_epoch": receipt.get("context_epoch"), + "preserves_raw_state": True, + "preserved_failure_facts": facts, + "preserved_open_obligations": obligations, + "bytes_saved": 0, + "net_savings_bytes": net_savings_bytes if net_savings_bytes is not None else 0, + "round_trips_saved": 0, + "error_observation": error_observation or receipt.get("error_observation"), + } + if rendered_baseline_bytes is not None: + payload["rendered_prompt_baseline_bytes"] = rendered_baseline_bytes + if adjudicated is not None: + # Preserve threshold-gate audit fields and baseline metrics from adjudication, + # never rejected-candidate delivered measurements. + _apply_prompt_gate_audit_fields(payload, adjudicated, include_delivered_metrics=False) + if rendered_delivered_bytes is not None: + payload["rendered_prompt_delivered_bytes"] = rendered_delivered_bytes + if rendered_baseline_bytes is not None: + payload["rendered_prompt_delta_bytes"] = rendered_delivered_bytes - rendered_baseline_bytes + updated = dict(request) + updated["epoch_prefetch"] = payload + return updated + + +def _measure_and_finalize_keep_raw_payload( + request: Mapping[str, Any], + receipt: Mapping[str, Any], + *, + fallback_reason: str, + net_savings_bytes: int | None, + error_observation: str | None = None, + adjudicated: Mapping[str, Any] | None = None, + rendered_baseline_bytes: int | None = None, + rendered_baseline_tokens: int | None = None, + active_renderer: HostInputRenderer | None, + encoding_name: str, + token_counter: Callable[[str], int] | None, +) -> dict[str, Any]: + """Construct the KeepRaw request first, then measure its actual delivered host input.""" + baseline_bytes = rendered_baseline_bytes + baseline_tokens = rendered_baseline_tokens + if baseline_bytes is None and adjudicated is not None: + adj_bytes = adjudicated.get("rendered_prompt_baseline_bytes") + if isinstance(adj_bytes, int) and not isinstance(adj_bytes, bool): + baseline_bytes = adj_bytes + if baseline_tokens is None and adjudicated is not None: + adj_tokens = adjudicated.get("rendered_prompt_baseline_tokens") + if isinstance(adj_tokens, int) and not isinstance(adj_tokens, bool): + baseline_tokens = adj_tokens + + if active_renderer is not None and (baseline_bytes is None or baseline_tokens is None): + raw_prompt = _safe_rendered_prompt(request, renderer=active_renderer) + if raw_prompt is not None: + if baseline_bytes is None: + baseline_bytes = len(raw_prompt.encode("utf-8")) + if baseline_tokens is None: + raw_counted = count_verifiable_tokens( + raw_prompt, + encoding_name=encoding_name, + token_counter=token_counter, + ) + if raw_counted is not None: + baseline_tokens = raw_counted[0] + + updated_keep = _keep_raw_prefetch_payload( + request, + receipt, + fallback_reason=fallback_reason, + net_savings_bytes=net_savings_bytes, + rendered_baseline_bytes=baseline_bytes, + rendered_delivered_bytes=None, + error_observation=error_observation, + adjudicated=adjudicated, + ) + ep = updated_keep["epoch_prefetch"] + _clear_delivered_prompt_telemetry(ep) + if baseline_bytes is not None: + ep["rendered_prompt_baseline_bytes"] = baseline_bytes + if baseline_tokens is not None: + ep["rendered_prompt_baseline_tokens"] = baseline_tokens + + keep_prompt = _safe_rendered_prompt(updated_keep, renderer=active_renderer) + for _ in range(3): + if keep_prompt is None: + _clear_delivered_prompt_telemetry(ep) + return updated_keep + keep_bytes = len(keep_prompt.encode("utf-8")) + ep["rendered_prompt_delivered_bytes"] = keep_bytes + if baseline_bytes is not None: + ep["rendered_prompt_delta_bytes"] = keep_bytes - baseline_bytes + else: + ep.pop("rendered_prompt_delta_bytes", None) + keep_counted = count_verifiable_tokens( + keep_prompt, + encoding_name=encoding_name, + token_counter=token_counter, + ) + if keep_counted is not None: + keep_tokens, keep_tok_meta = keep_counted + ep["rendered_prompt_delivered_tokens"] = keep_tokens + if baseline_tokens is not None: + ep["rendered_prompt_delta_tokens"] = keep_tokens - baseline_tokens + else: + ep.pop("rendered_prompt_delta_tokens", None) + if "tokenizer" not in ep: + ep["tokenizer"] = keep_tok_meta + else: + ep.pop("rendered_prompt_delivered_tokens", None) + ep.pop("rendered_prompt_delta_tokens", None) + + stabilized_prompt = _safe_rendered_prompt(updated_keep, renderer=active_renderer) + if stabilized_prompt == keep_prompt: + return updated_keep + keep_prompt = stabilized_prompt + + _clear_delivered_prompt_telemetry(ep) + return updated_keep + + +def _external_verified_baseline( + receipt: Mapping[str, Any], + *, + encoding_name: str, + token_counter: Callable[[str], int] | None, +) -> tuple[int | None, int | None]: + raw_bytes = receipt.get("baseline_bytes") + fallback_bytes = ( + int(raw_bytes) if isinstance(raw_bytes, int) and not isinstance(raw_bytes, bool) else None + ) + measured = _measure_verified_source_ref_tokens( + receipt.get("source_ref") if isinstance(receipt.get("source_ref"), Mapping) else None, + encoding_name=encoding_name, + token_counter=token_counter, + ) + if measured is not None: + return measured[0], measured[1] + receipt_tokens = receipt.get("baseline_tokens") + receipt_tokenizer = receipt.get("tokenizer") + if ( + receipt.get("baseline_tokens_verified") is True + and isinstance(receipt_tokens, int) + and not isinstance(receipt_tokens, bool) + and isinstance(receipt_tokenizer, Mapping) + and receipt_tokenizer.get("encoding") == encoding_name + ): + return fallback_bytes, int(receipt_tokens) + return fallback_bytes, None + + +def _prompt_gate_policy( + epoch_prefetch: Mapping[str, Any] | None, + receipt: Mapping[str, Any], +) -> dict[str, Any] | None: + if isinstance(epoch_prefetch, Mapping): + return dict(epoch_prefetch) + policy: dict[str, Any] = {} + for key in ( + "min_net_savings_bytes", + "min_net_savings_tokens", + "cold_prefill_amortization_tokens", + "tokenizer_encoding", + ): + if key in receipt and receipt[key] is not None: + policy[key] = receipt[key] + return policy or None + + +def _resolve_active_host_renderer( + *, + host: str | None, + host_input_renderer: HostInputRenderer | None | object, +) -> HostInputRenderer | None: + if host_input_renderer is not UNSET_HOST_INPUT_RENDERER: + return cast(HostInputRenderer | None, host_input_renderer) + if host is not None: + return resolve_host_input_renderer(host) + return _render_codex_cli_host_input + + +def _adjudicate_candidate_prompt_gate( + *, + policy_cfg: Mapping[str, Any] | None, + encoding_name: str, + token_counter: Callable[[str], int] | None, + raw_prompt: str | None, + epoch_prompt: str | None, + has_inline_exploratory: bool, + replace_exploratory_context: bool, + ext_bytes: int | None, + ext_tokens: int | None, + potential_saved: int, + host_input_measurable: bool, +) -> tuple[dict[str, Any], int | None, int | None]: + before_bytes = len(raw_prompt.encode("utf-8")) if raw_prompt is not None else None + after_bytes = len(epoch_prompt.encode("utf-8")) if epoch_prompt is not None else None + before_counted = ( + count_verifiable_tokens(raw_prompt, encoding_name=encoding_name, token_counter=token_counter) + if host_input_measurable and raw_prompt is not None + else None + ) + after_counted = ( + count_verifiable_tokens(epoch_prompt, encoding_name=encoding_name, token_counter=token_counter) + if host_input_measurable and epoch_prompt is not None + else None + ) + tokenizer_meta = ( + before_counted[1] + if before_counted is not None and after_counted is not None + else None + ) + adjudicated = evaluate_epoch_prefetch_prompt_gate( + epoch_prefetch=policy_cfg, + has_inline_exploratory=has_inline_exploratory, + replace_exploratory_context=replace_exploratory_context, + host_input_measurable=host_input_measurable, + rendered_prompt_baseline_bytes=before_bytes, + rendered_prompt_delivered_bytes=after_bytes, + rendered_prompt_baseline_tokens=before_counted[0] if before_counted is not None else None, + rendered_prompt_delivered_tokens=after_counted[0] if after_counted is not None else None, + external_baseline_bytes=ext_bytes, + external_baseline_tokens=ext_tokens, + potential_bytes_saved=potential_saved, + tokenizer=tokenizer_meta, + ) + return adjudicated, before_bytes, after_bytes + + +def apply_turn_epoch_prefetch_to_request( + request: Mapping[str, Any], + receipt: Mapping[str, Any], + *, + replace_exploratory_context: bool = False, + epoch_prefetch: Mapping[str, Any] | None = None, + token_counter: Callable[[str], int] | None = None, + host: str | None = None, + host_input_renderer: HostInputRenderer | None | object = UNSET_HOST_INPUT_RENDERER, +) -> dict[str, Any]: + """Attach Stage-then-Swap observation onto a host request with host-accurate prompt token gating.""" + policy_cfg = _prompt_gate_policy(epoch_prefetch, receipt) + encoding_name = str((policy_cfg or {}).get("tokenizer_encoding") or DEFAULT_TOKENIZER_ENCODING) + active_renderer = _resolve_active_host_renderer( + host=host, + host_input_renderer=host_input_renderer, + ) + if receipt.get("operator") != "EpochReset": + return _measure_and_finalize_keep_raw_payload( + request, + receipt, + fallback_reason=str(receipt.get("fallback_reason") or "command_failed"), + net_savings_bytes=0, + active_renderer=active_renderer, + encoding_name=encoding_name, + token_counter=token_counter, + ) + + potential_saved = int(receipt.get("bytes_saved") or 0) + epoch_payload: dict[str, Any] = { + "schema_version": receipt["schema_version"], + "operator": "EpochReset", + "trust_level": receipt["trust_level"], + "context_epoch": receipt["context_epoch"], + "source_ref": receipt.get("source_ref"), + "header_fields": receipt.get("header_fields"), + "hydrated_text": receipt.get("hydrated_text"), + "potential_bytes_saved": potential_saved, + "bytes_saved": potential_saved, + "net_savings_bytes": receipt.get("net_savings_bytes"), + "round_trips_saved": receipt.get("round_trips_saved", 1), + "replayed": bool(receipt.get("replayed")), + } + candidate = dict(request) + candidate["epoch_prefetch"] = epoch_payload + has_inline_exploratory = "exploratory_context" in request + if replace_exploratory_context and has_inline_exploratory: + candidate["exploratory_context"] = { + "replaced_by_epoch_reset": True, + "source_ref": receipt.get("source_ref"), + } + + raw_prompt = _safe_rendered_prompt(request, renderer=active_renderer) + epoch_prompt = _safe_rendered_prompt(candidate, renderer=active_renderer) + ext_bytes, ext_tokens = ( + (None, None) + if has_inline_exploratory + else _external_verified_baseline(receipt, encoding_name=encoding_name, token_counter=token_counter) + ) + host_input_measurable = ( + active_renderer is not None + and raw_prompt is not None + and epoch_prompt is not None + and not ( + not has_inline_exploratory + and bool(receipt.get("hydrated_text")) + and epoch_prompt == raw_prompt + ) + ) + + adjudicated: dict[str, Any] | None = None + before_bytes: int | None = None + after_bytes: int | None = None + for _ in range(2): + adjudicated, before_bytes, after_bytes = _adjudicate_candidate_prompt_gate( + policy_cfg=policy_cfg, + encoding_name=encoding_name, + token_counter=token_counter, + raw_prompt=raw_prompt, + epoch_prompt=epoch_prompt, + has_inline_exploratory=has_inline_exploratory, + replace_exploratory_context=replace_exploratory_context, + ext_bytes=ext_bytes, + ext_tokens=ext_tokens, + potential_saved=potential_saved, + host_input_measurable=host_input_measurable, + ) + if adjudicated.get("operator") != "EpochReset": + return _measure_and_finalize_keep_raw_payload( + request, + receipt, + fallback_reason=str(adjudicated.get("fallback_reason") or "negative_net_savings"), + net_savings_bytes=int(adjudicated.get("net_savings_bytes") or 0), + error_observation=str(adjudicated.get("error_observation") or ""), + adjudicated=adjudicated, + rendered_baseline_bytes=before_bytes, + active_renderer=active_renderer, + encoding_name=encoding_name, + token_counter=token_counter, + ) + epoch_payload["bytes_saved"] = adjudicated["bytes_saved"] + epoch_payload["net_savings_bytes"] = adjudicated["net_savings_bytes"] + final_prompt = _safe_rendered_prompt(candidate, renderer=active_renderer) + if final_prompt is None: + host_input_measurable = False + epoch_prompt = None + continue + if final_prompt == epoch_prompt: + _apply_prompt_gate_audit_fields(epoch_payload, adjudicated) + return candidate + epoch_prompt = final_prompt + + # Fail closed if rendered host output did not stabilize after updating bytes_saved. + fallback_adj, before_bytes, _after_bytes = _adjudicate_candidate_prompt_gate( + policy_cfg=policy_cfg, + encoding_name=encoding_name, + token_counter=token_counter, + raw_prompt=raw_prompt, + epoch_prompt=epoch_prompt, + has_inline_exploratory=has_inline_exploratory, + replace_exploratory_context=replace_exploratory_context, + ext_bytes=ext_bytes, + ext_tokens=ext_tokens, + potential_saved=potential_saved, + host_input_measurable=False, + ) + return _measure_and_finalize_keep_raw_payload( + request, + receipt, + fallback_reason=str(fallback_adj.get("fallback_reason") or "host_input_unmeasurable"), + net_savings_bytes=int(fallback_adj.get("net_savings_bytes") or 0), + error_observation=str(fallback_adj.get("error_observation") or ""), + adjudicated=fallback_adj, + rendered_baseline_bytes=before_bytes, + active_renderer=active_renderer, + encoding_name=encoding_name, + token_counter=token_counter, + ) + + +def prepare_turn_epoch_context( + *, + plan: Mapping[str, Any], + request: Mapping[str, Any], + journal_path: Path, + goal_id: str, + agent_id: str, + turn_key: str, + project: Path, + epoch_prefetch: Mapping[str, Any] | None = None, + quiet_turn: bool | Mapping[str, Any] = False, + decision_capture_payload: Mapping[str, Any] | None = None, + existing_journal: Mapping[str, Any] | None = None, + capture: Any = None, + allow_execute: bool = True, + host: str | None = None, + host_input_renderer: HostInputRenderer | None | object = UNSET_HOST_INPUT_RENDERER, +) -> tuple[dict[str, Any] | None, dict[str, Any] | None, dict[str, Any]]: + """Evaluate default-off Quiet-Turn & Stage-then-Swap EpochReset state for a Turn.""" + goal_state_root = journal_path.parent.parent + sqlite_path = goal_state_root / "turn_prefetch_state.sqlite" + effective_host = ( + host + if host is not None + else ( + str(plan["host"].get("kind") or "") + if isinstance(plan.get("host"), Mapping) + else "" + ) + ) + + effective_epoch_prefetch = ( + dict(epoch_prefetch) + if isinstance(epoch_prefetch, Mapping) + else dict(decision_capture_payload["epoch_prefetch"]) + if isinstance(decision_capture_payload, Mapping) + and isinstance(decision_capture_payload.get("epoch_prefetch"), Mapping) + else None + ) + effective_quiet = ( + quiet_turn + if quiet_turn + else decision_capture_payload.get("quiet_turn") + if isinstance(decision_capture_payload, Mapping) + else False + ) + + quiet_meta: dict[str, Any] | None = None + if not allow_execute and isinstance(existing_journal, Mapping) and isinstance(existing_journal.get("quiet_turn"), Mapping): + quiet_meta = dict(existing_journal["quiet_turn"]) + elif effective_quiet is True or ( + isinstance(effective_quiet, Mapping) and effective_quiet.get("enabled") is True + ): + target = _quiet_turn_target_params( + plan=plan, + goal_id=goal_id, + agent_id=agent_id, + goal_state_root=goal_state_root, + effective_quiet=effective_quiet, + ) + # Never commit digest before Turn settlement succeeds; inspect read-only here. + quiet_meta = resolve_quiet_turn_metadata( + scope_key=target.scope_key, + file_path=target.file_path, + sqlite_path=target.sqlite_path, + enabled=True, + quiet_noop_allowed=target.quiet_noop_allowed, + must_attempt=target.must_attempt, + state_changed=target.state_changed, + current_state_digest=target.state_digest, + record_if_changed=False, + work_contract=target.work_contract, + turn_envelope=target.turn_envelope, + ) + + prefetch_receipt: dict[str, Any] | None = None + updated_request = dict(request) + existing_inline = ( + existing_journal.get("epoch_prefetch") + if isinstance(existing_journal, Mapping) + else None + ) + if not allow_execute: + if isinstance(existing_inline, Mapping): + prefetch_receipt = { + **dict(existing_inline), + "replayed": True, + "executed": False, + } + elif isinstance(effective_epoch_prefetch, Mapping) and effective_epoch_prefetch.get("enabled") is True: + inputs = _turn_epoch_inputs( + plan=plan, + request=updated_request, + epoch_prefetch=effective_epoch_prefetch, + capture=capture, + ) + prefetch_receipt = resolve_or_execute_epoch_prefetch( + epoch_prefetch=effective_epoch_prefetch, + scope_key=f"turn_driver:{goal_id}:{turn_key}", + context_epoch=inputs["context_epoch"], + file_store_dir=goal_state_root / "turn_prefetch", + sqlite_path=sqlite_path, + reclaimed_turns=inputs["reclaimed_turns"], + dropped_failures=inputs["dropped_failures"], + failure_facts=inputs["failure_facts"], + open_obligations=inputs["open_obligations"], + source_ref=inputs["source_ref"], + baseline_bytes=inputs["baseline_bytes"], + cwd=effective_epoch_prefetch.get("cwd") or project, + existing_inline_record=None, + allow_execute=False, + ) + return prefetch_receipt, quiet_meta, updated_request + + if ( + isinstance(effective_epoch_prefetch, Mapping) + and effective_epoch_prefetch.get("enabled") is True + and not (quiet_meta and quiet_meta.get("skipped")) + ): + inputs = _turn_epoch_inputs( + plan=plan, + request=updated_request, + epoch_prefetch=effective_epoch_prefetch, + capture=capture, + ) + prefetch_receipt = resolve_or_execute_epoch_prefetch( + epoch_prefetch=effective_epoch_prefetch, + scope_key=f"turn_driver:{goal_id}:{turn_key}", + context_epoch=inputs["context_epoch"], + file_store_dir=goal_state_root / "turn_prefetch", + sqlite_path=sqlite_path, + reclaimed_turns=inputs["reclaimed_turns"], + dropped_failures=inputs["dropped_failures"], + failure_facts=inputs["failure_facts"], + open_obligations=inputs["open_obligations"], + source_ref=inputs["source_ref"], + baseline_bytes=inputs["baseline_bytes"], + cwd=effective_epoch_prefetch.get("cwd") or project, + existing_inline_record=existing_inline, + allow_execute=True, + ) + if prefetch_receipt is not None: + updated_request = apply_turn_epoch_prefetch_to_request( + updated_request, + prefetch_receipt, + replace_exploratory_context=bool( + effective_epoch_prefetch.get("replace_exploratory_context") + ), + epoch_prefetch=effective_epoch_prefetch, + host=effective_host, + host_input_renderer=host_input_renderer, + ) + adjudicated = updated_request.get("epoch_prefetch") + if isinstance(adjudicated, Mapping): + prefetch_receipt = dict(prefetch_receipt) + for field in ( + "operator", + "status", + "fallback_reason", + "preserves_raw_state", + "bytes_saved", + "net_savings_bytes", + "potential_bytes_saved", + "round_trips_saved", + "error_observation", + *_PROMPT_GATE_AUDIT_FIELDS, + ): + if field in adjudicated: + prefetch_receipt[field] = adjudicated[field] + elif field in _PROMPT_GATE_AUDIT_FIELDS: + prefetch_receipt.pop(field, None) + return prefetch_receipt, quiet_meta, updated_request + + +def attach_turn_replay_epoch_metadata( + payload: dict[str, Any], + *, + plan: Mapping[str, Any], + request: Mapping[str, Any], + journal_path: Path, + goal_id: str, + agent_id: str, + turn_key: str, + project: Path, + options: Mapping[str, Any], + existing_journal: Mapping[str, Any], +) -> dict[str, Any]: + """Attach persisted Stage-then-Swap EpochReset and Quiet-Turn metadata on replay.""" + replay_prefetch, replay_quiet, _ = prepare_turn_epoch_context( + plan=plan, + request=request, + journal_path=journal_path, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + project=project, + epoch_prefetch=options.get("epoch_prefetch"), + quiet_turn=options.get("quiet_turn", False), + decision_capture_payload=options.get("decision_capture_payload"), + existing_journal=existing_journal, + allow_execute=False, + host=options.get("host"), + host_input_renderer=options.get("host_input_renderer", UNSET_HOST_INPUT_RENDERER), + ) + if replay_prefetch is not None: + payload["epoch_prefetch"] = replay_prefetch + if replay_quiet is not None: + payload["quiet_turn"] = replay_quiet + return payload + + +def prepare_turn_execution_epoch_context( + *, + plan: Mapping[str, Any], + request: Mapping[str, Any], + journal_path: Path, + goal_id: str, + turn_key: str, + project: Path, + settlement_lineage: Mapping[str, Any] | None, + options: Mapping[str, Any], + existing_journal: Mapping[str, Any] | None, + capture: Any, + needs_host: bool = True, +) -> tuple[dict[str, Any], dict[str, Any]]: + """Prepare opt-in Stage-then-Swap prefetch & Quiet-Turn state before Turn launch.""" + epoch_prefetch = options.get("epoch_prefetch") + quiet_turn = options.get("quiet_turn", False) + decision_capture_payload = options.get("decision_capture_payload") + epoch_opted_in = _is_turn_option_enabled( + epoch_prefetch, decision_capture_payload, "epoch_prefetch", + ) + 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): + return {}, dict(request) + + allow_execute = bool( + needs_host + and not ( + isinstance(existing_journal, Mapping) + and isinstance(existing_journal.get("epoch_prefetch"), Mapping) + ) + ) + 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 + + +def attach_epoch_metadata_to_journal( + journal: dict[str, Any], + epoch_metadata: Mapping[str, Any] | None, +) -> None: + """Persist Stage-then-Swap prefetch & Quiet-Turn metadata into a Turn journal.""" + if not epoch_metadata: + return + prefetch_receipt = epoch_metadata.get("epoch_prefetch") + quiet_meta = epoch_metadata.get("quiet_turn") + if isinstance(prefetch_receipt, Mapping) and "epoch_prefetch" not in journal: + journal["epoch_prefetch"] = dict(prefetch_receipt) + if isinstance(quiet_meta, Mapping): + journal["quiet_turn"] = dict(quiet_meta) + + +def reset_failed_turn_journal_with_epoch_metadata( + journal: dict[str, Any], + *, + validation_reinvokes_host: bool, + completed_prefix: list[str], + epoch_metadata: Mapping[str, Any], +) -> None: + """Reset failed phase fields in-place when retrying an existing Turn journal.""" + receipt = journal.get("receipt") if isinstance(journal.get("receipt"), dict) else {} + if receipt.get("failed_phase") == "validation": + if validation_reinvokes_host: + journal.pop("host_result", None) + journal.pop("result_kind", None) + journal["completed_phases"] = ( + list(completed_prefix) if isinstance(journal.get("host_result"), dict) else [] + ) + journal.pop("task_validation", None) + journal.pop("validation_stage", None) + for key in ("reason", "receipt", "host_recovery", "host_failure"): + journal.pop(key, None) + journal["status"] = "in_progress" + attach_epoch_metadata_to_journal(journal, epoch_metadata) + + +def resolve_codex_context_epoch_prefetch_hook( + *, + directory: str, + hook_name: str, + state: Mapping[str, Any], + event: Mapping[str, Any], + recovery: Mapping[str, Any], + lock_ctx: Callable[[str], Any], + read_state_fn: Callable[[Path], dict[str, Any]], + save_state_fn: Callable[[Path, dict[str, Any]], None], + continuation_text: str, + raw_guidance_text: str, +) -> dict[str, Any] | None: + """Resolve Stage-then-Swap EpochReset or KeepRaw output for SessionStart hooks.""" + cfg = ( + event.get("epoch_prefetch") + if isinstance(event.get("epoch_prefetch"), Mapping) + else state.get("epoch_prefetch_policy") + if isinstance(state.get("epoch_prefetch_policy"), Mapping) + else None + ) + if not (isinstance(cfg, Mapping) and cfg.get("enabled") is True): + return None + source_ref = ( + {"path": str(recovery["path"]), "sha256": str(recovery["sha256"])} + if isinstance(recovery.get("path"), str) and isinstance(recovery.get("sha256"), str) + else None + ) + baseline_bytes = cfg.get("baseline_bytes") + if baseline_bytes is None and source_ref is not None: + try: + baseline_bytes = Path(source_ref["path"]).stat().st_size + except OSError: + baseline_bytes = None + goal_label = str(state.get("goal_id") or event.get("goal_id") or "default") + agent_label = str(state.get("agent_id") or event.get("agent_id") or "default") + context_epoch = str(state.get("context_epoch") or "epoch-0") + with lock_ctx(directory) as root: + current_state = read_state_fn(root) + receipt = resolve_or_execute_epoch_prefetch( + epoch_prefetch=cfg, + scope_key=f"codex_context:{goal_label}:{agent_label}", + context_epoch=context_epoch, + file_store_dir=root / "epoch_prefetch", + sqlite_path=root / "epoch_prefetch.sqlite", + reclaimed_turns=int(event.get("reclaimed_turns") or cfg.get("reclaimed_turns") or 0), + dropped_failures=int(event.get("dropped_failures") or cfg.get("dropped_failures") or 0), + failure_facts=list(event.get("failure_facts") or cfg.get("failure_facts") or ()), + open_obligations=list(event.get("open_obligations") or cfg.get("open_obligations") or ()), + source_ref=source_ref, + baseline_bytes=baseline_bytes, + cwd=event.get("cwd"), + existing_inline_record=current_state.get("epoch_prefetch"), + require_token_gate=True, + ) + if receipt is not None: + current_state["epoch_prefetch"] = receipt + save_state_fn(root, current_state) + if receipt is None: + return None + epoch_meta = { + "schema_version": receipt["schema_version"], + "operator": receipt["operator"], + "status": receipt["status"], + "fallback_reason": receipt.get("fallback_reason"), + "trust_level": receipt["trust_level"], + "context_epoch": receipt["context_epoch"], + "replayed": receipt["replayed"], + "executed": receipt["executed"], + "round_trips_saved": receipt["round_trips_saved"], + "bytes_saved": receipt["bytes_saved"], + "receipt_sha256": receipt["receipt_sha256"], + } + if receipt["operator"] == "EpochReset" and isinstance(receipt.get("hydrated_text"), str): + additional_context = ( + "LoopX model-context baseline swapped via Stage-then-Swap EpochReset " + f"(trust={receipt['trust_level']}).\n" + + receipt["hydrated_text"] + + "\nOriginal saved capture remains available at: " + + continuation_text + ) + else: + facts = json.dumps(receipt.get("preserved_failure_facts", []), ensure_ascii=False) + obligations = json.dumps(receipt.get("preserved_open_obligations", []), ensure_ascii=False) + additional_context = ( + "LoopX model-context baseline invalidated. Saved files remain available. " + + continuation_text + + raw_guidance_text + + f"\nPreserved failure facts: {facts}" + + f"\nPreserved open obligations: {obligations}" + + f"\nPrefetch fallback notice (KeepRaw): {receipt.get('error_observation')}" + ) + return { + "hookSpecificOutput": { + "hookEventName": hook_name, + "additionalContext": additional_context, + "epochPrefetch": epoch_meta, + } + } diff --git a/loopx/control_plane/turn_driver/execution_readback.py b/loopx/control_plane/turn_driver/execution_readback.py index f5439fd1c0..055abd6cd2 100644 --- a/loopx/control_plane/turn_driver/execution_readback.py +++ b/loopx/control_plane/turn_driver/execution_readback.py @@ -75,6 +75,10 @@ def execution_payload( "effects": dict(effects), **({"admission": dict(journal["admission"])} if isinstance(journal.get("admission"), Mapping) else {}), + **({"epoch_prefetch": dict(journal["epoch_prefetch"])} + if isinstance(journal.get("epoch_prefetch"), Mapping) else {}), + **({"quiet_turn": dict(journal["quiet_turn"])} + if isinstance(journal.get("quiet_turn"), Mapping) else {}), "quota_slot_spend_count": 1 if quota_spent else 0, **( {"settlement_result": journal["settlement_result"]} diff --git a/loopx/control_plane/turn_driver/executor.py b/loopx/control_plane/turn_driver/executor.py index b7b4ce0806..a8bbd0e4b5 100644 --- a/loopx/control_plane/turn_driver/executor.py +++ b/loopx/control_plane/turn_driver/executor.py @@ -48,6 +48,23 @@ selected_turn_todo, turn_host_lineage, ) from .decision_capture import stage_turn_decision_capture +from .epoch_prefetch import ( + HostInputRenderer, + UNSET_HOST_INPUT_RENDERER, + attach_epoch_metadata_to_journal, + attach_turn_replay_epoch_metadata, + prepare_turn_execution_epoch_context, + reset_failed_turn_journal_with_epoch_metadata, + strip_internal_epoch_prefetch_audit_fields, +) +from .quiet_turn_store import ( + assert_no_conflicting_quiet_turn_skip, + commit_turn_quiet_state_after_success, + effective_turn_agent_id, + maybe_skip_quiet_turn_before_admission, + resolve_quiet_wait_or_replay_before_admission, + resolve_turn_request_or_quiet_wait, +) from .execution_readback import execution_payload from .host_process_transport import run_host_process from .host_binding import ( @@ -877,6 +894,17 @@ def _host_failure( } +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"]), + } + return json.dumps(host_input, ensure_ascii=False, separators=(",", ":")) + + def _run_host( request: Mapping[str, Any], *, @@ -888,9 +916,6 @@ def _run_host( # Dispatch has checked the source and its internal effect adapter before # journal/cadence admission. External stdin gets the same single complete # input as native model prompts, not another executable authority carrier. - from ..quota.turn_envelope import captured_turn_host_input - - host_input = captured_turn_host_input(request) if "work_contract" in request else request stdout: list[str] = [] stderr_chars = 0 @@ -902,7 +927,7 @@ def count_stderr(text: str) -> None: observed = run_host_process( argv, project=project, - input_text=json.dumps(host_input, ensure_ascii=False, separators=(",", ":")), + input_text=serialize_generic_cli_host_input(request), timeout_seconds=timeout_seconds, stdout_limit_bytes=HOST_RESULT_MAX_BYTES, on_stdout=stdout.append, @@ -1621,6 +1646,9 @@ def run_loopx_turn_once( confirm_start: Callable[[], None] | None = None, goal_admission: FirstPartyHostGoalAdmission | None = None, host_launch_guard: Callable[[], AbstractContextManager[None]] | None = None, + epoch_prefetch: Mapping[str, Any] | None = None, + quiet_turn: bool | Mapping[str, Any] = False, + 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, @@ -1630,7 +1658,20 @@ def run_loopx_turn_once( plan.get("transaction") if isinstance(plan.get("transaction"), dict) else {} ) settlement_lineage = _ensure_turn_settlement_plan(plan, transaction_plan) - request = build_loopx_turn_host_request(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, + "host": "generic-cli" if argv is not None else str(planned_host.get("kind") or ""), + "host_input_renderer": host_input_renderer, + } + request, turn_key = resolve_turn_request_or_quiet_wait( + plan=plan, transaction_plan=transaction_plan, execute=execute, + runtime_root=runtime_root, goal_id=goal_id, quiet_turn=quiet_turn, + decision_capture_payload=decision_capture_payload, + journal_path_fn=turn_journal_path, request_builder=build_loopx_turn_host_request, + ) empty_effects = { "host_invoked": False, "state_written": False, @@ -1666,7 +1707,6 @@ def run_loopx_turn_once( "executing run-once requires writeback, spend, and scheduler callbacks" ) - turn_key = str(request["turn_key"]) journal_path = turn_journal_path(runtime_root, goal_id=goal_id, turn_key=turn_key) def persist_journal(snapshot: Mapping[str, Any]) -> None: @@ -1720,15 +1760,12 @@ def persist_source_journal(source_admission: Mapping[str, Any]) -> None: # Recovery uses the recorded source through Host dispatch, # cached-result validation and settlement. plan, request = recorded_plan, build_loopx_turn_host_request(recorded_plan) - if settlement_lineage is not None: - agent_id = settlement_lineage["agent_id"] - else: - envelope = ( - plan.get("turn_envelope") - if isinstance(plan.get("turn_envelope"), Mapping) - else {} - ) - agent_id = str(envelope.get("agent_id") or "") + elif request is None: + request = build_loopx_turn_host_request(plan) + agent_id = effective_turn_agent_id(plan, settlement_lineage) + assert_no_conflicting_quiet_turn_skip( + journal_path=journal_path, goal_id=goal_id, agent_id=agent_id, turn_key=turn_key, + ) assessment = assess_existing_turn_recovery( journal, request, @@ -1741,25 +1778,34 @@ def persist_source_journal(source_admission: Mapping[str, Any]) -> None: recovery_decision = assessment.decision action = recovery_decision.get("action") if action == "return_existing": - payload = execution_payload( - plan, - journal, - execute=True, - replayed=True, - effects=empty_effects, + payload = attach_turn_replay_epoch_metadata( + execution_payload( + plan, journal, execute=True, replayed=True, effects=empty_effects, + ), + plan=plan, request=request, journal_path=journal_path, + goal_id=goal_id, agent_id=agent_id, turn_key=turn_key, project=project, + options=quiet_options, existing_journal=journal, ) payload.update(recover_post_settlement( plan=plan, post_settlement=post_settlement, journal=journal, )) payload["recovery"] = build_turn_recovery_audit( - recovery_decision, - journal, - status="finished", - host_invoked=False, + recovery_decision, journal, status="finished", host_invoked=False, ) return payload request = require_turn_recovery_continuation(assessment) + else: + quiet_early, request = resolve_quiet_wait_or_replay_before_admission( + plan=plan, request=request, journal_path=journal_path, + goal_id=goal_id, turn_key=turn_key, settlement_lineage=settlement_lineage, + host_projection=host_projection, empty_effects=empty_effects, + needs_host=needs_host, goal_admission=goal_admission, options=quiet_options, + payload_builder=execution_payload, request_builder=build_loopx_turn_host_request, + ) + if quiet_early is not None: + return quiet_early + assert request is not None if needs_host and goal_admission is not None: goal_admission.require_current() if (reason := _turn_transport_refusal( @@ -1771,6 +1817,12 @@ def persist_source_journal(source_admission: Mapping[str, Any]) -> None: plan, {"status": "unavailable", "host": host_projection, "reason": reason}, execute=True, replayed=False, effects=empty_effects, ) + if journal is None and needs_host and (quiet_skip_payload := maybe_skip_quiet_turn_before_admission( + plan=plan, journal_path=journal_path, goal_id=goal_id, turn_key=turn_key, + settlement_lineage=settlement_lineage, host_projection=host_projection, + empty_effects=empty_effects, payload_builder=execution_payload, options=quiet_options, + )) is not None: + return quiet_skip_payload capture = stage_turn_decision_capture( journal["plan"] if journal is not None else plan, journal_path=journal_path, decision=decision_capture_payload, existing_journal=journal is not None, @@ -1811,37 +1863,26 @@ 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, + ) 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, + recovery_decision, journal, status="started", host_invoked=None, ) persist_journal(journal) if journal and journal.get("status") == "failed": - receipt = ( - journal.get("receipt") - if isinstance(journal.get("receipt"), dict) - else {} + reset_failed_turn_journal_with_epoch_metadata( + journal, + validation_reinvokes_host=validation_reinvokes_host, + completed_prefix=list(TRANSACTION_PHASES[:2]), + epoch_metadata=epoch_metadata, ) - if receipt.get("failed_phase") == "validation": - if validation_reinvokes_host: - journal.pop("host_result", None) - journal.pop("result_kind", None) - journal["completed_phases"] = ( - list(TRANSACTION_PHASES[:2]) - if isinstance(journal.get("host_result"), dict) - else [] - ) - journal.pop("task_validation", None) - journal.pop("validation_stage", None) - journal.pop("reason", None) - journal.pop("receipt", None) - journal.pop("host_recovery", None) - journal.pop("host_failure", None) - journal["status"] = "in_progress" persist_journal(journal) reserved_start = admission is not None and admission.get("reserved") is True if journal is None or reserved_start: @@ -1855,6 +1896,7 @@ def persist_source_journal(source_admission: Mapping[str, Any]) -> None: "host_attempt_count": 0, "plan": dict(plan), } + attach_epoch_metadata_to_journal(journal, epoch_metadata) if reserved_start: journal["admission"] = admission # The accepted reservation belongs to the initial snapshot. Keep @@ -1949,4 +1991,9 @@ def finish_recovery(payload: dict[str, Any]) -> dict[str, Any]: else None ), ) + commit_turn_quiet_state_after_success( + settled=settled, epoch_metadata=epoch_metadata, plan=plan, + journal_path=journal_path, goal_id=goal_id, + settlement_lineage=settlement_lineage, options=quiet_options, + ) 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 dccadcb2cb..21eb004f7b 100644 --- a/loopx/control_plane/turn_driver/host_candidate.py +++ b/loopx/control_plane/turn_driver/host_candidate.py @@ -314,6 +314,13 @@ def goal_acceptance_prompt_instruction(authority: Mapping[str, Any]) -> str: return GOAL_ACCEPTANCE_READ_RULE if authority.get("vision_continuation_audit") else "" +def render_dsh_host_prompt(request: Mapping[str, Any]) -> str | None: + """Render the exact prompt delivered by run_dsh_host when measurable pre-launch.""" + if "work_contract" not in request: + return None + return render_prompt(extract_turn_authority(request)) + + def render_prompt(authority: Mapping[str, Any], *, allow_completion: bool = False) -> str: """Wrap one signed Turn authority packet in a typed JSON result request. @@ -322,6 +329,15 @@ 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 + + model_input = { + **dict(model_input), + "epoch_prefetch": strip_internal_epoch_prefetch_audit_fields( + model_input["epoch_prefetch"] + ), + } authority_json = json.dumps( model_input if model_input is not None else dict(authority), ensure_ascii=False, diff --git a/loopx/control_plane/turn_driver/quiet_turn_store.py b/loopx/control_plane/turn_driver/quiet_turn_store.py new file mode 100644 index 0000000000..19c0f82ff8 --- /dev/null +++ b/loopx/control_plane/turn_driver/quiet_turn_store.py @@ -0,0 +1,1161 @@ +"""Durable File + SQLite Quiet-Turn state, skip receipts, and pre-host guards. + +Work-contract and Quiet-Turn skip semantics remain TypeScript-owned +(`quota/stage_then_swap.ts` via `quota/turn_envelope.py`). This module owns +once-only File + SQLite persistence, crash-healing, and terminal skip replay. +""" +from __future__ import annotations + +from collections.abc import Callable, Mapping +from contextlib import closing +from dataclasses import dataclass +from datetime import UTC, datetime +import hashlib +import json +import os +from pathlib import Path +import sqlite3 +from typing import Any + +from ...file_lock import exclusive_file_lock +from ..quota.turn_envelope import compute_quiet_turn_state_digest, evaluate_quiet_turn +from .journal_store import TURN_KEY_RE + +QUIET_TURN_STATE_SCHEMA_VERSION = "loopx_quiet_turn_state_v0" +QUIET_TURN_SKIP_SCHEMA_VERSION = "loopx_quiet_turn_skip_receipt_v0" + + +def now_iso() -> str: + return datetime.now(UTC).isoformat().replace("+00:00", "Z") + + +def sha256_text(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def atomic_write_json(path: Path, payload: Mapping[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + raw = ( + json.dumps(dict(payload), ensure_ascii=False, sort_keys=True, indent=2) + + "\n" + ).encode("utf-8") + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + try: + with os.fdopen(descriptor, "wb") as stream: + stream.write(raw) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + + +def init_turn_prefetch_sqlite_db(connection: sqlite3.Connection) -> None: + """Initialize shared Stage-then-Swap EpochReset & Quiet-Turn SQLite schema.""" + connection.execute("PRAGMA busy_timeout = 5000") + connection.execute("PRAGMA journal_mode = WAL") + connection.execute("PRAGMA synchronous = FULL") + connection.execute( + """ + CREATE TABLE IF NOT EXISTS epoch_prefetch_records ( + scope_key TEXT NOT NULL, + context_epoch TEXT NOT NULL, + command_sha256 TEXT NOT NULL, + source_sha256 TEXT NOT NULL, + receipt_sha256 TEXT NOT NULL, + operator TEXT NOT NULL, + record_json TEXT NOT NULL, + created_at TEXT NOT NULL, + PRIMARY KEY (scope_key, context_epoch, command_sha256, source_sha256) + ) + """ + ) + connection.execute( + """ + CREATE TABLE IF NOT EXISTS quiet_turn_state ( + scope_key TEXT PRIMARY KEY, + state_digest TEXT NOT NULL, + metadata_json TEXT NOT NULL, + updated_at TEXT NOT NULL + ) + """ + ) + connection.execute( + """ + CREATE TABLE IF NOT EXISTS quiet_turn_skips ( + turn_key TEXT PRIMARY KEY, + scope_key TEXT NOT NULL, + state_digest TEXT, + receipt_json TEXT NOT NULL, + recorded_at TEXT NOT NULL + ) + """ + ) + + +def is_turn_option_enabled( + explicit: Any, + decision_capture_payload: Mapping[str, Any] | None, + key: str, + *, + allow_bool_true: bool = False, +) -> bool: + if (allow_bool_true and explicit is True) or ( + isinstance(explicit, Mapping) and explicit.get("enabled") is True + ): + return True + if not isinstance(decision_capture_payload, Mapping): + return False + captured = decision_capture_payload.get(key) + return (allow_bool_true and captured is True) or ( + isinstance(captured, Mapping) and captured.get("enabled") is True + ) + + +def effective_turn_agent_id( + plan: Mapping[str, Any], settlement_lineage: Mapping[str, Any] | None, +) -> str: + if settlement_lineage is not None: + return str(settlement_lineage["agent_id"]) + raw_contract = plan.get("work_contract") + raw_envelope = plan.get("turn_envelope") + container: Any = ( + (raw_contract if isinstance(raw_contract, Mapping) else {}).get("agent_identity", {}) + if plan.get("schema_version") == "loopx_turn_plan_v1" + else (raw_envelope if isinstance(raw_envelope, Mapping) else {}) + ) + return str(container.get("agent_id") or "") if isinstance(container, Mapping) else "" + + +def _resolve_effective_quiet( + quiet_turn: Any, decision_capture_payload: Mapping[str, Any] | None, +) -> Any: + if quiet_turn: + return quiet_turn + if isinstance(decision_capture_payload, Mapping): + return decision_capture_payload.get("quiet_turn") + return False + + +@dataclass(frozen=True) +class QuietTurnTarget: + scope_key: str + file_path: Path + sqlite_path: Path + config: dict[str, Any] + quiet_noop_allowed: bool + must_attempt: bool + state_changed: Any + state_digest: str + work_contract: dict[str, Any] | None + turn_envelope: dict[str, Any] | None + + +def _compact_contract_slice(contract: Any) -> dict[str, Any] | None: + if not isinstance(contract, Mapping): + return None + compact: dict[str, Any] = {} + for flag in ("must_attempt", "quiet_noop_allowed"): + if flag in contract: + compact[flag] = contract[flag] + interaction = contract.get("interaction_contract") + if isinstance(interaction, Mapping): + agent_channel = interaction.get("agent_channel") + if isinstance(agent_channel, Mapping): + compact["interaction_contract"] = { + "agent_channel": { + key: agent_channel[key] + for key in ("must_attempt", "quiet_noop_allowed", "delivery_allowed") + if key in agent_channel + } + } + action = contract.get("action") + if isinstance(action, Mapping): + compact_action = { + key: action[key] + for key in ("must_attempt", "quiet_noop_allowed", "effective_action") + if key in action + } + if compact_action: + compact["action"] = compact_action + decision = contract.get("decision") + if isinstance(decision, Mapping): + compact_decision = _compact_contract_slice(decision) + if compact_decision: + compact["decision"] = compact_decision + return compact + + +def _plan_quiet_contract_inputs( + plan: Mapping[str, Any], +) -> tuple[dict[str, Any] | None, dict[str, Any] | None]: + work_contract_slice = _compact_contract_slice(plan.get("work_contract")) + turn_envelope_slice = _compact_contract_slice(plan.get("turn_envelope")) + if work_contract_slice is None and turn_envelope_slice is None: + # Fail closed via TS resolvePlanQuietNoopEligibility when both contracts are absent. + return {}, None + return work_contract_slice, turn_envelope_slice + + +def _hook_quiet_contract_inputs( + *, + event: Mapping[str, Any], + state: Mapping[str, Any], + qt_cfg: Mapping[str, Any], +) -> tuple[dict[str, Any] | None, dict[str, Any] | None, bool, bool]: + raw_work = event.get("work_contract") if "work_contract" in event else state.get("work_contract") + raw_env = event.get("turn_envelope") if "turn_envelope" in event else state.get("turn_envelope") + work_contract_slice = _compact_contract_slice(raw_work) + turn_envelope_slice = _compact_contract_slice(raw_env) + must_attempt_opt = qt_cfg.get("must_attempt") is True + raw_quiet = qt_cfg.get("quiet_noop_allowed", True) + quiet_cap = raw_quiet if isinstance(raw_quiet, bool) else bool(raw_quiet) + return work_contract_slice, turn_envelope_slice, must_attempt_opt, quiet_cap + + +def build_cli_quiet_turn_option( + plan: Mapping[str, Any], + *, + goal_id: str, + agent_id: str, +) -> dict[str, Any]: + """Build structured Quiet-Turn opt-in config from the authoritative Turn plan.""" + authoritative = compute_quiet_turn_state_digest( + goal_id=goal_id, + agent_id=agent_id, + route=plan.get("route") if isinstance(plan.get("route"), Mapping) else None, + work_contract=( + plan.get("work_contract") if isinstance(plan.get("work_contract"), Mapping) else None + ), + turn_envelope=( + plan.get("turn_envelope") if isinstance(plan.get("turn_envelope"), Mapping) else None + ), + ) + return { + "enabled": True, + "quiet_noop_allowed": bool(authoritative["quiet_noop_allowed"]), + "must_attempt": bool(authoritative["must_attempt"]), + "current_state_digest": str(authoritative["state_digest"]), + "skip_host_when_unchanged": True, + "record_wait_baseline_when_changed": True, + } + + +def quiet_turn_target_params( + *, + plan: Mapping[str, Any], + goal_id: str, + agent_id: str, + goal_state_root: Path, + effective_quiet: Any, +) -> QuietTurnTarget: + qt_cfg = dict(effective_quiet) if isinstance(effective_quiet, Mapping) else {} + work_contract_slice, turn_envelope_slice = _plan_quiet_contract_inputs(plan) + raw_quiet = qt_cfg.get("quiet_noop_allowed", True) + quiet_cap = raw_quiet if isinstance(raw_quiet, bool) else bool(raw_quiet) + must_attempt_opt = qt_cfg.get("must_attempt") is True + scope_key = f"turn_quiet:{goal_id}:{agent_id}" + raw_envelope = plan.get("turn_envelope") + if isinstance(qt_cfg.get("current_state_digest"), str): + state_digest = str(qt_cfg["current_state_digest"]) + else: + computed = compute_quiet_turn_state_digest( + goal_id=goal_id, + agent_id=agent_id, + route=plan.get("route") if isinstance(plan.get("route"), Mapping) else None, + work_contract=( + plan.get("work_contract") if isinstance(plan.get("work_contract"), Mapping) else None + ), + turn_envelope=( + raw_envelope if isinstance(raw_envelope, Mapping) else None + ), + ) + state_digest = str(computed["state_digest"]) + return QuietTurnTarget( + scope_key=scope_key, + file_path=goal_state_root / "quiet_turn" / f"{sha256_text(scope_key)}.json", + sqlite_path=goal_state_root / "turn_prefetch_state.sqlite", + config=qt_cfg, + quiet_noop_allowed=quiet_cap, + must_attempt=must_attempt_opt, + state_changed=qt_cfg.get("state_changed"), + state_digest=state_digest, + work_contract=work_contract_slice, + turn_envelope=turn_envelope_slice, + ) + + +def _persist_quiet_turn_state( + *, + scope_key: str, + file_path: Path | None, + sqlite_path: Path | None, + state_digest: str, + metadata: Mapping[str, Any], +) -> None: + state_payload = { + "schema_version": QUIET_TURN_STATE_SCHEMA_VERSION, + "scope_key": scope_key, + "state_digest": state_digest, + "metadata": dict(metadata), + "updated_at": now_iso(), + } + if file_path is not None: + atomic_write_json(file_path, state_payload) + if sqlite_path is not None: + sqlite_path.parent.mkdir(parents=True, exist_ok=True) + with closing(sqlite3.connect(sqlite_path, timeout=5.0, isolation_level=None)) as connection: + init_turn_prefetch_sqlite_db(connection) + connection.execute("BEGIN IMMEDIATE") + try: + connection.execute( + """ + INSERT INTO quiet_turn_state (scope_key, state_digest, metadata_json, updated_at) + VALUES (?, ?, ?, ?) + ON CONFLICT(scope_key) DO UPDATE SET + state_digest = excluded.state_digest, + metadata_json = excluded.metadata_json, + updated_at = excluded.updated_at + """, + ( + scope_key, + state_digest, + json.dumps(dict(metadata), ensure_ascii=False, sort_keys=True), + now_iso(), + ), + ) + connection.execute("COMMIT") + except BaseException: + if connection.in_transaction: + connection.execute("ROLLBACK") + raise + + +def commit_quiet_turn_state( + *, + scope_key: str, + file_path: Path | None = None, + sqlite_path: Path | None = None, + state_digest: str, + metadata: Mapping[str, Any] | None = None, +) -> None: + """Persist Quiet-Turn state digest in BOTH File and SQLite after Turn settlement.""" + if not state_digest: + return + meta = dict(metadata) if isinstance(metadata, Mapping) else evaluate_quiet_turn( + enabled=True, + quiet_noop_allowed=True, + state_changed=True, + current_state_digest=state_digest, + previous_state_digest=None, + ) + _persist_quiet_turn_state( + scope_key=scope_key, + file_path=file_path, + sqlite_path=sqlite_path, + state_digest=state_digest, + metadata=meta, + ) + + +def resolve_quiet_turn_metadata( + *, + scope_key: str, + file_path: Path | None = None, + sqlite_path: Path | None = None, + enabled: bool = True, + quiet_noop_allowed: bool = True, + must_attempt: bool = False, + state_changed: bool | None = None, + current_state_digest: str | None = None, + record_if_changed: bool = True, + work_contract: Mapping[str, Any] | None = None, + turn_envelope: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + """Compute and optionally persist Quiet-Turn zero-tax skip metadata in File & SQLite.""" + file_digest: str | None = None + sqlite_digest: str | None = None + corrupt_stores: list[str] = [] + if current_state_digest is not None: + if file_path is not None and file_path.exists(): + if not file_path.is_file(): + corrupt_stores.append("file") + else: + try: + saved = json.loads(file_path.read_text(encoding="utf-8")) + if ( + isinstance(saved, dict) + and saved.get("scope_key") == scope_key + and isinstance(saved.get("state_digest"), str) + and saved.get("state_digest") + ): + file_digest = str(saved["state_digest"]) + else: + corrupt_stores.append("file") + except (OSError, ValueError): + corrupt_stores.append("file") + if sqlite_path is not None and sqlite_path.exists(): + try: + with closing(sqlite3.connect(sqlite_path, timeout=5.0)) as connection: + has_table = connection.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='quiet_turn_state'" + ).fetchone() + if has_table is not None: + row = connection.execute( + "SELECT state_digest FROM quiet_turn_state WHERE scope_key = ?", + (scope_key,), + ).fetchone() + if row is not None: + if isinstance(row[0], str) and row[0]: + sqlite_digest = row[0] + else: + corrupt_stores.append("sqlite") + except sqlite3.Error: + corrupt_stores.append("sqlite") + + if corrupt_stores: + corrupt_meta = evaluate_quiet_turn( + enabled=enabled, + quiet_noop_allowed=quiet_noop_allowed, + must_attempt=must_attempt, + state_changed=True, + current_state_digest=current_state_digest, + previous_state_digest=None, + work_contract=work_contract, + turn_envelope=turn_envelope, + ) + return { + **corrupt_meta, + "reason": "state_corrupt", + "state_corrupt": True, + "corrupt_stores": corrupt_stores, + } + + if file_digest is not None and sqlite_digest is not None and file_digest != sqlite_digest: + conflict_meta = evaluate_quiet_turn( + enabled=enabled, + quiet_noop_allowed=quiet_noop_allowed, + must_attempt=must_attempt, + state_changed=True, + current_state_digest=current_state_digest, + previous_state_digest=None, + work_contract=work_contract, + turn_envelope=turn_envelope, + ) + return { + **conflict_meta, + "reason": "state_conflict", + "state_conflict": True, + "file_digest": file_digest, + "sqlite_digest": sqlite_digest, + } + + previous_digest = file_digest if file_digest is not None else sqlite_digest + metadata = evaluate_quiet_turn( + enabled=enabled, + quiet_noop_allowed=quiet_noop_allowed, + must_attempt=must_attempt, + state_changed=state_changed, + current_state_digest=current_state_digest, + previous_state_digest=previous_digest, + work_contract=work_contract, + turn_envelope=turn_envelope, + ) + if record_if_changed and enabled and current_state_digest and not metadata.get("skipped"): + _persist_quiet_turn_state( + scope_key=scope_key, + file_path=file_path, + sqlite_path=sqlite_path, + state_digest=current_state_digest, + metadata=metadata, + ) + return metadata + + +def _quiet_turn_skip_paths(journal_path: Path, turn_key: str) -> tuple[Path, Path, Path]: + goal_state_root = journal_path.parent.parent + skip_file = goal_state_root / "quiet_turn" / "skips" / f"{sha256_text(turn_key)}.json" + sqlite_path = goal_state_root / "turn_prefetch_state.sqlite" + return goal_state_root, skip_file, sqlite_path + + +def quiet_turn_skip_requested( + quiet_turn: Any, + decision_capture_payload: Mapping[str, Any] | None, +) -> bool: + if not is_turn_option_enabled( + quiet_turn, decision_capture_payload, "quiet_turn", allow_bool_true=True, + ): + return False + effective_quiet = _resolve_effective_quiet(quiet_turn, decision_capture_payload) + return isinstance(effective_quiet, Mapping) and effective_quiet.get("skip_host_when_unchanged") is True + + +def has_quiet_turn_skip_store(journal_path: Path, turn_key: str) -> bool: + """Cheap non-creating probe for File or SQLite Quiet-Turn skip persistence.""" + _goal_state_root, skip_file, sqlite_path = _quiet_turn_skip_paths(journal_path, turn_key) + return skip_file.exists() or sqlite_path.exists() + + +def resolve_turn_request_or_quiet_wait( + *, + plan: Mapping[str, Any], + transaction_plan: Mapping[str, Any], + execute: bool, + runtime_root: Path, + goal_id: str, + quiet_turn: Any, + decision_capture_payload: Mapping[str, Any] | None, + journal_path_fn: Callable[..., Path], + request_builder: Callable[[Mapping[str, Any]], dict[str, Any]], +) -> tuple[dict[str, Any] | None, str]: + """Build executable Host request upfront or defer only for quiet-noop wait Turns.""" + raw_route = plan.get("route") + route = raw_route if isinstance(raw_route, Mapping) else {} + raw_turn_key = transaction_plan.get("turn_key") + if ( + execute + and route.get("would_invoke_host") is not True + and route.get("kind") == "wait" + and isinstance(raw_turn_key, str) + and TURN_KEY_RE.fullmatch(raw_turn_key) + ): + probe_journal_path = journal_path_fn( + runtime_root, goal_id=goal_id, turn_key=raw_turn_key, + ) + if quiet_turn_skip_requested(quiet_turn, decision_capture_payload) or has_quiet_turn_skip_store( + probe_journal_path, raw_turn_key, + ): + return None, raw_turn_key + request = request_builder(plan) + return request, str(request["turn_key"]) + + +def _validate_skip_receipt_mapping( + raw: Any, + *, + goal_id: str, + agent_id: str, + turn_key: str, + scope_key: str, +) -> dict[str, Any]: + if not isinstance(raw, Mapping): + raise ValueError("Quiet-Turn skip receipt must be a JSON object") + receipt = dict(raw) + if receipt.get("schema_version") != QUIET_TURN_SKIP_SCHEMA_VERSION: + raise ValueError("Quiet-Turn skip receipt schema_version mismatch") + if receipt.get("turn_key") != turn_key or receipt.get("scope_key") != scope_key: + raise ValueError("Quiet-Turn skip receipt identity mismatch") + if "goal_id" in receipt and receipt.get("goal_id") != goal_id: + raise ValueError("Quiet-Turn skip receipt goal_id mismatch") + if "agent_id" in receipt and receipt.get("agent_id") != agent_id: + raise ValueError("Quiet-Turn skip receipt agent_id mismatch") + quiet_meta = receipt.get("quiet_turn") + if not isinstance(quiet_meta, Mapping) or quiet_meta.get("skipped") is not True: + raise ValueError("Quiet-Turn skip receipt must have skipped=true") + return receipt + + +def _read_file_skip_receipt( + skip_file: Path, + *, + goal_id: str, + agent_id: str, + turn_key: str, + scope_key: str, +) -> dict[str, Any] | None: + if not skip_file.exists(): + return None + if not skip_file.is_file(): + raise ValueError(f"Quiet-Turn skip receipt path is not a file: {skip_file}") + try: + raw = json.loads(skip_file.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise ValueError("Corrupt File Quiet-Turn skip receipt") from exc + return _validate_skip_receipt_mapping( + raw, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + scope_key=scope_key, + ) + + +def _read_sqlite_skip_receipt( + sqlite_path: Path, + *, + goal_id: str, + agent_id: str, + turn_key: str, + scope_key: str, +) -> dict[str, Any] | None: + if not sqlite_path.exists(): + return None + try: + with closing(sqlite3.connect(sqlite_path, timeout=5.0)) as connection: + has_table = connection.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='quiet_turn_skips'" + ).fetchone() + if has_table is None: + return None + row = connection.execute( + """ + SELECT scope_key, state_digest, receipt_json, recorded_at + FROM quiet_turn_skips + WHERE turn_key = ? + """, + (turn_key,), + ).fetchone() + except sqlite3.Error as exc: + raise ValueError("Corrupt SQLite Quiet-Turn skip store") from exc + if row is None: + return None + row_scope_key, row_state_digest, row_json, row_recorded_at = row + if row_scope_key != scope_key: + raise ValueError("SQLite Quiet-Turn skip receipt scope_key mismatch") + try: + raw = json.loads(row_json) + except (TypeError, ValueError) as exc: + raise ValueError("Corrupt SQLite Quiet-Turn skip receipt") from exc + receipt = _validate_skip_receipt_mapping( + raw, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + scope_key=scope_key, + ) + if (row_state_digest or None) != (receipt.get("state_digest") or None) or ( + row_recorded_at != receipt.get("recorded_at") + ): + raise ValueError("SQLite Quiet-Turn skip receipt metadata mismatch") + return receipt + + +def _write_sqlite_skip_receipt_once( + sqlite_path: Path, + receipt: Mapping[str, Any], +) -> None: + sqlite_path.parent.mkdir(parents=True, exist_ok=True) + encoded = json.dumps(dict(receipt), ensure_ascii=False, sort_keys=True) + with closing(sqlite3.connect(sqlite_path, timeout=5.0, isolation_level=None)) as connection: + init_turn_prefetch_sqlite_db(connection) + connection.execute("BEGIN IMMEDIATE") + try: + existing = connection.execute( + "SELECT scope_key FROM quiet_turn_skips WHERE turn_key = ?", + (str(receipt["turn_key"]),), + ).fetchone() + if existing is not None: + raise ValueError("Quiet-Turn skip receipt already exists in SQLite") + connection.execute( + """ + INSERT INTO quiet_turn_skips (turn_key, scope_key, state_digest, receipt_json, recorded_at) + VALUES (?, ?, ?, ?, ?) + """, + ( + str(receipt["turn_key"]), + str(receipt["scope_key"]), + str(receipt.get("state_digest") or "") or None, + encoded, + str(receipt["recorded_at"]), + ), + ) + connection.execute("COMMIT") + except BaseException: + if connection.in_transaction: + connection.execute("ROLLBACK") + raise + + +def _load_or_heal_quiet_turn_skip_receipt( + *, + skip_file: Path, + sqlite_path: Path, + goal_id: str, + agent_id: str, + turn_key: str, + scope_key: str, +) -> dict[str, Any] | None: + if not skip_file.exists(): + peek_sqlite = _read_sqlite_skip_receipt( + sqlite_path, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + scope_key=scope_key, + ) + if peek_sqlite is None: + return None + with exclusive_file_lock(skip_file): + file_receipt = _read_file_skip_receipt( + skip_file, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + scope_key=scope_key, + ) + sqlite_receipt = _read_sqlite_skip_receipt( + sqlite_path, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + scope_key=scope_key, + ) + if file_receipt is None and sqlite_receipt is None: + return None + if file_receipt is not None and sqlite_receipt is not None: + if file_receipt != sqlite_receipt: + raise ValueError("Conflicting File and SQLite Quiet-Turn skip receipts") + return file_receipt + if file_receipt is not None: + _write_sqlite_skip_receipt_once(sqlite_path, file_receipt) + return file_receipt + assert sqlite_receipt is not None + atomic_write_json(skip_file, sqlite_receipt) + return sqlite_receipt + + +def recover_quiet_turn_skip_receipt( + *, + plan: Mapping[str, Any], + journal_path: Path, + goal_id: str, + turn_key: str, + settlement_lineage: Mapping[str, Any] | None, + host_projection: Mapping[str, Any], + empty_effects: Mapping[str, bool], + payload_builder: Callable[..., dict[str, Any]], +) -> dict[str, Any] | None: + """Replay an already-committed Quiet-Turn skip terminally without rewriting receipts or invoking Host.""" + _goal_state_root, skip_file, sqlite_path = _quiet_turn_skip_paths(journal_path, turn_key) + if not skip_file.exists() and not sqlite_path.exists(): + return None + agent_id = effective_turn_agent_id(plan, settlement_lineage) + scope_key = f"turn_quiet:{goal_id}:{agent_id}" + receipt = _load_or_heal_quiet_turn_skip_receipt( + skip_file=skip_file, + sqlite_path=sqlite_path, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + scope_key=scope_key, + ) + if receipt is None: + return None + replayed_quiet = dict(receipt["quiet_turn"]) + replayed_quiet["replayed"] = True + return { + **payload_builder( + plan, + {"status": "stopped", "host": host_projection, "reason": "quiet_turn_unchanged"}, + execute=True, + replayed=True, + effects=empty_effects, + ), + "status": "skipped", + "quiet_turn": replayed_quiet, + } + + +def assert_no_conflicting_quiet_turn_skip( + *, + journal_path: Path, + goal_id: str, + agent_id: str, + turn_key: str, +) -> None: + """Fail closed if a Turn journal coexists with a committed Quiet-Turn skip receipt.""" + _goal_state_root, skip_file, sqlite_path = _quiet_turn_skip_paths(journal_path, turn_key) + if not skip_file.exists() and not sqlite_path.exists(): + return + scope_key = f"turn_quiet:{goal_id}:{agent_id}" + if skip_file.exists(): + _read_file_skip_receipt( + skip_file, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + scope_key=scope_key, + ) + raise ValueError("Conflicting Turn journal and File Quiet-Turn skip receipt for turn_key") + sqlite_receipt = _read_sqlite_skip_receipt( + sqlite_path, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + scope_key=scope_key, + ) + if sqlite_receipt is not None: + raise ValueError("Conflicting Turn journal and SQLite Quiet-Turn skip receipt for turn_key") + + +def _record_quiet_turn_skip_receipt( + *, + goal_state_root: Path, + sqlite_path: Path, + goal_id: str, + agent_id: str, + turn_key: str, + scope_key: str, + quiet_meta: Mapping[str, Any], +) -> tuple[dict[str, Any], bool]: + skip_file = goal_state_root / "quiet_turn" / "skips" / f"{sha256_text(turn_key)}.json" + incoming_digest = str(quiet_meta.get("state_digest") or "") or None + with exclusive_file_lock(skip_file): + file_receipt = _read_file_skip_receipt( + skip_file, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + scope_key=scope_key, + ) + sqlite_receipt = _read_sqlite_skip_receipt( + sqlite_path, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + scope_key=scope_key, + ) + if file_receipt is not None or sqlite_receipt is not None: + if file_receipt is not None and sqlite_receipt is not None: + if file_receipt != sqlite_receipt: + raise ValueError("Conflicting File and SQLite Quiet-Turn skip receipts") + existing = file_receipt + elif file_receipt is not None: + existing = file_receipt + else: + assert sqlite_receipt is not None + existing = sqlite_receipt + if (existing.get("state_digest") or None) != incoming_digest: + raise ValueError("Conflicting Quiet-Turn skip state_digest for committed turn_key") + if file_receipt is None: + atomic_write_json(skip_file, existing) + elif sqlite_receipt is None: + _write_sqlite_skip_receipt_once(sqlite_path, existing) + return existing, True + + skip_payload = { + "schema_version": QUIET_TURN_SKIP_SCHEMA_VERSION, + "goal_id": goal_id, + "agent_id": agent_id, + "turn_key": turn_key, + "scope_key": scope_key, + "state_digest": incoming_digest, + "quiet_turn": dict(quiet_meta), + "recorded_at": now_iso(), + } + atomic_write_json(skip_file, skip_payload) + _write_sqlite_skip_receipt_once(sqlite_path, skip_payload) + return skip_payload, False + + +def _evaluate_quiet_skip_candidate( + *, + plan: Mapping[str, Any], + journal_path: Path, + goal_id: str, + settlement_lineage: Mapping[str, Any] | None, + options: Mapping[str, Any], +) -> tuple[Path, str, QuietTurnTarget, dict[str, Any], Mapping[str, Any]] | None: + quiet_turn = options.get("quiet_turn", False) + decision_capture_payload = options.get("decision_capture_payload") + if not is_turn_option_enabled( + quiet_turn, decision_capture_payload, "quiet_turn", allow_bool_true=True, + ): + return None + effective_quiet = _resolve_effective_quiet(quiet_turn, decision_capture_payload) + skip_host_cfg = effective_quiet if isinstance(effective_quiet, Mapping) else {} + if not skip_host_cfg.get("skip_host_when_unchanged"): + return None + goal_state_root = journal_path.parent.parent + agent_id = effective_turn_agent_id(plan, settlement_lineage) + target = quiet_turn_target_params( + plan=plan, + goal_id=goal_id, + agent_id=agent_id, + goal_state_root=goal_state_root, + effective_quiet=effective_quiet, + ) + with exclusive_file_lock(target.file_path): + quiet_meta = resolve_quiet_turn_metadata( + scope_key=target.scope_key, + file_path=target.file_path, + sqlite_path=target.sqlite_path, + enabled=True, + quiet_noop_allowed=target.quiet_noop_allowed, + must_attempt=target.must_attempt, + state_changed=target.state_changed, + current_state_digest=target.state_digest, + record_if_changed=False, + work_contract=target.work_contract, + turn_envelope=target.turn_envelope, + ) + return goal_state_root, agent_id, target, quiet_meta, skip_host_cfg + + +def _skip_payload_from_meta( + *, + plan: Mapping[str, Any], + goal_state_root: Path, + agent_id: str, + goal_id: str, + turn_key: str, + target: QuietTurnTarget, + quiet_meta: Mapping[str, Any], + host_projection: Mapping[str, Any], + empty_effects: Mapping[str, bool], + payload_builder: Callable[..., dict[str, Any]], +) -> dict[str, Any]: + stored_receipt, replayed_existing = _record_quiet_turn_skip_receipt( + goal_state_root=goal_state_root, + sqlite_path=target.sqlite_path, + goal_id=goal_id, + agent_id=agent_id, + turn_key=turn_key, + scope_key=target.scope_key, + quiet_meta=quiet_meta, + ) + returned_quiet = dict(stored_receipt["quiet_turn"]) + if replayed_existing: + returned_quiet["replayed"] = True + return { + **payload_builder( + plan, + {"status": "stopped", "host": host_projection, "reason": "quiet_turn_unchanged"}, + execute=True, + replayed=replayed_existing, + effects=empty_effects, + ), + "status": "skipped", + "quiet_turn": returned_quiet, + } + + +def maybe_skip_quiet_turn_before_admission( + *, + plan: Mapping[str, Any], + journal_path: Path, + goal_id: str, + turn_key: str, + settlement_lineage: Mapping[str, Any] | None, + host_projection: Mapping[str, Any], + empty_effects: Mapping[str, bool], + options: Mapping[str, Any], + payload_builder: Callable[..., dict[str, Any]], +) -> dict[str, Any] | None: + """Evaluate Quiet-Turn BEFORE quota admission/capture publish and record durable skip receipt.""" + replayed_payload = recover_quiet_turn_skip_receipt( + plan=plan, + journal_path=journal_path, + goal_id=goal_id, + turn_key=turn_key, + settlement_lineage=settlement_lineage, + host_projection=host_projection, + empty_effects=empty_effects, + payload_builder=payload_builder, + ) + if replayed_payload is not None: + return replayed_payload + + evaluated = _evaluate_quiet_skip_candidate( + plan=plan, + journal_path=journal_path, + goal_id=goal_id, + settlement_lineage=settlement_lineage, + options=options, + ) + if evaluated is None: + return None + goal_state_root, agent_id, target, quiet_meta, _skip_host_cfg = evaluated + if not quiet_meta.get("skipped"): + return None + return _skip_payload_from_meta( + plan=plan, + goal_state_root=goal_state_root, + agent_id=agent_id, + goal_id=goal_id, + turn_key=turn_key, + target=target, + quiet_meta=quiet_meta, + host_projection=host_projection, + empty_effects=empty_effects, + payload_builder=payload_builder, + ) + + +def resolve_quiet_wait_or_replay_before_admission( + *, + plan: Mapping[str, Any], + request: dict[str, Any] | None, + journal_path: Path, + goal_id: str, + turn_key: str, + settlement_lineage: Mapping[str, Any] | None, + host_projection: Mapping[str, Any], + empty_effects: Mapping[str, bool], + needs_host: bool, + goal_admission: Any, + options: Mapping[str, Any], + payload_builder: Callable[..., dict[str, Any]], + request_builder: Callable[[Mapping[str, Any]], dict[str, Any]], +) -> tuple[dict[str, Any] | None, dict[str, Any]]: + """Enforce terminal Quiet-Turn skip replay or resolve deferred quiet-noop wait before admission.""" + replayed_payload = recover_quiet_turn_skip_receipt( + plan=plan, + journal_path=journal_path, + goal_id=goal_id, + turn_key=turn_key, + settlement_lineage=settlement_lineage, + host_projection=host_projection, + empty_effects=empty_effects, + payload_builder=payload_builder, + ) + if replayed_payload is not None: + return replayed_payload, (request if request is not None else {}) + if request is not None: + return None, request + if needs_host and goal_admission is not None: + goal_admission.require_current() + evaluated = _evaluate_quiet_skip_candidate( + plan=plan, + journal_path=journal_path, + goal_id=goal_id, + settlement_lineage=settlement_lineage, + options=options, + ) + if evaluated is not None: + goal_state_root, agent_id, target, quiet_meta, skip_host_cfg = evaluated + if quiet_meta.get("state_conflict") or quiet_meta.get("state_corrupt"): + raise ValueError(f"Quiet-Turn state store error: {quiet_meta.get('reason')}") + if quiet_meta.get("skipped"): + return ( + _skip_payload_from_meta( + plan=plan, + goal_state_root=goal_state_root, + agent_id=agent_id, + goal_id=goal_id, + turn_key=turn_key, + target=target, + quiet_meta=quiet_meta, + host_projection=host_projection, + empty_effects=empty_effects, + payload_builder=payload_builder, + ), + {}, + ) + if ( + quiet_meta.get("quiet_noop_allowed") is True + and skip_host_cfg.get("record_wait_baseline_when_changed") is True + and skip_host_cfg.get("state_changed") is None + and target.state_digest + ): + with exclusive_file_lock(target.file_path): + commit_quiet_turn_state( + scope_key=target.scope_key, + file_path=target.file_path, + sqlite_path=target.sqlite_path, + state_digest=target.state_digest, + metadata=quiet_meta, + ) + return ( + { + **payload_builder( + plan, + {"status": "stopped", "host": host_projection, "reason": "quiet_turn_state_changed"}, + execute=True, + replayed=False, + effects=empty_effects, + ), + "quiet_turn": dict(quiet_meta), + }, + {}, + ) + return None, request_builder(plan) + + +def commit_turn_quiet_state_after_success( + *, + settled: Mapping[str, Any], + epoch_metadata: Mapping[str, Any] | None, + plan: Mapping[str, Any], + journal_path: Path, + goal_id: str, + settlement_lineage: Mapping[str, Any] | None, + options: Mapping[str, Any], +) -> None: + """Commit Quiet-Turn state_digest ONLY after the Turn has settled cleanly.""" + if not epoch_metadata: + return + if settled.get("ok") is not True or settled.get("status") not in { + "committed", + "stopped", + "scheduler_action_required", + }: + return + quiet_meta = epoch_metadata.get("quiet_turn") + if not isinstance(quiet_meta, Mapping) or quiet_meta.get("enabled") is not True: + return + if quiet_meta.get("skipped") is True: + return + effective_quiet = _resolve_effective_quiet( + 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, + goal_id=goal_id, + agent_id=agent_id, + goal_state_root=goal_state_root, + effective_quiet=effective_quiet, + ) + commit_quiet_turn_state( + scope_key=target.scope_key, + file_path=target.file_path, + sqlite_path=target.sqlite_path, + state_digest=target.state_digest, + metadata=quiet_meta, + ) + + +def resolve_codex_context_quiet_turn_hook( + *, + hook_name: Any, + state: Mapping[str, Any], + event: Mapping[str, Any], + recovery: Mapping[str, Any] | None, + root_dir: Path, +) -> dict[str, Any] | None: + """Resolve opt-in Quiet-Turn zero-tax skip metadata for codex_context_hook.""" + quiet_cfg = event.get("quiet_turn") + if not (quiet_cfg is True or (isinstance(quiet_cfg, Mapping) and quiet_cfg.get("enabled") is True)): + return None + qt_cfg = quiet_cfg if isinstance(quiet_cfg, Mapping) else {} + goal_label = str(state.get("goal_id") or event.get("goal_id") or "default") + agent_label = str(state.get("agent_id") or event.get("agent_id") or "default") + work_contract, turn_envelope, must_attempt, quiet_cap = _hook_quiet_contract_inputs( + event=event, + state=state, + qt_cfg=qt_cfg, + ) + quiet_meta = resolve_quiet_turn_metadata( + scope_key=f"codex_context:{goal_label}:{agent_label}", + file_path=root_dir / "quiet_turn_state.json", + sqlite_path=root_dir / "epoch_prefetch.sqlite", + enabled=True, + quiet_noop_allowed=quiet_cap, + must_attempt=must_attempt, + state_changed=qt_cfg.get("state_changed"), + current_state_digest=( + str(qt_cfg["current_state_digest"]) + if isinstance(qt_cfg.get("current_state_digest"), str) + else str((recovery or {}).get("sha256") or "") or None + ), + work_contract=work_contract, + turn_envelope=turn_envelope, + ) + if quiet_meta.get("skipped"): + return {"hookSpecificOutput": {"hookEventName": hook_name, "quietTurn": quiet_meta}} + return None diff --git a/loopx/control_plane/turn_driver/semantic_unit_hook.py b/loopx/control_plane/turn_driver/semantic_unit_hook.py new file mode 100644 index 0000000000..5f4b30b708 --- /dev/null +++ b/loopx/control_plane/turn_driver/semantic_unit_hook.py @@ -0,0 +1,403 @@ +"""Hook-boundary handler for receipt-gated Todo semantic-unit anchor and fold swaps. + +Semantic validation, anti-whitewashing receipt construction, net token gating, +and KeepRaw rollback stay owned by TypeScript (`quota/stage_then_swap.ts`). +""" +from __future__ import annotations + +from collections.abc import Callable, Mapping +import json + +from ..effect_runtime import EffectRuntimeRejected, EffectRuntimeRemoteError, EffectRuntimeStartupError +from ..quota.turn_envelope import ( + build_semantic_unit_fold_swap, + plan_stage_then_swap_prefetch, + record_semantic_unit_anchor, +) +from .epoch_prefetch import ( + DEFAULT_TOKENIZER_ENCODING, + count_verifiable_tokens, + run_bounded_prefetch_subprocess as run_bounded_prefetch_subprocess, +) + + +def _as_object_dict(value: object) -> dict[str, object]: + if isinstance(value, Mapping): + return {str(k): v for k, v in value.items()} + return {} + + +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)] + + +def _opt_int(value: object) -> int | None: + return value if isinstance(value, int) and not isinstance(value, bool) else None + + +def _semantic_unit_fold_replay_key( + fold_cfg: Mapping[str, object], + context_epoch: str, +) -> str | None: + todo_id = fold_cfg.get("todo_id") + turn_id = fold_cfg.get("turn_instance_id") + receipt = fold_cfg.get("completion_receipt") + receipt_id = receipt.get("completion_receipt_id") if isinstance(receipt, Mapping) else None + if ( + isinstance(todo_id, str) + and todo_id + and isinstance(turn_id, str) + and turn_id + and isinstance(receipt_id, str) + and receipt_id + and context_epoch + ): + return f"{todo_id}:{turn_id}:{receipt_id}:{context_epoch}" + return None + + +def _run_semantic_unit_obs_command( + fold_cfg: Mapping[str, object], + *, + anchor: Mapping[str, object] | None, + todo_id: str, + turn_instance_id: str, + context_epoch: str, + prefix_digest: str | None, + quiescent_boundary: bool, + cwd: object, +) -> tuple[dict[str, object] | None, bool]: + raw_obs = fold_cfg.get("obs_next_cmd") + if not isinstance(raw_obs, Mapping): + return None, False + obs: dict[str, object] = {str(k): v for k, v in raw_obs.items()} + if "output" in obs and "exit_code" in obs: + return obs, False + cmd = obs.get("prefetch_command") if obs.get("prefetch_command") is not None else obs.get("command") + receipt = fold_cfg.get("completion_receipt") + pre_valid = ( + cmd is not None + and quiescent_boundary + and isinstance(anchor, Mapping) + and anchor.get("todo_id") == todo_id + and anchor.get("turn_instance_id") == turn_instance_id + and anchor.get("context_epoch") == context_epoch + and anchor.get("prefix_digest") == prefix_digest + and isinstance(receipt, Mapping) + and receipt.get("todo_id") == todo_id + and receipt.get("exit_code") == 0 + ) + if not pre_valid: + return obs, False + safety = plan_stage_then_swap_prefetch( + epoch_prefetch={ + "enabled": True, + "initiator": obs.get("initiator") or "turn_driver", + "prefetch_command": cmd, + "timeout_ms": _opt_int(obs.get("timeout_ms")) or 5000, + "max_output_bytes": _opt_int(obs.get("max_output_bytes")) or 16384, + "reject_on_truncation": obs.get("reject_on_truncation", True), + } + ) + if not safety.get("eligible"): + return obs, False + argv = list(safety["safety"]["argv"]) + run_result = run_bounded_prefetch_subprocess( + argv, + timeout_ms=int(safety["timeout_ms"]), + max_output_bytes=int(safety["max_output_bytes"]), + cwd=str(cwd) if isinstance(cwd, str) and cwd else None, + ) + obs["prefetch_command"] = argv + obs["exit_code"] = run_result["exit_code"] + obs["timed_out"] = run_result["timed_out"] + obs["truncated"] = run_result["truncated"] + obs["output"] = run_result.get("prefetched_output", "") + obs["latency_ms"] = run_result["latency_ms"] + return obs, True + + +def _format_semantic_unit_hook_output( + hook_name: str, + receipt: Mapping[str, object], + *, + anchor: Mapping[str, object] | None = None, +) -> dict[str, object]: + if receipt.get("operator") == "FoldToReceipt" and isinstance(receipt.get("replacement_text"), str): + additional_context = str(receipt["replacement_text"]) + else: + facts = json.dumps(receipt.get("preserved_failure_facts", []), ensure_ascii=False) + obligations = json.dumps(receipt.get("preserved_open_obligations", []), ensure_ascii=False) + reason_note = str( + receipt.get("error_observation") or "Semantic-unit fold kept raw context intact (KeepRaw)." + ) + additional_context = ( + f"{reason_note}\n" + f"Preserved failure facts: {facts}\n" + f"Preserved open obligations: {obligations}" + ) + hook_out: dict[str, object] = { + "hookEventName": hook_name, + "additionalContext": additional_context, + "semanticUnitFold": {str(k): v for k, v in receipt.items()}, + } + if anchor is not None: + hook_out["semanticUnitAnchor"] = {str(k): v for k, v in anchor.items()} + return {"hookSpecificOutput": hook_out} + + +def _record_semantic_unit_anchor_if_present( + state: Mapping[str, object], + updated: dict[str, object], + event: Mapping[str, object], +) -> dict[str, object] | None: + raw_req = event.get("semantic_unit_anchor") + if not (isinstance(raw_req, Mapping) and raw_req.get("enabled", True) is not False): + return None + target_epoch = str(raw_req.get("context_epoch") or updated.get("context_epoch") or state.get("context_epoch") or "") + if not target_epoch or target_epoch != str(updated.get("context_epoch") or ""): + return None + step_idx = _opt_int(raw_req.get("anchor_step_index")) + try: + recorded = record_semantic_unit_anchor( + todo_id=str(raw_req.get("todo_id") or ""), + turn_instance_id=str(raw_req.get("turn_instance_id") or ""), + anchor_step_index=step_idx if step_idx is not None else -1, + prefix_digest=str(raw_req.get("prefix_digest") or ""), + context_epoch=target_epoch, + anchor_surface_seq=_opt_int(raw_req.get("anchor_surface_seq")), + goal_id=raw_req.get("goal_id") if isinstance(raw_req.get("goal_id"), str) else None, + agent_id=raw_req.get("agent_id") if isinstance(raw_req.get("agent_id"), str) else None, + ) + except (EffectRuntimeRejected, EffectRuntimeRemoteError, EffectRuntimeStartupError, ValueError, TypeError): + return None + anchors = _as_object_dict(updated.get("semantic_unit_anchors")) + anchors[str(recorded["todo_id"])] = recorded + updated["semantic_unit_anchors"] = anchors + return recorded + + +def _lookup_replayed_fold( + state: Mapping[str, object], + updated: Mapping[str, object], + replay_key: str | None, +) -> dict[str, object] | None: + if not replay_key: + return None + for container in (updated.get("semantic_unit_folds"), state.get("semantic_unit_folds")): + if isinstance(container, Mapping) and isinstance(container.get(replay_key), Mapping): + return {**_as_object_dict(container[replay_key]), "replayed": True, "executed": False} + return None + + +def _resolve_semantic_unit_anchor( + fold_req: Mapping[str, object], + state: Mapping[str, object], + updated: Mapping[str, object], + todo_id: str, +) -> dict[str, object] | None: + if isinstance(fold_req.get("anchor"), Mapping): + return _as_object_dict(fold_req["anchor"]) + same_epoch = str(updated.get("context_epoch") or "") == str(state.get("context_epoch") or "") + anchors_map = ( + updated.get("semantic_unit_anchors") + if isinstance(updated.get("semantic_unit_anchors"), Mapping) + else (state.get("semantic_unit_anchors") if same_epoch else None) + ) + stored = anchors_map.get(todo_id) if isinstance(anchors_map, Mapping) and todo_id else None + return _as_object_dict(stored) if isinstance(stored, Mapping) else None + + +def _evaluate_semantic_unit_fold( + *, + fold_req: Mapping[str, object], + anchor: Mapping[str, object] | None, + todo_id: str, + turn_instance_id: str, + context_epoch: str, + quiescent: bool, + cwd: object, + token_counter: Callable[[str], int] | None, +) -> dict[str, object]: + raw_prefix = fold_req.get("prefix_digest") + prefix_digest = raw_prefix if isinstance(raw_prefix, str) else None + obs_payload, obs_executed = _run_semantic_unit_obs_command( + fold_req, + anchor=anchor, + todo_id=todo_id, + turn_instance_id=turn_instance_id, + context_epoch=context_epoch, + prefix_digest=prefix_digest, + quiescent_boundary=quiescent, + cwd=cwd, + ) + encoding_name = str(fold_req.get("tokenizer_encoding") or DEFAULT_TOKENIZER_ENCODING) + baseline_tokens = _opt_int(fold_req.get("baseline_tokens")) + baseline_bytes = _opt_int(fold_req.get("baseline_bytes")) + tokenizer_meta: dict[str, object] | None = ( + _as_object_dict(fold_req.get("tokenizer")) if isinstance(fold_req.get("tokenizer"), Mapping) else None + ) + baseline_text = fold_req.get("baseline_text") + if baseline_tokens is None and isinstance(baseline_text, str): + measured_base = count_verifiable_tokens(baseline_text, encoding_name=encoding_name, token_counter=token_counter) + if measured_base is not None: + baseline_tokens = measured_base[0] + if tokenizer_meta is None: + tokenizer_meta = _as_object_dict(measured_base[1]) + if baseline_bytes is None: + baseline_bytes = len(baseline_text.encode("utf-8")) + + replacement_tokens = _opt_int(fold_req.get("replacement_tokens")) + raw_receipt = fold_req.get("completion_receipt") + def call_fold( + *, + rep_tokens: int | None, + min_sav: int | None, + cold_amort: int | None, + tok_meta: dict[str, object] | None, + ) -> dict[str, object]: + return build_semantic_unit_fold_swap( + enabled=True, + anchor=anchor, + todo_id=todo_id, + turn_instance_id=turn_instance_id, + context_epoch=context_epoch, + prefix_digest=prefix_digest, + now_step_index=_opt_int(fold_req.get("now_step_index")), + now_surface_seq=_opt_int(fold_req.get("now_surface_seq")), + completion_receipt=raw_receipt if isinstance(raw_receipt, Mapping) else None, + baseline_tokens=baseline_tokens, + replacement_tokens=rep_tokens, + baseline_bytes=baseline_bytes, + min_net_savings_tokens=min_sav, + cold_prefill_amortization_tokens=cold_amort, + tokenizer_encoding=encoding_name, + tokenizer=tok_meta, + obs_next_cmd=obs_payload, + surface_prefix_intact=fold_req.get("surface_prefix_intact", True) is not False, + tool_pairing_valid=fold_req.get("tool_pairing_valid", True) is not False, + quiescent_boundary=quiescent, + failure_facts=_as_str_list(fold_req.get("failure_facts")), + open_obligations=_as_str_list(fold_req.get("open_obligations")), + ) + + if replacement_tokens is None and baseline_tokens is not None and tokenizer_meta is not None: + preview = call_fold(rep_tokens=1, min_sav=1, cold_amort=0, tok_meta=tokenizer_meta) + preview_text = preview.get("replacement_text") + measured_rep = ( + count_verifiable_tokens(preview_text, encoding_name=encoding_name, token_counter=token_counter) + if isinstance(preview_text, str) + else None + ) + if measured_rep is not None: + replacement_tokens = measured_rep[0] + tokenizer_meta = _as_object_dict(measured_rep[1]) + elif isinstance(preview_text, str): + tokenizer_meta = None + + receipt = call_fold( + rep_tokens=replacement_tokens, + min_sav=_opt_int(fold_req.get("min_net_savings_tokens")), + cold_amort=_opt_int(fold_req.get("cold_prefill_amortization_tokens")), + tok_meta=tokenizer_meta, + ) + return {**_as_object_dict(receipt), "replayed": False, "executed": obs_executed} + + +def apply_codex_context_semantic_unit_hook( + *, + hook_name: str, + state: Mapping[str, object], + updated: dict[str, object], + event: Mapping[str, object], + token_counter: Callable[[str], int] | None = None, +) -> dict[str, object] | None: + """Emit or consume default-off Todo semantic-unit anchors and fold receipts on quiescent hooks.""" + recorded_anchor = _record_semantic_unit_anchor_if_present(state, updated, event) + raw_fold_req = event.get("semantic_unit_fold") + if not (isinstance(raw_fold_req, Mapping) and raw_fold_req.get("enabled") is True): + return ( + {"hookSpecificOutput": {"hookEventName": hook_name, "semanticUnitAnchor": recorded_anchor}} + if recorded_anchor is not None + else None + ) + fold_req = _as_object_dict(raw_fold_req) + context_epoch = str(fold_req.get("context_epoch") or updated.get("context_epoch") or state.get("context_epoch") or "") + todo_id = str(fold_req.get("todo_id") or "") + replay_key = _semantic_unit_fold_replay_key(fold_req, context_epoch) + replayed = _lookup_replayed_fold(state, updated, replay_key) + if replayed is not None: + return _format_semantic_unit_hook_output(hook_name, replayed, anchor=recorded_anchor) + quiescent = ( + not bool(event.get("tool_in_flight")) + and not bool(event.get("unpaired_tool_calls")) + and not bool(state.get("pending")) + and not bool(updated.get("pending")) + and fold_req.get("quiescent_boundary", True) is not False + ) + receipt = _evaluate_semantic_unit_fold( + fold_req=fold_req, + anchor=_resolve_semantic_unit_anchor(fold_req, state, updated, todo_id), + todo_id=todo_id, + turn_instance_id=str(fold_req.get("turn_instance_id") or ""), + context_epoch=context_epoch, + quiescent=quiescent, + cwd=event.get("cwd"), + token_counter=token_counter, + ) + if replay_key and receipt.get("operator") == "FoldToReceipt": + folds = _as_object_dict(updated.get("semantic_unit_folds")) + folds[replay_key] = receipt + updated["semantic_unit_folds"] = folds + return _format_semantic_unit_hook_output(hook_name, receipt, anchor=recorded_anchor) + + +def semantic_unit_event_active(event: Mapping[str, object]) -> bool: + """Return True only when an opt-in Todo semantic-unit anchor or fold hook is active.""" + fold = event.get("semantic_unit_fold") + return isinstance(event.get("semantic_unit_anchor"), Mapping) or ( + isinstance(fold, Mapping) and fold.get("enabled") is True + ) + + +def run_locked_semantic_unit_hook( + *, + hook_name: object, + session: str, + state: Mapping[str, object], + updated: dict[str, object], + event: Mapping[str, object], +) -> dict[str, object] | None: + """Run opt-in Todo semantic-unit hook persistence cleanly inside the codex_context lock.""" + if not ( + semantic_unit_event_active(event) + and isinstance(hook_name, str) + and hook_name in {"PreCompact", "PostCompact", "SessionStart", "PostToolUse"} + and updated.get("session_id") == session + and updated.get("cwd") == event.get("cwd") + ): + return None + return apply_codex_context_semantic_unit_hook( + hook_name=hook_name, + state=state, + updated=updated, + event=event, + ) + + +def merge_semantic_unit_hook_output( + target: dict[str, object], + semantic_output: Mapping[str, object] | None, +) -> dict[str, object]: + """Attach semanticUnitAnchor / semanticUnitFold metadata onto an existing hook output.""" + if semantic_output is None: + return target + fold_out = semantic_output.get("hookSpecificOutput") + target_out = target.get("hookSpecificOutput") + if isinstance(fold_out, Mapping) and isinstance(target_out, dict): + for key in ("semanticUnitAnchor", "semanticUnitFold"): + if key in fold_out: + target_out[key] = fold_out[key] + return target diff --git a/packages/dsh-loopx-plugin/smoke/dsh-client-artifact-smoke.mjs b/packages/dsh-loopx-plugin/smoke/dsh-client-artifact-smoke.mjs index f15456de08..cbdf97eec8 100644 --- a/packages/dsh-loopx-plugin/smoke/dsh-client-artifact-smoke.mjs +++ b/packages/dsh-loopx-plugin/smoke/dsh-client-artifact-smoke.mjs @@ -67,6 +67,7 @@ const packedStaticEntries = new Set([ 'package/lib/types/native-operation-context.d.ts', 'package/lib/types/native-operation.d.ts', 'package/lib/types/observer.d.ts', + 'package/lib/types/todo-unit-fold.d.ts', 'package/package.json', ]) const packedHashedEntries = [ diff --git a/packages/dsh-loopx-plugin/smoke/dsh-goalbar-runtime-smoke.mjs b/packages/dsh-loopx-plugin/smoke/dsh-goalbar-runtime-smoke.mjs index 1e77cdb51f..4d41ae1b25 100644 --- a/packages/dsh-loopx-plugin/smoke/dsh-goalbar-runtime-smoke.mjs +++ b/packages/dsh-loopx-plugin/smoke/dsh-goalbar-runtime-smoke.mjs @@ -69,6 +69,7 @@ const packedStaticEntries = new Set([ 'package/lib/types/native-operation-context.d.ts', 'package/lib/types/native-operation.d.ts', 'package/lib/types/observer.d.ts', + 'package/lib/types/todo-unit-fold.d.ts', 'package/package.json', ]) const packedHashedEntries = [ diff --git a/packages/dsh-loopx-plugin/smoke/dsh-profile-smoke.mjs b/packages/dsh-loopx-plugin/smoke/dsh-profile-smoke.mjs index 008e8f2766..58b4315aab 100755 --- a/packages/dsh-loopx-plugin/smoke/dsh-profile-smoke.mjs +++ b/packages/dsh-loopx-plugin/smoke/dsh-profile-smoke.mjs @@ -50,6 +50,7 @@ const packedStaticEntries = new Set([ 'package/lib/types/native-operation-context.d.ts', 'package/lib/types/native-operation.d.ts', 'package/lib/types/observer.d.ts', + 'package/lib/types/todo-unit-fold.d.ts', 'package/package.json', ]) const packedHashedEntries = [ diff --git a/packages/dsh-loopx-plugin/src/driver.ts b/packages/dsh-loopx-plugin/src/driver.ts index 17b2d8d32a..0bae1167e2 100644 --- a/packages/dsh-loopx-plugin/src/driver.ts +++ b/packages/dsh-loopx-plugin/src/driver.ts @@ -28,6 +28,39 @@ import type { GoalBarAdmissionFailureCategoryV1, GoalBarContinuationAdmissionV1, } from './goalbar/protocol.ts' +import { + applyTodoUnitFoldAndPrefetch, + hasValidDshToolCallPairing, + recordDshTodoUnitAnchor, + validateTodoUnitObsForExecution, +} from './todo-unit-fold.ts' +import type { + LoopXTodoFoldMessageSource, + TodoUnitAnchor, + TodoUnitAnchorInput, + TodoUnitCompletionReceipt, + TodoUnitFoldOutcome, + TodoUnitFoldPolicy, + TodoUnitFoldRequest, + TodoUnitObsNextCommand, + TodoUnitObsRunner, + TodoUnitReceiptMu, + TodoUnitSourceRef, +} from './todo-unit-fold.ts' + +export type { + LoopXTodoFoldMessageSource, + TodoUnitAnchor, + TodoUnitAnchorInput, + TodoUnitCompletionReceipt, + TodoUnitFoldOutcome, + TodoUnitFoldPolicy, + TodoUnitFoldRequest, + TodoUnitObsNextCommand, + TodoUnitObsRunner, + TodoUnitReceiptMu, + TodoUnitSourceRef, +} export const name = 'dsh-loopx-driver' export const inject = ['agents', 'loopxBootstrap'] @@ -94,6 +127,8 @@ interface SessionDriverRetention { goalBarPaused?: boolean admissionFailure?: GoalBarAdmissionFailureCategoryV1 | undefined reservation?: Reservation | undefined + todoUnitAnchors?: Map | undefined + todoUnitFolds?: Map | undefined } // HMR can replace this module while the same Agent and Session keep running. @@ -199,6 +234,10 @@ export interface LoopXDriverOptions { readonly warn?: ((message: string) => void) | undefined /** Notified only when the projected admission failure is set or cleared. */ readonly onAdmissionChange?: ((session: Agent['session']) => void) | undefined + /** Strictly default-off Todo semantic-unit context folding & prefetch policy. */ + readonly todoUnitFold?: TodoUnitFoldPolicy | undefined + /** Optional bounded reader for Todo-unit Obs(next_cmd) verification commands. */ + readonly runObsCommand?: TodoUnitObsRunner | undefined } const systemClock: DriverClock = Object.freeze({ @@ -827,6 +866,8 @@ export class LoopXContinuationDriver { private readonly runDetached: (operation: () => Promise) => Promise private readonly warn: (message: string) => void private readonly onAdmissionChange: ((session: Agent['session']) => void) | undefined + private readonly todoUnitFold: TodoUnitFoldPolicy | undefined + private readonly runObsCommand: TodoUnitObsRunner | undefined private command?: LoopXCommand | undefined private disposed = false @@ -846,6 +887,98 @@ export class LoopXContinuationDriver { } } this.onAdmissionChange = options.onAdmissionChange + this.todoUnitFold = options.todoUnitFold + this.runObsCommand = options.runObsCommand + } + + /** 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 + const anchor = recordDshTodoUnitAnchor(agent.session, input) + const retained = retainedState(agent, agent.session) + retained.todoUnitAnchors ??= new Map() + retained.todoUnitAnchors.set(anchor.todoId, anchor) + return anchor + } + + /** + * Default-off FoldAndPrefetch hook executed when a Todo semantic unit settles: + * 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 { + const policy = this.todoUnitFold + if (policy?.enabled !== true) { + return applyTodoUnitFoldAndPrefetch(agent.session, policy, request) + } + const state = this.stateFor(agent) + const retained = retainedState(agent, agent.session) + const foldKey = request.completionReceipt?.completionReceiptId + ? `${request.todoId}:${request.turnInstanceId}:${request.completionReceipt.completionReceiptId}:${request.contextEpoch}` + : undefined + const cached = foldKey !== undefined ? retained.todoUnitFolds?.get(foldKey) : undefined + 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 + && 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) + const activeAnchor = request.anchor ?? storedAnchor + let effectiveRequest: TodoUnitFoldRequest = { + ...request, + quiescentBoundary: quiescent, + } + if ( + quiescent + && typeof sessionCwd === 'string' + && sessionCwd.length > 0 + && activeAnchor !== undefined + && activeAnchor.todoId === request.todoId + && activeAnchor.turnInstanceId === request.turnInstanceId + && activeAnchor.contextEpoch === request.contextEpoch + && request.completionReceipt?.exitCode === 0 + && request.completionReceipt.todoId.trim() === request.todoId + && hasValidDshToolCallPairing(agent.session, activeAnchor.prefixNodeCount) + && this.runObsCommand !== undefined + ) { + const safeArgv = validateTodoUnitObsForExecution(request.obsNextCmd) + if (safeArgv !== null && request.obsNextCmd !== undefined) { + 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 outcome = applyTodoUnitFoldAndPrefetch(agent.session, policy, effectiveRequest, storedAnchor) + if (outcome.operator === 'FoldToReceipt') { + retained.todoUnitAnchors?.delete(request.todoId) + if (foldKey !== undefined) { + retained.todoUnitFolds ??= new Map() + retained.todoUnitFolds.set(foldKey, outcome) + } + } + return outcome + } + + /** Named alias matching FoldAndPrefetch hook semantics on the real Driver. */ + foldAndPrefetch(agent: Agent, request: TodoUnitFoldRequest): Promise { + return this.onTodoUnitSettled(agent, request) } observeAgent(agent: Agent): void { @@ -871,6 +1004,8 @@ export class LoopXContinuationDriver { state.schedulerToken = '' state.unchangedPolls = 0 state.commands.clear() + retainedState(agent, agent.session).todoUnitAnchors?.clear() + retainedState(agent, agent.session).todoUnitFolds?.clear() state.activation = foldSessionActivation(agent.session) this.requestEvaluation(state) } diff --git a/packages/dsh-loopx-plugin/src/index.ts b/packages/dsh-loopx-plugin/src/index.ts index ba11bf2f2c..ef1aadf95a 100644 --- a/packages/dsh-loopx-plugin/src/index.ts +++ b/packages/dsh-loopx-plugin/src/index.ts @@ -61,7 +61,21 @@ export type { GoalBarServiceOptions, } from './goalbar/service.ts' export { LoopXContinuationDriver } from './driver.ts' -export type { DriverClock, LoopXDriverOptions } from './driver.ts' +export type { + DriverClock, + LoopXDriverOptions, + LoopXTodoFoldMessageSource, + TodoUnitAnchor, + TodoUnitAnchorInput, + TodoUnitCompletionReceipt, + TodoUnitFoldOutcome, + TodoUnitFoldPolicy, + TodoUnitFoldRequest, + TodoUnitObsNextCommand, + TodoUnitObsRunner, + TodoUnitReceiptMu, + TodoUnitSourceRef, +} from './driver.ts' export { initializeLoopX, LoopXInitError, diff --git a/packages/dsh-loopx-plugin/src/todo-unit-fold.ts b/packages/dsh-loopx-plugin/src/todo-unit-fold.ts new file mode 100644 index 0000000000..d8d2117731 --- /dev/null +++ b/packages/dsh-loopx-plugin/src/todo-unit-fold.ts @@ -0,0 +1,680 @@ +import { createHash, randomUUID } from 'node:crypto' +import type { AssistantMessage, ToolResultMessage, UserMessage } from '@deepseek-ai/dsh-llm' +import type { Session, SessionEvent, SessionSeq } from '@deepseek-ai/dsh-session' +import type { FileRunner, LoopXCommand } from './cli.ts' + +export const TODO_UNIT_ANCHOR_SCHEMA_VERSION = 'loopx_semantic_unit_anchor_v0' as const +export const TODO_UNIT_FOLD_SCHEMA_VERSION = 'loopx_semantic_unit_fold_swap_v0' as const +export const DEFAULT_TODO_FOLD_MIN_NET_SAVINGS_TOKENS = 64 +export const DEFAULT_TODO_FOLD_AMORTIZATION_DIVISOR = 20 +export const DEFAULT_TODO_FOLD_MAX_OBS_BYTES = 16_384 + +const BARE_SHA256_RE = /^[a-f0-9]{64}$/u +const DISALLOWED_SHELL_OPERATORS = new Set([';', '|', '&', '&&', '||', '>', '>>', '<', '<<', '<<<', '(', ')']) +const READ_ONLY_PROBES = new Set(['cat', 'head', 'tail', 'wc', 'ls', 'stat', 'pwd', 'rg', 'grep']) +const READ_ONLY_GIT_SUBCOMMANDS = new Set(['status', 'diff', 'log', 'show', 'rev-parse']) + +export interface LoopXTodoFoldMessageSource { + readonly kind: 'loopx-todo-fold' + readonly schemaVersion: typeof TODO_UNIT_FOLD_SCHEMA_VERSION + readonly form: 'recall' + readonly todoId: string + readonly turnInstanceId: string + readonly completionReceiptId: string + readonly completionSha256: string + readonly contextEpoch: string + readonly prefixDigest: string + readonly reclaimedSeqRange: readonly [SessionSeq, SessionSeq] +} + +declare module '@deepseek-ai/dsh-llm' { + interface MessageSourceMap { + 'loopx-todo-fold': LoopXTodoFoldMessageSource + } +} + +export interface TodoUnitFoldPolicy { + readonly enabled: boolean + readonly minNetSavingsTokens?: number | undefined + readonly coldPrefillAmortizationTokens?: number | undefined + readonly maxObsOutputBytes?: number | undefined + readonly rejectOnTruncation?: boolean | undefined +} + +export interface TodoUnitAnchorInput { + readonly todoId: string + readonly turnInstanceId: string + readonly contextEpoch: string + readonly anchorStepIndex: number + readonly anchorSurfaceSeq?: SessionSeq | undefined +} + +export interface TodoUnitAnchor { + readonly schemaVersion: typeof TODO_UNIT_ANCHOR_SCHEMA_VERSION + readonly todoId: string + readonly turnInstanceId: string + readonly contextEpoch: string + readonly anchorStepIndex: number + readonly prefixNodeCount: number + readonly prefixSurfaceSeqs: readonly SessionSeq[] + readonly anchorSurfaceSeq?: SessionSeq | undefined + readonly prefixDigest: string + readonly anchorSha256: string +} + +export interface TodoUnitSourceRef { + readonly path: string + readonly sha256: string +} + +export interface TodoUnitCompletionReceipt { + readonly todoId: string + readonly completionReceiptId: string + readonly exitCode: number + readonly sha256: string + readonly failureFacts: readonly string[] + readonly openObligations: readonly string[] + readonly sourceRef: TodoUnitSourceRef +} + +export interface TodoUnitObsNextCommand { + readonly command: string | readonly string[] + readonly initiator?: string | undefined + readonly exitCode?: number | null | undefined + readonly output?: string | undefined + readonly timedOut?: boolean | undefined + readonly truncated?: boolean | undefined + readonly latencyMs?: number | undefined + readonly rejectOnTruncation?: boolean | undefined +} + +export interface TodoUnitFoldRequest { + readonly todoId: string + readonly turnInstanceId: string + readonly contextEpoch: string + readonly nowStepIndex: number + readonly anchor?: TodoUnitAnchor | undefined + readonly completionReceipt?: TodoUnitCompletionReceipt | undefined + readonly obsNextCmd?: TodoUnitObsNextCommand | undefined + readonly baselineTokens?: number | undefined + readonly replacementTokens?: number | undefined + readonly quiescentBoundary?: boolean | undefined + readonly failureFacts?: readonly string[] | undefined + readonly openObligations?: readonly string[] | undefined +} + +export interface TodoUnitReceiptMu { + readonly trustLevel: 'tool' + readonly todoId: string + readonly completionReceiptId: string + readonly sha256: string + readonly turnInstanceId: string + readonly contextEpoch: string + readonly prefixDigest: string + readonly reclaimRange: readonly [number, number] + readonly reclaimSeqRange: readonly [SessionSeq, SessionSeq] + readonly exitCode: number + readonly failureFacts: readonly string[] + readonly openObligations: readonly string[] + readonly sourceRef: TodoUnitSourceRef +} + +export interface TodoUnitFoldOutcome { + readonly schemaVersion: typeof TODO_UNIT_FOLD_SCHEMA_VERSION + readonly operator: 'FoldToReceipt' | 'KeepRaw' + readonly status: 'committed' | 'fallback_keep_raw' | 'disabled' + readonly fallbackReason: string | null + readonly preservesRawState: boolean + readonly preservesPrefixKv: boolean + readonly todoId: string + readonly turnInstanceId: string + readonly contextEpoch: string + readonly prefixDigest: string | null + readonly reclaimRange: readonly [number, number] | null + readonly reclaimSeqRange: readonly [SessionSeq, SessionSeq] | null + readonly foldedEventSeq: SessionSeq | null + readonly receiptMu: TodoUnitReceiptMu | null + readonly obsNextCmd: { + readonly allowed: boolean + readonly exitCode: number | null + readonly truncated: boolean + readonly output: string | null + } | null + readonly replacementText: string | null + readonly preservedFailureFacts: readonly string[] + readonly preservedOpenObligations: readonly string[] + readonly baselineTokens: number | null + readonly replacementTokens: number | null + readonly netSavingsTokens: number | null + readonly amortizedNetSavingsTokens: number | null + readonly errorObservation: string | null +} + +function sha256Hex(text: string): string { + return createHash('sha256').update(text, 'utf8').digest('hex') +} + +export function deriveMessagesPrefixDigest( + session: Pick, + prefixCount: number, +): string { + const nodes = session.surface.nodes.slice(0, prefixCount) + const messages = session.deriveMessages().slice(0, prefixCount) + return sha256Hex(JSON.stringify({ nodes, messages })) +} + +function approximateTokens(text: string): number { + const bytes = Buffer.byteLength(text, 'utf8') + return bytes === 0 ? 0 : Math.ceil(bytes / 4) +} + +function cleanFacts(values: readonly string[] | undefined, limit: number): string[] { + if (!Array.isArray(values)) return [] + const seen = new Set() + const out: string[] = [] + for (const item of values) { + if (typeof item !== 'string') continue + const trimmed = item.trim() + if (!trimmed) continue + const bounded = trimmed.length > 512 ? `${trimmed.slice(0, 509)}...` : trimmed + if (seen.has(bounded)) continue + seen.add(bounded) + out.push(bounded) + if (out.length >= limit) break + } + return out +} + +function splitCommandTokens(rawCommand: string | readonly string[]): string[] | null { + if (Array.isArray(rawCommand)) { + const argv: string[] = [] + for (const entry of rawCommand) { + if (typeof entry !== 'string' || !entry.trim()) return null + argv.push(entry) + } + return argv.length > 0 ? argv : null + } + if (typeof rawCommand !== 'string') return null + const trimmed = rawCommand.trim() + if (!trimmed) return null + const parts = trimmed.split(/\s+/u) + return parts.length > 0 ? parts : null +} + +function validateReadOnlyObsCommand(command: string | readonly string[], initiator: string): { + allowed: boolean + reason: string | null + argv: string[] +} { + if (initiator === 'history_view_policy' || initiator === 'passive_plugin') { + return { allowed: false, reason: 'passive_plugin_blocked', argv: [] } + } + const argv = splitCommandTokens(command) + if (!argv) return { allowed: false, reason: 'missing_prefetch_command', argv: [] } + for (const tok of argv) { + if (tok.includes('\n') || tok.includes('\r') || tok.includes('\0') || DISALLOWED_SHELL_OPERATORS.has(tok)) { + return { allowed: false, reason: 'shell_metacharacters_disallowed', argv: [] } + } + if (tok === '--execute' || tok === '--spend' || tok === '--apply') { + return { allowed: false, reason: 'mutating_flag_disallowed', argv: [] } + } + } + const head = argv[0]?.split('/').pop() ?? '' + if (head === 'git') { + const sub = argv.slice(1).find(tok => !tok.startsWith('-')) ?? '' + if (!READ_ONLY_GIT_SUBCOMMANDS.has(sub)) { + return { allowed: false, reason: 'disallowed_git_command', argv: [] } + } + return { allowed: true, reason: null, argv } + } + if (READ_ONLY_PROBES.has(head)) { + return { allowed: true, reason: null, argv } + } + if ((head === 'loopx' || head === 'python' || head === 'python3') && argv.includes('--readonly')) { + return { allowed: true, reason: null, argv } + } + if (head === 'loopx' && argv.some((tok, idx) => tok === 'quota' && argv[idx + 1] === 'context-read')) { + return { allowed: true, reason: null, argv } + } + return { allowed: false, reason: 'disallowed_prefetch_command', argv: [] } +} + +function toolCallIdsFromAssistantMessage(message: AssistantMessage): string[] { + const ids: string[] = [] + for (const block of message.content) { + if (typeof block !== 'object' || block === null) continue + const candidate = block as { type?: unknown; id?: unknown; callId?: unknown } + if (candidate.type !== 'tool-call') continue + const callId = typeof candidate.id === 'string' + ? candidate.id + : typeof candidate.callId === 'string' + ? candidate.callId + : '' + if (callId) ids.push(callId) + } + return ids +} + +export function hasValidDshToolCallPairing( + session: Pick, + prefixCount: number, +): boolean { + const nodes = session.surface.nodes + if (prefixCount < 0 || prefixCount > nodes.length) return false + const events = session.snapshotEvents() + const eventBySeq = new Map() + for (const ev of events) { + eventBySeq.set(ev.seq, ev) + } + const retainedSet = new Set(nodes.slice(0, prefixCount)) + const shadowedSet = new Set(nodes.slice(prefixCount)) + + const callToTurnStep = new Map() + const assistantCallsByGroup = new Map() + const resultSeqByCallId = new Map() + + for (const ev of events) { + if (ev.type === 'tool/call') { + const key = `${ev.data.turn}:${ev.data.step}` + callToTurnStep.set(ev.data.callId, key) + } else if (ev.type === 'assistant/message') { + if (!retainedSet.has(ev.seq) && !shadowedSet.has(ev.seq)) continue + const key = `${ev.data.turn}:${ev.data.step}` + const msg = session.deriveEventMessage(ev) as AssistantMessage | null + const blockIds = msg ? toolCallIdsFromAssistantMessage(msg) : [] + if (blockIds.length > 0) { + assistantCallsByGroup.set(key, blockIds) + for (const id of blockIds) { + callToTurnStep.set(id, key) + } + } + } else if (ev.type === 'tool/result') { + if (!retainedSet.has(ev.seq) && !shadowedSet.has(ev.seq)) continue + resultSeqByCallId.set(ev.data.message.toolCallId, ev.seq) + } + } + + for (const seq of nodes) { + const ev = eventBySeq.get(seq) + if (!ev) return false + const inShadowed = shadowedSet.has(seq) + if (ev.type === 'assistant/message') { + const key = `${ev.data.turn}:${ev.data.step}` + const blockIds = assistantCallsByGroup.get(key) ?? [] + for (const callId of blockIds) { + const resSeq = resultSeqByCallId.get(callId) + if (resSeq === undefined) return false + if (shadowedSet.has(resSeq) !== inShadowed) return false + } + } else if (ev.type === 'tool/result') { + const callId = (ev.data.message as ToolResultMessage).toolCallId + const groupKey = callToTurnStep.get(callId) + let matchedAssistantInRetained = false + let matchedAssistantInShadowed = false + for (const otherSeq of nodes) { + const other = eventBySeq.get(otherSeq) + if (other?.type !== 'assistant/message') continue + if (`${other.data.turn}:${other.data.step}` === groupKey) { + if (shadowedSet.has(otherSeq)) matchedAssistantInShadowed = true + else matchedAssistantInRetained = true + } + } + if (inShadowed && matchedAssistantInRetained) return false + if (!inShadowed && matchedAssistantInShadowed) return false + if (!matchedAssistantInRetained && !matchedAssistantInShadowed) return false + } + } + + const firstShadowedSeq = nodes[prefixCount] ?? Number.MAX_SAFE_INTEGER + for (const [callId, groupKey] of callToTurnStep.entries()) { + const assistantLive = nodes.some(seq => { + const ev = eventBySeq.get(seq) + return ev?.type === 'assistant/message' && `${ev.data.turn}:${ev.data.step}` === groupKey + }) + const suffixCall = events.some( + ev => ev.type === 'tool/call' && ev.data.callId === callId && ev.seq >= firstShadowedSeq, + ) + if ((assistantLive || suffixCall) && !resultSeqByCallId.has(callId)) return false + } + return true +} + +export function recordDshTodoUnitAnchor( + session: Pick, + input: TodoUnitAnchorInput, +): TodoUnitAnchor { + if (!input.todoId.trim()) throw new Error('todoId must be non-empty') + if (!input.turnInstanceId.trim()) throw new Error('turnInstanceId must be non-empty') + if (!input.contextEpoch.trim()) throw new Error('contextEpoch must be non-empty') + if (!Number.isSafeInteger(input.anchorStepIndex) || input.anchorStepIndex < 0) { + throw new Error('anchorStepIndex must be a non-negative integer') + } + const nodes = session.surface.nodes + let prefixNodeCount = nodes.length + if (input.anchorSurfaceSeq !== undefined) { + const idx = nodes.indexOf(input.anchorSurfaceSeq) + if (idx < 0) throw new Error('anchorSurfaceSeq not found in current session surface') + prefixNodeCount = idx + } + const prefixSurfaceSeqs = nodes.slice(0, prefixNodeCount) + const prefixDigest = deriveMessagesPrefixDigest(session, prefixNodeCount) + const core = { + schemaVersion: TODO_UNIT_ANCHOR_SCHEMA_VERSION, + todoId: input.todoId.trim(), + turnInstanceId: input.turnInstanceId.trim(), + contextEpoch: input.contextEpoch.trim(), + anchorStepIndex: input.anchorStepIndex, + prefixNodeCount, + prefixSurfaceSeqs, + ...(input.anchorSurfaceSeq !== undefined ? { anchorSurfaceSeq: input.anchorSurfaceSeq } : {}), + prefixDigest, + } + const anchorSha256 = sha256Hex(JSON.stringify(core)) + return { ...core, anchorSha256 } +} + +export function applyTodoUnitFoldAndPrefetch( + session: Session, + policy: TodoUnitFoldPolicy | undefined, + request: TodoUnitFoldRequest, + storedAnchor?: TodoUnitAnchor, +): TodoUnitFoldOutcome { + const receipt = request.completionReceipt + const preservedFailureFacts = cleanFacts(receipt?.failureFacts ?? request.failureFacts, 32) + const preservedOpenObligations = cleanFacts(receipt?.openObligations ?? request.openObligations, 64) + + const keepRawOutcome = ( + status: 'disabled' | 'fallback_keep_raw', + reason: string, + baselineTokens: number | null = request.baselineTokens ?? null, + replacementTokens: number | null = request.replacementTokens ?? null, + prefixDigest: string | null = null, + obsMeta: TodoUnitFoldOutcome['obsNextCmd'] = null, + ): TodoUnitFoldOutcome => ({ + schemaVersion: TODO_UNIT_FOLD_SCHEMA_VERSION, + operator: 'KeepRaw', + status, + fallbackReason: reason, + preservesRawState: true, + preservesPrefixKv: true, + todoId: request.todoId, + turnInstanceId: request.turnInstanceId, + contextEpoch: request.contextEpoch, + prefixDigest, + reclaimRange: null, + reclaimSeqRange: null, + foldedEventSeq: null, + receiptMu: null, + obsNextCmd: obsMeta, + replacementText: null, + preservedFailureFacts, + preservedOpenObligations, + baselineTokens, + replacementTokens, + netSavingsTokens: null, + amortizedNetSavingsTokens: null, + errorObservation: status === 'disabled' + ? null + : `Todo-unit fold rolled back atomically to KeepRaw (${reason}).`, + }) + + if (policy?.enabled !== true) { + return keepRawOutcome('disabled', 'disabled') + } + if (request.quiescentBoundary === false) { + return keepRawOutcome('fallback_keep_raw', 'non_quiescent_boundary') + } + + const anchor = request.anchor ?? storedAnchor + if (!anchor) { + return keepRawOutcome('fallback_keep_raw', 'missing_anchor') + } + const expectedAnchorCore = { + schemaVersion: anchor.schemaVersion, + todoId: anchor.todoId, + turnInstanceId: anchor.turnInstanceId, + contextEpoch: anchor.contextEpoch, + anchorStepIndex: anchor.anchorStepIndex, + prefixNodeCount: anchor.prefixNodeCount, + prefixSurfaceSeqs: anchor.prefixSurfaceSeqs, + ...(anchor.anchorSurfaceSeq !== undefined ? { anchorSurfaceSeq: anchor.anchorSurfaceSeq } : {}), + prefixDigest: anchor.prefixDigest, + } + if (anchor.anchorSha256 !== sha256Hex(JSON.stringify(expectedAnchorCore))) { + return keepRawOutcome('fallback_keep_raw', 'anchor_digest_mismatch') + } + if (anchor.todoId !== request.todoId) { + return keepRawOutcome('fallback_keep_raw', 'todo_id_mismatch') + } + if (anchor.turnInstanceId !== request.turnInstanceId) { + return keepRawOutcome('fallback_keep_raw', 'turn_instance_mismatch') + } + if (anchor.contextEpoch !== request.contextEpoch) { + return keepRawOutcome('fallback_keep_raw', 'context_epoch_mismatch') + } + if (!Number.isSafeInteger(request.nowStepIndex) || request.nowStepIndex < anchor.anchorStepIndex) { + return keepRawOutcome('fallback_keep_raw', 'invalid_reclaim_range') + } + + const nodes = session.surface.nodes + if (nodes.length <= anchor.prefixNodeCount) { + return keepRawOutcome('fallback_keep_raw', 'empty_reclaim_suffix') + } + const currentPrefixSeqs = nodes.slice(0, anchor.prefixNodeCount) + if ( + currentPrefixSeqs.length !== anchor.prefixSurfaceSeqs.length + || currentPrefixSeqs.some((seq, i) => seq !== anchor.prefixSurfaceSeqs[i]) + ) { + return keepRawOutcome('fallback_keep_raw', 'prefix_kv_not_preserved') + } + const livePrefixDigest = deriveMessagesPrefixDigest(session, anchor.prefixNodeCount) + if (livePrefixDigest !== anchor.prefixDigest) { + return keepRawOutcome('fallback_keep_raw', 'prefix_digest_mismatch', undefined, undefined, livePrefixDigest) + } + + const shadowedSeqs = nodes.slice(anchor.prefixNodeCount) + const startSeq = shadowedSeqs[0] + const endSeq = shadowedSeqs.at(-1) + if (startSeq === undefined || endSeq === undefined) { + return keepRawOutcome('fallback_keep_raw', 'empty_reclaim_suffix', undefined, undefined, livePrefixDigest) + } + if (anchor.anchorSurfaceSeq !== undefined && anchor.anchorSurfaceSeq !== startSeq) { + return keepRawOutcome('fallback_keep_raw', 'invalid_reclaim_range', undefined, undefined, livePrefixDigest) + } + if (anchor.prefixNodeCount === 0) { + const firstEv = session.snapshotEvents().find(ev => ev.seq === startSeq) + if (firstEv?.type === 'system/message') { + return keepRawOutcome('fallback_keep_raw', 'prefix_kv_not_preserved', undefined, undefined, livePrefixDigest) + } + } + if (!hasValidDshToolCallPairing(session, anchor.prefixNodeCount)) { + return keepRawOutcome('fallback_keep_raw', 'unpaired_tool_calls', undefined, undefined, livePrefixDigest) + } + + if (!receipt) { + return keepRawOutcome('fallback_keep_raw', 'missing_completion_receipt', undefined, undefined, livePrefixDigest) + } + if (!receipt.todoId.trim() || !receipt.completionReceiptId.trim()) { + return keepRawOutcome('fallback_keep_raw', 'invalid_completion_receipt', undefined, undefined, livePrefixDigest) + } + if (receipt.todoId.trim() !== request.todoId) { + return keepRawOutcome('fallback_keep_raw', 'receipt_todo_mismatch', undefined, undefined, livePrefixDigest) + } + if (!BARE_SHA256_RE.test(receipt.sha256)) { + return keepRawOutcome('fallback_keep_raw', 'invalid_completion_sha256', undefined, undefined, livePrefixDigest) + } + if (!receipt.sourceRef.path.trim() || !BARE_SHA256_RE.test(receipt.sourceRef.sha256)) { + return keepRawOutcome('fallback_keep_raw', 'missing_source_ref', undefined, undefined, livePrefixDigest) + } + if (!Number.isSafeInteger(receipt.exitCode) || receipt.exitCode !== 0) { + return keepRawOutcome('fallback_keep_raw', 'command_error', undefined, undefined, livePrefixDigest) + } + + const maxObsBytes = policy.maxObsOutputBytes ?? DEFAULT_TODO_FOLD_MAX_OBS_BYTES + const rejectTruncation = policy.rejectOnTruncation ?? true + let obsMeta: TodoUnitFoldOutcome['obsNextCmd'] = null + let obsText: string | null = null + if (request.obsNextCmd !== undefined) { + const obs = request.obsNextCmd + const safety = validateReadOnlyObsCommand(obs.command, obs.initiator ?? 'turn_driver') + const exitCode = obs.exitCode ?? null + const truncated = obs.truncated === true + const output = obs.output ?? '' + let obsFail: string | null = null + if (!safety.allowed) obsFail = safety.reason + else if (obs.timedOut === true) obsFail = 'obs_command_timeout' + else if (exitCode === null || exitCode !== 0) obsFail = 'command_error' + else if ((obs.rejectOnTruncation ?? rejectTruncation) && truncated) obsFail = 'output_truncated' + else if (Buffer.byteLength(output, 'utf8') > maxObsBytes) obsFail = 'output_overflow' + obsMeta = { + allowed: safety.allowed, + exitCode, + truncated, + output: obsFail === null ? output : null, + } + if (obsFail !== null) { + return keepRawOutcome('fallback_keep_raw', obsFail, undefined, undefined, livePrefixDigest, obsMeta) + } + obsText = output.length > 0 ? output : null + } + + const reclaimRange: readonly [number, number] = [anchor.anchorStepIndex, request.nowStepIndex] + const reclaimSeqRange: readonly [SessionSeq, SessionSeq] = [startSeq, endSeq] + const receiptMu: TodoUnitReceiptMu = { + trustLevel: 'tool', + todoId: request.todoId, + completionReceiptId: receipt.completionReceiptId.trim(), + sha256: receipt.sha256, + turnInstanceId: request.turnInstanceId, + contextEpoch: request.contextEpoch, + prefixDigest: livePrefixDigest, + reclaimRange, + reclaimSeqRange, + exitCode: receipt.exitCode, + failureFacts: preservedFailureFacts, + openObligations: preservedOpenObligations, + sourceRef: receipt.sourceRef, + } + const lines = [ + '[Semantic-Unit Fold Receipt mu | trust=tool]', + `todo_id: ${receiptMu.todoId}`, + `completion_receipt_id: ${receiptMu.completionReceiptId}`, + `completion_sha256: ${receiptMu.sha256}`, + `turn_instance_id: ${receiptMu.turnInstanceId}`, + `context_epoch: ${receiptMu.contextEpoch}`, + `prefix_digest: ${receiptMu.prefixDigest}`, + `reclaim_range: [${reclaimRange[0]}..${reclaimRange[1]}]`, + `exit_code: ${receiptMu.exitCode}`, + `source_ref: ${receiptMu.sourceRef.path} (sha256:${receiptMu.sourceRef.sha256})`, + `failure_facts: ${JSON.stringify(receiptMu.failureFacts)}`, + `open_obligations: ${JSON.stringify(receiptMu.openObligations)}`, + ] + if (obsText !== null) { + lines.push('--- obs_next_cmd ---', obsText) + } + const replacementText = lines.join('\n') + + const suffixDerivedMessages = session.deriveMessages().slice(anchor.prefixNodeCount) + const baselineTokens = request.baselineTokens ?? approximateTokens(JSON.stringify(suffixDerivedMessages)) + const replacementTokens = request.replacementTokens ?? approximateTokens(replacementText) + const minSavings = policy.minNetSavingsTokens ?? DEFAULT_TODO_FOLD_MIN_NET_SAVINGS_TOKENS + const amortization = + policy.coldPrefillAmortizationTokens + ?? Math.ceil(replacementTokens / DEFAULT_TODO_FOLD_AMORTIZATION_DIVISOR) + const rawNet = baselineTokens - replacementTokens + const amortizedNet = rawNet - amortization + if (rawNet <= 0 || amortizedNet < minSavings) { + return keepRawOutcome( + 'fallback_keep_raw', + 'negative_net_savings', + baselineTokens, + replacementTokens, + livePrefixDigest, + obsMeta, + ) + } + + const foldMessage: UserMessage = { + id: randomUUID() as UserMessage['id'], + role: 'user', + content: [{ type: 'text', text: replacementText }], + source: { + kind: 'loopx-todo-fold', + schemaVersion: TODO_UNIT_FOLD_SCHEMA_VERSION, + form: 'recall', + todoId: receiptMu.todoId, + turnInstanceId: receiptMu.turnInstanceId, + completionReceiptId: receiptMu.completionReceiptId, + completionSha256: receiptMu.sha256, + contextEpoch: receiptMu.contextEpoch, + prefixDigest: livePrefixDigest, + reclaimedSeqRange: reclaimSeqRange, + }, + } + + let committedEvent: SessionEvent<'user/message'> + try { + committedEvent = session.append('user/message', foldMessage, { + surfaceOp: { op: 'replace', startSeq, endSeq }, + sourceEventSeqs: [...shadowedSeqs], + }) + } catch { + return keepRawOutcome( + 'fallback_keep_raw', + 'surface_replace_rejected', + baselineTokens, + replacementTokens, + livePrefixDigest, + obsMeta, + ) + } + + const postPrefixDigest = deriveMessagesPrefixDigest(session, anchor.prefixNodeCount) + const prefixPreserved = postPrefixDigest === anchor.prefixDigest + return { + schemaVersion: TODO_UNIT_FOLD_SCHEMA_VERSION, + operator: 'FoldToReceipt', + status: 'committed', + fallbackReason: null, + preservesRawState: false, + preservesPrefixKv: prefixPreserved, + todoId: request.todoId, + turnInstanceId: request.turnInstanceId, + contextEpoch: request.contextEpoch, + prefixDigest: postPrefixDigest, + reclaimRange, + reclaimSeqRange, + foldedEventSeq: committedEvent.seq, + receiptMu, + obsNextCmd: obsMeta, + replacementText, + preservedFailureFacts, + preservedOpenObligations, + baselineTokens, + replacementTokens, + netSavingsTokens: rawNet, + amortizedNetSavingsTokens: amortizedNet, + errorObservation: null, + } +} + +export type TodoUnitObsRunner = ( + command: readonly string[], + cwd: string, +) => Promise<{ + readonly exitCode: number | null + readonly output: string + readonly timedOut?: boolean | undefined + readonly truncated?: boolean | undefined +}> + +export function validateTodoUnitObsForExecution( + obs: TodoUnitObsNextCommand | undefined, +): readonly string[] | null { + if (!obs) return null + if (obs.output !== undefined && obs.exitCode !== undefined) return null + const safety = validateReadOnlyObsCommand(obs.command, obs.initiator ?? 'turn_driver') + return safety.allowed ? safety.argv : null +} + +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 new file mode 100644 index 0000000000..e25f051ffb --- /dev/null +++ b/packages/dsh-loopx-plugin/tests/todo-unit-fold.spec.ts @@ -0,0 +1,422 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' +import type { MessageId, ToolCallId, UserMessage } from '@deepseek-ai/dsh-llm' +import { SessionStore } from '@deepseek-ai/dsh-session' +import type { + Session, + SessionSeq, +} from '@deepseek-ai/dsh-session' +import { LoopXContinuationDriver } from '../src/driver.ts' +import type { + TodoUnitCompletionReceipt, + TodoUnitObsRunner, +} from '../src/driver.ts' +import { deriveMessagesPrefixDigest } from '../src/todo-unit-fold.ts' + +async function createRealSessionHarness(cwd: string) { + const ctx = new Context() + const storeFiber = await ctx.plugin(SessionStore) + const sessionId = 'session-todo-fold-real' as Agent['id'] + const session = storeFiber.ctx.sessions.create(sessionId, { meta: { cwd } }) + let status: AgentStatus = 'idle' + const agent = { + id: sessionId, + options: {}, + session, + inbox: { nextTurn: [], nextStep: [], hasPending: false, remove: () => false }, + ctx, + get status() { return status }, + cancel() {}, + whenIdle: async () => {}, + runMaintenance: async (fn: (signal: AbortSignal) => Promise) => fn(new AbortController().signal), + send() {}, + followup() {}, + steer() {}, + inject() {}, + } as unknown as Agent + + return { + ctx, + session, + agent, + setStatus(next: AgentStatus) { status = next }, + async dispose() { + await storeFiber.dispose() + await ctx.fiber.dispose() + }, + } +} + +function appendPrefixQ(session: Session): SessionSeq[] { + session.append('system/message', { + turn: 1, + step: 1, + message: { + id: 'sys-1' as MessageId, + role: 'system', + content: [{ type: 'text', text: 'System instructions.' }], + source: { kind: 'system-prompt' }, + }, + }, { surfaceOp: 'append' }) + + session.append('user/message', { + id: 'user-q-1' as UserMessage['id'], + role: 'user', + content: [{ type: 'text', text: 'Parent goal prompt Q.' }], + source: { kind: 'user' }, + }, { surfaceOp: 'append' }) + + const callId = 'call-q-1' as ToolCallId + session.append('tool/call', { + turn: 1, + step: 1, + callId, + name: 'read_file', + arguments: '{"path":"README.md"}', + }) + session.append('assistant/message', { + turn: 1, + step: 1, + message: { + id: 'asst-q-1' as MessageId, + role: 'assistant', + content: [{ type: 'tool-call', id: callId, name: 'read_file', arguments: '{"path":"README.md"}' } as unknown as { type: 'text'; text: string }], + source: { kind: 'model', provider: 'mock', model: 'mock-1' }, + }, + stream: [], + }, { surfaceOp: 'append' }) + session.append('tool/result', { + turn: 1, + step: 1, + message: { + id: 'res-q-1' as MessageId, + role: 'tool', + toolCallId: callId, + content: [{ type: 'text', text: 'README summary content.' }], + source: { kind: 'tool', callId }, + }, + }, { surfaceOp: 'append' }) + + return [...session.surface.nodes] +} + +function appendTodoExploratorySuffix(session: Session, suffixTag: string): SessionSeq[] { + const before = session.surface.nodes.length + const callId = `call-${suffixTag}-1` as ToolCallId + const bloat = `exploratory search output for ${suffixTag} `.repeat(80) + session.append('user/message', { + id: `user-${suffixTag}` as UserMessage['id'], + role: 'user', + content: [{ type: 'text', text: `Start Todo ${suffixTag}` }], + source: { kind: 'user' }, + }, { surfaceOp: 'append' }) + session.append('tool/call', { + turn: 2, + step: 1, + callId, + name: 'search', + arguments: '{"q":"loopx"}', + }) + session.append('assistant/message', { + turn: 2, + step: 1, + message: { + id: `asst-${suffixTag}-1` as MessageId, + role: 'assistant', + content: [{ type: 'tool-call', id: callId, name: 'search', arguments: '{"q":"loopx"}' } as unknown as { type: 'text'; text: string }], + source: { kind: 'model', provider: 'mock', model: 'mock-1' }, + }, + stream: [], + }, { surfaceOp: 'append' }) + session.append('tool/result', { + turn: 2, + step: 1, + message: { + id: `res-${suffixTag}-1` as MessageId, + role: 'tool', + toolCallId: callId, + content: [{ type: 'text', text: bloat }], + source: { kind: 'tool', callId }, + }, + }, { surfaceOp: 'append' }) + session.append('assistant/message', { + turn: 2, + step: 2, + message: { + id: `asst-${suffixTag}-2` as MessageId, + role: 'assistant', + content: [{ type: 'text', text: `Completed analysis for ${suffixTag}.` }], + source: { kind: 'model', provider: 'mock', model: 'mock-1' }, + }, + stream: [], + }, { surfaceOp: 'append' }) + return session.surface.nodes.slice(before) +} + +const VALID_RECEIPT: TodoUnitCompletionReceipt = { + todoId: 'todo-s1-1', + completionReceiptId: 'cqr-s1-1', + exitCode: 0, + sha256: 'a'.repeat(64), + failureFacts: ['earlier test warned on missing flag'], + openObligations: ['run downstream package verification'], + sourceRef: { path: 'captures/todo-s1-1.json', sha256: 'b'.repeat(64) }, +} + +describe('dsh-loopx-plugin Todo semantic-unit FoldAndPrefetch', () => { + it('stays strictly default-off with zero surface or KV prefix drift', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'dsh-fold-off-')) + const harness = await createRealSessionHarness(cwd) + try { + appendPrefixQ(harness.session) + appendTodoExploratorySuffix(harness.session, 'off') + const beforeNodes = [...harness.session.surface.nodes] + const beforeMessages = harness.session.deriveMessages() + + const driver = new LoopXContinuationDriver({ isLiveAgent: () => true }) + expect(driver.anchorTodoUnit(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-1', + anchorStepIndex: 2, + })).toBeNull() + + const outcome = await driver.onTodoUnitSettled(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-1', + nowStepIndex: 5, + completionReceipt: VALID_RECEIPT, + }) + expect(outcome.operator).toBe('KeepRaw') + expect(outcome.status).toBe('disabled') + expect(harness.session.surface.nodes).toEqual(beforeNodes) + expect(harness.session.deriveMessages()).toEqual(beforeMessages) + } finally { + await harness.dispose() + await rm(cwd, { recursive: true, force: true }) + } + }) + + it('pops contiguous exploratory suffix [anchor..now] -> [mu + Obs(next_cmd)] while keeping parent prefix Q byte-identical', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'dsh-fold-on-')) + const harness = await createRealSessionHarness(cwd) + try { + const prefixSeqs = appendPrefixQ(harness.session) + const prefixMessagesBefore = harness.session.deriveMessages() + const prefixDigestBefore = deriveMessagesPrefixDigest(harness.session, prefixSeqs.length) + + const obsRunner = vi.fn(async () => ({ + exitCode: 0, + output: 'NEXT_CMD_READY: clean git tree', + })) + const driver = new LoopXContinuationDriver({ + isLiveAgent: () => true, + todoUnitFold: { enabled: true, minNetSavingsTokens: 64 }, + runObsCommand: obsRunner, + }) + + const anchor = driver.anchorTodoUnit(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-dsh-1', + anchorStepIndex: 2, + }) + expect(anchor).not.toBeNull() + expect(anchor?.prefixDigest).toBe(prefixDigestBefore) + + const suffixSeqs = appendTodoExploratorySuffix(harness.session, 'fold') + expect(harness.session.surface.nodes).toEqual([...prefixSeqs, ...suffixSeqs]) + + const outcome = await driver.onTodoUnitSettled(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-dsh-1', + nowStepIndex: 6, + completionReceipt: VALID_RECEIPT, + obsNextCmd: { command: ['git', 'status', '--short'] }, + }) + + expect(outcome.operator).toBe('FoldToReceipt') + expect(outcome.status).toBe('committed') + expect(outcome.preservesPrefixKv).toBe(true) + expect(outcome.reclaimRange).toEqual([2, 6]) + expect(outcome.reclaimSeqRange).toEqual([suffixSeqs[0], suffixSeqs.at(-1)]) + expect(outcome.netSavingsTokens).toBeGreaterThan(200) + expect(obsRunner).toHaveBeenCalledTimes(1) + + // Parent prefix Q nodes and derived messages are byte-identical (KV cache intact). + expect(harness.session.surface.nodes.slice(0, prefixSeqs.length)).toEqual(prefixSeqs) + expect(harness.session.deriveMessages().slice(0, prefixSeqs.length)).toEqual(prefixMessagesBefore) + expect(deriveMessagesPrefixDigest(harness.session, prefixSeqs.length)).toBe(prefixDigestBefore) + + // Contiguous suffix replaced by exact single [mu + Obs(next_cmd)] node. + expect(harness.session.surface.nodes.length).toBe(prefixSeqs.length + 1) + const replacementMsg = harness.session.deriveMessages().at(-1) as UserMessage + expect(replacementMsg.role).toBe('user') + expect(replacementMsg.source.kind).toBe('loopx-todo-fold') + const blockText = (replacementMsg.content[0] as { type: 'text'; text: string }).text + expect(blockText).toContain('[Semantic-Unit Fold Receipt mu | trust=tool]') + expect(blockText).toContain('run downstream package verification') + expect(blockText).toContain('--- obs_next_cmd ---') + expect(blockText).toContain('NEXT_CMD_READY: clean git tree') + + // Idempotent duplicate settlement replays without running obsNextCmd again. + const replay = await driver.foldAndPrefetch(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-dsh-1', + nowStepIndex: 6, + completionReceipt: VALID_RECEIPT, + obsNextCmd: { command: ['git', 'status', '--short'] }, + }) + expect(replay.foldedEventSeq).toBe(outcome.foldedEventSeq) + expect(obsRunner).toHaveBeenCalledTimes(1) + } finally { + await harness.dispose() + await rm(cwd, { recursive: true, force: true }) + } + }) + + it('fails closed atomically to KeepRaw on unpaired tool-call cuts, missing receipt, obs error, negative savings, or busy agent', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'dsh-fold-fail-')) + const harness = await createRealSessionHarness(cwd) + try { + // Build parent prefix with an assistant tool-call whose tool/result lands AFTER the anchor cut! + harness.session.append('system/message', { + turn: 1, + step: 1, + message: { + id: 'sys-split' as MessageId, + role: 'system', + content: [{ type: 'text', text: 'System instructions.' }], + source: { kind: 'system-prompt' }, + }, + }, { surfaceOp: 'append' }) + const splitCallId = 'call-split' as ToolCallId + harness.session.append('tool/call', { + turn: 1, + step: 1, + callId: splitCallId, + name: 'probe', + arguments: '{}', + }) + harness.session.append('assistant/message', { + turn: 1, + step: 1, + message: { + id: 'asst-split' as MessageId, + role: 'assistant', + content: [{ type: 'tool-call', id: splitCallId, name: 'probe', arguments: '{}' } as unknown as { type: 'text'; text: string }], + source: { kind: 'model', provider: 'mock', model: 'mock-1' }, + }, + stream: [], + }, { surfaceOp: 'append' }) + + const obsRunner = vi.fn(async () => ({ exitCode: 1, output: 'boom' })) + const driver = new LoopXContinuationDriver({ + isLiveAgent: () => true, + todoUnitFold: { enabled: true, minNetSavingsTokens: 64 }, + runObsCommand: obsRunner, + }) + + // Anchor BEFORE matching tool/result lands -> cut splits assistant tool-call from tool/result! + driver.anchorTodoUnit(harness.agent, { + todoId: 'todo-split', + turnInstanceId: 'turn-split', + contextEpoch: 'epoch-split', + anchorStepIndex: 1, + }) + harness.session.append('tool/result', { + turn: 1, + step: 1, + message: { + id: 'res-split' as MessageId, + role: 'tool', + toolCallId: splitCallId, + content: [{ type: 'text', text: 'huge result '.repeat(100) }], + source: { kind: 'tool', callId: splitCallId }, + }, + }, { surfaceOp: 'append' }) + const beforeNodes = [...harness.session.surface.nodes] + const splitRes = await driver.onTodoUnitSettled(harness.agent, { + todoId: 'todo-split', + turnInstanceId: 'turn-split', + contextEpoch: 'epoch-split', + nowStepIndex: 3, + completionReceipt: { ...VALID_RECEIPT, todoId: 'todo-split' }, + obsNextCmd: { command: ['git', 'status'] }, + }) + expect(splitRes.operator).toBe('KeepRaw') + expect(splitRes.fallbackReason).toBe('unpaired_tool_calls') + expect(harness.session.surface.nodes).toEqual(beforeNodes) + expect(obsRunner).not.toHaveBeenCalled() + + // Now re-anchor AFTER split pair closes cleanly -> test missing receipt, busy agent, obs failure, negative savings. + driver.anchorTodoUnit(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-clean', + anchorStepIndex: 3, + }) + appendTodoExploratorySuffix(harness.session, 'clean') + const cleanNodesBefore = [...harness.session.surface.nodes] + + harness.setStatus('running') + const busyRes = await driver.onTodoUnitSettled(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-clean', + nowStepIndex: 6, + completionReceipt: VALID_RECEIPT, + }) + expect(busyRes.operator).toBe('KeepRaw') + expect(busyRes.fallbackReason).toBe('non_quiescent_boundary') + expect(harness.session.surface.nodes).toEqual(cleanNodesBefore) + harness.setStatus('idle') + + const missingRes = await driver.onTodoUnitSettled(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-clean', + nowStepIndex: 6, + }) + expect(missingRes.operator).toBe('KeepRaw') + expect(missingRes.fallbackReason).toBe('missing_completion_receipt') + expect(harness.session.surface.nodes).toEqual(cleanNodesBefore) + + const obsErrRes = await driver.onTodoUnitSettled(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-clean', + nowStepIndex: 6, + completionReceipt: VALID_RECEIPT, + obsNextCmd: { command: ['git', 'status'] }, + }) + expect(obsErrRes.operator).toBe('KeepRaw') + expect(obsErrRes.fallbackReason).toBe('command_error') + expect(obsRunner).toHaveBeenCalledTimes(1) + expect(harness.session.surface.nodes).toEqual(cleanNodesBefore) + + const negSavingsRes = await driver.onTodoUnitSettled(harness.agent, { + todoId: 'todo-s1-1', + turnInstanceId: 'turn-s1-1', + contextEpoch: 'epoch-clean', + nowStepIndex: 6, + completionReceipt: VALID_RECEIPT, + baselineTokens: 200, + replacementTokens: 250, + }) + expect(negSavingsRes.operator).toBe('KeepRaw') + expect(negSavingsRes.fallbackReason).toBe('negative_net_savings') + expect(harness.session.surface.nodes).toEqual(cleanNodesBefore) + } 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 new file mode 100644 index 0000000000..dc63ee7941 --- /dev/null +++ b/tests/control_plane/test_semantic_unit_fold_hooks.py @@ -0,0 +1,290 @@ +"""Tests for S1-A Todo semantic-unit anchor, FoldToReceipt, KeepRaw rollback, and codex_context hooks.""" +from __future__ import annotations + +from collections.abc import Mapping +from pathlib import Path + +import pytest + +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 + + +def _write_source_file(path: Path, text: str) -> dict[str, str]: + import hashlib + + path.write_text(text, encoding="utf-8") + return { + "path": str(path), + "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + } + + +def test_turn_envelope_semantic_unit_anchor_and_fold_contract(tmp_path: Path) -> None: + prefix_digest = "a" * 64 + source_ref = _write_source_file(tmp_path / "todo-capture.json", '{"todo":"ok"}\n') + anchor = record_semantic_unit_anchor( + todo_id="todo_alpha", + turn_instance_id="turn_alpha", + anchor_step_index=3, + anchor_surface_seq=8, + prefix_digest=prefix_digest, + context_epoch="epoch-alpha", + ) + assert anchor["schema_version"] == "loopx_semantic_unit_anchor_v0" + assert anchor["todo_id"] == "todo_alpha" + + receipt = { + "todo_id": "todo_alpha", + "completion_receipt_id": "cqr_alpha", + "exit_code": 0, + "sha256": "b" * 64, + "failure_facts": ["earlier lint failure fixed"], + "open_obligations": ["confirm caller parity"], + "source_ref": source_ref, + } + committed = build_semantic_unit_fold_swap( + enabled=True, + anchor=anchor, + todo_id="todo_alpha", + turn_instance_id="turn_alpha", + context_epoch="epoch-alpha", + prefix_digest=prefix_digest, + now_step_index=10, + now_surface_seq=22, + completion_receipt=receipt, + baseline_tokens=1600, + replacement_tokens=140, + tokenizer={"name": "tiktoken", "encoding": "o200k_base"}, + obs_next_cmd={"command": ["cat", str(tmp_path / "todo-capture.json")], "exit_code": 0, "output": '{"todo":"ok"}'}, + ) + assert committed["operator"] == "FoldToReceipt" + assert committed["reclaim_range"] == [3, 10] + assert committed["preserves_prefix_kv"] is True + assert committed["amortized_net_savings_tokens"] == 1453 + + rolled_back = build_semantic_unit_fold_swap( + enabled=True, + anchor=anchor, + todo_id="todo_alpha", + turn_instance_id="turn_alpha", + context_epoch="epoch-alpha", + prefix_digest=prefix_digest, + now_step_index=10, + now_surface_seq=22, + completion_receipt=None, + baseline_tokens=1600, + replacement_tokens=140, + tokenizer={"name": "tiktoken", "encoding": "o200k_base"}, + failure_facts=["keep raw fact"], + open_obligations=["keep raw obligation"], + ) + assert rolled_back["operator"] == "KeepRaw" + assert rolled_back["fallback_reason"] == "missing_completion_receipt" + assert rolled_back["preserves_raw_state"] is True + assert rolled_back["preserved_failure_facts"] == ["keep raw fact"] + + +@pytest.mark.parametrize("hook_name", ["PostToolUse", "PreCompact", "PostCompact", "SessionStart"]) +def test_codex_context_hook_semantic_unit_fold_emits_consumes_and_replays_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, hook_name: str, +) -> None: + ctx_dir = tmp_path / f"codex-{hook_name}" + ctx_dir.mkdir(mode=0o700) + # Ordinary PostToolUse without semantic-unit payloads stays a zero-overhead no-op. + assert codex_context.codex_context_hook( + str(ctx_dir), + {"session_id": "s1", "cwd": str(tmp_path), "hook_event_name": "PostToolUse", "tool_name": "bash"}, + ) == {} + + codex_context._save( + ctx_dir, + { + "session_id": "s1", + "cwd": str(tmp_path), + "context_epoch": "epoch-hook-unit", + }, + ) + prefix_digest = "e" * 64 + source_ref = _write_source_file(tmp_path / "unit-result.json", '{"status":"done"}\n') + obs_target = tmp_path / "next-cmd.txt" + obs_target.write_text("NEXT_OBS=ready\n", encoding="utf-8") + + # Anchor on PostToolUse boundary. + anchor_res = codex_context.codex_context_hook( + str(ctx_dir), + { + "session_id": "s1", + "cwd": str(tmp_path), + "hook_event_name": "PostToolUse", + "semantic_unit_anchor": { + "todo_id": "todo_hook_1", + "turn_instance_id": "turn_hook_1", + "anchor_step_index": 2, + "anchor_surface_seq": 5, + "prefix_digest": prefix_digest, + }, + }, + ) + assert anchor_res["hookSpecificOutput"]["semanticUnitAnchor"]["todo_id"] == "todo_hook_1" + + from loopx.control_plane.turn_driver import semantic_unit_hook as hook_mod + + exec_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]: + exec_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) + + fold_event = { + "session_id": "s1", + "cwd": str(tmp_path), + "hook_event_name": hook_name, + **({"source": "compact"} if hook_name == "SessionStart" else {}), + "semantic_unit_fold": { + "enabled": True, + "todo_id": "todo_hook_1", + "turn_instance_id": "turn_hook_1", + "prefix_digest": prefix_digest, + "now_step_index": 9, + "now_surface_seq": 19, + "baseline_text": "exploratory turn step data " * 600, + "completion_receipt": { + "todo_id": "todo_hook_1", + "completion_receipt_id": "cqr_hook_1", + "exit_code": 0, + "sha256": "f" * 64, + "failure_facts": ["no silent fallback"], + "open_obligations": ["run final canary"], + "source_ref": source_ref, + }, + "obs_next_cmd": {"command": ["cat", str(obs_target)], "max_output_bytes": 4096}, + }, + } + res1 = codex_context.codex_context_hook(str(ctx_dir), fold_event) + fold_out1 = res1["hookSpecificOutput"]["semanticUnitFold"] + assert fold_out1["operator"] == "FoldToReceipt" + assert fold_out1["status"] == "committed" + assert fold_out1["preserves_prefix_kv"] is True + assert fold_out1["reclaim_range"] == [2, 9] + assert fold_out1["executed"] is True + assert fold_out1["replayed"] is False + assert "NEXT_OBS=ready" in res1["hookSpecificOutput"]["additionalContext"] + assert len(exec_calls) == 1 + + # Duplicate hook delivery MUST replay committed receipt without re-spawning obs_next_cmd. + res2 = codex_context.codex_context_hook(str(ctx_dir), fold_event) + fold_out2 = res2["hookSpecificOutput"]["semanticUnitFold"] + assert fold_out2["operator"] == "FoldToReceipt" + assert fold_out2["replayed"] is True + assert fold_out2["executed"] is False + assert len(exec_calls) == 1 + + +@pytest.mark.parametrize( + "case_name", + ["missing_receipt", "non_quiescent", "command_error", "negative_savings", "prefix_mismatch"], +) +def test_codex_context_hook_semantic_unit_fails_closed_keep_raw( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case_name: str, +) -> None: + ctx_dir = tmp_path / f"codex-fail-{case_name}" + ctx_dir.mkdir(mode=0o700) + codex_context._save( + ctx_dir, + { + "session_id": "s1", + "cwd": str(tmp_path), + "context_epoch": "epoch-fail", + }, + ) + prefix_digest = "1" * 64 + source_ref = _write_source_file(tmp_path / "fail-source.json", '{"status":"err"}\n') + codex_context.codex_context_hook( + str(ctx_dir), + { + "session_id": "s1", + "cwd": str(tmp_path), + "hook_event_name": "PostToolUse", + "semantic_unit_anchor": { + "todo_id": "todo_fail_1", + "turn_instance_id": "turn_fail_1", + "anchor_step_index": 1, + "anchor_surface_seq": 3, + "prefix_digest": prefix_digest, + }, + }, + ) + + from loopx.control_plane.turn_driver import semantic_unit_hook as hook_mod + + obs_spawns: 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_spawns.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) + + receipt: dict[str, object] = { + "todo_id": "todo_fail_1", + "completion_receipt_id": "cqr_fail_1", + "exit_code": 0, + "sha256": "2" * 64, + "failure_facts": ["retained failure fact"], + "open_obligations": ["retained obligation"], + "source_ref": source_ref, + } + baseline_text = "exploratory token bloat " * 600 + obs_cmd: dict[str, object] = {"command": ["cat", str(tmp_path / "fail-source.json")]} + fold_spec: dict[str, object] = { + "enabled": True, + "todo_id": "todo_fail_1", + "turn_instance_id": "turn_fail_1", + "prefix_digest": prefix_digest, + "now_step_index": 5, + "now_surface_seq": 9, + "baseline_text": baseline_text, + "completion_receipt": receipt, + "obs_next_cmd": obs_cmd, + "failure_facts": ["retained failure fact"], + "open_obligations": ["retained obligation"], + } + event: dict[str, object] = { + "session_id": "s1", + "cwd": str(tmp_path), + "hook_event_name": "PreCompact", + "semantic_unit_fold": fold_spec, + } + if case_name == "missing_receipt": + fold_spec["completion_receipt"] = None + elif case_name == "non_quiescent": + event["unpaired_tool_calls"] = True + elif case_name == "command_error": + obs_cmd["command"] = ["cat", str(tmp_path / "missing-obs-file.txt")] + elif case_name == "negative_savings": + fold_spec["baseline_text"] = "short" + elif case_name == "prefix_mismatch": + fold_spec["prefix_digest"] = "9" * 64 + + res = codex_context.codex_context_hook(str(ctx_dir), event) + fold_out = res["hookSpecificOutput"]["semanticUnitFold"] + assert fold_out["operator"] == "KeepRaw" + assert fold_out["status"] == "fallback_keep_raw" + assert fold_out["preserves_raw_state"] is True + assert fold_out["preserves_prefix_kv"] is True + assert fold_out["reclaim_range"] is None + assert "retained failure fact" in res["hookSpecificOutput"]["additionalContext"] + assert "retained obligation" in res["hookSpecificOutput"]["additionalContext"] + if case_name in {"missing_receipt", "non_quiescent", "prefix_mismatch"}: + assert obs_spawns == [], f"pre-check must prevent obs_next_cmd execution for {case_name}" + 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") diff --git a/tests/control_plane/test_stage_then_swap_quiet_turn.py b/tests/control_plane/test_stage_then_swap_quiet_turn.py new file mode 100644 index 0000000000..7eaafd825a --- /dev/null +++ b/tests/control_plane/test_stage_then_swap_quiet_turn.py @@ -0,0 +1,3015 @@ +"""End-to-end File + SQLite verification for Stage-then-Swap EpochReset, Quiet-Turn, and telemetry.""" +from __future__ import annotations + +from contextlib import closing, redirect_stdout +from datetime import UTC, datetime +import hashlib +import io +import json +import os +from pathlib import Path +import sqlite3 +import sys + +import pytest + +from loopx.capabilities.benchmark_toolkit.experiment_board import ( + BENCHMARK_EXPERIMENT_BOARD_ROW_SCHEMA_VERSION, + normalize_benchmark_experiment_board_row, +) +from loopx.capabilities.benchmark_toolkit.study_projection import _effort_aggregate +from loopx.capabilities.benchmark_toolkit.token_capacity import ( + BENCHMARK_TOKEN_USAGE_SAMPLE_SCHEMA_VERSION, + build_benchmark_token_capacity_policy, + build_benchmark_token_capacity_status, + configure_benchmark_token_capacity, + observe_benchmark_token_usage, + read_benchmark_token_capacity_state, +) +from loopx.cli import main as cli_main +from loopx.control_plane.turn_driver import codex_context +from loopx.control_plane.turn_driver.codex_cli import prepare_codex_cli_input +from loopx.control_plane.turn_driver.decision_capture import write_decision_capture +from loopx.control_plane.turn_driver.epoch_prefetch import resolve_or_execute_epoch_prefetch +from loopx.control_plane.turn_driver.journal_store import turn_journal_path +from benchmark.runtime.session_observation import collect_context_policy_telemetry +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 _invoke_cli(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 _write_generic_host_and_validator(tmp_path: Path, seen_log: Path) -> tuple[Path, Path]: + runner = tmp_path / "generic_host_runner.py" + runner.write_text( + "import json, pathlib, sys\n" + "request = json.load(sys.stdin)\n" + f"log_path = pathlib.Path({str(seen_log)!r})\n" + "existing = json.loads(log_path.read_text()) if log_path.exists() else []\n" + "existing.append({'turn_key': request['turn_key'], 'epoch_prefetch': request.get('epoch_prefetch'), 'exploratory_context': request.get('exploratory_context')})\n" + "log_path.write_text(json.dumps(existing))\n" + "result = {\n" + " 'schema_version': 'loopx_turn_result_v0',\n" + " 'turn_key': request['turn_key'],\n" + " 'result_kind': 'validated_progress',\n" + " 'completed_phases': ['host_execute', 'typed_result'],\n" + " 'classification': 'fixture_stage_swap',\n" + " 'recommended_action': 'continue verified step',\n" + " 'next_action': 'continue verified step',\n" + " 'delivery_batch_scale': 'single_surface',\n" + " 'delivery_outcome': 'outcome_progress',\n" + " 'vision_unchanged_reason': 'Fixture objective remains active.',\n" + " 'summary': 'Fixture host completed bounded work.',\n" + " 'work_evidence': ['artifact:fixture-prefetch'],\n" + " 'validation_evidence': ['check:fixture-validator'],\n" + "}\n" + "json.dump(result, sys.stdout)\n", + encoding="utf-8", + ) + validator = tmp_path / "validator.py" + validator.write_text("import sys; sys.stdin.read()\n", encoding="utf-8") + return runner, validator + + +def _switch_fixture_to_idle_monitor(registry: Path, runtime: Path) -> None: + """Close the open executable fixture Todo and leave one non-due monitor_task.""" + add_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + role="agent", + text="Observe public fixture quietly.", + task_class="continuous_monitor", + claimed_by="codex-fixture", + monitor_metadata={ + "target_key": "quiet-public-target", + "cadence": "1h", + "next_due_at": "2099-01-01T00:00:00+00:00", + "watch_only": "true", + }, + ) + complete_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + todo_id="todo_fixture0001", + agent_id="codex-fixture", + claimed_by="codex-fixture", + evidence="Fixture executable step settled before quiet monitor wait.", + no_followup=True, + ) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_default_off_turn_and_hook_have_zero_behavior_drift( + 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) + seen_log = tmp_path / "host_seen.json" + runner, validator = _write_generic_host_and_validator(tmp_path, seen_log) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + + code, payload = _invoke_cli( + route, + [ + "turn", + "run-once", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--host", + "generic-cli", + "--project", + str(project), + "--host-adapter-request-schema", + "loopx_turn_host_request_v1", + "--host-adapter-command-json", + json.dumps([sys.executable, str(runner)]), + "--validation-command-json", + json.dumps([sys.executable, str(validator)]), + "--no-global-sync", + "--execute", + ], + ) + assert code == 0, payload + assert payload["status"] == "committed" + assert "epoch_prefetch" not in payload + assert "quiet_turn" not in payload + assert not (runtime / "goals" / "loopx-turn-fixture" / "turn_prefetch_state.sqlite").exists() + seen = json.loads(seen_log.read_text()) + assert len(seen) == 1 and seen[0]["epoch_prefetch"] is None + + # Codex context hook default-off check. + ctx_dir = tmp_path / "codex-ctx" + ctx_dir.mkdir(mode=0o700) + capture_file = tmp_path / "capture.json" + capture_sha = write_decision_capture(capture_file, {"summary": "keep default behavior"}) + codex_context._save( + ctx_dir, + { + "session_id": "s-default", + "cwd": str(tmp_path), + "context_epoch": "epoch-1", + "recovery": {"path": str(capture_file), "sha256": capture_sha, "command": f"read {capture_file}"}, + }, + ) + hook_res = codex_context.codex_context_hook( + str(ctx_dir), + {"session_id": "s-default", "cwd": str(tmp_path), "hook_event_name": "SessionStart", "source": "compact"}, + ) + assert "epochPrefetch" not in hook_res.get("hookSpecificOutput", {}) + assert not (ctx_dir / "epoch_prefetch.sqlite").exists() + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_turn_epoch_reset_prefetch_file_sqlite_once_only_replay_and_savings( + 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) + seen_log = tmp_path / "host_seen.json" + runner, validator = _write_generic_host_and_validator(tmp_path, seen_log) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + + # Create a large capture (>10KB noisy raw turns + compact selected summary) clearing token & cold-prefill gate. + raw_history = [{"turn": idx, "log": f"verbose exploratory tool output row {idx} " * 4} for idx in range(60)] + capture_payload = { + "ok": True, + "summary": {"next_probe": "verify solver parity", "blocker_count": 0}, + "exploratory_history": raw_history, + } + capture_file = tmp_path / "capture.json" + capture_sha = write_decision_capture(capture_file, capture_payload) + baseline_bytes = capture_file.stat().st_size + assert baseline_bytes > 3000 + + # Safe D8 context-read command selecting ONLY `/summary` via a single-shot call. + prefetch_argv = [ + sys.executable, + "-m", + "loopx.cli", + "--format", + "json", + "quota", + "context-read", + "--capture-file", + str(capture_file), + "--capture-sha256", + capture_sha, + "--select", + "/summary", + ] + call_counter = {"count": 0} + real_exec = resolve_or_execute_epoch_prefetch + from loopx.control_plane.turn_driver import epoch_prefetch as ep_mod + + real_subproc = ep_mod.run_bounded_prefetch_subprocess + + def counting_subproc(*args, **kwargs): + call_counter["count"] += 1 + return real_subproc(*args, **kwargs) + + monkeypatch.setattr(ep_mod, "run_bounded_prefetch_subprocess", counting_subproc) + + epoch_cfg = { + "enabled": True, + "initiator": "turn_driver", + "context_epoch": "epoch-swap-1", + "prefetch_command": prefetch_argv, + "timeout_ms": 10000, + "max_output_bytes": 4096, + "reclaimed_turns": 25, + "dropped_failures": 1, + "failure_facts": ["earlier solver iteration failed exit=1 before fix"], + "open_obligations": ["preserve regression test coverage"], + "source_ref": {"path": str(capture_file), "sha256": capture_sha}, + "baseline_bytes": baseline_bytes, + } + + turn_args = [ + "turn", + "run-once", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "stage-swap-once", + "--host", + "generic-cli", + "--project", + str(project), + "--host-adapter-request-schema", + "loopx_turn_host_request_v1", + "--host-adapter-command-json", + json.dumps([sys.executable, str(runner)]), + "--validation-command-json", + json.dumps([sys.executable, str(validator)]), + "--epoch-prefetch-json", + json.dumps(epoch_cfg), + "--no-global-sync", + "--execute", + ] + code1, first = _invoke_cli(route, turn_args) + assert code1 == 0, first + assert first["status"] == "committed" + assert first["replayed"] is False + assert call_counter["count"] == 1 + + ep = first["epoch_prefetch"] + assert ep["operator"] == "EpochReset" + assert ep["trust_level"] == "tool" + assert ep["exit_code"] == 0 + assert ep["truncated"] is False + assert ep["round_trips_saved"] == 1 + assert ep["bytes_saved"] > 0 + assert ep["hydrated_bytes"] < baseline_bytes + assert "[Stage-then-Swap EpochReset Receipt | trust=tool]" in ep["hydrated_text"] + assert "reclaimed_turns: 25" in ep["hydrated_text"] + assert "dropped_failures: 1" in ep["hydrated_text"] + assert "preserve regression test coverage" in ep["hydrated_text"] + assert "verify solver parity" in ep["hydrated_text"] + assert first["epoch_prefetch"]["replayed"] is False + + # Verify BOTH File (turn_journal + turn_prefetch file) AND SQLite hold the persisted completion. + turn_key = first["resume_turn_key"] + jpath = turn_journal_path(runtime, goal_id="loopx-turn-fixture", turn_key=turn_key) + journal_data = json.loads(jpath.read_text(encoding="utf-8")) + assert journal_data["epoch_prefetch"]["receipt_sha256"] == ep["receipt_sha256"] + file_store_dir = runtime / "goals" / "loopx-turn-fixture" / "turn_prefetch" + file_records = list(file_store_dir.glob("*.json")) + assert len(file_records) == 1 + sqlite_db = runtime / "goals" / "loopx-turn-fixture" / "turn_prefetch_state.sqlite" + assert sqlite_db.exists() + with closing(sqlite3.connect(sqlite_db)) as conn: + rows = conn.execute("SELECT operator, receipt_sha256 FROM epoch_prefetch_records").fetchall() + assert rows == [("EpochReset", ep["receipt_sha256"])] + + # Replay the exact Turn via --resume-turn-key (without --turn-instance-id): prefetch_command MUST NEVER execute again. + replay_args = [ + arg + for idx, arg in enumerate(turn_args) + if arg not in {"--turn-instance-id", "stage-swap-once"} + and not (idx > 0 and turn_args[idx - 1] == "--turn-instance-id") + ] + ["--resume-turn-key", turn_key] + code2, replay = _invoke_cli(route, replay_args) + assert code2 == 0, replay + assert replay["replayed"] is True + assert call_counter["count"] == 1 + assert replay["epoch_prefetch"]["replayed"] is True + assert replay["epoch_prefetch"]["executed"] is False + assert replay["epoch_prefetch"]["hydrated_text"] == ep["hydrated_text"] + + # Crash-recovery parity: remove File sidecar, verify SQLite supplies replay without re-executing! + file_records[0].unlink() + replayed_from_sqlite = real_exec( + epoch_prefetch=epoch_cfg, + scope_key=f"turn_driver:loopx-turn-fixture:{turn_key}", + context_epoch="epoch-swap-1", + file_store_dir=file_store_dir, + sqlite_path=sqlite_db, + reclaimed_turns=25, + dropped_failures=1, + failure_facts=epoch_cfg["failure_facts"], + open_obligations=epoch_cfg["open_obligations"], + source_ref=epoch_cfg["source_ref"], + baseline_bytes=baseline_bytes, + ) + assert replayed_from_sqlite is not None + assert replayed_from_sqlite["replayed"] is True and replayed_from_sqlite["executed"] is False + assert call_counter["count"] == 1 + assert len(list(file_store_dir.glob("*.json"))) == 1 # Healed back to File. + + # Telemetry aggregation on the recorded journal directory avoids double counting. + telemetry = collect_context_policy_telemetry( + runtime, + goal_id="loopx-turn-fixture", + usage={ + "completed_turns": 2, + "request_coverage": { + "status": "verified", + "requests": [ + {"input_tokens": 2000, "cached_input_tokens": 0, "cache_regime": "cold"}, + {"input_tokens": 800, "cached_input_tokens": 600, "cache_regime": "warm"}, + ], + }, + }, + ) + assert telemetry["operator_counts"] == {"KeepRaw": 0, "FoldToReceipt": 0, "EpochReset": 1} + assert telemetry["prefetch_bytes"] == ep["retained_bytes"] + assert telemetry["prefetch_bytes_saved"] == ep["bytes_saved"] + assert telemetry["round_trips_saved"] == 1 + assert telemetry["prefix_kv"]["cold"] == {"requests": 1, "uncached_prefix_kv_tokens": 2000, "cached_prefix_kv_tokens": 0} + assert telemetry["prefix_kv"]["warm"] == {"requests": 1, "uncached_prefix_kv_tokens": 200, "cached_prefix_kv_tokens": 600} + + +@pytest.mark.parametrize("failure_mode", ["command_error", "timeout", "policy_violation", "passive_plugin", "reject_truncation"]) +def test_codex_context_hook_epoch_prefetch_fails_closed_to_keep_raw_and_replays_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure_mode: str, +) -> None: + ctx_dir = tmp_path / "codex-ctx" + ctx_dir.mkdir(mode=0o700) + capture_file = tmp_path / "capture.json" + capture_sha = write_decision_capture(capture_file, {"big_payload": "data " * 500}) + codex_context._save( + ctx_dir, + { + "session_id": "s1", + "cwd": str(tmp_path), + "context_epoch": "epoch-hook-1", + "goal_id": "goal-a", + "agent_id": "agent-a", + "candidate": {"capture_bytes_verified": True}, + "recovery": {"path": str(capture_file), "sha256": capture_sha, "command": f"read {capture_file}"}, + }, + ) + codex_context.codex_context_hook(str(ctx_dir), {"session_id": "s1", "cwd": str(tmp_path), "hook_event_name": "PreCompact"}) + + fifo_path = tmp_path / "hang.fifo" + large_file = tmp_path / "large.txt" + large_file.write_text("Z" * 1024, encoding="utf-8") + + cfg: dict = { + "enabled": True, + "initiator": "turn_driver", + "timeout_ms": 2000, + "max_output_bytes": 256, + "failure_facts": ["validator exited 2 on module X"], + "open_obligations": ["keep failure facts visible"], + } + if failure_mode == "command_error": + cfg["prefetch_command"] = ["cat", str(tmp_path / "does-not-exist.txt")] + elif failure_mode == "timeout": + os.mkfifo(fifo_path) + cfg["prefetch_command"] = ["cat", str(fifo_path)] + cfg["timeout_ms"] = 60 + elif failure_mode == "policy_violation": + cfg["prefetch_command"] = ["git", "push", "origin", "main"] + elif failure_mode == "passive_plugin": + cfg["initiator"] = "history_view_policy" + cfg["prefetch_command"] = ["cat", str(large_file)] + elif failure_mode == "reject_truncation": + cfg["prefetch_command"] = ["cat", str(large_file)] + cfg["reject_on_truncation"] = True + cfg["baseline_bytes"] = 5000 + + res1 = codex_context.codex_context_hook( + str(ctx_dir), + { + "session_id": "s1", + "cwd": str(tmp_path), + "hook_event_name": "SessionStart", + "source": "compact", + "epoch_prefetch": cfg, + }, + ) + hook_out = res1["hookSpecificOutput"] + ep = hook_out["epochPrefetch"] + assert ep["operator"] == "KeepRaw" + assert ep["status"] == "fallback_keep_raw" + assert ep["round_trips_saved"] == 0 + assert ep["bytes_saved"] == 0 + assert "validator exited 2 on module X" in hook_out["additionalContext"] + assert "keep failure facts visible" in hook_out["additionalContext"] + assert f"read {capture_file}" in hook_out["additionalContext"] + + # Replay SessionStart(compact) MUST NOT re-execute prefetch_command. + from loopx.control_plane.turn_driver import epoch_prefetch as ep_mod + + def fail_if_executed(*args, **kwargs): + raise AssertionError("prefetch_command must never re-execute on replay") + + monkeypatch.setattr(ep_mod, "run_bounded_prefetch_subprocess", fail_if_executed) + res2 = codex_context.codex_context_hook( + str(ctx_dir), + { + "session_id": "s1", + "cwd": str(tmp_path), + "hook_event_name": "SessionStart", + "source": "compact", + "epoch_prefetch": cfg, + }, + ) + assert res2["hookSpecificOutput"]["epochPrefetch"]["replayed"] is True + assert res2["hookSpecificOutput"]["epochPrefetch"]["executed"] is False + if fifo_path.exists(): + fifo_path.unlink() + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_quiet_turn_zero_tax_skip_and_codex_cli_prompt_rendering( + 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) + seen_log = tmp_path / "host_seen.json" + runner, validator = _write_generic_host_and_validator(tmp_path, seen_log) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + + # First Turn records current state digest; second with unchanged state skips with zero tax. + digest = hashlib.sha256(b"steady-frontier-state").hexdigest() + from loopx.control_plane.turn_driver.executor import run_loopx_turn_once + + def _plan(instance_id: str) -> dict: + c, p = _invoke_cli( + route, + [ + "turn", + "plan", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + instance_id, + "--host", + "generic-cli", + "--execution-mode", + "isolated-headless", + "--scheduler-owner", + "outer_controller", + "--include-transaction-detail", + ], + ) + assert c == 0, p + return p + + plan = _plan("qt-1") + + host_calls = {"n": 0} + + def fake_host(req: dict): + host_calls["n"] += 1 + return { + "schema_version": "loopx_turn_result_v0", + "turn_key": req["turn_key"], + "result_kind": "validated_progress", + "completed_phases": ["host_execute", "typed_result"], + "classification": "quiet_probe", + "recommended_action": "wait", + "next_action": "wait", + "delivery_batch_scale": "single_surface", + "delivery_outcome": "outcome_progress", + "vision_unchanged_reason": "Unchanged state.", + "summary": "Initial observation recorded.", + "work_evidence": ["artifact:initial"], + "validation_evidence": ["check:initial"], + } + + def ok_noop(*args, **kwargs): + return {"ok": True, "appended": True, "classification": "quiet_probe", "recommended_action": "wait"} + + # First Turn executes normally and persists state_digest. + r1 = run_loopx_turn_once( + plan, + host_runner=fake_host, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn={ + "enabled": True, + "quiet_noop_allowed": True, + "current_state_digest": digest, + "skip_host_when_unchanged": True, + }, + ) + assert r1["status"] == "scheduler_action_required" and host_calls["n"] == 1 + assert r1["quiet_turn"]["skipped"] is False + + # Open executable Todo MUST NOT be skipped even if caller passes quiet_noop_allowed=True. + plan_open_mandatory = _plan("qt-open-mandatory") + r_open = run_loopx_turn_once( + plan_open_mandatory, + host_runner=fake_host, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn={ + "enabled": True, + "quiet_noop_allowed": True, + "current_state_digest": digest, + "skip_host_when_unchanged": True, + }, + ) + assert r_open["status"] == "scheduler_action_required" and host_calls["n"] == 2 + assert r_open["quiet_turn"]["skipped"] is False + assert r_open["quiet_turn"]["quiet_noop_allowed"] is False + + # Once open work is settled and only a non-due monitor remains, unchanged state skips with zero tax. + _switch_fixture_to_idle_monitor(registry, runtime) + plan_second = _plan("qt-2") + assert plan_second["route"]["kind"] == "wait" + r2 = run_loopx_turn_once( + plan_second, + host_runner=fake_host, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn={ + "enabled": True, + "quiet_noop_allowed": True, + "current_state_digest": digest, + "skip_host_when_unchanged": True, + }, + epoch_prefetch={ + "enabled": True, + "prefetch_command": ["rm", "-rf", "/should-never-run"], + }, + ) + assert r2["status"] == "skipped" + assert host_calls["n"] == 2 # Host never invoked for quiet-noop wait Turn! + assert r2["quota_slot_spend_count"] == 0 + assert r2["quiet_turn"]["skipped"] is True + assert r2["quiet_turn"]["zero_tax"] is True + assert r2["quiet_turn"]["prefetch_skipped"] is True + assert r2["quiet_turn"]["context_delivery_skipped"] is True + + # Also verify codex_cli prompt builder preserves complete contract with attached tool-trust EpochReset observation. + from loopx.control_plane.turn_driver.executor import build_loopx_turn_host_request + + cli_req = build_loopx_turn_host_request(plan) + cli_req["epoch_prefetch"] = { + "schema_version": "loopx_epoch_prefetch_receipt_v0", + "operator": "EpochReset", + "trust_level": "tool", + "hydrated_text": "[Stage-then-Swap EpochReset Receipt | trust=tool]\n---\nprefetched probe", + } + prompt, schema = prepare_codex_cli_input(cli_req) + assert "tool trust level only" in prompt + assert "prefetched probe" in prompt + assert schema["additionalProperties"] is False + + keep_raw_req = build_loopx_turn_host_request(plan) + keep_raw_req["epoch_prefetch"] = { + "schema_version": "loopx_epoch_prefetch_receipt_v0", + "operator": "KeepRaw", + "status": "fallback_keep_raw", + "fallback_reason": "timeout", + "trust_level": "tool", + "preserved_failure_facts": ["earlier check failed exit=2"], + "preserved_open_obligations": ["keep original evidence intact"], + } + keep_prompt, _ = prepare_codex_cli_input(keep_raw_req) + assert "aborted atomically to KeepRaw" in keep_prompt + assert "earlier check failed exit=2" in keep_prompt + assert "keep original evidence intact" in keep_prompt + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_turn_run_once_fail_closed_keep_raw_preserves_obligations_in_file_and_sqlite( + 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) + seen_log = tmp_path / "host_seen.json" + runner, validator = _write_generic_host_and_validator(tmp_path, seen_log) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + + cfg = { + "enabled": True, + "initiator": "turn_driver", + "context_epoch": "epoch-fail-1", + "prefetch_command": ["cat", str(tmp_path / "missing-probe.txt")], + "timeout_ms": 2000, + "max_output_bytes": 1024, + "reclaimed_turns": 5, + "dropped_failures": 1, + "failure_facts": ["original failure fact must stay preserved"], + "open_obligations": ["original obligation must stay preserved"], + "baseline_bytes": 4096, + } + args = [ + "turn", + "run-once", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "keep-raw-once", + "--host", + "generic-cli", + "--project", + str(project), + "--host-adapter-request-schema", + "loopx_turn_host_request_v1", + "--host-adapter-command-json", + json.dumps([sys.executable, str(runner)]), + "--validation-command-json", + json.dumps([sys.executable, str(validator)]), + "--epoch-prefetch-json", + json.dumps(cfg), + "--no-global-sync", + "--execute", + ] + code, res = _invoke_cli(route, args) + assert code == 0, res + assert res["status"] == "committed" + ep = res["epoch_prefetch"] + assert ep["operator"] == "KeepRaw" + assert ep["fallback_reason"] == "command_failed" + assert ep["preserves_raw_state"] is True + assert ep["preserved_failure_facts"] == ["original failure fact must stay preserved"] + assert any("todo_fixture0001" in item for item in ep["preserved_open_obligations"]) + assert "original obligation must stay preserved" in ep["preserved_open_obligations"] + + seen = json.loads(seen_log.read_text(encoding="utf-8")) + assert len(seen) == 1 + assert seen[0]["epoch_prefetch"]["operator"] == "KeepRaw" + assert seen[0]["epoch_prefetch"]["preserved_failure_facts"] == ["original failure fact must stay preserved"] + + sqlite_db = runtime / "goals" / "loopx-turn-fixture" / "turn_prefetch_state.sqlite" + with closing(sqlite3.connect(sqlite_db)) as conn: + rows = conn.execute("SELECT operator, receipt_sha256 FROM epoch_prefetch_records").fetchall() + assert rows == [("KeepRaw", ep["receipt_sha256"])] + + +def test_benchmark_cost_schema_and_token_capacity_record_telemetry_without_legacy_drift(tmp_path: Path) -> None: + now = datetime(2026, 11, 21, 12, 0, tzinfo=UTC) + row = normalize_benchmark_experiment_board_row( + { + "schema_version": BENCHMARK_EXPERIMENT_BOARD_ROW_SCHEMA_VERSION, + "benchmark_id": "fixture@1", + "study_id": "pareto-study", + "case_id": "case-1", + "run_id": "run-epoch-1", + "arm_id": "epoch-reset", + "arm_role": "treatment", + "comparison_anchor_run_id": "run-baseline-1", + "attempt": 1, + "status": "completed", + "observed_at": now.isoformat(), + "model_id": "solver-model-v1", + "protocol_id": "proto-v1", + "comparison_protocol_id": "proto-v1", + "claim_scope": "matched_study", + "primary_metric": "score", + "metrics": {"score": {"value": 9, "total": 10, "higher_is_better": True}}, + "countability": { + "integrity_qualified": True, + "official_result_present": True, + "score_countable": True, + }, + "treatment_fidelity": "qualified", + "effort": { + "duration_ms": 1000, + "agent_steps": 4, + "goal_turns": 2, + "token_count": 3000, + "estimated_cost_usd": 0.12, + "cached_prefix_kv_tokens": 1800, + "uncached_prefix_kv_tokens": 1200, + "cold_uncached_prefix_kv_tokens": 900, + "cold_cached_prefix_kv_tokens": 0, + "warm_uncached_prefix_kv_tokens": 300, + "warm_cached_prefix_kv_tokens": 1800, + "prefetch_latency_ms": 15, + "prefetch_bytes": 240, + "prefetch_bytes_saved": 2600, + "quiet_turn_skips": 2, + "operator_counts": {"KeepRaw": 1, "FoldToReceipt": 0, "EpochReset": 2}, + }, + } + ) + assert row["effort"]["operator_counts"] == {"KeepRaw": 1, "FoldToReceipt": 0, "EpochReset": 2} + agg = _effort_aggregate([row]) + assert agg["operator_counts"] == {"KeepRaw": 1, "FoldToReceipt": 0, "EpochReset": 2} + assert agg["cold_uncached_prefix_kv_tokens"]["mean"] == 900.0 + assert agg["warm_cached_prefix_kv_tokens"]["mean"] == 1800.0 + + # Token capacity telemetry records cold/warm KV & operator counts while keeping omit-when-absent parity. + cap_path = tmp_path / "token-capacity.json" + configure_benchmark_token_capacity( + cap_path, + build_benchmark_token_capacity_policy(quota_tokens_per_minute=1_000_000), + execute=True, + observed_at=now.isoformat(), + ) + observe_benchmark_token_usage( + cap_path, + { + "schema_version": BENCHMARK_TOKEN_USAGE_SAMPLE_SCHEMA_VERSION, + "sample_id": "cold-epoch", + "observed_at": now.isoformat(), + "metering_state": "measured", + "request_count": 1, + "uncached_input_tokens": 900, + "cached_input_tokens": 0, + "output_tokens": 50, + "cache_regime": "cold", + "operator_counts": {"KeepRaw": 0, "FoldToReceipt": 0, "EpochReset": 1}, + "prefetch_latency_ms": 15, + "prefetch_bytes": 240, + "prefetch_bytes_saved": 2600, + }, + execute=True, + recorded_at=now.isoformat(), + ) + observe_benchmark_token_usage( + cap_path, + { + "schema_version": BENCHMARK_TOKEN_USAGE_SAMPLE_SCHEMA_VERSION, + "sample_id": "warm-follow", + "observed_at": now.isoformat(), + "metering_state": "measured", + "request_count": 1, + "uncached_input_tokens": 300, + "cached_input_tokens": 1800, + "output_tokens": 40, + "cache_regime": "warm", + "operator_counts": {"KeepRaw": 1, "FoldToReceipt": 0, "EpochReset": 0}, + "quiet_turn_skips": 2, + }, + execute=True, + recorded_at=now.isoformat(), + ) + status = build_benchmark_token_capacity_status( + read_benchmark_token_capacity_state(cap_path), observed_at=now.isoformat() + ) + usage = status["usage"] + assert usage["prefix_kv"]["cold"] == {"request_count": 1, "uncached_prefix_kv_tokens": 900, "cached_prefix_kv_tokens": 0} + assert usage["prefix_kv"]["warm"] == {"request_count": 1, "uncached_prefix_kv_tokens": 300, "cached_prefix_kv_tokens": 1800} + assert usage["context_policy"]["operator_counts"] == {"KeepRaw": 1, "FoldToReceipt": 0, "EpochReset": 1} + assert usage["context_policy"]["quiet_turn_skips"] == 2 + assert usage["context_policy"]["prefetch_latency_ms"] == 15 + assert usage["context_policy"]["prefetch_bytes"] == 240 + assert usage["context_policy"]["prefetch_bytes_saved"] == 2600 + + +def test_quiet_turn_failed_host_does_not_skip_next_turn_records_skip_telemetry_and_detects_conflict( + tmp_path: Path, +) -> None: + from loopx.control_plane.turn_driver.epoch_prefetch import resolve_quiet_turn_metadata + from loopx.control_plane.turn_driver.executor import run_loopx_turn_once + + project, runtime, registry = _write_live_fixture(tmp_path) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + digest = "9" * 64 + + def _plan(turn_id: str) -> dict: + c, p = _invoke_cli( + route, + [ + "turn", + "plan", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + turn_id, + "--host", + "generic-cli", + "--execution-mode", + "isolated-headless", + "--scheduler-owner", + "outer_controller", + "--include-transaction-detail", + ], + ) + assert c == 0, p + return p + + admit_calls = {"n": 0} + host_calls = {"n": 0} + should_fail = {"flag": True} + + def fake_admit(_payload: dict) -> dict: + admit_calls["n"] += 1 + return {"admitted": True} + + def fake_host(req: dict) -> dict: + host_calls["n"] += 1 + if should_fail["flag"]: + raise RuntimeError("transient host failure") + return { + "schema_version": "loopx_turn_result_v0", + "turn_key": req["turn_key"], + "result_kind": "validated_progress", + "completed_phases": ["host_execute", "typed_result"], + "classification": "quiet_probe", + "recommended_action": "wait", + "next_action": "wait", + "delivery_batch_scale": "single_surface", + "delivery_outcome": "outcome_progress", + "vision_unchanged_reason": "Unchanged state.", + "summary": "Recovered turn completed.", + "work_evidence": ["artifact:recovered"], + "validation_evidence": ["check:recovered"], + } + + def ok_noop(*_args, **_kwargs) -> dict: + return {"ok": True, "appended": True, "classification": "quiet_probe", "recommended_action": "wait"} + + qt_cfg = { + "enabled": True, + "quiet_noop_allowed": True, + "current_state_digest": digest, + "skip_host_when_unchanged": True, + } + + # Turn 1 fails inside host_runner: digest MUST NOT be committed prematurely. + r1 = run_loopx_turn_once( + _plan("qt-fail-1"), + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_cfg, + ) + assert r1["status"] == "failed" and r1["ok"] is False + assert admit_calls["n"] == 1 and host_calls["n"] == 1 + + # Turn 2 with identical digest executes cleanly (NOT skipped) and commits digest on settlement. + should_fail["flag"] = False + r2 = run_loopx_turn_once( + _plan("qt-ok-2"), + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_cfg, + ) + assert r2["ok"] is True + assert admit_calls["n"] == 2 and host_calls["n"] == 2 + + # Switch to non-due monitor wait Turn: unchanged digest now skips BEFORE admit_start() / host_runner. + _switch_fixture_to_idle_monitor(registry, runtime) + skip_plan = _plan("qt-skip-3") + assert skip_plan["route"]["kind"] == "wait" + r3 = run_loopx_turn_once( + skip_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_cfg, + ) + assert r3["status"] == "skipped" + assert admit_calls["n"] == 2 # admit_start skipped! + assert host_calls["n"] == 2 + tel = collect_context_policy_telemetry(runtime, goal_id="loopx-turn-fixture") + assert tel["quiet_turn_skips"] == 1 + + # Inject File vs SQLite conflict on quiet_turn_state -> must fail closed (state_changed=True, skipped=False). + goal_root = runtime / "goals" / "loopx-turn-fixture" + q_file = next((goal_root / "quiet_turn").glob("*.json")) + q_payload = json.loads(q_file.read_text(encoding="utf-8")) + q_payload["state_digest"] = "1" * 64 + q_file.write_text(json.dumps(q_payload), encoding="utf-8") + conflict = resolve_quiet_turn_metadata( + scope_key=q_payload["scope_key"], + file_path=q_file, + sqlite_path=goal_root / "turn_prefetch_state.sqlite", + enabled=True, + quiet_noop_allowed=True, + current_state_digest=digest, + record_if_changed=False, + ) + assert conflict["skipped"] is False + assert conflict["state_changed"] is True + assert conflict["reason"] == "state_conflict" + assert conflict["state_conflict"] is True + + +def test_committed_turn_replay_with_altered_epoch_prefetch_never_reexecutes_and_partial_page_keeps_raw( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + import loopx.control_plane.turn_driver.epoch_prefetch as ep_mod + from loopx.control_plane.turn_driver.executor import run_loopx_turn_once + + project, runtime, registry = _write_live_fixture(tmp_path) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + baseline_a = tmp_path / "baseline_a.json" + baseline_a_raw = json.dumps( + { + "summary": "concise summary", + "exploratory_history": [ + {"step": i, "detail": f"verbose raw exploratory log line {i} " * 5} + for i in range(60) + ], + }, + separators=(",", ":"), + ) + baseline_a.write_text(baseline_a_raw, encoding="utf-8") + baseline_a_sha = hashlib.sha256(baseline_a_raw.encode("utf-8")).hexdigest() + probe_a = tmp_path / "probe_a.json" + probe_a.write_text( + json.dumps( + { + "ok": True, + "schema_version": "context_capture_selection_page_v1", + "sha256": baseline_a_sha, + "offset": 0, + "next_offset": None, + "total_bytes": len('{"summary":"concise summary"}'), + "eof": True, + "content": '{"summary":"concise summary"}', + } + ), + encoding="utf-8", + ) + probe_b = tmp_path / "probe_b.txt" + probe_b.write_text("completely different command probe", encoding="utf-8") + + # 1) Partial page (eof=false) via real context-read --page-bytes MUST fail closed to KeepRaw. + big_cap = tmp_path / "big_cap.json" + big_raw = json.dumps({"big": "b" * 16000}) + big_cap.write_text(big_raw, encoding="utf-8") + big_sha = hashlib.sha256(big_raw.encode("utf-8")).hexdigest() + partial_receipt = resolve_or_execute_epoch_prefetch( + epoch_prefetch={ + "enabled": True, + "prefetch_command": [ + sys.executable, + "-m", + "loopx.cli", + "--format", + "json", + "quota", + "context-read", + "--capture-file", + str(big_cap), + "--capture-sha256", + big_sha, + "--select", + "/big", + "--page-bytes", + "1600", + ], + "timeout_ms": 10000, + "max_output_bytes": 16384, + }, + scope_key="partial:eof:test", + context_epoch="epoch-partial-1", + file_store_dir=tmp_path / "ep_partial", + sqlite_path=tmp_path / "ep_partial.sqlite", + source_ref={"path": str(big_cap), "sha256": big_sha}, + baseline_bytes=len(big_raw.encode("utf-8")), + cwd=Path.cwd(), + ) + assert partial_receipt is not None + assert partial_receipt["operator"] == "KeepRaw" + assert partial_receipt["fallback_reason"] == "incomplete_output" + assert partial_receipt["truncated"] is True + assert partial_receipt["preserves_raw_state"] is True + assert partial_receipt["round_trips_saved"] == 0 + assert partial_receipt["bytes_saved"] == 0 + + # 2) Replay of committed Turn with ALTERED --epoch-prefetch-json NEVER re-executes prefetch_command. + c, plan = _invoke_cli( + route, + [ + "turn", + "plan", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "replay-altered-1", + "--host", + "generic-cli", + "--execution-mode", + "isolated-headless", + "--scheduler-owner", + "outer_controller", + "--include-transaction-detail", + ], + ) + assert c == 0, plan + + calls = {"n": 0} + orig_runner = ep_mod.run_bounded_prefetch_subprocess + + def spy_runner(argv, *, timeout_ms, max_output_bytes, cwd=None): + calls["n"] += 1 + return orig_runner(argv, timeout_ms=timeout_ms, max_output_bytes=max_output_bytes, cwd=cwd) + + monkeypatch.setattr(ep_mod, "run_bounded_prefetch_subprocess", spy_runner) + + def ok_host(req: dict) -> dict: + return { + "schema_version": "loopx_turn_result_v0", + "turn_key": req["turn_key"], + "result_kind": "validated_progress", + "completed_phases": ["host_execute", "typed_result"], + "classification": "quiet_probe", + "recommended_action": "wait", + "next_action": "wait", + "delivery_batch_scale": "single_surface", + "delivery_outcome": "outcome_progress", + "vision_unchanged_reason": "Completed.", + "summary": "Committed.", + "work_evidence": ["artifact:committed"], + "validation_evidence": ["check:committed"], + } + + def ok_noop(*_args, **_kwargs) -> dict: + return {"ok": True, "appended": True, "classification": "quiet_probe", "recommended_action": "wait"} + + cfg_a = { + "enabled": True, + "context_epoch": "epoch-replay-lock", + "prefetch_command": ["cat", str(probe_a)], + "source_ref": {"path": str(baseline_a), "sha256": baseline_a_sha}, + "baseline_bytes": len(baseline_a_raw.encode("utf-8")), + "timeout_ms": 2000, + "max_output_bytes": 8192, + } + cfg_b = { + "enabled": True, + "context_epoch": "epoch-replay-lock", + "prefetch_command": ["cat", str(probe_b)], + "source_ref": {"path": str(baseline_a), "sha256": baseline_a_sha}, + "baseline_bytes": len(baseline_a_raw.encode("utf-8")), + "timeout_ms": 2000, + "max_output_bytes": 8192, + } + r1 = run_loopx_turn_once( + plan, + host_runner=ok_host, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + epoch_prefetch=cfg_a, + ) + assert calls["n"] == 1 + assert r1["epoch_prefetch"]["operator"] == "EpochReset" + r2 = run_loopx_turn_once( + plan, + host_runner=ok_host, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + epoch_prefetch=cfg_b, + ) + assert calls["n"] == 1 + assert r2["epoch_prefetch"]["receipt_sha256"] == r1["epoch_prefetch"]["receipt_sha256"] + + # Also prove CLI return_existing (--resume-turn-key on committed Turn) with altered --epoch-prefetch-json. + seen_log = tmp_path / "cli_seen.json" + runner, validator = _write_generic_host_and_validator(tmp_path, seen_log) + cli_args_a = [ + "turn", + "run-once", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "cli-replay-altered", + "--host", + "generic-cli", + "--project", + str(project), + "--host-adapter-request-schema", + "loopx_turn_host_request_v1", + "--host-adapter-command-json", + json.dumps([sys.executable, str(runner)]), + "--validation-command-json", + json.dumps([sys.executable, str(validator)]), + "--epoch-prefetch-json", + json.dumps(cfg_a), + "--no-global-sync", + "--execute", + ] + c_a, first_cli = _invoke_cli(route, cli_args_a) + assert c_a == 0 and first_cli["status"] == "committed" + assert calls["n"] == 2 + cli_args_b = [ + arg + for idx, arg in enumerate(cli_args_a) + if arg not in {"--turn-instance-id", "cli-replay-altered", "--epoch-prefetch-json", json.dumps(cfg_a)} + and not (idx > 0 and cli_args_a[idx - 1] in {"--turn-instance-id", "--epoch-prefetch-json"}) + ] + ["--resume-turn-key", first_cli["resume_turn_key"], "--epoch-prefetch-json", json.dumps(cfg_b)] + c_b, replay_cli = _invoke_cli(route, cli_args_b) + assert c_b == 0 and replay_cli["replayed"] is True + assert calls["n"] == 2 # Altered cfg_b MUST NOT re-execute! + assert replay_cli["epoch_prefetch"]["executed"] is False + assert replay_cli["epoch_prefetch"]["replayed"] is True + assert replay_cli["epoch_prefetch"]["receipt_sha256"] == first_cli["epoch_prefetch"]["receipt_sha256"] + + +def test_inflight_quiet_turn_settlement_recovery_after_spend_failure_never_skips( + tmp_path: Path, +) -> None: + from loopx.control_plane.turn_driver.epoch_prefetch import commit_quiet_turn_state + from loopx.control_plane.turn_driver.executor import run_loopx_turn_once + + project, runtime, registry = _write_live_fixture(tmp_path) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + c, plan = _invoke_cli( + route, + [ + "turn", + "plan", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "qt-inflight-settle", + "--host", + "generic-cli", + "--execution-mode", + "isolated-headless", + "--scheduler-owner", + "outer_controller", + "--include-transaction-detail", + ], + ) + assert c == 0, plan + + digest = hashlib.sha256(b"same-digest-after-host").hexdigest() + qt_cfg = { + "enabled": True, + "quiet_noop_allowed": True, + "current_state_digest": digest, + } + scope_key = "turn_driver:loopx-turn-fixture:codex-fixture" + goal_root = runtime / "goals" / "loopx-turn-fixture" + host_calls = {"n": 0} + spend_calls = {"n": 0} + + def fake_host(req: dict) -> dict: + host_calls["n"] += 1 + return { + "schema_version": "loopx_turn_result_v0", + "turn_key": req["turn_key"], + "result_kind": "validated_progress", + "completed_phases": ["host_execute", "typed_result"], + "classification": "quiet_probe", + "recommended_action": "wait", + "next_action": "wait", + "delivery_batch_scale": "single_surface", + "delivery_outcome": "outcome_progress", + "vision_unchanged_reason": "Unchanged state.", + "summary": "Host completed before transient spend error.", + "work_evidence": ["artifact:inflight"], + "validation_evidence": ["check:inflight"], + } + + def ok_noop(*_a: object, **_k: object) -> dict[str, object]: + return {"ok": True, "appended": True, "classification": "quiet_probe", "recommended_action": "wait"} + + def flaky_spend(*_a: object, **_k: object) -> dict[str, object]: + spend_calls["n"] += 1 + if spend_calls["n"] == 1: + raise RuntimeError("transient spend interruption") + return {"ok": True, "appended": True, "receipt": {"status": "committed"}} + + with pytest.raises(RuntimeError, match="transient spend interruption"): + run_loopx_turn_once( + plan, + host_runner=fake_host, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=flaky_spend, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True, "completed": True}, + quiet_turn=qt_cfg, + ) + assert host_calls["n"] == 1 + assert spend_calls["n"] == 1 + + # Even if quiet_turn_state already records the exact same state_digest on disk + # while this Turn's journal sits in flight waiting on settlement (needs_host=False), + # resuming the in-flight journal MUST finish spend() instead of skipping! + commit_quiet_turn_state( + scope_key=scope_key, + file_path=goal_root / "quiet_turn" / f"{hashlib.sha256(scope_key.encode()).hexdigest()}.json", + sqlite_path=goal_root / "turn_prefetch_state.sqlite", + state_digest=digest, + metadata={"enabled": True}, + ) + r2 = run_loopx_turn_once( + plan, + host_runner=fake_host, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=flaky_spend, + spend_resolver=lambda _ref: {"kind": "absent"}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True, "completed": True}, + quiet_turn=qt_cfg, + ) + assert host_calls["n"] == 1 + assert spend_calls["n"] == 2 + assert r2["status"] == "committed" and r2["ok"] is True + tel = collect_context_policy_telemetry(runtime, goal_id="loopx-turn-fixture") + assert tel["quiet_turn_skips"] == 0 + + +def test_collect_context_policy_telemetry_prefers_usage_prefix_kv_and_compacted_cold( + tmp_path: Path, +) -> None: + runtime = tmp_path / "runtime" + (runtime / "goals" / "g1").mkdir(parents=True) + # 1) Prefers usage["context_policy_telemetry"]["prefix_kv"] over flat/request fallback + usage_with_cpt = { + "context_policy_telemetry": { + "prefix_kv": { + "cold": {"requests": 2, "uncached_prefix_kv_tokens": 500, "cached_prefix_kv_tokens": 100}, + "warm": {"requests": 3, "uncached_prefix_kv_tokens": 90, "cached_prefix_kv_tokens": 900}, + } + }, + "request_coverage": { + "requests": [{"input_tokens": 100, "cached_input_tokens": 80}], + }, + } + tel = collect_context_policy_telemetry(runtime, goal_id="g1", usage=usage_with_cpt) + assert tel["prefix_kv"] == usage_with_cpt["context_policy_telemetry"]["prefix_kv"] + + # 2) Fallback on request_coverage classifies compacted=True as cold even when cached_input_tokens > 0 + usage_requests = { + "request_coverage": { + "requests": [ + {"input_tokens": 200, "cached_input_tokens": 150, "compacted": True}, + {"input_tokens": 120, "cached_input_tokens": 90, "compacted": False}, + ] + } + } + tel2 = collect_context_policy_telemetry(runtime, goal_id="g1", usage=usage_requests) + assert tel2["prefix_kv"]["cold"] == { + "requests": 1, + "uncached_prefix_kv_tokens": 50, + "cached_prefix_kv_tokens": 150, + } + assert tel2["prefix_kv"]["warm"] == { + "requests": 1, + "uncached_prefix_kv_tokens": 30, + "cached_prefix_kv_tokens": 90, + } + + +def test_real_cli_context_read_nonzero_offset_tail_fails_closed_vs_zero_offset_select( + tmp_path: Path, +) -> None: + cap = tmp_path / "large_capture.json" + cap_obj = {"summary": "concise executive summary", "noise": "n" * 14100} + cap_raw = json.dumps(cap_obj, separators=(",", ":")) + cap.write_text(cap_raw, encoding="utf-8") + cap_sha = hashlib.sha256(cap_raw.encode("utf-8")).hexdigest() + total_len = len(cap_raw.encode("utf-8")) + assert total_len > 14095 + + # 1) Exact A2 repro: real `loopx quota context-read --offset 14095 --page-bytes 512` + # yields eof=true on the final 80B tail! Must STILL fail closed to KeepRaw. + tail_receipt = resolve_or_execute_epoch_prefetch( + epoch_prefetch={ + "enabled": True, + "prefetch_command": [ + sys.executable, + "-m", + "loopx.cli", + "--format", + "json", + "quota", + "context-read", + "--capture-file", + str(cap), + "--capture-sha256", + cap_sha, + "--offset", + "14095", + "--page-bytes", + "512", + ], + "timeout_ms": 10000, + "max_output_bytes": 16384, + }, + scope_key="offset-tail-guard:tail", + context_epoch="epoch-tail-1", + file_store_dir=tmp_path / "ep_tail", + sqlite_path=tmp_path / "ep_tail.sqlite", + source_ref={"path": str(cap), "sha256": cap_sha}, + baseline_bytes=total_len, + cwd=Path.cwd(), + ) + assert tail_receipt is not None + assert tail_receipt["operator"] == "KeepRaw" + assert tail_receipt["fallback_reason"] == "incomplete_output" + assert tail_receipt["preserves_raw_state"] is True + assert tail_receipt["round_trips_saved"] == 0 + assert tail_receipt["bytes_saved"] == 0 + + # 2) Paired --offset 0 --select /summary complete compact page commits EpochReset! + zero_select_receipt = resolve_or_execute_epoch_prefetch( + epoch_prefetch={ + "enabled": True, + "prefetch_command": [ + sys.executable, + "-m", + "loopx.cli", + "--format", + "json", + "quota", + "context-read", + "--capture-file", + str(cap), + "--capture-sha256", + cap_sha, + "--select", + "/summary", + "--offset", + "0", + "--page-bytes", + "4096", + ], + "timeout_ms": 10000, + "max_output_bytes": 16384, + }, + scope_key="offset-tail-guard:select-zero", + context_epoch="epoch-tail-2", + file_store_dir=tmp_path / "ep_zero_select", + sqlite_path=tmp_path / "ep_zero_select.sqlite", + source_ref={"path": str(cap), "sha256": cap_sha}, + baseline_bytes=total_len, + cwd=Path.cwd(), + ) + assert zero_select_receipt is not None + assert zero_select_receipt["operator"] == "EpochReset" + assert zero_select_receipt["status"] == "committed" + assert zero_select_receipt["round_trips_saved"] == 1 + assert zero_select_receipt["bytes_saved"] > 10_000 + + # 3) Paired --offset 0 with mismatched source_ref sha256 fails closed to KeepRaw. + wrong_sha = ("0" if cap_sha[0] != "0" else "1") + cap_sha[1:] + mismatch_receipt = resolve_or_execute_epoch_prefetch( + epoch_prefetch={ + "enabled": True, + "prefetch_command": [ + sys.executable, + "-m", + "loopx.cli", + "--format", + "json", + "quota", + "context-read", + "--capture-file", + str(cap), + "--capture-sha256", + cap_sha, + "--select", + "/summary", + "--offset", + "0", + "--page-bytes", + "4096", + ], + "timeout_ms": 10000, + "max_output_bytes": 16384, + }, + scope_key="offset-tail-guard:digest-mismatch", + context_epoch="epoch-tail-3", + file_store_dir=tmp_path / "ep_digest_mismatch", + sqlite_path=tmp_path / "ep_digest_mismatch.sqlite", + source_ref={"path": str(cap), "sha256": wrong_sha}, + baseline_bytes=total_len, + cwd=Path.cwd(), + ) + assert mismatch_receipt is not None + assert mismatch_receipt["operator"] == "KeepRaw" + assert mismatch_receipt["fallback_reason"] == "source_digest_mismatch" + assert mismatch_receipt["round_trips_saved"] == 0 + assert mismatch_receipt["bytes_saved"] == 0 + + +def test_codex_cli_prompt_single_emission_and_rendered_prompt_net_byte_gate(tmp_path: Path) -> None: + """PR #9213 P2: single-emission in _render_prompt + real rendered-prompt net byte check/gate.""" + from loopx.control_plane.turn_driver.codex_cli import _prompt + from loopx.control_plane.turn_driver.epoch_prefetch import apply_turn_epoch_prefetch_to_request + from loopx.control_plane.turn_driver.executor import build_loopx_turn_host_request + + _project, runtime, registry = _write_live_fixture(tmp_path, provider="file") + c, plan = _invoke_cli( + ["--registry", str(registry), "--runtime-root", str(runtime)], + [ + "turn", "plan", + "--goal-id", "loopx-turn-fixture", + "--agent-id", "codex-fixture", + "--turn-instance-id", "prompt-gate-1", + "--host", "generic-cli", + "--execution-mode", "isolated-headless", + "--scheduler-owner", "outer_controller", + "--include-transaction-detail", + ], + ) + assert c == 0, plan + + base_req = build_loopx_turn_host_request(plan) + base_req["exploratory_context"] = [ + {"turn": i, "summary": f"verbose exploratory tool output row {i} " * 5} + for i in range(40) + ] + baseline_prompt = _prompt(base_req) + baseline_prompt_bytes = len(baseline_prompt.encode("utf-8")) + assert baseline_prompt_bytes > 10_000 + + hydrated = "[Stage-then-Swap EpochReset Receipt | trust=tool]\ncontext_epoch: e-prompt\n--- prefetched_output ---\nSUMMARY_OK" + receipt = { + "schema_version": "loopx_epoch_prefetch_receipt_v0", + "operator": "EpochReset", + "status": "committed", + "trust_level": "tool", + "context_epoch": "e-prompt", + "source_ref": None, + "header_fields": {"failure_facts": ["earlier test failed"], "open_obligations": ["keep obligation"]}, + "hydrated_text": hydrated, + "baseline_bytes": 8000, + "bytes_saved": 7061, + "net_savings_bytes": 7061, + "round_trips_saved": 1, + "replayed": False, + } + + # 1. Default append mode (replace_exploratory_context=False) MUST NOT grow prompt while claiming savings! + appended = apply_turn_epoch_prefetch_to_request(base_req, receipt, replace_exploratory_context=False) + appended_ep = appended["epoch_prefetch"] + assert appended_ep["operator"] == "KeepRaw" + assert appended_ep["fallback_reason"] == "negative_net_savings" + assert appended_ep["bytes_saved"] == 0 + assert appended_ep["round_trips_saved"] == 0 + assert appended["exploratory_context"] == base_req["exploratory_context"] + appended_prompt = _prompt(appended) + assert hydrated not in appended_prompt + assert appended_prompt.count("earlier test failed") == 1 + + # 2. Explicit replace_exploratory_context=True shrinks rendered prompt and emits hydrated_text ONCE. + replaced = apply_turn_epoch_prefetch_to_request(base_req, receipt, replace_exploratory_context=True) + replaced_ep = replaced["epoch_prefetch"] + replaced_prompt = _prompt(replaced) + replaced_prompt_bytes = len(replaced_prompt.encode("utf-8")) + real_saved = baseline_prompt_bytes - replaced_prompt_bytes + assert replaced_ep["operator"] == "EpochReset" + assert replaced_prompt.count(hydrated) == 1 + assert real_saved > 0 + assert replaced_ep["bytes_saved"] == min(7061, real_saved) + assert replaced_ep["rendered_prompt_baseline_bytes"] == baseline_prompt_bytes + assert replaced_ep["rendered_prompt_delivered_bytes"] == replaced_prompt_bytes + + +def _quiet_turn_fixture_callbacks(seen_hosts: list[str] | None = None, admit_counter: dict[str, int] | None = None): + def fake_admit(_payload: dict) -> dict: + if admit_counter is not None: + admit_counter["n"] += 1 + return {"admitted": True} + + def fake_host(req: dict) -> dict: + if seen_hosts is not None: + seen_hosts.append(req["turn_key"]) + return { + "schema_version": "loopx_turn_result_v0", + "turn_key": req["turn_key"], + "result_kind": "validated_progress", + "completed_phases": ["host_execute", "typed_result"], + "classification": "quiet_probe", + "recommended_action": "wait", + "next_action": "wait", + "delivery_batch_scale": "single_surface", + "delivery_outcome": "outcome_progress", + "vision_unchanged_reason": "Unchanged state.", + "summary": "Fixture host turn completed.", + "work_evidence": ["artifact:turn-ok"], + "validation_evidence": ["check:turn-ok"], + } + + def ok_noop(*_args: object, **_kwargs: object) -> dict[str, object]: + return {"ok": True, "appended": True, "classification": "quiet_probe", "recommended_action": "wait"} + + return fake_admit, fake_host, ok_noop + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_quiet_turn_never_skips_mandatory_todo_or_breaks_default_off_wait_across_file_and_sqlite( + 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)] + from loopx.control_plane.turn_driver.executor import run_loopx_turn_once + + def _plan(turn_id: str) -> dict: + c, p = _invoke_cli( + route, + [ + "turn", + "plan", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + turn_id, + "--host", + "generic-cli", + "--execution-mode", + "isolated-headless", + "--scheduler-owner", + "outer_controller", + "--include-transaction-detail", + ], + ) + assert c == 0, p + return p + + digest = "a" * 64 + seen_hosts: list[str] = [] + admit_calls = {"n": 0} + fake_admit, fake_host, ok_noop = _quiet_turn_fixture_callbacks(seen_hosts, admit_calls) + qt_cfg = { + "enabled": True, + "quiet_noop_allowed": True, + "current_state_digest": digest, + "skip_host_when_unchanged": True, + } + + # Seed baseline state_digest via a settled Turn 1. + r1 = run_loopx_turn_once( + _plan("seed-1"), + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_cfg, + ) + assert r1["ok"] is True and admit_calls["n"] == 1 and len(seen_hosts) == 1 + + # Turn 2 still has open Todo (must_attempt=True, quiet_noop_allowed=False) -> CANNOT skip! + open_plan = _plan("mandatory-open-2") + assert open_plan["work_contract"]["interaction_contract"]["agent_channel"]["must_attempt"] is True + assert open_plan["work_contract"]["interaction_contract"]["agent_channel"]["quiet_noop_allowed"] is False + r2 = run_loopx_turn_once( + open_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_cfg, + ) + assert r2["status"] == "scheduler_action_required" + assert r2["quiet_turn"]["skipped"] is False + assert r2["quiet_turn"]["quiet_noop_allowed"] is False + assert admit_calls["n"] == 2 and len(seen_hosts) == 2 + + # Legacy v0 envelope with must_attempt=True, quiet_noop_allowed=False MUST also refuse skipping. + import copy + from loopx.control_plane.quota.turn_envelope import build_turn_envelope + + open_plan_v0 = _plan("v0-mandatory-1") + v0_mandatory_plan = copy.deepcopy(open_plan_v0) + v0_mandatory_plan["schema_version"] = "loopx_turn_plan_v0" + v0_mandatory_plan["turn_envelope"] = { + **build_turn_envelope(open_plan_v0["work_contract"]), + "interaction_contract": { + "agent_channel": {"must_attempt": True, "delivery_allowed": True, "quiet_noop_allowed": False} + }, + } + for key in ("work_contract", "source_decision_hash", "detail_ref"): + v0_mandatory_plan.pop(key, None) + r_v0 = run_loopx_turn_once( + v0_mandatory_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + require_decision_capture=False, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_cfg, + ) + assert r_v0["status"] == "scheduler_action_required" + assert r_v0["quiet_turn"]["skipped"] is False + assert admit_calls["n"] == 3 and len(seen_hosts) == 3 + + # Switch to non-due monitor wait Turn -> default-off (quiet_turn=False) preserves exact ValueError parity! + _switch_fixture_to_idle_monitor(registry, runtime) + wait_plan = _plan("idle-wait-1") + assert wait_plan["route"]["kind"] == "wait" + assert wait_plan["work_contract"]["interaction_contract"]["agent_channel"]["must_attempt"] is False + assert wait_plan["work_contract"]["interaction_contract"]["agent_channel"]["quiet_noop_allowed"] is True + with pytest.raises(ValueError, match="LoopX Turn route is not host executable"): + run_loopx_turn_once( + wait_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=False, + ) + assert admit_calls["n"] == 3 and len(seen_hosts) == 3 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_quiet_turn_skip_replay_idempotency_and_post_skip_host_guard( + 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)] + from loopx.control_plane.turn_driver.executor import run_loopx_turn_once + + def _plan(turn_id: str) -> dict: + c, p = _invoke_cli( + route, + [ + "turn", + "plan", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + turn_id, + "--host", + "generic-cli", + "--execution-mode", + "isolated-headless", + "--scheduler-owner", + "outer_controller", + "--include-transaction-detail", + ], + ) + assert c == 0, p + return p + + digest_v1 = "b" * 64 + digest_v2 = "c" * 64 + seen_hosts: list[str] = [] + admit_calls = {"n": 0} + fake_admit, fake_host, ok_noop = _quiet_turn_fixture_callbacks(seen_hosts, admit_calls) + qt_v1 = { + "enabled": True, + "current_state_digest": digest_v1, + "skip_host_when_unchanged": True, + } + + # Commit initial digest on Turn 1, then move to non-due monitor wait Turn. + r1 = run_loopx_turn_once( + _plan("seed-skip-1"), + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_v1, + ) + assert r1["ok"] is True and admit_calls["n"] == 1 and len(seen_hosts) == 1 + + _switch_fixture_to_idle_monitor(registry, runtime) + skip_plan = _plan("quiet-skip-once") + turn_key = skip_plan["transaction"]["turn_key"] + + r_skip = run_loopx_turn_once( + skip_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_v1, + ) + assert r_skip["status"] == "skipped" and r_skip["replayed"] is False + assert admit_calls["n"] == 1 and len(seen_hosts) == 1 + + goal_root = runtime / "goals" / "loopx-turn-fixture" + skip_file = goal_root / "quiet_turn" / "skips" / f"{hashlib.sha256(turn_key.encode('utf-8')).hexdigest()}.json" + sqlite_path = goal_root / "turn_prefetch_state.sqlite" + orig_file_bytes = skip_file.read_bytes() + orig_file_mtime_ns = skip_file.stat().st_mtime_ns + with closing(sqlite3.connect(sqlite_path, timeout=5.0)) as conn: + sqlite_rows_before = conn.execute( + "SELECT turn_key, scope_key, state_digest, receipt_json, recorded_at FROM quiet_turn_skips ORDER BY turn_key" + ).fetchall() + assert len(sqlite_rows_before) == 1 + + # Retry 1: exact same Turn identity -> terminal replay, File & SQLite skip receipts UNTOUCHED! + r_retry_same = run_loopx_turn_once( + skip_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_v1, + ) + assert r_retry_same["status"] == "skipped" and r_retry_same["replayed"] is True + assert r_retry_same["quiet_turn"]["replayed"] is True + assert admit_calls["n"] == 1 and len(seen_hosts) == 1 + assert skip_file.read_bytes() == orig_file_bytes + assert skip_file.stat().st_mtime_ns == orig_file_mtime_ns + with closing(sqlite3.connect(sqlite_path, timeout=5.0)) as conn: + assert conn.execute( + "SELECT turn_key, scope_key, state_digest, receipt_json, recorded_at FROM quiet_turn_skips ORDER BY turn_key" + ).fetchall() == sqlite_rows_before + + # Retry 2: same Turn identity after state_digest changes -> MUST still replay skip & block admission/host! + r_retry_changed_digest = run_loopx_turn_once( + skip_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn={"enabled": True, "current_state_digest": digest_v2, "state_changed": True, "skip_host_when_unchanged": True}, + ) + assert r_retry_changed_digest["status"] == "skipped" and r_retry_changed_digest["replayed"] is True + assert r_retry_changed_digest["quiet_turn"]["state_digest"] == digest_v1 + assert admit_calls["n"] == 1 and len(seen_hosts) == 1 + + # Retry 3: same Turn identity with quiet_turn=False -> MUST still block host invocation & journal creation! + r_retry_disabled = run_loopx_turn_once( + skip_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=False, + ) + assert r_retry_disabled["status"] == "skipped" and r_retry_disabled["replayed"] is True + assert admit_calls["n"] == 1 and len(seen_hosts) == 1 + assert not turn_journal_path(runtime, goal_id="loopx-turn-fixture", turn_key=turn_key).exists() + assert skip_file.read_bytes() == orig_file_bytes + assert skip_file.stat().st_mtime_ns == orig_file_mtime_ns + assert collect_context_policy_telemetry(runtime, goal_id="loopx-turn-fixture")["quiet_turn_skips"] == 1 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_quiet_turn_skip_single_store_crash_healing_and_fail_closed_conflicts( + 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)] + from loopx.control_plane.turn_driver.executor import run_loopx_turn_once + + def _plan(turn_id: str) -> dict: + c, p = _invoke_cli( + route, + [ + "turn", + "plan", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + turn_id, + "--host", + "generic-cli", + "--execution-mode", + "isolated-headless", + "--scheduler-owner", + "outer_controller", + "--include-transaction-detail", + ], + ) + assert c == 0, p + return p + + digest = "d" * 64 + seen_hosts: list[str] = [] + admit_calls = {"n": 0} + fake_admit, fake_host, ok_noop = _quiet_turn_fixture_callbacks(seen_hosts, admit_calls) + qt_cfg = {"enabled": True, "current_state_digest": digest, "skip_host_when_unchanged": True} + + run_loopx_turn_once( + _plan("heal-seed"), + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_cfg, + ) + _switch_fixture_to_idle_monitor(registry, runtime) + skip_plan = _plan("heal-skip") + turn_key = skip_plan["transaction"]["turn_key"] + r_skip = run_loopx_turn_once( + skip_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_cfg, + ) + assert r_skip["status"] == "skipped" and admit_calls["n"] == 1 and len(seen_hosts) == 1 + + goal_root = runtime / "goals" / "loopx-turn-fixture" + skip_file = goal_root / "quiet_turn" / "skips" / f"{hashlib.sha256(turn_key.encode('utf-8')).hexdigest()}.json" + sqlite_path = goal_root / "turn_prefetch_state.sqlite" + orig_bytes = skip_file.read_bytes() + orig_payload = json.loads(orig_bytes.decode("utf-8")) + + # 1. Drop SQLite row only -> replay crash-heals SQLite while leaving File untouched. + with closing(sqlite3.connect(sqlite_path, timeout=5.0)) as conn: + conn.execute("DELETE FROM quiet_turn_skips WHERE turn_key = ?", (turn_key,)) + conn.commit() + mtime_before_heal = skip_file.stat().st_mtime_ns + r_heal_sql = run_loopx_turn_once( + skip_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=False, + ) + assert r_heal_sql["status"] == "skipped" and r_heal_sql["replayed"] is True + assert skip_file.stat().st_mtime_ns == mtime_before_heal + with closing(sqlite3.connect(sqlite_path, timeout=5.0)) as conn: + healed_row = conn.execute( + "SELECT recorded_at, receipt_json FROM quiet_turn_skips WHERE turn_key = ?", + (turn_key,), + ).fetchone() + assert healed_row is not None and healed_row[0] == orig_payload["recorded_at"] + + # 2. Delete File skip receipt only -> replay crash-heals File with identical recorded_at & skips host! + skip_file.unlink() + r_heal_file = run_loopx_turn_once( + skip_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_cfg, + ) + assert r_heal_file["status"] == "skipped" and r_heal_file["replayed"] is True + assert json.loads(skip_file.read_text(encoding="utf-8")) == orig_payload + assert admit_calls["n"] == 1 and len(seen_hosts) == 1 + + # 3. Conflict between File and SQLite skip receipts MUST fail closed without invoking Host. + tampered = dict(orig_payload) + tampered["state_digest"] = "0" * 64 + skip_file.write_text(json.dumps(tampered), encoding="utf-8") + with pytest.raises(ValueError, match="Conflicting File and SQLite Quiet-Turn skip receipts"): + run_loopx_turn_once( + skip_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_cfg, + ) + assert admit_calls["n"] == 1 and len(seen_hosts) == 1 + + # 4. Corrupt File skip receipt MUST fail closed without falling back to Host. + skip_file.write_text("{corrupt", encoding="utf-8") + with pytest.raises(ValueError, match="Corrupt File Quiet-Turn skip receipt"): + run_loopx_turn_once( + skip_plan, + host_runner=fake_host, + admit_start=fake_admit, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda p, r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=ok_noop, + spend=lambda *a, **k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *a, **k: {"ok": True, "acknowledged": True}, + quiet_turn=qt_cfg, + ) + assert admit_calls["n"] == 1 and len(seen_hosts) == 1 + + +def test_stage_then_swap_token_gate_blocks_byte_shrink_when_tokens_grow_or_fail_cold_prefill( + tmp_path: Path, +) -> None: + """PR #9213 P2 #1: gate EpochReset on verifiable token net savings minus cold-prefill amortization.""" + from loopx.control_plane.turn_driver.codex_cli import _prompt + from loopx.control_plane.turn_driver.epoch_prefetch import ( + apply_turn_epoch_prefetch_to_request, + count_verifiable_tokens, + ) + from loopx.control_plane.turn_driver.executor import build_loopx_turn_host_request + + project, runtime, registry = _write_live_fixture(tmp_path, provider="file") + seen_log = tmp_path / "cf_seen.json" + runner, validator = _write_generic_host_and_validator(tmp_path, seen_log) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + c, plan = _invoke_cli( + route, + [ + "turn", + "plan", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "token-gate-cf-1", + "--host", + "generic-cli", + "--execution-mode", + "isolated-headless", + "--scheduler-owner", + "outer_controller", + "--include-transaction-detail", + ], + ) + assert c == 0, plan + + # 1. Exact counterfactual: low-token-density exploratory_context + high-token-density prefetched observation. + # Rendered prompt UTF-8 bytes DROP (~25.5 KB -> ~22.6 KB) while o200k_base tokens GROW (~5,380 -> ~5,830)! + raw_req = build_loopx_turn_host_request(plan) + raw_req["exploratory_context"] = {"notes": "exploration " * 360} + raw_prompt = _prompt(raw_req) + raw_bytes = len(raw_prompt.encode("utf-8")) + raw_tok_pair = count_verifiable_tokens(raw_prompt) + assert raw_tok_pair is not None + raw_tokens, tok_meta = raw_tok_pair + assert tok_meta["encoding"] == "o200k_base" + assert 25_000 <= raw_bytes <= 27_500 and 5_200 <= raw_tokens <= 6_000 + + dense_obs = " ".join(f"{i % 10}{(i * 7) % 10}!" for i in range(230)) + dense_hydrated = ( + "[Stage-then-Swap EpochReset Receipt | trust=tool]\n" + "context_epoch: epoch-cf-1\n--- prefetched_output ---\n" + dense_obs + ) + dense_receipt = { + "schema_version": "loopx_epoch_prefetch_receipt_v0", + "operator": "EpochReset", + "status": "committed", + "trust_level": "tool", + "context_epoch": "epoch-cf-1", + "source_ref": None, + "header_fields": {"failure_facts": ["earlier check failed"], "open_obligations": ["keep raw"]}, + "hydrated_text": dense_hydrated, + "baseline_bytes": 4300, + "bytes_saved": 2500, + "net_savings_bytes": 2500, + "round_trips_saved": 1, + "replayed": False, + } + blocked = apply_turn_epoch_prefetch_to_request( + raw_req, dense_receipt, replace_exploratory_context=True, + ) + blocked_ep = blocked["epoch_prefetch"] + assert blocked_ep["operator"] == "KeepRaw" + assert blocked_ep["fallback_reason"] == "negative_net_savings" + assert blocked_ep["bytes_saved"] == 0 + assert blocked_ep["round_trips_saved"] == 0 + assert blocked_ep["rendered_prompt_baseline_bytes"] == raw_bytes + assert blocked_ep["rendered_prompt_baseline_tokens"] == raw_tokens + assert blocked_ep["net_savings_tokens"] < 0 + assert blocked_ep["amortized_net_savings_tokens"] < 0 + assert blocked["exploratory_context"] == raw_req["exploratory_context"] + blocked_delivered_prompt = _prompt(blocked) + assert dense_hydrated not in blocked_delivered_prompt + blocked_delivered_bytes = len(blocked_delivered_prompt.encode("utf-8")) + blocked_delivered_tok_pair = count_verifiable_tokens(blocked_delivered_prompt) + assert blocked_delivered_tok_pair is not None + assert blocked_ep["rendered_prompt_delivered_bytes"] == blocked_delivered_bytes + assert blocked_ep["rendered_prompt_delta_bytes"] == blocked_delivered_bytes - raw_bytes + assert blocked_ep["rendered_prompt_delivered_tokens"] == blocked_delivered_tok_pair[0] + assert blocked_ep["rendered_prompt_delta_tokens"] == blocked_delivered_tok_pair[0] - raw_tokens + + # Custom host renderer that includes audit telemetry converges on stabilized KeepRaw bytes and tokens. + def _custom_keep_renderer(req: dict) -> str: + return json.dumps(req, sort_keys=True, separators=(",", ":")) + + custom_blocked = apply_turn_epoch_prefetch_to_request( + raw_req, + dense_receipt, + replace_exploratory_context=True, + host_input_renderer=_custom_keep_renderer, + ) + custom_ep = custom_blocked["epoch_prefetch"] + custom_prompt = _custom_keep_renderer(custom_blocked) + assert custom_ep["operator"] == "KeepRaw" + assert custom_ep["rendered_prompt_delivered_bytes"] == len(custom_prompt.encode("utf-8")) + assert custom_ep["rendered_prompt_delivered_tokens"] == count_verifiable_tokens(custom_prompt)[0] + + # 2. Marginal positive token savings (~120 tokens) that fail cold-prefill amortization (~265 tokens) -> KeepRaw! + marginal_obs = " ".join(f"item{i}" for i in range(110)) + marginal_receipt = { + **dense_receipt, + "hydrated_text": ( + "[Stage-then-Swap EpochReset Receipt | trust=tool]\n" + "context_epoch: epoch-cf-marginal\n--- prefetched_output ---\n" + marginal_obs + ), + } + marginal_res = apply_turn_epoch_prefetch_to_request( + raw_req, marginal_receipt, replace_exploratory_context=True, + ) + marginal_ep = marginal_res["epoch_prefetch"] + assert marginal_ep["operator"] == "KeepRaw" + assert marginal_ep["fallback_reason"] == "negative_net_savings" + assert 0 < marginal_ep["net_savings_tokens"] < marginal_ep["cold_prefill_amortization_tokens"] + assert marginal_ep["amortized_net_savings_tokens"] < marginal_ep["min_net_savings_tokens"] + + # 3. Missing/failing token estimator OR unverified external baseline (bytes-only without source_ref) -> KeepRaw! + failing_est = apply_turn_epoch_prefetch_to_request( + raw_req, + dense_receipt, + replace_exploratory_context=True, + token_counter=lambda _text: -1, + ) + assert failing_est["epoch_prefetch"]["operator"] == "KeepRaw" + assert failing_est["epoch_prefetch"]["fallback_reason"] == "token_estimation_unavailable" + assert failing_est["epoch_prefetch"]["rendered_prompt_delivered_bytes"] == len( + _prompt(failing_est).encode("utf-8") + ) + assert "rendered_prompt_delivered_tokens" not in failing_est["epoch_prefetch"] + assert "rendered_prompt_delta_tokens" not in failing_est["epoch_prefetch"] + + no_source_req = build_loopx_turn_host_request(plan) + unverified_ext = apply_turn_epoch_prefetch_to_request( + no_source_req, + { + **dense_receipt, + "hydrated_text": "[Stage-then-Swap EpochReset Receipt | trust=tool]\ncontext_epoch: e-ext\n--- prefetched_output ---\nOK", + "baseline_bytes": 16000, + }, + replace_exploratory_context=False, + ) + assert unverified_ext["epoch_prefetch"]["operator"] == "KeepRaw" + assert unverified_ext["epoch_prefetch"]["fallback_reason"] == "token_estimation_unavailable" + + # 4. Genuine net-token-saving contrast meeting threshold + cold-prefill amortization -> EpochReset! + concise_hydrated = ( + "[Stage-then-Swap EpochReset Receipt | trust=tool]\n" + "context_epoch: epoch-cf-ok\n--- prefetched_output ---\nSUMMARY_OK" + ) + genuine_receipt = { + **dense_receipt, + "hydrated_text": concise_hydrated, + } + # Use a wider low-density exploratory section (~1,000 tokens) so net savings clear cold-prefill amortization (~255). + wide_req = build_loopx_turn_host_request(plan) + wide_req["exploratory_context"] = [ + {"turn": i, "summary": f"verbose exploratory tool output row {i} " * 4} + for i in range(30) + ] + genuine = apply_turn_epoch_prefetch_to_request( + wide_req, genuine_receipt, replace_exploratory_context=True, + ) + genuine_ep = genuine["epoch_prefetch"] + assert genuine_ep["operator"] == "EpochReset" + assert genuine_ep["bytes_saved"] > 0 + assert genuine_ep["net_savings_tokens"] > 500 + assert genuine_ep["cold_prefill_amortization_tokens"] > 0 + assert genuine_ep["amortized_net_savings_tokens"] >= genuine_ep["min_net_savings_tokens"] + assert genuine_ep["tokenizer"]["encoding"] == "o200k_base" + delivered_prompt = _prompt(genuine) + assert len(delivered_prompt.encode("utf-8")) == genuine_ep["rendered_prompt_delivered_bytes"] + assert count_verifiable_tokens(delivered_prompt)[0] == genuine_ep["rendered_prompt_delivered_tokens"] + + # 5. End-to-end real CLI run where capture shrinks bytes (~4.6 KB -> ~1.5 KB) yet dense probe grows tokens! + cap_low_density = tmp_path / "low_density_capture.json" + cap_low_raw = json.dumps({"summary": "exploration " * 380}, separators=(",", ":")) + cap_low_density.write_text(cap_low_raw, encoding="utf-8") + cap_low_sha = hashlib.sha256(cap_low_raw.encode("utf-8")).hexdigest() + dense_page = tmp_path / "dense_page.json" + dense_page.write_text( + json.dumps( + { + "ok": True, + "schema_version": "context_capture_selection_page_v1", + "sha256": cap_low_sha, + "offset": 0, + "next_offset": None, + "total_bytes": len(dense_obs.encode("utf-8")), + "eof": True, + "content": dense_obs, + } + ), + encoding="utf-8", + ) + code_cli, res_cli = _invoke_cli( + route, + [ + "turn", + "run-once", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "cli-token-gate-cf", + "--host", + "generic-cli", + "--project", + str(project), + "--host-adapter-request-schema", + "loopx_turn_host_request_v1", + "--host-adapter-command-json", + json.dumps([sys.executable, str(runner)]), + "--validation-command-json", + json.dumps([sys.executable, str(validator)]), + "--epoch-prefetch-json", + json.dumps( + { + "enabled": True, + "context_epoch": "epoch-cli-cf", + "prefetch_command": ["cat", str(dense_page)], + "source_ref": {"path": str(cap_low_density), "sha256": cap_low_sha}, + "baseline_bytes": len(cap_low_raw.encode("utf-8")), + "timeout_ms": 2000, + "max_output_bytes": 4096, + } + ), + "--no-global-sync", + "--execute", + ], + ) + assert code_cli == 0, res_cli + assert res_cli["epoch_prefetch"]["operator"] == "KeepRaw" + assert res_cli["epoch_prefetch"]["bytes_saved"] == 0 + assert res_cli["epoch_prefetch"]["round_trips_saved"] == 0 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_cli_quiet_turn_wait_route_persists_skip_replays_and_preserves_default_off( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + """PR #9213 P2 #2: pure CLI `--quiet-turn` on idle non-due monitor skips, persists, replays, and preserves default-off.""" + import time as _time + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_live_fixture(tmp_path, provider=provider) + _switch_fixture_to_idle_monitor(registry, runtime) + seen_log = tmp_path / "cli_quiet_host_seen.json" + runner, validator = _write_generic_host_and_validator(tmp_path, seen_log) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + + def _cli_run_once(turn_instance_id: str, *, quiet: bool, host: str = "generic-cli") -> tuple[int, dict]: + args = [ + "turn", + "run-once", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + turn_instance_id, + "--host", + host, + "--project", + str(project), + "--no-global-sync", + "--execute", + ] + if host == "generic-cli": + args.extend([ + "--host-adapter-request-schema", + "loopx_turn_host_request_v1", + "--host-adapter-command-json", + json.dumps([sys.executable, str(runner)]), + "--validation-command-json", + json.dumps([sys.executable, str(validator)]), + ]) + if quiet: + args.append("--quiet-turn") + return _invoke_cli(route, args) + + # 1. Default-off (without --quiet-turn) preserves exact existing refusal on wait route. + c_off, out_off = _cli_run_once("cli-wait-default-off", quiet=False) + assert c_off == 1 + assert out_off.get("ok") is False + assert "LoopX Turn route is not host executable" in str(out_off.get("error") or out_off.get("reason")) + assert not seen_log.exists() + + # 2. First pure CLI --quiet-turn observation establishes stable authoritative baseline digest cleanly. + c_seed, out_seed = _cli_run_once("cli-wait-baseline", quiet=True) + assert c_seed == 0, out_seed + assert out_seed["ok"] is True + assert out_seed["status"] == "stopped" + assert out_seed["quota_slot_spend_count"] == 0 + assert out_seed["effects"]["host_invoked"] is False + assert out_seed["quiet_turn"]["skipped"] is False + assert out_seed["quiet_turn"]["state_changed"] is True + assert not seen_log.exists() + + # Cross a wall-clock second to verify volatile projection_envelope timestamps never break unchanged state digest! + _time.sleep(1.1) + + # 3. Run 1 via pure CLI --quiet-turn on unchanged idle monitor plan: skips Host & persists skip receipt! + c_run1, out_run1 = _cli_run_once("cli-wait-skip-1", quiet=True) + assert c_run1 == 0, out_run1 + assert out_run1["ok"] is True + assert out_run1["status"] == "skipped" + assert out_run1["replayed"] is False + assert out_run1["quota_slot_spend_count"] == 0 + assert out_run1["effects"]["host_invoked"] is False + assert out_run1["quiet_turn"]["skipped"] is True + assert out_run1["quiet_turn"]["zero_tax"] is True + assert not seen_log.exists() + + turn_key = out_run1["resume_turn_key"] + goal_root = runtime / "goals" / "loopx-turn-fixture" + skip_file = goal_root / "quiet_turn" / "skips" / f"{hashlib.sha256(turn_key.encode('utf-8')).hexdigest()}.json" + sqlite_db = goal_root / "turn_prefetch_state.sqlite" + assert skip_file.is_file() + orig_skip_bytes = skip_file.read_bytes() + orig_skip_mtime = skip_file.stat().st_mtime_ns + assert sqlite_db.is_file() + with closing(sqlite3.connect(sqlite_db, timeout=5.0)) as conn: + rows_after_run1 = conn.execute( + "SELECT turn_key, scope_key, state_digest, receipt_json, recorded_at FROM quiet_turn_skips ORDER BY turn_key" + ).fetchall() + assert len(rows_after_run1) == 1 + assert not turn_journal_path(runtime, goal_id="loopx-turn-fixture", turn_key=turn_key).exists() + + # 4. Run 2 via pure CLI --quiet-turn (same turn identity): replays skipped with replayed=True! + c_run2, out_run2 = _cli_run_once("cli-wait-skip-1", quiet=True) + assert c_run2 == 0, out_run2 + assert out_run2["ok"] is True + assert out_run2["status"] == "skipped" + assert out_run2["replayed"] is True + assert out_run2["quiet_turn"]["skipped"] is True + assert out_run2["quiet_turn"]["replayed"] is True + assert out_run2["effects"]["host_invoked"] is False + assert skip_file.read_bytes() == orig_skip_bytes + assert skip_file.stat().st_mtime_ns == orig_skip_mtime + assert not seen_log.exists() + + # 5. Also verify default codex-cli host path (no --host-adapter-command-json) baseline -> skip -> replay! + c_codex_base, out_codex_base = _cli_run_once("cli-wait-codex-base", quiet=True, host="codex-cli") + assert c_codex_base == 0, out_codex_base + assert out_codex_base["status"] == "stopped" + assert out_codex_base["quiet_turn"]["skipped"] is False + c_codex, out_codex = _cli_run_once("cli-wait-codex-1", quiet=True, host="codex-cli") + assert c_codex == 0, out_codex + assert out_codex["status"] == "skipped" + assert out_codex["replayed"] is False + c_codex2, out_codex2 = _cli_run_once("cli-wait-codex-1", quiet=True, host="codex-cli") + assert c_codex2 == 0, out_codex2 + assert out_codex2["status"] == "skipped" + assert out_codex2["replayed"] is True + + # 6. Default-off on a fresh turn identity WITHOUT --quiet-turn STILL refuses cleanly! + c_off2, out_off2 = _cli_run_once("cli-wait-default-off-2", quiet=False) + assert c_off2 == 1 + assert out_off2.get("ok") is False + assert "LoopX Turn route is not host executable" in str(out_off2.get("error") or out_off2.get("reason")) + + # 7. Real state change (adding an open advancement Todo) breaks unchanged skip & invokes Host! + add_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id="loopx-turn-fixture", + role="agent", + text="Actionable task unblocks active work.", + task_class="advancement_task", + claimed_by="codex-fixture", + ) + c_work, out_work = _cli_run_once("cli-wait-unblocked", quiet=True) + assert c_work == 0, out_work + assert out_work["status"] == "committed" + assert out_work["quiet_turn"]["skipped"] is False + assert out_work["quiet_turn"]["quiet_noop_allowed"] is False + assert seen_log.is_file() and len(json.loads(seen_log.read_text(encoding="utf-8"))) == 1 + + +def _write_raw_stdin_generic_host_and_validator(tmp_path: Path, seen_log: Path) -> tuple[Path, Path]: + runner = tmp_path / "raw_stdin_generic_host_runner.py" + runner.write_text( + "import json, pathlib, sys\n" + "raw_stdin = sys.stdin.read()\n" + "request = json.loads(raw_stdin)\n" + f"log_path = pathlib.Path({str(seen_log)!r})\n" + "existing = json.loads(log_path.read_text()) if log_path.exists() else []\n" + "existing.append({\n" + " 'turn_key': request['turn_key'],\n" + " 'raw_stdin': raw_stdin,\n" + " 'stdin_utf8_bytes': len(raw_stdin.encode('utf-8')),\n" + " 'epoch_prefetch': request.get('epoch_prefetch'),\n" + " 'exploratory_context': request.get('exploratory_context'),\n" + "})\n" + "log_path.write_text(json.dumps(existing))\n" + "result = {\n" + " 'schema_version': 'loopx_turn_result_v0',\n" + " 'turn_key': request['turn_key'],\n" + " 'result_kind': 'validated_progress',\n" + " 'completed_phases': ['host_execute', 'typed_result'],\n" + " 'classification': 'fixture_stage_swap',\n" + " 'recommended_action': 'continue verified step',\n" + " 'next_action': 'continue verified step',\n" + " 'delivery_batch_scale': 'single_surface',\n" + " 'delivery_outcome': 'outcome_progress',\n" + " 'vision_unchanged_reason': 'Fixture objective remains active.',\n" + " 'summary': 'Fixture host completed bounded work.',\n" + " 'work_evidence': ['artifact:fixture-prefetch'],\n" + " 'validation_evidence': ['check:fixture-validator'],\n" + "}\n" + "json.dump(result, sys.stdout)\n", + encoding="utf-8", + ) + validator = tmp_path / "validator.py" + validator.write_text("import sys; sys.stdin.read()\n", encoding="utf-8") + return runner, validator + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_generic_cli_stdin_gate_rejects_codex_passing_counterexample_and_commits_positive_savings( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + """PR #9213 review 6042617569: gate EpochReset on actual generic-cli stdin JSON, not Codex prompt tokens.""" + from loopx.control_plane.turn_driver.epoch_prefetch import ( + apply_turn_epoch_prefetch_to_request, + count_verifiable_tokens, + ) + from loopx.control_plane.turn_driver.executor import ( + build_loopx_turn_host_request, + serialize_generic_cli_host_input, + ) + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + facts = [f"prior failure trace {i}: exit=1 module=solver check=parity" for i in range(8)] + obligations = [f"preserve acceptance gate {i}: check regression parity and readback" for i in range(8)] + cap_obj = { + "ok": True, + "summary": {"next_probe": "verify solver parity", "status": "ok"}, + "history": [ + {"step": i, "detail": "verbose exploratory observation record payload " * 4} + for i in range(154) + ], + } + cap_raw = json.dumps(cap_obj, separators=(",", ":")) + cap_file = tmp_path / "counterexample_capture.json" + cap_file.write_text(cap_raw, encoding="utf-8") + cap_sha = hashlib.sha256(cap_raw.encode("utf-8")).hexdigest() + cap_tokens_pair = count_verifiable_tokens(cap_raw, encoding_name="o200k_base") + assert cap_tokens_pair is not None + cap_tokens, _ = cap_tokens_pair + + def _run_in_isolated_fixture( + lane_name: str, epoch_cfg: dict | None = None, + ) -> tuple[dict, dict, Path, Path, Path]: + lane_dir = tmp_path / lane_name + lane_dir.mkdir(parents=True) + project, runtime, registry = _write_live_fixture(lane_dir, provider=provider) + seen_log = lane_dir / "raw_stdin_seen.json" + runner, validator = _write_raw_stdin_generic_host_and_validator(lane_dir, seen_log) + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + cmd = [ + "turn", + "run-once", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "generic-stdin-turn", + "--host", + "generic-cli", + "--project", + str(project), + "--host-adapter-request-schema", + "loopx_turn_host_request_v1", + "--host-adapter-command-json", + json.dumps([sys.executable, str(runner)]), + "--validation-command-json", + json.dumps([sys.executable, str(validator)]), + "--no-global-sync", + "--execute", + ] + if epoch_cfg is not None: + cmd.extend(["--epoch-prefetch-json", json.dumps(epoch_cfg)]) + code, res = _invoke_cli(route, cmd) + assert code == 0, res + seen = json.loads(seen_log.read_text(encoding="utf-8")) + assert len(seen) == 1 + return res, seen[0], project, runtime, registry + + # 1. Baseline uncompacted generic-cli stdin payload (without --epoch-prefetch-json). + baseline_res, baseline_host_entry, _, _, _ = _run_in_isolated_fixture("lane_baseline") + assert baseline_res["status"] == "committed" + baseline_stdin = baseline_host_entry["raw_stdin"] + baseline_tok_pair = count_verifiable_tokens(baseline_stdin, encoding_name="o200k_base") + assert baseline_tok_pair is not None + baseline_stdin_tokens, _ = baseline_tok_pair + + # 2. Reviewer's counterexample: min_net_savings_tokens=3241, cold_prefill_amortization_tokens=128. + # Codex prompt clears >= 3241 (~3425 tokens), while actual generic-cli stdin JSON falls short (< 3241)! + prefetch_argv = [ + sys.executable, + "-m", + "loopx.cli", + "--format", + "json", + "quota", + "context-read", + "--capture-file", + str(cap_file), + "--capture-sha256", + cap_sha, + "--select", + "/summary", + ] + counterexample_cfg = { + "enabled": True, + "initiator": "turn_driver", + "context_epoch": "epoch-ce-3241", + "prefetch_command": prefetch_argv, + "timeout_ms": 10000, + "max_output_bytes": 8192, + "reclaimed_turns": 18, + "dropped_failures": len(facts), + "failure_facts": facts, + "open_obligations": obligations, + "source_ref": {"path": str(cap_file), "sha256": cap_sha}, + "baseline_bytes": len(cap_raw.encode("utf-8")), + "min_net_savings_tokens": 3241, + "cold_prefill_amortization_tokens": 128, + } + ce_res, ce_host_entry, project, runtime, registry = _run_in_isolated_fixture( + "lane_counterexample", counterexample_cfg, + ) + assert ce_res["status"] == "committed" + ce_ep = ce_res["epoch_prefetch"] + assert ce_ep["operator"] == "KeepRaw" + assert ce_ep["fallback_reason"] == "negative_net_savings" + assert ce_ep["preserves_raw_state"] is True + assert ce_ep["bytes_saved"] == 0 + assert ce_ep["round_trips_saved"] == 0 + assert ce_ep["cold_prefill_amortization_tokens"] == 128 + assert ce_ep["min_net_savings_tokens"] == 3241 + assert ce_ep["amortized_net_savings_tokens"] < 3241 + + assert ce_host_entry["epoch_prefetch"]["operator"] == "KeepRaw" + assert ce_host_entry["epoch_prefetch"]["fallback_reason"] == "negative_net_savings" + assert ce_host_entry["epoch_prefetch"].get("hydrated_text") is None + assert ce_host_entry["epoch_prefetch"]["preserved_failure_facts"] == facts + assert "hydrated_text" not in ce_host_entry["raw_stdin"] + assert "[Stage-then-Swap EpochReset Receipt" not in ce_host_entry["raw_stdin"] + + ce_stdin = ce_host_entry["raw_stdin"] + ce_stdin_bytes = len(ce_stdin.encode("utf-8")) + assert ce_host_entry["stdin_utf8_bytes"] == ce_stdin_bytes + ce_tok_pair = count_verifiable_tokens(ce_stdin, encoding_name="o200k_base") + assert ce_tok_pair is not None + ce_stdin_tokens, _ = ce_tok_pair + assert ce_ep["rendered_prompt_delivered_bytes"] == ce_stdin_bytes + assert ce_ep["rendered_prompt_delivered_tokens"] == ce_stdin_tokens + assert ce_ep["rendered_prompt_delta_bytes"] == ce_stdin_bytes - ce_ep["rendered_prompt_baseline_bytes"] + assert ce_ep["rendered_prompt_delta_tokens"] == ce_stdin_tokens - ce_ep["rendered_prompt_baseline_tokens"] + + ce_journal = json.loads( + turn_journal_path( + runtime, goal_id="loopx-turn-fixture", turn_key=ce_res["resume_turn_key"], + ).read_text(encoding="utf-8") + ) + assert ce_journal["epoch_prefetch"]["rendered_prompt_delivered_bytes"] == ce_stdin_bytes + assert ce_journal["epoch_prefetch"]["rendered_prompt_delivered_tokens"] == ce_stdin_tokens + assert ce_journal["epoch_prefetch"]["rendered_prompt_delta_bytes"] == ( + ce_stdin_bytes - ce_ep["rendered_prompt_baseline_bytes"] + ) + assert ce_journal["epoch_prefetch"]["rendered_prompt_delta_tokens"] == ( + ce_stdin_tokens - ce_ep["rendered_prompt_baseline_tokens"] + ) + assert ce_journal["epoch_prefetch"]["amortized_net_savings_tokens"] == ce_ep["amortized_net_savings_tokens"] + + ce_lane_dir = runtime.parent + c_replay, ce_replay = _invoke_cli( + ["--registry", str(registry), "--runtime-root", str(runtime)], + [ + "turn", + "run-once", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--resume-turn-key", + ce_res["resume_turn_key"], + "--host", + "generic-cli", + "--project", + str(project), + "--host-adapter-request-schema", + "loopx_turn_host_request_v1", + "--host-adapter-command-json", + json.dumps([sys.executable, str(ce_lane_dir / "raw_stdin_generic_host_runner.py")]), + "--validation-command-json", + json.dumps([sys.executable, str(ce_lane_dir / "validator.py")]), + "--epoch-prefetch-json", + json.dumps(counterexample_cfg), + "--no-global-sync", + "--execute", + ], + ) + assert c_replay == 0, ce_replay + assert ce_replay["epoch_prefetch"]["replayed"] is True + assert ce_replay["epoch_prefetch"]["executed"] is False + assert ce_replay["epoch_prefetch"]["operator"] == "KeepRaw" + assert ce_replay["epoch_prefetch"]["rendered_prompt_delivered_bytes"] == ce_stdin_bytes + assert ce_replay["epoch_prefetch"]["rendered_prompt_delivered_tokens"] == ce_stdin_tokens + assert ce_replay["epoch_prefetch"]["rendered_prompt_delta_bytes"] == ( + ce_stdin_bytes - ce_replay["epoch_prefetch"]["rendered_prompt_baseline_bytes"] + ) + assert ce_replay["epoch_prefetch"]["rendered_prompt_delta_tokens"] == ( + ce_stdin_tokens - ce_replay["epoch_prefetch"]["rendered_prompt_baseline_tokens"] + ) + assert len(json.loads((ce_lane_dir / "raw_stdin_seen.json").read_text(encoding="utf-8"))) == 1 + + # Confirm the exact same plan + capture + policy clears >= 3241 when gated for codex-cli! + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + c_plan, plan_obj = _invoke_cli( + route, + [ + "turn", + "plan", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "generic-stdin-turn", + "--host", + "generic-cli", + "--execution-mode", + "isolated-headless", + "--scheduler-owner", + "outer_controller", + "--include-transaction-detail", + ], + ) + assert c_plan == 0, plan_obj + req_obj = build_loopx_turn_host_request(plan_obj) + epoch_receipt_ce = resolve_or_execute_epoch_prefetch( + epoch_prefetch=counterexample_cfg, + scope_key="counterexample:compare", + context_epoch="epoch-ce-3241", + file_store_dir=tmp_path / "ce_cmp_f", + sqlite_path=tmp_path / "ce_cmp.sqlite", + reclaimed_turns=18, + dropped_failures=len(facts), + failure_facts=facts, + open_obligations=obligations, + source_ref={"path": str(cap_file), "sha256": cap_sha}, + baseline_bytes=len(cap_raw.encode("utf-8")), + cwd=project, + ) + assert epoch_receipt_ce is not None and epoch_receipt_ce["operator"] == "EpochReset" + codex_gate = apply_turn_epoch_prefetch_to_request( + req_obj, + epoch_receipt_ce, + epoch_prefetch=counterexample_cfg, + host="codex-cli", + ) + assert codex_gate["epoch_prefetch"]["operator"] == "EpochReset" + assert codex_gate["epoch_prefetch"]["amortized_net_savings_tokens"] >= 3241 + + # 3. Positive generic-cli case clearing actual stdin JSON threshold commits EpochReset & matches stdin bytes/tokens. + positive_cfg = { + **counterexample_cfg, + "context_epoch": "epoch-ce-positive", + "min_net_savings_tokens": 2800, + } + pos_res, pos_host_entry, _, pos_runtime, _ = _run_in_isolated_fixture( + "lane_positive", positive_cfg, + ) + assert pos_res["status"] == "committed" + pos_ep = pos_res["epoch_prefetch"] + assert pos_ep["operator"] == "EpochReset" + assert pos_ep["bytes_saved"] > 0 + assert pos_ep["round_trips_saved"] == 1 + assert pos_ep["cold_prefill_amortization_tokens"] == 128 + assert pos_ep["amortized_net_savings_tokens"] >= 2800 + + pos_stdin = pos_host_entry["raw_stdin"] + pos_tok_pair = count_verifiable_tokens(pos_stdin, encoding_name="o200k_base") + assert pos_tok_pair is not None + pos_stdin_tokens, _ = pos_tok_pair + assert pos_host_entry["epoch_prefetch"]["operator"] == "EpochReset" + assert pos_host_entry["stdin_utf8_bytes"] == pos_ep["rendered_prompt_delivered_bytes"] + assert pos_stdin_tokens == pos_ep["rendered_prompt_delivered_tokens"] + assert baseline_host_entry["stdin_utf8_bytes"] == pos_ep["rendered_prompt_baseline_bytes"] + assert abs(baseline_stdin_tokens - pos_ep["rendered_prompt_baseline_tokens"]) < 64 + pos_journal = json.loads( + turn_journal_path( + pos_runtime, goal_id="loopx-turn-fixture", turn_key=pos_res["resume_turn_key"], + ).read_text(encoding="utf-8") + ) + pos_baseline_stdin = serialize_generic_cli_host_input( + build_loopx_turn_host_request(pos_journal["plan"]) + ) + pos_baseline_tok_pair = count_verifiable_tokens(pos_baseline_stdin, encoding_name="o200k_base") + assert pos_baseline_tok_pair is not None + pos_baseline_tokens, _ = pos_baseline_tok_pair + assert len(pos_baseline_stdin.encode("utf-8")) == pos_ep["rendered_prompt_baseline_bytes"] + assert pos_baseline_tokens == pos_ep["rendered_prompt_baseline_tokens"] + measured_amortized = cap_tokens - (pos_stdin_tokens - pos_baseline_tokens) - 128 + assert measured_amortized == pos_ep["amortized_net_savings_tokens"] + assert measured_amortized >= 2800 + + # 4. Inline exploratory_context replacement for generic-cli stabilizes digit counts & matches exact serializer. + inline_req = dict(req_obj) + inline_req["exploratory_context"] = [ + {"turn": i, "summary": f"verbose inline generic exploratory output row {i} " * 5} + for i in range(40) + ] + inline_receipt = { + **epoch_receipt_ce, + "source_ref": None, + "hydrated_text": "[Stage-then-Swap EpochReset Receipt | trust=tool]\ncontext_epoch: e-inline-gen\n--- prefetched_output ---\nOK", + "header_fields": {"failure_facts": ["check failed"], "open_obligations": ["preserve test"]}, + "bytes_saved": 10_500, + "net_savings_bytes": 10_500, + } + inline_res = apply_turn_epoch_prefetch_to_request( + inline_req, + inline_receipt, + replace_exploratory_context=True, + epoch_prefetch={"enabled": True, "min_net_savings_tokens": 200, "cold_prefill_amortization_tokens": 128}, + host="generic-cli", + ) + inline_ep = inline_res["epoch_prefetch"] + assert inline_ep["operator"] == "EpochReset" + delivered_inline_stdin = serialize_generic_cli_host_input(inline_res) + assert len(delivered_inline_stdin.encode("utf-8")) == inline_ep["rendered_prompt_delivered_bytes"] + assert count_verifiable_tokens(delivered_inline_stdin)[0] == inline_ep["rendered_prompt_delivered_tokens"] + + +def test_unmeasurable_and_unsupported_hosts_fail_closed_to_keep_raw(tmp_path: Path) -> None: + """PR #9213: non-Codex hosts never silently fall back to Codex prompt formatting.""" + from loopx.control_plane.turn_driver.epoch_prefetch import ( + apply_turn_epoch_prefetch_to_request, + count_verifiable_tokens, + ) + from loopx.control_plane.turn_driver.executor import ( + build_loopx_turn_host_request, + run_loopx_turn_once, + ) + from loopx.control_plane.turn_driver.host_candidate import render_dsh_host_prompt + + project, runtime, registry = _write_live_fixture(tmp_path, provider="file") + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + c, plan = _invoke_cli( + route, + [ + "turn", + "plan", + "--goal-id", + "loopx-turn-fixture", + "--agent-id", + "codex-fixture", + "--turn-instance-id", + "unmeasurable-host-1", + "--host", + "codex-cli", + "--execution-mode", + "isolated-headless", + "--include-transaction-detail", + ], + ) + assert c == 0, plan + base_req = build_loopx_turn_host_request(plan) + base_req["exploratory_context"] = {"notes": "verbose exploration " * 200} + + receipt = { + "schema_version": "loopx_epoch_prefetch_receipt_v0", + "operator": "EpochReset", + "status": "committed", + "trust_level": "tool", + "context_epoch": "epoch-unmeasurable", + "source_ref": None, + "header_fields": {"failure_facts": ["preserved fact"], "open_obligations": ["preserved obligation"]}, + "hydrated_text": "[Stage-then-Swap EpochReset Receipt | trust=tool]\ncontext_epoch: epoch-unmeasurable\n--- prefetched_output ---\nOK", + "baseline_bytes": 4000, + "bytes_saved": 3500, + "net_savings_bytes": 3500, + "round_trips_saved": 1, + "replayed": False, + } + + for host_name in ("codex-app-server", "claude-code", "unknown-custom-host", ""): + res = apply_turn_epoch_prefetch_to_request( + base_req, + receipt, + replace_exploratory_context=True, + host=host_name, + ) + ep = res["epoch_prefetch"] + assert ep["operator"] == "KeepRaw", host_name + assert ep["fallback_reason"] == "host_input_unmeasurable", host_name + assert ep["preserves_raw_state"] is True + assert ep["bytes_saved"] == 0 + assert ep["round_trips_saved"] == 0 + assert res["exploratory_context"] == base_req["exploratory_context"] + + explicit_none = apply_turn_epoch_prefetch_to_request( + base_req, + receipt, + replace_exploratory_context=True, + host="codex-cli", + host_input_renderer=None, + ) + assert explicit_none["epoch_prefetch"]["operator"] == "KeepRaw" + assert explicit_none["epoch_prefetch"]["fallback_reason"] == "host_input_unmeasurable" + + # DSH host with work_contract uses render_dsh_host_prompt and matches byte/token counts; legacy without work_contract fails closed. + dsh_req = dict(base_req) + dsh_req["exploratory_context"] = [ + {"turn": i, "summary": f"verbose exploratory dsh context observation row {i} " * 5} + for i in range(40) + ] + dsh_res = apply_turn_epoch_prefetch_to_request( + dsh_req, + receipt, + replace_exploratory_context=True, + host="dsh", + ) + assert dsh_res["epoch_prefetch"]["operator"] == "EpochReset" + dsh_prompt = render_dsh_host_prompt(dsh_res) + assert dsh_prompt is not None + assert len(dsh_prompt.encode("utf-8")) == dsh_res["epoch_prefetch"]["rendered_prompt_delivered_bytes"] + assert count_verifiable_tokens(dsh_prompt)[0] == dsh_res["epoch_prefetch"]["rendered_prompt_delivered_tokens"] + + legacy_req = {k: v for k, v in base_req.items() if k != "work_contract"} + assert render_dsh_host_prompt(legacy_req) is None + legacy_dsh = apply_turn_epoch_prefetch_to_request( + legacy_req, + receipt, + replace_exploratory_context=True, + host="dsh", + ) + assert legacy_dsh["epoch_prefetch"]["operator"] == "KeepRaw" + assert legacy_dsh["epoch_prefetch"]["fallback_reason"] == "host_input_unmeasurable" + + # End-to-end Turn executor with codex-app-server (unmeasurable native host) fails closed to KeepRaw. + cap_file = tmp_path / "unmeasurable_cap.json" + cap_raw = json.dumps({"summary": "ok", "history": ["verbose row " * 5 for _ in range(120)]}, separators=(",", ":")) + cap_file.write_text(cap_raw, encoding="utf-8") + cap_sha = hashlib.sha256(cap_raw.encode("utf-8")).hexdigest() + page_file = tmp_path / "unmeasurable_page.json" + page_file.write_text( + json.dumps( + { + "ok": True, + "schema_version": "context_capture_selection_page_v1", + "sha256": cap_sha, + "offset": 0, + "next_offset": None, + "total_bytes": 16, + "eof": True, + "content": '{"summary":"ok"}', + } + ), + encoding="utf-8", + ) + app_server_plan = { + **plan, + "host": {**plan["host"], "kind": "codex-app-server"}, + } + seen_host_requests: list[dict] = [] + + def native_like_runner(req: dict) -> dict: + seen_host_requests.append(dict(req)) + return { + "schema_version": "loopx_turn_result_v0", + "turn_key": req["turn_key"], + "result_kind": "validated_progress", + "completed_phases": ["host_execute", "typed_result"], + "classification": "fixture_unmeasurable", + "recommended_action": "continue", + "next_action": "continue", + "delivery_batch_scale": "single_surface", + "delivery_outcome": "outcome_progress", + "vision_unchanged_reason": "Unchanged.", + "summary": "Done.", + "work_evidence": ["artifact:ok"], + "validation_evidence": ["check:ok"], + } + + run_res = run_loopx_turn_once( + app_server_plan, + host_runner=native_like_runner, + project=project, + runtime_root=runtime, + goal_id="loopx-turn-fixture", + timeout_seconds=10.0, + execute=True, + task_validator=lambda _p, _r: {"status": "passed", "validator_kind": "callback", "summary": "ok"}, + writeback=lambda *_a, **_k: {"ok": True, "appended": True, "classification": "ok", "recommended_action": "wait"}, + spend=lambda *_a, **_k: {"ok": True, "appended": True, "receipt": {"status": "committed"}}, + scheduler=lambda *_a, **_k: {"ok": True, "completed": True, "acknowledged": True}, + epoch_prefetch={ + "enabled": True, + "context_epoch": "epoch-app-server", + "prefetch_command": ["cat", str(page_file)], + "source_ref": {"path": str(cap_file), "sha256": cap_sha}, + "baseline_bytes": len(cap_raw.encode("utf-8")), + "timeout_ms": 2000, + "max_output_bytes": 4096, + }, + ) + assert run_res["status"] == "committed" + assert run_res["epoch_prefetch"]["operator"] == "KeepRaw" + assert run_res["epoch_prefetch"]["fallback_reason"] == "host_input_unmeasurable" + assert run_res["epoch_prefetch"]["bytes_saved"] == 0 + assert run_res["epoch_prefetch"]["round_trips_saved"] == 0 + assert "rendered_prompt_delivered_bytes" not in run_res["epoch_prefetch"] + assert "rendered_prompt_delivered_tokens" not in run_res["epoch_prefetch"] + assert len(seen_host_requests) == 1 + assert seen_host_requests[0]["epoch_prefetch"]["operator"] == "KeepRaw" diff --git a/tests/control_plane_ts/content_digest_single_owner.test.ts b/tests/control_plane_ts/content_digest_single_owner.test.ts index a5880485ae..7bedfcc5b3 100644 --- a/tests/control_plane_ts/content_digest_single_owner.test.ts +++ b/tests/control_plane_ts/content_digest_single_owner.test.ts @@ -166,6 +166,7 @@ const CANONICAL_CONSUMERS = [ "control_plane/quota/heartbeat_receipt_identity.ts", "control_plane/quota/refresh_external_delivery.ts", "control_plane/quota/semantic_replan_guard.ts", + "control_plane/quota/stage_then_swap.ts", "control_plane/quota/turn_envelope.ts", "control_plane/quota/turn_envelope_references.ts", "control_plane/runtime/checkpoint_artifacts.ts", diff --git a/tests/control_plane_ts/stage_then_swap_telemetry.test.ts b/tests/control_plane_ts/stage_then_swap_telemetry.test.ts new file mode 100644 index 0000000000..34cbb7adb8 --- /dev/null +++ b/tests/control_plane_ts/stage_then_swap_telemetry.test.ts @@ -0,0 +1,843 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + buildAntiWhitewashingReceiptHeader, + buildSemanticUnitFoldSwap, + computeQuietTurnStateDigest, + evaluateEpochPrefetchPromptGate, + evaluateEpochPrefetchSwap, + evaluateQuietTurn, + planStageThenSwapPrefetch, + recordSemanticUnitAnchor, + resolvePlanQuietNoopEligibility, + validatePrefetchCommandSafety, +} from '../../loopx/control_plane/quota/stage_then_swap.ts'; +import {updateNativeContextLifecycle} from '../../loopx/control_plane/quota/native_context_lifecycle.ts'; +import {evaluateTurnEnvelope} from '../../loopx/control_plane/quota/turn_envelope.ts'; +import {summarizeTrajectoryCodexUsage} from '../../loopx/control_plane/capabilities/trajectory_codex_usage.ts'; + +test('stage-then-swap prefetch is default-off with zero behavior drift', () => { + for (const config of [undefined, null, false, {enabled: false, prefetch_command: ['cat', 'a.txt']}]) { + const plan = planStageThenSwapPrefetch({epoch_prefetch: config}); + assert.equal(plan.enabled, false); + assert.equal(plan.eligible, false); + assert.equal(plan.fallback_operator, 'KeepRaw'); + } +}); + +test('D8 safety admission enforces read-only allowlist and blocks passive plugins', () => { + const passive = validatePrefetchCommandSafety({ + prefetch_command: ['loopx', 'quota', 'context-read', '--select', '/summary'], + initiator: 'history_view_policy', + }); + assert.equal(passive.allowed, false); + assert.equal(passive.reason, 'policy_violation:passive_policy_cannot_emit_command'); + + for (const unsafeCmd of [ + 'git push origin main', + ['git', 'branch', 'evil-branch-created'], + ['git', 'branch', '--track', 'evil', 'main'], + ['git', 'branch', '-u', 'origin/main'], + ['git', 'log', '--output=/tmp/evil-log.txt', '-n', '1'], + ['git', 'diff', '--output', '/tmp/evil-diff.txt'], + ['git', 'show', '--output=/tmp/evil-show.txt', 'HEAD'], + ['git', 'diff', '--ext-diff'], + 'rm -rf /tmp/something', + 'bash -c "cat foo"', + 'cat a.txt && echo hi', + 'cat a.txt | grep foo', + 'loopx quota spend-slot --execute', + 'loopx quota context-read --execute', + 'find . -delete', + ['python', '-c', 'print(1)'], + ]) { + const res = validatePrefetchCommandSafety({prefetch_command: unsafeCmd}); + assert.equal(res.allowed, false, `expected unsafe command rejected: ${String(unsafeCmd)}`); + } + + for (const safeCmd of [ + ['loopx', 'quota', 'context-read', '--capture-file', 'dec.json', '--capture-sha256', 'a'.repeat(64), '--select', '/summary'], + ['git', 'status'], + ['git', 'branch'], + ['git', 'branch', '--list'], + ['git', 'branch', '--show-current'], + ['cat', 'notes.md'], + ['head', '-n', '20', 'notes.md'], + ['find', '.', '-maxdepth', '2'], + ]) { + const res = validatePrefetchCommandSafety({prefetch_command: safeCmd}); + assert.equal(res.allowed, true, `expected safe command allowed: ${JSON.stringify(safeCmd)}`); + assert.ok(res.command_sha256); + } +}); + +test('EpochReset builds deterministic anti-whitewashing receipt header with tool trust', () => { + const sourceSha = 'b'.repeat(64); + const res = evaluateTurnEnvelope({ + operation: 'stage_then_swap_evaluate', + epoch_prefetch: { + enabled: true, + prefetch_command: ['loopx', 'quota', 'context-read', '--select', '/summary'], + timeout_ms: 2000, + max_output_bytes: 1024, + }, + context_epoch: 'epoch-2', + reclaimed_turns: 7, + dropped_failures: 1, + failure_facts: ['pytest failed exit=2 on test_bar'], + open_obligations: ['todo_1: fix test_bar'], + source_ref: {path: '/tmp/capture.json', sha256: sourceSha}, + exit_code: 0, + timed_out: false, + truncated: false, + raw_bytes_read: 192, + prefetched_output: JSON.stringify({ + ok: true, + schema_version: 'context_capture_page_v1', + sha256: sourceSha, + offset: 0, + next_offset: null, + total_bytes: Buffer.byteLength('{"summary":"narrow repro isolated"}', 'utf8'), + eof: true, + content: '{"summary":"narrow repro isolated"}', + }), + baseline_bytes: 4096, + latency_ms: 12, + }); + + assert.equal(res.operator, 'EpochReset'); + assert.equal(res.status, 'committed'); + assert.equal(res.trust_level, 'tool'); + assert.equal(res.round_trips_saved, 1); + assert.ok((res.bytes_saved as number) > 3000); + const text = String(res.hydrated_text); + assert.ok(text.includes('[Stage-then-Swap EpochReset Receipt | trust=tool]')); + assert.ok(text.includes('reclaimed_turns: 7')); + assert.ok(text.includes('dropped_failures: 1')); + assert.ok(text.includes('exit_code: 0')); + assert.ok(text.includes('truncated: false')); + assert.ok(text.includes('todo_1: fix test_bar')); + assert.ok(text.includes(`sha256:${sourceSha}`)); + assert.ok(text.includes('narrow repro isolated')); + + const headerAgain = buildAntiWhitewashingReceiptHeader({ + context_epoch: 'epoch-2', + reclaimed_turns: 7, + dropped_failures: 1, + failure_facts: ['pytest failed exit=2 on test_bar'], + open_obligations: ['todo_1: fix test_bar'], + exit_code: 0, + truncated: false, + source_ref: {path: '/tmp/capture.json', sha256: sourceSha}, + }); + assert.equal(headerAgain.header, res.header); +}); + +test('failed, timed-out, policy-denied, truncated-strict, or negative-savings prefetch fails closed to KeepRaw', () => { + const base = { + epoch_prefetch: { + enabled: true, + prefetch_command: ['cat', 'status.txt'], + timeout_ms: 500, + max_output_bytes: 256, + }, + context_epoch: 'epoch-3', + reclaimed_turns: 4, + dropped_failures: 2, + failure_facts: ['failure-A', 'failure-B'], + open_obligations: ['obligation-X'], + source_ref: {path: '/tmp/capture.json', sha256: 'c'.repeat(64)}, + baseline_bytes: 2048, + latency_ms: 5, + }; + + const failed = evaluateEpochPrefetchSwap({...base, exit_code: 2, prefetched_output: 'partial'}); + assert.equal(failed.operator, 'KeepRaw'); + assert.equal(failed.fallback_reason, 'command_failed'); + assert.equal(failed.preserves_raw_state, true); + assert.deepEqual(failed.preserved_failure_facts, ['failure-A', 'failure-B']); + assert.deepEqual(failed.preserved_open_obligations, ['obligation-X']); + + const timedOut = evaluateEpochPrefetchSwap({...base, exit_code: null, timed_out: true}); + assert.equal(timedOut.operator, 'KeepRaw'); + assert.equal(timedOut.fallback_reason, 'timeout'); + + const unsafe = evaluateEpochPrefetchSwap({ + ...base, + epoch_prefetch: {...base.epoch_prefetch, prefetch_command: ['rm', '-rf', '/tmp/nope']}, + exit_code: 0, + }); + assert.equal(unsafe.operator, 'KeepRaw'); + assert.match(String(unsafe.fallback_reason), /^policy_violation:/); + + const strictTruncated = evaluateEpochPrefetchSwap({ + ...base, + epoch_prefetch: {...base.epoch_prefetch, reject_on_truncation: true}, + exit_code: 0, + truncated: true, + prefetched_output: 'x'.repeat(256), + }); + assert.equal(strictTruncated.operator, 'KeepRaw'); + assert.equal(strictTruncated.fallback_reason, 'output_truncated'); + + const negativeSavings = evaluateEpochPrefetchSwap({ + ...base, + source_ref: null, + baseline_bytes: 100, + exit_code: 0, + prefetched_output: 'x'.repeat(200), + }); + assert.equal(negativeSavings.operator, 'KeepRaw'); + assert.equal(negativeSavings.fallback_reason, 'negative_net_savings'); + + const incompletePage = evaluateEpochPrefetchSwap({ + ...base, + exit_code: 0, + truncated: false, + prefetched_output: JSON.stringify({ + ok: true, + schema_version: 'context_capture_page_v1', + eof: false, + content: 'partial-page', + }), + }); + assert.equal(incompletePage.operator, 'KeepRaw'); + assert.equal(incompletePage.fallback_reason, 'incomplete_output'); + assert.equal(incompletePage.truncated, true); + assert.equal(incompletePage.preserves_raw_state, true); + assert.equal(incompletePage.round_trips_saved, 0); + assert.equal(incompletePage.bytes_saved, 0); +}); + +test('native lifecycle keeps epoch_prefetch across idempotent PostCompact and clears on new epoch rotation', () => { + const afterPre = updateNativeContextLifecycle({ + state: { + session_id: 's1', + cwd: '/tmp/ws', + context_epoch: 'epoch-1', + candidate: {capture_bytes_verified: true}, + epoch_prefetch: {context_epoch: 'epoch-1', operator: 'EpochReset'}, + }, + event: {session_id: 's1', cwd: '/tmp/ws', hook_event_name: 'PreCompact'}, + new_epoch: 'epoch-2', + pages: [], + }); + assert.equal(afterPre.context_epoch, 'epoch-2'); + // Candidate was cleared by PreCompact; rotating from epoch-1 -> epoch-2 invalidated stale epoch_prefetch. + assert.equal('epoch_prefetch' in afterPre, false); + + const populated = {...afterPre, epoch_prefetch: {context_epoch: 'epoch-2', operator: 'EpochReset'}}; + const afterPost = updateNativeContextLifecycle({ + state: populated, + event: {session_id: 's1', cwd: '/tmp/ws', hook_event_name: 'PostCompact'}, + new_epoch: 'epoch-3', + pages: [], + }); + // Idempotent invalidation keeps epoch-2 and preserves epoch-2 prefetch receipt. + assert.equal(afterPost.context_epoch, 'epoch-2'); + assert.deepEqual(afterPost.epoch_prefetch, {context_epoch: 'epoch-2', operator: 'EpochReset'}); +}); + +test('Quiet-Turn emits zero-tax skip metadata on unchanged state and clears on state change', () => { + const digest = 'd'.repeat(64); + const unchanged = evaluateQuietTurn({ + enabled: true, + quiet_noop_allowed: true, + current_state_digest: digest, + previous_state_digest: digest, + }); + assert.equal(unchanged.skipped, true); + assert.equal(unchanged.zero_tax, true); + assert.equal(unchanged.context_delivery_skipped, true); + assert.equal(unchanged.prefetch_skipped, true); + + const changed = evaluateTurnEnvelope({ + operation: 'quiet_turn_evaluate', + enabled: true, + quiet_noop_allowed: true, + current_state_digest: 'e'.repeat(64), + previous_state_digest: digest, + }); + assert.equal(changed.skipped, false); + assert.equal(changed.zero_tax, false); +}); + +test('trajectory usage telemetry tracks operator counts, prefetch latency/bytes, and cold/warm KV prefix tokens', () => { + const usage = (input: number, cached: number, output: number) => ({ + input_tokens: input, + cached_input_tokens: cached, + output_tokens: output, + }); + const events = [ + {type: 'session_meta', payload: {id: 's1'}}, + {type: 'event_msg', payload: {type: 'task_started', turn_id: 't1'}}, + {type: 'event_msg', payload: {type: 'token_count', info: {total_token_usage: usage(100, 0, 10), last_token_usage: usage(100, 0, 10)}}}, + {type: 'event_msg', payload: {type: 'token_count', info: {total_token_usage: usage(220, 90, 20), last_token_usage: usage(120, 90, 10)}}}, + {type: 'compacted', payload: {reason: 'epoch_reset'}}, + {type: 'event_msg', payload: {type: 'token_count', info: {total_token_usage: usage(300, 130, 25), last_token_usage: usage(80, 40, 5)}}}, + {type: 'event_msg', payload: {type: 'task_complete', turn_id: 't1'}}, + ].map((item, idx) => ({...item, line: idx + 1, timestamp: `2026-11-21T00:00:0${idx}Z`})); + + const baseline = summarizeTrajectoryCodexUsage({events, session_id: 's1'}); + assert.equal('context_policy_telemetry' in baseline, false); + + const enriched = summarizeTrajectoryCodexUsage({ + events, + session_id: 's1', + include_prefix_kv_regimes: true, + context_policy: [ + {operator: 'EpochReset', latency_ms: 14, retained_bytes: 180, bytes_saved: 2400, round_trips_saved: 1}, + {operator: 'KeepRaw', latency_ms: 8, retained_bytes: 0, bytes_saved: 0, quiet_turn_skipped: true}, + {operator: 'FoldToReceipt'}, + ], + }); + const tel = enriched.context_policy_telemetry!; + assert.equal(tel.schema_version, 'loopx_context_policy_telemetry_v0'); + assert.deepEqual(tel.operator_counts, {KeepRaw: 1, FoldToReceipt: 1, EpochReset: 1}); + assert.equal(tel.quiet_turn_skips, 1); + assert.equal(tel.prefetch.latency_ms, 22); + assert.equal(tel.prefetch.output_bytes, 180); + assert.equal(tel.prefetch.bytes_saved, 2400); + assert.equal(tel.prefetch.round_trips_saved, 1); + // Request 1 (100/0) and post-compacted Request 3 (80/40) both bucket cold; Request 2 (120/90) buckets warm. + assert.deepEqual(tel.prefix_kv?.cold, {requests: 2, uncached_prefix_kv_tokens: 140, cached_prefix_kv_tokens: 40}); + assert.deepEqual(tel.prefix_kv?.warm, {requests: 1, uncached_prefix_kv_tokens: 30, cached_prefix_kv_tokens: 90}); +}); + +test("D8 safety admission rejects attached -O flag on git grep", () => { + const attached = validatePrefetchCommandSafety({prefetch_command: ["git", "grep", "-Otouch /tmp/git-grep-o-poc", "loopx"]}); + assert.equal(attached.allowed, false); + assert.equal(attached.reason, "policy_violation:git_output_or_external_diff_forbidden"); +}); + +test("evaluateEpochPrefetchSwap enforces offset === 0, contiguous length, and source sha256 on capture pages", () => { + const digest = "c".repeat(64); + const base = { + epoch_prefetch: {enabled: true, prefetch_command: ["loopx", "--format", "json", "quota", "context-read"]}, + context_epoch: "epoch-page-guard", + reclaimed_turns: 4, + failure_facts: ["build failed"], + open_obligations: ["keep failing tests"], + source_ref: {path: "/tmp/capture.json", sha256: digest}, + baseline_bytes: 14_175, + latency_ms: 5, + exit_code: 0, + truncated: false, + }; + + // Tail slice (--offset > 0) with eof=true MUST fail closed to KeepRaw rather than truncating prefix! + const nonZeroOffset = evaluateEpochPrefetchSwap({ + ...base, + prefetched_output: JSON.stringify({ + ok: true, + schema_version: "context_capture_page_v1", + sha256: digest, + offset: 14095, + next_offset: null, + total_bytes: 14175, + eof: true, + content: "t".repeat(80), + }), + }); + assert.equal(nonZeroOffset.operator, "KeepRaw"); + assert.equal(nonZeroOffset.fallback_reason, "incomplete_output"); + assert.equal(nonZeroOffset.truncated, true); + assert.equal(nonZeroOffset.preserves_raw_state, true); + assert.equal(nonZeroOffset.round_trips_saved, 0); + assert.equal(nonZeroOffset.bytes_saved, 0); + + // Content byte count < total_bytes MUST also fail closed. + const truncatedContent = evaluateEpochPrefetchSwap({ + ...base, + prefetched_output: JSON.stringify({ + ok: true, + schema_version: "context_capture_page_v1", + sha256: digest, + offset: 0, + next_offset: null, + total_bytes: 500, + eof: true, + content: "short", + }), + }); + assert.equal(truncatedContent.operator, "KeepRaw"); + assert.equal(truncatedContent.fallback_reason, "incomplete_output"); + + // Mismatched sha256 vs source_ref.sha256 MUST fail closed. + const wrongDigest = evaluateEpochPrefetchSwap({ + ...base, + prefetched_output: JSON.stringify({ + ok: true, + schema_version: "context_capture_page_v1", + sha256: "b".repeat(64), + offset: 0, + next_offset: null, + total_bytes: 8, + eof: true, + content: "full-cap", + }), + }); + assert.equal(wrongDigest.operator, "KeepRaw"); + assert.equal(wrongDigest.fallback_reason, "source_digest_mismatch"); + + // Complete offset=0, next_offset=null, matching total_bytes and sha256 commits EpochReset cleanly. + const validFull = evaluateEpochPrefetchSwap({ + ...base, + prefetched_output: JSON.stringify({ + ok: true, + schema_version: "context_capture_page_v1", + sha256: digest, + offset: 0, + next_offset: null, + total_bytes: 8, + eof: true, + content: "full-cap", + }), + }); + assert.equal(validFull.operator, "EpochReset"); + assert.equal(validFull.status, "committed"); + assert.equal(validFull.round_trips_saved, 1); + assert.ok(Number(validFull.bytes_saved) > 0); + + // Non-JSON capture tail (mdTail) or unpaginated JSON with bound source_ref / quota context-read + // MUST fail closed identically to jsonTail (KeepRaw incomplete_output, saved=0, round_trips_saved=0). + const mdTail = evaluateEpochPrefetchSwap({ + ...base, + prefetched_output: "# Capture tail markdown\n...tail bytes only...", + }); + assert.equal(mdTail.operator, "KeepRaw"); + assert.equal(mdTail.fallback_reason, "incomplete_output"); + assert.equal(mdTail.truncated, true); + assert.equal(mdTail.round_trips_saved, 0); + assert.equal(mdTail.bytes_saved, 0); + + const unpaginatedJson = evaluateEpochPrefetchSwap({ + ...base, + prefetched_output: JSON.stringify({ok: true, summary: "missing page metadata"}), + }); + assert.equal(unpaginatedJson.operator, "KeepRaw"); + assert.equal(unpaginatedJson.fallback_reason, "incomplete_output"); + assert.equal(unpaginatedJson.round_trips_saved, 0); + assert.equal(unpaginatedJson.bytes_saved, 0); + + // prefetch_command: null without source_ref MUST fail closed cleanly instead of throwing TypeError. + const nullCmd = evaluateEpochPrefetchSwap({ + ...base, + source_ref: null, + epoch_prefetch: {enabled: true, prefetch_command: null}, + prefetched_output: "", + }); + assert.equal(nullCmd.operator, "KeepRaw"); + assert.equal(nullCmd.fallback_reason, "policy_violation:missing_command"); + assert.equal(nullCmd.round_trips_saved, 0); + assert.equal(nullCmd.bytes_saved, 0); + + // String quota context-read command without source_ref MUST still enforce verified typed pagination. + const stringCmdMdTail = evaluateEpochPrefetchSwap({ + ...base, + source_ref: null, + epoch_prefetch: {enabled: true, prefetch_command: "loopx --format json quota context-read"}, + prefetched_output: "# Capture tail markdown\n...tail bytes only...", + }); + assert.equal(stringCmdMdTail.operator, "KeepRaw"); + assert.equal(stringCmdMdTail.fallback_reason, "incomplete_output"); + assert.equal(stringCmdMdTail.truncated, true); + assert.equal(stringCmdMdTail.round_trips_saved, 0); + assert.equal(stringCmdMdTail.bytes_saved, 0); +}); + +test("Quiet-Turn enforces canonical work_contract and legacy turn_envelope precedence over caller flags", () => { + const digest = "f".repeat(64); + // 1. Canonical v1 work_contract with mandatory work blocks skipping even if quiet_noop_allowed=true is requested. + const v1Mandatory = { + interaction_contract: {agent_channel: {must_attempt: true, delivery_allowed: true, quiet_noop_allowed: false}}, + }; + assert.deepEqual(resolvePlanQuietNoopEligibility({work_contract: v1Mandatory}), { + must_attempt: true, + quiet_noop_allowed: false, + source: "work_contract", + }); + const blockedV1 = evaluateQuietTurn({ + enabled: true, + quiet_noop_allowed: true, + current_state_digest: digest, + previous_state_digest: digest, + work_contract: v1Mandatory, + }); + assert.equal(blockedV1.skipped, false); + assert.equal(blockedV1.quiet_noop_allowed, false); + assert.equal(blockedV1.reason, "quiet_noop_disallowed"); + + // 2. Legacy v0 turn_envelope with mandatory work also refuses skipping even with quiet_noop_allowed=true. + const v0Mandatory = { + interaction_contract: {agent_channel: {must_attempt: true, delivery_allowed: false, quiet_noop_allowed: false}}, + }; + assert.deepEqual(resolvePlanQuietNoopEligibility({turn_envelope: v0Mandatory}), { + must_attempt: true, + quiet_noop_allowed: false, + source: "turn_envelope", + }); + const blockedV0 = evaluateQuietTurn({ + enabled: true, + quiet_noop_allowed: true, + current_state_digest: digest, + previous_state_digest: digest, + turn_envelope: v0Mandatory, + }); + assert.equal(blockedV0.skipped, false); + assert.equal(blockedV0.quiet_noop_allowed, false); + + // 3. Idle v1 work_contract (must_attempt=false, quiet_noop_allowed=true) permits unchanged skip, while caller cap false restricts. + const v1Idle = { + interaction_contract: {agent_channel: {must_attempt: false, delivery_allowed: false, quiet_noop_allowed: true}}, + }; + const skippedIdle = evaluateQuietTurn({ + enabled: true, + quiet_noop_allowed: true, + current_state_digest: digest, + previous_state_digest: digest, + work_contract: v1Idle, + }); + assert.equal(skippedIdle.skipped, true); + assert.equal(skippedIdle.reason, "unchanged_state"); + + const restrictedIdle = evaluateQuietTurn({ + enabled: true, + quiet_noop_allowed: false, + current_state_digest: digest, + previous_state_digest: digest, + work_contract: v1Idle, + }); + assert.equal(restrictedIdle.skipped, false); + assert.equal(restrictedIdle.quiet_noop_allowed, false); + + // 4. Empty contract fails closed (does not default quiet_noop_allowed to true). + const emptyContract = evaluateQuietTurn({ + enabled: true, + quiet_noop_allowed: true, + current_state_digest: digest, + previous_state_digest: digest, + work_contract: {}, + }); + assert.equal(emptyContract.skipped, false); + assert.equal(emptyContract.quiet_noop_allowed, false); +}); + +test("STAGE-THEN-SWAP-NET-SAVINGS token & cold-prefill gate rejects byte-shrink token-growth counterfactuals", () => { + const tokenizer = {name: "tiktoken", version: "0.12.0", encoding: "o200k_base"}; + + // 1. Exact counterfactual: prompt UTF-8 bytes shrink (25,534 -> 23,182 B) while tokens grow (5,434 -> 5,878). + const tokenGrowth = evaluateEpochPrefetchPromptGate({ + has_inline_exploratory: true, + replace_exploratory_context: true, + rendered_prompt_baseline_bytes: 25_534, + rendered_prompt_delivered_bytes: 23_182, + rendered_prompt_baseline_tokens: 5_434, + rendered_prompt_delivered_tokens: 5_878, + potential_bytes_saved: 2_352, + tokenizer, + }); + assert.equal(tokenGrowth.operator, "KeepRaw"); + assert.equal(tokenGrowth.fallback_reason, "negative_net_savings"); + assert.equal(tokenGrowth.bytes_saved, 0); + assert.equal(tokenGrowth.round_trips_saved, 0); + assert.equal(tokenGrowth.net_savings_tokens, -444); + + // 2. Small raw token savings (+100) that fail cold-prefill amortization on 5,400-token prompt -> KeepRaw. + const failsColdPrefill = evaluateEpochPrefetchPromptGate({ + has_inline_exploratory: true, + replace_exploratory_context: true, + rendered_prompt_baseline_bytes: 26_000, + rendered_prompt_delivered_bytes: 23_500, + rendered_prompt_baseline_tokens: 5_500, + rendered_prompt_delivered_tokens: 5_400, + potential_bytes_saved: 2_500, + tokenizer, + }); + assert.equal(failsColdPrefill.operator, "KeepRaw"); + assert.equal(failsColdPrefill.fallback_reason, "negative_net_savings"); + assert.equal(failsColdPrefill.net_savings_tokens, 100); + assert.equal(failsColdPrefill.cold_prefill_amortization_tokens, 270); + assert.equal(failsColdPrefill.amortized_net_savings_tokens, -170); + + // 3. Missing tokenizer provenance / token counts fail closed to KeepRaw. + const missingTokens = evaluateEpochPrefetchSwap({ + epoch_prefetch: {enabled: true, prefetch_command: ["cat", "summary.txt"]}, + context_epoch: "epoch-tok-missing", + baseline_bytes: 8_192, + exit_code: 0, + prefetched_output: "short", + require_token_gate: true, + }); + assert.equal(missingTokens.operator, "KeepRaw"); + assert.equal(missingTokens.fallback_reason, "token_estimation_unavailable"); + + // 4. Genuine net token savings clearing cold-prefill amortization + min_net_savings_tokens commits EpochReset. + const genuineSavings = evaluateEpochPrefetchPromptGate({ + has_inline_exploratory: true, + replace_exploratory_context: true, + rendered_prompt_baseline_bytes: 28_000, + rendered_prompt_delivered_bytes: 22_000, + rendered_prompt_baseline_tokens: 6_800, + rendered_prompt_delivered_tokens: 5_100, + potential_bytes_saved: 6_000, + tokenizer, + }); + assert.equal(genuineSavings.operator, "EpochReset"); + assert.equal(genuineSavings.status, "committed"); + assert.equal(genuineSavings.bytes_saved, 6_000); + assert.equal(genuineSavings.net_savings_tokens, 1_700); + assert.equal(genuineSavings.cold_prefill_amortization_tokens, 255); + assert.equal(genuineSavings.amortized_net_savings_tokens, 1_445); + assert.equal(genuineSavings.round_trips_saved, 1); + + // 5. Unmeasurable host input fails closed to KeepRaw with typed fallback_reason=host_input_unmeasurable. + const unmeasurable = evaluateEpochPrefetchPromptGate({ + has_inline_exploratory: true, + replace_exploratory_context: true, + host_input_measurable: false, + rendered_prompt_baseline_bytes: null, + rendered_prompt_delivered_bytes: null, + rendered_prompt_baseline_tokens: null, + rendered_prompt_delivered_tokens: null, + potential_bytes_saved: 6_000, + tokenizer, + }); + assert.equal(unmeasurable.operator, "KeepRaw"); + assert.equal(unmeasurable.fallback_reason, "host_input_unmeasurable"); + assert.equal(unmeasurable.bytes_saved, 0); + assert.equal(unmeasurable.round_trips_saved, 0); +}); + +test("computeQuietTurnStateDigest ignores volatile read envelopes and detects real state changes", () => { + const baseContract = { + goal_id: "g-quiet", + effective_action: "terminal_no_followup", + interaction_contract: { + mode: "terminal_no_followup", + agent_channel: {must_attempt: false, delivery_allowed: false, quiet_noop_allowed: true}, + }, + agent_todo_summary: {open_count: 1, monitor_due_count: 0}, + }; + const d1 = computeQuietTurnStateDigest({ + goal_id: "g-quiet", + agent_id: "a1", + route: {kind: "wait", would_invoke_host: false}, + work_contract: { + ...baseContract, + projection_envelope: {observed_at: "2026-11-24T10:00:00Z", age_seconds: 0}, + contract_binding: {source_decision_hash: "sha256:" + "1".repeat(64)}, + heartbeat_receipt: {turn_instance_id: "t-1"}, + }, + }); + const d2 = computeQuietTurnStateDigest({ + goal_id: "g-quiet", + agent_id: "a1", + route: {kind: "wait", would_invoke_host: false}, + work_contract: { + ...baseContract, + projection_envelope: {observed_at: "2026-11-24T10:05:00Z", age_seconds: 5}, + contract_binding: {source_decision_hash: "sha256:" + "2".repeat(64)}, + heartbeat_receipt: {turn_instance_id: "t-2"}, + }, + }); + assert.equal(d1.state_digest, d2.state_digest); + assert.equal(d1.must_attempt, false); + assert.equal(d1.quiet_noop_allowed, true); + + const dChanged = computeQuietTurnStateDigest({ + goal_id: "g-quiet", + agent_id: "a1", + route: {kind: "wait", would_invoke_host: false}, + work_contract: { + ...baseContract, + agent_todo_summary: {open_count: 2, monitor_due_count: 1}, + }, + }); + assert.notEqual(d1.state_digest, dChanged.state_digest); +}); + +test('semantic-unit anchor & FoldToReceipt contract preserves parent KV prefix and rolls back atomically to KeepRaw', () => { + const prefixDigest = 'a'.repeat(64); + const receiptSha = 'b'.repeat(64); + const sourceSha = 'c'.repeat(64); + const anchor = recordSemanticUnitAnchor({ + todo_id: 'todo_unit_1', + turn_instance_id: 'turn_inst_1', + anchor_step_index: 4, + anchor_surface_seq: 10, + prefix_digest: prefixDigest, + context_epoch: 'epoch-todo-1', + goal_id: 'goal-1', + agent_id: 'agent-1', + }); + assert.equal(anchor.schema_version, 'loopx_semantic_unit_anchor_v0'); + assert.equal(anchor.prefix_digest, prefixDigest); + assert.match(String(anchor.anchor_sha256), /^[a-f0-9]{64}$/); + + const validReceipt = { + todo_id: 'todo_unit_1', + completion_receipt_id: 'cqr_unit_1', + exit_code: 0, + sha256: receiptSha, + failure_facts: ['check-1 previously warned on stale fixture'], + open_obligations: ['verify downstream caller readback'], + source_ref: {path: 'captures/todo-unit-1.json', sha256: sourceSha}, + }; + const validTokenizer = {name: 'tiktoken', encoding: 'o200k_base'}; + + // 1. Default-off keeps raw state intact cleanly. + const disabled = buildSemanticUnitFoldSwap({ + enabled: false, + anchor, + todo_id: 'todo_unit_1', + turn_instance_id: 'turn_inst_1', + context_epoch: 'epoch-todo-1', + prefix_digest: prefixDigest, + now_step_index: 12, + now_surface_seq: 28, + completion_receipt: validReceipt, + }); + assert.equal(disabled.operator, 'KeepRaw'); + assert.equal(disabled.status, 'disabled'); + assert.equal(disabled.preserves_raw_state, true); + assert.equal(disabled.preserves_prefix_kv, true); + assert.equal(disabled.reclaim_range, null); + + // 2. Positive receipt-gated FoldToReceipt with bounded Obs(next_cmd) & token savings. + const committed = buildSemanticUnitFoldSwap({ + enabled: true, + anchor, + todo_id: 'todo_unit_1', + turn_instance_id: 'turn_inst_1', + context_epoch: 'epoch-todo-1', + prefix_digest: prefixDigest, + now_step_index: 12, + now_surface_seq: 28, + completion_receipt: validReceipt, + baseline_tokens: 1800, + replacement_tokens: 160, + baseline_bytes: 7200, + tokenizer: validTokenizer, + obs_next_cmd: { + command: ['git', 'status', '--short'], + exit_code: 0, + output: 'M loopx/control_plane/quota/stage_then_swap.ts', + truncated: false, + latency_ms: 14, + }, + }); + assert.equal(committed.operator, 'FoldToReceipt'); + assert.equal(committed.status, 'committed'); + assert.equal(committed.preserves_raw_state, false); + assert.equal(committed.preserves_prefix_kv, true); + assert.deepEqual(committed.reclaim_range, [4, 12]); + assert.equal(committed.round_trips_saved, 1); + assert.equal(committed.net_savings_tokens, 1640); + assert.equal(committed.amortized_net_savings_tokens, 1632); + assert.match(String(committed.replacement_text), /\[Semantic-Unit Fold Receipt mu \| trust=tool\]/); + assert.match(String(committed.replacement_text), /--- obs_next_cmd ---/); + assert.match(String(committed.replacement_text), /verify downstream caller readback/); + + // 3. Atomic fail-closed KeepRaw rollback across critical invariants. + const failures: Array<[Record, string]> = [ + [{completion_receipt: null, baseline_tokens: 1800, replacement_tokens: 160, tokenizer: validTokenizer}, 'missing_completion_receipt'], + [{completion_receipt: {...validReceipt, exit_code: 2}, baseline_tokens: 1800, replacement_tokens: 160, tokenizer: validTokenizer}, 'command_error'], + [{ + completion_receipt: validReceipt, + baseline_tokens: 1800, + replacement_tokens: 160, + tokenizer: validTokenizer, + obs_next_cmd: {command: ['git', 'push', 'origin', 'main'], exit_code: 0, output: 'bad'}, + }, 'policy_violation:git_subcommand_not_read_only'], + [{ + completion_receipt: validReceipt, + baseline_tokens: 200, + replacement_tokens: 160, + tokenizer: validTokenizer, + }, 'negative_net_savings'], + [{ + completion_receipt: validReceipt, + prefix_digest: 'd'.repeat(64), + baseline_tokens: 1800, + replacement_tokens: 160, + tokenizer: validTokenizer, + }, 'prefix_digest_mismatch'], + [{ + completion_receipt: validReceipt, + context_epoch: 'epoch-other', + baseline_tokens: 1800, + replacement_tokens: 160, + tokenizer: validTokenizer, + }, 'context_epoch_mismatch'], + [{ + completion_receipt: validReceipt, + tool_pairing_valid: false, + baseline_tokens: 1800, + replacement_tokens: 160, + tokenizer: validTokenizer, + }, 'unpaired_tool_calls'], + [{ + completion_receipt: validReceipt, + quiescent_boundary: false, + baseline_tokens: 1800, + replacement_tokens: 160, + tokenizer: validTokenizer, + }, 'non_quiescent_boundary'], + ]; + for (const [override, expectedReason] of failures) { + const rolledBack = buildSemanticUnitFoldSwap({ + enabled: true, + anchor, + todo_id: 'todo_unit_1', + turn_instance_id: 'turn_inst_1', + context_epoch: 'epoch-todo-1', + prefix_digest: prefixDigest, + now_step_index: 12, + now_surface_seq: 28, + ...override, + }); + assert.equal(rolledBack.operator, 'KeepRaw', `expected KeepRaw for ${expectedReason}`); + assert.equal(rolledBack.status, 'fallback_keep_raw'); + assert.equal(rolledBack.fallback_reason, expectedReason); + assert.equal(rolledBack.preserves_raw_state, true); + assert.equal(rolledBack.preserves_prefix_kv, true); + assert.equal(rolledBack.reclaim_range, null); + assert.equal(rolledBack.replacement_text, null); + } + + // 4. Native context lifecycle retains semantic_unit_anchors across idempotent PreCompact->PostCompact->SessionStart(compact) + // and clears them when context_epoch rotates. + const s0 = updateNativeContextLifecycle({ + state: {}, + event: {hook_event_name: 'SessionStart', session_id: 'sess-1', cwd: '/repo', source: 'startup'}, + new_epoch: 'epoch-1', + pages: [], + semantic_unit_anchor: recordSemanticUnitAnchor({ + todo_id: 'todo_unit_1', + turn_instance_id: 'turn_inst_1', + anchor_step_index: 2, + prefix_digest: prefixDigest, + context_epoch: 'epoch-1', + }), + }); + assert.ok((s0.semantic_unit_anchors as Record)?.todo_unit_1); + const sCompact = updateNativeContextLifecycle({ + state: s0, + event: {hook_event_name: 'PreCompact', session_id: 'sess-1', cwd: '/repo'}, + new_epoch: 'epoch-2', + pages: [], + }); + assert.equal(sCompact.context_epoch, 'epoch-1'); + assert.ok((sCompact.semantic_unit_anchors as Record)?.todo_unit_1); + + const sRotated = updateNativeContextLifecycle({ + state: {...sCompact, candidate: {basis: 'native_hook_assumption', capture_bytes_verified: true}}, + event: {hook_event_name: 'PreCompact', session_id: 'sess-1', cwd: '/repo'}, + new_epoch: 'epoch-2', + pages: [], + }); + assert.equal(sRotated.context_epoch, 'epoch-2'); + assert.equal(sRotated.semantic_unit_anchors, undefined); +});