diff --git a/README.md b/README.md index 9ef79fc0..8a119206 100644 --- a/README.md +++ b/README.md @@ -755,7 +755,7 @@ prompts, files the agent reads, and MCP tool arguments are scanned for secrets b Scanning happens server-side, so the scanned content leaves the machine: the prompt text, the contents of files the agent reads, and MCP tool arguments are sent to your Cycode tenant to be checked for secrets. -For GitHub Copilot, PNG and JPEG images attached to a prompt are sent along with its text. +For GitHub Copilot, Claude Code, Codex and Cursor, PNG and JPEG images attached to a prompt are sent along with its text. Each event is also reported with context about the developer and the machine, so a finding can be attributed to the device and user it came from. Some of this is personal data: diff --git a/cycode/cli/apps/ai_guardrails/ides/_transcript_utils.py b/cycode/cli/apps/ai_guardrails/ides/_transcript_utils.py new file mode 100644 index 00000000..ab9106d3 --- /dev/null +++ b/cycode/cli/apps/ai_guardrails/ides/_transcript_utils.py @@ -0,0 +1,45 @@ +"""Shared transcript helpers for IDE integrations. + +Agents keep a session's transcript as JSONL that grows with every turn, images included, so it is read from +the end. +""" + +from collections.abc import Iterator +from pathlib import Path + + +def reverse_readline(path: Path, buf_size: int = 8192) -> Iterator[str]: + """Yield lines of `path` from end to start without loading the file. + + A transcript can be very large; reading from the tail keeps memory bounded + since only the most recent entries are wanted. + """ + with path.open('rb') as f: + f.seek(0, 2) + file_size = f.tell() + if file_size == 0: + return + + remaining = file_size + buffer = b'' + + while remaining > 0: + read_size = min(buf_size, remaining) + remaining -= read_size + f.seek(remaining) + chunk = f.read(read_size) + buffer = chunk + buffer + + while b'\n' in buffer: + newline_pos = buffer.rfind(b'\n') + if newline_pos == len(buffer) - 1: + newline_pos = buffer.rfind(b'\n', 0, newline_pos) + if newline_pos == -1: + break + line = buffer[newline_pos + 1 :] + buffer = buffer[: newline_pos + 1] + if line.strip(): + yield line.decode('utf-8', errors='replace') + + if buffer.strip(): + yield buffer.decode('utf-8', errors='replace') diff --git a/cycode/cli/apps/ai_guardrails/ides/_vscode_utils.py b/cycode/cli/apps/ai_guardrails/ides/_vscode_utils.py new file mode 100644 index 00000000..15f0781e --- /dev/null +++ b/cycode/cli/apps/ai_guardrails/ides/_vscode_utils.py @@ -0,0 +1,21 @@ +"""Shared helpers for VS Code and its forks, such as Cursor: where they keep their data, and reading their databases.""" + +import platform +import sqlite3 +from contextlib import closing +from pathlib import Path + + +def vscode_user_data_dir(product_name: str = 'Code') -> Path: + """Per-platform user data directory of VS Code or a fork: 'Code', 'Code - Insiders' or 'Cursor'.""" + if platform.system() == 'Darwin': + return Path.home() / 'Library' / 'Application Support' / product_name + if platform.system() == 'Windows': + return Path.home() / 'AppData' / 'Roaming' / product_name + return Path.home() / '.config' / product_name + + +def read_only_query(db_path: Path, sql: str, params: tuple = ()) -> list[tuple]: + """The rows of a query on an app's SQLite database, opened read-only: the app keeps writing to the file.""" + with closing(sqlite3.connect(f'{db_path.resolve().as_uri()}?mode=ro', uri=True, timeout=1)) as connection: + return connection.execute(sql, params).fetchall() diff --git a/cycode/cli/apps/ai_guardrails/ides/claude_code.py b/cycode/cli/apps/ai_guardrails/ides/claude_code.py index ca126d84..b7fed0b3 100644 --- a/cycode/cli/apps/ai_guardrails/ides/claude_code.py +++ b/cycode/cli/apps/ai_guardrails/ides/claude_code.py @@ -1,7 +1,9 @@ """Claude Code IDE integration for AI guardrails.""" import json +import os import re +import tempfile from collections.abc import Iterator from copy import deepcopy from pathlib import Path @@ -15,8 +17,16 @@ walk_enabled_plugins, ) from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_plugin_skills, walk_skill_dirs +from cycode.cli.apps.ai_guardrails.ides._transcript_utils import reverse_readline from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload +from cycode.cli.apps.ai_guardrails.scan.prompt_images import ( + PromptImage, + collect_since_prompt_mark, + image_chips, + mentioned_files, + modified_between, +) from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType from cycode.logger import get_logger @@ -39,45 +49,18 @@ _SCAN_COMMAND = f'{CYCODE_SCAN_PROMPT_COMMAND} --ide claude-code' _SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide claude-code' - -# --- transcript JSONL parsing ------------------------------------------------- +# Claude Code saves every image attached to a prompt (pasted, dragged in, or attached in VS Code or the desktop app) +# before the prompt's hook runs, as . in the session's folder of its temp directory, +# /claude-///images, the temp root being $CLAUDE_CODE_TMPDIR or /tmp. The number +# counts up across the session, and a pasted or dragged image shows in the prompt as its [Image #] chip. +_TEMP_DIR_ENV_VAR = 'CLAUDE_CODE_TMPDIR' +_SESSION_IMAGES_DIR_NAME = 'images' +_SAVED_IMAGE_NAME_PATTERN = re.compile(r'(\d+)\.[A-Za-z]+') +# The session id names a folder; one that could leave it (or match others) is not looked up +_SESSION_ID_PATTERN = re.compile(r'[A-Za-z0-9_-]+') -def _reverse_readline(path: Path, buf_size: int = 8192) -> Iterator[str]: - """Yield lines of `path` from end to start without loading the file. - - The Claude Code transcript can be very large; reading from the tail keeps - memory bounded since we only care about the most recent entries. - """ - with path.open('rb') as f: - f.seek(0, 2) - file_size = f.tell() - if file_size == 0: - return - - remaining = file_size - buffer = b'' - - while remaining > 0: - read_size = min(buf_size, remaining) - remaining -= read_size - f.seek(remaining) - chunk = f.read(read_size) - buffer = chunk + buffer - - while b'\n' in buffer: - newline_pos = buffer.rfind(b'\n') - if newline_pos == len(buffer) - 1: - newline_pos = buffer.rfind(b'\n', 0, newline_pos) - if newline_pos == -1: - break - line = buffer[newline_pos + 1 :] - buffer = buffer[: newline_pos + 1] - if line.strip(): - yield line.decode('utf-8', errors='replace') - - if buffer.strip(): - yield buffer.decode('utf-8', errors='replace') +# --- transcript JSONL parsing ------------------------------------------------- def _extract_model(entry: dict) -> str | None: @@ -112,7 +95,7 @@ def extract_from_claude_transcript( generation_id = None try: - for line in _reverse_readline(path): + for line in reverse_readline(path): line = line.strip() if not line: continue @@ -289,6 +272,60 @@ def _resolve_mcp_server_name(server: str, config: dict | None, cwd: str | None) return server +# --- prompt images ------------------------------------------------------------ + + +def _user_id() -> int | None: + """The process's uid; None on Windows, which has none.""" + return None if os.name == 'nt' else os.getuid() + + +def _session_image_dirs(session_id: str) -> list[Path]: + """The folders where Claude Code saved this session's images (normally one). + + Without a uid (Windows) the folder is looked for under any claude* folder of the system temp directory. + """ + if not _SESSION_ID_PATTERN.fullmatch(session_id): + return [] + override = os.environ.get(_TEMP_DIR_ENV_VAR) + uid = _user_id() + if uid is not None: + root = Path(override or '/tmp') # noqa: S108 - Claude Code's own location, read only + user_dir_pattern = f'claude-{uid}' + else: + root = Path(override or tempfile.gettempdir()) + user_dir_pattern = 'claude*' + pattern = f'{user_dir_pattern}/*/{session_id}/{_SESSION_IMAGES_DIR_NAME}' + return [path for path in root.glob(pattern) if path.is_dir()] + + +def _saved_session_images(session_id: str | None, prompt: str, since: float, until: float) -> list[Path]: + """This prompt's images among those Claude Code saved for the session. + + Those its chips name, then those saved since the session's previous prompt: VS Code and the desktop app put no chip + in the prompt. Claude Code also saves an image again when its prompt is sent, so a prompt sent again after a block + finds it in that window too. The chips don't rely on that: they are the prompt's own reference to its files, so a + named image is found even if Claude Code didn't save it again. + """ + if not isinstance(session_id, str) or not session_id: + return [] + saved: dict[int, Path] = {} + for directory in _session_image_dirs(session_id): + try: + paths = list(directory.iterdir()) + except OSError as e: + logger.debug('Failed to list a session images folder, %s', {'path': str(directory)}, exc_info=e) + continue + for path in paths: + match = _SAVED_IMAGE_NAME_PATTERN.fullmatch(path.name) + if match: + saved.setdefault(int(match.group(1)), path) + + chips = dict.fromkeys(int(number) for number in image_chips(prompt)) + named = [saved[number] for number in chips if number in saved] + return named + modified_between(saved.values(), since, until) + + # --- IDE integration ---------------------------------------------------------- @@ -393,6 +430,18 @@ def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload: mcp_arguments=mcp_arguments, ) + def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]: + """Images attached to a prompt: those Claude Code saved for it, and `@path` mentions.""" + session_id = raw_payload.get('session_id') + prompt = raw_payload.get('prompt') or '' + return collect_since_prompt_mark( + session_id, + lambda since, until: [ + *_saved_session_images(session_id, prompt, since, until), + *mentioned_files(prompt, raw_payload.get('cwd')), + ], + ) + def build_hook_response(self, decision: HookDecision) -> dict: if decision.event_type == AiHookEventType.PROMPT: if decision.action == DecisionAction.ALLOW: diff --git a/cycode/cli/apps/ai_guardrails/ides/codex.py b/cycode/cli/apps/ai_guardrails/ides/codex.py index cb8e6deb..88282b1c 100644 --- a/cycode/cli/apps/ai_guardrails/ides/codex.py +++ b/cycode/cli/apps/ai_guardrails/ides/codex.py @@ -4,7 +4,10 @@ import os import re import sys +import tempfile +import time from collections.abc import Iterator +from datetime import datetime from pathlib import Path from typing import ClassVar @@ -23,8 +26,16 @@ walk_enabled_plugins, ) from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_plugin_skills, walk_skill_dirs +from cycode.cli.apps.ai_guardrails.ides._transcript_utils import reverse_readline from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload +from cycode.cli.apps.ai_guardrails.scan.prompt_images import ( + PromptImage, + image_chips, + mentioned_files, + modified_between, + select_prompt_images, +) from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType from cycode.cli.utils.jwt_utils import decode_jwt_unverified from cycode.logger import get_logger @@ -43,6 +54,17 @@ _SCAN_COMMAND = f'{CYCODE_SCAN_PROMPT_COMMAND} --ide codex' _SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide codex' +# The prompt names each attached image only by an [Image #N] chip. Codex's terminal UI saves an image pasted from the +# clipboard as codex-clipboard-.png in the temp directory and keeps it; an image dragged in, picked from the +# @ popup or passed with --image is attached from where it is, and nothing names it. +_CLIPBOARD_IMAGE_GLOB = 'codex-clipboard-*.png' +# How long after its paste a prompt may still be sent with the image +_CLIPBOARD_IMAGE_MAX_AGE_SECONDS = 60 * 60 +# How long before a session's first prompt its pastes may have been made: Codex starts the transcript at that prompt +_FIRST_PROMPT_PASTE_LOOKBACK_SECONDS = 10 * 60 +# Transcript lines worth parsing: the session's start, a turn's start, and user messages +_TRANSCRIPT_LINE_MARKERS = ('session_meta', 'turn_context', '"user"') + def _codex_home() -> Path: """Resolve Codex's user-scope home directory. @@ -229,6 +251,99 @@ def _enable_codex_hooks_feature(scope: str, repo_path: Path | None = None) -> tu return False, f'Failed to write Codex config at {config_path}' +# --- prompt images ------------------------------------------------------------ + + +def _transcript_time(item: dict) -> float | None: + """When a transcript line was written, from its timestamp such as 2026-11-17T16:27:50.595Z.""" + timestamp = item.get('timestamp') + if not isinstance(timestamp, str): + return None + try: + return datetime.fromisoformat(timestamp.replace('Z', '+00:00')).timestamp() + except ValueError: + return None + + +def _is_user_message(item: dict) -> bool: + payload = item.get('payload') + return item.get('type') == 'response_item' and isinstance(payload, dict) and payload.get('role') == 'user' + + +def _transcript_items_newest_first(transcript_path: str) -> Iterator[dict]: + """The transcript's lines that may be a session's start, a turn's start or a user message, newest first.""" + for line in reverse_readline(Path(transcript_path)): + if not any(marker in line for marker in _TRANSCRIPT_LINE_MARKERS): + continue + try: + item = json.loads(line) + except ValueError: + continue + if isinstance(item, dict): + yield item + + +def _last_prompt_time(transcript_path: str) -> float | None: + """When the session's last prompt that its hook let through was sent, or None if none was. + + Codex writes a prompt into the transcript as a user message only once its hook lets it through; a blocked prompt + leaves only turn bookkeeping. Read from the end, which the last prompt is usually near. A user message is that + prompt once a turn's start shows up before it. If a session's start shows up first, the message came before the + session's first turn: it is the session's context, not a prompt, and the read goes on to the session before it. + """ + newest_message = None + for item in _transcript_items_newest_first(transcript_path): + kind = item.get('type') + if kind == 'turn_context' and newest_message is not None: + return newest_message + if kind == 'session_meta': + newest_message = None + elif newest_message is None and _is_user_message(item): + newest_message = _transcript_time(item) + return None + + +def _session_start_time(transcript_path: str) -> float | None: + """When the session (re)started: its latest session_meta, which Codex writes when its first prompt is submitted.""" + for item in _transcript_items_newest_first(transcript_path): + if item.get('type') == 'session_meta': + return _transcript_time(item) + return None + + +def _paste_window_start(transcript_path: str, now: float) -> float: + """Where the pastes this prompt may carry begin: at the session's last prompt that its hook let through. + + A blocked prompt isn't one, so its pastes are found again when it is sent again. Until a prompt goes through, the + window reaches back from the session's start. + """ + try: + last_prompt = _last_prompt_time(transcript_path) + if last_prompt is not None: + return last_prompt + session_start = _session_start_time(transcript_path) + except OSError as e: + logger.debug('Failed to read the Codex transcript, %s', {'path': transcript_path}, exc_info=e) + session_start = None + return (session_start if session_start is not None else now) - _FIRST_PROMPT_PASTE_LOOKBACK_SECONDS + + +def _pasted_clipboard_images(prompt: str, transcript_path: object, now: float) -> list[Path]: + """The newest clipboard pastes made since the session's last prompt that went through, one per [Image #N] chip. + + A chip doesn't say whether its image was pasted, dragged in or picked from the @ popup, so a dragged or picked + image takes in its place a paste made since then that a blocked prompt, or another session, left behind. Without + a transcript there is no session to go by, so none is taken: the prompt Codex sends to title a new thread has + none and quotes the user's prompt, chips included. + """ + chips_count = len(set(image_chips(prompt))) + if not chips_count or not isinstance(transcript_path, str) or not transcript_path: + return [] + since = max(_paste_window_start(transcript_path, now), now - _CLIPBOARD_IMAGE_MAX_AGE_SECONDS) + pastes = list(Path(tempfile.gettempdir()).glob(_CLIPBOARD_IMAGE_GLOB)) + return modified_between(pastes, since, now)[-chips_count:] + + class Codex(IDE): name: ClassVar[str] = 'codex' display_name: ClassVar[str] = 'Codex' @@ -302,6 +417,21 @@ def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload: mcp_arguments=mcp_arguments, ) + def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]: + """Images attached to a prompt: clipboard pastes, one per chip, and `@path` mentions. + + The payload names no image, and the transcript records a prompt only after its hook. + """ + prompt = raw_payload.get('prompt') or '' + images = select_prompt_images( + [ + *_pasted_clipboard_images(prompt, raw_payload.get('transcript_path'), time.time()), + *mentioned_files(prompt, raw_payload.get('cwd')), + ] + ) + logger.debug('Collected prompt images, %s', {'images_count': len(images)}) + return images + def build_hook_response(self, decision: HookDecision) -> dict: # Codex hook response shapes: # - allow: empty (no objection). Older Codex runtimes reject an explicit diff --git a/cycode/cli/apps/ai_guardrails/ides/copilot.py b/cycode/cli/apps/ai_guardrails/ides/copilot.py index caff99a3..8275c7ff 100644 --- a/cycode/cli/apps/ai_guardrails/ides/copilot.py +++ b/cycode/cli/apps/ai_guardrails/ides/copilot.py @@ -27,13 +27,10 @@ import json import os -import platform import re import sqlite3 import tempfile -import time from collections.abc import Iterable -from contextlib import closing from pathlib import Path from typing import ClassVar from urllib.parse import urlparse @@ -46,14 +43,14 @@ walk_enabled_plugins, ) from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_plugin_skills, walk_skill_dirs +from cycode.cli.apps.ai_guardrails.ides._vscode_utils import read_only_query, vscode_user_data_dir from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload from cycode.cli.apps.ai_guardrails.scan.prompt_images import ( PromptImage, - get_prompt_mark, + collect_since_prompt_mark, + mentioned_files, modified_between, - save_prompt_mark, - select_prompt_images, ) from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType from cycode.logger import get_logger @@ -112,13 +109,6 @@ _SCAN_COMMAND = f'{CYCODE_SCAN_PROMPT_COMMAND} --ide copilot' _SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide copilot' -# Copilot CLI leaves an `@path` mention in the prompt as typed: quoted, with -# backslash-escaped spaces (a file dragged into a terminal), or plain up to the next -# whitespace. Never mid-word, so an email address is not a mention. A lookahead, so -# every `@` is read on its own: a quote left open must not swallow the mentions after -# it, and a quoted path never spans lines. -_MENTION_PATTERN = re.compile(r'(? Path: return Path.home() / '.vscode' / 'agent-plugins' -def _vscode_user_data_dir(product_name: str = 'Code') -> Path: - """Per-platform VS Code user data directory; ``product_name`` is 'Code' or 'Code - Insiders'.""" - if platform.system() == 'Darwin': - return Path.home() / 'Library' / 'Application Support' / product_name - if platform.system() == 'Windows': - return Path.home() / 'AppData' / 'Roaming' / product_name - return Path.home() / '.config' / product_name - - def _vscode_user_dir() -> Path: """Per-platform VS Code user settings directory.""" - return _vscode_user_data_dir() / 'User' + return vscode_user_data_dir() / 'User' def _vscode_mcp_config_path() -> Path: @@ -423,27 +404,6 @@ def split_mcp_tool_name(tool_name: str, server_names: Iterable[str]) -> tuple[st # --- prompt images ------------------------------------------------------------------ -def _mentioned_files(prompt: str, cwd: str | None) -> list[Path]: - """Existing files named by `@` mentions, resolved against the hook's cwd.""" - base = Path(cwd) if cwd else Path() - files = [] - for match in _MENTION_PATTERN.finditer(prompt): - token = match.group(1) - if len(token) > 1 and token[0] == token[-1] and token[0] in '"\'': - spellings = [token[1:-1]] - else: - if os.sep == '/': - token = token.replace('\\ ', ' ') - # The mention may end a sentence ("look at @shot.png.") - spellings = [token, token.rstrip(_MENTION_TRAILING_PUNCTUATION)] - for spelling in spellings: - path = base / os.path.expanduser(spelling) - if os.path.isfile(path): - files.append(path) - break - return files - - def _pasted_cli_images(prompt: str) -> list[Path]: """Images pasted into Copilot CLI, saved in the temp directory its placeholder names.""" temp_dir = Path(tempfile.gettempdir()) @@ -459,9 +419,7 @@ def _vscode_chat_session_id(chat_dir: Path) -> str | None: placeholders = ', '.join('?' * len(_VSCODE_CHAT_SESSION_KEYS)) query = f'SELECT value FROM session_metadata WHERE key IN ({placeholders})' # noqa: S608 try: - # Read-only: VS Code keeps writing to the file while the chat is open - with closing(sqlite3.connect(f'{db_path.resolve().as_uri()}?mode=ro', uri=True, timeout=1)) as connection: - values = [value for (value,) in connection.execute(query, _VSCODE_CHAT_SESSION_KEYS)] + values = [value for (value,) in read_only_query(db_path, query, _VSCODE_CHAT_SESSION_KEYS)] except sqlite3.Error as e: logger.debug('Failed to read a VS Code chat session database, %s', {'path': str(db_path)}, exc_info=e) return None @@ -485,7 +443,7 @@ def _vscode_saved_attachments(session_id: str | None, since: float, until: float return [] copies: list[Path] = [] for product_name in _VSCODE_PRODUCT_NAMES: - copies.extend(_vscode_user_data_dir(product_name).glob(_VSCODE_ATTACHMENT_COPIES_GLOB)) + copies.extend(vscode_user_data_dir(product_name).glob(_VSCODE_ATTACHMENT_COPIES_GLOB)) recent = modified_between(copies, since, until) # /attachments// chats_of_this_session = { @@ -574,20 +532,14 @@ def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]: """ session_id = raw_payload.get('session_id') prompt = raw_payload.get('prompt') or '' - now = time.time() - since = get_prompt_mark(session_id, now) - - images = select_prompt_images( - [ - *_mentioned_files(prompt, raw_payload.get('cwd')), + return collect_since_prompt_mark( + session_id, + lambda since, until: [ + *mentioned_files(prompt, raw_payload.get('cwd')), *_pasted_cli_images(prompt), - *_vscode_saved_attachments(session_id, since, now), - ] + *_vscode_saved_attachments(session_id, since, until), + ], ) - save_prompt_mark(session_id, now) - - logger.debug('Collected prompt images, %s', {'images_count': len(images), 'since': since}) - return images def build_hook_response(self, decision: HookDecision) -> dict: if decision.action == DecisionAction.ALLOW: diff --git a/cycode/cli/apps/ai_guardrails/ides/cursor.py b/cycode/cli/apps/ai_guardrails/ides/cursor.py index 0dab8c5e..885df1d8 100644 --- a/cycode/cli/apps/ai_guardrails/ides/cursor.py +++ b/cycode/cli/apps/ai_guardrails/ides/cursor.py @@ -2,14 +2,20 @@ import json import platform +import sqlite3 +import time from pathlib import Path from typing import ClassVar +from urllib.parse import urlparse +from urllib.request import url2pathname from cycode.cli.apps.ai_guardrails.consts import CYCODE_SCAN_PROMPT_COMMAND, CYCODE_SESSION_START_COMMAND from cycode.cli.apps.ai_guardrails.ides._plugin_utils import build_global_config_files from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_skill_dirs +from cycode.cli.apps.ai_guardrails.ides._vscode_utils import read_only_query, vscode_user_data_dir from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload +from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage, select_prompt_images from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType from cycode.logger import get_logger @@ -31,14 +37,22 @@ _SCAN_COMMAND = CYCODE_SCAN_PROMPT_COMMAND _SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide cursor' +# The hook payload names no image attached to a prompt; Cursor's own record of the prompt does. It is the +# conversation's bubble whose requestId is the hook's generation_id, in the cursorDiskKV table of Cursor's global +# state database, and context.selectedImages lists each pasted, dropped or picked image, saved in the workspace's +# storage when it is attached. An @-mentioned file is only a link the agent may read later, not an attachment. +# Cursor starts saving the record just before it runs the hook, so the record may take a moment to appear. +_STATE_DB_PATH_PARTS = ('User', 'globalStorage', 'state.vscdb') +_PROMPT_RECORD_QUERY = 'SELECT value FROM cursorDiskKV WHERE key >= ? AND key < ? AND instr(value, ?) > 0' +_PROMPT_RECORD_WAIT_SECONDS = 1.0 +_PROMPT_RECORD_POLL_SECONDS = 0.2 + def _user_hooks_dir() -> Path: - """Per-platform Cursor user-scope settings directory.""" + """Per-platform Cursor user-scope settings directory: ~/.cursor on macOS, its user data directory elsewhere.""" if platform.system() == 'Darwin': return Path.home() / '.cursor' - if platform.system() == 'Windows': - return Path.home() / 'AppData' / 'Roaming' / 'Cursor' - return Path.home() / '.config' / 'Cursor' + return vscode_user_data_dir('Cursor') def _cursor_mcp_config_path() -> Path: @@ -102,6 +116,66 @@ def _resolve_mcp_server_name(raw_payload: dict) -> str | None: return command +# --- prompt images ------------------------------------------------------------ + + +def _image_file_path(value: object) -> str | None: + """A selected image's file, given as a path or a file URI.""" + if not isinstance(value, str) or not value: + return None + if value.startswith('file:'): + return url2pathname(urlparse(value).path) + return value + + +def _prompt_record_image_paths(db_path: Path, conversation_id: str, generation_id: str) -> list[str] | None: + """The image files Cursor's record of the prompt lists; None while there is no record.""" + key_range = (f'bubbleId:{conversation_id}:', f'bubbleId:{conversation_id};') + values = [value for (value,) in read_only_query(db_path, _PROMPT_RECORD_QUERY, (*key_range, generation_id))] + + paths: list[str] | None = None + for value in values: + try: + bubble = json.loads(value) + except (TypeError, ValueError): + continue + if not isinstance(bubble, dict) or bubble.get('requestId') != generation_id: + continue + paths = paths or [] + context = bubble.get('context') + selected = context.get('selectedImages') if isinstance(context, dict) else None + for image in selected if isinstance(selected, list) else []: + path = _image_file_path(image.get('path')) if isinstance(image, dict) else None + if path: + paths.append(path) + return paths + + +def _prompt_record_images(conversation_id: object, generation_id: object) -> list[str]: + """The image files Cursor's record of the prompt lists, waiting a moment for the record to be saved.""" + if not isinstance(conversation_id, str) or not conversation_id: + return [] + if not isinstance(generation_id, str) or not generation_id: + return [] + db_path = vscode_user_data_dir('Cursor').joinpath(*_STATE_DB_PATH_PARTS) + if not db_path.is_file(): + return [] + + deadline = time.monotonic() + _PROMPT_RECORD_WAIT_SECONDS + while True: + try: + paths = _prompt_record_image_paths(db_path, conversation_id, generation_id) + except sqlite3.Error as e: + logger.debug('Failed to read Cursor state database, %s', {'path': str(db_path)}, exc_info=e) + return [] + if paths is not None: + return paths + if time.monotonic() >= deadline: + logger.debug('Cursor has not saved the prompt yet, scanning its text only') + return [] + time.sleep(_PROMPT_RECORD_POLL_SECONDS) + + class Cursor(IDE): name: ClassVar[str] = 'cursor' display_name: ClassVar[str] = 'Cursor' @@ -140,6 +214,13 @@ def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload: mcp_arguments=(raw_payload.get('arguments') or raw_payload.get('tool_input') or raw_payload.get('input')), ) + def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]: + """Images attached to a prompt, as Cursor's record of the prompt lists them.""" + paths = _prompt_record_images(raw_payload.get('conversation_id'), raw_payload.get('generation_id')) + images = select_prompt_images(paths) + logger.debug('Collected prompt images, %s', {'images_count': len(images)}) + return images + def build_hook_response(self, decision: HookDecision) -> dict: if decision.event_type == AiHookEventType.PROMPT: if decision.action == DecisionAction.ALLOW: diff --git a/cycode/cli/apps/ai_guardrails/scan/prompt_images.py b/cycode/cli/apps/ai_guardrails/scan/prompt_images.py index 8713ff4d..65193ba3 100644 --- a/cycode/cli/apps/ai_guardrails/scan/prompt_images.py +++ b/cycode/cli/apps/ai_guardrails/scan/prompt_images.py @@ -1,9 +1,9 @@ """Images attached to an AI prompt, scanned for secrets along with its text. -Some IDEs (GitHub Copilot) save a prompt's attachments to disk before its hook runs, yet never name them in the -hook payload. The IDE integration finds the candidates (``IDE.collect_prompt_images``); this module holds what is -IDE-agnostic about them: the filters every candidate passes, and the per-session prompt marks that turn "files saved -for this prompt" into "files saved since the session's previous prompt". +Some IDEs (GitHub Copilot, Claude Code) save a prompt's attachments to disk before its hook runs, yet never name them +in the hook payload. The IDE integration finds the candidates (``IDE.collect_prompt_images``); this module holds what +is IDE-agnostic about them: `@path` mentions, the filters every candidate passes, and the per-session prompt marks that +turn "files saved for this prompt" into "files saved since the session's previous prompt". A session's first prompt looks back a fixed time rather than to session start: VS Code fires SessionStart together with the first prompt, after its attachments were already saved. @@ -12,8 +12,10 @@ import hashlib import json import os +import re import stat -from collections.abc import Iterable +import time +from collections.abc import Callable, Iterable from dataclasses import dataclass from pathlib import Path @@ -31,6 +33,9 @@ # Covers attachments saved a while before the prompt was sent FIRST_PROMPT_LOOKBACK_SECONDS = 600 +# A pasted or dragged image's placeholder in the prompt text, as Claude Code and Codex write it +_IMAGE_CHIP_PATTERN = re.compile(r'\[Image #(\d+)\]') + # A session idle this long loses its mark; if it comes back, its next prompt falls back to the lookback _MARK_RETENTION_SECONDS = 7 * 24 * 60 * 60 @@ -42,6 +47,12 @@ ) _SIGNATURE_LENGTH = max(len(signature) for signature, _ in _IMAGE_FORMATS) +# An `@path` mention as typed in a prompt: quoted, with backslash-escaped spaces (a file dragged into a terminal), or +# plain up to the next whitespace. Never mid-word, so an email address is not a mention. A lookahead, so every `@` is +# read on its own: a quote left open must not swallow the mentions after it, and a quoted path never spans lines. +_MENTION_PATTERN = re.compile(r'(? Path: return Path.home() / CYCODE_CONFIGURATION_DIRECTORY / PROMPT_MARKS_FILE_NAME @@ -113,6 +124,27 @@ def modified_between(paths: Iterable[Path], since: float, until: float) -> list[ return [path for _, path in sorted(dated, key=lambda item: item[0])] +def mentioned_files(prompt: str, cwd: str | None) -> list[Path]: + """Existing files named by `@` mentions, resolved against the hook's cwd.""" + base = Path(cwd) if cwd else Path() + files = [] + for match in _MENTION_PATTERN.finditer(prompt): + token = match.group(1) + if len(token) > 1 and token[0] == token[-1] and token[0] in '"\'': + spellings = [token[1:-1]] + else: + if os.sep == '/': + token = token.replace('\\ ', ' ') + # The mention may end a sentence ("look at @shot.png.") + spellings = [token, token.rstrip(_MENTION_TRAILING_PUNCTUATION)] + for spelling in spellings: + path = base / os.path.expanduser(spelling) + if os.path.isfile(path): + files.append(path) + break + return files + + def _image_extensions(content: bytes) -> tuple[str, ...]: return next((extensions for signature, extensions in _IMAGE_FORMATS if content.startswith(signature)), ()) @@ -182,3 +214,23 @@ def select_prompt_images(candidates: Iterable[str | os.PathLike]) -> list[Prompt selected.append(PromptImage(path=str(candidate), content=content)) return selected + + +def image_chips(prompt: str) -> list[str]: + """The numbers of the prompt's ``[Image #N]`` placeholders, as written and in the prompt's order.""" + return _IMAGE_CHIP_PATTERN.findall(prompt) + + +def collect_since_prompt_mark( + session_id: str | None, gather: Callable[[float, float], Iterable[str | os.PathLike]] +) -> list[PromptImage]: + """The images ``gather`` finds in the session's window ``[since, now)``, then the session's mark moves to now. + + The mark moves only after the images are selected; moving it first would leave this prompt's files to no one. + """ + now = time.time() + since = get_prompt_mark(session_id, now) + images = select_prompt_images(gather(since, now)) + save_prompt_mark(session_id, now) + logger.debug('Collected prompt images, %s', {'images_count': len(images), 'since': since}) + return images diff --git a/tests/cli/commands/ai_guardrails/ides/test_claude_code.py b/tests/cli/commands/ai_guardrails/ides/test_claude_code.py index d7d37e3e..ffc10dd2 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_claude_code.py +++ b/tests/cli/commands/ai_guardrails/ides/test_claude_code.py @@ -1,9 +1,13 @@ """Claude Code IDE integration tests.""" import json +import os +import tempfile +import time from pathlib import Path from unittest.mock import patch +import pytest from pyfakefs.fake_filesystem import FakeFilesystem from pytest_mock import MockerFixture @@ -13,9 +17,16 @@ _email_from_config, _read_claude_plugin, _resolve_mcp_server_name, + _user_id, load_claude_config, resolve_plugins, ) +from cycode.cli.apps.ai_guardrails.scan.prompt_images import ( + FIRST_PROMPT_LOOKBACK_SECONDS, + PromptImage, + get_prompt_mark, + save_prompt_mark, +) from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType @@ -510,3 +521,143 @@ def test_resolve_plugins_surfaces_plugin_skills(fs: FakeFilesystem) -> None: entry = plugins['dummy-plugin@dummy-marketplace'] assert [Path(s['path']).parent.name for s in entry['skill_files']] == ['cached-skill'] + + +# --- prompt images ---------------------------------------------------------------- + +_SESSION_ID = '0c974f38-5b1e-4a3c-9d2f-7e6a1b2c3d4e' +_PROJECT_KEY = '-Users-user-project' +_TEMP_ROOT = '/tmp' # noqa: S108 - Claude Code's default, on a fake filesystem + + +def _png(marker: bytes) -> bytes: + return b'\x89PNG\r\n\x1a\n' + marker + + +def _prompt_payload(prompt: str, session_id: str = _SESSION_ID) -> dict: + return { + 'hook_event_name': 'UserPromptSubmit', + 'session_id': session_id, + 'transcript_path': f'/Users/user/.claude/projects/{_PROJECT_KEY}/{session_id}.jsonl', + 'cwd': '/Users/user/project', + 'prompt': prompt, + } + + +def _session_images_dir(session_id: str = _SESSION_ID, root: str = _TEMP_ROOT) -> Path: + return Path(root) / f'claude-{_user_id()}' / _PROJECT_KEY / session_id / 'images' + + +def _saved_image( + fs: FakeFilesystem, + name: str, + content: bytes, + modified_at: float, + session_id: str = _SESSION_ID, + root: str = _TEMP_ROOT, +) -> str: + """An image Claude Code saved for a session.""" + path = _session_images_dir(session_id, root) / name + fs.create_file(path, contents=content) + os.utime(path, (modified_at, modified_at)) + return str(path) + + +def _paths(images: list[PromptImage]) -> list[str]: + return [image.path for image in images] + + +skip_without_uid = pytest.mark.skipif(_user_id() is None, reason='the folder is named after the uid') + + +@skip_without_uid +def test_collect_prompt_images_takes_the_images_its_chips_name(fs: FakeFilesystem) -> None: + now = time.time() + save_prompt_mark(_SESSION_ID, now - 60) + first = _saved_image(fs, '1.png', _png(b'first'), now - 600) + _saved_image(fs, '2.png', _png(b'second'), now - 300) + third = _saved_image(fs, '3.jpg', b'\xff\xd8\xff' + b'third', now - 120) + + images = ClaudeCode().collect_prompt_images(_prompt_payload('[Image #3] compare with [Image #1] and [Image #9]')) + + # In the prompt's order; an earlier prompt's image counts when a chip names it, an unknown number is skipped + assert _paths(images) == [third, first] + + +@skip_without_uid +def test_collect_prompt_images_takes_images_saved_since_the_previous_prompt(fs: FakeFilesystem) -> None: + now = time.time() + save_prompt_mark(_SESSION_ID, now - 60) + _saved_image(fs, '1.png', _png(b'previous prompt'), now - 120) + second = _saved_image(fs, '2.png', _png(b'this prompt'), now - 2) + third = _saved_image(fs, '3.webp', _png(b'this prompt, any extension'), now - 1) + + # VS Code and the desktop app put no chip in the prompt; an image-only prompt has no text at all + assert _paths(ClaudeCode().collect_prompt_images(_prompt_payload(''))) == [second, third] + # The mark moved to this prompt, so the next one doesn't take them again + assert get_prompt_mark(_SESSION_ID, time.time()) >= now + assert _paths(ClaudeCode().collect_prompt_images(_prompt_payload('next'))) == [] + + +@skip_without_uid +def test_first_prompt_takes_images_from_the_lookback(fs: FakeFilesystem) -> None: + now = time.time() + recent = _saved_image(fs, '2.png', _png(b'recent'), now - (FIRST_PROMPT_LOOKBACK_SECONDS - 60)) + _saved_image(fs, '1.png', _png(b'old'), now - (FIRST_PROMPT_LOOKBACK_SECONDS + 60)) + + assert _paths(ClaudeCode().collect_prompt_images(_prompt_payload('what is this?'))) == [recent] + + +@skip_without_uid +def test_collect_prompt_images_reads_only_this_sessions_folder(fs: FakeFilesystem) -> None: + now = time.time() + own = _saved_image(fs, '1.png', _png(b'own'), now - 5) + _saved_image(fs, '1.png', _png(b'other session'), now - 5, session_id='another-session') + other_user = Path(_TEMP_ROOT, 'claude-0') / _PROJECT_KEY / _SESSION_ID / 'images' / '1.png' + fs.create_file(other_user, contents=_png(b'other user')) + + assert _paths(ClaudeCode().collect_prompt_images(_prompt_payload('[Image #1]'))) == [own] + + +@skip_without_uid +@pytest.mark.parametrize('session_id', ['', '*', '../images', 'a/b', None, 7]) +def test_collect_prompt_images_looks_up_no_folder_for_an_unusable_session_id( + fs: FakeFilesystem, session_id: object +) -> None: + _saved_image(fs, '1.png', _png(b'own'), time.time() - 5) + + payload = {**_prompt_payload('[Image #1]'), 'session_id': session_id} + + assert ClaudeCode().collect_prompt_images(payload) == [] + + +@skip_without_uid +def test_collect_prompt_images_honors_the_temp_dir_override( + fs: FakeFilesystem, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv('CLAUDE_CODE_TMPDIR', '/scratch/tmp') + now = time.time() + _saved_image(fs, '1.png', _png(b'default root'), now - 5) + moved = _saved_image(fs, '2.png', _png(b'moved root'), now - 5, root='/scratch/tmp') + + assert _paths(ClaudeCode().collect_prompt_images(_prompt_payload('[Image #1] [Image #2]'))) == [moved] + + +def test_collect_prompt_images_without_a_uid_looks_in_the_system_temp_dir( + fs: FakeFilesystem, mocker: MockerFixture +) -> None: + mocker.patch('cycode.cli.apps.ai_guardrails.ides.claude_code._user_id', return_value=None) + path = Path(tempfile.gettempdir()) / 'claude' / _PROJECT_KEY / _SESSION_ID / 'images' / '1.png' + fs.create_file(path, contents=_png(b'windows')) + + assert _paths(ClaudeCode().collect_prompt_images(_prompt_payload('[Image #1]'))) == [str(path)] + + +def test_collect_prompt_images_finds_mentions_against_cwd(fs: FakeFilesystem) -> None: + shot = Path('/Users/user/project/docs/shot.png') + fs.create_file(shot, contents=_png(b'shot')) + fs.create_file('/Users/user/project/notes.txt', contents=b'not an image') + + images = ClaudeCode().collect_prompt_images(_prompt_payload('look at @docs/shot.png and @notes.txt')) + + assert _paths(images) == [str(shot)] diff --git a/tests/cli/commands/ai_guardrails/ides/test_codex.py b/tests/cli/commands/ai_guardrails/ides/test_codex.py index e69ef0b7..461eaf71 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_codex.py +++ b/tests/cli/commands/ai_guardrails/ides/test_codex.py @@ -2,13 +2,19 @@ import base64 import json +import os import sys +import tempfile +import time +from collections.abc import Iterator +from datetime import datetime, timezone from pathlib import Path from unittest.mock import patch import pytest from pyfakefs.fake_filesystem import FakeFilesystem +from cycode.cli.apps.ai_guardrails.ides._transcript_utils import reverse_readline from cycode.cli.apps.ai_guardrails.ides.base import HookDecision from cycode.cli.apps.ai_guardrails.ides.codex import ( Codex, @@ -18,6 +24,7 @@ _load_codex_config, _read_codex_plugin, ) +from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType if sys.version_info >= (3, 11): @@ -460,3 +467,268 @@ def test_get_skills_reads_user_scope_skills(fs: FakeFilesystem) -> None: def test_get_skills_no_skills_dir_returns_empty(fs: FakeFilesystem) -> None: assert Codex().get_skills() == [] + + +# --- prompt images ---------------------------------------------------------------- + + +def _png(marker: bytes) -> bytes: + return b'\x89PNG\r\n\x1a\n' + marker + + +def _paste(fs: FakeFilesystem, name: str, modified_at: float) -> str: + """An image the terminal UI saved from the clipboard.""" + path = Path(tempfile.gettempdir()) / f'codex-clipboard-{name}.png' + fs.create_file(path, contents=_png(name.encode())) + os.utime(path, (modified_at, modified_at)) + return str(path) + + +def _at(seconds: float) -> str: + """A transcript timestamp, as Codex writes it.""" + return datetime.fromtimestamp(seconds, tz=timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z' + + +def _message(seconds: float, role: str, text: str) -> dict: + content = [{'type': 'input_text', 'text': text}] + return { + 'timestamp': _at(seconds), + 'type': 'response_item', + 'payload': {'type': 'message', 'role': role, 'content': content}, + } + + +def _transcript(fs: FakeFilesystem, started: float, *prompts: tuple[float, bool], extra: tuple[str, ...] = ()) -> str: + """A session transcript as Codex writes it: the session's start and context, then a turn per prompt. + + Each prompt is (submitted at, whether its hook let it through). Codex records a prompt as a user message only when + it went through; a blocked one leaves only the turn's bookkeeping. + """ + path = '/Users/user/.codex/sessions/2026/11/17/rollout-session-1.jsonl' + lines = [ + {'timestamp': _at(started), 'type': 'session_meta', 'payload': {'id': 'session-1'}}, + _message(started, 'developer', 'instructions'), + # The session's context, written before the first turn: not a prompt + _message(started, 'user', ''), + ] + for submitted_at, went_through in prompts: + lines.append({'timestamp': _at(submitted_at), 'type': 'event_msg', 'payload': {'type': 'task_started'}}) + lines.append({'timestamp': _at(submitted_at), 'type': 'turn_context', 'payload': {}}) + if went_through: + lines.append(_message(submitted_at, 'user', '')) + lines.append({'timestamp': _at(submitted_at + 1), 'type': 'event_msg', 'payload': {'type': 'task_complete'}}) + text = '\n'.join([*(json.dumps(line) for line in lines), *extra]) + '\n' + fs.create_file(path, contents=text) + return path + + +def _prompt_payload(prompt: str, transcript_path: str | None = None) -> dict: + return { + 'hook_event_name': 'UserPromptSubmit', + 'session_id': 'session-1', + 'turn_id': 'turn-1', + 'transcript_path': transcript_path, + 'cwd': '/Users/user/project', + 'prompt': prompt, + } + + +def _paths(images: list[PromptImage]) -> list[str]: + return [image.path for image in images] + + +def test_collect_prompt_images_takes_the_newest_paste_per_chip(fs: FakeFilesystem) -> None: + now = time.time() + _paste(fs, 'Old111', now - 300) + middle = _paste(fs, 'Mid222', now - 60) + newest = _paste(fs, 'New333', now - 5) + transcript = _transcript(fs, now - 2) + + images = Codex().collect_prompt_images(_prompt_payload('[Image #1] [Image #2] what changed?', transcript)) + + # Oldest first, the order they were pasted in + assert _paths(images) == [middle, newest] + + +def test_collect_prompt_images_takes_only_pastes_since_the_last_prompt_that_went_through(fs: FakeFilesystem) -> None: + now = time.time() + _paste(fs, 'Before11', now - 200) + after = _paste(fs, 'After222', now - 30) + transcript = _transcript(fs, now - 300, (now - 190, True)) + + payload = _prompt_payload('[Image #1] [Image #2]', transcript) + + assert _paths(Codex().collect_prompt_images(payload)) == [after] + + +def test_collect_prompt_images_finds_a_blocked_prompts_paste_again(fs: FakeFilesystem) -> None: + now = time.time() + pasted = _paste(fs, 'Blocked1', now - 110) + # A blocked prompt isn't recorded, so its paste is found again when it is sent again + transcript = _transcript(fs, now - 300, (now - 250, True), (now - 100, False)) + + assert _paths(Codex().collect_prompt_images(_prompt_payload('[Image #1] again', transcript))) == [pasted] + + +def test_collect_prompt_images_takes_no_earlier_paste_for_a_dragged_image(fs: FakeFilesystem) -> None: + now = time.time() + # Left by a blocked prompt, or by another session, before this session's last prompt went through + _paste(fs, 'Blocked1', now - 200) + transcript = _transcript(fs, now - 300, (now - 190, False), (now - 60, True)) + + payload = _prompt_payload('[Image #1] what is it', transcript) + + assert Codex().collect_prompt_images(payload) == [] + + +def test_collect_prompt_images_first_prompt_looks_back_ten_minutes_from_the_session_start(fs: FakeFilesystem) -> None: + now = time.time() + _paste(fs, 'TooOld11', now - 700) + recent = _paste(fs, 'Recent22', now - 400) + # Codex starts the transcript when the first prompt is submitted, after its pastes + transcript = _transcript(fs, now - 5) + + payload = _prompt_payload('[Image #1] [Image #2]', transcript) + + assert _paths(Codex().collect_prompt_images(payload)) == [recent] + + +def test_collect_prompt_images_skips_a_resumed_sessions_context(fs: FakeFilesystem) -> None: + now = time.time() + pasted = _paste(fs, 'Recent11', now - 30) + # A resumed session starts again with its context, which is no prompt that went through + resumed = ( + json.dumps({'timestamp': _at(now - 20), 'type': 'session_meta', 'payload': {'id': 'session-1'}}), + json.dumps(_message(now - 20, 'user', '')), + ) + transcript = _transcript(fs, now - 300, (now - 250, True), extra=resumed) + + assert _paths(Codex().collect_prompt_images(_prompt_payload('[Image #1]', transcript))) == [pasted] + + +def test_collect_prompt_images_reads_the_transcript_back_to_the_last_prompt_only(fs: FakeFilesystem) -> None: + now = time.time() + pasted = _paste(fs, 'After222', now - 30) + transcript = _transcript(fs, now - 900, *[(now - 800 + 10 * turn, turn % 2 == 0) for turn in range(60)]) + lines_read = [] + + def counting_reverse_readline(path: Path) -> Iterator[str]: + for line in reverse_readline(path): + lines_read.append(line) + yield line + + with patch('cycode.cli.apps.ai_guardrails.ides.codex.reverse_readline', counting_reverse_readline): + images = Codex().collect_prompt_images(_prompt_payload('[Image #1]', transcript)) + + assert _paths(images) == [pasted] + # Of 60 turns, only the last (blocked) one and the one before it (which went through) are read + assert len(lines_read) == 6 + + +def test_collect_prompt_images_looks_back_from_a_resumed_sessions_latest_start(fs: FakeFilesystem) -> None: + now = time.time() + _paste(fs, 'BeforeRe', now - 1000) + pasted = _paste(fs, 'AfterRe1', now - 400) + # No prompt went through before or after the resume + resumed = ( + json.dumps({'timestamp': _at(now - 20), 'type': 'session_meta', 'payload': {'id': 'session-1'}}), + json.dumps(_message(now - 20, 'user', '')), + ) + transcript = _transcript(fs, now - 3000, (now - 2900, False), extra=resumed) + + payload = _prompt_payload('[Image #1] [Image #2]', transcript) + + assert _paths(Codex().collect_prompt_images(payload)) == [pasted] + + +def test_collect_prompt_images_takes_the_newest_message_of_a_turn(fs: FakeFilesystem) -> None: + now = time.time() + _paste(fs, 'Between1', now - 150) + # A message sent while the turn ran, after the one that started it + steered = (json.dumps(_message(now - 100, 'user', 'and also this')),) + transcript = _transcript(fs, now - 300, (now - 200, True), extra=steered) + + assert Codex().collect_prompt_images(_prompt_payload('[Image #1]', transcript)) == [] + + +def test_collect_prompt_images_takes_no_paste_without_a_chip(fs: FakeFilesystem) -> None: + now = time.time() + _paste(fs, 'Recent11', now - 5) + + assert Codex().collect_prompt_images(_prompt_payload('no image here', _transcript(fs, now - 2))) == [] + + +def test_collect_prompt_images_counts_a_repeated_chip_once(fs: FakeFilesystem) -> None: + now = time.time() + _paste(fs, 'First111', now - 60) + newest = _paste(fs, 'Second22', now - 5) + + payload = _prompt_payload('compare [Image #1] with itself: [Image #1]', _transcript(fs, now - 2)) + + assert _paths(Codex().collect_prompt_images(payload)) == [newest] + + +def test_collect_prompt_images_ignores_pastes_older_than_an_hour(fs: FakeFilesystem) -> None: + now = time.time() + _paste(fs, 'Stale111', now - 2 * 60 * 60) + transcript = _transcript(fs, now - 4 * 60 * 60, (now - 3 * 60 * 60, True)) + + assert Codex().collect_prompt_images(_prompt_payload('[Image #1]', transcript)) == [] + + +@pytest.mark.parametrize('transcript_path', [None, '']) +def test_collect_prompt_images_takes_no_paste_without_a_transcript( + fs: FakeFilesystem, transcript_path: str | None +) -> None: + _paste(fs, 'Recent11', time.time() - 5) + # The prompt Codex sends to title a new thread has no transcript and quotes the user's prompt, chips included + title_prompt = 'Generate a concise, single-line task title.\n\nUser prompt:\nwhat does it say? [Image #1]' + + assert Codex().collect_prompt_images(_prompt_payload(title_prompt, transcript_path)) == [] + + +@pytest.mark.parametrize('make_transcript', ['missing', 'directory']) +def test_collect_prompt_images_looks_back_ten_minutes_without_a_readable_transcript( + fs: FakeFilesystem, make_transcript: str +) -> None: + now = time.time() + _paste(fs, 'TooOld11', now - 700) + pasted = _paste(fs, 'Recent11', now - 5) + path = '/Users/user/.codex/sessions/2026/11/17/rollout-new.jsonl' + if make_transcript == 'directory': + fs.create_dir(path) + + payload = _prompt_payload('[Image #1] [Image #2]', path) + + assert _paths(Codex().collect_prompt_images(payload)) == [pasted] + + +def test_collect_prompt_images_skips_transcript_lines_it_cannot_read(fs: FakeFilesystem) -> None: + now = time.time() + _paste(fs, 'Before11', now - 250) + after = _paste(fs, 'After222', now - 100) + odd_lines = ( + 'not json, but "user"', + '["user"]', + json.dumps({'type': 'response_item', 'payload': {'role': 'user'}}), + json.dumps({'timestamp': 'yesterday', 'type': 'response_item', 'payload': {'role': 'user'}}), + json.dumps({'timestamp': _at(now - 50), 'type': 'response_item', 'payload': 'user'}), + # Not a message line, though its payload names the user + json.dumps( + {'timestamp': _at(now - 40), 'type': 'event_msg', 'payload': {'type': 'item_completed', 'role': 'user'}} + ), + ) + transcript = _transcript(fs, now - 300, (now - 200, True), extra=odd_lines) + + payload = _prompt_payload('[Image #1] [Image #2]', transcript) + + assert _paths(Codex().collect_prompt_images(payload)) == [after] + + +def test_collect_prompt_images_finds_mentions_against_cwd(fs: FakeFilesystem) -> None: + shot = Path('/Users/user/project/docs/shot.png') + fs.create_file(shot, contents=_png(b'shot')) + + images = Codex().collect_prompt_images(_prompt_payload('explain @docs/shot.png', _transcript(fs, time.time()))) + + assert _paths(images) == [str(shot)] diff --git a/tests/cli/commands/ai_guardrails/ides/test_copilot.py b/tests/cli/commands/ai_guardrails/ides/test_copilot.py index c5aee5ba..0fede8dd 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_copilot.py +++ b/tests/cli/commands/ai_guardrails/ides/test_copilot.py @@ -15,13 +15,13 @@ from pyfakefs.fake_filesystem import FakeFilesystem from pytest_mock import MockerFixture +from cycode.cli.apps.ai_guardrails.ides._vscode_utils import vscode_user_data_dir from cycode.cli.apps.ai_guardrails.ides.base import HookDecision from cycode.cli.apps.ai_guardrails.ides.copilot import ( Copilot, _read_copilot_plugin, _vscode_chat_session_id, _vscode_mcp_config_path, - _vscode_user_data_dir, split_mcp_tool_name, ) from cycode.cli.apps.ai_guardrails.scan.prompt_images import ( @@ -587,7 +587,7 @@ def _vscode_copy( chat: str = 'chat-1', ) -> str: """A send-time copy of an attachment, in a chat's session data.""" - path = _vscode_user_data_dir(product_name) / 'agentSessionData' / chat / 'attachments' / 'uuid-1' / name + path = vscode_user_data_dir(product_name) / 'agentSessionData' / chat / 'attachments' / 'uuid-1' / name return _create_file(fs, path, content, modified_at) @@ -659,7 +659,7 @@ def test_collect_prompt_images_finds_cli_paste_in_the_temp_dir(fs: FakeFilesyste def test_collect_prompt_images_finds_vscode_attachments( fs: FakeFilesystem, mocker: MockerFixture, vscode_chats: dict[str, str], system: str, product_name: str ) -> None: - mocker.patch('cycode.cli.apps.ai_guardrails.ides.copilot.platform.system', return_value=system) + mocker.patch('cycode.cli.apps.ai_guardrails.ides._vscode_utils.platform.system', return_value=system) now = time.time() first = _vscode_copy(fs, 'diagram.png', _png(b'first'), now - 20, product_name) second = _vscode_copy(fs, 'image.png', _png(b'second'), now - 5, product_name) @@ -695,10 +695,10 @@ def test_cli_prompt_takes_no_vscode_attachments(fs: FakeFilesystem, vscode_chats ], ) def test_vscode_user_data_dir_per_platform(mocker: MockerFixture, system: str, base_parts: tuple[str, ...]) -> None: - mocker.patch('cycode.cli.apps.ai_guardrails.ides.copilot.platform.system', return_value=system) + mocker.patch('cycode.cli.apps.ai_guardrails.ides._vscode_utils.platform.system', return_value=system) - assert _vscode_user_data_dir() == Path.home().joinpath(*base_parts, 'Code') - assert _vscode_user_data_dir('Code - Insiders') == Path.home().joinpath(*base_parts, 'Code - Insiders') + assert vscode_user_data_dir() == Path.home().joinpath(*base_parts, 'Code') + assert vscode_user_data_dir('Code - Insiders') == Path.home().joinpath(*base_parts, 'Code - Insiders') assert _vscode_mcp_config_path() == Path.home().joinpath(*base_parts, 'Code', 'User', 'mcp.json') diff --git a/tests/cli/commands/ai_guardrails/ides/test_cursor.py b/tests/cli/commands/ai_guardrails/ides/test_cursor.py index f54e6752..a37d2866 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_cursor.py +++ b/tests/cli/commands/ai_guardrails/ides/test_cursor.py @@ -1,12 +1,17 @@ """Cursor IDE integration tests (payload parsing, response building, MCP context).""" import json +import sqlite3 +from contextlib import closing from pathlib import Path from typing import Any from unittest.mock import patch +import pytest from pyfakefs.fake_filesystem import FakeFilesystem +from pytest_mock import MockerFixture +from cycode.cli.apps.ai_guardrails.ides._vscode_utils import vscode_user_data_dir from cycode.cli.apps.ai_guardrails.ides.base import HookDecision from cycode.cli.apps.ai_guardrails.ides.cursor import Cursor from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType @@ -248,3 +253,167 @@ def test_get_skills_reads_user_scope_skills(fs: FakeFilesystem) -> None: def test_get_skills_no_skills_dir_returns_empty(fs: FakeFilesystem) -> None: assert Cursor().get_skills() == [] + + +# --- prompt images (a real SQLite file, so no fake filesystem) ------------------------ + +_CONVERSATION_ID = '6f1c2d3e-4b5a-4c6d-8e7f-9a0b1c2d3e4f' +_GENERATION_ID = 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d' + + +def _png(marker: bytes) -> bytes: + return b'\x89PNG\r\n\x1a\n' + marker + + +@pytest.fixture +def cursor_user_data(tmp_path: Path, mocker: MockerFixture) -> Path: + user_data = tmp_path / 'Cursor' + mocker.patch('cycode.cli.apps.ai_guardrails.ides.cursor.vscode_user_data_dir', return_value=user_data) + mocker.patch('cycode.cli.apps.ai_guardrails.ides.cursor._PROMPT_RECORD_WAIT_SECONDS', 0) + return user_data + + +def _state_db(user_data: Path, bubbles: dict[str, object]) -> Path: + """Cursor's global state database, holding these bubbles of the conversation (by bubble id).""" + db_path = user_data / 'User' / 'globalStorage' / 'state.vscdb' + db_path.parent.mkdir(parents=True) + with closing(sqlite3.connect(db_path)) as connection, connection: + connection.execute('CREATE TABLE cursorDiskKV (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)') + connection.executemany( + 'INSERT INTO cursorDiskKV VALUES (?, ?)', + [(key, value if isinstance(value, str) else json.dumps(value)) for key, value in bubbles.items()], + ) + return db_path + + +def _bubble(request_id: str, *image_paths: str) -> dict: + return { + 'type': 1, + 'requestId': request_id, + 'context': { + 'selectedImages': [{'uuid': f'uuid-{index}', 'path': path} for index, path in enumerate(image_paths)] + }, + } + + +def _image(directory: Path, name: str) -> str: + path = directory / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(_png(name.encode())) + return str(path) + + +def _prompt_payload(**overrides: object) -> dict: + return { + 'hook_event_name': 'beforeSubmitPrompt', + 'conversation_id': _CONVERSATION_ID, + 'generation_id': _GENERATION_ID, + 'prompt': 'what does this screenshot show?', + 'attachments': [], + **overrides, + } + + +def test_collect_prompt_images_reads_the_prompts_record(cursor_user_data: Path, tmp_path: Path) -> None: + pasted = _image(cursor_user_data / 'User' / 'workspaceStorage' / 'ws-1' / 'images', 'image-uuid-1.png') + mentioned = _image(tmp_path / 'project', 'diagram.png') + earlier = _image(tmp_path / 'project', 'earlier.png') + other = _image(tmp_path / 'project', 'other.png') + _state_db( + cursor_user_data, + { + f'bubbleId:{_CONVERSATION_ID}:bubble-1': _bubble('earlier-generation', earlier), + f'bubbleId:{_CONVERSATION_ID}:bubble-2': _bubble(_GENERATION_ID, pasted, Path(mentioned).as_uri()), + 'bubbleId:another-conversation:bubble-3': _bubble(_GENERATION_ID, other), + f'composerData:{_CONVERSATION_ID}': {'latestChatGenerationUUID': _GENERATION_ID}, + }, + ) + + images = Cursor().collect_prompt_images(_prompt_payload()) + + assert [image.path for image in images] == [pasted, mentioned] + + +def test_collect_prompt_images_finds_nothing_in_a_record_without_images(cursor_user_data: Path) -> None: + _state_db(cursor_user_data, {f'bubbleId:{_CONVERSATION_ID}:bubble-1': _bubble(_GENERATION_ID)}) + + assert Cursor().collect_prompt_images(_prompt_payload()) == [] + + +def test_collect_prompt_images_waits_for_the_record( + cursor_user_data: Path, tmp_path: Path, mocker: MockerFixture +) -> None: + pasted = _image(tmp_path / 'images', 'pasted.png') + db_path = _state_db(cursor_user_data, {}) + mocker.patch('cycode.cli.apps.ai_guardrails.ides.cursor._PROMPT_RECORD_WAIT_SECONDS', 5) + + def save_the_record(_: float) -> None: + with closing(sqlite3.connect(db_path)) as connection, connection: + key = f'bubbleId:{_CONVERSATION_ID}:bubble-1' + connection.execute( + 'INSERT INTO cursorDiskKV VALUES (?, ?)', (key, json.dumps(_bubble(_GENERATION_ID, pasted))) + ) + + sleep = mocker.patch('cycode.cli.apps.ai_guardrails.ides.cursor.time.sleep', side_effect=save_the_record) + + assert [image.path for image in Cursor().collect_prompt_images(_prompt_payload())] == [pasted] + sleep.assert_called_once() + + +def test_collect_prompt_images_gives_up_when_the_record_never_comes(cursor_user_data: Path) -> None: + _state_db(cursor_user_data, {f'bubbleId:{_CONVERSATION_ID}:bubble-1': _bubble('earlier-generation')}) + + assert Cursor().collect_prompt_images(_prompt_payload()) == [] + + +@pytest.mark.parametrize( + 'overrides', + [{'conversation_id': None}, {'generation_id': ''}, {'conversation_id': 7}, {'generation_id': ['x']}], +) +def test_collect_prompt_images_needs_both_ids(cursor_user_data: Path, tmp_path: Path, overrides: dict) -> None: + pasted = _image(tmp_path / 'images', 'pasted.png') + _state_db(cursor_user_data, {f'bubbleId:{_CONVERSATION_ID}:bubble-1': _bubble(_GENERATION_ID, pasted)}) + + assert Cursor().collect_prompt_images(_prompt_payload(**overrides)) == [] + + +def test_collect_prompt_images_without_a_state_database(cursor_user_data: Path) -> None: + assert Cursor().collect_prompt_images(_prompt_payload()) == [] + + +def test_collect_prompt_images_skips_an_unreadable_database(cursor_user_data: Path) -> None: + db_path = cursor_user_data / 'User' / 'globalStorage' / 'state.vscdb' + db_path.parent.mkdir(parents=True) + db_path.write_bytes(b'not a database') + + assert Cursor().collect_prompt_images(_prompt_payload()) == [] + + +def test_collect_prompt_images_skips_malformed_records(cursor_user_data: Path, tmp_path: Path) -> None: + pasted = _image(tmp_path / 'images', 'pasted.png') + _state_db( + cursor_user_data, + { + f'bubbleId:{_CONVERSATION_ID}:bubble-1': f'not json {_GENERATION_ID}', + f'bubbleId:{_CONVERSATION_ID}:bubble-2': { + 'requestId': _GENERATION_ID, + 'context': {'selectedImages': [None, {'path': 7}, {'path': ''}, {'path': pasted}]}, + }, + }, + ) + + assert [image.path for image in Cursor().collect_prompt_images(_prompt_payload())] == [pasted] + + +@pytest.mark.parametrize( + ('system', 'base_parts'), + [ + ('Darwin', ('Library', 'Application Support')), + ('Linux', ('.config',)), + ('Windows', ('AppData', 'Roaming')), + ], +) +def test_cursor_user_data_dir_per_platform(mocker: MockerFixture, system: str, base_parts: tuple[str, ...]) -> None: + mocker.patch('cycode.cli.apps.ai_guardrails.ides._vscode_utils.platform.system', return_value=system) + + assert vscode_user_data_dir('Cursor') == Path.home().joinpath(*base_parts, 'Cursor') diff --git a/tests/cli/commands/ai_guardrails/scan/test_scan_command.py b/tests/cli/commands/ai_guardrails/scan/test_scan_command.py index 88234e72..9f9a3ae1 100644 --- a/tests/cli/commands/ai_guardrails/scan/test_scan_command.py +++ b/tests/cli/commands/ai_guardrails/scan/test_scan_command.py @@ -12,8 +12,9 @@ from typer.testing import CliRunner from cycode.cli.apps.ai_guardrails import app as ai_guardrails_app +from cycode.cli.apps.ai_guardrails.ides._vscode_utils import vscode_user_data_dir from cycode.cli.apps.ai_guardrails.ides.base import HookDecision -from cycode.cli.apps.ai_guardrails.ides.copilot import Copilot, _vscode_user_data_dir +from cycode.cli.apps.ai_guardrails.ides.copilot import Copilot from cycode.cli.apps.ai_guardrails.scan.guardrail_config import GuardrailConfig from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage, get_prompt_marks_path from cycode.cli.apps.ai_guardrails.scan.scan_command import scan_command @@ -671,7 +672,7 @@ def test_images_are_collected_by_the_detached_child_not_the_parent( ) -> None: """Collecting moves the session's prompt mark past the image, so a parent that collected before detaching would leave the child that scans nothing to find.""" - paste = _vscode_user_data_dir() / 'agentSessionData' / 'chat-1' / 'attachments' / 'uuid-1' / 'image-1.png' + paste = vscode_user_data_dir() / 'agentSessionData' / 'chat-1' / 'attachments' / 'uuid-1' / 'image-1.png' fs.create_file(paste, contents=b'\x89PNG\r\n\x1a\n' + b'pasted') os.utime(paste, (time.time() - 5, time.time() - 5)) mocker.patch(