Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
Add Codex CLI provider and project integration (#348)
Raghav Chamadiya2e21dad38c7e
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.jsonnew file mode 100644index 000000000..d3fa42d3d--- /dev/null+++ b/.agents/plugins/marketplace.json@@ -0,0 +1,20 @@+{+ "name": "repowise",+ "interface": {+ "displayName": "Repowise"+ },+ "plugins": [+ {+ "name": "codex",+ "source": {+ "source": "local",+ "path": "./plugins/codex"+ },+ "policy": {+ "installation": "AVAILABLE",+ "authentication": "ON_INSTALL"+ },+ "category": "Productivity"+ }+ ]+}diff --git a/README.md b/README.mdindex 66a438897..4aec5667a 100644--- a/README.md+++ b/README.md@@ -50,7 +50,7 @@ source code and no memory of how the codebase got there.repowise fixes that. It indexes your codebase into **five intelligence layers** —dependency graph, git history, auto-generated docs, architectural decisions, and-code health — and exposes them to Claude Code (and any MCP-compatible agent)+code health — and exposes them to Claude Code, Codex, and any MCP-compatible agentthrough **nine task-shaped tools**. The result: your agent answers *"why doesauth work this way?"* instead of *"here is what `auth.ts` contains"* — with**fewer tool calls, fewer file reads, and lower cost per query, at comparable@@ -255,6 +255,10 @@ repowise serve # workspace dashboard + per-repo pages`repowise init` automatically registers the MCP server, installsPreToolUse/PostToolUse hooks in `~/.claude/settings.json`, generates `.mcp.json`at the project root, and offers a post-commit hook that keeps everything in sync.+If the Codex CLI is installed and logged in, interactive runs also offer to write+project-local `.codex/config.toml`, `.codex/hooks.json`, and a managed `AGENTS.md`;+non-interactive runs require `--codex`. Skip Codex setup with `--no-codex`; force or+skip `AGENTS.md` with `--agents` / `--no-agents`.To add the MCP server to another editor manually:@@ -273,7 +277,7 @@ To add the MCP server to another editor manually:> commit-triggered update takes **under 30 seconds** and only regenerates the> pages your change touched.-**Docs:** [Quickstart](docs/QUICKSTART.md) · [User Guide](docs/USER_GUIDE.md) · [CLI Reference](docs/CLI_REFERENCE.md) · [MCP Tools](docs/MCP_TOOLS.md) · [Workspaces](docs/WORKSPACES.md) · [Auto-Sync](docs/AUTO_SYNC.md) · [Config](docs/CONFIG.md)+**Docs:** [Quickstart](docs/QUICKSTART.md) · [User Guide](docs/USER_GUIDE.md) · [CLI Reference](docs/CLI_REFERENCE.md) · [Codex](docs/CODEX.md) · [MCP Tools](docs/MCP_TOOLS.md) · [Workspaces](docs/WORKSPACES.md) · [Auto-Sync](docs/AUTO_SYNC.md) · [Config](docs/CONFIG.md)---@@ -311,8 +315,8 @@ Worked example (*"Add rate limiting to all API endpoints"* in 5 calls instead of| Private repo — no cloud | ✅ | ❌ in development | ❌ OSS forks only | ✅ Enterprise tier | ✅ || Auto-generated documentation | ✅ | ✅ Gemini | ✅ | ✅ PR2Doc | ❌ || MCP server for AI agents | ✅ 9 tools | ❌ | ✅ 3 tools | ✅ | ✅ |-| Proactive agent hooks | ✅ Pre + PostToolUse | ❌ | ❌ | ❌ | ❌ |-| Auto-generated CLAUDE.md | ✅ | ❌ | ❌ | ❌ | ❌ |+| Proactive agent hooks | ✅ Claude + Codex hooks | ❌ | ❌ | ❌ | ❌ |+| Auto-generated AI instructions (`CLAUDE.md`, `AGENTS.md`) | ✅ | ❌ | ❌ | ❌ | ❌ || Code health score (1–10) | ✅ 25 biomarkers | ❌ | ❌ | ❌ | ✅ 25–30 || Brain Method / LCOM4 / god class | ✅ | ❌ | ❌ | ❌ | ✅ || Test-coverage intelligence | ✅ LCOV/Cobertura/Clover | ❌ | ❌ | ❌ | ❌ |diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.mdindex 6977930e8..27cf69e4f 100644--- a/docs/CLI_REFERENCE.md+++ b/docs/CLI_REFERENCE.md@@ -42,7 +42,7 @@ repowise init .1. **Ingestion** — walks every file, parses AST with tree-sitter, builds a two-tier dependency graph (file + symbol nodes), indexes git history (churn, hotspots, ownership, bus factor)2. **Analysis** — detects dead code, extracts architectural decisions from inline markers, READMEs, and git history. Runs Leiden community detection and execution flow tracing.3. **Generation** — sends structured prompts to the LLM, generates file-level, module-level, and repo-level wiki pages-4. **Persistence** — stores everything in `.repowise/wiki.db`, builds search indexes, generates `CLAUDE.md`, registers MCP server and Claude Code hooks+4. **Persistence** — stores everything in `.repowise/wiki.db`, builds search indexes, generates editor instruction files, registers MCP server and hooksIn workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (co-changes, contracts, package deps), workspace CLAUDE.md generation.@@ -50,7 +50,7 @@ In workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (| Flag | Description ||------|-------------|-| `--provider` | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `ollama`, `litellm`, `mock` |+| `--provider` | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `ollama`, `litellm`, `codex_cli`, `mock` || `--model` | Model name override (e.g., `claude-sonnet-4-6`) || `--embedder` | Embedder for semantic search: `gemini`, `openai`, `mock` || `--index-only` | Skip LLM generation. Only parse, build graph, and index git. Free. |@@ -62,12 +62,14 @@ In workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (| `--exclude / -x` | Gitignore-style exclusion patterns. Repeatable. || `--include-submodules` | Include git submodule directories. || `--concurrency` | Max concurrent LLM calls (default: 5). |-| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`, or `minimal` (default: `auto`). |+| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` (default: `auto`). || `--resume` | Resume from the last checkpoint if interrupted. || `--force` | Regenerate all pages even if they exist. || `--commit-limit` | Max commits to analyze per file (default: 500). || `--follow-renames` | Track file renames in git history. || `--no-claude-md` | Don't generate `CLAUDE.md`. |+| `--agents / --no-agents` | Generate or skip managed `AGENTS.md` for Codex. Persists the preference. |+| `--codex / --no-codex` | Generate or skip project-local Codex MCP/hooks setup. Interactive runs prompt when Codex CLI is installed and logged in; non-interactive runs require `--codex`. || `--yes / -y` | Skip confirmation prompts. |**Examples:**@@ -75,6 +77,7 @@ In workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (```bashrepowise init # interactiverepowise init --provider anthropic --yes # automated+repowise init --provider codex_cli --codex --yes # use authenticated Codex CLIrepowise init --index-only # free, no LLMrepowise init --dry-run # preview costrepowise init --test-run # quick test (10 files)@@ -82,6 +85,7 @@ repowise init --provider openai --model qwen3 --reasoning offrepowise init --provider openrouter --model openai/gpt-5 --reasoning minimalrepowise init -x vendor/ -x "*.gen.go" # exclude patternsrepowise init --include-submodules # include submodules+repowise init --no-codex --no-agents # skip Codex project filesrepowise init . # workspace moderepowise init . --index-only -x "node_modules/" # workspace, no LLM```@@ -99,13 +103,14 @@ Incrementally update wiki pages for files changed since the last sync.| `--provider` | Override LLM provider for this run || `--model` | Override model || `--since` | Git ref to diff from (overrides `state.json`) |-| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`, or `minimal` |+| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` || `--cascade-budget` | Max pages to regenerate (default: auto) || `--dry-run` | Show what would be updated without regenerating || `--workspace` | Update all stale repos in the workspace + cross-repo analysis || `--no-workspace` | Force single-repo mode (handy when running from a workspace root) || `--repo` | Update a specific workspace repo by alias || `--full` | Upgrade a fast (`--mode fast`) index to a full one — see below. Single-repo only. |+| `--agents / --no-agents` | Generate or skip managed `AGENTS.md` after update. Persists the preference. |**First-time indexing:** as of v0.8, `update --workspace` now runs full first-time indexing for workspace entries that have no `.repowise/` dir yet (previously skipped with `"not_indexed"`). The pipeline runs index-only — no LLM cost — and writes a state.json marker so `repowise update --repo <alias> --docs` later picks up doc generation cleanly.@@ -452,6 +457,8 @@ See [Auto-Sync](AUTO_SYNC.md) for all sync methods (hooks, file watcher, webhookStart the MCP server for AI editor integration.+If `PATH` is omitted, `repowise mcp` first walks upward from the current directory to the nearest initialized `.repowise` repository. This lets project-local Codex config use `args = ["mcp"]` with `cwd` set to the repo root.+**Options:**| Flag | Description |@@ -460,7 +467,7 @@ Start the MCP server for AI editor integration.| `--port` | Port for SSE transport (default: 7338) |```bash-repowise mcp --transport stdio # for Claude Code, Cursor, etc.+repowise mcp --transport stdio # for Claude Code, Codex, Cursor, etc.repowise mcp --transport sse --port 7338 # for web clients```@@ -480,6 +487,12 @@ repowise generate-claude-md --stdout---+### `AGENTS.md`++`repowise init --codex` generates managed `AGENTS.md` for Codex. `repowise update` refreshes it when `editor_files.agents_md` is enabled in config, or when `--agents` is passed. User content outside the Repowise managed markers is preserved.++---+### `repowise export [PATH]`Export wiki pages to files.@@ -560,4 +573,4 @@ repowise delete <repo-id> --force # delete a specific repo's index, no pr### `repowise augment`-Hook-driven context enrichment engine. Not meant to be called manually — invoked by Claude Code hooks installed during `repowise init`.+Hook-driven context enrichment engine. Not meant to be called manually — invoked by Claude Code and Codex hooks installed during `repowise init`. Claude Code uses it for search-result enrichment and stale-wiki checks; Codex uses it for `SessionStart`, `UserPromptSubmit`, and `PostToolUse` lifecycle guidance.diff --git a/docs/CODEX.md b/docs/CODEX.mdnew file mode 100644index 000000000..854f58e6c--- /dev/null+++ b/docs/CODEX.md@@ -0,0 +1,136 @@+# Codex Integration++Repowise supports Codex in three separate ways:++- Project setup for Codex MCP and lifecycle hooks.+- The `codex_cli` LLM provider for wiki generation through your authenticated Codex CLI subscription.+- A local Codex plugin with bundled MCP, hooks, and Repowise skills.++These features use project-local files. `repowise init --codex` writes under the repository, not to global `~/.codex/config.toml`.++## Prerequisites++Install and authenticate the Codex CLI:++```bash+npm install -g @openai/codex+codex login+codex login status+```++Repowise checks `codex --version` and `codex login status`. When both succeed, interactive `repowise init` offers to enable Codex project setup. Non-interactive runs require `--codex`; use `--no-codex` to skip the prompt.++## Project MCP Setup++Run from the repository root:++```bash+repowise init --codex+```++Repowise merges this server into `.codex/config.toml`:++```toml+[mcp_servers.repowise]+command = "repowise"+args = ["mcp"]+cwd = "/absolute/path/to/repo"+startup_timeout_sec = 20++[features]+hooks = true+```++The MCP server uses `repowise mcp` without a path. In no-path mode, Repowise walks upward from the current directory to the nearest initialized `.repowise` repository.++Smoke check:++```bash+codex mcp list+```++## Codex Hooks++Repowise writes hooks to `.codex/hooks.json`, not inline `[hooks]` tables. The default hooks call the import-isolated `repowise-augment` entry point for:++- `SessionStart` to add Repowise MCP workflow guidance.+- `UserPromptSubmit` to remind Codex when Repowise context is available.+- `PostToolUse` for `Bash` to detect git operations that make the wiki stale.+- `PostToolUse` for `apply_patch`, `Edit`, and `Write` to remind Codex after edits.++Claude Code has its own search-result enrichment hook path for `Grep` and `Glob`. Codex setup stays focused on lifecycle guidance and freshness checks instead of trying to reuse that Claude-specific search enrichment.++## `codex_cli` Provider++Use `codex_cli` when you want Repowise page generation to run through your Codex CLI subscription instead of an API key:++```bash+repowise init --provider codex_cli --codex --yes+```++You can also persist it:++```bash+REPOWISE_PROVIDER=codex_cli repowise update+```++The provider runs:++```bash+codex exec --ephemeral --sandbox read-only --json --cd /absolute/path/to/repo -+```++Repowise sends the prompt on stdin, parses Codex JSONL output, records token usage from `turn.completed.usage`, and treats `codex_cli/*` cost as `$0.00` because subscription billing happens outside Repowise API pricing. `--model` is passed to Codex only when you explicitly configure a model. `--reasoning minimal` maps to Codex `model_reasoning_effort="low"`; `low`, `medium`, `high`, and `xhigh` pass through when the selected Codex model advertises those levels. `off`/`none` is not supported by the Codex CLI provider.++Smoke check:++```bash+codex exec --ephemeral --sandbox read-only --json "Return exactly OK"+```++## Plugin And Skills++The repository includes a local Codex plugin:++```text+.agents/plugins/marketplace.json+plugins/codex/.codex-plugin/plugin.json+plugins/codex/.mcp.json+plugins/codex/hooks/hooks.json+plugins/codex/skills/*/SKILL.md+```++From the Repowise repository root, add the local marketplace to Codex, then install the Repowise plugin from the Codex plugin browser:++```bash+codex plugin marketplace add .+codex+/plugins+```++The plugin bundles Repowise MCP, lifecycle hooks, and Codex-neutral skills for exploration, pre-modification checks, architectural decisions, and dead-code cleanup. It does not add Claude-style slash commands. Plugin-bundled hooks are opt-in in current Codex releases; enable them with `[features] plugin_hooks = true` if you want hooks loaded from an installed plugin.++## AGENTS.md++`repowise init --codex` generates a managed `AGENTS.md` by default. `repowise update` refreshes it when `editor_files.agents_md` is enabled, or when `--agents` is passed. The Repowise section is bounded by managed markers and user content outside the markers is preserved.++Controls:++```bash+repowise init --no-agents+repowise init --agents+repowise update --no-agents+repowise update --agents+```++The generated section tells Codex when to use Repowise MCP tools for overview, search, context, risk, why/decision history, dependency tracing, diagrams, and dead-code cleanup.++## Official Codex Docs++- [Codex hooks](https://developers.openai.com/codex/hooks)+- [Codex MCP](https://developers.openai.com/codex/mcp)+- [Codex non-interactive mode](https://developers.openai.com/codex/noninteractive)+- [Codex plugins](https://developers.openai.com/codex/plugins)+- [Build Codex plugins](https://developers.openai.com/codex/plugins/build)+- [Codex skills](https://developers.openai.com/codex/skills)+- [AGENTS.md instructions](https://developers.openai.com/codex/guides/agents-md)diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.mdindex a7a31de0b..f34558150 100644--- a/docs/MCP_TOOLS.md+++ b/docs/MCP_TOOLS.md@@ -1,15 +1,15 @@# MCP Tools Reference-repowise exposes 9 tools via the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). These tools give AI coding assistants (Claude Code, Cursor, Cline, Windsurf) structured access to your codebase intelligence — dependency graph, git history, documentation, and architectural decisions.+repowise exposes 9 tools via the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). These tools give AI coding assistants (Claude Code, Codex, Cursor, Cline, Windsurf) structured access to your codebase intelligence — dependency graph, git history, documentation, and architectural decisions.**Start the MCP server:**```bash-repowise mcp --transport stdio # for Claude Code, Cursor, etc.+repowise mcp --transport stdio # for Claude Code, Codex, Cursor, etc.repowise mcp --transport sse --port 7338 # for web clients```-**Auto-setup for Claude Code:** `repowise init` automatically registers the MCP server and installs proactive hooks. No manual configuration needed.+**Auto-setup:** `repowise init` automatically registers the MCP server and installs proactive hooks for Claude Code. `repowise init --codex` writes project-local Codex MCP config and hooks.---@@ -287,9 +287,10 @@ The MCP server automatically enriches responses with cross-repo intelligence:## Proactive Hooks (Complementary)-In addition to the 9 MCP tools, `repowise init` installs Claude Code hooks that provide **passive, automatic** context enrichment:+In addition to the 9 MCP tools, `repowise init` installs AI-agent hooks (Claude Code and Codex) that provide **passive, automatic** context enrichment:-- **PreToolUse** — every `Grep`/`Glob` call is enriched with graph context (symbols, importers, dependencies, git signals) at ~24ms latency-- **PostToolUse** — after git commits, the agent is notified when the wiki is stale+- **Claude Code PostToolUse** — broad or zero-result `Grep`/`Glob` calls can be enriched with graph context, and git operations can trigger stale-wiki notices.+- **Codex SessionStart/UserPromptSubmit** — Codex receives concise Repowise MCP workflow guidance when a session or prompt starts.+- **Codex PostToolUse** — after edits or git operations, Codex receives a freshness reminder when indexed context may be stale.-Hooks fire automatically on every search. MCP tools are for deeper, on-demand investigation. See [Auto-Sync](AUTO_SYNC.md) for details.+Hooks are lightweight reminders. MCP tools are for deeper, on-demand investigation. See [Auto-Sync](AUTO_SYNC.md) and [Codex Integration](CODEX.md) for details.diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.mdindex a684227a8..d7f0535c6 100644--- a/docs/QUICKSTART.md+++ b/docs/QUICKSTART.md@@ -14,6 +14,14 @@ pip install "repowise[anthropic]"Or substitute `openai`, `gemini`, `litellm`, or `all` depending on your LLM provider.+For the Codex CLI subscription flow, no provider SDK or API key is required:++```bash+pip install repowise+npm install -g @openai/codex+codex login+```+**Requirements:** Python 3.11+, Git.## 2. Set Your API Key@@ -24,6 +32,12 @@ export ANTHROPIC_API_KEY="sk-ant-..."Or `OPENAI_API_KEY`, `GEMINI_API_KEY` — whichever provider you installed.+If you use Codex as the LLM provider, authenticate the Codex CLI instead:++```bash+codex login status+```+On Windows PowerShell:```powershell@@ -39,6 +53,12 @@ repowise initRepowise will walk you through an interactive setup — choose a provider, review the cost estimate, and confirm. It parses every file, builds a dependency graph, indexes git history, and generates wiki pages.+Codex users can force project-local MCP/hooks setup and use the Codex CLI provider in one command:++```bash+repowise init --codex --provider codex_cli --yes+```+A typical run on a ~500-file codebase takes 5-15 minutes.**Want to skip LLM costs?** Use `--index-only` to just parse and analyze without generating docs:@@ -67,13 +87,15 @@ repowise serveIf Node.js 20+ is installed, the web UI starts automatically. Otherwise, use Docker (see below).-**Connect to your AI editor (Claude Code, Cursor, Cline, Windsurf):**+**Connect to your AI editor (Claude Code, Codex, Cursor, Cline, Windsurf):**```bashrepowise mcp --transport stdio```-> **Automatic for Claude Code:** `repowise init` already registers the MCP server and installs PreToolUse/PostToolUse hooks in `~/.claude/settings.json`. Every `Grep`/`Glob` call is automatically enriched with graph context (importers, dependencies, symbols, git signals). After git commits, the agent is notified when the wiki is stale.+> **Automatic for Claude Code:** `repowise init` already registers the MCP server and installs PostToolUse hooks in `~/.claude/settings.json`. Broad or zero-result `Grep`/`Glob` searches can receive graph context, and git operations can notify the agent when the wiki is stale.++> **Automatic for Codex:** run `repowise init --codex` to write project-local `.codex/config.toml`, `.codex/hooks.json`, and managed `AGENTS.md`. See [Codex Integration](CODEX.md).## 5. Keep It in Syncdiff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex 54d7c9734..4caffe0a3 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -52,6 +52,14 @@ pip install "repowise[litellm]" # 100+ providers via LiteLLM (Together, Gropip install "repowise[all]" # All LLM providers + PostgreSQL support```+Codex CLI users can use the local subscription/auth flow without an API-key provider SDK:++```bash+pip install repowise+npm install -g @openai/codex+codex login+```+If you plan to use PostgreSQL instead of the default SQLite:```bash@@ -62,7 +70,7 @@ pip install "repowise[postgres]"- Python 3.11 or later- Git (repowise analyzes your repository's git history)-- An LLM API key (for documentation generation — not needed for analysis-only mode)+- An LLM API key or authenticated Codex CLI (for documentation generation — not needed for analysis-only mode)### Verify Installation@@ -95,6 +103,12 @@ export OPENAI_API_KEY="sk-..."export GEMINI_API_KEY="..."```+For Codex CLI auth:++```bash+codex login status+```+On Windows PowerShell:```powershell@@ -123,7 +137,7 @@ After init completes, you have several ways to access the generated documentatio```bashrepowise search "authentication" # Search from the terminalrepowise serve # Browse in a web UI at localhost:7337-repowise mcp # Connect to Claude Code, Cursor, etc.+repowise mcp # Connect to Claude Code, Codex, Cursor, etc.```### What gets created@@ -136,7 +150,9 @@ your-repo/│ ├── config.yaml # Saved configuration (provider, model, excludes)│ ├── .env # Saved API keys (gitignored)│ └── lancedb/ # Vector store for semantic search-└── CLAUDE.md # Auto-generated codebase context for AI editors+├── .claude/CLAUDE.md # Auto-generated Claude Code context+├── AGENTS.md # Auto-generated Codex context when enabled+└── .codex/ # Project-local Codex MCP/hooks config when --codex is used```---@@ -156,13 +172,13 @@ repowise init [PATH]1. **Ingestion** — walks every file, parses AST with tree-sitter, builds a dependency graph, indexes git history (churn, hotspots, ownership, bus factor)2. **Analysis** — detects dead code, extracts architectural decisions from inline markers, READMEs, and git history3. **Generation** — sends structured prompts to the LLM, generates file-level, module-level, and repo-level wiki pages, plus architecture diagrams-4. **Persistence** — stores everything in `.repowise/wiki.db`, builds search indexes, generates `CLAUDE.md`+4. **Persistence** — stores everything in `.repowise/wiki.db`, builds search indexes, generates managed editor instruction files**Options:**| Flag | Description ||------|-------------|-| `--provider` | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `ollama`, `litellm`, `mock`. Auto-detected from env vars if not set. |+| `--provider` | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `ollama`, `litellm`, `codex_cli`, `mock`. Auto-detected from env vars if not set. || `--model` | Model name override (e.g., `claude-sonnet-4-6`, `gpt-5.4-nano`) || `--embedder` | Embedder for semantic search: `gemini`, `openai`, `mock`. Auto-detected from env vars. || `--index-only` | Skip LLM generation entirely. Only parse, build graph, and index git. Free. |@@ -172,12 +188,14 @@ repowise init [PATH]| `--skip-infra` | Exclude infrastructure files (Dockerfiles, Makefiles, Terraform, shell scripts). || `--exclude / -x` | Gitignore-style exclusion patterns. Repeatable: `-x vendor/ -x "*.generated.*"` || `--concurrency` | Max concurrent LLM calls (default: 5). Higher = faster but more API pressure. |-| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`, or `minimal` (default: `auto`). |+| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` (default: `auto`). || `--resume` | Resume from the last checkpoint if a previous run was interrupted. || `--force` | Regenerate all pages even if they already exist. || `--commit-limit` | Max commits to analyze per file (default: 500, max: 5000). Saved to config. || `--follow-renames` | Track file renames in git history (slower but more accurate). || `--no-claude-md` | Don't generate `CLAUDE.md` at the end. |+| `--agents / --no-agents` | Generate or skip managed `AGENTS.md` for Codex. Persists the preference. |+| `--codex / --no-codex` | Generate or skip project-local Codex MCP config and hooks. || `--yes / -y` | Skip cost confirmation prompt (auto-confirms if cost > $2). |**Examples:**@@ -189,6 +207,9 @@ repowise init# Fully automatedrepowise init --provider anthropic --model claude-sonnet-4-6 --yes+# Use the authenticated local Codex CLI+repowise init --provider codex_cli --codex --yes+# Just index, no LLM costrepowise init --index-only@@ -223,7 +244,7 @@ Much faster and cheaper than a full `init` — only regenerates pages for change2. Re-parses changed files and rebuilds the dependency graph3. Determines affected pages (direct changes + dependents via cascade analysis)4. Regenerates only those pages-5. Updates `state.json` and `CLAUDE.md`+5. Updates `state.json` and configured editor instruction files**Options:**@@ -232,10 +253,11 @@ Much faster and cheaper than a full `init` — only regenerates pages for change| `--provider` | Override LLM provider for this run || `--model` | Override model || `--since` | Git ref to diff from (overrides `state.json`). Example: `--since v1.0.0` |-| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`, or `minimal`. |+| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`. || `--cascade-budget` | Max pages to regenerate per run (default: 30). Prevents runaway regeneration. || `--dry-run` | Show what would be updated without regenerating. || `--full` | Upgrade a fast (`--mode fast`) index to a full one (single-repo). See below. |+| `--agents / --no-agents` | Generate or skip managed `AGENTS.md` after update. Persists the preference. |**Upgrading a fast index to full (`--full`):**@@ -802,6 +824,16 @@ repowise mcp /path/to/your-repo --transport stdioClaude Code auto-detects the `.repowise/.mcp.json` generated by `repowise init`.+### Codex++Run:++```bash+repowise init --codex+```++This writes project-local `.codex/config.toml`, `.codex/hooks.json`, and managed `AGENTS.md`. The Codex config uses `repowise mcp` from the repository root, so it does not require editing global `~/.codex/config.toml`. See [Codex Integration](CODEX.md).+### Cursor / Windsurf / ClineAdd an MCP server entry pointing to:@@ -837,15 +869,15 @@ Once connected, your AI editor can:## Proactive Context Enrichment (Hooks)-Repowise automatically enriches AI agent tool calls with codebase graph context via Claude Code hooks. This is installed automatically during `repowise init` — no manual configuration required.+Repowise installs lightweight AI-agent hooks during editor setup. Claude Code hooks are installed during `repowise init`; Codex hooks are written by `repowise init --codex`.-Unlike MCP tools (which agents must explicitly call), hooks fire on every search automatically. Every `Grep` or `Glob` an agent runs gets graph context injected alongside the results, without the agent having to think about it.+Unlike MCP tools, hooks are passive reminders that fire from editor lifecycle events and tool-use events. They do not call an LLM or the network.### How it works-#### PreToolUse Hook — Grep/Glob enrichment+#### Claude Code PostToolUse Hook — Grep/Glob enrichment-Whenever an AI agent runs `Grep` or `Glob`, repowise intercepts the call and queries the local `wiki.db` for each matching file. The enrichment is appended to the tool result before the agent sees it:+When Claude Code runs a broad or zero-result `Grep` or `Glob`, repowise can query the local `wiki.db` and append focused context:| Field | What it tells the agent ||-------|------------------------|@@ -854,11 +886,11 @@ Whenever an AI agent runs `Grep` or `Glob`, repowise intercepts the call and que| **Depends on** | What this file imports (forward dependency) || **Git signals** | Hotspot status, bus factor, and owner |-Average latency is ~24ms — well under the 500ms target. No LLM calls, no network requests — pure local SQLite queries against `wiki.db`.+No LLM calls, no network requests — pure local SQLite queries against `wiki.db`.-#### PostToolUse Hook — Git commit detection+#### PostToolUse Hook — Git/edit freshness detection-After a successful `git commit`, `git merge`, `git rebase`, `git cherry-pick`, or `git pull`, repowise checks whether the wiki is stale by comparing `HEAD` against the last indexed commit in `.repowise/state.json`. If the wiki is out of date, the agent is notified:+After a successful `git commit`, `git merge`, `git rebase`, `git cherry-pick`, or `git pull`, repowise checks whether the wiki is stale by comparing `HEAD` against the last indexed commit in `.repowise/state.json`. Codex edit hooks also remind the agent that indexed context may be stale after edits.```Wiki is stale — run `repowise update` to refresh@@ -868,19 +900,20 @@ This ensures agents are never silently working from outdated documentation.### Configuration-Hooks are written to `~/.claude/settings.json` automatically during `repowise init`. The installed configuration:+Claude Code hooks are written to `~/.claude/settings.json` automatically during `repowise init`. Codex hooks are written to `.codex/hooks.json` by `repowise init --codex`.| Hook type | Matcher | Action ||-----------|---------|--------|-| `PreToolUse` | `Grep\|Glob` | Query `wiki.db` and prepend graph context to the result |-| `PostToolUse` | `Bash` | Check for git operations and notify if wiki is stale |+| Claude `PostToolUse` | `Bash\|Grep\|Glob` | Check git freshness and add search rescue/triage context |+| Codex `SessionStart` / `UserPromptSubmit` | lifecycle | Remind Codex to use Repowise MCP tools |+| Codex `PostToolUse` | `Bash`, `apply_patch\|Edit\|Write` | Check git/edit freshness |Both hooks call the `repowise-augment` console script — a standalone, import-isolated entry point that does not load the full `repowise` CLI. This keeps cold start under the 500ms target and ensures a broken environment (missing optional dep, corrupt DB, etc.) never crashes the agent: any failure exits 0 silently. The equivalent `repowise augment` Click subcommand still exists for manual debugging.### CLI command```bash-repowise-augment # Not meant to be called manually — invoked by Claude Code hooks+repowise-augment # Not meant to be called manually — invoked by AI-agent hooksrepowise augment # Equivalent Click subcommand, useful for manual debugging```diff --git a/examples/codex/README.md b/examples/codex/README.mdnew file mode 100644index 000000000..db0634bb1--- /dev/null+++ b/examples/codex/README.md@@ -0,0 +1,49 @@+# Codex Example++This example shows the expected Codex setup for an initialized Repowise repository.++## Setup++```bash+cd /path/to/your-repo+codex login status+repowise init --codex --index-only --yes # fast smoke: index only, no LLM wiki generation+repowise init --codex --provider codex_cli --yes+```++`repowise init --codex --index-only` is the quick setup smoke path. Drop `--index-only` when you want the full LLM-generated wiki. `repowise init --codex` writes project-local Codex files:++```text+.codex/config.toml+.codex/hooks.json+AGENTS.md+```++It does not write to global `~/.codex/config.toml`.++## Smoke Checks++```bash+codex mcp list+codex exec --ephemeral --sandbox read-only --json "Return exactly OK"+```++Inside Codex, start a new session in the repository and ask:++```text+Use Repowise to summarize the architecture and identify risky files before editing.+```++Codex should have Repowise MCP available, load the managed `AGENTS.md`, and receive hook guidance from `.codex/hooks.json`.++## Local Plugin++From the Repowise repository root:++```bash+codex plugin marketplace add .+codex+/plugins+```++Install the Repowise plugin from the local marketplace. The plugin bundles Repowise MCP, hooks, and Codex-neutral skills; it does not add slash commands. Plugin-bundled hooks require `[features] plugin_hooks = true` in current Codex releases.diff --git a/packages/cli/src/repowise/cli/augment_hook.py b/packages/cli/src/repowise/cli/augment_hook.pyindex ed1509381..eecef110d 100644--- a/packages/cli/src/repowise/cli/augment_hook.py+++ b/packages/cli/src/repowise/cli/augment_hook.py@@ -1,11 +1,11 @@-"""Standalone entry point for the Claude Code ``repowise-augment`` hook.+"""Standalone entry point for installed AI-agent ``repowise-augment`` hooks.Hooks must never crash the agent. The full ``repowise`` CLI imports theentire command surface — including ``init_cmd`` → ``cost_estimator`` →``core.ingestion.graph``, which pulls in ``networkx``, ``scipy``, and otherheavy dependencies. A single missing dep (or any other import-time failurein any subcommand) would otherwise propagate as a non-zero exit on every-``Grep``/``Glob``/``Bash`` tool call, spamming the agent transcript with+``Grep``/``Glob``/``Bash``/edit tool call, spamming the agent transcript withtracebacks.This entry point is wired as a separate ``[project.scripts]`` console script@@ -27,11 +27,20 @@ from __future__ import annotationsimport sys+def _parse_client_arg(argv: list[str]) -> str | None:+ for idx, arg in enumerate(argv):+ if arg == "--client" and idx + 1 < len(argv):+ return argv[idx + 1]+ if arg.startswith("--client="):+ return arg.split("=", 1)[1]+ return None++def main() -> None:try:from repowise.cli.commands.augment_cmd import _run_augment- _run_augment()+ _run_augment(client=_parse_client_arg(sys.argv[1:]))except (SystemExit, KeyboardInterrupt):raiseexcept BaseException:diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd.py b/packages/cli/src/repowise/cli/commands/augment_cmd.pyindex 0637c868d..a36f3f63e 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd.py@@ -1,7 +1,7 @@"""``repowise augment`` — hook-driven context enrichment for AI coding agents.-Reads a Claude Code hook payload from stdin (JSON) and writes targeted-enrichment back as a PostToolUse hook response.+Reads Claude Code or Codex hook payloads from stdin (JSON) and writes+targeted enrichment back as a hook response.Design philosophy: an enrichment hook is only valuable when it tells theagent something the raw tool output didn't. Anything else is noise the@@ -21,12 +21,18 @@ asymmetric, durable value:* Skip otherwise: a focused result set means the agent alreadyfound what it wanted; further graph context is just noise.+Codex SessionStart/UserPromptSubmit: adds short repowise MCP usage guidance.+PostToolUse → Bash* After a successful git commit/merge/rebase/cherry-pick/pull, ifthe wiki HEAD has drifted from .repowise/state.json's last synccommit AND no `repowise update` is in flight AND we haven'talready warned for this HEAD, emit a one-line stale-wiki notice.+ PostToolUse → edit tools+ * After file edits, emit a short reminder that the indexed context may+ be stale.+There is intentionally NO PreToolUse handling. Earlier versions enrichedevery Grep/Glob unconditionally with importers/dependencies/symbols; inpractice this added noise on the >70% of searches where the agent had@@ -43,8 +49,10 @@ Operational invariants:from __future__ import annotations+import contextlibimport jsonimport sys+from pathlib import Pathimport click@@ -57,10 +65,16 @@ _RESCUE_TOP_N = 2@click.command("augment")-def augment_command() -> None:+ "--client",+ type=click.Choice(["codex"]),+ default=None,+ help="Hook client marker. Codex lifecycle hooks pass this explicitly.",+)+def augment_command(client: str | None = None) -> None:"""Enrich AI agent tool calls with codebase graph context (hook mode)."""try:- _run_augment()+ _run_augment(client=client)except (SystemExit, KeyboardInterrupt):raiseexcept Exception:@@ -68,8 +82,8 @@ def augment_command() -> None:sys.exit(0)-def _run_augment() -> None:- """Main entry point — reads stdin, dispatches to the post handler."""+def _run_augment(*, client: str | None = None) -> None:+ """Main entry point — reads stdin, dispatches to hook handlers."""raw = sys.stdin.read()if not raw.strip():return@@ -80,25 +94,21 @@ def _run_augment() -> None:returnevent = payload.get("hook_event_name", "")- if event != "PostToolUse":- return-tool_name = payload.get("tool_name", "")tool_input = payload.get("tool_input", {})- tool_output = (- payload.get("tool_output")- or payload.get("tool_response")- or {}- )cwd = payload.get("cwd", "")- if tool_name == "Bash":- result = _handle_bash_post(tool_input, tool_output, cwd)- elif tool_name in ("Grep", "Glob"):- result = _handle_search_post(tool_name, tool_input, tool_output, cwd)- else:- result = None+ if client == "codex" and event in ("SessionStart", "UserPromptSubmit"):+ result = _handle_codex_context_event(event, cwd)+ if result:+ _emit_response(event, result)+ return+ if event != "PostToolUse":+ return++ tool_output = payload.get("tool_response", payload.get("tool_output", {}))+ result = _handle_post_tool_use(tool_name, tool_input, tool_output, cwd, client=client)if result:_emit_response(event, result)@@ -115,6 +125,29 @@ def _emit_response(event: str, context: str) -> None:sys.stdout.flush()+# ---------------------------------------------------------------------------+# Codex SessionStart/UserPromptSubmit — lightweight MCP guidance+# ---------------------------------------------------------------------------+++def _handle_codex_context_event(event: str, cwd: str) -> str | None:+ """Return short Codex developer context when repowise is initialized."""+ if event not in ("SessionStart", "UserPromptSubmit"):+ return None++ repo_path = _find_repo_root(Path(cwd))+ if repo_path is None:+ return None++ return (+ "[repowise] This repository has a local codebase wiki and graph index. "+ "Use the repowise MCP tools for architecture overview, semantic search, "+ "implementation context, risk/hotspot checks, decision history, and "+ "dead-code analysis. After meaningful edits or git operations, run "+ "`repowise update` when refreshed context is needed."+ )++# ---------------------------------------------------------------------------# PostToolUse — Grep / Glob: smart enrichment# ---------------------------------------------------------------------------@@ -136,8 +169,6 @@ def _handle_search_post(if _looks_like_path_lookup(pattern):return None- from pathlib import Path-repo_path = _find_repo_root(Path(cwd))if repo_path is None:return None@@ -173,13 +204,39 @@ def _looks_like_path_lookup(pattern: str) -> bool:if "/" in pattern or "\\" in pattern:return Truelower = pattern.lower().rstrip()- _EXTS = (- ".py", ".pyi", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",- ".go", ".rs", ".java", ".kt", ".kts", ".scala", ".rb", ".php",- ".cs", ".swift", ".cpp", ".cc", ".c", ".h", ".hpp", ".lua",- ".sql", ".yaml", ".yml", ".toml", ".json", ".md",+ exts = (+ ".py",+ ".pyi",+ ".ts",+ ".tsx",+ ".js",+ ".jsx",+ ".mjs",+ ".cjs",+ ".go",+ ".rs",+ ".java",+ ".kt",+ ".kts",+ ".scala",+ ".rb",+ ".php",+ ".cs",+ ".swift",+ ".cpp",+ ".cc",+ ".c",+ ".h",+ ".hpp",+ ".lua",+ ".sql",+ ".yaml",+ ".yml",+ ".toml",+ ".json",+ ".md",)- return lower.endswith(_EXTS)+ return lower.endswith(exts)def _extract_output_text(tool_output: object) -> str:@@ -219,7 +276,7 @@ def _count_search_results(output_text: str) -> int:return 0stripped = output_text.strip()# Common no-match sentinels emitted by Claude Code's Grep/Glob tool.- _ZERO_MARKERS = (+ zero_markers = ("no matches found","no files found","no files matched",@@ -227,7 +284,7 @@ def _count_search_results(output_text: str) -> int:"found 0 matches",)head = stripped.lower().splitlines()[0] if stripped else ""- if any(marker in head for marker in _ZERO_MARKERS):+ if any(marker in head for marker in zero_markers):return 0# Strip a "Found N files\n" / "Found N matches\n" header if present —# the count we want is the actual result lines, not the banner.@@ -238,7 +295,7 @@ def _count_search_results(output_text: str) -> int:async def _search_enrich(- repo_path: "object",+ repo_path: object,pattern: str,mode: str,result_count: int,@@ -246,13 +303,7 @@ async def _search_enrich("""Run the rescue or triage query against the wiki and format output."""import re- from pathlib import Path- from sqlalchemy import select-from repowise.core.persistence import (- FullTextSearch,- GraphNode,- WikiSymbol,create_engine,create_session_factory,get_session,@@ -279,13 +330,9 @@ async def _search_enrich(clean = re.sub(r"[^\w./_-]", "", pattern).strip("./")if mode == "rescue":- return await _rescue(- session, engine, repo_id, pattern, clean- )+ return await _rescue(session, engine, repo_id, pattern, clean)if mode == "triage":- return await _triage(- session, repo_id, pattern, clean, result_count- )+ return await _triage(session, repo_id, pattern, clean, result_count)return Nonefinally:await engine.dispose()@@ -316,7 +363,6 @@ async def _rescue(from repowise.core.persistence import (FullTextSearch,- GraphNode,WikiSymbol,)@@ -364,7 +410,13 @@ async def _rescue(page_type = getattr(r, "page_type", "") or ""if "::" in target:target = target.split("::")[0]- if target and page_type in ("file", "file_page", "module_page", "api_contract", "infra_page"):+ if target and page_type in (+ "file",+ "file_page",+ "module_page",+ "api_contract",+ "infra_page",+ ):return (f"[repowise] No literal match for `{pattern}`. "f"Wiki suggests `{target}` ({page_type})."@@ -388,7 +440,7 @@ async def _triage(Output is one line plus an enumerated list. Three lines max."""- from sqlalchemy import or_, select+ from sqlalchemy import selectfrom repowise.core.persistence import GraphNode, WikiSymbol@@ -432,14 +484,11 @@ async def _triage(if not pr_rows:return None- ranked = sorted(pr_rows, key=lambda r: (r[1] or 0.0), reverse=True)[:_TRIAGE_TOP_N]+ ranked = sorted(pr_rows, key=lambda r: r[1] or 0.0, reverse=True)[:_TRIAGE_TOP_N]if not ranked:return None- header = (- f"[repowise] {result_count}+ matches for `{pattern}`. "- f"Top files by graph centrality:"- )+ header = f"[repowise] {result_count}+ matches for `{pattern}`. Top files by graph centrality:"lines = [header] + [f" {row[0]}" for row in ranked]return "\n".join(lines)@@ -486,6 +535,46 @@ _GIT_COMMIT_PATTERNS = ("git pull",)+_EDIT_TOOL_NAMES = {"apply_patch", "Edit", "Write"}+++def _handle_post_tool_use(+ tool_name: str,+ tool_input: dict,+ tool_output: dict | str,+ cwd: str,+ *,+ client: str | None = None,+) -> str | None:+ """Dispatch PostToolUse events from Claude or Codex."""+ # The edit-tool freshness notice is a Codex-only lifecycle hook. Gate it on the+ # Codex client so a future widening of the Claude installer's PostToolUse matcher+ # can't start emitting Codex-flavored banners to existing Claude Code users.+ if client == "codex" and tool_name in _EDIT_TOOL_NAMES:+ return _handle_post_edit_use(cwd)+ if tool_name == "Bash":+ return _handle_bash_post(tool_input, tool_output, cwd)+ if tool_name in ("Grep", "Glob"):+ return _handle_search_post(tool_name, tool_input, tool_output, cwd)+ return None+++def _handle_post_edit_use(cwd: str) -> str | None:+ """After a Codex edit tool completes, flag that indexed context may be stale."""+ repo_path = _find_repo_root(Path(cwd))+ if repo_path is None:+ return None++ state_path = repo_path / ".repowise" / "state.json"+ if not state_path.exists():+ return None++ return (+ "[repowise] Files were edited after the last indexed snapshot. "+ "Run `repowise update` before relying on refreshed docs, graph context, "+ "risk checks, or dead-code results."+ )+def _handle_bash_post(tool_input: dict, tool_output: object, cwd: str) -> str | None:"""After a successful git commit, check if the wiki needs updating.@@ -506,25 +595,21 @@ def _handle_bash_post(tool_input: dict, tool_output: object, cwd: str) -> str |once per HEAD as before, so the user knows the wiki is genuinelyout of sync."""- if isinstance(tool_output, dict):- exit_code = tool_output.get("exit_code")- if exit_code is None:- stdout = tool_output.get("stdout", "")- if isinstance(stdout, str) and (- "error" in stdout.lower() or "fatal" in stdout.lower()- ):- return None- elif exit_code != 0:+ output = tool_output if isinstance(tool_output, dict) else {"stdout": str(tool_output)}+ exit_code = _extract_exit_code(output)+ if exit_code is None:+ stdout = output.get("stdout", "")+ stderr = output.get("stderr", "")+ combined = f"{stdout}\n{stderr}".lower()+ if "error" in combined or "fatal" in combined:return None+ elif exit_code != 0:+ return Nonecmd = tool_input.get("command", "")- if not isinstance(cmd, str) or not any(- p in cmd for p in _GIT_COMMIT_PATTERNS- ):+ if not isinstance(cmd, str) or not any(p in cmd for p in _GIT_COMMIT_PATTERNS):return None- from pathlib import Path-repo_path = _find_repo_root(Path(cwd))if repo_path is None:return None@@ -638,7 +723,7 @@ def _read_in_flight_marker(repo_path: "object") -> dict | None:return None-def _already_warned(repo_path: "object", head: str) -> bool:+def _already_warned(repo_path: object, head: str) -> bool:from pathlib import Pathmarker = Path(repo_path) / ".repowise" / ".augment-warned"@@ -650,14 +735,25 @@ def _already_warned(repo_path: "object", head: str) -> bool:return False-def _record_warning(repo_path: "object", head: str) -> None:+def _record_warning(repo_path: object, head: str) -> None:from pathlib import Pathmarker = Path(repo_path) / ".repowise" / ".augment-warned"- try:+ with contextlib.suppress(OSError):marker.write_text(head, encoding="utf-8")- except OSError:- pass+++def _extract_exit_code(tool_output: dict) -> int | None:+ """Extract a process exit code from known hook output shapes."""+ for key in ("exit_code", "exitCode", "status"):+ value = tool_output.get(key)+ if value is None:+ continue+ try:+ return int(value)+ except (TypeError, ValueError):+ return None+ return None# ---------------------------------------------------------------------------@@ -665,10 +761,8 @@ def _record_warning(repo_path: "object", head: str) -> None:# ----------------------------------------------------------------------------def _find_repo_root(cwd: "object") -> "object | None":- """Walk up from cwd to find a directory with ``.repowise/``."""- from pathlib import Path-+def _find_repo_root(cwd: Path) -> Path | None:+ """Walk up from cwd to find a directory with .repowise/."""current = Path(cwd).resolve()for _ in range(20):if (current / ".repowise").is_dir():diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex 431c3d361..d4c2098d2 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -19,7 +19,11 @@ from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElfrom rich.table import Tablefrom repowise.cli._setup import setup_logging_silence-from repowise.cli.editor_integrations.defaults import get_default_disabled_project_files+from repowise.cli.editor_integrations.defaults import (+ get_default_disabled_project_files,+ get_default_integration_overrides,+ get_default_project_file_overrides,+)from repowise.cli.editor_setup import (register_editor_clients,resolve_editor_setup_options,@@ -48,7 +52,7 @@ from repowise.cli.ui import (interactive_advanced_config,interactive_fast_mode_offer,interactive_mode_select,- interactive_provider_select,+ interactive_provider_config_select,load_dotenv,print_banner,print_index_only_intro,@@ -57,6 +61,7 @@ from repowise.cli.ui import (quick_repo_scan,should_offer_fast_mode,)+from repowise.core.reasoning import REASONING_MODESfrom ._interactive import offer_hook_installfrom .generation import cost_gate_declined, format_cost, run_repo_generation, select_coverage@@ -200,7 +205,7 @@ def _run_generation_phase(default=None,help=("LLM provider name (anthropic, openai, openrouter, gemini, "- "deepseek, ollama, litellm, mock)."+ "deepseek, ollama, litellm, codex_cli, mock)."),)@click.option("--model", default=None, help="Model identifier override.")@@ -224,9 +229,12 @@ def _run_generation_phase(@click.option("--concurrency", type=int, default=5, help="Max concurrent LLM calls.")@click.option("--reasoning",- type=click.Choice(["auto", "off", "minimal"]),+ type=click.Choice(REASONING_MODES),default=None,- help="Reasoning mode for supported providers: auto, off, or minimal. Default: auto.",+ help=(+ "Reasoning mode for supported providers: auto, off/none, minimal, "+ "low, medium, high, xhigh, or max. Default: auto."+ ),)@click.option("--test-run",@@ -277,6 +285,18 @@ def _run_generation_phase(default=False,help="Skip generating CLAUDE.md. Saves 'editor_files.claude_md: false' to config.",)+ "--agents/--no-agents",+ "agents_md",+ default=None,+ help="Generate managed AGENTS.md (default: config or enabled).",+)+ "--codex/--no-codex",+ "codex_setup",+ default=None,+ help="Generate or skip project-local Codex MCP config and hooks.",+)@click.option("--include-submodules",is_flag=True,@@ -344,6 +364,8 @@ def init_command(commit_limit: int | None,follow_renames: bool,no_claude_md: bool,+ agents_md: bool | None,+ codex_setup: bool | None,include_submodules: bool,init_all: bool,onboarding: bool,@@ -381,6 +403,8 @@ def init_command(commit_limit=commit_limit,follow_renames=follow_renames,no_claude_md=no_claude_md,+ agents_md=agents_md,+ codex_setup=codex_setup,include_submodules=include_submodules,provider_name=provider_name,model=model,@@ -448,8 +472,21 @@ def init_command():run_mode = "fast"elif mode == "advanced":- provider_name, model = interactive_provider_select(console, model, repo_path=repo_path)- adv = interactive_advanced_config(console, scan=scan_info, allow_fast=True)+ selection = interactive_provider_config_select(+ console,+ model,+ reasoning,+ repo_path=repo_path,+ )+ provider_name = selection.provider_name+ model = selection.model+ reasoning = selection.reasoning+ adv = interactive_advanced_config(+ console,+ scan=scan_info,+ allow_fast=True,+ prompt_reasoning=False,+ )commit_limit = adv["commit_limit"]follow_renames = adv["follow_renames"]skip_tests = adv["skip_tests"]@@ -465,7 +502,15 @@ def init_command(if run_mode == "fast":index_only = Trueelse:- provider_name, model = interactive_provider_select(console, model, repo_path=repo_path)+ selection = interactive_provider_config_select(+ console,+ model,+ reasoning,+ repo_path=repo_path,+ )+ provider_name = selection.provider_name+ model = selection.model+ reasoning = selection.reasoning# Full mode picked, but on a large repo offer the quick path too.# Default no here — the user explicitly asked for docs.if (@@ -481,6 +526,12 @@ def init_command(disabled_project_files=get_default_disabled_project_files(no_claude_md=no_claude_md,),+ project_file_overrides=get_default_project_file_overrides(+ agents_md=agents_md,+ ),+ integration_overrides=get_default_integration_overrides(+ codex_setup=codex_setup,+ ),prompt_for_project_files=is_interactive and not index_only,)@@ -538,12 +589,15 @@ def init_command()else:if not is_interactive and provider_name is None and sys.stdin.isatty():- from repowise.cli.ui import interactive_provider_select as _ips+ from repowise.cli.ui import interactive_provider_config_select as _ipcs- provider_name, model = _ips(console, model)+ selection = _ipcs(console, model, reasoning, repo_path=repo_path)+ provider_name = selection.provider_name+ model = selection.model+ reasoning = selection.reasoningprovider = resolve_provider(provider_name, model, repo_path)- # resolve_provider / interactive_provider_select may have just set+ # resolve_provider / interactive provider selection may have just set# the API key in os.environ. Re-resolve the embedder so the# display (and the embed path below) honors the key the user just# pasted, rather than the pre-prompt "mock" fallback.diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex ba47fb595..84c9a05c2 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -19,7 +19,11 @@ from typing import Anyfrom rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumnfrom repowise.cli._setup import setup_logging_silence-from repowise.cli.editor_integrations.defaults import get_default_disabled_project_files+from repowise.cli.editor_integrations.defaults import (+ get_default_disabled_project_files,+ get_default_integration_overrides,+ get_default_project_file_overrides,+)from repowise.cli.editor_setup import (register_editor_clients,resolve_editor_setup_options,@@ -46,7 +50,7 @@ from repowise.cli.ui import (interactive_advanced_config,interactive_mode_select,interactive_primary_select,- interactive_provider_select,+ interactive_provider_config_select,interactive_repo_select,load_dotenv,print_banner,@@ -138,6 +142,19 @@ def _run_workspace_generation()+def _workspace_generation_provider_for_repo(provider: Any, repo_path: Path) -> Any:+ """Return a generation provider bound to the current workspace repo.++ The Codex CLI provider shells out ``codex exec --cd <repo>``, so it must be+ re-resolved against each repo's path; all other providers are path-agnostic+ and returned unchanged.+ """++ if getattr(provider, "provider_name", None) != "codex_cli":+ return provider+ return resolve_provider("codex_cli", getattr(provider, "model_name", None), repo_path)++@dataclassclass _WorkspaceCtx:"""Run-wide settings shared across per-repo indexing in a workspace init."""@@ -253,10 +270,11 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCtrepo_docs_enabled = Falseelse:try:+ repo_provider = _workspace_generation_provider_for_repo(provider, repo.path)generated_pages = _run_workspace_generation(repo_path=repo.path,result=result,- provider=provider,+ provider=repo_provider,embedder_name_resolved=ctx.embedder_name_resolved,concurrency=ctx.concurrency,yes=ctx.yes,@@ -369,6 +387,8 @@ def _workspace_init(commit_limit: int | None,follow_renames: bool,no_claude_md: bool,+ agents_md: bool | None,+ codex_setup: bool | None,include_submodules: bool,# Generation params (passed through from init_command)provider_name: str | None = None,@@ -431,10 +451,13 @@ def _workspace_init(if mode == "index_only":index_only = Trueelif mode == "advanced":- provider_name, model = interactive_provider_select(- console, model, repo_path=primary_repo.path+ selection = interactive_provider_config_select(+ console, model, reasoning, repo_path=primary_repo.path)- adv = interactive_advanced_config(console)+ provider_name = selection.provider_name+ model = selection.model+ reasoning = selection.reasoning+ adv = interactive_advanced_config(console, prompt_reasoning=False)commit_limit = adv.get("commit_limit") or commit_limitfollow_renames = adv.get("follow_renames", follow_renames)skip_tests = adv.get("skip_tests", skip_tests)@@ -447,9 +470,12 @@ def _workspace_init(embedder_name_resolved = resolve_embedder(adv.get("embedder") or embedder_name)elif not index_only:# "full" mode- provider_name, model = interactive_provider_select(- console, model, repo_path=primary_repo.path+ selection = interactive_provider_config_select(+ console, model, reasoning, repo_path=primary_repo.path)+ provider_name = selection.provider_name+ model = selection.model+ reasoning = selection.reasoning# Resolve provider once (shared across all repos for generation)primary_cfg = load_config(primary_repo.path)@@ -458,7 +484,7 @@ def _workspace_init(if not index_only:try:provider = resolve_provider(provider_name, model, primary_repo.path)- # Re-resolve the embedder now that interactive_provider_select+ # Re-resolve the embedder now that interactive provider selection# may have set the provider's API key in os.environ. Without# this, full-mode runs would display "mock" forever because# the initial resolution happened before the key was available.@@ -510,6 +536,12 @@ def _workspace_init(disabled_project_files=get_default_disabled_project_files(no_claude_md=no_claude_md,),+ project_file_overrides=get_default_project_file_overrides(+ agents_md=agents_md,+ ),+ integration_overrides=get_default_integration_overrides(+ codex_setup=codex_setup,+ ),)ctx = _WorkspaceCtx(diff --git a/packages/cli/src/repowise/cli/commands/mcp_cmd.py b/packages/cli/src/repowise/cli/commands/mcp_cmd.pyindex 32ae65672..b73ae24fe 100644--- a/packages/cli/src/repowise/cli/commands/mcp_cmd.py+++ b/packages/cli/src/repowise/cli/commands/mcp_cmd.py@@ -2,9 +2,11 @@from __future__ import annotations+from pathlib import Path+import click-from repowise.cli.helpers import console, resolve_repo_path+from repowise.cli.helpers import console, find_repowise_repo_root, resolve_repo_pathfrom repowise.cli.ui import load_dotenv@@ -14,7 +16,7 @@ from repowise.cli.ui import load_dotenv"--transport",type=click.Choice(["stdio", "sse"]),default="stdio",- help="Transport protocol: stdio (Claude Code/Cursor) or sse (web clients).",+ help="Transport protocol: stdio (Claude Code/Codex/Cursor) or sse (web clients).",)@click.option("--port",@@ -26,7 +28,7 @@ def mcp_command(path: str | None, transport: str, port: int) -> None:"""Start the MCP server for editor integration.Exposes 16 tools for querying the repowise wiki via the MCP protocol.- Supports both stdio (for Claude Code, Cursor, Cline) and SSE transports.+ Supports both stdio (for Claude Code, Codex, Cursor, Cline) and SSE transports.Loads ``<repo>/.repowise/.env`` into the environment before starting sothat MCP tools (e.g. ``get_answer``) can resolve the configured LLM@@ -38,7 +40,10 @@ def mcp_command(path: str | None, transport: str, port: int) -> None:repowise mcp /path/to/repo # stdio, specific reporepowise mcp --transport sse # SSE on port 7338"""- repo_path = resolve_repo_path(path)+ if path is None:+ repo_path = find_repowise_repo_root(Path.cwd()) or resolve_repo_path(None)+ else:+ repo_path = resolve_repo_path(path)load_dotenv(repo_path)repowise_dir = repo_path / ".repowise"diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.pyindex 7bb795786..ed1b58ca9 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport time+from pathlib import Pathfrom typing import Anyimport click@@ -30,6 +31,7 @@ from repowise.cli.helpers import (save_state,write_update_pending,)+from repowise.core.reasoning import REASONING_MODES# ---------------------------------------------------------------------------# Mode resolution@@ -170,6 +172,7 @@ def _workspace_update(target: CommandTarget,*,dry_run: bool = False,+ agents_md: bool | None = None,) -> None:"""Update stale repos in a workspace.@@ -210,6 +213,13 @@ def _workspace_update(if stale_count == 0:console.print("[green]All repos are up to date.[/green]")+ if not dry_run:+ _refresh_workspace_editor_project_files(+ ws_root=ws_root,+ ws_config=ws_config,+ repo_filter=repo_alias,+ agents_md=agents_md,+ )returnif dry_run:@@ -259,6 +269,44 @@ def _workspace_update(f"[bold]Done:[/bold] {updated} updated, {skipped} skipped"+ (f", {errors} errors" if errors else ""))+ _refresh_workspace_editor_project_files(+ ws_root=ws_root,+ ws_config=ws_config,+ repo_filter=repo_alias,+ agents_md=agents_md,+ )+++def _refresh_workspace_editor_project_files(+ *,+ ws_root: Path,+ ws_config: Any,+ repo_filter: str | None,+ agents_md: bool | None,+) -> None:+ """Refresh workspace repo editor files for explicit per-run overrides."""++ if agents_md is None:+ return++ from repowise.cli.editor_integrations.defaults import get_default_project_file_overrides+ from repowise.cli.editor_setup import EditorSetupOptions, refresh_editor_project_files++ options = EditorSetupOptions(+ project_file_overrides=get_default_project_file_overrides(agents_md=agents_md),+ )+ for entry in ws_config.repos:+ if repo_filter and entry.alias != repo_filter:+ continue+ repo_path = (ws_root / entry.path).resolve()+ if not (repo_path / ".repowise").is_dir():+ continue+ try:+ refresh_editor_project_files(console, repo_path, options=options)+ except Exception as exc:+ console.print(+ f" [yellow]{entry.alias}: editor project-file refresh skipped: {exc}[/yellow]"+ )# ---------------------------------------------------------------------------@@ -737,9 +785,12 @@ def _run_full_health_rescore(@click.option("--concurrency", type=int, default=5, help="Max concurrent LLM calls.")@click.option("--reasoning",- type=click.Choice(["auto", "off", "minimal"]),+ type=click.Choice(REASONING_MODES),default=None,- help="Reasoning mode for supported providers: auto, off, or minimal.",+ help=(+ "Reasoning mode for supported providers: auto, off/none, minimal, "+ "low, medium, high, xhigh, or max."+ ),)@click.option("--cascade-budget",@@ -815,6 +866,12 @@ def _run_full_health_rescore("REPOWISE_NO_COST_TRACKING env var."),)+ "--agents/--no-agents",+ "agents_md",+ default=None,+ help="Generate managed AGENTS.md after update (default: config or enabled).",+)def update_command(path: str | None,provider_name: str | None,@@ -829,6 +886,7 @@ def update_command(index_only: bool = False,docs_flag: bool | None = None,full: bool = False,+ agents_md: bool | None = None,concurrency: int = 5,no_cost_tracking: bool = False,) -> None:@@ -855,7 +913,7 @@ def update_command("--full is single-repo only. Run it inside a specific repo ""(or pass --no-workspace / --repo <alias>).")- _workspace_update(target, dry_run=dry_run)+ _workspace_update(target, dry_run=dry_run, agents_md=agents_md)return# --- Single-repo path from here on. ---@@ -1448,9 +1506,21 @@ def update_command(# ---- Editor project files (best-effort) ----try:- from repowise.cli.editor_setup import refresh_editor_project_files-- refresh_editor_project_files(console, repo_path)+ from repowise.cli.editor_integrations.defaults import get_default_project_file_overrides+ from repowise.cli.editor_setup import EditorSetupOptions, refresh_editor_project_files++ editor_options = None+ if agents_md is not None:+ editor_options = EditorSetupOptions(+ project_file_overrides=get_default_project_file_overrides(+ agents_md=agents_md,+ ),+ )+ refresh_editor_project_files(+ console,+ repo_path,+ options=editor_options,+ )except Exception:pass # Editor project-file refresh must never fail the update commanddiff --git a/packages/cli/src/repowise/cli/cost_estimator/pricing.py b/packages/cli/src/repowise/cli/cost_estimator/pricing.pyindex 8c461d4a4..d26ffeed3 100644--- a/packages/cli/src/repowise/cli/cost_estimator/pricing.py+++ b/packages/cli/src/repowise/cli/cost_estimator/pricing.py@@ -35,6 +35,7 @@ _COST_TABLE_PREFIX: dict[str, tuple[float, float]] = {"gemini": (0.00025, 0.0015),"llama": (0.0, 0.0),"mock": (0.0, 0.0),+ "codex_cli/": (0.0, 0.0),}diff --git a/packages/cli/src/repowise/cli/editor_files.py b/packages/cli/src/repowise/cli/editor_files.pynew file mode 100644index 000000000..3a8ccd96e--- /dev/null+++ b/packages/cli/src/repowise/cli/editor_files.py@@ -0,0 +1,85 @@+"""Shared helpers for managed AI editor instruction files."""++from __future__ import annotations++from pathlib import Path++from repowise.cli.helpers import get_db_url_for_repo, load_config+from repowise.core.generation.editor_files import (+ AgentsMdGenerator,+ ClaudeMdGenerator,+ EditorFileData,+ EditorFileDataFetcher,+)+from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+)+from repowise.core.persistence.crud import get_repository_by_path+++def set_editor_file_enabled(repo_path: Path, key: str, enabled: bool) -> None:+ """Persist an editor_files.<key> preference in .repowise/config.yaml."""+ import yaml # type: ignore[import-untyped]++ cfg = load_config(repo_path)+ editor_files = dict(cfg.get("editor_files", {}))+ editor_files[key] = enabled+ cfg["editor_files"] = editor_files++ cfg_path = repo_path / ".repowise" / "config.yaml"+ cfg_path.parent.mkdir(parents=True, exist_ok=True)+ cfg_path.write_text(+ yaml.dump(cfg, default_flow_style=False, sort_keys=False),+ encoding="utf-8",+ )+++def should_generate_editor_file(+ repo_path: Path,+ key: str,+ *,+ default: bool = True,+ override: bool | None = None,+) -> bool:+ """Resolve and persist an optional per-command editor file override."""+ if override is not None:+ set_editor_file_enabled(repo_path, key, override)+ return override+ cfg = load_config(repo_path)+ return bool(cfg.get("editor_files", {}).get(key, default))+++async def fetch_editor_file_data(repo_path: Path) -> EditorFileData | None:+ """Fetch indexed repo data for editor-file generation."""+ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)+ try:+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return None+ fetcher = EditorFileDataFetcher(session, repo.id, repo_path)+ return await fetcher.fetch()+ finally:+ await engine.dispose()+++async def write_claude_md(repo_path: Path) -> Path | None:+ """Fetch editor data and write .claude/CLAUDE.md."""+ data = await fetch_editor_file_data(repo_path)+ if data is None:+ return None+ return ClaudeMdGenerator().write(repo_path, data)+++async def write_agents_md(repo_path: Path) -> Path | None:+ """Fetch editor data and write AGENTS.md."""+ data = await fetch_editor_file_data(repo_path)+ if data is None:+ return None+ return AgentsMdGenerator().write(repo_path, data)diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude.py b/packages/cli/src/repowise/cli/editor_integrations/claude.pyindex ced15ffc0..42c6cda61 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude.py@@ -62,9 +62,7 @@ class ClaudeCodeSetup:hooks = install_claude_code_hooks()if hooks:- console_obj.print(- " [green]✓[/green] Claude Code hooks registered (PreToolUse + PostToolUse)"- )+ console_obj.print(" [green]✓[/green] Claude Code hooks registered (PostToolUse)")def refresh_project_files(self,diff --git a/packages/cli/src/repowise/cli/editor_integrations/codex.py b/packages/cli/src/repowise/cli/editor_integrations/codex.pynew file mode 100644index 000000000..a6310d508--- /dev/null+++ b/packages/cli/src/repowise/cli/editor_integrations/codex.py@@ -0,0 +1,147 @@+"""Codex setup integration."""++from __future__ import annotations++from pathlib import Path+from typing import Any++import click++from repowise.cli.editor_setup import EditorSetupOptions+++class CodexSetup:+ """Project-local Codex setup integration."""++ integration_id = "codex"+ project_file_id = "agents_md"++ def configure_options(+ self,+ console_obj: Any,+ options: EditorSetupOptions,+ ) -> EditorSetupOptions:+ if self.integration_id in options.integration_overrides:+ return options+ if not options.prompt_for_project_files:+ return options++ from repowise.cli.mcp_config import is_codex_cli_installed, is_codex_logged_in++ if not (is_codex_cli_installed() and is_codex_logged_in()):+ return options++ console_obj.print()+ console_obj.print("[bold]Codex:[/bold] Generate project-local .codex config and hooks?")+ enabled = click.confirm(+ " Write .codex/config.toml and .codex/hooks.json?",+ default=False,+ )+ if not enabled:+ console_obj.print(+ " [dim]Skipped. Run 'repowise init --codex' later to set up Codex.[/dim]"+ )+ return options.with_integration_override(self.integration_id, enabled)++ def write_project_files(+ self,+ console_obj: Any,+ repo_path: Path,+ options: EditorSetupOptions,+ ) -> None:+ from repowise.cli.mcp_config import (+ is_codex_cli_installed,+ is_codex_logged_in,+ save_codex_hooks_config,+ save_codex_mcp_config,+ )++ setup_override = options.integration_overrides.get(self.integration_id)+ agents_override = options.project_file_overrides.get(self.project_file_id)+ agents_override_present = self.project_file_id in options.project_file_overrides+ if setup_override is False:+ if agents_override_present:+ maybe_generate_agents_md(console_obj, repo_path, agents_md=agents_override)+ return+ if setup_override is None:+ if agents_override_present:+ maybe_generate_agents_md(console_obj, repo_path, agents_md=agents_override)+ return++ installed = is_codex_cli_installed()+ logged_in = is_codex_logged_in() if installed else False++ config_path = save_codex_mcp_config(repo_path)+ console_obj.print(f" [green]✓[/green] Codex MCP registered ({config_path})")+ hooks_path = save_codex_hooks_config(repo_path)+ console_obj.print(f" [green]✓[/green] Codex hooks registered ({hooks_path})")+ maybe_generate_agents_md(+ console_obj,+ repo_path,+ agents_md=True if agents_override is None else agents_override,+ )++ if setup_override is True and not installed:+ console_obj.print(+ " [yellow]Codex CLI was not detected; install with "+ "'npm install -g @openai/codex' before using this config.[/yellow]"+ )+ elif setup_override is True and not logged_in:+ console_obj.print(+ " [yellow]Codex CLI is not logged in; run 'codex login' before using this config.[/yellow]"+ )++ def register_client(self, console_obj: Any, repo_path: Path) -> None:+ """Codex setup is project-local and does not require global registration."""++ return None++ def refresh_project_files(+ self,+ console_obj: Any,+ repo_path: Path,+ options: EditorSetupOptions,+ ) -> None:+ if self.project_file_id in options.disabled_project_files:+ return+ maybe_generate_agents_md(+ console_obj,+ repo_path,+ agents_md=options.project_file_overrides.get(self.project_file_id),+ default=False,+ )+++def maybe_generate_agents_md(+ console_obj: Any,+ repo_path: Path,+ *,+ agents_md: bool | None = None,+ default: bool = True,+) -> None:+ """Generate AGENTS.md if enabled in config and not opted out."""++ from repowise.cli.editor_files import should_generate_editor_file+ from repowise.cli.helpers import run_async++ if not should_generate_editor_file(+ repo_path,+ "agents_md",+ default=default,+ override=agents_md,+ ):+ return+ try:+ with console_obj.status(" Generating AGENTS.md...", spinner="dots"):+ run_async(_write_agents_md_async(repo_path))+ console_obj.print(" [green]✓[/green] AGENTS.md updated")+ except Exception as exc:+ console_obj.print(f" [yellow]AGENTS.md skipped: {exc}[/yellow]")+++async def _write_agents_md_async(repo_path: Path) -> None:+ """Fetch indexed repo data and write AGENTS.md."""++ from repowise.cli.editor_files import write_agents_md++ await write_agents_md(repo_path)diff --git a/packages/cli/src/repowise/cli/editor_integrations/defaults.py b/packages/cli/src/repowise/cli/editor_integrations/defaults.pyindex e162baded..d75f0ecee 100644--- a/packages/cli/src/repowise/cli/editor_integrations/defaults.py+++ b/packages/cli/src/repowise/cli/editor_integrations/defaults.py@@ -5,12 +5,13 @@ from __future__ import annotationsfrom repowise.cli.editor_setup import EditorSetupIntegrationfrom .claude import ClaudeCodeSetup+from .codex import CodexSetupdef get_default_editor_integrations() -> tuple[EditorSetupIntegration, ...]:"""Return the editor integrations enabled by default today."""- return (ClaudeCodeSetup(),)+ return (ClaudeCodeSetup(), CodexSetup())def get_default_disabled_project_files(*, no_claude_md: bool = False) -> tuple[str, ...]:@@ -20,3 +21,27 @@ def get_default_disabled_project_files(*, no_claude_md: bool = False) -> tuple[sif no_claude_md:disabled.append(ClaudeCodeSetup.project_file_id)return tuple(disabled)+++def get_default_project_file_overrides(+ *,+ agents_md: bool | None = None,+) -> dict[str, bool]:+ """Map legacy/default CLI editor-file flags to integration-owned file ids."""++ overrides: dict[str, bool] = {}+ if agents_md is not None:+ overrides[CodexSetup.project_file_id] = agents_md+ return overrides+++def get_default_integration_overrides(+ *,+ codex_setup: bool | None = None,+) -> dict[str, bool]:+ """Map CLI setup toggles to integration ids."""++ overrides: dict[str, bool] = {}+ if codex_setup is not None:+ overrides[CodexSetup.integration_id] = codex_setup+ return overridesdiff --git a/packages/cli/src/repowise/cli/editor_setup.py b/packages/cli/src/repowise/cli/editor_setup.pyindex f1c70f094..0fd15c1ec 100644--- a/packages/cli/src/repowise/cli/editor_setup.py+++ b/packages/cli/src/repowise/cli/editor_setup.py@@ -9,7 +9,7 @@ live in ``repowise.cli.editor_integrations``.from __future__ import annotationsimport os-from collections.abc import Iterable+from collections.abc import Iterable, Mappingfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Protocol@@ -37,6 +37,8 @@ class EditorSetupOptions:disabled_project_files: frozenset[str] = field(default_factory=frozenset)prompt_for_project_files: bool = False+ project_file_overrides: dict[str, bool] = field(default_factory=dict)+ integration_overrides: dict[str, bool] = field(default_factory=dict)def with_disabled_project_file(self, project_file_id: str) -> EditorSetupOptions:"""Return options with one managed project file disabled."""@@ -44,6 +46,36 @@ class EditorSetupOptions:return EditorSetupOptions(disabled_project_files=self.disabled_project_files | {project_file_id},prompt_for_project_files=self.prompt_for_project_files,+ project_file_overrides=dict(self.project_file_overrides),+ integration_overrides=dict(self.integration_overrides),+ )++ def with_project_file_override(+ self,+ project_file_id: str,+ enabled: bool,+ ) -> EditorSetupOptions:+ """Return options with one managed project file explicitly enabled or disabled."""++ return EditorSetupOptions(+ disabled_project_files=self.disabled_project_files,+ prompt_for_project_files=self.prompt_for_project_files,+ project_file_overrides={**self.project_file_overrides, project_file_id: enabled},+ integration_overrides=dict(self.integration_overrides),+ )++ def with_integration_override(+ self,+ integration_id: str,+ enabled: bool,+ ) -> EditorSetupOptions:+ """Return options with one editor integration explicitly enabled or disabled."""++ return EditorSetupOptions(+ disabled_project_files=self.disabled_project_files,+ prompt_for_project_files=self.prompt_for_project_files,+ project_file_overrides=dict(self.project_file_overrides),+ integration_overrides={**self.integration_overrides, integration_id: enabled},)@@ -96,6 +128,8 @@ def resolve_editor_setup_options(*,disabled_project_files: Iterable[str] | None = None,prompt_for_project_files: bool = False,+ project_file_overrides: Mapping[str, bool] | None = None,+ integration_overrides: Mapping[str, bool] | None = None,integrations: tuple[EditorSetupIntegration, ...] | None = None,) -> EditorSetupOptions:"""Build setup options, allowing integrations to own their prompts."""@@ -103,6 +137,8 @@ def resolve_editor_setup_options(options = EditorSetupOptions(disabled_project_files=frozenset(disabled_project_files or ()),prompt_for_project_files=prompt_for_project_files,+ project_file_overrides=dict(project_file_overrides or {}),+ integration_overrides=dict(integration_overrides or {}),)for integration in _resolve_integrations(integrations):options = integration.configure_options(console_obj, options)diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex 973188b79..e99ef8ac5 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -91,6 +91,26 @@ def resolve_repo_path(path: str | None) -> Path:return Path(path).resolve()+def find_repowise_repo_root(start: Path | None = None) -> Path | None:+ """Walk upward from *start* looking for a repo with ``.repowise``."""++ current = (start or Path.cwd()).resolve()+ home = Path.home().resolve()+ for candidate in (current, *current.parents):+ if _same_path(candidate, home):+ return None+ if (candidate / REPOWISE_DIR).is_dir():+ return candidate+ return None+++def _same_path(left: Path, right: Path) -> bool:+ try:+ return left.samefile(right)+ except OSError:+ return left == right++def find_workspace_root(start: Path | None = None) -> Path | None:"""Walk up from *start* (default: cwd) looking for ``.repowise-workspace.yaml``.@@ -554,6 +574,14 @@ def config_fingerprint(repo_path: Path) -> str:# ---------------------------------------------------------------------------+def _is_codex_cli_available() -> bool:+ """Check if the Codex CLI binary is available."""++ import shutil++ return shutil.which("codex") is not None++def resolve_provider(provider_name: str | None,model: str | None,@@ -617,6 +645,8 @@ def resolve_provider(base_url = _resolve_base_url(provider_name)if base_url:kwargs["base_url"] = base_url+ if provider_name == "codex_cli" and repo_path is not None:+ kwargs["repo_path"] = repo_path# Pass API key from environment if availableif provider_name == "anthropic" and os.environ.get("ANTHROPIC_API_KEY"):@@ -695,7 +725,10 @@ def resolve_provider(raise click.ClickException("No provider configured. Use --provider, set REPOWISE_PROVIDER, "- "or set ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY / OLLAMA_BASE_URL / GEMINI_API_KEY / GOOGLE_API_KEY / DEEPSEEK_API_KEY / LITELLM_API_KEY."+ "or set ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY / "+ "OLLAMA_BASE_URL / GEMINI_API_KEY / GOOGLE_API_KEY / DEEPSEEK_API_KEY / "+ "LITELLM_API_KEY. Use REPOWISE_PROVIDER=codex_cli to use an authenticated "+ "Codex CLI subscription.")@@ -737,6 +770,14 @@ def validate_provider_config(provider_name: str | None = None) -> list[str]:}if provider_name:+ if provider_name == "codex_cli":+ if not _is_codex_cli_available():+ warnings.append(+ "Provider 'codex_cli' requires the Codex CLI. "+ "Install it with: npm install -g @openai/codex"+ )+ return warnings+# Validate specific providerif provider_name not in provider_env_vars:warnings.append(f"Unknown provider '{provider_name}' - cannot validate configuration")diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex 1c7bea599..5392cf306 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -36,8 +36,8 @@ def cli(ctx: click.Context) -> None:# Self-heal: migrate any legacy `repowise augment` Claude Code hooks# to the import-isolated `repowise-augment` console script. Cheap,# silent, idempotent — only writes when there is something to change.- # Skipped when invoked as the augment subcommand itself (hot path on- # every Grep/Glob/Bash) — `augment_hook.main` handles that case.+ # Skipped when invoked as the augment subcommand itself (hook hot path) —+ # `augment_hook.main` handles that case.if ctx.invoked_subcommand != "augment":try:from repowise.cli.editor_integrations.claude_config import migrate_claude_code_hooks@@ -72,4 +72,3 @@ register_command(reindex_command)register_command(workspace_group)cli_registry.apply(cli)-diff --git a/packages/cli/src/repowise/cli/mcp_config.py b/packages/cli/src/repowise/cli/mcp_config.pyindex 8da2ca377..fe42e575b 100644--- a/packages/cli/src/repowise/cli/mcp_config.py+++ b/packages/cli/src/repowise/cli/mcp_config.py@@ -3,6 +3,10 @@from __future__ import annotationsimport json+import re+import shutil+import subprocess+import tomllibfrom pathlib import Pathimport click@@ -25,6 +29,113 @@ def generate_mcp_config(repo_path: Path) -> dict:}+def resolve_codex_executable() -> str | None:+ """Return the executable path used to launch Codex, or None if unavailable."""++ return shutil.which("codex")+++def is_codex_cli_installed() -> bool:+ """Return True when the Codex CLI is on PATH and runnable."""++ codex_cmd = resolve_codex_executable()+ if not codex_cmd:+ return False+ try:+ result = subprocess.run(+ [codex_cmd, "--version"],+ capture_output=True,+ text=True,+ timeout=5,+ )+ except (OSError, subprocess.TimeoutExpired):+ return False+ return result.returncode == 0+++def is_codex_logged_in() -> bool:+ """Return True when the local Codex CLI reports an authenticated session."""++ codex_cmd = resolve_codex_executable()+ if not codex_cmd or not is_codex_cli_installed():+ return False+ try:+ result = subprocess.run(+ [codex_cmd, "login", "status"],+ capture_output=True,+ text=True,+ timeout=10,+ )+ except (OSError, subprocess.TimeoutExpired):+ return False+ return result.returncode == 0+++def generate_codex_mcp_server_config(repo_path: Path) -> dict[str, object]:+ """Generate the Codex config.toml server table for repowise."""++ return {+ "command": "repowise",+ "args": ["mcp"],+ "cwd": str(repo_path.resolve()),+ "startup_timeout_sec": 20,+ }+++def generate_codex_hooks_config() -> dict[str, object]:+ """Generate project-local Codex hooks for repowise context and freshness checks."""++ context_hook = {+ "type": "command",+ "command": "repowise-augment --client codex",+ "timeout": 30,+ "statusMessage": "Loading repowise context...",+ }+ freshness_hook = {+ "type": "command",+ "command": "repowise-augment --client codex",+ "timeout": 30,+ "statusMessage": "Checking repowise freshness...",+ }+ return {+ "hooks": {+ "SessionStart": [{"matcher": "startup|resume|clear", "hooks": [context_hook]}],+ "UserPromptSubmit": [{"hooks": [context_hook]}],+ "PostToolUse": [+ {"matcher": "Bash", "hooks": [freshness_hook]},+ {"matcher": "apply_patch|Edit|Write", "hooks": [freshness_hook]},+ ],+ }+ }+++def _toml_value(value: object) -> str:+ if isinstance(value, bool):+ return "true" if value else "false"+ if isinstance(value, str):+ return json.dumps(value)+ if isinstance(value, int):+ return str(value)+ if isinstance(value, list) and all(isinstance(item, str) for item in value):+ return f"[{', '.join(json.dumps(item) for item in value)}]"+ raise TypeError(f"Unsupported TOML value: {value!r}")+++def _codex_mcp_server_toml(repo_path: Path) -> str:+ lines = ["[mcp_servers.repowise]"]+ lines.extend(+ f"{key} = {_toml_value(value)}"+ for key, value in generate_codex_mcp_server_config(repo_path).items()+ )+ return "\n".join(lines)+++def _toml_table_block(table_name: str, values: dict[str, object]) -> str:+ lines = [f"[{table_name}]"]+ lines.extend(f"{key} = {_toml_value(value)}" for key, value in values.items())+ return "\n".join(lines)++def save_mcp_config(repo_path: Path) -> Path:"""Save MCP config to .repowise/mcp.json and return the path."""repowise_dir = repo_path / ".repowise"@@ -56,6 +167,141 @@ def _merge_server_entries(servers: dict, new_entry: dict) -> dict:return servers+def _ensure_valid_toml(merged_text: str, config_path: Path) -> None:+ """Abort before writing if the regex merge produced invalid TOML.++ The merge validates the *existing* file, but the table-rewrite regex only+ matches the bare ``[mcp_servers.repowise]`` / ``[features]`` spellings. A user+ who expressed the same key differently (quoted ``["features"]`` or inline under+ a parent table) would slip past the regex, and appending our block would yield a+ duplicate-key file. Re-parsing the merged result turns every such case into a+ clean abort with the original file untouched.+ """++ try:+ tomllib.loads(merged_text)+ except tomllib.TOMLDecodeError as exc:+ raise click.ClickException(+ f"Cannot update {config_path}: merging the repowise entry would produce "+ "invalid TOML (an existing entry may use a different key spelling). "+ "No changes were written."+ ) from exc+++def enable_codex_hooks_feature(repo_path: Path) -> Path:+ """Enable Codex hooks in project-local .codex/config.toml."""++ config_path = repo_path / ".codex" / "config.toml"++ try:+ if config_path.exists():+ existing_text = config_path.read_text(encoding="utf-8")+ doc = tomllib.loads(existing_text)+ else:+ config_path.parent.mkdir(parents=True, exist_ok=True)+ existing_text = ""+ doc = {}+ except tomllib.TOMLDecodeError as exc:+ raise click.ClickException(+ f"Cannot update {config_path}: existing file is not valid TOML. "+ "Fix or remove it and retry; no changes were written."+ ) from exc++ existing_features = doc.get("features", {})+ if not isinstance(existing_features, dict):+ raise click.ClickException(+ f"Cannot update {config_path}: [features] must be a TOML table. "+ "Fix or remove it and retry; no changes were written."+ )++ features = dict(existing_features)+ features["hooks"] = True+ feature_block = _toml_table_block("features", features)+ table_re = re.compile(r"(?ms)^\s*\[features\]\s*\n.*?(?=^\s*\[|\Z)")+ merged_text = table_re.sub("", existing_text).rstrip()+ merged_text = f"{merged_text}\n\n{feature_block}\n" if merged_text else f"{feature_block}\n"+ _ensure_valid_toml(merged_text, config_path)+ config_path.write_text(merged_text, encoding="utf-8")+ return config_path+++def save_codex_mcp_config(repo_path: Path) -> Path:+ """Merge the repowise MCP server into project-local .codex/config.toml."""++ config_path = repo_path / ".codex" / "config.toml"+ server_block = _codex_mcp_server_toml(repo_path)++ try:+ if config_path.exists():+ existing_text = config_path.read_text(encoding="utf-8")+ doc = tomllib.loads(existing_text)+ else:+ config_path.parent.mkdir(parents=True, exist_ok=True)+ config_path.write_text(f"{server_block}\n", encoding="utf-8")+ return config_path+ except tomllib.TOMLDecodeError as exc:+ raise click.ClickException(+ f"Cannot update {config_path}: existing file is not valid TOML. "+ "Fix or remove it and retry; no changes were written."+ ) from exc++ servers = doc.get("mcp_servers")+ if servers is not None and not isinstance(servers, dict):+ raise click.ClickException(+ f"Cannot update {config_path}: [mcp_servers] must be a TOML table. "+ "Fix or remove it and retry; no changes were written."+ )+ if isinstance(servers, dict):+ repowise = servers.get("repowise")+ if repowise is not None and not isinstance(repowise, dict):+ raise click.ClickException(+ f"Cannot update {config_path}: [mcp_servers.repowise] must be a TOML table. "+ "Fix or remove it and retry; no changes were written."+ )++ table_re = re.compile(r"(?ms)^\s*\[mcp_servers\.repowise\]\s*\n.*?(?=^\s*\[|\Z)")+ merged_text = table_re.sub("", existing_text).rstrip()+ merged_text = f"{merged_text}\n\n{server_block}\n" if merged_text else f"{server_block}\n"+ _ensure_valid_toml(merged_text, config_path)+ config_path.write_text(merged_text, encoding="utf-8")+ return config_path+++def save_codex_hooks_config(repo_path: Path) -> Path:+ """Merge repowise hooks into project-local .codex/hooks.json."""++ hooks_path = repo_path / ".codex" / "hooks.json"+ new_config = generate_codex_hooks_config()++ if hooks_path.exists():+ existing = load_existing_config(hooks_path)+ else:+ hooks_path.parent.mkdir(parents=True, exist_ok=True)+ existing = {}++ hooks = existing.setdefault("hooks", {})+ if not isinstance(hooks, dict):+ raise click.ClickException(+ f"Cannot update {hooks_path}: hooks must contain a JSON object. "+ "Fix or remove it and retry; no changes were written."+ )++ for event, entries in new_config["hooks"].items():+ event_hooks = hooks.setdefault(event, [])+ if not isinstance(event_hooks, list):+ raise click.ClickException(+ f"Cannot update {hooks_path}: hooks.{event} must contain a JSON array. "+ "Fix or remove it and retry; no changes were written."+ )+ for entry in entries:+ if not _has_repowise_hook_for_matcher(event_hooks, entry.get("matcher")):+ event_hooks.append(entry)++ hooks_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")+ enable_codex_hooks_feature(repo_path)+ return hooks_path++def save_root_mcp_config(repo_path: Path) -> Path:"""Write .mcp.json at repo root for MCP clients that support discovery.@@ -125,6 +371,23 @@ def load_existing_config(config_path: Path) -> dict:return existing+def _is_repowise_hook(hook: dict) -> bool:+ cmd = hook.get("command", "")+ return "repowise-augment" in cmd or "repowise augment" in cmd+++def _has_repowise_hook_for_matcher(hook_list: list, matcher: object) -> bool:+ """Check if a repowise augment hook is registered for a matcher group."""++ for entry in hook_list:+ if entry.get("matcher") != matcher:+ continue+ for hook in entry.get("hooks", []):+ if _is_repowise_hook(hook):+ return True+ return False++def format_setup_instructions(repo_path: Path) -> str:"""Return human-readable setup instructions for MCP clients."""config = generate_mcp_config(repo_path)diff --git a/packages/cli/src/repowise/cli/ui/__init__.py b/packages/cli/src/repowise/cli/ui/__init__.pyindex 919fcda9a..7a37e3fad 100644--- a/packages/cli/src/repowise/cli/ui/__init__.py+++ b/packages/cli/src/repowise/cli/ui/__init__.py@@ -28,7 +28,11 @@ from repowise.cli.ui.mode_selection import (should_offer_fast_mode,)from repowise.cli.ui.progress import MaybeCountColumn, RichProgressCallback-from repowise.cli.ui.provider_selection import interactive_provider_select+from repowise.cli.ui.provider_selection import (+ ProviderSelection,+ interactive_provider_config_select,+ interactive_provider_select,+)from repowise.cli.ui.repo_scanner import (RepoScanInfo,print_scan_summary,@@ -53,6 +57,7 @@ __all__ = ["OK","WARN","MaybeCountColumn",+ "ProviderSelection","RepoScanInfo","RichProgressCallback","build_analysis_summary_panel",@@ -63,6 +68,7 @@ __all__ = ["interactive_fast_mode_offer","interactive_mode_select","interactive_primary_select",+ "interactive_provider_config_select","interactive_provider_select","interactive_repo_select","load_dotenv",diff --git a/packages/cli/src/repowise/cli/ui/mode_selection.py b/packages/cli/src/repowise/cli/ui/mode_selection.pyindex 2975b432c..e2f599aa4 100644--- a/packages/cli/src/repowise/cli/ui/mode_selection.py+++ b/packages/cli/src/repowise/cli/ui/mode_selection.py@@ -15,6 +15,7 @@ from rich.text import Textfrom repowise.cli.ui.brand import BRAND, BRAND_STYLE, DIMfrom repowise.cli.ui.repo_scanner import RepoScanInfo+from repowise.core.reasoning import REASONING_MODES# A repo at or above this many files is "large" — large enough that a quick# fast-mode first index (graph + essential git, no LLM docs) is worth offering.@@ -231,6 +232,7 @@ def _prompt_generation(*,allow_fast: bool,is_large: bool,+ prompt_reasoning: bool = True,) -> None:"""Generation section: concurrency, reasoning, embedder, test run, tiering."""console.print()@@ -251,11 +253,14 @@ def _prompt_generation(type=int,)- result["reasoning"] = click.prompt(- " Reasoning mode",- default="auto",- type=click.Choice(["auto", "off", "minimal"]),- )+ if prompt_reasoning:+ result["reasoning"] = click.prompt(+ " Reasoning mode",+ default="auto",+ type=click.Choice(REASONING_MODES),+ )+ else:+ result["reasoning"] = None# Embedder selectiondetected_embedder = _resolve_embedder_from_env()@@ -300,7 +305,8 @@ def _build_summary_table(result: dict[str, Any], patterns: list[str], *, allow_fsummary.add_row("Commit limit", str(result["commit_limit"]))summary.add_row("Follow renames", "yes" if result["follow_renames"] else "no")summary.add_row("Concurrency", str(result["concurrency"]))- summary.add_row("Reasoning", result["reasoning"])+ if result.get("reasoning"):+ summary.add_row("Reasoning", result["reasoning"])summary.add_row("Embedder", result["embedder"])if allow_fast:summary.add_row("Run mode", result["run_mode"])@@ -321,6 +327,7 @@ def interactive_advanced_config(scan: RepoScanInfo | None = None,*,allow_fast: bool = False,+ prompt_reasoning: bool = True,) -> dict[str, Any]:"""Prompt for advanced init options, grouped into logical sections.@@ -351,7 +358,14 @@ def interactive_advanced_config(_prompt_run_mode(console, result, allow_fast=allow_fast, is_large=is_large)patterns = _prompt_exclude(console, scan, result)_prompt_git(console, scan, result)- _prompt_generation(console, scan, result, allow_fast=allow_fast, is_large=is_large)+ _prompt_generation(+ console,+ scan,+ result,+ allow_fast=allow_fast,+ is_large=is_large,+ prompt_reasoning=prompt_reasoning,+ )# ── Summary ───────────────────────────────────────────────────────────console.print()diff --git a/packages/cli/src/repowise/cli/ui/provider_selection.py b/packages/cli/src/repowise/cli/ui/provider_selection.pyindex d59905d34..b9afd268f 100644--- a/packages/cli/src/repowise/cli/ui/provider_selection.py+++ b/packages/cli/src/repowise/cli/ui/provider_selection.py@@ -3,6 +3,7 @@from __future__ import annotationsimport os+from dataclasses import dataclassfrom pathlib import Pathimport click@@ -12,6 +13,8 @@ from rich.table import Tablefrom repowise.cli.ui.brand import BRAND, BRAND_STYLE, OK, WARNfrom repowise.cli.ui.env_persistence import _save_key_to_dotenv+from repowise.core.providers.llm.base import ProviderModelOption+from repowise.core.reasoning import ReasoningMode, normalize_reasoning# ---------------------------------------------------------------------------# Provider metadata — order matters (gemini first = default)@@ -22,6 +25,7 @@ _PROVIDER_DEFAULTS: dict[str, str] = {"openai": "gpt-5.4-nano","anthropic": "claude-sonnet-4-6","deepseek": "deepseek-v4-flash",+ "codex_cli": "codex_cli/default","ollama": "llama3.2","openrouter": "anthropic/claude-sonnet-4.6","litellm": "groq/llama-3.1-70b-versatile",@@ -32,6 +36,7 @@ _PROVIDER_ENV: dict[str, str] = {"openai": "OPENAI_API_KEY","anthropic": "ANTHROPIC_API_KEY","deepseek": "DEEPSEEK_API_KEY",+ "codex_cli": "__CODEX_CLI__","ollama": "OLLAMA_BASE_URL","openrouter": "OPENROUTER_API_KEY",}@@ -41,11 +46,29 @@ _PROVIDER_SIGNUP: dict[str, str] = {"openai": "https://platform.openai.com/api-keys","anthropic": "https://console.anthropic.com/settings/keys","deepseek": "https://platform.deepseek.com/api_keys",+ "codex_cli": "https://developers.openai.com/codex/cli","ollama": "https://ollama.com/download","openrouter": "https://openrouter.ai/keys",}+@dataclass(frozen=True)+class ProviderSelection:+ """Interactive provider/model/reasoning selection result."""++ provider_name: str+ model: str+ reasoning: ReasoningMode = "auto"+++def _detect_codex_cli_status() -> tuple[bool, bool]:+ """Return ``(installed, logged_in)`` for the local Codex CLI."""+ from repowise.cli.mcp_config import is_codex_cli_installed, is_codex_logged_in++ installed = is_codex_cli_installed()+ return installed, is_codex_logged_in() if installed else False++def _detect_provider_status() -> dict[str, str]:"""Return {provider: env_var_name} for providers whose key is set."""status: dict[str, str] = {}@@ -53,20 +76,24 @@ def _detect_provider_status() -> dict[str, str]:if prov == "gemini":if os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY"):status[prov] = env_var+ elif prov == "codex_cli":+ installed, logged_in = _detect_codex_cli_status()+ if installed and logged_in:+ status[prov] = "codex CLI"elif os.environ.get(env_var):status[prov] = env_varreturn status-def interactive_provider_select(+def _interactive_provider_name(console: Console,model_flag: str | None,*,repo_path: Path | None = None,-) -> tuple[str, str]:+) -> str:"""Show provider table, handle selection + inline key entry + save.- Returns ``(provider_name, model_name)``.+ Returns the chosen provider name."""providers = list(_PROVIDER_ENV.keys()) # gemini firstdetected = _detect_provider_status()@@ -85,12 +112,23 @@ def interactive_provider_select(table.add_column("Default Model", style="dim")for idx, prov in enumerate(providers, 1):- status_text = f"[{OK}]✓ API key set[/]" if prov in detected else "[dim]✗ no key[/dim]"+ if prov == "codex_cli":+ codex_installed, codex_logged_in = _detect_codex_cli_status()+ if codex_logged_in:+ status_text = f"[{OK}]✓ codex CLI logged in[/]"+ elif codex_installed:+ status_text = "[yellow]✗ codex login required[/yellow]"+ else:+ status_text = "[dim]✗ codex CLI not found[/dim]"+ else:+ status_text = f"[{OK}]✓ API key set[/]" if prov in detected else "[dim]✗ no key[/dim]"default_model = _PROVIDER_DEFAULTS.get(prov, "")# Mark gemini as recommendedlabel = provif prov == "gemini":label = f"{prov} [dim](recommended)[/dim]"+ elif prov == "codex_cli":+ label = f"{prov} [dim](uses Codex CLI auth)[/dim]"table.add_row(f"[{idx}]", label, status_text, default_model)console.print()@@ -116,6 +154,27 @@ def interactive_provider_select(# --- inline API key entry if missing ---if chosen not in detected:+ if chosen == "codex_cli":+ codex_installed, codex_logged_in = _detect_codex_cli_status()+ console.print()+ console.print(+ " [bold]codex_cli[/bold] requires the Codex CLI on PATH "+ "and an authenticated Codex session."+ )+ console.print(f" Install CLI: [{BRAND}]npm install -g @openai/codex[/]")+ console.print(f" Authenticate: [{BRAND}]codex login[/]")+ console.print()+ if not codex_installed:+ console.print(+ f" [{WARN}]Codex CLI not detected. Please install and retry, "+ "or select another provider.[/]"+ )+ elif not codex_logged_in:+ console.print(+ f" [{WARN}]Codex CLI is not logged in. Run 'codex login' and retry, "+ "or select another provider.[/]"+ )+ return _interactive_provider_name(console, model_flag, repo_path=repo_path)env_var = _PROVIDER_ENV[chosen]signup_url = _PROVIDER_SIGNUP.get(chosen, "")console.print()@@ -126,28 +185,274 @@ def interactive_provider_select(key = _prompt_api_key(console, chosen, env_var, repo_path=repo_path)if not key:console.print(f" [{WARN}]Skipped. Please select another provider.[/]")- return interactive_provider_select(console, model_flag, repo_path=repo_path)+ return _interactive_provider_name(console, model_flag, repo_path=repo_path)- # --- model ---- default_model = _PROVIDER_DEFAULTS.get(chosen, "")- if not model_flag:+ return chosen+++def _fallback_model_option(provider_name: str) -> ProviderModelOption:+ default_model = _PROVIDER_DEFAULTS.get(provider_name, "")+ return ProviderModelOption(+ model=default_model,+ label=default_model,+ reasoning_modes=("auto",),+ recommended=True,+ source="fallback",+ )+++def _provider_model_options(+ console: Console,+ provider_name: str,+ *,+ model: str,+ repo_path: Path | None,+) -> tuple[ProviderModelOption, ...]:+ try:+ from repowise.cli.helpers import resolve_provider++ provider = resolve_provider(provider_name, model, repo_path)+ return provider.available_model_options()+ except Exception as exc:console.print(- " [dim]↳ Smaller is fine — repowise is calibrated for "- "flash-lite / nano / haiku / 8B-class ollama. Bigger models "- "don't improve doc quality.[/]"+ f" [dim]Model list unavailable for {provider_name}: {exc}. "+ "Using built-in defaults.[/dim]")- model = model_flag or click.prompt(- " Model",- default=default_model,+ return (_fallback_model_option(provider_name),)+++def _provider_supported_reasoning_modes(+ provider_name: str,+ model: str,+ repo_path: Path | None,+) -> tuple[ReasoningMode, ...]:+ try:+ from repowise.cli.helpers import resolve_provider++ provider = resolve_provider(provider_name, model, repo_path)+ return provider.supported_reasoning_modes()+ except Exception:+ return ("auto",)+++def _format_reasoning_modes(modes: tuple[ReasoningMode, ...]) -> str:+ modes = tuple(dict.fromkeys(modes or ("auto",)))+ return ", ".join(modes)+++def _filtered_model_options(+ console: Console,+ options: tuple[ProviderModelOption, ...],+) -> list[ProviderModelOption]:+ if len(options) <= 40:+ return list(options)++ console.print(f" [dim]{len(options):,} models available.[/dim]")+ query = click.prompt(+ " Filter models (Enter for recommended)",+ default="",+ show_default=False,+ ).strip()+ if query:+ q = query.lower()+ filtered = [+ option+ for option in options+ if q in option.model.lower()+ or (option.label and q in option.label.lower())+ or (option.notes and q in option.notes.lower())+ ][:40]+ if filtered:+ return filtered+ console.print(f" [{WARN}]No models matched {query!r}; showing recommended.[/]")++ recommended = [option for option in options if option.recommended]+ return (recommended or list(options))[:40]+++def _select_model_option(+ console: Console,+ provider_name: str,+ options: tuple[ProviderModelOption, ...],+ *,+ default_model: str,+ repo_path: Path | None,+) -> ProviderModelOption:+ console.print(+ " [dim]↳ Smaller is fine — repowise is calibrated for "+ "flash-lite / nano / haiku / 8B-class ollama. Bigger models "+ "don't improve doc quality.[/]")- if not model_flag and _is_flagship_model(model):+ display_options = _filtered_model_options(console, options)+ if not display_options:+ display_options = [_fallback_model_option(provider_name)]++ table = Table(+ show_header=True,+ box=None,+ padding=(0, 2),+ title="[bold]Model Options[/bold]",+ title_style="",+ )+ table.add_column("#", style=BRAND_STYLE, width=4)+ table.add_column("Model", style="bold", min_width=22)+ table.add_column("Reasoning", style="dim")+ table.add_column("Source", style="dim")+ table.add_column("Notes", style="dim")++ default_idx = "1"+ for idx, option in enumerate(display_options, 1):+ if option.model == default_model or option.recommended:+ default_idx = str(idx)+ break++ for idx, option in enumerate(display_options, 1):+ label = option.label or option.model+ if option.recommended:+ label = f"{label} [dim](recommended)[/dim]"+ table.add_row(+ f"[{idx}]",+ label,+ _format_reasoning_modes(option.reasoning_modes),+ option.source,+ option.notes,+ )++ custom_idx = str(len(display_options) + 1)+ table.add_row(+ f"[{custom_idx}]",+ "Custom model",+ "auto",+ "manual",+ "type an exact model id",+ )++ console.print()+ console.print(table)+ console.print()++ choice = Prompt.ask(+ " Select model",+ choices=[str(i) for i in range(1, len(display_options) + 2)],+ default=default_idx,+ console=console,+ )+ if choice == custom_idx:+ model = click.prompt(" Model", default=default_model)+ return ProviderModelOption(+ model=model,+ label=model,+ reasoning_modes=_provider_supported_reasoning_modes(+ provider_name,+ model,+ repo_path,+ ),+ source="fallback",+ )++ return display_options[int(choice) - 1]+++def _select_reasoning_mode(+ selected: ProviderModelOption,+ reasoning_flag: str | None,+) -> ReasoningMode:+ choices = tuple(dict.fromkeys(selected.reasoning_modes or ("auto",)))+ if "auto" not in choices:+ choices = ("auto", *choices)++ if reasoning_flag:+ try:+ requested = normalize_reasoning(reasoning_flag)+ except ValueError as exc:+ raise click.ClickException(str(exc)) from exc+ if requested not in choices:+ supported = ", ".join(choices)+ raise click.ClickException(+ f"reasoning={requested!r} is not supported by model "+ f"{selected.model!r}. Supported reasoning modes: {supported}."+ )+ return requested++ if choices == ("auto",):+ return "auto"++ return click.prompt(+ " Reasoning",+ default="auto",+ type=click.Choice(choices),+ )+++def interactive_provider_config_select(+ console: Console,+ model_flag: str | None,+ reasoning_flag: str | None = None,+ *,+ repo_path: Path | None = None,+) -> ProviderSelection:+ """Show provider/model/reasoning selection for interactive init.++ Returns a :class:`ProviderSelection` carrying the chosen provider name,+ model, and reasoning mode.+ """+ chosen = _interactive_provider_name(console, model_flag, repo_path=repo_path)+ default_model = _PROVIDER_DEFAULTS.get(chosen, "")++ if model_flag:+ selected = ProviderModelOption(+ model=model_flag,+ label=model_flag,+ reasoning_modes=_provider_supported_reasoning_modes(+ chosen,+ model_flag,+ repo_path,+ ),+ source="fallback",+ )+ else:+ options = _provider_model_options(+ console,+ chosen,+ model=default_model,+ repo_path=repo_path,+ )+ selected = _select_model_option(+ console,+ chosen,+ options,+ default_model=default_model,+ repo_path=repo_path,+ )++ if not model_flag and _is_flagship_model(selected.model):console.print(- f" [{WARN}]Note:[/] [dim]'{model}' works, but flash-lite / haiku / "+ f" [{WARN}]Note:[/] [dim]'{selected.model}' works, but flash-lite / haiku / ""nano produce equivalent docs at ~10x lower cost on most repos.[/]")- return chosen, model+ reasoning = _select_reasoning_mode(selected, reasoning_flag)+ return ProviderSelection(chosen, selected.model, reasoning)+++def interactive_provider_select(+ console: Console,+ model_flag: str | None,+ *,+ repo_path: Path | None = None,+) -> tuple[str, str]:+ """Show provider table, handle selection + inline key entry + save.++ Returns ``(provider_name, model_name)``.+ """+ selection = interactive_provider_config_select(+ console,+ model_flag,+ reasoning_flag="auto",+ repo_path=repo_path,+ )+ return selection.provider_name, selection.model_FLAGSHIP_MODEL_TOKENS = (diff --git a/packages/core/src/repowise/core/generation/cost_tracker.py b/packages/core/src/repowise/core/generation/cost_tracker.pyindex 189287609..80c9b2378 100644--- a/packages/core/src/repowise/core/generation/cost_tracker.py+++ b/packages/core/src/repowise/core/generation/cost_tracker.py@@ -49,6 +49,8 @@ _warned_models: set[str] = set()def _get_pricing(model: str) -> dict[str, float]:"""Return pricing for *model*, falling back and warning if unknown."""+ if model.startswith("codex_cli/"):+ return {"input": 0.0, "output": 0.0}if model in _PRICING:return _PRICING[model]if model not in _warned_models:diff --git a/packages/core/src/repowise/core/generation/editor_files/__init__.py b/packages/core/src/repowise/core/generation/editor_files/__init__.pyindex 3af8106a3..aab870ecb 100644--- a/packages/core/src/repowise/core/generation/editor_files/__init__.py+++ b/packages/core/src/repowise/core/generation/editor_files/__init__.py@@ -6,6 +6,7 @@ Provides generators that create and maintain AI-editor configuration filesNo LLM calls are made — all content is derived from the repowise DB."""+from .agents_md import AgentsMdGeneratorfrom .claude_md import ClaudeMdGenerator, WorkspaceClaudeMdGeneratorfrom .data import (DecisionSummary,@@ -19,17 +20,15 @@ from .data import (from .fetcher import EditorFileDataFetcher__all__ = [- # Generators+ "AgentsMdGenerator","ClaudeMdGenerator",- "WorkspaceClaudeMdGenerator",- # Data containers"DecisionSummary","EditorFileData",+ "EditorFileDataFetcher","HotspotFile","KeyModule","TechStackItem",+ "WorkspaceClaudeMdGenerator","WorkspaceEditorFileData","WorkspaceRepoSummary",- # Fetcher- "EditorFileDataFetcher",]diff --git a/packages/core/src/repowise/core/generation/editor_files/agents_md.py b/packages/core/src/repowise/core/generation/editor_files/agents_md.pynew file mode 100644index 000000000..f19a8205a--- /dev/null+++ b/packages/core/src/repowise/core/generation/editor_files/agents_md.py@@ -0,0 +1,23 @@+"""AgentsMdGenerator - generates and maintains AGENTS.md for Codex."""++from __future__ import annotations++from .base import BaseEditorFileGenerator+++class AgentsMdGenerator(BaseEditorFileGenerator):+ """Generates and maintains a repo-level AGENTS.md file.++ The file has two sections:+ - User section outside the REPOWISE_AGENTS markers: never touched.+ - Repowise section between markers: regenerated from indexed data.+ """++ filename = "AGENTS.md"+ marker_tag = "REPOWISE_AGENTS"+ template_name = "agents_md.j2"+ user_placeholder = (+ "# AGENTS.md\n\n"+ "<!-- Add your project instructions above or below the Repowise section. "+ "Repowise only updates the managed section between markers. -->\n"+ )diff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2new file mode 100644index 000000000..06f1e9e6b--- /dev/null+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2@@ -0,0 +1,50 @@+## Repowise Codebase Context For {{ data.repo_name }}++This repository is indexed by Repowise. Use the Repowise MCP tools for codebase orientation, discovery, implementation context, modification risk, design rationale, and cleanup planning. MCP data reflects the last index run; verify against source files before editing.++Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.indexed_commit }}){% endif %}{% if data.avg_confidence %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% endif %}++{% if data.architecture_summary %}+### Architecture+{{ data.architecture_summary }}+{% endif %}+{% if data.key_modules %}+### Key Modules+| Module | Purpose | Owner |+|--------|---------|-------|+{% for mod in data.key_modules %}+| `{{ mod.name }}` | {{ mod.purpose or "-" }} | {{ mod.owner or "-" }} |+{% endfor %}+{% endif %}+{% if data.entry_points %}+### Entry Points+{% for ep in data.entry_points %}+- `{{ ep }}`+{% endfor %}+{% endif %}+{% if data.hotspots %}+### Risk Hotspots+| File | Churn | 90d Commits | Owner |+|------|-------|-------------|-------|+{% for h in data.hotspots %}+| `{{ h.path }}` | {{ h.churn_percentile }}th percentile | {{ h.commit_count_90d }} | {{ h.owner or "-" }} |+{% endfor %}+{% endif %}++### Repowise MCP Workflow++- Overview: call `get_overview()` at the start of an unfamiliar task to orient on architecture, modules, entry points, and tech stack.+- Search: call `search_codebase(query="...")` when locating where a concept, symbol, feature, or behavior is implemented.+- Context: call `get_context(targets=["path/or/symbol", "..."])` for enriched docs, ownership, decisions, callers, and related files before relying on raw source alone.+- Risk: call `get_risk(targets=["path/to/file.py"])` before modifying shared utilities, public APIs, hotspots, high-coupling modules, or files with unknown dependents.+- Why: call `get_why(query="...")` before architectural changes or when the user asks why code is structured a certain way.+- Dead code: call `get_dead_code(safe_only=true)` before cleanup or removal work; treat lower-confidence findings as candidates to investigate.+- Connections: call `get_dependency_path(source="...", target="...")` when tracing how modules connect.+- Diagrams: call `get_architecture_diagram(scope="...")` when a visual structure would clarify the change.+{% if data.build_commands %}++### Commands+{% for label, cmd in data.build_commands.items() %}+- {{ label | capitalize }}: `{{ cmd }}`+{% endfor %}+{% endif %}diff --git a/packages/core/src/repowise/core/providers/llm/__init__.py b/packages/core/src/repowise/core/providers/llm/__init__.pyindex 7b1d272b5..650e07041 100644--- a/packages/core/src/repowise/core/providers/llm/__init__.py+++ b/packages/core/src/repowise/core/providers/llm/__init__.py@@ -16,6 +16,7 @@ Built-in providers:deepseek — deepseek-v4-flash, deepseek-v4-pro via api.deepseek.comollama — local inference (llama3.2, codellama, etc.)litellm — 100+ providers via LiteLLM proxy+ codex_cli — local authenticated Codex CLI via codex execmock — deterministic test provider"""diff --git a/packages/core/src/repowise/core/providers/llm/anthropic.py b/packages/core/src/repowise/core/providers/llm/anthropic.pyindex 6bd431e2d..f2f64c2b5 100644--- a/packages/core/src/repowise/core/providers/llm/anthropic.py+++ b/packages/core/src/repowise/core/providers/llm/anthropic.py@@ -14,7 +14,8 @@ from __future__ import annotationsimport contextlibimport os-from typing import TYPE_CHECKING, Any, AsyncIterator+from collections.abc import AsyncIterator+from typing import TYPE_CHECKING, Anyimport structlogfrom anthropic import APIStatusError as _AnthropicAPIStatusError@@ -22,7 +23,6 @@ from anthropic import AsyncAnthropicfrom anthropic import RateLimitError as _AnthropicRateLimitErrorfrom tenacity import (RetryError,- before_sleep_log,retry,retry_if_exception_type,stop_after_attempt,@@ -36,8 +36,10 @@ from repowise.core.providers.llm.base import (ChatToolCall,GeneratedResponse,ProviderError,+ ProviderModelOption,RateLimitError,ensure_reasoning_supported,+ fallback_model_option,)from repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode@@ -50,6 +52,57 @@ log = structlog.get_logger(__name__)_MAX_RETRIES = 3_MIN_WAIT = 1.0_MAX_WAIT = 4.0+_DEFAULT_BASE_URL = "https://api.anthropic.com"+++def _anthropic_model_options(+ api_key: str,+ base_url: str,+ fallback_model: str,+) -> tuple[ProviderModelOption, ...]:+ fallback = fallback_model_option(fallback_model)+ try:+ import httpx++ models_url = base_url.rstrip("/")+ if not models_url.endswith("/v1"):+ models_url = f"{models_url}/v1"+ response = httpx.get(+ f"{models_url}/models",+ headers={+ "x-api-key": api_key,+ "anthropic-version": "2023-06-01",+ },+ timeout=5.0,+ )+ response.raise_for_status()+ data = response.json().get("data", [])+ except Exception:+ return (fallback,)++ if not isinstance(data, list):+ return (fallback,)++ options: list[ProviderModelOption] = []+ for raw in data:+ if not isinstance(raw, dict) or not isinstance(raw.get("id"), str):+ continue+ model_id = raw["id"]+ display_name = raw.get("display_name")+ options.append(+ ProviderModelOption(+ model=model_id,+ label=display_name if isinstance(display_name, str) else model_id,+ reasoning_modes=("auto",),+ recommended=model_id == fallback_model,+ source="api",+ )+ )++ if not options:+ return (fallback,)++ return tuple(options)class AnthropicProvider(BaseProvider):@@ -78,6 +131,8 @@ class AnthropicProvider(BaseProvider):"No API key provided. Pass api_key= or set ANTHROPIC_API_KEY.",)resolved_base_url = base_url or os.environ.get("ANTHROPIC_BASE_URL")+ self._api_key = resolved_key+ self._base_url = resolved_base_url or _DEFAULT_BASE_URLself._client = AsyncAnthropic(api_key=resolved_key, base_url=resolved_base_url)self._model = modelself._rate_limiter = rate_limiter@@ -91,6 +146,9 @@ class AnthropicProvider(BaseProvider):def model_name(self) -> str:return self._model+ def available_model_options(self) -> tuple[ProviderModelOption, ...]:+ return _anthropic_model_options(self._api_key, self._base_url, self._model)+async def generate(self,system_prompt: str,@@ -156,9 +214,7 @@ class AnthropicProvider(BaseProvider):except _AnthropicRateLimitError as exc:raise RateLimitError("anthropic", str(exc), status_code=429) from excexcept _AnthropicAPIStatusError as exc:- raise ProviderError(- "anthropic", str(exc), status_code=exc.status_code- ) from exc+ raise ProviderError("anthropic", str(exc), status_code=exc.status_code) from exccached = getattr(response.usage, "cache_read_input_tokens", 0) or 0result = GeneratedResponse(@@ -220,11 +276,13 @@ class AnthropicProvider(BaseProvider):anthropic_tools = []for t in tools:fn = t.get("function", t)- anthropic_tools.append({- "name": fn["name"],- "description": fn.get("description", ""),- "input_schema": fn.get("parameters", {}),- })+ anthropic_tools.append(+ {+ "name": fn["name"],+ "description": fn.get("description", ""),+ "input_schema": fn.get("parameters", {}),+ }+ )# Convert OpenAI-format messages to Anthropic formatanthropic_messages = _to_anthropic_messages(messages)@@ -262,7 +320,11 @@ class AnthropicProvider(BaseProvider):elif event.type == "content_block_stop":if current_tool_name:try:- args = _json.loads(current_tool_input_json) if current_tool_input_json else {}+ args = (+ _json.loads(current_tool_input_json)+ if current_tool_input_json+ else {}+ )except Exception:args = {}yield ChatStreamEvent(@@ -353,14 +415,18 @@ def _to_anthropic_messages(messages: list[dict[str, Any]]) -> list[dict[str, Anyif role == "tool":# OpenAI tool result → Anthropic user message with tool_result block- result.append({- "role": "user",- "content": [{- "type": "tool_result",- "tool_use_id": msg.get("tool_call_id", ""),- "content": msg.get("content", ""),- }],- })+ result.append(+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": msg.get("tool_call_id", ""),+ "content": msg.get("content", ""),+ }+ ],+ }+ )elif role == "assistant":content_blocks: list[dict[str, Any]] = []# Text content@@ -371,18 +437,21 @@ def _to_anthropic_messages(messages: list[dict[str, Any]]) -> list[dict[str, Anyfor tc in msg.get("tool_calls", []):fn = tc.get("function", {})import json as _json+args = fn.get("arguments", "{}")if isinstance(args, str):try:args = _json.loads(args)except Exception:args = {}- content_blocks.append({- "type": "tool_use",- "id": tc.get("id", ""),- "name": fn.get("name", ""),- "input": args,- })+ content_blocks.append(+ {+ "type": "tool_use",+ "id": tc.get("id", ""),+ "name": fn.get("name", ""),+ "input": args,+ }+ )if content_blocks:result.append({"role": "assistant", "content": content_blocks})else:diff --git a/packages/core/src/repowise/core/providers/llm/base.py b/packages/core/src/repowise/core/providers/llm/base.pyindex adaf4a98c..96dc3146c 100644--- a/packages/core/src/repowise/core/providers/llm/base.py+++ b/packages/core/src/repowise/core/providers/llm/base.py@@ -14,13 +14,45 @@ Adding a new provider:from __future__ import annotationsfrom abc import ABC, abstractmethod+from collections.abc import AsyncIteratorfrom dataclasses import dataclass, field-from typing import Any, AsyncIterator, Literal, Protocol, runtime_checkable+from typing import Any, Literal, Protocol, runtime_checkablefrom repowise.core.reasoning import ReasoningMode, normalize_reasoning-CacheSegment = Literal["system", "user_prefix"]+ModelOptionSource = Literal["api", "local", "fallback"]+++@dataclass(frozen=True)+class ProviderModelOption:+ """A model choice exposed by a provider for interactive configuration."""++ model: str+ label: str | None = None+ reasoning_modes: tuple[ReasoningMode, ...] = ("auto",)+ recommended: bool = False+ source: ModelOptionSource = "fallback"+ notes: str = ""+++def fallback_model_option(+ model: str,+ *,+ label: str | None = None,+ reasoning_modes: tuple[ReasoningMode, ...] = ("auto",),+ notes: str = "model list unavailable; using configured model",+) -> ProviderModelOption:+ """Return the single fallback option used when live discovery fails."""++ return ProviderModelOption(+ model=model,+ label=label or model,+ reasoning_modes=reasoning_modes,+ recommended=True,+ source="fallback",+ notes=notes,+ )@dataclass(frozen=True)@@ -120,8 +152,8 @@ class BaseProvider(ABC):repowise uses 0.3 for consistent doc style.request_id: Optional trace ID for logging and debugging.reasoning: Provider-level reasoning intent. ``auto`` preserves- provider defaults; ``off`` and ``minimal`` are- translated by providers that support them.+ provider defaults; explicit modes are translated by+ providers that support them.cache_hints: Optional hints that one or more prompt segments arereusable across calls. Providers with an explicitcaching primitive (Anthropic) use them; others@@ -156,6 +188,29 @@ class BaseProvider(ABC):"""...+ def supported_reasoning_modes(self) -> tuple[ReasoningMode, ...]:+ """Return reasoning modes supported by this provider/model.++ ``auto`` is always present because it means "preserve provider defaults".+ Providers with model-specific support should override this method and+ return the exact explicit modes they can translate before an API call.+ """++ return ("auto",)++ def available_model_options(self) -> tuple[ProviderModelOption, ...]:+ """Return model options available for interactive provider setup."""++ return (+ ProviderModelOption(+ model=self.model_name,+ label=self.model_name,+ reasoning_modes=self.supported_reasoning_modes(),+ recommended=True,+ source="fallback",+ ),+ )+class ProviderError(Exception):"""Raised when a provider returns an unrecoverable error.diff --git a/packages/core/src/repowise/core/providers/llm/codex_cli.py b/packages/core/src/repowise/core/providers/llm/codex_cli.pynew file mode 100644index 000000000..b715a0b35--- /dev/null+++ b/packages/core/src/repowise/core/providers/llm/codex_cli.py@@ -0,0 +1,514 @@+"""Codex CLI provider for repowise.++This provider delegates generation to the authenticated local Codex CLI via+``codex exec``. It is intended for users with Codex subscription/auth already+configured by ``codex login`` and does not require an OpenAI API key.+"""++from __future__ import annotations++import asyncio+import contextlib+import json+import shutil+import subprocess+from dataclasses import dataclass+from functools import lru_cache+from pathlib import Path+from typing import Any++import structlog++from repowise.core.providers.llm.base import (+ BaseProvider,+ CacheHint,+ GeneratedResponse,+ ProviderError,+ ProviderModelOption,+)+from repowise.core.rate_limiter import RateLimiter+from repowise.core.reasoning import REASONING_MODES, ReasoningMode, normalize_reasoning++log = structlog.get_logger(__name__)++_DEFAULT_MODEL_LABEL = "codex_cli/default"+_EXEC_TIMEOUT_SECONDS = 600+_CATALOG_TIMEOUT_SECONDS = 5+++async def _close_subprocess_transport(proc: asyncio.subprocess.Process) -> None:+ """Close asyncio's subprocess transport before the event loop shuts down."""++ transport = getattr(proc, "_transport", None)+ close = getattr(transport, "close", None)+ if not callable(close):+ return+ with contextlib.suppress(Exception):+ close()+ await asyncio.sleep(0)+++@dataclass(frozen=True)+class CodexModelReasoning:+ """Small reasoning-capability slice extracted from the Codex model catalog."""++ slug: str+ default_effort: str | None+ supported_efforts: tuple[str, ...]+++def _resolve_codex_executable() -> str | None:+ """Return the executable path used to launch Codex, or None if unavailable."""++ return shutil.which("codex")+++def _normalize_model(model: str | None) -> str | None:+ """Return the native Codex model slug, or None to use CLI config."""+ if not model:+ return None+ if model == _DEFAULT_MODEL_LABEL:+ return None+ if model.startswith("codex_cli/"):+ suffix = model.removeprefix("codex_cli/")+ return suffix or None+ return model+++def _model_label(model: str | None) -> str:+ """Return the persisted attribution label for a Codex CLI model."""+ native = _normalize_model(model)+ return f"codex_cli/{native}" if native else _DEFAULT_MODEL_LABEL+++def _extract_codex_model_catalog(raw: object) -> dict[str, CodexModelReasoning]:+ if not isinstance(raw, dict):+ return {}++ raw_models = raw.get("models")+ if not isinstance(raw_models, list):+ return {}++ catalog: dict[str, CodexModelReasoning] = {}+ for raw_model in raw_models:+ if not isinstance(raw_model, dict):+ continue+ slug = raw_model.get("slug")+ if not isinstance(slug, str) or not slug.strip():+ continue++ supported: list[str] = []+ raw_levels = raw_model.get("supported_reasoning_levels")+ if isinstance(raw_levels, list):+ for raw_level in raw_levels:+ if not isinstance(raw_level, dict):+ continue+ effort = raw_level.get("effort")+ if isinstance(effort, str) and effort.strip():+ supported.append(effort.strip().lower())++ if not supported:+ continue++ default_effort = raw_model.get("default_reasoning_level")+ catalog[slug.lower()] = CodexModelReasoning(+ slug=slug,+ default_effort=(+ default_effort.strip().lower()+ if isinstance(default_effort, str) and default_effort.strip()+ else None+ ),+ supported_efforts=tuple(dict.fromkeys(supported)),+ )++ return catalog+++@lru_cache(maxsize=8)+def _load_codex_model_catalog(codex_cmd: str) -> dict[str, CodexModelReasoning] | None:+ """Ask the installed Codex CLI for its bundled model catalog."""++ try:+ completed = subprocess.run(+ [codex_cmd, "debug", "models", "--bundled"],+ capture_output=True,+ check=False,+ text=True,+ timeout=_CATALOG_TIMEOUT_SECONDS,+ )+ except (OSError, subprocess.SubprocessError):+ return None++ if completed.returncode != 0:+ return None++ try:+ raw = json.loads(completed.stdout)+ except json.JSONDecodeError:+ return None++ catalog = _extract_codex_model_catalog(raw)+ return catalog or None+++def _codex_effort_for_reasoning(+ reasoning: ReasoningMode,+ supported_efforts: tuple[str, ...] | None,+) -> str | None:+ mode = normalize_reasoning(reasoning)+ if mode == "auto":+ return None+ if mode in ("off", "none"):+ return "none"+ if mode == "minimal":+ if supported_efforts and "minimal" in supported_efforts:+ return "minimal"+ if supported_efforts and "low" in supported_efforts:+ return "low"+ return "low"+ return mode+++def _catalog_supported_efforts(+ catalog: dict[str, CodexModelReasoning],+ native_model: str | None,+) -> tuple[str, ...] | None:+ if native_model:+ model = catalog.get(native_model.lower())+ return model.supported_efforts if model else None++ efforts: list[str] = []+ for model in catalog.values():+ efforts.extend(model.supported_efforts)+ return tuple(dict.fromkeys(efforts))+++def _codex_modes_from_efforts(+ supported_efforts: tuple[str, ...],+) -> tuple[ReasoningMode, ...]:+ modes: list[ReasoningMode] = ["auto"]+ if "none" in supported_efforts:+ modes.extend(("off", "none"))+ if "minimal" in supported_efforts or "low" in supported_efforts:+ modes.append("minimal")+ for mode in ("low", "medium", "high", "xhigh", "max"):+ if mode in supported_efforts:+ modes.append(mode)+ return tuple(dict.fromkeys(modes))+++def _codex_supported_reasoning_modes(+ codex_cmd: str,+ model: str,+) -> tuple[ReasoningMode, ...]:+ catalog = _load_codex_model_catalog(codex_cmd)+ if catalog is None:+ return REASONING_MODES++ supported_efforts = _catalog_supported_efforts(catalog, _normalize_model(model))+ if supported_efforts is None:+ return REASONING_MODES++ return _codex_modes_from_efforts(supported_efforts)+++def _codex_model_options(codex_cmd: str) -> tuple[ProviderModelOption, ...]:+ catalog = _load_codex_model_catalog(codex_cmd)+ if catalog is None:+ return (+ ProviderModelOption(+ model=_DEFAULT_MODEL_LABEL,+ label="Codex CLI default",+ reasoning_modes=REASONING_MODES,+ recommended=True,+ source="fallback",+ notes="uses Codex CLI config",+ ),+ )++ default_efforts = _catalog_supported_efforts(catalog, None) or ()+ options: list[ProviderModelOption] = [+ ProviderModelOption(+ model=_DEFAULT_MODEL_LABEL,+ label="Codex CLI default",+ reasoning_modes=_codex_modes_from_efforts(default_efforts),+ recommended=True,+ source="local",+ notes="uses Codex CLI config",+ )+ ]+ for model in sorted(catalog.values(), key=lambda item: item.slug.lower()):+ notes = f"default {model.default_effort}" if model.default_effort else ""+ options.append(+ ProviderModelOption(+ model=_model_label(model.slug),+ label=model.slug,+ reasoning_modes=_codex_modes_from_efforts(model.supported_efforts),+ recommended=False,+ source="local",+ notes=notes,+ )+ )+ return tuple(options)+++def _codex_reasoning_config(+ codex_cmd: str,+ model: str,+ reasoning: ReasoningMode,+) -> str | None:+ mode = normalize_reasoning(reasoning)+ if mode == "auto":+ return None++ native_model = _normalize_model(model)+ catalog = _load_codex_model_catalog(codex_cmd)+ supported_efforts = (+ _catalog_supported_efforts(catalog, native_model) if catalog is not None else None+ )+ effort = _codex_effort_for_reasoning(mode, supported_efforts)+ if effort is None:+ return None++ if supported_efforts is not None and effort not in supported_efforts:+ supported = ", ".join(supported_efforts)+ mapped = f" maps to model_reasoning_effort={effort!r}" if effort != mode else ""+ raise ProviderError(+ "codex_cli",+ (+ f"reasoning={mode!r}{mapped} is not supported by the Codex CLI "+ f"model catalog for model {model!r}. Supported reasoning efforts: "+ f"{supported}."+ ),+ )++ return f'model_reasoning_effort="{effort}"'+++def _combine_prompt(system_prompt: str, user_prompt: str) -> str:+ return (+ "Follow these system instructions for this one-shot documentation task:\n\n"+ f"{system_prompt.strip()}\n\n"+ "User request and context:\n\n"+ f"{user_prompt.strip()}\n"+ )+++def _parse_jsonl(stdout: str) -> tuple[str, dict[str, Any]]:+ """Parse Codex JSONL output, ignoring non-JSON noise."""+ content_parts: list[str] = []+ usage: dict[str, Any] = {}++ for raw_line in stdout.splitlines():+ line = raw_line.strip()+ if not line:+ continue+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ continue++ if event.get("type") == "item.completed":+ item = event.get("item") or {}+ if item.get("type") == "agent_message":+ text = item.get("text")+ if isinstance(text, str) and text:+ content_parts.append(text)+ elif event.get("type") == "turn.completed":+ event_usage = event.get("usage")+ if isinstance(event_usage, dict):+ usage = event_usage++ return "\n".join(content_parts), usage+++def _tail(text: str, max_chars: int = 2_000) -> str:+ text = text.strip()+ if len(text) <= max_chars:+ return text+ return text[-max_chars:]+++def _error_message(stderr: str, stdout: str, returncode: int) -> str:+ for candidate in (_tail(stderr), _tail(stdout)):+ if not candidate:+ continue+ if candidate.lstrip().startswith(("{", "[")):+ continue+ return candidate+ return f"codex exec exited with {returncode}"+++class CodexCliProvider(BaseProvider):+ """LLM provider backed by ``codex exec``.++ Args:+ model: Optional native Codex model slug. If omitted, Codex CLI config+ chooses the model. Persisted labels like ``codex_cli/gpt-5.5`` are+ accepted and normalized before calling the CLI.+ repo_path: Working directory passed to ``codex exec --cd``.+ rate_limiter: Accepted for interface consistency, but the provider+ serializes subprocess calls by default.+ """++ def __init__(+ self,+ model: str | None = None,+ repo_path: str | Path | None = None,+ rate_limiter: RateLimiter | None = None,+ ) -> None:+ codex_cmd = _resolve_codex_executable()+ if not codex_cmd:+ raise ProviderError(+ "codex_cli",+ "Codex CLI not found. Install it with: npm install -g @openai/codex",+ )+ self._codex_cmd = codex_cmd+ self._model = _normalize_model(model)+ self._repo_path = (+ Path(repo_path).resolve() if repo_path is not None else Path.cwd().resolve()+ )+ self._rate_limiter = rate_limiter+ self._subprocess_semaphore: asyncio.Semaphore | None = None+ self._semaphore_loop: asyncio.AbstractEventLoop | None = None++ @property+ def provider_name(self) -> str:+ return "codex_cli"++ @property+ def model_name(self) -> str:+ return _model_label(self._model)++ def supported_reasoning_modes(self) -> tuple[ReasoningMode, ...]:+ return _codex_supported_reasoning_modes(self._codex_cmd, self.model_name)++ def available_model_options(self) -> tuple[ProviderModelOption, ...]:+ return _codex_model_options(self._codex_cmd)++ def _get_semaphore(self) -> asyncio.Semaphore:+ loop = asyncio.get_running_loop()+ if self._semaphore_loop is not loop:+ self._subprocess_semaphore = asyncio.Semaphore(1)+ self._semaphore_loop = loop+ return self._subprocess_semaphore # type: ignore[return-value]++ def _build_command(self, *, reasoning: ReasoningMode = "auto") -> list[str]:+ cmd = [+ self._codex_cmd,+ "exec",+ "--ephemeral",+ "--sandbox",+ "read-only",+ "--json",+ "--cd",+ str(self._repo_path),+ ]+ reasoning_config = _codex_reasoning_config(self._codex_cmd, self.model_name, reasoning)+ if reasoning_config:+ cmd.extend(["--config", reasoning_config])+ if self._model:+ cmd.extend(["--model", self._model])+ cmd.append("-")+ return cmd++ async def generate(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int = 4096,+ temperature: float = 0.3,+ request_id: str | None = None,+ reasoning: ReasoningMode = "auto",+ cache_hints: tuple[CacheHint, ...] = (),+ ) -> GeneratedResponse:+ if self._rate_limiter:+ await self._rate_limiter.acquire(estimated_tokens=max_tokens)++ # _build_command may shell out to `codex debug models` (cached) to validate+ # the reasoning effort; run it off the event loop so a cold catalog load+ # can't stall every concurrent generation coroutine.+ cmd = await asyncio.to_thread(self._build_command, reasoning=reasoning)+ prompt = _combine_prompt(system_prompt, user_prompt)+ log.debug(+ "codex_cli.generate.start",+ model=self.model_name,+ repo_path=str(self._repo_path),+ request_id=request_id,+ )++ async with self._get_semaphore():+ try:+ proc = await asyncio.create_subprocess_exec(+ *cmd,+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ except FileNotFoundError as exc:+ raise ProviderError(+ "codex_cli",+ "Codex CLI not found. Install it with: npm install -g @openai/codex",+ ) from exc++ try:+ stdout_bytes, stderr_bytes = await asyncio.wait_for(+ proc.communicate(prompt.encode("utf-8")),+ timeout=_EXEC_TIMEOUT_SECONDS,+ )+ except TimeoutError as exc:+ proc.kill()+ with contextlib.suppress(ProcessLookupError):+ await proc.wait()+ raise ProviderError(+ "codex_cli",+ f"codex exec timed out after {_EXEC_TIMEOUT_SECONDS} seconds.",+ ) from exc+ finally:+ await _close_subprocess_transport(proc)++ stdout = stdout_bytes.decode("utf-8", errors="replace") if stdout_bytes else ""+ stderr = stderr_bytes.decode("utf-8", errors="replace") if stderr_bytes else ""++ if proc.returncode != 0:+ raise ProviderError(+ "codex_cli",+ _error_message(stderr, stdout, proc.returncode),+ status_code=proc.returncode,+ )++ content, usage = _parse_jsonl(stdout)+ if not content:+ raise ProviderError(+ "codex_cli",+ "codex exec completed but no agent_message was found in JSONL output.",+ )++ usage_missing = not usage+ input_tokens = int(usage.get("input_tokens", 0) or 0)+ output_tokens = int(usage.get("output_tokens", 0) or 0)+ cached_tokens = int(usage.get("cached_input_tokens", 0) or 0)++ log.debug(+ "codex_cli.generate.done",+ input_tokens=input_tokens,+ output_tokens=output_tokens,+ cached_tokens=cached_tokens,+ request_id=request_id,+ )+ usage_payload = {+ **usage,+ "source": "codex_exec",+ "model": self.model_name,+ "stderr": _tail(stderr, max_chars=1_000) if stderr.strip() else "",+ }+ if usage_missing:+ usage_payload["estimated"] = True++ return GeneratedResponse(+ content=content,+ input_tokens=input_tokens,+ output_tokens=output_tokens,+ cached_tokens=cached_tokens,+ usage=usage_payload,+ )diff --git a/packages/core/src/repowise/core/providers/llm/deepseek.py b/packages/core/src/repowise/core/providers/llm/deepseek.pyindex dfd616613..fa12db48f 100644--- a/packages/core/src/repowise/core/providers/llm/deepseek.py+++ b/packages/core/src/repowise/core/providers/llm/deepseek.py@@ -35,11 +35,13 @@ from repowise.core.providers.llm.base import (ChatToolCall,GeneratedResponse,ProviderError,+ ProviderModelOption,RateLimitError,ensure_reasoning_supported,+ fallback_model_option,)from repowise.core.rate_limiter import RateLimiter-from repowise.core.reasoning import ReasoningMode+from repowise.core.reasoning import ReasoningMode, normalize_reasoningif TYPE_CHECKING:from repowise.core.generation.cost_tracker import CostTracker@@ -51,6 +53,100 @@ _MIN_WAIT = 1.0_MAX_WAIT = 4.0_DEFAULT_BASE_URL = "https://api.deepseek.com"+_DEEPSEEK_REASONING_MODES: tuple[ReasoningMode, ...] = (+ "off",+ "none",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+)+++def _deepseek_supported_reasoning_modes(model: str) -> tuple[ReasoningMode, ...]:+ if model.startswith("deepseek-v4-"):+ return _DEEPSEEK_REASONING_MODES+ return ()+++def _resolve_deepseek_reasoning_mode(+ reasoning: ReasoningMode,+ *,+ model: str,+) -> ReasoningMode:+ return ensure_reasoning_supported(+ "deepseek",+ model,+ normalize_reasoning(reasoning),+ _deepseek_supported_reasoning_modes(model),+ detail=(+ "DeepSeek /models lists IDs only; reasoning controls are enabled "+ "for the documented V4 model family."+ ),+ )+++def _deepseek_reasoning_kwargs(reasoning: ReasoningMode) -> dict[str, Any]:+ mode = normalize_reasoning(reasoning)+ if mode == "auto":+ return {}+ if mode in ("off", "none"):+ return {"extra_body": {"thinking": {"type": "disabled"}}}+ effort = "max" if mode in ("xhigh", "max") else "high"+ return {"extra_body": {"thinking": {"type": "enabled", "reasoning_effort": effort}}}+++def _deepseek_model_options(+ api_key: str,+ base_url: str,+ fallback_model: str,+) -> tuple[ProviderModelOption, ...]:+ fallback = fallback_model_option(+ fallback_model,+ reasoning_modes=("auto", *_deepseek_supported_reasoning_modes(fallback_model)),+ )+ try:+ import httpx++ response = httpx.get(+ f"{base_url.rstrip('/')}/models",+ headers={"Authorization": f"Bearer {api_key}"},+ timeout=5.0,+ )+ response.raise_for_status()+ data = response.json().get("data", [])+ except Exception:+ return (fallback,)++ if not isinstance(data, list):+ return (fallback,)++ options: list[ProviderModelOption] = []+ for raw in data:+ if not isinstance(raw, dict) or not isinstance(raw.get("id"), str):+ continue+ model_id = raw["id"]+ reasoning_modes = ("auto", *_deepseek_supported_reasoning_modes(model_id))+ options.append(+ ProviderModelOption(+ model=model_id,+ label=model_id,+ reasoning_modes=reasoning_modes,+ recommended=model_id == fallback_model,+ source="api",+ notes=(+ "reasoning controls documented for DeepSeek V4"+ if len(reasoning_modes) > 1+ else ""+ ),+ )+ )++ if not options:+ return (fallback,)++ return tuple(options)class DeepSeekProvider(BaseProvider):@@ -79,6 +175,8 @@ class DeepSeekProvider(BaseProvider):"No API key provided. Pass api_key= or set DEEPSEEK_API_KEY.",)resolved_base_url = base_url or os.environ.get("DEEPSEEK_BASE_URL") or _DEFAULT_BASE_URL+ self._api_key = resolved_key+ self._base_url = resolved_base_urlself._client = AsyncOpenAI(api_key=resolved_key,base_url=resolved_base_url,@@ -95,6 +193,12 @@ class DeepSeekProvider(BaseProvider):def model_name(self) -> str:return self._model+ def supported_reasoning_modes(self) -> tuple[ReasoningMode, ...]:+ return ("auto", *_deepseek_supported_reasoning_modes(self._model))++ def available_model_options(self) -> tuple[ProviderModelOption, ...]:+ return _deepseek_model_options(self._api_key, self._base_url, self._model)+async def generate(self,system_prompt: str,@@ -105,7 +209,7 @@ class DeepSeekProvider(BaseProvider):reasoning: ReasoningMode = "auto",cache_hints: tuple = (),) -> GeneratedResponse:- ensure_reasoning_supported("deepseek", self._model, reasoning)+ reasoning_mode = _resolve_deepseek_reasoning_mode(reasoning, model=self._model)if self._rate_limiter:await self._rate_limiter.acquire(estimated_tokens=max_tokens)@@ -123,6 +227,7 @@ class DeepSeekProvider(BaseProvider):max_tokens=max_tokens,temperature=temperature,request_id=request_id,+ reasoning=reasoning_mode,)except RetryError as exc:raise ProviderError(@@ -143,23 +248,24 @@ class DeepSeekProvider(BaseProvider):max_tokens: int,temperature: float,request_id: str | None,+ reasoning: ReasoningMode,) -> GeneratedResponse:try:- response = await self._client.chat.completions.create(- model=self._model,- max_tokens=max_tokens,- temperature=temperature,- messages=[+ kwargs: dict[str, Any] = {+ "model": self._model,+ "max_tokens": max_tokens,+ "temperature": temperature,+ "messages": [{"role": "system", "content": system_prompt},{"role": "user", "content": user_prompt},],- )+ }+ kwargs.update(_deepseek_reasoning_kwargs(reasoning))+ response = await self._client.chat.completions.create(**kwargs)except _OpenAIRateLimitError as exc:raise RateLimitError("deepseek", str(exc), status_code=429) from excexcept _OpenAIAPIStatusError as exc:- raise ProviderError(- "deepseek", str(exc), status_code=exc.status_code- ) from exc+ raise ProviderError("deepseek", str(exc), status_code=exc.status_code) from excusage = response.usageresult = GeneratedResponse(diff --git a/packages/core/src/repowise/core/providers/llm/gemini.py b/packages/core/src/repowise/core/providers/llm/gemini.pyindex 9ec38f490..c8f03ae27 100644--- a/packages/core/src/repowise/core/providers/llm/gemini.py+++ b/packages/core/src/repowise/core/providers/llm/gemini.py@@ -14,14 +14,10 @@ import asyncioimport contextlibimport loggingimport os+from collections.abc import AsyncIterator+from typing import TYPE_CHECKING, Anyimport structlog--# Suppress "Both GOOGLE_API_KEY and GEMINI_API_KEY are set" from google-genai SDK.-# We resolve and pass the key explicitly, so the env-var conflict warning is noise.-logging.getLogger("google_genai._api_client").setLevel(logging.ERROR)-from typing import TYPE_CHECKING, Any, AsyncIterator-from tenacity import (RetryError,retry,@@ -36,20 +32,156 @@ from repowise.core.providers.llm.base import (ChatToolCall,GeneratedResponse,ProviderError,+ ProviderModelOption,RateLimitError,ensure_reasoning_supported,+ fallback_model_option,)from repowise.core.rate_limiter import RateLimiter-from repowise.core.reasoning import ReasoningMode+from repowise.core.reasoning import ReasoningMode, normalize_reasoningif TYPE_CHECKING:from repowise.core.generation.cost_tracker import CostTracker+# Suppress "Both GOOGLE_API_KEY and GEMINI_API_KEY are set" from google-genai SDK.+# We resolve and pass the key explicitly, so the env-var conflict warning is noise.+logging.getLogger("google_genai._api_client").setLevel(logging.ERROR)+log = structlog.get_logger(__name__)_MAX_RETRIES = 3_MIN_WAIT = 1.0_MAX_WAIT = 4.0+_DEFAULT_MODELS_URL = "https://generativelanguage.googleapis.com/v1beta/models"+_GEMINI_THINKING_MODES: tuple[ReasoningMode, ...] = (+ "minimal",+ "low",+ "medium",+ "high",+)+_GEMINI_THINKING_MODELS_BY_BASE: dict[str, set[str]] = {}+++def _gemini_cache_key(base_url: str | None) -> str:+ return (base_url or _DEFAULT_MODELS_URL).rstrip("/")+++def _gemini_supported_reasoning_modes(+ model: str,+ *,+ base_url: str | None,+) -> tuple[ReasoningMode, ...]:+ if model in _GEMINI_THINKING_MODELS_BY_BASE.get(_gemini_cache_key(base_url), set()):+ return _GEMINI_THINKING_MODES+ return ()+++def _resolve_gemini_reasoning_mode(+ reasoning: ReasoningMode,+ *,+ model: str,+ base_url: str | None,+) -> ReasoningMode:+ return ensure_reasoning_supported(+ "gemini",+ model,+ normalize_reasoning(reasoning),+ _gemini_supported_reasoning_modes(model, base_url=base_url),+ detail=(+ "Gemini reasoning options are exposed only for models whose "+ "models.list entry advertises thinking support."+ ),+ )+++def _gemini_thinking_config(reasoning: ReasoningMode, genai_types: Any) -> object | None:+ mode = normalize_reasoning(reasoning)+ if mode == "auto":+ return None+ levels = {+ "minimal": genai_types.ThinkingLevel.MINIMAL,+ "low": genai_types.ThinkingLevel.LOW,+ "medium": genai_types.ThinkingLevel.MEDIUM,+ "high": genai_types.ThinkingLevel.HIGH,+ }+ return genai_types.ThinkingConfig(thinking_level=levels[mode])+++def _gemini_model_options(+ api_key: str,+ base_url: str | None,+ fallback_model: str,+) -> tuple[ProviderModelOption, ...]:+ fallback = fallback_model_option(fallback_model)+ try:+ import httpx++ url = f"{base_url.rstrip('/')}/models" if base_url else _DEFAULT_MODELS_URL+ models: list[dict[str, Any]] = []+ page_token: str | None = None+ while True:+ params: dict[str, str | int] = {"pageSize": 1000}+ if page_token:+ params["pageToken"] = page_token+ response = httpx.get(+ url,+ headers={"x-goog-api-key": api_key},+ params=params,+ timeout=5.0,+ )+ response.raise_for_status()+ payload = response.json()+ raw_models = payload.get("models", [])+ if isinstance(raw_models, list):+ models.extend(raw for raw in raw_models if isinstance(raw, dict))+ page_token = payload.get("nextPageToken")+ if not isinstance(page_token, str) or not page_token:+ break+ except Exception:+ return (fallback,)++ options: list[ProviderModelOption] = []+ thinking_models: set[str] = set()+ for raw in models:+ name = raw.get("name")+ if not isinstance(name, str):+ continue+ methods = raw.get("supportedGenerationMethods")+ if isinstance(methods, list) and "generateContent" not in methods:+ continue+ model_id = name.removeprefix("models/")+ display_name = raw.get("displayName")+ has_thinking = raw.get("thinking") is True+ if has_thinking:+ thinking_models.add(model_id)+ options.append(+ ProviderModelOption(+ model=model_id,+ label=display_name if isinstance(display_name, str) else model_id,+ reasoning_modes=(+ "auto",+ *_GEMINI_THINKING_MODES,+ )+ if has_thinking+ else ("auto",),+ recommended=model_id == fallback_model,+ source="api",+ notes=(+ "generateContent; thinking advertised by models.list"+ if has_thinking+ else "generateContent"+ ),+ )+ )++ if thinking_models:+ _GEMINI_THINKING_MODELS_BY_BASE[_gemini_cache_key(base_url)] = thinking_models++ if not options:+ return (fallback,)++ options.sort(key=lambda option: option.model)+ return tuple(options)class GeminiProvider(BaseProvider):@@ -69,13 +201,11 @@ class GeminiProvider(BaseProvider):api_key: str | None = None,base_url: str | None = None,rate_limiter: RateLimiter | None = None,- cost_tracker: "CostTracker | None" = None,+ cost_tracker: CostTracker | None = None,) -> None:self._model = modelself._api_key = (- api_key- or os.environ.get("GEMINI_API_KEY")- or os.environ.get("GOOGLE_API_KEY")+ api_key or os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY"))if not self._api_key:raise ProviderError(@@ -95,6 +225,18 @@ class GeminiProvider(BaseProvider):def model_name(self) -> str:return self._model+ def supported_reasoning_modes(self) -> tuple[ReasoningMode, ...]:+ return (+ "auto",+ *_gemini_supported_reasoning_modes(+ self._model,+ base_url=self._base_url,+ ),+ )++ def available_model_options(self) -> tuple[ProviderModelOption, ...]:+ return _gemini_model_options(self._api_key, self._base_url, self._model)+async def generate(self,system_prompt: str,@@ -105,7 +247,18 @@ class GeminiProvider(BaseProvider):reasoning: ReasoningMode = "auto",cache_hints: tuple = (),) -> GeneratedResponse:- ensure_reasoning_supported("gemini", self._model, reasoning)+ if normalize_reasoning(reasoning) != "auto" and not _gemini_supported_reasoning_modes(+ self._model,+ base_url=self._base_url,+ ):+ # available_model_options() does blocking, paginated HTTP discovery to+ # populate the thinking-model cache; keep it off the event loop.+ await asyncio.to_thread(self.available_model_options)+ reasoning_mode = _resolve_gemini_reasoning_mode(+ reasoning,+ model=self._model,+ base_url=self._base_url,+ )if self._rate_limiter:await self._rate_limiter.acquire(estimated_tokens=max_tokens)@@ -123,6 +276,7 @@ class GeminiProvider(BaseProvider):max_tokens=max_tokens,temperature=temperature,request_id=request_id,+ reasoning=reasoning_mode,)except RetryError as exc:raise ProviderError(@@ -143,6 +297,7 @@ class GeminiProvider(BaseProvider):max_tokens: int,temperature: float,request_id: str | None,+ reasoning: ReasoningMode,) -> GeneratedResponse:# Capture self attrs for thread safety (avoids closing over self)model = self._model@@ -179,16 +334,21 @@ class GeminiProvider(BaseProvider):self._client = genai.Client(**client_kwargs)client = self._clienttry:+ thinking_config = _gemini_thinking_config(reasoning, genai_types)+ config_kwargs: dict[str, Any] = {+ "system_instruction": system_prompt,+ "temperature": temperature,+ # max_output_tokens intentionally omitted — Gemini flash+ # models default to 65k tokens, which is far better for+ # documentation generation than any low cap we'd impose.+ }+ if thinking_config is not None:+ config_kwargs["thinking_config"] = thinking_config+response = client.models.generate_content(model=model,contents=user_prompt,- config=genai_types.GenerateContentConfig(- system_instruction=system_prompt,- temperature=temperature,- # max_output_tokens intentionally omitted — Gemini flash- # models default to 65k tokens, which is far better for- # documentation generation than any low cap we'd impose.- ),+ config=genai_types.GenerateContentConfig(**config_kwargs),)except Exception as exc:exc_str = str(exc)@@ -207,7 +367,9 @@ class GeminiProvider(BaseProvider):"prompt_token_count": getattr(usage, "prompt_token_count", 0) or 0,"candidates_token_count": getattr(usage, "candidates_token_count", 0) or 0,"total_token_count": getattr(usage, "total_token_count", 0) or 0,- } if usage else {},+ }+ if usage+ else {},)try:@@ -265,8 +427,6 @@ class GeminiProvider(BaseProvider):yielded and the caller must handle it (though this will fail onthe next round-trip due to missing thought signatures)."""- import json as _json-model_name = self._modelapi_key = self._api_keybase_url = self._base_url@@ -303,11 +463,13 @@ class GeminiProvider(BaseProvider):for t in tools:fn = t.get("function", t)params = fn.get("parameters", {})- declarations.append(genai_types.FunctionDeclaration(- name=fn["name"],- description=fn.get("description", ""),- parameters=params if params else None,- ))+ declarations.append(+ genai_types.FunctionDeclaration(+ name=fn["name"],+ description=fn.get("description", ""),+ parameters=params if params else None,+ )+ )gemini_tools = [genai_types.Tool(function_declarations=declarations)]config = genai_types.GenerateContentConfig(@@ -417,13 +579,17 @@ def _to_gemini_contents(messages: list[dict[str, Any]]) -> list:# Tool result → function_response partcontent_str = msg.get("content", "{}")try:- response_data = _json.loads(content_str) if isinstance(content_str, str) else content_str+ response_data = (+ _json.loads(content_str) if isinstance(content_str, str) else content_str+ )except Exception:response_data = {"result": content_str}- parts.append(genai_types.Part.from_function_response(- name=msg.get("name", "unknown"),- response=response_data,- ))+ parts.append(+ genai_types.Part.from_function_response(+ name=msg.get("name", "unknown"),+ response=response_data,+ )+ )gemini_role = "user"elif role == "assistant":text = msg.get("content")@@ -439,10 +605,12 @@ def _to_gemini_contents(messages: list[dict[str, Any]]) -> list:args = {}else:args = args_str- parts.append(genai_types.Part.from_function_call(- name=fn.get("name", ""),- args=args,- ))+ parts.append(+ genai_types.Part.from_function_call(+ name=fn.get("name", ""),+ args=args,+ )+ )else:parts.append(genai_types.Part.from_text(text=msg.get("content", "")))diff --git a/packages/core/src/repowise/core/providers/llm/litellm.py b/packages/core/src/repowise/core/providers/llm/litellm.pyindex 22eaf7c45..064f29938 100644--- a/packages/core/src/repowise/core/providers/llm/litellm.py+++ b/packages/core/src/repowise/core/providers/llm/litellm.py@@ -21,7 +21,8 @@ from __future__ import annotationsimport contextlibimport os-from typing import TYPE_CHECKING, Any, AsyncIterator+from collections.abc import AsyncIterator+from typing import TYPE_CHECKING, Anyimport structlogfrom tenacity import (@@ -38,11 +39,13 @@ from repowise.core.providers.llm.base import (ChatToolCall,GeneratedResponse,ProviderError,+ ProviderModelOption,RateLimitError,ensure_reasoning_supported,+ fallback_model_option,)from repowise.core.rate_limiter import RateLimiter-from repowise.core.reasoning import ReasoningMode+from repowise.core.reasoning import ReasoningMode, normalize_reasoningif TYPE_CHECKING:from repowise.core.generation.cost_tracker import CostTracker@@ -52,6 +55,81 @@ log = structlog.get_logger(__name__)_MAX_RETRIES = 3_MIN_WAIT = 1.0_MAX_WAIT = 4.0+_LITELLM_REASONING_MODES: tuple[ReasoningMode, ...] = ("low", "medium", "high")+++def _litellm_supports_reasoning(model: str) -> bool:+ try:+ import litellm # type: ignore[import-untyped]++ return bool(litellm.supports_reasoning(model=model))+ except Exception:+ return False+++def _litellm_supported_reasoning_modes(model: str) -> tuple[ReasoningMode, ...]:+ if _litellm_supports_reasoning(model):+ return _LITELLM_REASONING_MODES+ return ()+++def _litellm_reasoning_kwargs(reasoning: ReasoningMode) -> dict[str, object]:+ mode = normalize_reasoning(reasoning)+ if mode == "auto":+ return {}+ return {"reasoning_effort": mode}+++def _litellm_model_options(fallback_model: str) -> tuple[ProviderModelOption, ...]:+ fallback = fallback_model_option(+ fallback_model,+ reasoning_modes=("auto", *_litellm_supported_reasoning_modes(fallback_model)),+ )+ try:+ import litellm # type: ignore[import-untyped]++ model_ids = sorted(+ {+ model+ for model in getattr(litellm, "model_list", []) or []+ if isinstance(model, str) and model+ }+ )+ except Exception:+ return (fallback,)++ if not model_ids:+ return (fallback,)++ options: list[ProviderModelOption] = []+ for model_id in model_ids:+ try:+ supports_reasoning = bool(litellm.supports_reasoning(model=model_id))+ except Exception:+ supports_reasoning = False+ reasoning_modes = (+ (+ "auto",+ *_LITELLM_REASONING_MODES,+ )+ if supports_reasoning+ else ("auto",)+ )+ notes = ""+ if supports_reasoning:+ notes = "LiteLLM reports reasoning support"+ options.append(+ ProviderModelOption(+ model=model_id,+ label=model_id,+ reasoning_modes=reasoning_modes,+ recommended=model_id == fallback_model,+ source="local",+ notes=notes,+ )+ )++ return tuple(options)class LiteLLMProvider(BaseProvider):@@ -73,7 +151,7 @@ class LiteLLMProvider(BaseProvider):api_base: str | None = None,base_url: str | None = None,rate_limiter: RateLimiter | None = None,- cost_tracker: "CostTracker | None" = None,+ cost_tracker: CostTracker | None = None,) -> None:self._model = modelself._api_key = api_key@@ -94,6 +172,12 @@ class LiteLLMProvider(BaseProvider):def model_name(self) -> str:return self._model+ def supported_reasoning_modes(self) -> tuple[ReasoningMode, ...]:+ return ("auto", *_litellm_supported_reasoning_modes(self._model))++ def available_model_options(self) -> tuple[ProviderModelOption, ...]:+ return _litellm_model_options(self._model)+async def generate(self,system_prompt: str,@@ -104,7 +188,13 @@ class LiteLLMProvider(BaseProvider):reasoning: ReasoningMode = "auto",cache_hints: tuple = (),) -> GeneratedResponse:- ensure_reasoning_supported("litellm", self._model, reasoning)+ reasoning_mode = ensure_reasoning_supported(+ "litellm",+ self._model,+ reasoning,+ _litellm_supported_reasoning_modes(self._model),+ detail="LiteLLM reasoning support comes from litellm.supports_reasoning().",+ )if self._rate_limiter:await self._rate_limiter.acquire(estimated_tokens=max_tokens)@@ -115,6 +205,7 @@ class LiteLLMProvider(BaseProvider):max_tokens=max_tokens,temperature=temperature,request_id=request_id,+ reasoning=reasoning_mode,)except RetryError as exc:raise ProviderError(@@ -135,6 +226,7 @@ class LiteLLMProvider(BaseProvider):max_tokens: int,temperature: float,request_id: str | None,+ reasoning: ReasoningMode,) -> GeneratedResponse:# Import litellm lazily — it's a large package and only needed at call timeimport litellm # type: ignore[import-untyped]@@ -156,6 +248,7 @@ class LiteLLMProvider(BaseProvider):call_kwargs["api_key"] = self._api_keyif self._api_base:call_kwargs["api_base"] = self._api_base+ call_kwargs.update(_litellm_reasoning_kwargs(reasoning))try:response = await litellm.acompletion(**call_kwargs)@@ -259,7 +352,11 @@ class LiteLLMProvider(BaseProvider):for tc_delta in delta.tool_calls:idx = tc_delta.indexif idx not in tool_calls_acc:- tool_calls_acc[idx] = {"id": getattr(tc_delta, "id", "") or "", "name": "", "arguments": ""}+ tool_calls_acc[idx] = {+ "id": getattr(tc_delta, "id", "") or "",+ "name": "",+ "arguments": "",+ }acc = tool_calls_acc[idx]if getattr(tc_delta, "id", None):acc["id"] = tc_delta.iddiff --git a/packages/core/src/repowise/core/providers/llm/ollama.py b/packages/core/src/repowise/core/providers/llm/ollama.pyindex ac89d03ad..c9d2df15f 100644--- a/packages/core/src/repowise/core/providers/llm/ollama.py+++ b/packages/core/src/repowise/core/providers/llm/ollama.py@@ -21,7 +21,8 @@ Usage:from __future__ import annotationsimport os-from typing import Any, AsyncIterator+from collections.abc import AsyncIterator+from typing import Anyimport structlogfrom openai import APIStatusError as _OpenAIAPIStatusError@@ -40,7 +41,9 @@ from repowise.core.providers.llm.base import (ChatToolCall,GeneratedResponse,ProviderError,+ ProviderModelOption,ensure_reasoning_supported,+ fallback_model_option,)from repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode@@ -62,6 +65,58 @@ def _normalize_base_url(url: str) -> str:return url+def _ollama_model_options(+ base_url: str,+ fallback_model: str,+) -> tuple[ProviderModelOption, ...]:+ fallback = fallback_model_option(fallback_model)+ try:+ import httpx++ response = httpx.get(+ f"{base_url.rstrip('/')}/api/tags",+ timeout=5.0,+ )+ response.raise_for_status()+ data = response.json().get("models", [])+ except Exception:+ return (fallback,)++ if not isinstance(data, list):+ return (fallback,)++ options: list[ProviderModelOption] = []+ for raw in data:+ if not isinstance(raw, dict):+ continue+ model_id = raw.get("name") or raw.get("model")+ if not isinstance(model_id, str) or not model_id:+ continue+ details = raw.get("details")+ notes = ""+ if isinstance(details, dict):+ family = details.get("family")+ params = details.get("parameter_size")+ parts = [part for part in (family, params) if isinstance(part, str)]+ notes = ", ".join(parts) or notes+ options.append(+ ProviderModelOption(+ model=model_id,+ label=model_id,+ reasoning_modes=("auto",),+ recommended=model_id == fallback_model,+ source="local",+ notes=notes,+ )+ )++ if not options:+ return (fallback,)++ options.sort(key=lambda option: option.model)+ return tuple(options)++class OllamaProvider(BaseProvider):"""Ollama provider for local, offline LLM inference.@@ -83,7 +138,10 @@ class OllamaProvider(BaseProvider):rate_limiter: RateLimiter | None = None,) -> None:resolved_base_url = base_url or os.environ.get("OLLAMA_BASE_URL") or _DEFAULT_BASE_URL- self._client = AsyncOpenAI(api_key="ollama", base_url=_normalize_base_url(resolved_base_url))+ self._base_url = resolved_base_url.rstrip("/")+ self._client = AsyncOpenAI(+ api_key="ollama", base_url=_normalize_base_url(resolved_base_url)+ )self._model = modelself._rate_limiter = rate_limiter@@ -95,6 +153,9 @@ class OllamaProvider(BaseProvider):def model_name(self) -> str:return self._model+ def available_model_options(self) -> tuple[ProviderModelOption, ...]:+ return _ollama_model_options(self._base_url, self._model)+async def generate(self,system_prompt: str,@@ -155,9 +216,7 @@ class OllamaProvider(BaseProvider):],)except _OpenAIAPIStatusError as exc:- raise ProviderError(- "ollama", str(exc), status_code=exc.status_code- ) from exc+ raise ProviderError("ollama", str(exc), status_code=exc.status_code) from excusage = response.usageresult = GeneratedResponse(@@ -227,7 +286,11 @@ class OllamaProvider(BaseProvider):for tc_delta in delta.tool_calls:idx = tc_delta.indexif idx not in tool_calls_acc:- tool_calls_acc[idx] = {"id": tc_delta.id or "", "name": "", "arguments": ""}+ tool_calls_acc[idx] = {+ "id": tc_delta.id or "",+ "name": "",+ "arguments": "",+ }acc = tool_calls_acc[idx]if tc_delta.id:acc["id"] = tc_delta.iddiff --git a/packages/core/src/repowise/core/providers/llm/openai.py b/packages/core/src/repowise/core/providers/llm/openai.pyindex f9d5f409e..0ed5eea13 100644--- a/packages/core/src/repowise/core/providers/llm/openai.py+++ b/packages/core/src/repowise/core/providers/llm/openai.py@@ -14,7 +14,8 @@ from __future__ import annotationsimport contextlibimport os-from typing import TYPE_CHECKING, Any, AsyncIterator+from collections.abc import AsyncIterator+from typing import TYPE_CHECKING, Anyimport structlogfrom openai import APIStatusError as _OpenAIAPIStatusError@@ -35,8 +36,10 @@ from repowise.core.providers.llm.base import (ChatToolCall,GeneratedResponse,ProviderError,+ ProviderModelOption,RateLimitError,ensure_reasoning_supported,+ fallback_model_option,)from repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode, normalize_reasoning@@ -50,8 +53,20 @@ _MAX_RETRIES = 3_MIN_WAIT = 1.0_MAX_WAIT = 4.0_QWEN_THINKING_MODEL_MARKERS = ("qwen", "qwq")-_OPENAI_MINIMAL_REASONING_EXACT_MODELS = ("gpt-5", "gpt-5-mini", "gpt-5-nano")-_OPENAI_MINIMAL_REASONING_PREFIXES = ("gpt-5-mini-", "gpt-5-nano-")+_OPENAI_TEXT_MODEL_PREFIXES = ("gpt-", "o1", "o3", "o4")+_OPENAI_NON_TEXT_MARKERS = (+ "audio",+ "babbage",+ "dall-e",+ "davinci",+ "embedding",+ "image",+ "moderation",+ "sora",+ "tts",+ "transcribe",+ "whisper",+)def _model_leaf(model: str) -> str:@@ -60,11 +75,7 @@ def _model_leaf(model: str) -> str:def _supports_openai_reasoning_effort(model: str) -> bool:leaf = _model_leaf(model)- # Keep this conservative: dotted, pro, codex, and future aliases do not all- # accept the same Chat Completions reasoning_effort values.- return leaf in _OPENAI_MINIMAL_REASONING_EXACT_MODELS or leaf.startswith(- _OPENAI_MINIMAL_REASONING_PREFIXES- )+ return leaf.startswith(("gpt-5", "o1", "o3", "o4"))def _supports_chat_template_thinking_toggle(model: str) -> bool:@@ -73,17 +84,24 @@ def _supports_chat_template_thinking_toggle(model: str) -> bool:def _openai_supported_reasoning_modes(model: str) -> tuple[ReasoningMode, ...]:- modes: list[ReasoningMode] = []- if _supports_openai_reasoning_effort(model):- modes.append("minimal")if _supports_chat_template_thinking_toggle(model):- modes.append("off")- return tuple(modes)-+ return ("off", "none")+ if not _supports_openai_reasoning_effort(model):+ return ()-def _resolve_openai_reasoning_mode(- reasoning: ReasoningMode, *, model: str-) -> ReasoningMode:+ leaf = _model_leaf(model)+ if "codex-max" in leaf:+ return ("none", "medium", "high", "xhigh")+ if leaf.startswith("gpt-5.1"):+ return ("none", "low", "medium", "high")+ if leaf.startswith("gpt-5-pro"):+ return ("high",)+ if leaf.startswith("gpt-5"):+ return ("minimal", "low", "medium", "high")+ return ("low", "medium", "high")+++def _resolve_openai_reasoning_mode(reasoning: ReasoningMode, *, model: str) -> ReasoningMode:"""Validate OpenAI-compatible reasoning support before retry handling."""return ensure_reasoning_supported("openai",@@ -91,28 +109,99 @@ def _resolve_openai_reasoning_mode(normalize_reasoning(reasoning),_openai_supported_reasoning_modes(model),detail=(- "OpenAIProvider maps minimal to OpenAI reasoning_effort only for "- "known compatible OpenAI model ids (gpt-5, gpt-5-mini, "- "gpt-5-nano, and mini/nano snapshot ids), and maps off to "- "Qwen/QwQ chat_template_kwargs for OpenAI-compatible endpoints."+ "OpenAIProvider maps explicit efforts to OpenAI reasoning_effort "+ "for known reasoning model ids, and maps off/none to Qwen/QwQ "+ "chat_template_kwargs for OpenAI-compatible endpoints."),)-def _openai_reasoning_kwargs(reasoning: ReasoningMode) -> dict[str, Any]:+def _openai_reasoning_kwargs(reasoning: ReasoningMode, *, model: str) -> dict[str, Any]:"""Translate a validated repowise reasoning intent to OpenAI kwargs."""mode = normalize_reasoning(reasoning)if mode == "auto":return {}- if mode == "minimal":- return {"reasoning_effort": "minimal"}- return {- "extra_body": {- "chat_template_kwargs": {- "enable_thinking": False,+ if _supports_chat_template_thinking_toggle(model) and mode in ("off", "none"):+ return {+ "extra_body": {+ "chat_template_kwargs": {+ "enable_thinking": False,+ },},- },- }+ }+ if mode == "off":+ return {}+ if mode in ("none", "minimal", "low", "medium", "high", "xhigh"):+ return {"reasoning_effort": mode}+ return {}+++def _is_openai_text_model(model_id: str) -> bool:+ leaf = _model_leaf(model_id)+ if any(marker in leaf for marker in _OPENAI_NON_TEXT_MARKERS):+ return False+ return leaf.startswith(_OPENAI_TEXT_MODEL_PREFIXES)+++def _openai_option(+ model_id: str,+ *,+ fallback_model: str,+) -> ProviderModelOption:+ reasoning_modes = ("auto", *_openai_supported_reasoning_modes(model_id))+ notes = (+ "reasoning levels inferred; OpenAI /models does not advertise them"+ if len(reasoning_modes) > 1+ else ""+ )+ return ProviderModelOption(+ model=model_id,+ label=model_id,+ reasoning_modes=reasoning_modes,+ recommended=model_id == fallback_model,+ source="api",+ notes=notes,+ )+++def _openai_model_options(+ api_key: str,+ base_url: str,+ fallback_model: str,+) -> tuple[ProviderModelOption, ...]:+ fallback = fallback_model_option(+ fallback_model,+ reasoning_modes=("auto", *_openai_supported_reasoning_modes(fallback_model)),+ )+ try:+ import httpx++ response = httpx.get(+ f"{base_url.rstrip('/')}/models",+ headers={"Authorization": f"Bearer {api_key}"},+ timeout=5.0,+ )+ response.raise_for_status()+ data = response.json().get("data", [])+ except Exception:+ return (fallback,)++ if not isinstance(data, list):+ return (fallback,)++ model_ids = sorted(+ {+ model["id"]+ for model in data+ if isinstance(model, dict)+ and isinstance(model.get("id"), str)+ and _is_openai_text_model(model["id"])+ }+ )+ if not model_ids:+ return (fallback,)++ return tuple(_openai_option(model_id, fallback_model=fallback_model) for model_id in model_ids)class OpenAIProvider(BaseProvider):@@ -131,7 +220,7 @@ class OpenAIProvider(BaseProvider):model: str = "gpt-5.4-nano",base_url: str | None = None,rate_limiter: RateLimiter | None = None,- cost_tracker: "CostTracker | None" = None,+ cost_tracker: CostTracker | None = None,) -> None:resolved_key = api_key or os.environ.get("OPENAI_API_KEY")if not resolved_key:@@ -140,6 +229,8 @@ class OpenAIProvider(BaseProvider):"No API key provided. Pass api_key= or set OPENAI_API_KEY.",)resolved_base_url = base_url or os.environ.get("OPENAI_BASE_URL")+ self._api_key = resolved_key+ self._base_url = resolved_base_url or "https://api.openai.com/v1"self._client = AsyncOpenAI(api_key=resolved_key, base_url=resolved_base_url)self._model = modelself._rate_limiter = rate_limiter@@ -153,6 +244,12 @@ class OpenAIProvider(BaseProvider):def model_name(self) -> str:return self._model+ def supported_reasoning_modes(self) -> tuple[ReasoningMode, ...]:+ return ("auto", *_openai_supported_reasoning_modes(self._model))++ def available_model_options(self) -> tuple[ProviderModelOption, ...]:+ return _openai_model_options(self._api_key, self._base_url, self._model)+async def generate(self,system_prompt: str,@@ -166,9 +263,7 @@ class OpenAIProvider(BaseProvider):# OpenAI auto-caches stable prompt prefixes >= 1024 tokens; hints are# informational only, so we accept and discard them.del cache_hints- reasoning_mode = _resolve_openai_reasoning_mode(- reasoning, model=self._model- )+ reasoning_mode = _resolve_openai_reasoning_mode(reasoning, model=self._model)if self._rate_limiter:await self._rate_limiter.acquire(estimated_tokens=max_tokens)@@ -219,16 +314,14 @@ class OpenAIProvider(BaseProvider):{"role": "user", "content": user_prompt},],}- kwargs.update(_openai_reasoning_kwargs(reasoning))+ kwargs.update(_openai_reasoning_kwargs(reasoning, model=self._model))response = await self._client.chat.completions.create(**kwargs,)except _OpenAIRateLimitError as exc:raise RateLimitError("openai", str(exc), status_code=429) from excexcept _OpenAIAPIStatusError as exc:- raise ProviderError(- "openai", str(exc), status_code=exc.status_code- ) from exc+ raise ProviderError("openai", str(exc), status_code=exc.status_code) from excusage = response.usagecached = 0diff --git a/packages/core/src/repowise/core/providers/llm/openrouter.py b/packages/core/src/repowise/core/providers/llm/openrouter.pyindex 3b31f8d67..0c25c7b08 100644--- a/packages/core/src/repowise/core/providers/llm/openrouter.py+++ b/packages/core/src/repowise/core/providers/llm/openrouter.py@@ -14,7 +14,8 @@ Popular models:from __future__ import annotationsimport os-from typing import TYPE_CHECKING, Any, AsyncIterator+from collections.abc import AsyncIterator+from typing import TYPE_CHECKING, Anyimport structlogfrom openai import APIStatusError as _OpenAIAPIStatusError@@ -34,8 +35,10 @@ from repowise.core.providers.llm.base import (ChatToolCall,GeneratedResponse,ProviderError,+ ProviderModelOption,RateLimitError,ensure_reasoning_supported,+ fallback_model_option,)from repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode, normalize_reasoning@@ -48,46 +51,52 @@ log = structlog.get_logger(__name__)_MAX_RETRIES = 3_MIN_WAIT = 1.0_MAX_WAIT = 4.0-_OPENROUTER_OPENAI_REASONING_PREFIXES = ("o1", "o3", "o4")-_OPENROUTER_OPENAI_GPT5_EXACT_MODELS = ("gpt-5", "gpt-5-mini", "gpt-5-nano")-_OPENROUTER_OPENAI_GPT5_PREFIXES = ("gpt-5-mini-", "gpt-5-nano-")---def _model_leaf(model: str) -> str:- return model.rsplit("/", 1)[-1].lower()+_OPENROUTER_REASONING_MODES: tuple[ReasoningMode, ...] = (+ "off",+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+)+_OPENROUTER_REASONING_MODELS_BY_BASE: dict[str, set[str]] = {}-def _openrouter_supports_reasoning_effort(model: str) -> bool:- normalized = model.lower()- leaf = _model_leaf(model)- if normalized.startswith(("x-ai/grok", "xai/grok")):- return True- if normalized.startswith("openai/"):- if leaf.startswith(_OPENROUTER_OPENAI_REASONING_PREFIXES):- return True- if leaf in _OPENROUTER_OPENAI_GPT5_EXACT_MODELS:- return True- if leaf.startswith(_OPENROUTER_OPENAI_GPT5_PREFIXES):+def _openrouter_supports_reasoning_effort(+ model: str,+ *,+ base_url: str | None = None,+) -> bool:+ if base_url:+ cached_models = _OPENROUTER_REASONING_MODELS_BY_BASE.get(base_url.rstrip("/"))+ if cached_models is not None and model in cached_models:return Truereturn False+def _openrouter_supported_reasoning_modes(+ model: str,+ *,+ base_url: str | None = None,+) -> tuple[ReasoningMode, ...]:+ if not _openrouter_supports_reasoning_effort(model, base_url=base_url):+ return ()+ return _OPENROUTER_REASONING_MODES++def _resolve_openrouter_reasoning_mode(- reasoning: ReasoningMode, *, model: str+ reasoning: ReasoningMode, *, model: str, base_url: str | None = None) -> ReasoningMode:"""Validate OpenRouter reasoning support before retry handling."""- supported_modes: tuple[ReasoningMode, ...] = (- ("off", "minimal") if _openrouter_supports_reasoning_effort(model) else ()- )return ensure_reasoning_supported("openrouter",model,normalize_reasoning(reasoning),- supported_modes,+ _openrouter_supported_reasoning_modes(model, base_url=base_url),detail=(- "OpenRouter maps reasoning.effort for OpenAI reasoning and Grok "- "model families with known effort support. Unknown, dotted, and "- "pro GPT-5 routes fail fast until explicitly mapped."+ "OpenRouter reasoning support is taken from models whose /models "+ "entry advertises the reasoning parameter."),)@@ -97,15 +106,84 @@ def _openrouter_reasoning_kwargs(reasoning: ReasoningMode) -> dict[str, Any]:mode = normalize_reasoning(reasoning)if mode == "auto":return {}+ effort = "none" if mode in ("off", "none") else modereturn {"extra_body": {"reasoning": {- "effort": "none" if mode == "off" else "minimal",+ "effort": effort,}}}+def _openrouter_model_options(+ api_key: str,+ base_url: str,+ fallback_model: str,+) -> tuple[ProviderModelOption, ...]:+ fallback = fallback_model_option(+ fallback_model,+ reasoning_modes=(+ "auto",+ *_openrouter_supported_reasoning_modes(fallback_model, base_url=base_url),+ ),+ )+ try:+ import httpx++ response = httpx.get(+ f"{base_url.rstrip('/')}/models",+ headers={"Authorization": f"Bearer {api_key}"},+ timeout=5.0,+ )+ response.raise_for_status()+ data = response.json().get("data", [])+ except Exception:+ return (fallback,)++ if not isinstance(data, list):+ return (fallback,)++ base_key = base_url.rstrip("/")+ reasoning_models: set[str] = set()+ options: list[ProviderModelOption] = []+ for raw in data:+ if not isinstance(raw, dict) or not isinstance(raw.get("id"), str):+ continue+ model_id = raw["id"]+ supported_parameters = raw.get("supported_parameters")+ has_reasoning = (+ isinstance(supported_parameters, list) and "reasoning" in supported_parameters+ )+ if has_reasoning:+ reasoning_models.add(model_id)+ display_name = raw.get("name")+ reasoning_modes = (+ _OPENROUTER_REASONING_MODES+ if has_reasoning+ else _openrouter_supported_reasoning_modes(model_id)+ )+ options.append(+ ProviderModelOption(+ model=model_id,+ label=display_name if isinstance(display_name, str) else model_id,+ reasoning_modes=("auto", *reasoning_modes),+ recommended=model_id == fallback_model,+ source="api",+ notes=("reasoning parameter advertised by /models" if has_reasoning else ""),+ )+ )++ if reasoning_models:+ _OPENROUTER_REASONING_MODELS_BY_BASE[base_key] = reasoning_models++ if not options:+ return (fallback,)++ options.sort(key=lambda option: option.model)+ return tuple(options)++class OpenRouterProvider(BaseProvider):"""OpenRouter provider — access 200+ models via a single API key.@@ -131,7 +209,7 @@ class OpenRouterProvider(BaseProvider):rate_limiter: RateLimiter | None = None,http_referer: str | None = None,app_title: str = "repowise",- cost_tracker: "CostTracker | None" = None,+ cost_tracker: CostTracker | None = None,) -> None:resolved_key = api_key or os.environ.get("OPENROUTER_API_KEY")if not resolved_key:@@ -146,6 +224,8 @@ class OpenRouterProvider(BaseProvider):if app_title:headers["X-Title"] = app_title+ self._api_key = resolved_key+ self._base_url = base_url.rstrip("/")self._client = AsyncOpenAI(api_key=resolved_key,base_url=base_url,@@ -162,6 +242,18 @@ class OpenRouterProvider(BaseProvider):def model_name(self) -> str:return self._model+ def supported_reasoning_modes(self) -> tuple[ReasoningMode, ...]:+ return (+ "auto",+ *_openrouter_supported_reasoning_modes(+ self._model,+ base_url=self._base_url,+ ),+ )++ def available_model_options(self) -> tuple[ProviderModelOption, ...]:+ return _openrouter_model_options(self._api_key, self._base_url, self._model)+async def generate(self,system_prompt: str,@@ -172,8 +264,13 @@ class OpenRouterProvider(BaseProvider):reasoning: ReasoningMode = "auto",cache_hints: tuple = (),) -> GeneratedResponse:+ if normalize_reasoning(reasoning) != "auto" and not _openrouter_supported_reasoning_modes(+ self._model,+ base_url=self._base_url,+ ):+ self.available_model_options()reasoning_mode = _resolve_openrouter_reasoning_mode(- reasoning, model=self._model+ reasoning, model=self._model, base_url=self._base_url)if self._rate_limiter:await self._rate_limiter.acquire(estimated_tokens=max_tokens)@@ -230,9 +327,7 @@ class OpenRouterProvider(BaseProvider):except _OpenAIRateLimitError as exc:raise RateLimitError("openrouter", str(exc), status_code=429) from excexcept _OpenAIAPIStatusError as exc:- raise ProviderError(- "openrouter", str(exc), status_code=exc.status_code- ) from exc+ raise ProviderError("openrouter", str(exc), status_code=exc.status_code) from excusage = response.usageresult = GeneratedResponse(diff --git a/packages/core/src/repowise/core/providers/llm/registry.py b/packages/core/src/repowise/core/providers/llm/registry.pyindex ac9603f13..8b2699ffd 100644--- a/packages/core/src/repowise/core/providers/llm/registry.py+++ b/packages/core/src/repowise/core/providers/llm/registry.py@@ -11,6 +11,7 @@ Built-in providers:- deepseek → DeepSeekProvider- ollama → OllamaProvider- litellm → LiteLLMProvider+ - codex_cli → CodexCliProvider- mock → MockProvider (testing only)Custom provider registration:@@ -26,7 +27,8 @@ Custom provider registration:from __future__ import annotationsimport importlib-from typing import Any, Callable+from collections.abc import Callable+from typing import Anyfrom repowise.core.providers.llm.base import BaseProviderfrom repowise.core.rate_limiter import PROVIDER_DEFAULTS, RateLimitConfig, RateLimiter@@ -43,6 +45,7 @@ _BUILTIN_PROVIDERS: dict[str, tuple[str, str]] = {"ollama": ("repowise.core.providers.llm.ollama", "OllamaProvider"),"litellm": ("repowise.core.providers.llm.litellm", "LiteLLMProvider"),"deepseek": ("repowise.core.providers.llm.deepseek", "DeepSeekProvider"),+ "codex_cli": ("repowise.core.providers.llm.codex_cli", "CodexCliProvider"),"mock": ("repowise.core.providers.llm.mock", "MockProvider"),}@@ -117,13 +120,10 @@ def get_provider(if name not in _BUILTIN_PROVIDERS:available = sorted(set(_BUILTIN_PROVIDERS) | set(_custom_providers))- raise ValueError(- f"Unknown provider: {name!r}. "- f"Available providers: {available}"- )+ raise ValueError(f"Unknown provider: {name!r}. Available providers: {available}")# Attach rate limiter (skip for mock — tests should run without limits)- if with_rate_limiter and name != "mock":+ if with_rate_limiter and name not in ("mock", "codex_cli"):config = rate_limit_config or PROVIDER_DEFAULTS.get(name)if config and "rate_limiter" not in kwargs:kwargs["rate_limiter"] = RateLimiter(config)@@ -141,6 +141,7 @@ def get_provider("openrouter": "openai", # openrouter uses the openai package"deepseek": "openai", # deepseek uses the openai package"litellm": "litellm",+ "codex_cli": "@openai/codex",}package = _missing.get(name, name)raise ImportError(diff --git a/packages/core/src/repowise/core/reasoning.py b/packages/core/src/repowise/core/reasoning.pyindex c4cf5213b..043ac694d 100644--- a/packages/core/src/repowise/core/reasoning.py+++ b/packages/core/src/repowise/core/reasoning.py@@ -5,8 +5,28 @@ from __future__ import annotationsimport osfrom typing import Literal, cast-ReasoningMode = Literal["auto", "off", "minimal"]-REASONING_MODES: tuple[ReasoningMode, ...] = ("auto", "off", "minimal")+ReasoningMode = Literal[+ "auto",+ "off",+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+]+REASONING_MODES: tuple[ReasoningMode, ...] = (+ "auto",+ "off",+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+)def normalize_reasoning(@@ -16,7 +36,7 @@ def normalize_reasoning() -> ReasoningMode:"""Normalize a user/config supplied reasoning mode.- ``auto`` preserves provider defaults. ``off`` and ``minimal`` are provider+ ``auto`` preserves provider defaults. The remaining values are portableintents; each provider decides whether and how to translate them."""if value is None:diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonnew file mode 100644index 000000000..8246ad5c0--- /dev/null+++ b/plugins/codex/.codex-plugin/plugin.json@@ -0,0 +1,45 @@+{+ "name": "codex",+ "version": "0.1.0",+ "description": "Repowise codebase intelligence for Codex.",+ "author": {+ "name": "Repowise",+ "email": "[email protected]",+ "url": "https://repowise.dev"+ },+ "homepage": "https://repowise.dev",+ "repository": "https://github.com/repowise-dev/repowise",+ "license": "AGPL-3.0-only",+ "keywords": [+ "codebase",+ "documentation",+ "architecture",+ "mcp",+ "codex",+ "graph",+ "git"+ ],+ "skills": "./skills/",+ "hooks": "./hooks/hooks.json",+ "mcpServers": "./.mcp.json",+ "interface": {+ "displayName": "Repowise",+ "shortDescription": "Codebase wiki, graph, git signals, and decisions for Codex.",+ "longDescription": "Adds Repowise MCP tools, lifecycle hooks, and focused skills so Codex can explore indexed repositories, assess edit risk, recover design rationale, and plan cleanup work.",+ "developerName": "Repowise",+ "category": "Productivity",+ "capabilities": [+ "Read",+ "MCP",+ "Hooks",+ "Skills"+ ],+ "websiteURL": "https://repowise.dev",+ "defaultPrompt": [+ "Explain this repository with Repowise.",+ "Find risk before changing this module.",+ "Identify safe dead-code cleanup candidates."+ ],+ "brandColor": "#2563EB"+ }+}diff --git a/plugins/codex/.mcp.json b/plugins/codex/.mcp.jsonnew file mode 100644index 000000000..7d691343f--- /dev/null+++ b/plugins/codex/.mcp.json@@ -0,0 +1,9 @@+{+ "repowise": {+ "command": "repowise",+ "args": [+ "mcp"+ ],+ "startup_timeout_sec": 20+ }+}diff --git a/plugins/codex/hooks/hooks.json b/plugins/codex/hooks/hooks.jsonnew file mode 100644index 000000000..e0f4826d0--- /dev/null+++ b/plugins/codex/hooks/hooks.json@@ -0,0 +1,53 @@+{+ "hooks": {+ "SessionStart": [+ {+ "matcher": "startup|resume|clear",+ "hooks": [+ {+ "type": "command",+ "command": "repowise-augment --client codex",+ "timeout": 30,+ "statusMessage": "Loading repowise context..."+ }+ ]+ }+ ],+ "UserPromptSubmit": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "repowise-augment --client codex",+ "timeout": 30,+ "statusMessage": "Loading repowise context..."+ }+ ]+ }+ ],+ "PostToolUse": [+ {+ "matcher": "Bash",+ "hooks": [+ {+ "type": "command",+ "command": "repowise-augment --client codex",+ "timeout": 30,+ "statusMessage": "Checking repowise freshness..."+ }+ ]+ },+ {+ "matcher": "apply_patch|Edit|Write",+ "hooks": [+ {+ "type": "command",+ "command": "repowise-augment --client codex",+ "timeout": 30,+ "statusMessage": "Checking repowise freshness..."+ }+ ]+ }+ ]+ }+}diff --git a/plugins/codex/skills/architectural-decisions/SKILL.md b/plugins/codex/skills/architectural-decisions/SKILL.mdnew file mode 100644index 000000000..9808c49b0--- /dev/null+++ b/plugins/codex/skills/architectural-decisions/SKILL.md@@ -0,0 +1,30 @@+---+name: architectural-decisions+description: Use when a task asks why code is built a certain way, proposes architectural changes, compares implementation approaches, or mentions decision markers such as WHY, DECISION, TRADEOFF, or ADR in a Repowise-indexed repository.+---++# Architectural Decisions With Repowise++Repowise captures architectural decisions: the rationale behind how code is built.++## When The User Asks Why Something Exists++Call `get_why(query="specific area or decision")` to search captured decisions. This covers inline decision markers, git-derived rationale, and decisions mined from documentation.++## Before Architectural Changes++1. Call `get_why(query="the area being changed")` before introducing new patterns, restructuring modules, replacing infrastructure, or choosing between approaches.+2. If decisions are found, summarize the relevant rationale and tradeoffs before editing.+3. If no decision is found, state that no recorded decision governs the area and continue with normal source inspection.++## When No Specific Query Exists++Call `get_why()` to inspect decision health: stale decisions, conflicts, and ungoverned hotspots.++## When Decision Markers Appear In Code++If a file contains `WHY:`, `DECISION:`, `TRADEOFF:`, or `ADR:`, call `get_context(targets=["path/to/file"])` to retrieve the full file context and related decisions.++## Recording New Decisions++When the user makes a new architectural decision, suggest recording it with a `DECISION:` comment in the relevant code or with `repowise decision add`.diff --git a/plugins/codex/skills/codebase-exploration/SKILL.md b/plugins/codex/skills/codebase-exploration/SKILL.mdnew file mode 100644index 000000000..22fc1b759--- /dev/null+++ b/plugins/codex/skills/codebase-exploration/SKILL.md@@ -0,0 +1,32 @@+---+name: codebase-exploration+description: Use when exploring, understanding, or answering questions about a Repowise-indexed codebase, including architecture, where code is implemented, how a module works, or which files are relevant before reading source.+---++# Codebase Exploration With Repowise++This project has a Repowise intelligence layer. Use Repowise MCP tools before broad source browsing so the answer starts from indexed docs, ownership, graph structure, git signals, and decisions.++## Starting A New Exploration Task++Call `get_overview()` first. It returns the architecture summary, module map, entry points, and tech stack.++## Answering How Or Where Questions++1. Call `search_codebase(query="topic or symbol")` to find relevant documented modules and files.+2. Call `get_context(targets=[...])` with all relevant files from the search results in one batch.+3. Read raw source only after the indexed context is not specific enough for the user’s question.++## Understanding Connections Between Modules++Call `get_dependency_path(source="module_a", target="module_b")` when the user asks how two areas connect.++## Getting Diagrams++Call `get_architecture_diagram(scope="module", path="path/to/module")` for a subsystem diagram, or `get_architecture_diagram()` for the full repository.++## Error Handling++- If tools report that no repositories were found, suggest running `repowise init`.+- If `search_codebase` has no useful results, the repository may be index-only; fall back to `get_context` with specific paths.+- If MCP tools are unavailable, proceed with normal source inspection and mention that Repowise context was unavailable.diff --git a/plugins/codex/skills/dead-code-cleanup/SKILL.md b/plugins/codex/skills/dead-code-cleanup/SKILL.mdnew file mode 100644index 000000000..99b66ca1a--- /dev/null+++ b/plugins/codex/skills/dead-code-cleanup/SKILL.md@@ -0,0 +1,39 @@+---+name: dead-code-cleanup+description: Use when the user asks about unused code, cleanup, deleting files or exports, refactoring old areas, reducing bundle size, code hygiene, technical debt, or maintenance in a Repowise-indexed repository.+---++# Dead Code Cleanup With Repowise++Repowise detects dead code through graph analysis and git context. Treat findings as a cleanup plan, not automatic permission to delete.++## Finding Dead Or Unused Code++Call `get_dead_code()` to get findings organized by confidence tier. Useful parameters:++- `safe_only=true` for findings already marked safe to delete.+- `min_confidence=0.7` for high-confidence cleanup work.+- `kind="unreachable_file"` for files with no importers.+- `kind="unused_export"` for public symbols with no known consumers.+- `kind="zombie_package"` for monorepo packages with no consumers.+- `directory="src/old/"` to limit scope.+- `tier="high"` for the highest-confidence band.++## Presenting Findings++- Only recommend deletion for findings with `safe_to_delete: true`.+- Present lower-confidence findings as candidates to investigate.+- Flag dynamic loading, plugin systems, route handlers, adapters, and public APIs as common false-positive zones.++## Before Deleting Anything++1. Confirm with the user.+2. Present the file or symbol, confidence score, and why Repowise thinks it is dead.+3. Call `get_risk(targets=["path/to/file"])` before deleting files or exports.+4. If the finding has recent git activity, note the higher false-positive risk.++## Safe Deletion Order++1. Unreachable files first.+2. Unused internal symbols next.+3. Unused exports last.diff --git a/plugins/codex/skills/pre-modification-check/SKILL.md b/plugins/codex/skills/pre-modification-check/SKILL.mdnew file mode 100644index 000000000..eebf3a11a--- /dev/null+++ b/plugins/codex/skills/pre-modification-check/SKILL.md@@ -0,0 +1,41 @@+---+name: pre-modification-check+description: Use before modifying, refactoring, moving, or deleting files in a Repowise-indexed repository, especially shared utilities, core modules, public APIs, or files the user did not explicitly identify.+---++# Pre-Modification Check With Repowise++Before editing a Repowise-indexed codebase, assess impact with the graph and git signals.++## Before Editing Files++Call `get_risk(targets=["path/to/file.py"])` to understand:++- Hotspot status and churn trend.+- Dependents and likely blast radius.+- Co-change partners that may need updates.+- Ownership and recommended review context.+- Bus factor and maintenance concentration.+- Test gaps or security signals.++## When Editing Multiple Files++Batch all targets in one call: `get_risk(targets=["file1.py", "file2.py", "module/"])`.++## When To Warn The User++Warn before editing when `get_risk` shows:++- Hotspot score above the 90th percentile.+- More than 10 dependents.+- Bus factor of 1.+- Risk type such as `bug-prone` or `high-coupling`.+- Missing tests around changed or affected files.++## Before Refactoring Or Moving Code++Call `get_context(targets=["path/to/file.py"])` first to understand what uses the file, which decisions govern it, and why it is structured that way.++## Error Handling++If `get_risk` fails or the MCP server is unavailable, proceed with normal inspection and mention that Repowise risk assessment was unavailable.diff --git a/tests/providers/test_registry.py b/tests/providers/test_registry.pyindex e9aa37077..cdc66d622 100644--- a/tests/providers/test_registry.py+++ b/tests/providers/test_registry.py@@ -26,6 +26,7 @@ class TestListProviders:assert "openrouter" in providersassert "ollama" in providersassert "litellm" in providers+ assert "codex_cli" in providersassert "mock" in providersdef test_returns_sorted_list(self) -> None:@@ -115,5 +116,5 @@ class TestCustomProviderRegistration:assert received.get("api_key") == "key-123"def test_builtin_count(self) -> None:- """Sanity check: we have exactly 8 built-in providers."""- assert len(_BUILTIN_PROVIDERS) == 8+ """Sanity check: we have exactly 9 built-in providers."""+ assert len(_BUILTIN_PROVIDERS) == 9diff --git a/tests/unit/cli/test_augment_cmd.py b/tests/unit/cli/test_augment_cmd.pynew file mode 100644index 000000000..38e4af0da--- /dev/null+++ b/tests/unit/cli/test_augment_cmd.py@@ -0,0 +1,168 @@+from __future__ import annotations++import json+import subprocess+from pathlib import Path+from typing import Any++import pytest+from click.testing import CliRunner++from repowise.cli.main import cli+++def runner() -> CliRunner:+ return CliRunner()+++def _invoke_augment(+ runner: CliRunner,+ payload: dict[str, Any],+ args: list[str] | None = None,+):+ return runner.invoke(cli, ["augment", *(args or [])], input=json.dumps(payload))+++def _hook_context(output: str) -> str:+ response = json.loads(output)+ return response["hookSpecificOutput"]["additionalContext"]+++def _init_repowise_repo(path: Path) -> None:+ repowise_dir = path / ".repowise"+ repowise_dir.mkdir()+ (repowise_dir / "state.json").write_text(+ json.dumps({"last_sync_commit": "1111111111111111111111111111111111111111"}),+ encoding="utf-8",+ )+++def test_codex_session_start_payload_returns_mcp_context(runner: CliRunner, tmp_path: Path) -> None:+ _init_repowise_repo(tmp_path)++ result = _invoke_augment(+ runner,+ {+ "hook_event_name": "SessionStart",+ "source": "startup",+ "cwd": str(tmp_path),+ },+ ["--client", "codex"],+ )++ assert result.exit_code == 0+ assert "repowise MCP tools" in _hook_context(result.output)+++def test_codex_user_prompt_submit_payload_returns_mcp_context(+ runner: CliRunner, tmp_path: Path+) -> None:+ _init_repowise_repo(tmp_path)++ result = _invoke_augment(+ runner,+ {+ "hook_event_name": "UserPromptSubmit",+ "turn_id": "turn-1",+ "prompt": "Where is the auth flow?",+ "cwd": str(tmp_path),+ },+ ["--client", "codex"],+ )++ assert result.exit_code == 0+ assert "semantic search" in _hook_context(result.output)+++def test_claude_lifecycle_payload_stays_silent_without_codex_client(+ runner: CliRunner, tmp_path: Path+) -> None:+ _init_repowise_repo(tmp_path)++ result = _invoke_augment(+ runner,+ {+ "hook_event_name": "SessionStart",+ "source": "startup",+ "cwd": str(tmp_path),+ },+ )++ assert result.exit_code == 0+ assert result.output == ""+++def test_codex_post_tool_use_bash_detects_stale_wiki(+ runner: CliRunner, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _init_repowise_repo(tmp_path)++ def fake_run(args: list[str], **_kwargs: Any) -> subprocess.CompletedProcess[str]:+ assert args == ["git", "rev-parse", "HEAD"]+ return subprocess.CompletedProcess(+ args, 0, stdout="2222222222222222222222222222222222222222\n", stderr=""+ )++ monkeypatch.setattr("subprocess.run", fake_run)++ result = _invoke_augment(+ runner,+ {+ "hook_event_name": "PostToolUse",+ "tool_name": "Bash",+ "tool_input": {"command": "git commit -m hook-test"},+ "tool_response": {"exit_code": 0, "stdout": "[main abc123] hook-test"},+ "cwd": str(tmp_path),+ },+ )++ assert result.exit_code == 0+ context = _hook_context(result.output)+ assert "Wiki is stale" in context+ assert "11111111" in context+ assert "22222222" in context+++def test_codex_post_tool_use_apply_patch_flags_stale_context(+ runner: CliRunner, tmp_path: Path+) -> None:+ _init_repowise_repo(tmp_path)++ result = _invoke_augment(+ runner,+ {+ "hook_event_name": "PostToolUse",+ "tool_name": "apply_patch",+ "tool_input": {"command": "*** Begin Patch\n*** End Patch"},+ "tool_response": {"success": True},+ "cwd": str(tmp_path),+ },+ ["--client", "codex"],+ )++ assert result.exit_code == 0+ assert "Files were edited" in _hook_context(result.output)+++def test_edit_post_tool_use_stays_silent_without_codex_client(+ runner: CliRunner, tmp_path: Path+) -> None:+ # The edit freshness notice is a Codex-only lifecycle hook; an Edit PostToolUse+ # delivered by an existing Claude Code augment install (no --client) must not emit+ # a Codex-flavored banner.+ _init_repowise_repo(tmp_path)++ result = _invoke_augment(+ runner,+ {+ "hook_event_name": "PostToolUse",+ "tool_name": "Edit",+ "tool_input": {"file_path": "a.py"},+ "tool_response": {"success": True},+ "cwd": str(tmp_path),+ },+ )++ assert result.exit_code == 0+ assert result.output == ""diff --git a/tests/unit/cli/test_codex_plugin.py b/tests/unit/cli/test_codex_plugin.pynew file mode 100644index 000000000..eb3d968b0--- /dev/null+++ b/tests/unit/cli/test_codex_plugin.py@@ -0,0 +1,89 @@+from __future__ import annotations++import json+import re+from pathlib import Path++ROOT = Path(__file__).resolve().parents[3]+PLUGIN_ROOT = ROOT / "plugins" / "codex"+++def _load_json(path: Path) -> dict:+ return json.loads(path.read_text(encoding="utf-8"))+++def test_codex_plugin_manifest_paths() -> None:+ manifest_path = PLUGIN_ROOT / ".codex-plugin" / "plugin.json"+ manifest = _load_json(manifest_path)++ assert manifest["name"] == "codex"+ assert manifest["skills"] == "./skills/"+ assert manifest["mcpServers"] == "./.mcp.json"+ assert manifest["hooks"] == "./hooks/hooks.json"+ assert "apps" not in manifest+ assert "[TODO" not in manifest_path.read_text(encoding="utf-8")+++def test_codex_plugin_mcp_uses_repowise_no_path_mode() -> None:+ config = _load_json(PLUGIN_ROOT / ".mcp.json")++ assert config["repowise"]["command"] == "repowise"+ assert config["repowise"]["args"] == ["mcp"]+ assert config["repowise"]["startup_timeout_sec"] == 20+++def test_codex_plugin_hooks_match_supported_codex_events() -> None:+ hooks = _load_json(PLUGIN_ROOT / "hooks" / "hooks.json")["hooks"]++ assert set(hooks) == {"SessionStart", "UserPromptSubmit", "PostToolUse"}+ assert hooks["SessionStart"][0]["matcher"] == "startup|resume|clear"+ assert [entry["matcher"] for entry in hooks["PostToolUse"]] == [+ "Bash",+ "apply_patch|Edit|Write",+ ]++ commands = [+ hook["command"]+ for entries in hooks.values()+ for entry in entries+ for hook in entry["hooks"]+ ]+ assert commands == ["repowise-augment --client codex"] * 4+ assert [+ hook["timeout"]+ for entries in hooks.values()+ for entry in entries+ for hook in entry["hooks"]+ ] == [30] * 4+++def test_codex_plugin_skills_have_metadata_and_neutral_wording() -> None:+ skill_paths = sorted((PLUGIN_ROOT / "skills").glob("*/SKILL.md"))++ assert {path.parent.name for path in skill_paths} == {+ "architectural-decisions",+ "codebase-exploration",+ "dead-code-cleanup",+ "pre-modification-check",+ }++ for path in skill_paths:+ text = path.read_text(encoding="utf-8")+ assert re.search(r"^---\nname: .+\ndescription: .+\n---", text)+ assert "Claude" not in text+ assert "/repowise:" not in text+++def test_codex_plugin_marketplace_entry() -> None:+ marketplace = _load_json(ROOT / ".agents" / "plugins" / "marketplace.json")+ entry = marketplace["plugins"][0]++ assert marketplace["name"] == "repowise"+ assert marketplace["interface"]["displayName"] == "Repowise"+ assert entry["name"] == "codex"+ assert entry["source"] == {"source": "local", "path": "./plugins/codex"}+ assert entry["policy"] == {+ "installation": "AVAILABLE",+ "authentication": "ON_INSTALL",+ }+ assert entry["category"] == "Productivity"diff --git a/tests/unit/cli/test_commands.py b/tests/unit/cli/test_commands.pyindex ed3a4ecb9..1e3dd3665 100644--- a/tests/unit/cli/test_commands.py+++ b/tests/unit/cli/test_commands.py@@ -38,12 +38,16 @@ class TestCliBasics:assert "--dry-run" in result.outputassert "--skip-tests" in result.outputassert "--reasoning" in result.output+ assert "xhigh" in result.output+ assert "--codex" in result.output+ assert "--agents" in result.outputdef test_update_help(self, runner):result = runner.invoke(cli, ["update", "--help"])assert result.exit_code == 0assert "--since" in result.outputassert "--reasoning" in result.output+ assert "xhigh" in result.outputdef test_search_help(self, runner):result = runner.invoke(cli, ["search", "--help"])diff --git a/tests/unit/cli/test_cost_estimator.py b/tests/unit/cli/test_cost_estimator.pyindex 64f5a400c..15a5ad4cc 100644--- a/tests/unit/cli/test_cost_estimator.py+++ b/tests/unit/cli/test_cost_estimator.py@@ -146,6 +146,12 @@ class TestEstimateCost:assert est.estimated_cost_usd == 0.0assert est.total_pages == 5+ def test_codex_cli_provider_zero_cost(self):+ plans = [PageTypePlan("file_page", 5, 2)]+ est = estimate_cost(plans, "codex_cli", "codex_cli/default")+ assert est.estimated_cost_usd == 0.0+ assert est.total_pages == 5+def test_anthropic_has_cost(self):plans = [PageTypePlan("file_page", 10, 2)]est = estimate_cost(plans, "anthropic", "claude-sonnet-4-6")diff --git a/tests/unit/cli/test_editor_files.py b/tests/unit/cli/test_editor_files.pynew file mode 100644index 000000000..c069301ca--- /dev/null+++ b/tests/unit/cli/test_editor_files.py@@ -0,0 +1,46 @@+from __future__ import annotations++from pathlib import Path++from repowise.cli.editor_files import set_editor_file_enabled, should_generate_editor_file+++def test_should_generate_editor_file_defaults_enabled(tmp_path: Path) -> None:+ (tmp_path / ".repowise").mkdir()++ assert should_generate_editor_file(tmp_path, "agents_md")+++def test_should_generate_editor_file_reads_config(tmp_path: Path) -> None:+ repowise_dir = tmp_path / ".repowise"+ repowise_dir.mkdir()+ (repowise_dir / "config.yaml").write_text(+ "editor_files:\n agents_md: false\n",+ encoding="utf-8",+ )++ assert not should_generate_editor_file(tmp_path, "agents_md")+++def test_should_generate_editor_file_persists_override(tmp_path: Path) -> None:+ (tmp_path / ".repowise").mkdir()++ assert not should_generate_editor_file(tmp_path, "agents_md", override=False)+ assert "agents_md: false" in (tmp_path / ".repowise" / "config.yaml").read_text(+ encoding="utf-8"+ )+++def test_set_editor_file_enabled_preserves_existing_keys(tmp_path: Path) -> None:+ repowise_dir = tmp_path / ".repowise"+ repowise_dir.mkdir()+ (repowise_dir / "config.yaml").write_text(+ "editor_files:\n claude_md: false\n",+ encoding="utf-8",+ )++ set_editor_file_enabled(tmp_path, "agents_md", True)++ saved = (repowise_dir / "config.yaml").read_text(encoding="utf-8")+ assert "claude_md: false" in saved+ assert "agents_md: true" in saveddiff --git a/tests/unit/cli/test_editor_setup.py b/tests/unit/cli/test_editor_setup.pyindex b2f8a5e71..bc50eeeec 100644--- a/tests/unit/cli/test_editor_setup.py+++ b/tests/unit/cli/test_editor_setup.py@@ -11,14 +11,21 @@ from repowise.cli import mcp_configfrom repowise.cli.commands import init_cmd, update_cmdfrom repowise.cli.editor_integrations import claude as claude_integrationfrom repowise.cli.editor_integrations import claude_config+from repowise.cli.editor_integrations import codex as codex_integrationfrom repowise.cli.editor_integrations.claude import ClaudeCodeSetup-from repowise.cli.editor_integrations.defaults import get_default_disabled_project_files+from repowise.cli.editor_integrations.codex import CodexSetup+from repowise.cli.editor_integrations.defaults import (+ get_default_disabled_project_files,+ get_default_integration_overrides,+ get_default_project_file_overrides,+)from repowise.cli.editor_setup import (EditorSetupOptions,refresh_editor_project_files,resolve_editor_setup_options,write_editor_project_files,)+from repowise.core.workspace.config import RepoEntry, WorkspaceConfigdef _silent_console() -> Console:@@ -95,6 +102,13 @@ def test_default_disabled_project_files_maps_legacy_no_claude_flag() -> None:assert get_default_disabled_project_files(no_claude_md=True) == ("claude_md",)+def test_default_overrides_map_codex_flags_to_integration_ids() -> None:+ assert get_default_project_file_overrides() == {}+ assert get_default_project_file_overrides(agents_md=False) == {"agents_md": False}+ assert get_default_integration_overrides() == {}+ assert get_default_integration_overrides(codex_setup=True) == {"codex": True}++def test_write_editor_project_files_saves_common_mcp_before_integrations(tmp_path: Path,monkeypatch: Any,@@ -230,6 +244,195 @@ def test_refresh_editor_project_files_delegates_to_integrations(tmp_path: Path)assert calls == [("refresh", tmp_path, frozenset({"skip"}))]+def test_codex_project_setup_writes_project_config_hooks_and_agents(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[tuple[str, Path, bool | None]] = []++ monkeypatch.setattr(mcp_config, "is_codex_cli_installed", lambda: True)+ monkeypatch.setattr(mcp_config, "is_codex_logged_in", lambda: True)+ monkeypatch.setattr(+ mcp_config,+ "save_codex_mcp_config",+ lambda repo_path: (+ calls.append(("codex-mcp", repo_path, None)) or repo_path / ".codex" / "config.toml"+ ),+ )+ monkeypatch.setattr(+ mcp_config,+ "save_codex_hooks_config",+ lambda repo_path: (+ calls.append(("codex-hooks", repo_path, None)) or repo_path / ".codex" / "hooks.json"+ ),+ )+ monkeypatch.setattr(+ codex_integration,+ "maybe_generate_agents_md",+ lambda _console, repo_path, *, agents_md=None: calls.append(+ ("agents-md", repo_path, agents_md)+ ),+ )++ CodexSetup().write_project_files(+ _silent_console(),+ tmp_path,+ EditorSetupOptions(+ integration_overrides={"codex": True},+ project_file_overrides={"agents_md": False},+ ),+ )++ assert calls == [+ ("codex-mcp", tmp_path, None),+ ("codex-hooks", tmp_path, None),+ ("agents-md", tmp_path, False),+ ]+++def test_codex_project_setup_enables_agents_by_default_with_codex(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[tuple[str, Path, bool | None]] = []++ monkeypatch.setattr(mcp_config, "is_codex_cli_installed", lambda: True)+ monkeypatch.setattr(mcp_config, "is_codex_logged_in", lambda: True)+ monkeypatch.setattr(+ mcp_config,+ "save_codex_mcp_config",+ lambda repo_path: (+ calls.append(("codex-mcp", repo_path, None)) or repo_path / ".codex" / "config.toml"+ ),+ )+ monkeypatch.setattr(+ mcp_config,+ "save_codex_hooks_config",+ lambda repo_path: (+ calls.append(("codex-hooks", repo_path, None)) or repo_path / ".codex" / "hooks.json"+ ),+ )+ monkeypatch.setattr(+ codex_integration,+ "maybe_generate_agents_md",+ lambda _console, repo_path, *, agents_md=None, default=True: calls.append(+ ("agents-md", repo_path, agents_md)+ ),+ )++ CodexSetup().write_project_files(+ _silent_console(),+ tmp_path,+ EditorSetupOptions(integration_overrides={"codex": True}),+ )++ assert calls == [+ ("codex-mcp", tmp_path, None),+ ("codex-hooks", tmp_path, None),+ ("agents-md", tmp_path, True),+ ]+++def test_codex_project_setup_skips_when_disabled(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[str] = []++ monkeypatch.setattr(+ mcp_config,+ "save_codex_mcp_config",+ lambda _repo_path: calls.append("codex-mcp"),+ )++ CodexSetup().write_project_files(+ _silent_console(),+ tmp_path,+ EditorSetupOptions(integration_overrides={"codex": False}),+ )++ assert calls == []+++def test_codex_project_setup_skips_without_explicit_opt_in(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[str] = []++ monkeypatch.setattr(mcp_config, "is_codex_cli_installed", lambda: True)+ monkeypatch.setattr(mcp_config, "is_codex_logged_in", lambda: True)+ monkeypatch.setattr(+ mcp_config,+ "save_codex_mcp_config",+ lambda _repo_path: calls.append("codex-mcp"),+ )++ CodexSetup().write_project_files(+ _silent_console(),+ tmp_path,+ EditorSetupOptions(),+ )++ assert calls == []+++def test_codex_project_setup_writes_agents_without_codex_setup(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[tuple[str, Path, bool | None]] = []++ monkeypatch.setattr(+ mcp_config,+ "save_codex_mcp_config",+ lambda _repo_path: calls.append(("unexpected-codex-mcp", tmp_path, None)),+ )+ monkeypatch.setattr(+ mcp_config,+ "save_codex_hooks_config",+ lambda _repo_path: calls.append(("unexpected-codex-hooks", tmp_path, None)),+ )+ monkeypatch.setattr(+ codex_integration,+ "maybe_generate_agents_md",+ lambda _console, repo_path, *, agents_md=None: calls.append(+ ("agents-md", repo_path, agents_md)+ ),+ )++ CodexSetup().write_project_files(+ _silent_console(),+ tmp_path,+ EditorSetupOptions(project_file_overrides={"agents_md": True}),+ )++ assert calls == [("agents-md", tmp_path, True)]+++def test_codex_refresh_project_files_delegates_to_agents_generator(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ calls: list[tuple[Path, bool | None, bool]] = []++ monkeypatch.setattr(+ codex_integration,+ "maybe_generate_agents_md",+ lambda _console, repo_path, *, agents_md=None, default=True: calls.append(+ (repo_path, agents_md, default)+ ),+ )++ CodexSetup().refresh_project_files(+ _silent_console(),+ tmp_path,+ EditorSetupOptions(project_file_overrides={"agents_md": True}),+ )++ assert calls == [(tmp_path, True, False)]++def test_claude_refresh_project_files_writes_when_enabled(tmp_path: Path,monkeypatch: Any,@@ -316,6 +519,66 @@ def test_update_command_uses_editor_refresh_abstraction() -> None:assert "claude_md" not in source+def test_workspace_update_refreshes_agents_for_selected_repos(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ backend = tmp_path / "backend"+ frontend = tmp_path / "frontend"+ (backend / ".repowise").mkdir(parents=True)+ (frontend / ".repowise").mkdir(parents=True)+ ws_config = WorkspaceConfig(+ repos=[+ RepoEntry(path="backend", alias="backend"),+ RepoEntry(path="frontend", alias="frontend"),+ ],+ )+ calls: list[tuple[Path, dict[str, bool]]] = []++ def fake_refresh(_console: object, repo_path: Path, *, options: EditorSetupOptions):+ calls.append((repo_path, options.project_file_overrides))++ monkeypatch.setattr(+ "repowise.cli.editor_setup.refresh_editor_project_files",+ fake_refresh,+ )++ update_cmd._refresh_workspace_editor_project_files(+ ws_root=tmp_path,+ ws_config=ws_config,+ repo_filter=None,+ agents_md=True,+ )++ assert calls == [+ (backend.resolve(), {"agents_md": True}),+ (frontend.resolve(), {"agents_md": True}),+ ]+++def test_workspace_generation_rebinds_codex_provider_to_repo(+ tmp_path: Path,+ monkeypatch: Any,+) -> None:+ class FakeProvider:+ provider_name = "codex_cli"+ model_name = "codex_cli/gpt-5.5"++ rebound = object()+ calls: list[tuple[str, str, Path]] = []++ def fake_resolve_provider(provider_name: str, model: str, repo_path: Path) -> object:+ calls.append((provider_name, model, repo_path))+ return rebound++ monkeypatch.setattr(init_cmd.workspace, "resolve_provider", fake_resolve_provider)++ result = init_cmd.workspace._workspace_generation_provider_for_repo(FakeProvider(), tmp_path)++ assert result is rebound+ assert calls == [("codex_cli", "codex_cli/gpt-5.5", tmp_path)]++def test_init_command_uses_editor_option_abstraction() -> None:source = inspect.getsource(init_cmd.init_command.callback) + inspect.getsource(init_cmd._workspace_initdiff --git a/tests/unit/cli/test_helpers.py b/tests/unit/cli/test_helpers.pyindex a46a374fd..2a4b528f2 100644--- a/tests/unit/cli/test_helpers.py+++ b/tests/unit/cli/test_helpers.py@@ -10,6 +10,7 @@ import pytestfrom repowise.cli.helpers import (CONFIG_FILENAME,ensure_repowise_dir,+ find_repowise_repo_root,get_db_url_for_repo,get_head_commit,get_repowise_dir,@@ -68,6 +69,28 @@ class TestResolveRepoPath:assert result == tmp_path.resolve()+class TestFindRepowiseRepoRoot:+ def test_finds_parent_repowise_dir(self, tmp_path):+ root = tmp_path / "repo"+ nested = root / "src" / "pkg"+ nested.mkdir(parents=True)+ (root / ".repowise").mkdir()++ assert find_repowise_repo_root(nested) == root.resolve()++ def test_returns_none_when_missing(self, tmp_path):+ assert find_repowise_repo_root(tmp_path) is None++ def test_ignores_nested_git_dirs(self, tmp_path):+ root = tmp_path / "repo"+ nested = root / "vendor" / "dep" / "src"+ nested.mkdir(parents=True)+ (root / ".repowise").mkdir()+ (root / "vendor" / "dep" / ".git").mkdir()++ assert find_repowise_repo_root(nested) == root.resolve()++# ---------------------------------------------------------------------------# .repowise/ directory# ---------------------------------------------------------------------------@@ -107,12 +130,12 @@ class TestResolveReasoning:assert resolve_reasoning("off", {"reasoning": "auto"}) == "off"def test_env_wins_over_config(self, monkeypatch):- monkeypatch.setenv("REPOWISE_REASONING", "minimal")- assert resolve_reasoning(config={"reasoning": "off"}) == "minimal"+ monkeypatch.setenv("REPOWISE_REASONING", "high")+ assert resolve_reasoning(config={"reasoning": "off"}) == "high"def test_config_wins_over_default(self, monkeypatch):monkeypatch.delenv("REPOWISE_REASONING", raising=False)- assert resolve_reasoning(config={"reasoning": "off"}) == "off"+ assert resolve_reasoning(config={"reasoning": "xhigh"}) == "xhigh"# ---------------------------------------------------------------------------@@ -291,9 +314,7 @@ class TestUpdateLock:)ensure_repowise_dir(tmp_path)- (tmp_path / ".repowise" / UPDATE_LOCK_FILENAME).write_text(- "not json", encoding="utf-8"- )+ (tmp_path / ".repowise" / UPDATE_LOCK_FILENAME).write_text("not json", encoding="utf-8")assert read_update_lock(tmp_path) is None@@ -427,7 +448,9 @@ class TestResolveProviderBaseUrl:return "provider"monkeypatch.setattr("repowise.core.providers.get_provider", fake_get_provider)- monkeypatch.setattr("repowise.cli.helpers.validate_provider_config", lambda *_args, **_kw: [])+ monkeypatch.setattr(+ "repowise.cli.helpers.validate_provider_config", lambda *_args, **_kw: []+ )monkeypatch.setenv("REPOWISE_PROVIDER", "openai")monkeypatch.setenv("OPENAI_API_KEY", "sk-test")monkeypatch.setenv("OPENAI_BASE_URL", "http://proxy.local")@@ -448,7 +471,9 @@ class TestResolveProviderBaseUrl:return "provider"monkeypatch.setattr("repowise.core.providers.get_provider", fake_get_provider)- monkeypatch.setattr("repowise.cli.helpers.validate_provider_config", lambda *_args, **_kw: [])+ monkeypatch.setattr(+ "repowise.cli.helpers.validate_provider_config", lambda *_args, **_kw: []+ )monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)cfg = {"provider": "ollama",@@ -464,7 +489,9 @@ class TestResolveProviderBaseUrl:yaml = Noneif "yaml" in locals() and yaml is not None:- config_path.write_text(yaml.dump(cfg, default_flow_style=False, sort_keys=False), encoding="utf-8")+ config_path.write_text(+ yaml.dump(cfg, default_flow_style=False, sort_keys=False), encoding="utf-8"+ )else:config_path.write_text("provider: ollama\nmodel: llama3\nollama:\n base_url: http://ollama.local:11434\n",diff --git a/tests/unit/cli/test_mcp_config.py b/tests/unit/cli/test_mcp_config.pyindex 05be464ec..c12d58d29 100644--- a/tests/unit/cli/test_mcp_config.py+++ b/tests/unit/cli/test_mcp_config.py@@ -1,7 +1,10 @@import jsonimport re+import subprocessimport sys+import tomllibfrom pathlib import Path+from typing import Anyimport clickimport pytest@@ -14,6 +17,225 @@ def _repowise_entry(repo_path: Path) -> dict:return mcp_config.generate_mcp_config(repo_path)["mcpServers"]+# ---------------------------------------------------------------------------+# Codex project config+# ---------------------------------------------------------------------------+++def test_generate_codex_mcp_server_config_uses_no_path_mcp(tmp_path: Path) -> None:+ server = mcp_config.generate_codex_mcp_server_config(tmp_path)++ assert server["command"] == "repowise"+ assert server["args"] == ["mcp"]+ assert server["cwd"] == str(tmp_path.resolve())+++def test_save_codex_mcp_config_creates_project_config(tmp_path: Path) -> None:+ config_path = mcp_config.save_codex_mcp_config(tmp_path)++ assert config_path == tmp_path / ".codex" / "config.toml"+ saved = tomllib.loads(config_path.read_text(encoding="utf-8"))+ assert saved["mcp_servers"]["repowise"]["command"] == "repowise"+ assert saved["mcp_servers"]["repowise"]["args"] == ["mcp"]+ assert saved["mcp_servers"]["repowise"]["cwd"] == str(tmp_path.resolve())+++def test_save_codex_mcp_config_merges_valid_existing_file(tmp_path: Path) -> None:+ config_path = tmp_path / ".codex" / "config.toml"+ config_path.parent.mkdir(parents=True)+ config_path.write_text(+ 'model = "gpt-5.5"\n\n[mcp_servers.other]\ncommand = "other"\n',+ encoding="utf-8",+ )++ mcp_config.save_codex_mcp_config(tmp_path)++ saved = tomllib.loads(config_path.read_text(encoding="utf-8"))+ assert saved["model"] == "gpt-5.5"+ assert saved["mcp_servers"]["other"]["command"] == "other"+ assert saved["mcp_servers"]["repowise"]["command"] == "repowise"+++def test_save_codex_mcp_config_rejects_invalid_existing_file(tmp_path: Path) -> None:+ config_path = tmp_path / ".codex" / "config.toml"+ config_path.parent.mkdir(parents=True)+ original = 'model = "gpt-5.5"\nmodel = "duplicate"\n'+ config_path.write_text(original, encoding="utf-8")++ with pytest.raises(click.ClickException, match=re.escape(str(config_path))):+ mcp_config.save_codex_mcp_config(tmp_path)++ assert config_path.read_text(encoding="utf-8") == original+++def test_save_codex_mcp_config_aborts_when_merge_would_duplicate_quoted_key(+ tmp_path: Path,+) -> None:+ # A quoted table spelling the bare-key regex can't match. The pre-write merge+ # validation must abort before producing a duplicate-key file, leaving the+ # user's config untouched.+ config_path = tmp_path / ".codex" / "config.toml"+ config_path.parent.mkdir(parents=True)+ original = '["mcp_servers"."repowise"]\ncommand = "stale"\n'+ config_path.write_text(original, encoding="utf-8")++ with pytest.raises(click.ClickException, match="invalid TOML"):+ mcp_config.save_codex_mcp_config(tmp_path)++ assert config_path.read_text(encoding="utf-8") == original+++def test_generate_codex_hooks_config_uses_supported_events_only() -> None:+ config = mcp_config.generate_codex_hooks_config()+ hooks = config["hooks"]++ assert set(hooks) == {"SessionStart", "UserPromptSubmit", "PostToolUse"}+ assert hooks["SessionStart"][0]["matcher"] == "startup|resume|clear"+ assert hooks["PostToolUse"][0]["matcher"] == "Bash"+ assert hooks["PostToolUse"][1]["matcher"] == "apply_patch|Edit|Write"+ assert [+ hook["timeout"]+ for entries in hooks.values()+ for entry in entries+ for hook in entry["hooks"]+ ] == [30] * 4+++def test_save_codex_hooks_config_creates_hooks_json_and_feature_flag(+ tmp_path: Path,+) -> None:+ hooks_path = mcp_config.save_codex_hooks_config(tmp_path)++ assert hooks_path == tmp_path / ".codex" / "hooks.json"+ saved_hooks = json.loads(hooks_path.read_text(encoding="utf-8"))+ assert "PreToolUse" not in saved_hooks["hooks"]+ assert saved_hooks["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"] == (+ "repowise-augment --client codex"+ )++ saved_config = tomllib.loads((tmp_path / ".codex" / "config.toml").read_text())+ assert saved_config["features"]["hooks"] is True+ assert "hooks" not in saved_config+++def test_save_codex_hooks_config_merges_without_duplicates(tmp_path: Path) -> None:+ hooks_path = tmp_path / ".codex" / "hooks.json"+ hooks_path.parent.mkdir(parents=True)+ hooks_path.write_text(+ json.dumps(+ {+ "hooks": {+ "SessionStart": [+ {+ "matcher": "startup",+ "hooks": [{"type": "command", "command": "echo existing"}],+ }+ ]+ },+ "custom": {"preserved": True},+ }+ ),+ encoding="utf-8",+ )+ config_path = tmp_path / ".codex" / "config.toml"+ config_path.write_text("[features]\nfoo = true\n", encoding="utf-8")++ mcp_config.save_codex_hooks_config(tmp_path)+ mcp_config.save_codex_hooks_config(tmp_path)++ saved_hooks = json.loads(hooks_path.read_text(encoding="utf-8"))+ assert saved_hooks["custom"] == {"preserved": True}+ assert saved_hooks["hooks"]["SessionStart"][0]["matcher"] == "startup"+ repowise_commands = [+ hook["command"]+ for entries in saved_hooks["hooks"].values()+ for entry in entries+ for hook in entry["hooks"]+ if hook["command"] == "repowise-augment --client codex"+ ]+ assert len(repowise_commands) == 4++ saved_config = tomllib.loads(config_path.read_text(encoding="utf-8"))+ assert saved_config["features"]["foo"] is True+ assert saved_config["features"]["hooks"] is True+++def test_save_codex_hooks_config_rejects_invalid_existing_file(tmp_path: Path) -> None:+ hooks_path = tmp_path / ".codex" / "hooks.json"+ hooks_path.parent.mkdir(parents=True)+ original = '{\n "hooks": {},\n}\n'+ hooks_path.write_text(original, encoding="utf-8")++ with pytest.raises(click.ClickException, match=re.escape(str(hooks_path))):+ mcp_config.save_codex_hooks_config(tmp_path)++ assert hooks_path.read_text(encoding="utf-8") == original+++def test_codex_detection_requires_binary(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("shutil.which", lambda _cmd: None)++ assert not mcp_config.is_codex_cli_installed()+ assert not mcp_config.is_codex_logged_in()+++def test_codex_detection_uses_resolved_executable(monkeypatch: pytest.MonkeyPatch) -> None:+ codex_cmd = str(Path("tmp") / "codex.CMD")+ calls: list[list[str]] = []++ def fake_run(args: list[str], **_kwargs: Any) -> subprocess.CompletedProcess[str]:+ calls.append(args)+ if args == [codex_cmd, "--version"]:+ return subprocess.CompletedProcess(args, 0, stdout="codex-cli 0.130.0", stderr="")+ if args == [codex_cmd, "login", "status"]:+ return subprocess.CompletedProcess(args, 0, stdout="Authenticated", stderr="")+ return subprocess.CompletedProcess(args, 1, stdout="", stderr="")++ monkeypatch.setattr("shutil.which", lambda cmd: codex_cmd if cmd == "codex" else None)+ monkeypatch.setattr("subprocess.run", fake_run)++ assert mcp_config.is_codex_cli_installed()+ assert mcp_config.is_codex_logged_in()+ assert [codex_cmd, "--version"] in calls+ assert [codex_cmd, "login", "status"] in calls+++def test_codex_login_detection_uses_exit_code_not_text(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ codex_cmd = "codex"+ monkeypatch.setattr("shutil.which", lambda cmd: codex_cmd if cmd == "codex" else None)++ def fake_run(args: list[str], **_kwargs: Any) -> subprocess.CompletedProcess[str]:+ if args == [codex_cmd, "--version"]:+ return subprocess.CompletedProcess(args, 0, stdout="codex-cli 0.130.0", stderr="")+ if args == [codex_cmd, "login", "status"]:+ return subprocess.CompletedProcess(args, 0, stdout="Authenticated", stderr="")+ raise AssertionError(f"Unexpected args: {args}")++ monkeypatch.setattr("subprocess.run", fake_run)++ assert mcp_config.is_codex_logged_in()+++def test_codex_login_detection_fails_on_nonzero_status(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ codex_cmd = "codex"+ monkeypatch.setattr("shutil.which", lambda cmd: codex_cmd if cmd == "codex" else None)++ def fake_run(args: list[str], **_kwargs: Any) -> subprocess.CompletedProcess[str]:+ if args == [codex_cmd, "--version"]:+ return subprocess.CompletedProcess(args, 0, stdout="codex-cli 0.130.0", stderr="")+ if args == [codex_cmd, "login", "status"]:+ return subprocess.CompletedProcess(args, 1, stdout="Logged in cached text", stderr="")+ raise AssertionError(f"Unexpected args: {args}")++ monkeypatch.setattr("subprocess.run", fake_run)++ assert not mcp_config.is_codex_logged_in()++# ---------------------------------------------------------------------------# Root .mcp.json# ---------------------------------------------------------------------------diff --git a/tests/unit/cli/test_ui_codex.py b/tests/unit/cli/test_ui_codex.pynew file mode 100644index 000000000..5d5f185aa--- /dev/null+++ b/tests/unit/cli/test_ui_codex.py@@ -0,0 +1,31 @@+from __future__ import annotations++from typing import Any++from repowise.cli.ui import provider_selection as ui+++def test_detect_provider_status_requires_codex_login(monkeypatch: Any) -> None:+ monkeypatch.setattr(+ "repowise.cli.mcp_config.is_codex_cli_installed",+ lambda: True,+ )+ monkeypatch.setattr(+ "repowise.cli.mcp_config.is_codex_logged_in",+ lambda: False,+ )++ assert "codex_cli" not in ui._detect_provider_status()+++def test_detect_provider_status_accepts_authenticated_codex(monkeypatch: Any) -> None:+ monkeypatch.setattr(+ "repowise.cli.mcp_config.is_codex_cli_installed",+ lambda: True,+ )+ monkeypatch.setattr(+ "repowise.cli.mcp_config.is_codex_logged_in",+ lambda: True,+ )++ assert ui._detect_provider_status()["codex_cli"] == "codex CLI"diff --git a/tests/unit/cli/test_ui_reasoning.py b/tests/unit/cli/test_ui_reasoning.pynew file mode 100644index 000000000..736eca56d--- /dev/null+++ b/tests/unit/cli/test_ui_reasoning.py@@ -0,0 +1,126 @@+from __future__ import annotations++from io import StringIO+from typing import Any++from rich.console import Console++from repowise.cli import ui+from repowise.cli.ui import mode_selection, provider_selection+from repowise.core.providers.llm.base import ProviderModelOption+from repowise.core.reasoning import REASONING_MODES+++def _silent_console() -> Console:+ return Console(file=StringIO(), force_terminal=False)+++def test_interactive_advanced_config_uses_shared_reasoning_modes(+ monkeypatch: Any,+) -> None:+ captured: dict[str, tuple[str, ...]] = {}++ def fake_confirm(*_args: object, **_kwargs: object) -> bool:+ return False++ def fake_prompt(+ text: str,+ *,+ default: Any = None,+ type: Any = None,+ **_kwargs: object,+ ) -> Any:+ label = text.strip()+ if label == "Pattern":+ return ""+ if label == "Reasoning mode":+ captured["reasoning_choices"] = tuple(type.choices)+ return "xhigh"+ return default++ monkeypatch.setattr(mode_selection.click, "confirm", fake_confirm)+ monkeypatch.setattr(mode_selection.click, "prompt", fake_prompt)++ result = ui.interactive_advanced_config(_silent_console())++ assert captured["reasoning_choices"] == REASONING_MODES+ assert result["reasoning"] == "xhigh"+++def test_interactive_advanced_config_can_skip_reasoning_prompt(+ monkeypatch: Any,+) -> None:+ def fake_confirm(*_args: object, **_kwargs: object) -> bool:+ return False++ def fake_prompt(+ text: str,+ *,+ default: Any = None,+ **_kwargs: object,+ ) -> Any:+ if text.strip() == "Reasoning mode":+ raise AssertionError("reasoning prompt should be skipped")+ if text.strip() == "Pattern":+ return ""+ return default++ monkeypatch.setattr(mode_selection.click, "confirm", fake_confirm)+ monkeypatch.setattr(mode_selection.click, "prompt", fake_prompt)++ result = ui.interactive_advanced_config(+ _silent_console(),+ prompt_reasoning=False,+ )++ assert result["reasoning"] is None+++def test_interactive_provider_config_select_uses_model_reasoning_options(+ monkeypatch: Any,+) -> None:+ monkeypatch.setattr(provider_selection, "_detect_provider_status", lambda: {"gemini": "GEMINI_API_KEY"})+ monkeypatch.setattr(provider_selection, "_detect_codex_cli_status", lambda: (False, False))+ monkeypatch.setattr(+ provider_selection,+ "_provider_model_options",+ lambda *_args, **_kwargs: (+ ProviderModelOption(+ model="gemini-fast",+ reasoning_modes=("auto",),+ recommended=True,+ source="api",+ ),+ ProviderModelOption(+ model="gemini-reasoner",+ reasoning_modes=("auto", "low", "high"),+ source="api",+ ),+ ),+ )++ prompt_answers = iter(["1", "2"])++ def fake_ask(*_args: object, **_kwargs: object) -> str:+ return next(prompt_answers)++ def fake_prompt(+ text: str,+ *,+ default: Any = None,+ type: Any = None,+ **_kwargs: object,+ ) -> Any:+ if text.strip() == "Reasoning":+ assert tuple(type.choices) == ("auto", "low", "high")+ return "high"+ return default++ monkeypatch.setattr(provider_selection.Prompt, "ask", fake_ask)+ monkeypatch.setattr(provider_selection.click, "prompt", fake_prompt)++ result = ui.interactive_provider_config_select(_silent_console(), None)++ assert result.provider_name == "gemini"+ assert result.model == "gemini-reasoner"+ assert result.reasoning == "high"diff --git a/tests/unit/cli/test_workspace_autodetect_e2e.py b/tests/unit/cli/test_workspace_autodetect_e2e.pyindex ea655740f..15d198e99 100644--- a/tests/unit/cli/test_workspace_autodetect_e2e.py+++ b/tests/unit/cli/test_workspace_autodetect_e2e.py@@ -52,9 +52,10 @@ def test_update_from_workspace_root_does_not_create_stray_repowise(# spawn a real pipeline, so we intercept _workspace_update.called = {}- def _fake_workspace_update(target, *, dry_run):+ def _fake_workspace_update(target, *, dry_run, agents_md=None):called["target"] = targetcalled["dry_run"] = dry_run+ called["agents_md"] = agents_mdmonkeypatch.setattr("repowise.cli.commands.update_cmd._workspace_update",diff --git a/tests/unit/generation/test_agents_md.py b/tests/unit/generation/test_agents_md.pynew file mode 100644index 000000000..443281a22--- /dev/null+++ b/tests/unit/generation/test_agents_md.py@@ -0,0 +1,64 @@+from __future__ import annotations++from repowise.core.generation.editor_files.agents_md import AgentsMdGenerator+from repowise.core.generation.editor_files.data import EditorFileData+++def _data() -> EditorFileData:+ return EditorFileData(+ repo_name="demo-repo",+ indexed_at="2026-05-03",+ indexed_commit="abc1234",+ architecture_summary="A small service.",+ build_commands={"test": "pytest"},+ )+++def test_agents_md_renders_repowise_workflows() -> None:+ rendered = AgentsMdGenerator().render(_data())++ assert "get_overview()" in rendered+ assert "search_codebase" in rendered+ assert "get_context" in rendered+ assert "get_risk" in rendered+ assert "get_why" in rendered+ assert "get_dead_code" in rendered+++def test_agents_md_writes_repo_root_file(tmp_path) -> None:+ written = AgentsMdGenerator().write(tmp_path, _data())++ assert written == tmp_path / "AGENTS.md"+ content = written.read_text(encoding="utf-8")+ assert "<!-- REPOWISE_AGENTS:START" in content+ assert "<!-- REPOWISE_AGENTS:END -->" in content+ assert "demo-repo" in content+++def test_agents_md_preserves_user_content(tmp_path) -> None:+ target = tmp_path / "AGENTS.md"+ target.write_text("# Team Rules\n\nKeep this instruction.\n", encoding="utf-8")++ AgentsMdGenerator().write(tmp_path, _data())++ content = target.read_text(encoding="utf-8")+ assert "Keep this instruction." in content+ assert content.count("<!-- REPOWISE_AGENTS:START") == 1+++def test_agents_md_replaces_only_managed_section(tmp_path) -> None:+ gen = AgentsMdGenerator()+ marker_start = gen.MARKER_START_FMT.format(tag=gen.marker_tag)+ marker_end = gen.MARKER_END_FMT.format(tag=gen.marker_tag)+ target = tmp_path / "AGENTS.md"+ target.write_text(+ f"# Team Rules\n\nKeep this.\n\n{marker_start}\nold managed text\n{marker_end}\n",+ encoding="utf-8",+ )++ gen.write(tmp_path, _data())++ content = target.read_text(encoding="utf-8")+ assert "Keep this." in content+ assert "old managed text" not in content+ assert "demo-repo" in contentdiff --git a/tests/unit/generation/test_models.py b/tests/unit/generation/test_models.pyindex beab47c53..e73ec8d66 100644--- a/tests/unit/generation/test_models.py+++ b/tests/unit/generation/test_models.py@@ -169,6 +169,11 @@ def test_generation_config_normalizes_reasoning():assert config.reasoning == "off"+def test_generation_config_accepts_native_reasoning_effort():+ config = GenerationConfig(reasoning="XHIGH")+ assert config.reasoning == "xhigh"++def test_generation_config_rejects_invalid_reasoning():with pytest.raises(ValueError):GenerationConfig(reasoning="verbose")diff --git a/tests/unit/test_providers/test_anthropic_provider.py b/tests/unit/test_providers/test_anthropic_provider.pyindex ded16ef7b..14d860d70 100644--- a/tests/unit/test_providers/test_anthropic_provider.py+++ b/tests/unit/test_providers/test_anthropic_provider.py@@ -51,6 +51,43 @@ def test_haiku_model():assert p.model_name == "claude-haiku-4-5"+def test_available_model_options_uses_models_endpoint(monkeypatch):+ class FakeResponse:+ def raise_for_status(self) -> None:+ pass++ def json(self) -> dict:+ return {+ "data": [+ {+ "id": "claude-sonnet-4-6",+ "display_name": "Claude Sonnet 4.6",+ },+ {"id": "claude-haiku-4-5"},+ ]+ }++ captured: dict[str, object] = {}++ def fake_get(url, *, headers, timeout):+ captured["url"] = url+ captured["headers"] = headers+ captured["timeout"] = timeout+ return FakeResponse()++ monkeypatch.setattr("httpx.get", fake_get)++ options = AnthropicProvider(api_key="sk-ant-test").available_model_options()++ assert captured["url"] == "https://api.anthropic.com/v1/models"+ assert captured["headers"]["x-api-key"] == "sk-ant-test"+ assert captured["headers"]["anthropic-version"] == "2023-06-01"+ sonnet = next(option for option in options if option.model == "claude-sonnet-4-6")+ assert sonnet.label == "Claude Sonnet 4.6"+ assert sonnet.reasoning_modes == ("auto",)+ assert sonnet.recommended is True++# ---------------------------------------------------------------------------# Successful generation# ---------------------------------------------------------------------------diff --git a/tests/unit/test_providers/test_codex_cli_provider.py b/tests/unit/test_providers/test_codex_cli_provider.pynew file mode 100644index 000000000..d1061bdcc--- /dev/null+++ b/tests/unit/test_providers/test_codex_cli_provider.py@@ -0,0 +1,469 @@+"""Unit tests for CodexCliProvider.++All tests mock the Codex subprocess; no real Codex CLI calls are made.+"""++from __future__ import annotations++import asyncio+import json+from typing import Any++import pytest++from repowise.core.providers.llm.base import GeneratedResponse, ProviderError+from repowise.core.providers.llm.codex_cli import (+ CodexCliProvider,+ CodexModelReasoning,+ _extract_codex_model_catalog,+)+++class FakeProcess:+ def __init__(+ self,+ *,+ returncode: int = 0,+ stdout: str = "",+ stderr: str = "",+ on_communicate: Any | None = None,+ transport: Any | None = None,+ ) -> None:+ self.returncode = returncode+ self._stdout = stdout+ self._stderr = stderr+ self._on_communicate = on_communicate+ self._transport = transport+ self.stdin_input: bytes | None = None+ self.killed = False++ async def communicate(self, input: bytes | None = None) -> tuple[bytes, bytes]:+ self.stdin_input = input+ if self._on_communicate is not None:+ await self._on_communicate()+ return self._stdout.encode("utf-8"), self._stderr.encode("utf-8")++ def kill(self) -> None:+ self.killed = True++ async def wait(self) -> int:+ return self.returncode+++class FakeTransport:+ def __init__(self) -> None:+ self.closed = False++ def close(self) -> None:+ self.closed = True+++def _jsonl(*events: dict[str, Any], noise: bool = False) -> str:+ lines = [json.dumps(event) for event in events]+ if noise:+ lines.insert(1, "warning: this is not JSON")+ return "\n".join(lines) + "\n"+++def _success_jsonl(text: str = "OK") -> str:+ return _jsonl(+ {"type": "thread.started", "thread_id": "t1"},+ {"type": "turn.started"},+ {"type": "item.completed", "item": {"type": "agent_message", "text": text}},+ {+ "type": "turn.completed",+ "usage": {+ "input_tokens": 120,+ "cached_input_tokens": 30,+ "output_tokens": 40,+ "reasoning_output_tokens": 10,+ },+ },+ noise=True,+ )+++def _reasoning_catalog(+ *efforts: str,+ slug: str = "gpt-5.5",+ default: str = "medium",+) -> dict[str, CodexModelReasoning]:+ return {+ slug: CodexModelReasoning(+ slug=slug,+ default_effort=default,+ supported_efforts=efforts,+ )+ }+++def test_extract_codex_model_catalog_keeps_only_reasoning_capabilities():+ catalog = _extract_codex_model_catalog(+ {+ "models": [+ {+ "slug": "gpt-5.5",+ "default_reasoning_level": "medium",+ "supported_reasoning_levels": [+ {"effort": "low", "description": "fast"},+ {"effort": "high", "description": "deeper"},+ ],+ "base_instructions": "large prompt metadata should stay ignored",+ },+ {"slug": "no-reasoning", "supported_reasoning_levels": []},+ ]+ }+ )++ assert catalog == {+ "gpt-5.5": CodexModelReasoning(+ slug="gpt-5.5",+ default_effort="medium",+ supported_efforts=("low", "high"),+ )+ }+++def test_provider_name_and_default_model(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)++ provider = CodexCliProvider(repo_path=tmp_path)++ assert provider.provider_name == "codex_cli"+ assert provider.model_name == "codex_cli/default"+++def test_custom_model_is_normalized_for_attribution(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)++ assert CodexCliProvider(model="gpt-5.5", repo_path=tmp_path).model_name == "codex_cli/gpt-5.5"+ assert (+ CodexCliProvider(model="codex_cli/gpt-5.5", repo_path=tmp_path).model_name+ == "codex_cli/gpt-5.5"+ )+ assert (+ CodexCliProvider(model="codex_cli/default", repo_path=tmp_path).model_name+ == "codex_cli/default"+ )+++def test_supported_reasoning_modes_reflect_codex_catalog(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)+ monkeypatch.setattr(+ "repowise.core.providers.llm.codex_cli._load_codex_model_catalog",+ lambda _cmd: _reasoning_catalog("none", "low", "medium", "high", "xhigh"),+ )++ assert CodexCliProvider(+ model="gpt-5.5",+ repo_path=tmp_path,+ ).supported_reasoning_modes() == (+ "auto",+ "off",+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ )+++def test_available_model_options_reflect_codex_catalog(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)+ monkeypatch.setattr(+ "repowise.core.providers.llm.codex_cli._load_codex_model_catalog",+ lambda _cmd: _reasoning_catalog(+ "none",+ "low",+ "medium",+ "high",+ slug="gpt-5.5",+ default="medium",+ ),+ )++ options = CodexCliProvider(repo_path=tmp_path).available_model_options()++ assert options[0].model == "codex_cli/default"+ assert options[0].recommended is True+ model_option = next(option for option in options if option.model == "codex_cli/gpt-5.5")+ assert model_option.label == "gpt-5.5"+ assert model_option.source == "local"+ assert model_option.reasoning_modes == (+ "auto",+ "off",+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ )+++def test_missing_cli_raises(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda _cmd: None)++ with pytest.raises(ProviderError, match="Codex CLI not found"):+ CodexCliProvider(repo_path=tmp_path)+++async def test_generate_invokes_codex_exec_with_stdin(monkeypatch, tmp_path):+ codex_cmd = str(tmp_path / "bin" / "codex.CMD")+ monkeypatch.setattr("shutil.which", lambda cmd: codex_cmd if cmd == "codex" else None)+ monkeypatch.setattr(+ "repowise.core.providers.llm.codex_cli._load_codex_model_catalog",+ lambda _cmd: _reasoning_catalog("low", "medium", "high", "xhigh"),+ )+ captured: dict[str, Any] = {}+ proc = FakeProcess(stdout=_success_jsonl("Hello from Codex"), stderr="plugin sync warning")++ async def fake_exec(*args: str, **kwargs: Any) -> FakeProcess:+ captured["args"] = args+ captured["kwargs"] = kwargs+ return proc++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ provider = CodexCliProvider(model="gpt-5.5", repo_path=tmp_path)+ result = await provider.generate("system rules", "user context", reasoning="minimal")++ assert isinstance(result, GeneratedResponse)+ assert result.content == "Hello from Codex"+ assert proc.stdin_input is not None+ prompt = proc.stdin_input.decode("utf-8")+ assert "system rules" in prompt+ assert "user context" in prompt+ args = list(captured["args"])+ assert args[:6] == [codex_cmd, "exec", "--ephemeral", "--sandbox", "read-only", "--json"]+ assert args[args.index("--cd") + 1] == str(tmp_path.resolve())+ assert args[args.index("--config") + 1] == 'model_reasoning_effort="low"'+ assert args[args.index("--model") + 1] == "gpt-5.5"+ assert args[-1] == "-"+ assert captured["kwargs"]["stdin"] == asyncio.subprocess.PIPE+++async def test_generate_passes_supported_codex_reasoning_effort(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)+ monkeypatch.setattr(+ "repowise.core.providers.llm.codex_cli._load_codex_model_catalog",+ lambda _cmd: _reasoning_catalog("low", "medium", "high", "xhigh"),+ )+ captured: dict[str, Any] = {}++ async def fake_exec(*args: str, **_kwargs: Any) -> FakeProcess:+ captured["args"] = args+ return FakeProcess(stdout=_success_jsonl("OK"))++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ await CodexCliProvider(model="gpt-5.5", repo_path=tmp_path).generate(+ "sys",+ "user",+ reasoning="xhigh",+ )++ args = list(captured["args"])+ assert args[args.index("--config") + 1] == 'model_reasoning_effort="xhigh"'+++async def test_generate_passes_unknown_model_effort_without_catalog_block(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)+ monkeypatch.setattr(+ "repowise.core.providers.llm.codex_cli._load_codex_model_catalog",+ lambda _cmd: _reasoning_catalog("low", "medium", "high", "xhigh"),+ )+ captured: dict[str, Any] = {}++ async def fake_exec(*args: str, **_kwargs: Any) -> FakeProcess:+ captured["args"] = args+ return FakeProcess(stdout=_success_jsonl("OK"))++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ await CodexCliProvider(model="future-codex", repo_path=tmp_path).generate(+ "sys",+ "user",+ reasoning="max",+ )++ args = list(captured["args"])+ assert args[args.index("--config") + 1] == 'model_reasoning_effort="max"'+ assert args[args.index("--model") + 1] == "future-codex"+++async def test_generate_uses_jsonl_usage_and_ignores_noise(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)++ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:+ return FakeProcess(stdout=_success_jsonl("OK"))++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ result = await CodexCliProvider(repo_path=tmp_path).generate("sys", "user")++ assert result.input_tokens == 120+ assert result.output_tokens == 40+ assert result.cached_tokens == 30+ assert result.usage["reasoning_output_tokens"] == 10+ assert result.usage["source"] == "codex_exec"+ assert "estimated" not in result.usage+++async def test_generate_accepts_cache_hints(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)++ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:+ return FakeProcess(stdout=_success_jsonl("OK"))++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ result = await CodexCliProvider(repo_path=tmp_path).generate(+ "sys",+ "user",+ cache_hints=(),+ )++ assert result.content == "OK"+++async def test_generate_closes_subprocess_transport(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)+ transport = FakeTransport()++ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:+ return FakeProcess(stdout=_success_jsonl("OK"), transport=transport)++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ await CodexCliProvider(repo_path=tmp_path).generate("sys", "user")++ assert transport.closed is True+++async def test_generate_marks_missing_usage_as_estimated(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)++ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:+ return FakeProcess(+ stdout=_jsonl(+ {+ "type": "item.completed",+ "item": {"type": "agent_message", "text": "OK"},+ }+ )+ )++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ result = await CodexCliProvider(repo_path=tmp_path).generate("sys", "user")++ assert result.input_tokens == 0+ assert result.output_tokens == 0+ assert result.usage["estimated"] is True+++async def test_generate_raises_on_nonzero_exit(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)++ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:+ return FakeProcess(returncode=1, stdout="", stderr="not logged in")++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ with pytest.raises(ProviderError, match="not logged in"):+ await CodexCliProvider(repo_path=tmp_path).generate("sys", "user")+++async def test_generate_hides_structured_error_stdout(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)++ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:+ return FakeProcess(returncode=2, stdout='{"error":{"message":"secret details"}}')++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ with pytest.raises(ProviderError, match="codex exec exited with 2") as exc_info:+ await CodexCliProvider(repo_path=tmp_path).generate("sys", "user")++ assert "secret details" not in str(exc_info.value)+++async def test_generate_raises_when_jsonl_has_no_agent_message(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)++ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:+ return FakeProcess(stdout=_jsonl({"type": "turn.completed", "usage": {}}))++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ with pytest.raises(ProviderError, match="no agent_message"):+ await CodexCliProvider(repo_path=tmp_path).generate("sys", "user")+++async def test_generate_serializes_subprocess_calls(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)+ active = 0+ max_active = 0++ async def on_communicate() -> None:+ nonlocal active, max_active+ active += 1+ max_active = max(max_active, active)+ await asyncio.sleep(0.01)+ active -= 1++ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:+ return FakeProcess(stdout=_success_jsonl("OK"), on_communicate=on_communicate)++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)+ provider = CodexCliProvider(repo_path=tmp_path)++ await asyncio.gather(+ provider.generate("sys", "user 1"),+ provider.generate("sys", "user 2"),+ )++ assert max_active == 1+++async def test_generate_times_out_and_kills_codex_exec(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)+ monkeypatch.setattr(+ "repowise.core.providers.llm.codex_cli._EXEC_TIMEOUT_SECONDS",+ 0.01,+ )++ async def on_communicate() -> None:+ await asyncio.sleep(1)++ proc = FakeProcess(stdout="", on_communicate=on_communicate)++ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:+ return proc++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ with pytest.raises(ProviderError, match="timed out"):+ await CodexCliProvider(repo_path=tmp_path).generate("sys", "user")++ assert proc.killed+++async def test_generate_rejects_unsupported_reasoning_off(monkeypatch, tmp_path):+ monkeypatch.setattr("shutil.which", lambda cmd: "codex" if cmd == "codex" else None)+ monkeypatch.setattr(+ "repowise.core.providers.llm.codex_cli._load_codex_model_catalog",+ lambda _cmd: _reasoning_catalog("low", "medium", "high", "xhigh"),+ )++ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:+ raise AssertionError("subprocess should not be started")++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ with pytest.raises(ProviderError, match="model_reasoning_effort='none'"):+ await CodexCliProvider(repo_path=tmp_path).generate("sys", "user", reasoning="off")diff --git a/tests/unit/test_providers/test_cost_estimator.py b/tests/unit/test_providers/test_cost_estimator.pyindex 56c7f2fda..5dd297905 100644--- a/tests/unit/test_providers/test_cost_estimator.py+++ b/tests/unit/test_providers/test_cost_estimator.py@@ -30,6 +30,8 @@ from repowise.cli.cost_estimator.heuristics import heuristic_tokens# Free/local models("mock", 0.0, 0.0),("llama3", 0.0, 0.0),+ ("codex_cli/default", 0.0, 0.0),+ ("codex_cli/gpt-5.5", 0.0, 0.0),],)def test_lookup_cost(model, expected_input, expected_output):diff --git a/tests/unit/test_providers/test_deepseek_provider.py b/tests/unit/test_providers/test_deepseek_provider.pyindex a265f67f3..a3eabffe4 100644--- a/tests/unit/test_providers/test_deepseek_provider.py+++ b/tests/unit/test_providers/test_deepseek_provider.py@@ -51,6 +51,47 @@ def test_custom_base_url():assert p.provider_name == "deepseek"+def test_available_model_options_uses_models_endpoint(monkeypatch):+ class FakeResponse:+ def raise_for_status(self) -> None:+ pass++ def json(self) -> dict:+ return {+ "data": [+ {"id": "deepseek-v4-flash"},+ {"id": "deepseek-v4-pro"},+ ]+ }++ captured: dict[str, object] = {}++ def fake_get(url, *, headers, timeout):+ captured["url"] = url+ captured["headers"] = headers+ captured["timeout"] = timeout+ return FakeResponse()++ monkeypatch.setattr("httpx.get", fake_get)++ options = DeepSeekProvider(api_key="sk-test").available_model_options()++ assert captured["url"] == "https://api.deepseek.com/models"+ assert captured["headers"] == {"Authorization": "Bearer sk-test"}+ flash = next(option for option in options if option.model == "deepseek-v4-flash")+ assert flash.reasoning_modes == (+ "auto",+ "off",+ "none",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+ )+ assert flash.recommended is True++def _make_mock_chat_response(text: str = "# Doc\nContent.") -> MagicMock:usage = MagicMock()usage.prompt_tokens = 120@@ -131,13 +172,26 @@ async def test_generate_uses_correct_model_name():assert kwargs["model"] == "deepseek-v4-flash"-async def test_generate_rejects_unsupported_reasoning_mode():+async def test_generate_forwards_disabled_thinking():provider = DeepSeekProvider(api_key="sk-test")+ mock_response = _make_mock_chat_response()++ with patch("openai.AsyncOpenAI") as mock_client:+ mock_client.return_value.chat.completions.create = AsyncMock(return_value=mock_response)+ provider._client = mock_client.return_value+ await provider.generate("system", "user", reasoning="off")++ kwargs = mock_client.return_value.chat.completions.create.call_args.kwargs+ assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}+++async def test_generate_rejects_reasoning_for_non_v4_model():+ provider = DeepSeekProvider(api_key="sk-test", model="deepseek-chat")with patch("openai.AsyncOpenAI") as mock_client:provider._client = mock_client.return_value- with pytest.raises(ProviderError, match="reasoning='off' is not supported"):- await provider.generate("system", "user", reasoning="off")+ with pytest.raises(ProviderError, match="reasoning='high' is not supported"):+ await provider.generate("system", "user", reasoning="high")mock_client.return_value.chat.completions.create.assert_not_called()diff --git a/tests/unit/test_providers/test_gemini_provider.py b/tests/unit/test_providers/test_gemini_provider.pyindex aa79213cb..6d9371857 100644--- a/tests/unit/test_providers/test_gemini_provider.py+++ b/tests/unit/test_providers/test_gemini_provider.py@@ -11,6 +11,7 @@ import pytestpytest.importorskip("google.genai", reason="google-genai SDK not installed")+from repowise.core.providers.llm import gemini as gemini_modulefrom repowise.core.providers.llm.base import GeneratedResponse, ProviderError, RateLimitErrorfrom repowise.core.providers.llm.gemini import GeminiProvider@@ -54,6 +55,66 @@ def test_model_name_custom():assert p.model_name == "gemini-3-flash-preview"+def test_available_model_options_lists_generate_content_models(monkeypatch):+ class FakeResponse:+ def __init__(self, payload: dict) -> None:+ self._payload = payload++ def raise_for_status(self) -> None:+ pass++ def json(self) -> dict:+ return self._payload++ calls: list[dict[str, object]] = []++ def fake_get(url, *, headers, params, timeout):+ calls.append(+ {+ "url": url,+ "headers": headers,+ "params": params,+ "timeout": timeout,+ }+ )+ return FakeResponse(+ {+ "models": [+ {+ "name": "models/gemini-3.1-flash-lite-preview",+ "displayName": "Gemini Flash Lite",+ "supportedGenerationMethods": ["generateContent"],+ "thinking": True,+ },+ {+ "name": "models/gemini-embed",+ "supportedGenerationMethods": ["embedContent"],+ },+ ]+ }+ )++ monkeypatch.setattr("httpx.get", fake_get)++ options = GeminiProvider(api_key="k").available_model_options()++ assert calls[0]["url"] == "https://generativelanguage.googleapis.com/v1beta/models"+ assert calls[0]["headers"] == {"x-goog-api-key": "k"}+ models = [option.model for option in options]+ assert "gemini-3.1-flash-lite-preview" in models+ assert "gemini-embed" not in models+ option = next(option for option in options if option.model == "gemini-3.1-flash-lite-preview")+ assert option.label == "Gemini Flash Lite"+ assert option.reasoning_modes == ("auto", "minimal", "low", "medium", "high")+ assert GeminiProvider(api_key="k").supported_reasoning_modes() == (+ "auto",+ "minimal",+ "low",+ "medium",+ "high",+ )++# ---------------------------------------------------------------------------# Successful generation# ---------------------------------------------------------------------------@@ -117,6 +178,25 @@ async def test_generate_passes_max_tokens():assert captured[0].max_output_tokens is None+async def test_generate_forwards_thinking_level():+ gemini_module._GEMINI_THINKING_MODELS_BY_BASE[gemini_module._gemini_cache_key(None)] = {+ "gemini-3.1-flash-lite-preview"+ }+ provider = GeminiProvider(api_key="fake-key")+ mock_response = _make_mock_response()+ captured: list = []++ def fake_generate_content(model, contents, config):+ captured.append(config)+ return mock_response++ with patch("google.genai.Client") as mock_client:+ mock_client.return_value.models.generate_content.side_effect = fake_generate_content+ await provider.generate("sys", "user", reasoning="high")++ assert captured[0].thinking_config.thinking_level.value == "HIGH"++# ---------------------------------------------------------------------------# Error mapping# ---------------------------------------------------------------------------diff --git a/tests/unit/test_providers/test_litellm_provider.py b/tests/unit/test_providers/test_litellm_provider.pynew file mode 100644index 000000000..12693a33c--- /dev/null+++ b/tests/unit/test_providers/test_litellm_provider.py@@ -0,0 +1,78 @@+"""Unit tests for LiteLLMProvider."""++from __future__ import annotations++from unittest.mock import AsyncMock++import pytest++from repowise.core.providers.llm.base import ProviderError+from repowise.core.providers.llm.litellm import LiteLLMProvider+++def test_available_model_options_uses_litellm_model_list(monkeypatch):+ litellm = pytest.importorskip("litellm", reason="litellm SDK not installed")+ monkeypatch.setattr(+ litellm,+ "model_list",+ ["vendor/plain", "vendor/reasoner"],+ raising=False,+ )+ monkeypatch.setattr(+ litellm,+ "supports_reasoning",+ lambda *, model: model == "vendor/reasoner",+ raising=False,+ )++ options = LiteLLMProvider(model="vendor/plain").available_model_options()++ models = [option.model for option in options]+ assert models[:2] == ["vendor/plain", "vendor/reasoner"]+ reasoner = next(option for option in options if option.model == "vendor/reasoner")+ assert reasoner.source == "local"+ assert reasoner.reasoning_modes == ("auto", "low", "medium", "high")+ assert "reasoning support" in reasoner.notes+++async def test_generate_rejects_explicit_reasoning_before_litellm_call(monkeypatch):+ litellm = pytest.importorskip("litellm", reason="litellm SDK not installed")+ monkeypatch.setattr(litellm, "acompletion", AsyncMock(), raising=False)++ provider = LiteLLMProvider(model="vendor/plain")++ with pytest.raises(ProviderError, match="reasoning='low' is not supported"):+ await provider.generate("sys", "user", reasoning="low")++ litellm.acompletion.assert_not_called()+++async def test_generate_forwards_reasoning_effort(monkeypatch):+ litellm = pytest.importorskip("litellm", reason="litellm SDK not installed")+ fake_response = type(+ "Response",+ (),+ {+ "choices": [+ type(+ "Choice",+ (),+ {"message": type("Message", (), {"content": "ok"})()},+ )()+ ],+ "usage": None,+ },+ )()+ completion = AsyncMock(return_value=fake_response)+ monkeypatch.setattr(litellm, "acompletion", completion, raising=False)+ monkeypatch.setattr(+ litellm,+ "supports_reasoning",+ lambda *, model: model == "vendor/reasoner",+ raising=False,+ )++ provider = LiteLLMProvider(model="vendor/reasoner")+ await provider.generate("sys", "user", reasoning="high")++ assert completion.call_args.kwargs["reasoning_effort"] == "high"diff --git a/tests/unit/test_providers/test_ollama_provider.py b/tests/unit/test_providers/test_ollama_provider.pynew file mode 100644index 000000000..8806d425b--- /dev/null+++ b/tests/unit/test_providers/test_ollama_provider.py@@ -0,0 +1,48 @@+"""Unit tests for OllamaProvider."""++from __future__ import annotations++import pytest++pytest.importorskip("openai", reason="openai SDK not installed")++from repowise.core.providers.llm.ollama import OllamaProvider+++def test_available_model_options_reads_local_tags(monkeypatch):+ class FakeResponse:+ def raise_for_status(self) -> None:+ pass++ def json(self) -> dict:+ return {+ "models": [+ {+ "name": "llama3.2:latest",+ "details": {+ "family": "llama",+ "parameter_size": "3B",+ },+ },+ {"model": "qwen2.5-coder:7b"},+ ]+ }++ captured: dict[str, object] = {}++ def fake_get(url, *, timeout):+ captured["url"] = url+ captured["timeout"] = timeout+ return FakeResponse()++ monkeypatch.setattr("httpx.get", fake_get)++ options = OllamaProvider(base_url="http://localhost:11434").available_model_options()++ assert captured["url"] == "http://localhost:11434/api/tags"+ models = [option.model for option in options]+ assert models == ["llama3.2:latest", "qwen2.5-coder:7b"]+ llama = options[0]+ assert llama.source == "local"+ assert llama.notes == "llama, 3B"+ assert llama.reasoning_modes == ("auto",)diff --git a/tests/unit/test_providers/test_openai_provider.py b/tests/unit/test_providers/test_openai_provider.pyindex d9da1b8f0..4fd00a23a 100644--- a/tests/unit/test_providers/test_openai_provider.py+++ b/tests/unit/test_providers/test_openai_provider.py@@ -46,11 +46,78 @@ def test_custom_model():assert p.model_name == "gpt-5.4-mini"+def test_supported_reasoning_modes_are_model_specific():+ assert OpenAIProvider(+ api_key="sk-test",+ model="gpt-5-mini",+ ).supported_reasoning_modes() == ("auto", "minimal", "low", "medium", "high")+ assert OpenAIProvider(+ api_key="sk-test",+ model="qwen3",+ ).supported_reasoning_modes() == ("auto", "off", "none")+ assert OpenAIProvider(+ api_key="sk-test",+ model="gpt-4o",+ ).supported_reasoning_modes() == ("auto",)++def test_gpt54_model():p = OpenAIProvider(api_key="sk-test", model="gpt-5.4")assert p.model_name == "gpt-5.4"+def test_available_model_options_uses_models_endpoint(monkeypatch):+ class FakeResponse:+ def raise_for_status(self) -> None:+ pass++ def json(self) -> dict:+ return {+ "data": [+ {"id": "gpt-5.4-nano"},+ {"id": "gpt-4.1"},+ {"id": "text-embedding-3-large"},+ ]+ }++ captured: dict[str, object] = {}++ def fake_get(url, *, headers, timeout):+ captured["url"] = url+ captured["headers"] = headers+ captured["timeout"] = timeout+ return FakeResponse()++ monkeypatch.setattr("httpx.get", fake_get)++ options = OpenAIProvider(api_key="sk-test").available_model_options()++ assert captured["url"] == "https://api.openai.com/v1/models"+ assert captured["headers"] == {"Authorization": "Bearer sk-test"}+ assert "gpt-5.4-nano" in [option.model for option in options]+ assert "text-embedding-3-large" not in [option.model for option in options]+ assert next(option for option in options if option.model == "gpt-5.4-nano").reasoning_modes == (+ "auto",+ "minimal",+ "low",+ "medium",+ "high",+ )+++def test_available_model_options_falls_back_to_configured_model(monkeypatch):+ def fake_get(*_args, **_kwargs):+ raise RuntimeError("offline")++ monkeypatch.setattr("httpx.get", fake_get)++ options = OpenAIProvider(api_key="sk-test").available_model_options()++ assert options[0].model == "gpt-5.4-nano"+ assert options[0].recommended is True+ assert options[0].source == "fallback"++# ---------------------------------------------------------------------------# Successful generation# ---------------------------------------------------------------------------@@ -141,6 +208,23 @@ async def test_generate_forwards_minimal_reasoning_effort():assert captured_kwargs[0]["reasoning_effort"] == "minimal"+async def test_generate_forwards_none_reasoning_effort_for_gpt51():+ provider = OpenAIProvider(api_key="sk-test", model="gpt-5.1")+ mock_response = _make_mock_chat_response()+ captured_kwargs: list[dict] = []++ async def fake_create(**kwargs):+ captured_kwargs.append(kwargs)+ return mock_response++ with patch("openai.AsyncOpenAI") as mock_client:+ mock_client.return_value.chat.completions.create = fake_create+ provider._client = mock_client.return_value+ await provider.generate("system msg", "user msg", reasoning="none")++ assert captured_kwargs[0]["reasoning_effort"] == "none"++async def test_generate_forwards_off_reasoning_extra_body():provider = OpenAIProvider(api_key="sk-test", model="qwen3")mock_response = _make_mock_chat_response()@@ -155,9 +239,24 @@ async def test_generate_forwards_off_reasoning_extra_body():provider._client = mock_client.return_valueawait provider.generate("system msg", "user msg", reasoning="off")- assert captured_kwargs[0]["extra_body"] == {- "chat_template_kwargs": {"enable_thinking": False}- }+ assert captured_kwargs[0]["extra_body"] == {"chat_template_kwargs": {"enable_thinking": False}}+++async def test_generate_forwards_none_reasoning_as_thinking_disabled():+ provider = OpenAIProvider(api_key="sk-test", model="qwen3")+ mock_response = _make_mock_chat_response()+ captured_kwargs: list[dict] = []++ async def fake_create(**kwargs):+ captured_kwargs.append(kwargs)+ return mock_response++ with patch("openai.AsyncOpenAI") as mock_client:+ mock_client.return_value.chat.completions.create = fake_create+ provider._client = mock_client.return_value+ await provider.generate("system msg", "user msg", reasoning="none")++ assert captured_kwargs[0]["extra_body"] == {"chat_template_kwargs": {"enable_thinking": False}}async def test_generate_rejects_minimal_for_non_reasoning_model():@@ -173,7 +272,7 @@ async def test_generate_rejects_minimal_for_non_reasoning_model():@pytest.mark.parametrize("model",- ["gpt-5.1", "gpt-5.2", "gpt-5-pro", "gpt-5-codex", "gpt-5.4-nano"],+ ["gpt-5.1", "gpt-5-pro"],)async def test_generate_rejects_minimal_for_known_unsupported_reasoning_models(model):provider = OpenAIProvider(api_key="sk-test", model=model)diff --git a/tests/unit/test_providers/test_openrouter_provider.py b/tests/unit/test_providers/test_openrouter_provider.pyindex d8f85ad6c..3b6383452 100644--- a/tests/unit/test_providers/test_openrouter_provider.py+++ b/tests/unit/test_providers/test_openrouter_provider.py@@ -11,6 +11,7 @@ import pytestpytest.importorskip("openai", reason="openai SDK not installed")+from repowise.core.providers.llm import openrouter as openrouter_modulefrom repowise.core.providers.llm.base import GeneratedResponse, ProviderError, RateLimitErrorfrom repowise.core.providers.llm.openrouter import OpenRouterProvider@@ -46,6 +47,17 @@ def test_custom_model():assert p.model_name == "google/gemini-3.1-flash-lite-preview"+def test_supported_reasoning_modes_are_model_specific():+ assert OpenRouterProvider(+ api_key="sk-or-test",+ model="x-ai/grok-4",+ ).supported_reasoning_modes() == ("auto",)+ assert OpenRouterProvider(+ api_key="sk-or-test",+ model="anthropic/claude-sonnet-4.6",+ ).supported_reasoning_modes() == ("auto",)++def test_default_headers_app_title():"""Default app_title='repowise' sets X-Title header."""p = OpenRouterProvider(api_key="sk-or-test")@@ -84,6 +96,62 @@ def test_rejects_unknown_kwargs():OpenRouterProvider(api_key="sk-or-test", future_param="oops")+def test_available_model_options_uses_models_endpoint(monkeypatch):+ class FakeResponse:+ def raise_for_status(self) -> None:+ pass++ def json(self) -> dict:+ return {+ "data": [+ {+ "id": "vendor/reasoner",+ "name": "Vendor Reasoner",+ "supported_parameters": ["reasoning", "tools"],+ },+ {+ "id": "vendor/plain",+ "name": "Vendor Plain",+ "supported_parameters": ["tools"],+ },+ ]+ }++ captured: dict[str, object] = {}++ def fake_get(url, *, headers, timeout):+ captured["url"] = url+ captured["headers"] = headers+ captured["timeout"] = timeout+ return FakeResponse()++ monkeypatch.setattr("httpx.get", fake_get)++ provider = OpenRouterProvider(api_key="sk-or-test")+ options = provider.available_model_options()++ assert captured["url"] == "https://openrouter.ai/api/v1/models"+ assert captured["headers"] == {"Authorization": "Bearer sk-or-test"}+ reasoner = next(option for option in options if option.model == "vendor/reasoner")+ assert reasoner.reasoning_modes == (+ "auto",+ "off",+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ )+ assert (+ OpenRouterProvider(+ api_key="sk-or-test",+ model="vendor/reasoner",+ ).supported_reasoning_modes()+ == reasoner.reasoning_modes+ )++# ---------------------------------------------------------------------------# Successful generation# ---------------------------------------------------------------------------@@ -132,7 +200,9 @@ async def test_generate_token_counts():async def test_generate_sends_correct_messages():- provider = OpenRouterProvider(api_key="sk-or-test", model="google/gemini-3.1-flash-lite-preview")+ provider = OpenRouterProvider(+ api_key="sk-or-test", model="google/gemini-3.1-flash-lite-preview"+ )mock_response = _make_mock_chat_response()captured_kwargs: list[dict] = []@@ -156,6 +226,9 @@ async def test_generate_sends_correct_messages():async def test_generate_forwards_minimal_reasoning_extra_body():+ openrouter_module._OPENROUTER_REASONING_MODELS_BY_BASE["https://openrouter.ai/api/v1"] = {+ "openai/gpt-5"+ }provider = OpenRouterProvider(api_key="sk-or-test", model="openai/gpt-5")mock_response = _make_mock_chat_response()captured_kwargs: list[dict] = []@@ -169,12 +242,33 @@ async def test_generate_forwards_minimal_reasoning_extra_body():provider._client = mock_client.return_valueawait provider.generate("system msg", "user msg", reasoning="minimal")- assert captured_kwargs[0]["extra_body"] == {- "reasoning": {"effort": "minimal"}+ assert captured_kwargs[0]["extra_body"] == {"reasoning": {"effort": "minimal"}}+++async def test_generate_forwards_high_reasoning_extra_body():+ openrouter_module._OPENROUTER_REASONING_MODELS_BY_BASE["https://openrouter.ai/api/v1"] = {+ "x-ai/grok-4"}+ provider = OpenRouterProvider(api_key="sk-or-test", model="x-ai/grok-4")+ mock_response = _make_mock_chat_response()+ captured_kwargs: list[dict] = []++ async def fake_create(**kwargs):+ captured_kwargs.append(kwargs)+ return mock_response++ with patch("openai.AsyncOpenAI") as mock_client:+ mock_client.return_value.chat.completions.create = fake_create+ provider._client = mock_client.return_value+ await provider.generate("system msg", "user msg", reasoning="high")++ assert captured_kwargs[0]["extra_body"] == {"reasoning": {"effort": "high"}}async def test_generate_forwards_off_reasoning_extra_body():+ openrouter_module._OPENROUTER_REASONING_MODELS_BY_BASE["https://openrouter.ai/api/v1"] = {+ "x-ai/grok-4"+ }provider = OpenRouterProvider(api_key="sk-or-test", model="x-ai/grok-4")mock_response = _make_mock_chat_response()captured_kwargs: list[dict] = []@@ -191,10 +285,32 @@ async def test_generate_forwards_off_reasoning_extra_body():assert captured_kwargs[0]["extra_body"] == {"reasoning": {"effort": "none"}}-async def test_generate_rejects_reasoning_for_unsupported_openrouter_model():- provider = OpenRouterProvider(- api_key="sk-or-test", model="google/gemini-3.1-flash-lite-preview"- )+async def test_generate_forwards_none_reasoning_extra_body():+ openrouter_module._OPENROUTER_REASONING_MODELS_BY_BASE["https://openrouter.ai/api/v1"] = {+ "x-ai/grok-4"+ }+ provider = OpenRouterProvider(api_key="sk-or-test", model="x-ai/grok-4")+ mock_response = _make_mock_chat_response()+ captured_kwargs: list[dict] = []++ async def fake_create(**kwargs):+ captured_kwargs.append(kwargs)+ return mock_response++ with patch("openai.AsyncOpenAI") as mock_client:+ mock_client.return_value.chat.completions.create = fake_create+ provider._client = mock_client.return_value+ await provider.generate("system msg", "user msg", reasoning="none")++ assert captured_kwargs[0]["extra_body"] == {"reasoning": {"effort": "none"}}+++async def test_generate_rejects_reasoning_for_unsupported_openrouter_model(monkeypatch):+ def fake_get(*_args, **_kwargs):+ raise RuntimeError("offline")++ monkeypatch.setattr("httpx.get", fake_get)+ provider = OpenRouterProvider(api_key="sk-or-test", model="anthropic/claude-sonnet-4.6")with patch("openai.AsyncOpenAI") as mock_client:provider._client = mock_client.return_value@@ -206,9 +322,13 @@ async def test_generate_rejects_reasoning_for_unsupported_openrouter_model():@pytest.mark.parametrize("model",- ["openai/gpt-5.2", "openai/gpt-5-pro", "openai/gpt-5-codex", "openai/gpt-5.4-nano"],+ ["openai/gpt-4.1", "anthropic/claude-sonnet-4.6"],)-async def test_generate_rejects_reasoning_for_known_unsupported_openai_route(model):+async def test_generate_rejects_reasoning_for_known_unsupported_openai_route(monkeypatch, model):+ def fake_get(*_args, **_kwargs):+ raise RuntimeError("offline")++ monkeypatch.setattr("httpx.get", fake_get)provider = OpenRouterProvider(api_key="sk-or-test", model=model)with patch("openai.AsyncOpenAI") as mock_client:diff --git a/website/cli-reference.md b/website/cli-reference.mdindex d0906e12c..75816a0f1 100644--- a/website/cli-reference.md+++ b/website/cli-reference.md@@ -44,7 +44,7 @@ repowise init [PATH] [OPTIONS]| Flag | Type | Default | Description ||------|------|---------|-------------|-| `--provider` | string | auto | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `ollama`, `litellm`, `mock` |+| `--provider` | string | auto | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `ollama`, `litellm`, `codex_cli`, `mock` || `--model` | string | — | Model override (e.g., `claude-sonnet-4-6`, `gpt-4.1`) || `--embedder` | choice | auto | Embedding provider: `gemini`, `openai`, `mock` || `--index-only` | flag | false | Skip LLM generation — parse, graph, git, dead code only |@@ -55,12 +55,14 @@ repowise init [PATH] [OPTIONS]| `--exclude` / `-x` | string | — | Gitignore-style exclude pattern (repeatable: `-x vendor/ -x "*.gen.*"`) || `--include-submodules` | flag | false | Include git submodule directories (excluded by default) || `--concurrency` | int | 5 | Max concurrent LLM calls |-| `--reasoning` | choice | auto | Reasoning mode for supported providers: `auto`, `off`, or `minimal` |+| `--reasoning` | choice | auto | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` || `--resume` | flag | false | Resume from last checkpoint after an interruption || `--force` | flag | false | Regenerate all pages even if up to date || `--commit-limit` | int | 500 | Max commits per file for git analysis (max 5000, saved to config) || `--follow-renames` | flag | false | Track file renames in git history (saved to config) || `--no-claude-md` | flag | false | Skip generating `.claude/CLAUDE.md` |+| `--agents` / `--no-agents` | flag | config | Generate or skip managed `AGENTS.md` for Codex |+| `--codex` / `--no-codex` | flag | prompt/skip | Generate or skip project-local Codex MCP config and hooks || `--yes` / `-y` | flag | false | Skip the cost confirmation prompt |### Examples@@ -72,6 +74,9 @@ repowise init# Non-interactive, specific providerrepowise init --provider anthropic --yes+# Use the authenticated local Codex CLI+repowise init --provider codex_cli --codex --yes+# OpenAI-compatible Qwen3 endpoint with thinking disabledrepowise init --provider openai --model qwen3 --reasoning off@@ -102,7 +107,7 @@ repowise init --resume1. **Ingestion** — parses all files with tree-sitter, builds dependency graph2. **Analysis** — git churn/ownership, dead code detection, decision mining3. **Generation** — LLM writes wiki pages at repo/module/file level (skipped with `--index-only`)-4. **Persistence** — writes to SQLite, builds vector index, generates `.claude/CLAUDE.md`+4. **Persistence** — writes to SQLite, builds vector index, generates managed editor instruction files### Provider auto-detection@@ -128,9 +133,10 @@ repowise update [PATH] [OPTIONS]| `--provider` | string | — | Override LLM provider || `--model` | string | — | Override model || `--since` | string | — | Git ref to diff from (overrides saved `state.json`) |-| `--reasoning` | choice | auto | Reasoning mode for supported providers: `auto`, `off`, or `minimal` |+| `--reasoning` | choice | auto | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` || `--cascade-budget` | int | auto | Max pages to regenerate from cascading changes || `--dry-run` | flag | false | Show affected pages without regenerating |+| `--agents` / `--no-agents` | flag | config | Generate or skip managed `AGENTS.md` after update |### Examplesdiff --git a/website/codex.md b/website/codex.mdnew file mode 100644index 000000000..7148f9828--- /dev/null+++ b/website/codex.md@@ -0,0 +1,120 @@+---+layout: default+title: Codex Integration+nav_order: 5.5+---++# Codex Integration+{: .no_toc }++Use Repowise with Codex MCP, lifecycle hooks, `AGENTS.md`, the `codex_cli` provider, and a local plugin.+{: .fs-6 .fw-300 }++---++## Table of contents+{: .no_toc .text-delta }++1. TOC+{:toc}++---++## Quick setup++```bash+npm install -g @openai/codex+codex login+codex login status++cd /path/to/your-repo+repowise init --codex --provider codex_cli --yes+```++`--codex` generates project-local `.codex/config.toml` and `.codex/hooks.json`. It does not write to global `~/.codex/config.toml`.++## MCP++Repowise writes:++```toml+[mcp_servers.repowise]+command = "repowise"+args = ["mcp"]+cwd = "/path/to/your-repo"+startup_timeout_sec = 20++[features]+hooks = true+```++`repowise mcp` can run without a path because it resolves upward to the nearest `.repowise` repository.++Smoke check:++```bash+codex mcp list+```++## Hooks++Codex hooks are written to `.codex/hooks.json`:++| Event | Purpose |+|-------|---------|+| `SessionStart` | Add Repowise MCP workflow guidance |+| `UserPromptSubmit` | Remind Codex that Repowise context is available |+| `PostToolUse` `Bash` | Detect git operations and stale wiki state |+| `PostToolUse` `apply_patch\|Edit\|Write` | Remind after edits that context may need refresh |++Repowise keeps Codex hooks focused on lifecycle guidance and freshness checks rather than trying to reuse Claude-specific search enrichment.++## Provider++`codex_cli` uses your local Codex CLI auth/subscription:++```bash+repowise init --provider codex_cli --yes+```++It runs:++```bash+codex exec --ephemeral --sandbox read-only --json --cd <repo> -+```++Repowise records token usage from Codex JSONL and treats `codex_cli/*` cost as `$0.00`. `--model` is passed to Codex only when explicitly configured.++## Plugin and skills++The Repowise repository includes a local Codex plugin at `plugins/codex` and a marketplace entry at `.agents/plugins/marketplace.json`.++```bash+cd /path/to/repowise+codex plugin marketplace add .+codex+/plugins+```++Install Repowise from the plugin browser. The plugin bundles MCP config, lifecycle hooks, and Codex-neutral skills. It does not add Claude-style slash commands. Plugin-bundled hooks are opt-in in current Codex releases; enable `[features] plugin_hooks = true` if you want hooks loaded from an installed plugin.++## AGENTS.md++`repowise init --codex` generates managed `AGENTS.md` by default. `repowise update` refreshes it when `editor_files.agents_md` is enabled, or when `--agents` is passed. Use:++```bash+repowise init --no-agents+repowise update --agents+```++User content outside the Repowise managed markers is preserved.++## Official docs++- [Codex hooks](https://developers.openai.com/codex/hooks)+- [Codex MCP](https://developers.openai.com/codex/mcp)+- [Codex non-interactive mode](https://developers.openai.com/codex/noninteractive)+- [Codex plugins](https://developers.openai.com/codex/plugins)+- [Build plugins](https://developers.openai.com/codex/plugins/build)+- [Codex skills](https://developers.openai.com/codex/skills)+- [AGENTS.md](https://developers.openai.com/codex/guides/agents-md)diff --git a/website/concepts.md b/website/concepts.mdindex 3593cb3b8..715f7f570 100644--- a/website/concepts.md+++ b/website/concepts.md@@ -111,7 +111,7 @@ repowise scans your git history, README files, and inline comments for patterns**What it captures:** Human-readable documentation at every level of the hierarchy.-Generation is the only layer that requires an LLM API key. repowise sends structured prompts to your chosen provider (Anthropic, OpenAI, Gemini, Ollama, or LiteLLM) and generates wiki pages at three levels:+Generation is the only layer that requires an LLM provider. repowise sends structured prompts to your chosen provider (Anthropic, OpenAI, Gemini, Ollama, LiteLLM, or the local Codex CLI provider) and generates wiki pages at three levels:| Level | What it contains ||-------|-----------------|@@ -161,7 +161,7 @@ The dependency graph is loaded into memory at server startup for fast traversal.## The MCP server-The MCP server sits on top of the persistence layer and exposes everything to AI coding assistants via 10 tools. It's the primary interface between repowise and Claude Code, Cursor, Cline, or any other MCP-compatible editor.+The MCP server sits on top of the persistence layer and exposes everything to AI coding assistants via 10 tools. It's the primary interface between repowise and Claude Code, Codex, Cursor, Cline, or any other MCP-compatible editor.When you run `repowise mcp`, the server starts in stdio mode and your editor can begin calling tools. The tools are designed to answer the questions an AI needs to make good decisions about your code — not just "what is this file" but "should I edit it", "why is it structured this way", and "what will break if I change it".diff --git a/website/configuration.md b/website/configuration.mdindex dededdd7c..ebd50c5ea 100644--- a/website/configuration.md+++ b/website/configuration.md@@ -46,28 +46,33 @@ The main configuration file. Created after first `init`, updated when you pass `provider: anthropic # LLM providermodel: claude-sonnet-4-6 # Model identifierembedder: gemini # Embedding provider-reasoning: auto # auto | off | minimal+reasoning: auto # auto | off/none | minimal | low | medium | high | xhigh | maxexclude_patterns: # Gitignore-style patterns- vendor/- "*.generated.*"- proto/commit_limit: 500 # Max commits per file for git analysisfollow_renames: false # Track file renames in git history+editor_files:+ claude_md: true+ agents_md: true```You can edit this file directly. Changes take effect on the next `init`, `update`, or `serve` run.`reasoning` controls documentation-generation calls for reasoning-capable chat-models. `auto` preserves provider defaults. `off` disables Qwen3-style thinking+models. `auto` preserves provider defaults. `off`/`none` disables Qwen3-style thinkingfor OpenAI-compatible vLLM/SGLang endpoints by sending`extra_body.chat_template_kwargs.enable_thinking=false`, and maps toOpenRouter's `reasoning.effort=none` for effort-capable OpenRouter modelfamilies. `minimal` requests OpenAI's lowest supported reasoning effort forsupported OpenAI reasoning models and maps to OpenRouter's`reasoning.effort=minimal` for effort-capable OpenRouter model families.-Providers or models that cannot translate an explicit mode fail before making-an API call. The interactive `serve` chat streaming path is separate and does-not currently consume this setting.+`low`, `medium`, `high`, `xhigh`, and `max` request native effort levels for+providers and model families that expose them. Providers or models that cannot+translate an explicit mode fail before making an API call. The interactive+`serve` chat streaming path is separate and does not currently consume this+setting.---@@ -171,6 +176,30 @@ repowise init --provider litellm --model azure/gpt-4---+### Codex CLI++Use your authenticated local Codex CLI subscription instead of an API key:++```bash+npm install -g @openai/codex+codex login+codex login status+repowise init --provider codex_cli --codex --yes+```++`codex_cli/default` uses the Codex CLI's configured model. `codex_cli/gpt-5.5` passes `--model gpt-5.5` to `codex exec`. Repowise records token usage from Codex JSONL output and treats `codex_cli/*` cost as `$0.00` because billing is handled by Codex CLI auth/subscription.++Project-local Codex setup is controlled by:++```yaml+editor_files:+ agents_md: true+```++Use `repowise init --codex` to write `.codex/config.toml` and `.codex/hooks.json`.++---+### Provider auto-detectionIf you don't pass `--provider`, repowise detects your provider by checking:@@ -179,6 +208,8 @@ If you don't pass `--provider`, repowise detects your provider by checking:2. `provider` in `.repowise/config.yaml`3. API key environment variables, in order: `ANTHROPIC_API_KEY` → `OPENAI_API_KEY` → `OLLAMA_BASE_URL` → `GEMINI_API_KEY`+Codex CLI is intentionally explicit: pass `--provider codex_cli` or set `REPOWISE_PROVIDER=codex_cli`.+---## Embeddings (for semantic search)diff --git a/website/getting-started.md b/website/getting-started.mdindex 77e84c498..39a81933b 100644--- a/website/getting-started.md+++ b/website/getting-started.md@@ -28,7 +28,8 @@ There are three ways to set up repowise. Pick the one that fits how you work.|------|----------|------|| [Claude Code Plugin](#path-1-claude-code-plugin) | Claude Code users | ~30 seconds || [pip + Claude Code](#path-2-pip--claude-code) | Manual control + Claude Code | ~2 minutes |-| [Standalone CLI](#path-3-standalone-cli) | No Claude Code, or CI use | ~2 minutes |+| [pip + Codex](#path-3-pip--codex) | Codex CLI users | ~2 minutes |+| [Standalone CLI](#path-4-standalone-cli) | No AI editor, or CI use | ~2 minutes |---@@ -145,7 +146,39 @@ To verify the MCP server is connected:----## Path 3: Standalone CLI+## Path 3: pip + Codex++Use the local Codex CLI auth/subscription flow and project-local MCP/hooks config.++### Step 1: Install repowise and Codex++```bash+pip install repowise+npm install -g @openai/codex+codex login+codex login status+```++### Step 2: Index your repo++```bash+cd /path/to/your-repo+repowise init --codex --provider codex_cli --yes+```++This writes `.codex/config.toml`, `.codex/hooks.json`, and managed `AGENTS.md` in the repository. It does not edit global `~/.codex/config.toml`.++### Step 3: Start Codex++```bash+codex+```++Codex reads `AGENTS.md`, starts the Repowise MCP server from project config, and receives lightweight lifecycle/freshness hooks. See [Codex Integration](codex).++---++## Path 4: Standalone CLIUse repowise without Claude Code — with the web dashboard, REST API, or any MCP-compatible editor.@@ -173,7 +206,7 @@ Open [http://localhost:3000](http://localhost:3000) in your browser. You'll see### Step 4: Start the MCP server (optional)-To connect any MCP-compatible editor (Cursor, Cline, Windsurf):+To connect any MCP-compatible editor (Codex, Cursor, Cline, Windsurf):```bashrepowise mcpdiff --git a/website/index.md b/website/index.mdindex 1534f8a3f..d617f2360 100644--- a/website/index.md+++ b/website/index.md@@ -24,7 +24,7 @@ repowise generates and maintains a structured wiki for any codebase. It tracks c| **Git intelligence** | Churn hotspots, ownership, bus factor, change patterns || **Dead code detection** | Finds confirmed unused exports, functions, and types || **Decision intelligence** | Captures *why* code is structured the way it is |-| **MCP server** | 10 tools for AI assistants (Claude Code, Cursor, Windsurf, Cline) |+| **MCP server** | 10 tools for AI assistants (Claude Code, Codex, Cursor, Windsurf, Cline) || **Web dashboard** | Browse wiki, search, and explore architecture diagrams || **Multi-language** | Python, TypeScript, JavaScript, Go, Rust, Java, C/C++, Kotlin, Ruby, C#, Swift, Scala, PHP |@@ -45,3 +45,4 @@ pip install repowise| [**60-second quickstart →**](getting-started) | The fastest path to a working setup. || [**Core concepts →**](concepts) | Understand the four layers before diving in. || [**CLI reference →**](cli-reference) | Every command, flag, and option. |+| [**Codex integration →**](codex) | Codex MCP, hooks, AGENTS.md, and local CLI provider setup. |diff --git a/website/mcp-server.md b/website/mcp-server.mdindex e1d421ec0..e04f6d440 100644--- a/website/mcp-server.md+++ b/website/mcp-server.md@@ -7,7 +7,7 @@ nav_order: 5# MCP Server{: .no_toc }-Connect repowise to Claude Code, Cursor, Cline, or any MCP-compatible editor.+Connect repowise to Claude Code, Codex, Cursor, Cline, or any MCP-compatible editor.{: .fs-6 .fw-300 }---@@ -65,6 +65,26 @@ If you're running repowise for the current directory, you can omit the path:}```+### Codex++Run the Codex setup command from your repository:++```bash+repowise init --codex+```++This writes project-local `.codex/config.toml` with a Repowise MCP server entry:++```toml+[mcp_servers.repowise]+command = "repowise"+args = ["mcp"]+cwd = "/path/to/your-repo"+startup_timeout_sec = 20+```++It also writes `.codex/hooks.json` and managed `AGENTS.md`. See [Codex Integration](codex).+### CursorAdd to `.cursor/mcp.json` in your repo or `~/.cursor/mcp.json` globally:@@ -118,7 +138,7 @@ Add to Windsurf's MCP configuration:### stdio (default)-The default transport. The MCP server runs as a subprocess of your editor, communicating over stdin/stdout. This is the correct option for Claude Code, Cursor, Cline, and Windsurf.+The default transport. The MCP server runs as a subprocess of your editor, communicating over stdin/stdout. This is the correct option for Claude Code, Codex, Cursor, Cline, and Windsurf.```bashrepowise mcp # stdio, current directory@@ -392,4 +412,4 @@ The tools are designed to form a decision workflow:5. **When locating code** → `search_codebase(query="...")` before grep6. **After making changes** → `update_decision_records(action="create", ...)` to record decisions-The [CLAUDE.md generator](claude-md-generator) writes these instructions directly into your project's CLAUDE.md, so Claude Code follows this workflow automatically.+The [CLAUDE.md generator](claude-md-generator) writes these instructions directly into your project's CLAUDE.md, so Claude Code follows this workflow automatically. Codex setup writes the same workflow into managed `AGENTS.md`.