Skip to content
Closed
15 changes: 14 additions & 1 deletion loopx/cli_commands/quota_native_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,8 @@ def _handle_context_config(
cli_argv += ["--runtime-root", str(Path(hook_runtime).expanduser().resolve())]
config = codex_context_configuration(directory, goal_id=args.goal_id, agent_id=args.agent_id,
cli_argv=cli_argv, scenario=activation["scenario"], session_root=bool(getattr(args, "codex_context_root", None)),
inherit_machine=bool(machine_runtime), progressive_enabled=activation["progressive_enabled"])
inherit_machine=bool(machine_runtime), progressive_enabled=activation["progressive_enabled"],
compact_direct_read=bool(getattr(args, "compact_direct_read", False)))
explicit_options = "--context-delivery on" if activation["progressive_enabled"] else "--context-delivery off --delta-delivery auto"
payload = {"ok": True, "context_delivery": activation, "native_config": config,
"activation": "Apply config_overrides, merge hooks and append developer_instructions to the existing native configuration; "
Expand Down Expand Up @@ -428,6 +429,8 @@ def _handle_context_hook(args: argparse.Namespace, *, activation: dict[str, Any]
raise ValueError("context directory unavailable")
scenario = activation["scenario"]
progressive_enabled = activation["progressive_enabled"]
if getattr(args, "compact_direct_read", False) and "compact_direct_read" not in event:
event = {**event, "compact_direct_read": True}
payload = codex_context_hook(directory, event)
request = None
preparation_context = ""
Expand Down Expand Up @@ -507,7 +510,13 @@ def _handle_context_hook(args: argparse.Namespace, *, activation: dict[str, Any]
if preparation_context:
existing = payload.get("hookSpecificOutput")
existing_context = str(existing.get("additionalContext") or "") if isinstance(existing, dict) else ""
preserved = (
{k: v for k, v in existing.items() if k not in ("hookEventName", "additionalContext")}
if isinstance(existing, dict)
else {}
)
payload["hookSpecificOutput"] = {
**preserved,
"hookEventName": event["hook_event_name"],
"additionalContext": " ".join(filter(None, [existing_context, preparation_context])),
}
Expand All @@ -528,6 +537,10 @@ def handle_native_context_command(args: argparse.Namespace, *, print_payload: Ca
print_payload({"ok": False, "reason": "--prepared-claim-operation-id requires quota context-project"},
args.format, str)
return 1
if getattr(args, "compact_direct_read", False) and args.quota_command not in ("context-config", "context-hook"):
print_payload({"ok": False, "reason": "--compact-direct-read is only supported by context-config or context-hook"},
args.format, str)
return 1
if getattr(args, "complete_turn", False) and (args.quota_command != "should-run" or args.format != "json"):
print_payload({"ok": False, "reason": "--complete-turn requires JSON quota should-run"}, args.format, str)
return 1
Expand Down
2 changes: 2 additions & 0 deletions loopx/cli_commands/quota_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,8 @@ def register_quota_command(
help="Existing private native context root, with independent journals per native session. "
"Use for shared Codex App hook configuration; cannot combine with --codex-context-dir. "
"context-config renders native configuration for the exact Goal/Agent; no host configuration, trust, guard or spend are changed.")
quota_parser.add_argument("--compact-direct-read", action="store_true",
help="Opt-in Phase-2 lock-free in-process JSON pointer read, wake deduplication, and automatic failure/obligation extraction for native compact hooks.")
quota_parser.add_argument("--capture-sha256",
help="For context-read, context-project or replan-view: exact SHA-256 supplied with the capture reference.")
quota_parser.add_argument("--initial-read", action="store_true",
Expand Down
8 changes: 8 additions & 0 deletions loopx/control_plane/effect_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1120,6 +1120,14 @@ def _locator_projection_after_probe(
return state, recorded_pid_alive, diagnostic_code


def runtime_currently_serving() -> bool:
"""Non-blocking probe reporting whether an HTTP control-plane daemon is alive now."""
if _uses_stdio_runtime():
return False
fingerprint = _runtime_fingerprint()
return _read_info(_runtime_info_path(fingerprint), fingerprint=fingerprint) is not None


def _read_local_snapshot_response(
envelope: dict[str, Any], sink: Path | None, *, method: str, request_id: str, timeout: float,
) -> dict[str, Any]:
Expand Down
2 changes: 2 additions & 0 deletions loopx/control_plane/quota/native_context_lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export function updateNativeContextLifecycle(request: JsonObject): JsonObject {
if (state.context_epoch !== previousEpoch) {
delete state.epoch_prefetch;
delete state.quiet_turn;
delete state.compact_hook_wake;
}
}
delete state.candidate;
Expand Down Expand Up @@ -102,6 +103,7 @@ export function updateNativeContextLifecycle(request: JsonObject): JsonObject {
}
if (name === "PreCompact" || name === "PostCompact") {
invalidate();
delete state.compact_hook_wake;
return state;
}
if (name === "Interrupt") {
Expand Down
150 changes: 144 additions & 6 deletions loopx/control_plane/turn_driver/codex_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,8 @@ def codex_context_recovery_instructions(directory: str, *, goal_id: str, agent_i

def codex_context_configuration(directory: str, *, goal_id: str, agent_id: str,
cli_argv: list[str], scenario: str, session_root: bool = False,
inherit_machine: bool = False, progressive_enabled: bool = True) -> dict[str, Any]:
inherit_machine: bool = False, progressive_enabled: bool = True,
compact_direct_read: bool = False) -> dict[str, Any]:
"""Native configuration data shared by the worker and CLI setup journey.

This renders no trust hashes and writes no host configuration. The native
Expand All @@ -346,6 +347,7 @@ def codex_context_configuration(directory: str, *, goal_id: str, agent_id: str,
handler = {"type": "command", "command": shlex.join([
*cli_argv, "--format", "json", "quota", "context-hook",
*([] if inherit_machine else activation_args),
*(["--compact-direct-read"] if compact_direct_read else []),
*(["--codex-app"] if scenario == "codex_app_heartbeat" else
["--runtime-profile", "codex_app_ssh_goal" if scenario == "codex_app_ssh_goal" else "generic_cli"]),
option, directory]), "timeout": 10}
Expand All @@ -362,6 +364,120 @@ def codex_context_configuration(directory: str, *, goal_id: str, agent_id: str,
page_output_bytes=NATIVE_CONTEXT_LARGE_OUTPUT_BYTES)}


def _reduce_hook_lifecycle(
read_state: dict[str, Any],
state: dict[str, Any],
event: dict[str, Any],
*,
name: Any,
session: str,
same: bool,
pages: list[dict[str, Any]],
direct_read_cfg: Mapping[str, Any] | None,
update_fn: Callable[..., dict[str, Any]],
native_resume_verified_fn: Callable[[dict[str, Any], dict[str, Any]], bool],
native_resume_sections_fn: Callable[[dict[str, Any], dict[str, Any]], Any],
) -> dict[str, Any]:
"""Run TS lifecycle reduction, or fail-closed lock-free compact invalidation under contention."""
from ..effect_runtime import (
EffectRuntimeRemoteError,
EffectRuntimeStartupError,
runtime_currently_serving,
)
from .codex_hook_direct_read import apply_fail_closed_compact_invalidation

is_compact = name in ("PreCompact", "PostCompact") or (
name == "SessionStart" and event.get("source") == "compact"
)
lifecycle_unpatched = (
getattr(update_fn, "__module__", "") == "loopx.control_plane.quota.turn_envelope"
)
if (
direct_read_cfg is not None
and direct_read_cfg["lock_free"]
and is_compact
and same
and lifecycle_unpatched
and not runtime_currently_serving()
):
return apply_fail_closed_compact_invalidation(
read_state,
session=session,
cwd=str(event.get("cwd") or ""),
new_epoch=uuid.uuid4().hex,
hook_name=name if isinstance(name, str) else None,
)
resume_verified = name == "SessionStart" and native_resume_verified_fn(state, event)
try:
return update_fn(
read_state,
event,
new_epoch=uuid.uuid4().hex,
pages=pages,
pages_verified=True,
resume_verified=resume_verified,
resume_sections=(
native_resume_sections_fn(state, event)
if name == "SessionStart" and not resume_verified
else None
),
)
except (EffectRuntimeRemoteError, EffectRuntimeStartupError):
if direct_read_cfg is not None and is_compact and same:
return apply_fail_closed_compact_invalidation(
read_state,
session=session,
cwd=str(event.get("cwd") or ""),
new_epoch=uuid.uuid4().hex,
hook_name=name if isinstance(name, str) else None,
)
raise


def _maybe_resolve_compact_direct_read(
root: Path,
updated: dict[str, Any],
*,
name: Any,
event: dict[str, Any],
recovery: Any,
recovery_needed: bool,
direct_read_cfg: Mapping[str, Any] | None,
) -> dict[str, Any] | None:
"""Resolve Phase-2 compact hook direct-read and persist updated wake/telemetry state."""
from .codex_hook_direct_read import resolve_compact_hook_direct_read

if direct_read_cfg is None or name != "SessionStart":
return None
saved = updated.get("recovery")
active_recovery = (
recovery
if isinstance(recovery, Mapping)
else (saved if isinstance(saved, Mapping) else None)
)
cmd = str(active_recovery.get("command") or "") if isinstance(active_recovery, Mapping) else ""
continuation_text = _context_continuation_instructions(cmd) if cmd else ""
raw_guidance_text = (
CONTEXT_CAPTURE_SELECTION_GUIDANCE
+ _NATIVE_CONTEXT_OUTPUT_GUIDANCE
+ "If you choose to read an entire file: "
+ CONTEXT_CAPTURE_PAGE_GUIDANCE
) if cmd else ""
direct_state = dict(updated)
reply = resolve_compact_hook_direct_read(
hook_name=name,
state=direct_state,
event=event,
recovery=active_recovery,
recovery_needed=recovery_needed,
continuation_text=continuation_text,
raw_guidance_text=raw_guidance_text,
)
if reply is not None and direct_state != updated:
_save(root, direct_state)
return reply


def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str, Any]:
"""Native IO around the shared typed lifecycle owner, without input tracing.

Expand All @@ -375,6 +491,7 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str
checkpoint_native_read, checkpoint_native_selection, native_resume_sections, native_resume_verified,
observe_native_read,
)
from .codex_hook_direct_read import resolve_compact_direct_read_config

if directory is None:
return {}
Expand All @@ -389,13 +506,15 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str
return {} # ordinary tool use neither invalidates nor rewrites the journal
state: dict[str, Any] = {}
recovery = None
direct_reply: dict[str, Any] | None = None
try:
with _locked(directory) as root:
try:
state = _state(root)
read_state = state
same_session = state.get("session_id") == session
same = same_session and state.get("cwd") == event.get("cwd")
direct_read_cfg = resolve_compact_direct_read_config(state, event)
if same:
recovery = state.get("recovery")
if name == "PostToolUse":
Expand All @@ -408,11 +527,19 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str
pages = _verified_context_pages(state, pages, selected_only=True)
if not pages or not isinstance(event.get("cwd"), str) or not event["cwd"]:
return {}
resume_verified = name == "SessionStart" and native_resume_verified(state, event)
updated = update_native_context_lifecycle(read_state, event,
new_epoch=uuid.uuid4().hex, pages=pages, pages_verified=True,
resume_verified=resume_verified,
resume_sections=native_resume_sections(state, event) if name == "SessionStart" and not resume_verified else None)
updated = _reduce_hook_lifecycle(
read_state,
state,
event,
name=name,
session=session,
same=same,
pages=pages,
direct_read_cfg=direct_read_cfg,
update_fn=update_native_context_lifecycle,
native_resume_verified_fn=native_resume_verified,
native_resume_sections_fn=native_resume_sections,
)
if name == "PostToolUse" and same:
checkpoint_native_read(read_state, updated, event,
[page for page in pages if "read_sections" not in page])
Expand Down Expand Up @@ -440,6 +567,15 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str
and isinstance(saved.get("target"), dict)
and saved["target"].get("context_epoch") == updated.get("context_epoch"))
recovery_needed = same and not updated.get("candidate") and not current_file_epoch
direct_reply = _maybe_resolve_compact_direct_read(
root,
updated,
name=name,
event=event,
recovery=recovery,
recovery_needed=recovery_needed,
direct_read_cfg=direct_read_cfg,
)
except (OSError, ValueError, TypeError, RecursionError, EffectRuntimeRemoteError, EffectRuntimeStartupError):
# A transient read/reduction failure can miss invalidation just
# as a failed write can. While holding the same lock, retire
Expand All @@ -449,6 +585,8 @@ 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 direct_reply is not None:
return direct_reply
if (name == "SessionStart" and recovery_needed
and isinstance(recovery, dict) and recovery.get("command")):
from .epoch_prefetch import resolve_codex_context_epoch_prefetch_hook
Expand Down
Loading
Loading