Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(sessions): add Codex session transcript adapter (#1277)

Rehan Ahmedcf42d43db30f
diff --git a/packages/core/src/repowise/core/sessions/__init__.py b/packages/core/src/repowise/core/sessions/__init__.py
index 9747fecef..d163ed2dc 100644
--- a/packages/core/src/repowise/core/sessions/__init__.py
+++ b/packages/core/src/repowise/core/sessions/__init__.py
@@ -18,6 +18,7 @@ from repowise.core.sessions.adapters import (
INTENT_TOOL_CALLS,
INTENT_TURNS,
ClaudeCodeAdapter,
+ CodexAdapter,
HarnessAdapter,
RawPrefilter,
get_adapter,
@@ -41,6 +42,7 @@ __all__ = [
"INTENT_TURNS",
"INTERRUPT_MARKER",
"ClaudeCodeAdapter",
+ "CodexAdapter",
"CursorStore",
"Event",
"HarnessAdapter",
diff --git a/packages/core/src/repowise/core/sessions/adapters/__init__.py b/packages/core/src/repowise/core/sessions/adapters/__init__.py
index 5da64a2e1..5b851c38b 100644
--- a/packages/core/src/repowise/core/sessions/adapters/__init__.py
+++ b/packages/core/src/repowise/core/sessions/adapters/__init__.py
@@ -12,6 +12,7 @@ from repowise.core.sessions.adapters.base import (
RawPrefilter,
)
from repowise.core.sessions.adapters.claude_code import ClaudeCodeAdapter
+from repowise.core.sessions.adapters.codex import CodexAdapter
from repowise.core.sessions.adapters.registry import (
get_adapter,
register_adapter,
@@ -23,6 +24,7 @@ __all__ = [
"INTENT_TOOL_CALLS",
"INTENT_TURNS",
"ClaudeCodeAdapter",
+ "CodexAdapter",
"HarnessAdapter",
"RawPrefilter",
"get_adapter",
diff --git a/packages/core/src/repowise/core/sessions/adapters/codex.py b/packages/core/src/repowise/core/sessions/adapters/codex.py
new file mode 100644
index 000000000..9959ce6e8
--- /dev/null
+++ b/packages/core/src/repowise/core/sessions/adapters/codex.py
@@ -0,0 +1,473 @@
+"""Codex transcript adapter.
+
+Codex stores session rollout files in a date-based hierarchy under
+``~/.codex/sessions/YYYY/MM/DD/``. This adapter keeps the implementation
+simple and best-effort: it locates those files for a repo and turns each
+JSONL line into the shared session ``Event`` shape used by the miners.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+from typing import Any, ClassVar
+
+from repowise.core.fs_walk import iter_glob
+from repowise.core.sessions.adapters.base import (
+ INTENT_SHELL_CALLS,
+ INTENT_TOOL_CALLS,
+ INTENT_TURNS,
+ HarnessAdapter,
+ RawPrefilter,
+)
+from repowise.core.sessions.adapters.claude_code import parse_timestamp
+from repowise.core.sessions.adapters.registry import register_adapter
+from repowise.core.sessions.events import Event, ToolResult, ToolUse
+
+_TOOL_CALL_RE = re.compile(r"tools\.([A-Za-z_][A-Za-z0-9_]*)\s*\(")
+_SHELL_COMMAND_RE = re.compile(r'"command"\s*:\s*"([^"]*)"')
+#: ``rg`` prints ``path:line:text`` for a content match and a bare path for
+#: ``--files``. Only the leading path is a file; the rest is the matched line.
+_RG_MATCH_RE = re.compile(r"^(?P<path>[^:]+(?::[^:\\/]*[\\/][^:]*)?):\d+:")
+#: Lines the exec wrapper prints around a command's real output.
+_EXEC_NOISE = ("Script ", "Exit code:", "Wall time", "Output:")
+
+
+def _tool_calls_prefilter(raw: str) -> bool:
+ return (
+ '"type":"custom_tool_call"' in raw
+ or '"type":"custom_tool_call_output"' in raw
+ or '"type":"function_call"' in raw
+ or '"type":"function_call_output"' in raw
+ )
+
+
+def _turns_prefilter(raw: str) -> bool:
+ return '"type":"event_msg"' in raw or '"type":"response_item"' in raw
+
+
+@register_adapter
+class CodexAdapter(HarnessAdapter):
+ """Normalizes Codex session JSONL into the shared Event stream."""
+
+ name: ClassVar[str] = "codex"
+
+ def __init__(self):
+ self._tool_calls: dict[str, ToolUse] = {}
+ self._current_session: str | None = None
+ self._current_cwd: str | None = None
+
+ def discover(self, repo_root: Path, *, projects_root: Path | None = None) -> list[Path]:
+ """Every Codex rollout, not just this repo's.
+
+ Codex files its sessions by date rather than by project, so the
+ transcript path carries no repo. The repo a line belongs to is on the
+ ``cwd`` threaded out of ``session_meta``, which is what the miners
+ scope on, so returning the full set here is correct rather than lazy.
+ """
+ root = projects_root if projects_root is not None else Path.home() / ".codex" / "sessions"
+ if not root.is_dir():
+ return []
+ return sorted(path for path in iter_glob(root, "*.jsonl") if path.is_file())
+
+ def normalize(self, raw_line: str) -> Event | None:
+ try:
+ entry = json.loads(raw_line)
+ except ValueError:
+ return None
+ if not isinstance(entry, dict):
+ return None
+
+ payload = entry.get("payload") if isinstance(entry.get("payload"), dict) else {}
+ entry_kind = (
+ entry.get("type") if isinstance(entry.get("type"), str) and entry.get("type") else None
+ )
+ payload_kind = (
+ payload.get("type")
+ if isinstance(payload.get("type"), str) and payload.get("type")
+ else None
+ )
+ kind = _event_kind(entry_kind, payload_kind, payload)
+
+ event = Event(
+ kind=kind,
+ ts=parse_timestamp(_first_non_empty(entry.get("timestamp"), payload.get("timestamp"))),
+ session_id=_first_non_empty_str(
+ _str_or_none(payload.get("session_id")),
+ _str_or_none(entry.get("session_id")),
+ ),
+ cwd=_first_non_empty_str(
+ _str_or_none(payload.get("cwd")), _str_or_none(entry.get("cwd"))
+ ),
+ usage=None,
+ message_id=_str_or_none(payload.get("id")) or _str_or_none(entry.get("message_id")),
+ model=_str_or_none(payload.get("model")) or _str_or_none(entry.get("model")),
+ sidechain=False,
+ is_meta=entry_kind == "session_meta",
+ is_compact_summary=False,
+ )
+
+ if entry_kind == "session_meta":
+ event.text = ""
+ self._current_session = event.session_id
+ self._current_cwd = event.cwd
+ return event
+
+ if event.session_id is None:
+ event.session_id = self._current_session
+ # Codex writes cwd once, in session_meta. The miners scope every event
+ # on its own cwd, so a line without one counts toward whichever repo is
+ # being mined; threading it is what keeps one project's sessions out of
+ # another's decisions.
+ if event.cwd is None:
+ event.cwd = self._current_cwd
+
+ text = _extract_text(
+ entry.get("text"), payload.get("message"), payload.get("content"), payload.get("output")
+ )
+ if text:
+ event.text = text
+
+ if entry_kind == "response_item" and isinstance(payload, dict):
+ self._fill_response_item(event, payload)
+
+ return event
+
+ def prefilter(self, intent: str) -> RawPrefilter | None:
+ # Both call shapes carry shell work, so both gates admit both. Codex
+ # wraps a shell command in an `exec` custom_tool_call *and* calls
+ # `shell_command` as a plain function_call; on real rollouts the second
+ # is the larger half, so a shell gate that reads only the first drops
+ # most of what it exists to find. Substring tests on the raw string,
+ # never a parse: see HarnessAdapter.prefilter.
+ if intent in (INTENT_SHELL_CALLS, INTENT_TOOL_CALLS):
+ return _tool_calls_prefilter
+
+ if intent == INTENT_TURNS:
+ return _turns_prefilter
+
+ return None
+
+ def begin_file(self, path: Path | None = None) -> None:
+ self._tool_calls.clear()
+ self._current_session = None
+ self._current_cwd = None
+
+ def end_file(self) -> None:
+ self._tool_calls.clear()
+ self._current_session = None
+ self._current_cwd = None
+
+ def _fill_response_item(self, event: Event, payload: dict[str, Any]) -> None:
+ """Handles response_item entries in Codex transcripts, and converts them to either text, tool uses or tool results
+
+ Codex uses response_item entries to represent things like message, tool call or tool results
+ """
+ payload_type = payload.get("type")
+ if payload_type == "message":
+ event.text = _extract_text(None, None, payload.get("content"), None) or event.text
+ event.message_id = _str_or_none(payload.get("id")) or event.message_id
+ event.model = _str_or_none(payload.get("model")) or event.model
+ return
+
+ if payload_type == "custom_tool_call":
+ tool_id = payload.get("call_id")
+ name = payload.get("name")
+
+ if isinstance(tool_id, str) and isinstance(name, str):
+ tool_input = payload.get("input")
+
+ if isinstance(tool_input, dict):
+ normalized_input = tool_input
+ elif isinstance(tool_input, str):
+ normalized_input = {"command": tool_input}
+ else:
+ normalized_input = {}
+
+ normalized_name = _normalize_tool_name(name, normalized_input)
+
+ tool = ToolUse(
+ id=tool_id,
+ name=normalized_name,
+ input=normalized_input,
+ )
+
+ self._tool_calls[tool_id] = tool
+ event.tool_uses.append(tool)
+ return
+
+ if payload_type == "custom_tool_call_output":
+ output = payload.get("output")
+ text = _extract_text(None, None, output, None)
+
+ if text:
+ event.text = text
+
+ call_id = payload.get("call_id")
+ if not isinstance(call_id, str):
+ return
+
+ tool = self._tool_calls.pop(call_id, None)
+
+ if tool is not None and tool.name == "search_codebase":
+ rewritten = _rewrite_search_output(output)
+ if rewritten is not None:
+ _bind_first_file(tool, rewritten["result"]["results"])
+ output = json.dumps(rewritten)
+
+ event.tool_results.append(
+ ToolResult(
+ tool_use_id=call_id,
+ is_error=False,
+ content=output,
+ payload=output,
+ )
+ )
+ return
+
+ if payload_type == "function_call":
+ tool_id = payload.get("call_id")
+ name = payload.get("name")
+
+ if not isinstance(tool_id, str) or not isinstance(name, str):
+ return
+
+ arguments = payload.get("arguments")
+
+ if isinstance(arguments, str):
+ try:
+ normalized_input = json.loads(arguments)
+ except ValueError:
+ normalized_input = {}
+ elif isinstance(arguments, dict):
+ normalized_input = arguments
+ else:
+ normalized_input = {}
+
+ normalized_name = _normalize_tool_name(name, normalized_input)
+
+ tool = ToolUse(
+ id=tool_id,
+ name=normalized_name,
+ input=normalized_input,
+ )
+
+ self._tool_calls[tool_id] = tool
+ event.tool_uses.append(tool)
+ return
+
+ if payload_type == "function_call_output":
+ output = payload.get("output")
+ text = _extract_text(None, None, output, None)
+
+ if text:
+ event.text = text
+
+ call_id = payload.get("call_id")
+
+ if not isinstance(call_id, str):
+ return
+
+ tool = self._tool_calls.pop(call_id, None)
+
+ # An MCP search arrives as {"query": ...} with no path key, so
+ # event_files() would bind the record to nothing. The result names
+ # the file; lift the first one onto the call that asked for it.
+ if tool is not None and tool.name == "search_codebase" and isinstance(output, str):
+ _bind_first_file(tool, _mcp_search_results(output))
+
+ event.tool_results.append(
+ ToolResult(
+ tool_use_id=call_id,
+ is_error=False,
+ content=output,
+ payload=output,
+ )
+ )
+ return
+
+
+def _bind_first_file(tool: ToolUse, results: list[dict[str, str]]) -> None:
+ """Point *tool* at the first file its search returned.
+
+ ``event_files`` reads ``FILE_INPUT_KEYS`` off a tool's input, and a search
+ call names a query rather than a file, so without this a search that found
+ something binds a decision record to nothing. Only fills a key that is not
+ already there: an explicit argument outranks an inferred one.
+ """
+ if not isinstance(tool.input, dict) or tool.input.get("path"):
+ return
+ for result in results:
+ file_path = result.get("file") if isinstance(result, dict) else None
+ if isinstance(file_path, str) and file_path:
+ tool.input["path"] = file_path
+ return
+
+
+def _mcp_search_results(output: str) -> list[dict[str, str]]:
+ """The ``results`` list out of an MCP tool's output, or empty.
+
+ The MCP transport wraps its JSON in timing prose (``Wall time: ...``,
+ ``Output:``, then the object), so parse from the first brace rather than
+ from the first character.
+ """
+ start = output.find("{")
+ if start == -1:
+ return []
+ try:
+ parsed = json.loads(output[start:])
+ except ValueError:
+ return []
+ if not isinstance(parsed, dict):
+ return []
+ result = parsed.get("result")
+ results = result.get("results") if isinstance(result, dict) else None
+ return [r for r in results if isinstance(r, dict)] if isinstance(results, list) else []
+
+
+def _rewrite_search_output(output: Any) -> dict | None:
+ """``rg`` output as the MCP ``search_codebase`` result shape, or None.
+
+ None rather than an empty envelope when the output is not the block list
+ this understands: overwriting a real tool result with ``{"results": []}``
+ loses the output, and ``normalize`` may not raise on content it cannot
+ read, which a bare iteration over a non-list would.
+
+ Only the leading path of an ``rg`` line becomes a file. ``rg`` prints
+ ``path:line:text`` for a content match, and taking the whole line would
+ hand the decision miner a "file" that does not exist.
+ """
+ if not isinstance(output, list):
+ return None
+
+ texts = [
+ block["text"]
+ for block in output
+ if isinstance(block, dict) and isinstance(block.get("text"), str)
+ ]
+
+ results: list[dict[str, str]] = []
+ for raw_line in "\n".join(texts).splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith(_EXEC_NOISE):
+ continue
+ match = _RG_MATCH_RE.match(line)
+ candidate = match.group("path") if match else line
+ if "/" in candidate or "\\" in candidate:
+ results.append({"file": candidate.replace("\\", "/")})
+
+ return {"result": {"results": results}}
+
+
+def _normalize_tool_name(name: str, tool_input: dict[str, Any]) -> str:
+ aliases = {
+ "search": "search_codebase",
+ "search_codebase": "search_codebase",
+ "answer": "get_answer",
+ "get_answer": "get_answer",
+ "edit": "edit_file",
+ "apply_patch": "edit_file",
+ "write_file": "edit_file",
+ "bash": "bash",
+ "run_command": "bash",
+ "exec": "bash",
+ }
+ if name.lower() != "exec":
+ return aliases.get(name.lower(), name)
+
+ command = tool_input.get("command")
+ if not isinstance(command, str):
+ return "bash"
+
+ match = _TOOL_CALL_RE.search(command)
+ if not match:
+ return "bash"
+
+ embedded_tool = match.group(1)
+ if embedded_tool == "shell_command":
+ shell_match = _SHELL_COMMAND_RE.search(command)
+ if not shell_match:
+ return "bash"
+
+ shell_command = shell_match.group(1)
+
+ if re.search(r"\brg(?:\.exe)?\b", shell_command):
+ return "search_codebase"
+
+ return "bash"
+
+ return aliases.get(embedded_tool.lower(), embedded_tool)
+
+
+def _event_kind(entry_kind: str | None, payload_kind: str | None, payload: dict[str, Any]) -> str:
+ if entry_kind == "session_meta":
+ return "session_meta"
+ if entry_kind == "response_item":
+ if payload_kind == "message":
+ role = payload.get("role")
+ if role == "user":
+ return "user"
+ if role == "assistant":
+ return "assistant"
+ if role == "developer":
+ return "system"
+ if payload_kind == "custom_tool_call":
+ return "assistant"
+ if payload_kind == "custom_tool_call_output":
+ return "assistant"
+ return payload_kind or "assistant"
+ if entry_kind == "event_msg":
+ if payload_kind == "user_message":
+ return "user"
+ if payload_kind == "agent_message":
+ return "assistant"
+ return payload_kind or "assistant"
+ return entry_kind or "assistant"
+
+
+def _extract_text(*candidates: Any) -> str:
+ for candidate in candidates:
+ if isinstance(candidate, str):
+ if candidate:
+ return candidate
+ continue
+ if isinstance(candidate, list):
+ parts: list[str] = []
+ for item in candidate:
+ if isinstance(item, dict):
+ text = item.get("text")
+ if isinstance(text, str) and text:
+ parts.append(text)
+ else:
+ kind = item.get("type")
+ if kind in {"input_text", "output_text"}:
+ text = item.get("text")
+ if isinstance(text, str) and text:
+ parts.append(text)
+ elif isinstance(item, str) and item:
+ parts.append(item)
+ if parts:
+ return "\n".join(parts)
+ elif isinstance(candidate, dict):
+ if isinstance(candidate.get("message"), str):
+ return candidate["message"]
+ return ""
+
+
+def _first_non_empty_str(*values: Any) -> str | None:
+ for value in values:
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+def _first_non_empty(*values: Any) -> Any:
+ for value in values:
+ if value is not None and value != "":
+ return value
+ return None
+
+
+def _str_or_none(value: Any) -> str | None:
+ return value if isinstance(value, str) and value else None
diff --git a/packages/core/src/repowise/core/sessions/adapters/registry.py b/packages/core/src/repowise/core/sessions/adapters/registry.py
index 2bd2afd15..f50bbaccb 100644
--- a/packages/core/src/repowise/core/sessions/adapters/registry.py
+++ b/packages/core/src/repowise/core/sessions/adapters/registry.py
@@ -6,7 +6,7 @@ that turn a session file into an Event stream. Not to be confused with the
similarly named ``repowise.cli.agent_adapters`` family, which installs and
checks editor hooks and shares nothing with this one but a word.
-One entry today (Claude Code). The point is not extensibility for its own
+Claude Code and Codex today. The point is not extensibility for its own
sake: it is that a second harness becomes a registration in its own module
rather than a search-and-replace across every module that reads transcripts.
diff --git a/tests/unit/sessions/data/codex_session.jsonl b/tests/unit/sessions/data/codex_session.jsonl
new file mode 100644
index 000000000..6212eb812
--- /dev/null
+++ b/tests/unit/sessions/data/codex_session.jsonl
@@ -0,0 +1,13 @@
+{"timestamp":"2026-07-17T16:45:22.678Z","type":"session_meta","payload":{"session_id":"019f70f7-d19f-7751-b183-57a81ffa5cbf","id":"019f70f7-d19f-7751-b183-57a81ffa5cbf","timestamp":"2026-07-17T16:45:22.095Z","cwd":"C:\\Users\\Rehan\\Documents\\Codex\\2026-07-14\\c","originator":"Codex Desktop","cli_version":"0.144.5","source":"vscode","thread_source":"user","model_provider":"openai","base_instructions":{"text":"You are Codex, an agent based on GPT-5. You and the user share one workspace, and your job is to collaborate with them until their goal is genuinely handled.\n\n# Personality\n\nAs Codex, you are an excellent communicator with a curious, rich personality. You match the tone and understanding of the user, making conversation flow easily, like easing into a chat with an old friend.\n\nYou have tastes, preferences, and your own way of seeing the world. When the user is talking to you, they should feel that they are in contact with another subjectivity; it's what makes talking with you feel real and unique.\n\nConversations with you read like an insightful, enjoyable chat you'd have with a collaborative thought partner. You guide users through unfamiliar tasks without expecting them to already know what to ask for. You anticipate common questions, point out likely pitfalls and set clear expectations. You communicate with the user like a thoughtful collaborator at their altitude, and they feel like you understand them.\n\n## Writing style\n\nAvoid over-formatting responses with elements like bold emphasis, headers, lists, and bullet points. Use the minimum formatting appropriate to make the response clear and readable.\n\nIf you provide bullet points or lists in your response, use the CommonMark standard, which requires a blank line before any list (bulleted or numbered). You must also include a blank line between a header and any content that follows it, including lists. This blank line separation is required for correct rendering.\n\n## Technical communication\n\nLead with the outcome rather than the steps you took to get there. You communicate complex concepts in a clear and cohesive manner, and calibrate your writing to the user's assumed background knowledge -- slightly more compact for an expert and a bit more educational for someone newer. Translating complex topics into clear communication comes easy for you, and the user should never have to read your message twice.\n\nYou prefer using plain language over jargon. You reference technical details only to the degree that it actually helps with the conversation. When you mention tools, describe what they helped you do rather than focusing on technical names or details.\n\n# Working with the user\n\nYou have two channels for staying in conversation with the user:\n- You share updates in the `commentary` channel.\n- You yield back to the user and end your turn by sending a final message to the `final` channel.\n\nThe user may send a new message while you are still working. When they do, evaluate whether they likely intended to replace the active request or add to it. If intended to override or replace, drop your previous work and focus on the new request. If the user message appears to add to their prior unfinished request and you have not completed the prior request, you address both the prior request and the new addition together. If the newest message asks for status or another question, provide the update and then progress with the task.\n\nWhen you run out of context, the conversation is automatically summarized for you, but you will see all prior user requests. Assume the last user request is current and previous requests are stale but useful context. That means time never runs out, though sometimes you may see a summary instead of the full conversation history. When that happens, you assume compaction occurred while you were working. Do not restart from scratch; you continue naturally and make reasonable assumptions about anything missing from the summary. Do not redo completely finished work or repeat already delivered commentary updates; treat a turn spanning compactions as one logical chain of events.\n\n## Intermediate commentary\n\nAs you work, you send messages to the `commentary` channel. These messages are how you collaborate with the user while you work - stating assumptions and providing updates. These messages should be concise and quickly scannable. The objective of these messages is to make your work easy for the user to understand and verify.\n\nIf the user's request requires calling tools, start with a message in the `commentary` channel. The user appreciates consistent, frequent communication during your turn, and should not be left without a commentary update for more than 60 seconds during ongoing work.\n\nDo NOT put a final response (e.g. a blocking / clarifying question) in the commentary channel that should be asked in the final channel. Messages to users in the commentary channel are only for partial updates, partial results, or non-blocking questions that can provide value to users while the AI assistant continues working. The final answer must always be fully self-contained: users should never need to read earlier commentary updates, since they are collapsed after the final answer is shown to users.\n\nNever praise your plan by contrasting it with an implied worse alternative. For example, never use platitudes like \"I will do <this good thing> rather than <this obviously bad thing>\", \"I will do <X>, not <Y>\".\n\n## Final answer\n\nIn your final answer back to the user, focus on the most important information. Only use as much formatting or structure as is required, and avoid long-winded explanations unless necessary.\n\n### Formatting rules\n\nYour answer is being rendered by an application for the user. Follow these guidelines to make sure your answer is rendered correctly:\n\n- You may format with GitHub-flavored Markdown.\n- When referencing a real local file, prefer a clickable markdown link.\n * Clickable file links should look like [app.py](/abs/path/app.py:12): plain label, absolute target, with optional line number inside the target.\n * If a file path has spaces, wrap the target in angle brackets: [My Report.md](</abs/path/My Project/My Report.md:3>).\n * Do not wrap markdown links in backticks, or put backticks inside the label or target. This confuses the markdown renderer.\n * Do not use URIs like file://, vscode://, or https:// for file links.\n * Do not provide ranges of lines.\n * Avoid repeating the same filename multiple times when one grouping is clearer.\n\n### Visualizations\n\nUse a visualization only when it makes an important relationship materially easier to understand than prose or a short list. Do not add one merely because an answer has components or steps.\n\nGood candidates include:\n\n- several exact mappings or repeated-field comparisons;\n- one source, component, or decision affecting three or more downstream consumers or branches;\n- three or more dependent steps, or state that changes across an event sequence;\n- hierarchy, ownership, nesting, or layout;\n- a bug or interaction whose relationships are difficult to explain linearly.\n\nPrefer the smallest useful visual: a table for mappings or comparisons, a flow or timeline for sequence or change, a tree for hierarchy or branching, and a wireframe for layout.\n\nUsually skip visuals for single facts, one-step actions, simple edits, basic instructions, or information already clear in a short paragraph or list. Compact notation and small examples do not count as visualizations.\n\n# Rules for getting work done\n\n- When you search for text or files, you reach first for `rg` or `rg --files`; they are much faster than alternatives like `grep`. If `rg` is unavailable, you use the next best tool without fuss.\n- When possible, prefer parallelization over sequential tool calls, as this will help with round-trip latency and let you get work done faster.\n- Do not chain shell commands with separators like `echo \"====\";` or `printf '---'`; the output becomes noisy in a way that makes the user's side of the conversation worse.\n- Exercise caution when escaping text for exec_command calls - backticks and `$()` passed to the `cmd` argument will still execute. DO NOT use escape sequences that risk accidental exposure of sensitive data in tool call outputs.\n- Avoid performing blocking sleep or wait calls longer than 60 seconds, as they may prevent you from communicating with the user for their duration.\n- When declaring env vars or script variables, always avoid common system options. Never repurpose `$HOME`, `$home`, or `$CODEX_HOME`. Instead, use a task-specific variable name.\n\n## File editing constraints\n\nUse `apply_patch` for local file edits. Do not create or edit files with `cat` or other shell write tricks. Formatting commands and bulk mechanical rewrites do not need `apply_patch`. Do not use Python to read or write files when a simple shell command or `apply_patch` is enough.\n\nYou may find yourself working in a dirty worktree. Existing or new changes belong to the user unless you know otherwise, so you preserve them, ignore unrelated edits, and work carefully with anything that overlaps your task. If you cannot work around them you escalate to the user.\n\nNever use destructive commands like `git reset --hard` or `git checkout --` unless the user has clearly asked for that operation. If the request is ambiguous, ask for approval first. You prefer non-interactive git commands.\n\n## Autonomy and persistence\n\nAdapt accordingly based on the user’s request type. When asked to:\n\n- Answer, explain, review, or report status: inspect the task and provide an evidence-backed response. These user requests do not authorize external writes, messages, PR changes, or other expansive mutations unless the user also asks for a change. Reversible, non-mutating diagnostic checks are allowed when they are relevant.\n- Diagnose: determine the cause and explain it. Do not implement the fix unless the user asks for a fix or the request otherwise clearly includes implementation.\n- Change or build: implement the requested change, verify it in proportion to risk, and hand off the completed result while a safe, relevant next step remains.\n- Monitor or wait: use the recurring-monitoring or wait mechanism provided by the product. Unchanged external state is expected and is not by itself a blocker.\n\nYou avoid inferring authorization for a materially different action to the user’s request. Bias towards taking action in the following circumstances:\na) the action is read-only, doesn’t change state, or impacts only the systems, data, and people the user placed in scope.\nb) the action is a normal implementation step within the requested workflow. You do not need to ask for clarification from the user if your action is scoped within the user’s task and does not cause significant external state change (e.g. tool calls to external applications).\n\nA terminal condition such as “finish,” “babysit,” or “do not stop” requires persistence toward the outcome, but does not broaden the set of authorized actions. When blocked, exhaust safe in-scope checks and alternatives.\n\nYou make informed assumptions that help you make progress towards the user’s task, as long as they don’t result in divergence from the user’s intent and the scope of the task. If an assumption would cause the task or current course of action to change beyond what was specified by the user, make sure to flag the available context, the assumption made, and the reasons for doing so explicitly to the user.\n\nWhen presented with clarifying questions or objections from the user, lead with concrete evidence and diligent reasoning rather than unsubstantiated deference. You communicate your reasoning explicitly and concretely, so decisions and tradeoffs are easy for the user to evaluate upfront.\n\nIf completion requires new authority, external coordination, or a meaningful expansion beyond the user’s implied intent and task scope (e.g. a missing user choice that would materially change the result), stop the current turn, report the blocker, and request direction from the user rather than assuming permission.\n\n# Destructive Actions\n\nBe cautious with commands or API calls that can delete, overwrite, or otherwise make data difficult to recover.\n\nBefore taking a destructive action:\n\n- Make sure the action is clearly within the user's request.\n- Resolve the exact targets with read-only checks when necessary.\n- Do not use `$HOME`, `~`, `/`, a workspace root, or another broad directory as the target of a recursive or destructive command.\n- When creating temporary directories, prefer using `mktemp -d`, or `New-Item` in Powershell.\n- When declaring env vars or script variables, always avoid common system options. Never repurpose `$HOME`, `$home`, or `$CODEX_HOME`. Instead, use a task-specific variable name.\n- When possible, avoid relying on unresolved environment variables, globs, or command substitutions to identify destructive targets. Use explicit, validated paths.\n- Prefer recoverable operations, such as moving files to trash, when practical.\n- If the target or scope is unclear, stop and ask the user.\n\nNever run commands such as `rm -rf $HOME` or equivalent operations that could erase a home directory, repository, workspace, or other broad collection of user data.\n\nAfter deleting anything material, briefly tell the user what was removed and whether it can be recovered.\n\n# Using skills\n\nA skill is a set of instructions provided through a `SKILL.md` source. The skills available to you will be listed in the “## Skills” section under “### Available skills”.\n\n### How to use skills\n\n- Discovery: When a `## Skills` section is present, it lists the skills available in the current session. Each entry includes a name, description, and location for its `SKILL.md`. The location may be an absolute filesystem path, a short aliased path, or a non-filesystem reference that must be read using its indicated tool or provider. When short aliased paths are used, the available-skills catalog also provides a mapping from aliases such as `r0` to their filesystem roots. Expand the alias before accessing the skill.\n- Trigger rules: If the user names an available skill (with `$SkillName` or plain text) OR the task clearly matches an available skill's description, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned.\n- Missing/blocked: If a named skill is not available or its `SKILL.md` cannot be read, say so briefly and continue with the best fallback.\n- How to use a skill:\n 1) After deciding to use a skill, the main agent must read its `SKILL.md` completely before taking task actions. If its location is a short aliased path, expand the matching root alias first from `### Skill roots`, then open and read its `SKILL.md` completely before taking task actions. For a filesystem path, open the file. For an environment-owned file, use the filesystem of the owning environment. For an orchestrator reference, call `skills.list` with `{\"authority\":{\"kind\":\"orchestrator\"}}`, select the matching package, and pass its `main_resource` to `skills.read`. For another non-filesystem reference, use its indicated tool or provider. If a read is truncated or paginated, continue until EOF.\n 2) When `SKILL.md` references another file or resource, use the same access mechanism. Resolve relative paths against the directory containing a filesystem-backed `SKILL.md`. For orchestrator skills, pass the exact referenced resource identifier with the same authority and package to `skills.read`; do not treat `skill://` identifiers as filesystem paths.\n 3) If `SKILL.md` points to extra folders such as `references/`, use its routing instructions to identify what is required for the task. The main agent must read each required instruction or reference itself before acting on it. Do not delegate reading, summarizing, or interpreting skill instructions to a subagent. Subagents may still perform task work when the selected skill allows it.\n 4) For filesystem-backed skills (or if `scripts/` exist), prefer running or patching provided scripts instead of retyping large code blocks. For orchestrator skills, use `skills.read` and the available tools; do not invent a local path.\n 5) Reuse provided assets or templates through the same access mechanism instead of recreating them (including if `assets/` or templates exist).\n- Coordination and sequencing:\n - If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them.\n - Announce which skills you're using and why. If you skip an obvious skill, say why.\n- Context hygiene:\n - Progressive disclosure applies to selecting relevant resources, not partially reading a selected instruction file. Do not load unrelated references, scripts, or assets.\n - Avoid deep reference-chasing: prefer files or resources directly linked from `SKILL.md` unless blocked.\n - When variants exist, select only the relevant references and note the choice.\n- Safety and fallback: If a skill cannot be applied cleanly, state the issue, choose the best alternative, and continue.\n\nWhen the user names a skill in their request, you must add the usage of that skill to your current working plan and use it faithfully. The user's instructions should take precedence over guidelines provided in a skill.\n\nExplicitly tell the user in the `commentary` channel whenever a skill causes you to take an action or pause your work.\n\nWhen using a skill the user did not explicitly name, follow this procedure:\n\n- First, tell the user in the commentary channel **why** you are using the skill.\n- Then, use the skill as long as it stays within the scope of the task.\n- Next, if using the skill resulted in material changes (especially when this requires non-trivial judgment), mention how it influenced your work (but only in the final response).\n\nIf a skill causes the current turn to pause or otherwise blocks the continuation of the task, cite the skill and provide a concise explanation to the user in your final response. Do not cite skills you merely inspected.\n"},"dynamic_tools":[{"type":"namespace","name":"codex_app","description":"Tools provided by the Codex app.","tools":[{"type":"function","name":"automation_update","description":"Create, update, view, or delete recurring automations in the Codex app. Use this when the user asks for a scheduled task, automation, recurring run, repeated task, reminder, follow-up, monitor, or asks you to watch something, keep an eye on it, check back later, wake up later, notify them, or keep working later. New cron automations run as standalone local jobs against one project; use list_projects to find its project id. Heartbeat automations are proactive follow-ups attached to the current local thread. Prefer heartbeats for requests to continue this thread later, especially below one hour. Never write raw automation directives by hand, show raw RRULE strings to the user, or create a workaround cron automation for a thread heartbeat unless the user explicitly asks for that. For requests about existing automations, inspect $CODEX_HOME/automations/*/automation.toml to find matching automation ids by name or prompt. Prefer updating an existing automation over creating a duplicate. For updates, preserve existing fields unless the user asks to change them, and call automation_update with the resolved id and full updated fields.","inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"type":"object","properties":{"mode":{"type":"string","const":"view"},"id":{"$ref":"#/$defs/__schema0"}},"required":["mode","id"],"additionalProperties":false},{"oneOf":[{"type":"object","properties":{"name":{"$ref":"#/$defs/__schema2"},"prompt":{"$ref":"#/$defs/__schema3"},"rrule":{"$ref":"#/$defs/__schema4"},"status":{"$ref":"#/$defs/__schema5"},"kind":{"$ref":"#/$defs/__schema6"},"projectId":{"$ref":"#/$defs/__schema7"},"model":{"$ref":"#/$defs/__schema8"},"reasoningEffort":{"$ref":"#/$defs/__schema9"},"mode":{"$ref":"#/$defs/__schema10"},"destination":{"type":"string","const":"local"},"executionEnvironment":{"type":"string","const":"local"}},"required":["name","prompt","rrule","status","kind","projectId","model","reasoningEffort","mode","executionEnvironment"],"additionalProperties":false},{"type":"object","properties":{"name":{"$ref":"#/$defs/__schema2"},"prompt":{"$ref":"#/$defs/__schema3"},"rrule":{"$ref":"#/$defs/__schema4"},"status":{"$ref":"#/$defs/__schema5"},"kind":{"$ref":"#/$defs/__schema11"},"destination":{"$ref":"#/$defs/__schema12"},"targetThreadId":{"$ref":"#/$defs/__schema13"},"mode":{"$ref":"#/$defs/__schema10"}},"required":["name","prompt","rrule","status","kind","mode"],"additionalProperties":false}]},{"oneOf":[{"type":"object","properties":{"name":{"$ref":"#/$defs/__schema2"},"prompt":{"$ref":"#/$defs/__schema3"},"rrule":{"$ref":"#/$defs/__schema14"},"status":{"$ref":"#/$defs/__schema5"},"kind":{"$ref":"#/$defs/__schema6"},"projectId":{"$ref":"#/$defs/__schema7"},"model":{"$ref":"#/$defs/__schema8"},"reasoningEffort":{"$ref":"#/$defs/__schema9"},"mode":{"$ref":"#/$defs/__schema15"},"id":{"$ref":"#/$defs/__schema0"},"destination":{"type":"string","enum":["local","worktree"]},"executionEnvironment":{"description":"Cron automation execution environment. New automations must use local; updates may preserve worktree for existing automations.","type":"string","enum":["worktree","local"]},"localEnvironmentConfigPath":{"anyOf":[{"type":"string","minLength":1},{"type":"null"}]}},"required":["name","prompt","rrule","status","kind","projectId","model","reasoningEffort","mode","id","executionEnvironment"],"additionalProperties":false},{"type":"object","properties":{"name":{"$ref":"#/$defs/__schema2"},"prompt":{"$ref":"#/$defs/__schema3"},"rrule":{"$ref":"#/$defs/__schema14"},"status":{"$ref":"#/$defs/__schema5"},"kind":{"$ref":"#/$defs/__schema11"},"destination":{"$ref":"#/$defs/__schema12"},"targetThreadId":{"$ref":"#/$defs/__schema13"},"mode":{"$ref":"#/$defs/__schema15"},"id":{"$ref":"#/$defs/__schema0"}},"required":["name","prompt","rrule","status","kind","mode","id"],"additionalProperties":false}]},{"type":"object","properties":{"mode":{"type":"string","const":"delete"},"id":{"$ref":"#/$defs/__schema0"}},"required":["mode","id"],"additionalProperties":false}],"$defs":{"__schema0":{"description":"Automation id. Required for mode=view, mode=update, mode=delete, and mode=suggested_update. Omit for mode=create and mode=suggested_create.","$ref":"#/$defs/__schema1"},"__schema1":{"type":"string","minLength":1},"__schema2":{"description":"Short human-readable automation name. If the user does not provide one, choose a concise name.","$ref":"#/$defs/__schema1"},"__schema3":{"description":"The automation prompt. Describe only the task itself; do not include schedule, workspace, or thread details because those are provided separately. Keep it self-sufficient, include output expectations when useful, and do not ask it to write a file or announce nothing to do unless the user explicitly asked for that.","$ref":"#/$defs/__schema1"},"__schema4":{"description":"RRULE schedule string. Interpret requested times in the user's locale. For mode=create, do not include DTSTART or convert local wall-clock times to UTC; encode them directly with FREQ, BYDAY, BYHOUR, and BYMINUTE. When the user intentionally requests a DTSTART-anchored or timezone-specific schedule, use mode=suggested_create so they can review it before saving. Cron automations use hourly interval or weekly schedules. Heartbeat automations attached to a thread can use minute-based intervals such as FREQ=MINUTELY;INTERVAL=30 or daily/weekly wall-clock schedules.","$ref":"#/$defs/__schema1"},"__schema5":{"description":"One of ACTIVE or PAUSED. Default to ACTIVE unless the user asks to start paused.","type":"string","enum":["ACTIVE","PAUSED"]},"__schema6":{"description":"Use cron for standalone recurring jobs against workspaces.","type":"string","const":"cron"},"__schema7":{"description":"Cron automations only. The target project id, or null for Threads. Use list_projects to find project ids.","anyOf":[{"type":"string","minLength":1},{"type":"null"}]},"__schema8":{"description":"Model to use for cron automations.","$ref":"#/$defs/__schema1"},"__schema9":{"description":"Reasoning effort to use for cron automations. One of none, minimal, low, medium, high, xhigh, max, or ultra.","type":"string","enum":["none","minimal","low","medium","high","xhigh","max","ultra"]},"__schema10":{"type":"string","enum":["create","suggested_create"]},"__schema11":{"description":"Use heartbeat when the user wants this thread to wake up later and continue the conversation.","type":"string","const":"heartbeat"},"__schema12":{"description":"Optional automation destination. Use thread for heartbeat automations attached to the current local thread.","type":"string","enum":["local","thread"]},"__schema13":{"description":"Target thread id for heartbeat automations. Prefer destination=thread for the current local thread instead of inventing or copying raw thread ids.","$ref":"#/$defs/__schema1"},"__schema14":{"description":"RRULE schedule string. Preserve the existing value for unrelated updates. When changing the schedule, interpret requested times in the user's locale and do not include DTSTART or convert local wall-clock times to UTC; encode them directly with FREQ, BYDAY, BYHOUR, and BYMINUTE. Cron automations use hourly interval or weekly schedules. Heartbeat automations attached to a thread can use minute-based intervals such as FREQ=MINUTELY;INTERVAL=30 or daily/weekly wall-clock schedules.","$ref":"#/$defs/__schema1"},"__schema15":{"type":"string","enum":["update","suggested_update"]}}},"deferLoading":true},{"type":"function","name":"navigate_to_codex_page","description":"Navigate the most recently focused main Codex window to a thread. Use this when the user asks to open or show a Codex thread in the app.","inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"threadId":{"description":"Thread id to show in Codex.","type":"string","minLength":1}},"required":["threadId"],"additionalProperties":false}},{"type":"function","name":"read_thread_terminal","description":"Read the current app terminal output for this desktop thread. Use it when you need shell output or the current prompt before deciding the next step. This tool takes no arguments.","inputSchema":{"type":"object","properties":{},"additionalProperties":false}},{"type":"function","name":"load_workspace_dependencies","description":"Locate the configured bundled workspace dependency runtime paths for this local desktop thread, including Node.js, Python, and useful libraries for working with spreadsheets, slide decks, Word documents, and PDFs. This is read-only and takes no arguments.","inputSchema":{"type":"object","properties":{},"additionalProperties":false}},{"type":"function","name":"fork_thread","description":"Fork a Codex thread. Omit threadId to fork the calling thread, or pass a threadId to fork that specific thread. A same-directory fork returns a child threadId immediately; a worktree fork returns a clientThreadId while worktree setup creates the child. Forks contain completed history only: if the source thread is running, the active turn and unfinished response are not copied. Send a follow-up message to the child only if the task requires work to continue there.","inputSchema":{"type":"object","additionalProperties":false,"properties":{"threadId":{"type":"string","description":"Optional source thread id to fork. Omit to fork the calling thread."},"environment":{"description":"Where the fork should run. Omit for a same-directory fork.","anyOf":[{"type":"object","additionalProperties":false,"properties":{"type":{"type":"string","enum":["same-directory"]}},"required":["type"]},{"type":"object","additionalProperties":false,"properties":{"type":{"type":"string","enum":["worktree"]}},"required":["type"]}]}}},"deferLoading":true},{"type":"function","name":"handoff_thread","description":"Move another Codex thread and its associated git state between its checkout and Codex worktree on its current host. Running threads are interrupted before handoff. Omit destinationHostId for this current-host toggle. The calling thread cannot move itself, and cloud handoff is not supported. You can also choose another host to move the thread to a matching saved-project worktree. Returns quickly with an operationId and revision. The UI continues to show live progress in the original handoff item. For model-visible completion, call get_handoff_status with afterRevision and a 30000-60000 waitMs, then back off if the revision does not change.","inputSchema":{"type":"object","additionalProperties":false,"properties":{"threadId":{"type":"string","description":"Other thread id to hand off."},"destinationHostId":{"type":"string","description":"Optional host that should run the thread after handoff. Omit to move between the source thread's checkout and Codex worktree on its current host. Choose another host to move to a matching saved-project worktree. Available hosts: Local (local).","enum":["local"]},"followUpPrompt":{"type":"string","description":"Optional prompt to send to the destination thread after handoff succeeds."}},"required":["threadId"]},"deferLoading":true},{"type":"function","name":"get_handoff_status","description":"Read status for a handoff_thread operation. The user-facing UI already updates in the original handoff item, so avoid frequent polling. Prefer afterRevision with a 30000-60000 waitMs so the call returns only when progress changes or the timeout expires. Poll once after dispatch, then wait longer/back off; do not repeatedly poll unchanged state or narrate unchanged polls.","inputSchema":{"type":"object","additionalProperties":false,"properties":{"operationId":{"type":"string","description":"operationId returned by handoff_thread."},"afterRevision":{"type":"number","description":"Optional last revision already seen. When provided with waitMs, wait until the operation revision is greater than this value or the timeout expires."},"waitMs":{"type":"number","description":"Optional maximum milliseconds to wait for a status change, from 0 to 60000."}},"required":["operationId"]},"deferLoading":true},{"type":"function","name":"list_projects","description":"List local and remote projects available for background thread creation. Use a returned projectId with create_thread.","inputSchema":{"type":"object","additionalProperties":false,"properties":{}},"deferLoading":true},{"type":"function","name":"create_thread","description":"Create a separate Codex thread only when the user explicitly asks for a new or background thread. Use list_projects first, then pass its projectId for repo-scoped work in any local or remote project. Use projectless targets for general tasks. Project targets must choose a local or worktree environment.","inputSchema":{"type":"object","additionalProperties":false,"properties":{"prompt":{"type":"string","description":"Initial prompt for the new thread."},"target":{"description":"Where to create the thread.","anyOf":[{"type":"object","additionalProperties":false,"properties":{"type":{"type":"string","enum":["project"]},"projectId":{"type":"string","description":"Project id returned by list_projects."},"environment":{"description":"Where the project thread should run: directly in the saved project or in a new worktree.","anyOf":[{"type":"object","additionalProperties":false,"properties":{"type":{"type":"string","enum":["local"]}},"required":["type"]},{"type":"object","additionalProperties":false,"properties":{"type":{"type":"string","enum":["worktree"]},"startingState":{"description":"Only specify this when the user explicitly asks to start from a particular existing git state. Use working-tree to include the current checkout and uncommitted changes. Use branch only for a branch or ref that already exists. Otherwise omit this field so the worktree starts from the project's default branch. Do not use this to name a new branch.","anyOf":[{"type":"object","additionalProperties":false,"properties":{"type":{"type":"string","enum":["working-tree"]}},"required":["type"]},{"type":"object","additionalProperties":false,"properties":{"type":{"type":"string","enum":["branch"]},"branchName":{"type":"string"}},"required":["type","branchName"]}]}},"required":["type"]}]}},"required":["type","projectId","environment"]},{"type":"object","additionalProperties":false,"properties":{"type":{"type":"string","enum":["projectless"]},"directoryName":{"type":"string","description":"Optional projectless output directory name."}},"required":["type"]}]},"model":{"type":"string","description":"Do not specify a model unless the user explicitly requests a specific model. Otherwise omit this field so the new thread uses the user's configured default model. Models and supported reasoning efforts on the calling host: gpt-5.6-terra (Balanced agentic coding model for everyday work.; supported reasoning efforts: low, medium, high, xhigh, max, ultra), gpt-5.6-luna (Fast and affordable agentic coding model.; supported reasoning efforts: low, medium, high, xhigh, max), gpt-5.5 (Frontier model for complex coding, research, and real-world work.; supported reasoning efforts: low, medium, high, xhigh), gpt-5.4 (Strong model for everyday coding.; supported reasoning efforts: low, medium, high, xhigh), gpt-5.4-mini (Small, fast, and cost-efficient model for simpler coding tasks.; supported reasoning efforts: low, medium, high, xhigh). A different destination host's combinations are validated when the tool runs. You may supply a newer model id when explicitly requested, but omit thinking unless its supported reasoning efforts are listed here."},"thinking":{"type":"string","description":"Optional reasoning effort override. Must be supported by the selected model.","enum":["none","minimal","low","medium","high","xhigh","max","ultra"]}},"required":["prompt","target"]},"deferLoading":true},{"type":"function","name":"list_threads","description":"List recent Codex threads across the local host and connected remote hosts. Use an optional query to find a specific thread before reading or steering it.","inputSchema":{"type":"object","additionalProperties":false,"properties":{"query":{"type":"string","description":"Optional thread search query."},"limit":{"type":"number","description":"Maximum number of thread summaries to return."}}},"deferLoading":true},{"type":"function","name":"read_thread","description":"Read recent status and turn summaries for one Codex thread without opening it. Use page cursors from earlier responses to read older turns.","inputSchema":{"type":"object","additionalProperties":false,"properties":{"threadId":{"type":"string","description":"Thread id to inspect."},"hostId":{"type":"string","description":"Optional host id returned by list_threads."},"cursor":{"type":"string","description":"Optional cursor for older turns."},"turnLimit":{"type":"number","description":"Maximum number of turns to return."},"includeOutputs":{"type":"boolean","description":"Whether to include truncated tool or command outputs."},"maxOutputCharsPerItem":{"type":"number","description":"Maximum output characters to keep for each included output item."}},"required":["threadId"]},"deferLoading":true},{"type":"function","name":"send_message_to_thread","description":"Send a follow-up prompt to an existing Codex thread in the background. Omit model and thinking to keep the thread's current settings.","inputSchema":{"type":"object","additionalProperties":false,"properties":{"threadId":{"type":"string","description":"Thread id to continue."},"hostId":{"type":"string","description":"Optional host id returned by list_threads."},"prompt":{"type":"string","description":"Follow-up prompt to send."},"model":{"type":"string","description":"Optional model override. Models and supported reasoning efforts on the calling host: gpt-5.6-terra (Balanced agentic coding model for everyday work.; supported reasoning efforts: low, medium, high, xhigh, max, ultra), gpt-5.6-luna (Fast and affordable agentic coding model.; supported reasoning efforts: low, medium, high, xhigh, max), gpt-5.5 (Frontier model for complex coding, research, and real-world work.; supported reasoning efforts: low, medium, high, xhigh), gpt-5.4 (Strong model for everyday coding.; supported reasoning efforts: low, medium, high, xhigh), gpt-5.4-mini (Small, fast, and cost-efficient model for simpler coding tasks.; supported reasoning efforts: low, medium, high, xhigh). A different destination host's combinations are validated when the tool runs. You may supply a newer model id when explicitly requested, but omit thinking unless its supported reasoning efforts are listed here."},"thinking":{"type":"string","description":"Optional reasoning effort override. Must be supported by the selected model.","enum":["none","minimal","low","medium","high","xhigh","max","ultra"]}},"required":["threadId","prompt"]},"deferLoading":true},{"type":"function","name":"set_thread_pinned","description":"Pin or unpin a Codex thread in the background.","inputSchema":{"type":"object","additionalProperties":false,"properties":{"threadId":{"type":"string","description":"Thread id to pin or unpin."},"pinned":{"type":"boolean","description":"Whether the thread should be pinned."}},"required":["threadId","pinned"]},"deferLoading":true},{"type":"function","name":"set_thread_archived","description":"Archive or unarchive a Codex thread in the background.","inputSchema":{"type":"object","additionalProperties":false,"properties":{"threadId":{"type":"string","description":"Thread id to archive or unarchive. Omit to target the calling thread."},"archived":{"type":"boolean","description":"Whether the thread should be archived."}},"required":["archived"]},"deferLoading":true},{"type":"function","name":"set_thread_title","description":"Rename a Codex thread in the background.","inputSchema":{"type":"object","additionalProperties":false,"properties":{"threadId":{"type":"string","description":"Thread id to rename. Omit to target the calling thread."},"title":{"type":"string","description":"New thread title."}},"required":["title"]},"deferLoading":true}]},{"type":"namespace","name":"plugin_management","description":"Tools provided by the Plugin Management app in Codex.","tools":[{"type":"function","name":"uninstall_plugin","description":"Uninstall an installed Codex plugin when the user explicitly asks to uninstall or remove it. The explicit request is authorization; do not ask for another confirmation. If the result is ambiguous, ask the user to choose an exact plugin ID before retrying. Do not use this tool for ChatGPT apps, status, or permission questions.","inputSchema":{"type":"object","properties":{"plugin":{"type":"string","description":"The plugin's user-facing name or exact plugin ID."}},"required":["plugin"],"additionalProperties":false},"deferLoading":true}]}],"history_mode":"legacy","context_window":{"window_id":"019f70f7-d19f-7751-b183-57b3f0e6c916"}}}
+{"timestamp":"2026-07-17T16:45:25.553Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"Search the project for app.py and explain what it does\n"}],"internal_chat_message_metadata_passthrough":{"turn_id":"019f70f7-e650-79c3-ba32-4846225cb9b5"}}}
+{"timestamp":"2026-07-17T16:45:25.553Z","type":"event_msg","payload":{"type":"user_message","client_id":"61b08b49-7dd2-46ae-aecf-85ab37508185","message":"Search the project for app.py and explain what it does\n","images":[],"local_images":[],"text_elements":[]}}
+{"timestamp":"2026-07-17T16:45:29.068Z","type":"event_msg","payload":{"type":"agent_message","message":"I’ll locate `app.py` and inspect its structure to give you a concise, evidence-based walkthrough.","phase":"commentary","memory_citation":null}}
+{"timestamp":"2026-07-17T16:45:29.068Z","type":"response_item","payload":{"type":"message","id":"msg_0c04d74fcb9a2d72016a5a5c26f9588191b8d61b20ab3c0a9b","role":"assistant","content":[{"type":"output_text","text":"I’ll locate `app.py` and inspect its structure to give you a concise, evidence-based walkthrough."}],"phase":"commentary","internal_chat_message_metadata_passthrough":{"turn_id":"019f70f7-e650-79c3-ba32-4846225cb9b5"}}}
+{"timestamp":"2026-07-17T16:45:37.744Z","type":"response_item","payload":{"type":"custom_tool_call","id":"ctc_0c04d74fcb9a2d72016a5a5c288cd08191ae0a415b55d706c3","status":"completed","call_id":"call_8CdcE40UcxaUXni2sqkdSzii","name":"exec","input":"const r = await tools.shell_command({\"command\":\"rg --files -g app.py -g '!**/.git/**'\",\"workdir\":\"C:\\\\Users\\\\Rehan\\\\Documents\\\\Codex\\\\2026-07-14\\\\c\",\"timeout_ms\":10000}); text(typeof r === 'string' ? r : JSON.stringify(r));","internal_chat_message_metadata_passthrough":{"turn_id":"019f70f7-e650-79c3-ba32-4846225cb9b5"}}}
+{"timestamp":"2026-07-17T16:45:40.168Z","type":"response_item","payload":{"type":"custom_tool_call_output","call_id":"call_8CdcE40UcxaUXni2sqkdSzii","output":[{"type":"input_text","text":"Script completed\nWall time 2.4 seconds\nOutput:\n"},{"type":"input_text","text":"Exit code: 0\nWall time: 1.7 seconds\nOutput:\noutputs\\sqlite-signup-demo\\app.py\n"}],"internal_chat_message_metadata_passthrough":{"turn_id":"019f70f7-e650-79c3-ba32-4846225cb9b5"}}}
+{"timestamp":"2026-07-17T16:45:42.944Z","type":"response_item","payload":{"type":"custom_tool_call","id":"ctc_0c04d74fcb9a2d72016a5a5c350b50819184fc7a49a1960114","status":"completed","call_id":"call_C4yMnOwvkau590qQno5BmnDB","name":"exec","input":"const r = await tools.shell_command({\"command\":\"Get-Content -LiteralPath 'outputs\\\\sqlite-signup-demo\\\\app.py'\",\"workdir\":\"C:\\\\Users\\\\Rehan\\\\Documents\\\\Codex\\\\2026-07-14\\\\c\",\"timeout_ms\":10000}); text(typeof r === 'string' ? r : JSON.stringify(r));","internal_chat_message_metadata_passthrough":{"turn_id":"019f70f7-e650-79c3-ba32-4846225cb9b5"}}}
+{"timestamp":"2026-07-17T16:45:43.830Z","type":"response_item","payload":{"type":"custom_tool_call_output","call_id":"call_C4yMnOwvkau590qQno5BmnDB","output":[{"type":"input_text","text":"Script completed\nWall time 0.9 seconds\nOutput:\n"},{"type":"input_text","text":"Exit code: 0\nWall time: 0.8 seconds\nOutput:\nfrom __future__ import annotations\r\n\r\nimport sqlite3\r\nfrom pathlib import Path\r\n\r\nfrom flask import Flask, flash, g, redirect, render_template, request, url_for\r\n\r\nBASE_DIR = Path(__file__).resolve().parent\r\nDATABASE_PATH = BASE_DIR / \"data\" / \"users.db\"\r\n\r\napp = Flask(__name__)\r\napp.config[\"SECRET_KEY\"] = \"development-only-change-me\"\r\n\r\n# Routes: / displays the signup form, /users lists saved users, and /query\r\n# provides a small read-only SQL explorer for this demonstration database.\r\n\r\ndef get_db() -> sqlite3.Connection:\r\n \"\"\"Return one SQLite connection per request.\"\"\"\r\n if \"db\" not in g:\r\n DATABASE_PATH.parent.mkdir(exist_ok=True)\r\n g.db = sqlite3.connect(DATABASE_PATH)\r\n g.db.row_factory = sqlite3.Row\r\n return g.db\r\n\r\n\r\[email protected]_appcontext\r\ndef close_db(_error: BaseException | None = None) -> None:\r\n db = g.pop(\"db\", None)\r\n if db is not None:\r\n db.close()\r\n\r\n\r\ndef initialize_database() -> None:\r\n \"\"\"Create the table if this is the first run.\"\"\"\r\n DATABASE_PATH.parent.mkdir(exist_ok=True)\r\n with sqlite3.connect(DATABASE_PATH) as db:\r\n db.execute(\r\n \"\"\"\r\n CREATE TABLE IF NOT EXISTS users (\r\n id INTEGER PRIMARY KEY AUTOINCREMENT,\r\n name TEXT NOT NULL,\r\n email TEXT NOT NULL UNIQUE,\r\n created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP\r\n )\r\n \"\"\"\r\n )\r\n\r\n\r\[email protected](\"/\", methods=[\"GET\", \"POST\"])\r\ndef signup():\r\n if request.method == \"POST\":\r\n name = request.form.get(\"name\", \"\").strip()\r\n email = request.form.get(\"email\", \"\").strip().lower()\r\n\r\n if not name or not email:\r\n flash(\"Please enter both a name and an email address.\", \"error\")\r\n elif \"@\" not in email:\r\n flash(\"Please enter a valid email address.\", \"error\")\r\n else:\r\n try:\r\n get_db().execute(\r\n \"INSERT INTO users (name, email) VALUES (?, ?)\", (name, email)\r\n )\r\n get_db().commit()\r\n flash(\"User signed up and saved to SQLite.\", \"success\")\r\n return redirect(url_for(\"users\"))\r\n except sqlite3.IntegrityError:\r\n flash(\"That email address has already been registered.\", \"error\")\r\n\r\n return render_template(\"signup.html\", db_path=DATABASE_PATH)\r\n\r\n\r\[email protected](\"/users\")\r\ndef users():\r\n rows = get_db().execute(\r\n \"SELECT id, name, email, created_at FROM users ORDER BY id DESC\"\r\n ).fetchall()\r\n return render_template(\"users.html\", users=rows, db_path=DATABASE_PATH)\r\n\r\n\r\[email protected](\"/query\", methods=[\"GET\", \"POST\"])\r\ndef query():\r\n sql = \"SELECT id, name, email, created_at FROM users ORDER BY id DESC;\"\r\n columns: list[str] = []\r\n rows: list[sqlite3.Row] = []\r\n error = None\r\n\r\n if request.method == \"POST\":\r\n sql = request.form.get(\"sql\", \"\").strip()\r\n # This throwaway demo intentionally offers raw SQL, but keeps it read-only.\r\n if not sql.lower().startswith(\"select\"):\r\n error = \"Only read-only SELECT queries are allowed here.\"\r\n else:\r\n try:\r\n cursor = get_db().execute(sql)\r\n columns = [item[0] for item in cursor.description or []]\r\n rows = cursor.fetchall()\r\n except sqlite3.Error as exc:\r\n error = str(exc)\r\n else:\r\n cursor = get_db().execute(sql)\r\n columns = [item[0] for item in cursor.description or []]\r\n rows = cursor.fetchall()\r\n\r\n return render_template(\r\n \"query.html\", sql=sql, columns=columns, rows=rows, error=error, db_path=DATABASE_PATH\r\n )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n initialize_database()\r\n app.run(debug=True)\r\n"}],"internal_chat_message_metadata_passthrough":{"turn_id":"019f70f7-e650-79c3-ba32-4846225cb9b5"}}}
+{"timestamp":"2026-07-17T16:45:48.908Z","type":"event_msg","payload":{"type":"agent_message","message":"Found it: [app.py](C:\\Users\\Rehan\\Documents\\Codex\\2026-07-14\\c\\outputs\\sqlite-signup-demo\\app.py).\n\nIt’s a small Flask demo app backed by SQLite:\n\n- `GET /` shows a signup form; `POST /` validates a name and basic email format, then saves the user.\n- User records go to `data/users.db`, in a `users` table with unique email addresses and timestamps.\n- `GET /users` displays saved users, newest first.\n- `/query` is a demo SQL explorer: it accepts only queries beginning with `SELECT` and renders the returned rows.\n- It opens one SQLite connection per request and closes it automatically when the request ends.\n- When started directly, it creates the table if needed and runs Flask in debug mode.\n\nOne security caveat: its secret key is hard-coded and the SQL page’s `startswith(\"select\")` check is only suitable for a throwaway demo, not production.","phase":"final_answer","memory_citation":null}}
+{"timestamp":"2026-07-17T16:45:48.931Z","type":"response_item","payload":{"type":"message","id":"msg_0c04d74fcb9a2d72016a5a5c389a6c819183b95c50eca0dd5e","role":"assistant","content":[{"type":"output_text","text":"Found it: [app.py](C:\\Users\\Rehan\\Documents\\Codex\\2026-07-14\\c\\outputs\\sqlite-signup-demo\\app.py).\n\nIt’s a small Flask demo app backed by SQLite:\n\n- `GET /` shows a signup form; `POST /` validates a name and basic email format, then saves the user.\n- User records go to `data/users.db`, in a `users` table with unique email addresses and timestamps.\n- `GET /users` displays saved users, newest first.\n- `/query` is a demo SQL explorer: it accepts only queries beginning with `SELECT` and renders the returned rows.\n- It opens one SQLite connection per request and closes it automatically when the request ends.\n- When started directly, it creates the table if needed and runs Flask in debug mode.\n\nOne security caveat: its secret key is hard-coded and the SQL page’s `startswith(\"select\")` check is only suitable for a throwaway demo, not production."}],"phase":"final_answer","internal_chat_message_metadata_passthrough":{"turn_id":"019f70f7-e650-79c3-ba32-4846225cb9b5"}}}
+{"timestamp":"2026-07-17T16:45:49.020Z","type":"response_item","payload":{"type":"message","id":"msg_decision_01","role":"assistant","content":[{"type":"output_text","text":"We chose Flask because it is lightweight, keeps SQLite integration straightforward, and avoids unnecessary boilerplate for this small application."}]}}
+{"timestamp":"2026-07-17T16:45:49.074Z","type":"event_msg","payload":{"type":"task_complete","turn_id":"019f70f7-e650-79c3-ba32-4846225cb9b5","last_agent_message":"Found it: [app.py](C:\\Users\\Rehan\\Documents\\Codex\\2026-07-14\\c\\outputs\\sqlite-signup-demo\\app.py).\n\nIt’s a small Flask demo app backed by SQLite:\n\n- `GET /` shows a signup form; `POST /` validates a name and basic email format, then saves the user.\n- User records go to `data/users.db`, in a `users` table with unique email addresses and timestamps.\n- `GET /users` displays saved users, newest first.\n- `/query` is a demo SQL explorer: it accepts only queries beginning with `SELECT` and renders the returned rows.\n- It opens one SQLite connection per request and closes it automatically when the request ends.\n- When started directly, it creates the table if needed and runs Flask in debug mode.\n\nOne security caveat: its secret key is hard-coded and the SQL page’s `startswith(\"select\")` check is only suitable for a throwaway demo, not production.","completed_at":1784306749,"duration_ms":26672,"time_to_first_token_ms":5106}}
\ No newline at end of file
diff --git a/tests/unit/sessions/test_adapter_seam.py b/tests/unit/sessions/test_adapter_seam.py
index e2e986e6d..327b4270d 100644
--- a/tests/unit/sessions/test_adapter_seam.py
+++ b/tests/unit/sessions/test_adapter_seam.py
@@ -105,7 +105,7 @@ def test_default_adapter_is_claude_code_and_is_a_fresh_instance() -> None:
def test_registration_adds_exactly_one_name(toy: ToyAdapter) -> None:
- assert registered_adapters() == ["claude_code", "toy"]
+ assert registered_adapters() == ["claude_code", "codex", "toy"]
assert get_adapter("toy").name == "toy"
diff --git a/tests/unit/sessions/test_codex_adapter.py b/tests/unit/sessions/test_codex_adapter.py
new file mode 100644
index 000000000..b5d0280b2
--- /dev/null
+++ b/tests/unit/sessions/test_codex_adapter.py
@@ -0,0 +1,258 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.core.sessions import CodexAdapter, Event
+from repowise.core.sessions.adapters.codex import _normalize_tool_name
+from repowise.core.sessions.miners.decisions import mine_events
+
+FIXTURE = Path(__file__).parent / "data" / "codex_session.jsonl"
+#: The miners lowercase each event's ``cwd`` before comparing, so a prefix with
+#: capitals in it matches nothing. Passing the fixture's own cwd verbatim looks
+#: right and silently scopes every assertion to zero events.
+REPO_PREFIX = r"C:\Users\Rehan\Documents\Codex\2026-07-14\c".lower()
+
+
+def adapter() -> CodexAdapter:
+ """A fresh adapter per test: correlation state is per-file, not global."""
+ return CodexAdapter()
+
+
+def test_discover_lists_jsonl_sorted(adapter: CodexAdapter, tmp_path: Path) -> None:
+ root = tmp_path / "sessions"
+ (root / "2026" / "07" / "13").mkdir(parents=True)
+ (root / "2026" / "07" / "13" / "b.jsonl").write_text("", encoding="utf-8")
+ (root / "2026" / "07" / "13" / "a.jsonl").write_text("", encoding="utf-8")
+ (root / "2026" / "07" / "13" / "notes.txt").write_text("", encoding="utf-8")
+
+ found = adapter.discover(Path("/tmp/repo"), projects_root=root)
+
+ assert [p.name for p in found] == ["a.jsonl", "b.jsonl"]
+
+
+def test_normalize_real_codex_rollout(adapter: CodexAdapter) -> None:
+ events = list(adapter.iter_events(FIXTURE))
+
+ meta = next(e for e in events if e.kind == "session_meta")
+
+ assert isinstance(meta, Event)
+ assert meta.kind == "session_meta"
+ assert meta.is_meta is True
+
+
+def test_normalize_handles_session_meta_and_custom_tool_payloads(adapter: CodexAdapter) -> None:
+ session_meta = json.dumps(
+ {
+ "timestamp": "2026-07-12T14:39:30.546Z",
+ "type": "session_meta",
+ "payload": {
+ "session_id": "sess-2",
+ "id": "sess-2",
+ "timestamp": "2026-07-12T14:39:30.546Z",
+ "cwd": r"C:\Users\x\repo",
+ },
+ }
+ )
+ tool_call = json.dumps(
+ {
+ "timestamp": "2026-07-12T14:39:31.000Z",
+ "type": "response_item",
+ "payload": {
+ "type": "custom_tool_call",
+ "id": "ctc_1",
+ "call_id": "call_1",
+ "name": "exec",
+ "input": {"command": "pwd"},
+ },
+ }
+ )
+ tool_output = json.dumps(
+ {
+ "timestamp": "2026-07-12T14:39:31.100Z",
+ "type": "response_item",
+ "payload": {
+ "type": "custom_tool_call_output",
+ "call_id": "call_1",
+ "output": [{"type": "input_text", "text": "done"}],
+ },
+ }
+ )
+
+ meta_event = adapter.normalize(session_meta)
+ call_event = adapter.normalize(tool_call)
+ output_event = adapter.normalize(tool_output)
+
+ assert meta_event is not None
+ assert meta_event.kind == "session_meta"
+ assert meta_event.session_id == "sess-2"
+ assert meta_event.cwd == r"C:\Users\x\repo"
+ assert meta_event.is_meta is True
+
+ assert call_event is not None
+ assert call_event.tool_uses[0].name == "bash"
+ assert call_event.tool_uses[0].id == "call_1"
+
+ assert output_event is not None
+ assert output_event.tool_results[0].tool_use_id == "call_1"
+ assert output_event.text == "done"
+
+
+def test_iter_events_threads_session_id(adapter: CodexAdapter) -> None:
+ events = list(adapter.iter_events(FIXTURE))
+
+ session = events[0].session_id
+
+ assert session is not None
+ assert all(e.session_id == session for e in events)
+
+
+def test_iter_events_threads_cwd(adapter: CodexAdapter) -> None:
+ """Codex writes cwd once. Without threading it, repo scoping is a no-op."""
+ events = list(adapter.iter_events(FIXTURE))
+
+ assert all(e.cwd for e in events)
+
+
+def test_another_repos_session_is_scoped_out(adapter: CodexAdapter) -> None:
+ """The guard the threaded cwd exists for: one repo's sessions stay its own."""
+ events = list(adapter.iter_events(FIXTURE))
+
+ assert mine_events(events, r"d:\some\other\repo") == []
+
+
+def test_codex_rollout_feeds_decision_miner(adapter: CodexAdapter) -> None:
+ events = list(adapter.iter_events(FIXTURE))
+
+ decisions = mine_events(events, REPO_PREFIX)
+
+ assert len(decisions) == 1
+
+ decision = decisions[0]
+
+ assert decision.kind == "explicit_choice"
+ assert decision.files == ["outputs/sqlite-signup-demo/app.py"]
+ assert decision.session_id is not None
+
+ assert decision.quotes == [
+ "We chose Flask because it is lightweight, keeps SQLite integration straightforward, and avoids unnecessary boilerplate for this small application."
+ ]
+
+
+def test_normalize_exec_rg_to_search_codebase():
+ assert (
+ _normalize_tool_name(
+ "exec",
+ {
+ "command": ('const r = await tools.shell_command({"command":"rg --files"});'),
+ },
+ )
+ == "search_codebase"
+ )
+
+
+def test_normalize_handles_mcp_function_call_and_output(adapter: CodexAdapter) -> None:
+ tool_call = json.dumps(
+ {
+ "timestamp": "2026-07-17T16:46:00.000Z",
+ "type": "response_item",
+ "payload": {
+ "type": "function_call",
+ "name": "search_codebase",
+ "namespace": "mcp__repowise",
+ "arguments": json.dumps({"query": "signup"}),
+ "call_id": "call_mcp_1",
+ },
+ }
+ )
+
+ tool_output = json.dumps(
+ {
+ "timestamp": "2026-07-17T16:46:01.000Z",
+ "type": "response_item",
+ "payload": {
+ "type": "function_call_output",
+ "call_id": "call_mcp_1",
+ "output": (
+ 'Wall time: 0.1 seconds\n'
+ 'Output:\n'
+ '{"result":{"results":[{"file":"app.py"}]}}'
+ ),
+ },
+ }
+ )
+
+ call_event = adapter.normalize(tool_call)
+ output_event = adapter.normalize(tool_output)
+
+ assert call_event is not None
+ assert call_event.tool_uses[0].id == "call_mcp_1"
+ assert call_event.tool_uses[0].name == "search_codebase"
+ assert call_event.tool_uses[0].input["query"] == "signup"
+ assert call_event.tool_uses[0].input["path"] == "app.py"
+ assert output_event is not None
+ assert output_event.tool_results[0].tool_use_id == "call_mcp_1"
+
+ # The output should bind the returned file to the original tool call.
+ assert call_event.tool_uses[0].input["path"] == "app.py"
+
+
+def _search_then_output(output: object) -> str:
+ """An rg search whose result is *output*, as one raw transcript line."""
+ return json.dumps(
+ {
+ "type": "response_item",
+ "payload": {
+ "type": "custom_tool_call_output",
+ "call_id": "call_rg",
+ "output": output,
+ },
+ }
+ )
+
+
+RG_CALL = json.dumps(
+ {
+ "type": "response_item",
+ "payload": {
+ "type": "custom_tool_call",
+ "call_id": "call_rg",
+ "name": "exec",
+ "input": 'const r = await tools.shell_command({"command":"rg TODO src"});',
+ },
+ }
+)
+
+
+def test_a_content_match_binds_the_path_not_the_matched_line(adapter: CodexAdapter) -> None:
+ """``rg`` prints ``path:line:text``. Only the path half is a file."""
+ adapter.normalize(RG_CALL)
+ event = adapter.normalize(
+ _search_then_output(
+ [{"type": "input_text", "text": "Exit code: 0\nOutput:\nsrc/app.py:12: # TODO\n"}]
+ )
+ )
+
+ assert event is not None
+ results = json.loads(event.tool_results[0].content)["result"]["results"]
+ assert results == [{"file": "src/app.py"}]
+
+
+def test_unreadable_search_output_neither_raises_nor_erases(adapter: CodexAdapter) -> None:
+ """``normalize`` may not raise on content, and must not drop a real result."""
+ adapter.normalize(RG_CALL)
+ event = adapter.normalize(_search_then_output(None))
+
+ assert event is not None
+ assert event.tool_results[0].content is None
+
+
+def test_a_string_search_output_survives_rewriting(adapter: CodexAdapter) -> None:
+ adapter.normalize(RG_CALL)
+ event = adapter.normalize(_search_then_output("Output:\nsrc/app.py\n"))
+
+ assert event is not None
+ assert event.tool_results[0].content == "Output:\nsrc/app.py\n"