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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 55 additions & 4 deletions src/codex_plugin_scanner/guard/runtime/command_executors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from __future__ import annotations

import base64
import json
import tempfile
from collections.abc import Callable
from datetime import datetime, timezone
Expand Down Expand Up @@ -47,6 +49,7 @@
_GUARD_REVIEW_MEMORY_REGISTRY_SYNC_KEY = "guard_review_memory_registry"
Comment thread
greptile-apps[bot] marked this conversation as resolved.
_GUARD_REVIEW_MEMORY_VERSION_SYNC_KEY = "guard_review_memory_policy_version"
_GUARD_REVIEW_MEMORY_ACK_SYNC_KEY = "guard_review_memory_last_ack"
_LOCAL_REQUEST_SNAPSHOT_CURSOR_SYNC_KEY = "guard_command_local_request_snapshot_cursor"

PACKAGE_SHIM_OPERATIONS: tuple[str, ...] = (
"guard.packageShims.status",
Expand All @@ -69,8 +72,8 @@
)
SUPPORTED_COMMAND_OPERATIONS: tuple[str, ...] = (*PACKAGE_SHIM_OPERATIONS, *APP_OPERATIONS, *APPROVAL_OPERATIONS)
COMMAND_OPERATION_SCHEMA_VERSIONS: dict[str, int] = {operation: 1 for operation in SUPPORTED_COMMAND_OPERATIONS}
LOCAL_REQUEST_PENDING_SNAPSHOT_LIMIT = 10_000
LOCAL_REQUEST_RESOLVED_SNAPSHOT_LIMIT = 500
LOCAL_REQUEST_PENDING_SNAPSHOT_LIMIT = 125
LOCAL_REQUEST_RESOLVED_SNAPSHOT_LIMIT = 25


def execute_guard_command_job(
Expand Down Expand Up @@ -467,7 +470,16 @@ def _local_request_snapshot_items_for_status(
oauth = guard_review_oauth_metadata(store)
except GuardReviewContractError:
oauth = None
rows = store.list_approval_requests(status=status, limit=limit + 1)
cursor_state = _local_request_snapshot_cursor_state(store)
cursor = cursor_state.get(status)
rows = store.list_approval_requests(
status=status,
limit=limit + 1,
cursor=cursor if isinstance(cursor, str) and cursor else None,
)
if not rows and isinstance(cursor, str) and cursor:
cursor = None
rows = store.list_approval_requests(status=status, limit=limit + 1)
for item in rows[:limit]:
request_id = item.get("request_id")
if not isinstance(request_id, str) or not request_id:
Expand Down Expand Up @@ -500,7 +512,46 @@ def _local_request_snapshot_items_for_status(
"resolvedAt": str(resolved_at) if isinstance(resolved_at, str) and resolved_at else None,
}
)
return items, len(rows) <= limit
if rows:
cursor_state[status] = _local_request_snapshot_next_cursor(rows, limit)
_save_local_request_snapshot_cursor_state(store, cursor_state)
return items, cursor is None and len(rows) <= limit


def _local_request_snapshot_cursor_state(store: GuardStore) -> dict[str, object]:
value = store.get_sync_payload(_LOCAL_REQUEST_SNAPSHOT_CURSOR_SYNC_KEY)
return dict(value) if isinstance(value, dict) else {}


def _save_local_request_snapshot_cursor_state(
store: GuardStore,
state: dict[str, object],
) -> None:
cleaned = {
key: value
for key, value in state.items()
if key in {"pending", "resolved"} and isinstance(value, str) and value
}
store.set_sync_payload(_LOCAL_REQUEST_SNAPSHOT_CURSOR_SYNC_KEY, cleaned, _now())


def _local_request_snapshot_next_cursor(
rows: list[dict[str, object]],
limit: int,
) -> str | None:
if len(rows) <= limit:
return None
last_item = rows[limit - 1]
payload = {
"last_seen_at": str(last_item.get("last_seen_at") or last_item.get("created_at") or ""),
"request_id": str(last_item.get("request_id") or ""),
}
if not payload["last_seen_at"] or not payload["request_id"]:
return None
encoded = base64.urlsafe_b64encode(
json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8"),
).decode("ascii")
return encoded.rstrip("=")


def _resolve_cloud_receipt_redaction_level(store: GuardStore) -> str:
Expand Down
90 changes: 90 additions & 0 deletions tests/test_guard_command_snapshot_paging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""Regression coverage for Cloud command local request snapshot paging."""

from __future__ import annotations

import base64
import json
from pathlib import Path

from codex_plugin_scanner.guard.runtime import command_executors


class PagingStore:
def __init__(self, guard_home: Path) -> None:
self.guard_home = guard_home
self.payloads: dict[str, object] = {}

def get_sync_payload(self, key: str) -> object | None:
return self.payloads.get(key)

def set_sync_payload(self, key: str, payload: object, now: str) -> None:
del now
self.payloads[key] = payload

def get_oauth_local_credentials(self, *, allow_primary: bool = False) -> object | None:
del allow_primary
return None

def list_approval_requests(
self,
*,
status: str | None = "pending",
harness: str | None = None,
limit: int | None = 50,
cursor: str | None = None,
search: str | None = None,
) -> list[dict[str, object]]:
del harness, search
if status != "pending":
return []
rows = [_approval_request_row(index) for index in range(130)]
if cursor:
padded = cursor + ("=" * (-len(cursor) % 4))
decoded = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8"))
marker_last_seen = decoded["last_seen_at"]
marker_request_id = decoded["request_id"]
rows = [
row
for row in rows
if (
str(row["last_seen_at"]) < marker_last_seen
or (str(row["last_seen_at"]) == marker_last_seen and str(row["request_id"]) < marker_request_id)
)
]
return rows if limit is None else rows[:limit]


def _approval_request_row(index: int) -> dict[str, object]:
return {
"request_id": f"req-pending-{index:03d}",
"status": "pending",
"harness": "codex",
"artifact_id": f"artifact-{index:03d}",
"artifact_hash": "b" * 64,
"policy_action": "require-reapproval",
"recommended_scope": "artifact",
"created_at": "2026-05-14T11:58:00.000Z",
"last_seen_at": f"2026-05-14T11:{59 - (index // 10):02d}:{59 - (index % 10):02d}.000Z",
"queue_group_id": "queue-group-1",
"action_envelope_json": {
"action_type": "shell_command",
"command": "npm install minimist@1.2.8",
"tool_name": "Bash",
},
}


def test_local_request_snapshot_pages_large_pending_backlog(tmp_path: Path) -> None:
store = PagingStore(tmp_path / "guard-home")

first_payload = command_executors._local_request_snapshot_payload(store)
second_payload = command_executors._local_request_snapshot_payload(store)

assert first_payload["pendingComplete"] is False
assert first_payload["pendingCount"] == command_executors.LOCAL_REQUEST_PENDING_SNAPSHOT_LIMIT
assert first_payload["requests"][0]["localRequestId"] == "req-pending-000"
assert first_payload["requests"][-1]["localRequestId"] == "req-pending-124"
assert second_payload["pendingComplete"] is False
assert second_payload["pendingCount"] == 5
assert second_payload["requests"][0]["localRequestId"] == "req-pending-125"
assert second_payload["requests"][-1]["localRequestId"] == "req-pending-129"
Loading