Skip to content

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

fix(init): persist an API key supplied through the environment (#1595)

Raghav Chamadiya3c25063f94d2
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index aa85c68e2..0b2456efd 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -22,6 +22,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
the API also rejects `max` for 5.6 (verified live against both `gpt-5.6-luna`
and `gpt-5.6-sol`), so it is not offered.
+### Fixed
+
+- **`init` now persists an API key supplied through the environment.** Key
+ persistence used to hang off the interactive key *prompt*, so
+ `repowise init --provider openai --yes` with `OPENAI_API_KEY` already exported
+ indexed fine and wrote `provider:` to `config.yaml`, but left no
+ `.repowise/.env`, and `repowise mcp` against that repo then answered
+ `degraded: "no-llm-provider"` with retrieval-only output. Scripted init is the
+ primary path for agents and CI, so a run that succeeds now leaves a repo whose
+ MCP server can actually answer. The key that indexed the repo is saved, with a
+ one-line notice naming the file; `--no-save-key` (or `REPOWISE_NO_SAVE_KEY=1`)
+ opts out, and answering No at the interactive prompt still wins. Covers
+ `init`, workspace init and `workspace add`. The `.gitignore` entry is now
+ written *before* the key, so a failure cannot leave a committable secret.
+
---
## [0.42.0] — 2026-08-13
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index b67f1053a..288985309 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -173,6 +173,7 @@ All three reach the indexing knobs; the LLM-only knobs appear only when model-wr
| `--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`. |
| `--distill-hook` / `--no-distill-hook` | Install or skip the Distill command-rewrite hook (Claude Code PreToolUse). Strictly opt-in: interactive runs prompt (default No); `--no-distill-hook` also gates the repo off in config so a globally installed hook stays inert here. In workspace mode the verdict applies to every selected repo. See [DISTILL.md](../agent/DISTILL.md). |
| `--editor-setup` / `--no-editor-setup` | Wire repowise into your editors, both halves at once. Machine-wide: the Claude Code (`~/.claude/settings.json`) and Claude Desktop MCP server entry, plus the Claude Code PostToolUse/SessionStart hooks. Project-local: `.mcp.json`, `.claude/CLAUDE.md`, `.vscode/mcp.json`, `.vscode/extensions.json`. Default: on. `--no-editor-setup` indexes the repo writing nothing into it and nothing outside it — only `.repowise/` is touched — which is what you want for a scratch checkout, a throwaway venv, a git worktree, or a CI run: each config holds a single `repowise` MCP key, so a second `init` repoints it at the newest repo instead of adding a second entry. `repowise mcp .` still prints the config to connect a client by hand. It also skips the `--distill-hook` offer, which installs a user-level hook; `--no-distill-hook`, `--no-claude-md` and `--no-agents-md` still record their opt-outs in this repo's config, because those flags mean "never", not "not this run". `REPOWISE_SKIP_EDITOR_SETUP=1` is the same switch for CI and sandboxes, and it wins: with it set, an explicit `--editor-setup` does not turn setup back on. |
+| `--save-key` / `--no-save-key` | Save the provider API key this run authenticated with into `.repowise/.env` (git-ignored, owner-only). Default: on, because a scripted `init` that succeeds must leave a repo whose MCP server can actually answer, and a key supplied through the environment would otherwise vanish with the shell that set it. The file is what `repowise mcp`, `serve` and `update` read back; without it `get_answer` degrades to `no-llm-provider` and returns retrieval-only output. Use `--no-save-key` when the key is injected per-process (CI secrets, a shared machine) and must not reach disk; `REPOWISE_NO_SAVE_KEY=1` is the same switch for CI and sandboxes. Answering No to the interactive key prompt also wins over the default. Note this writes one line to the repo's `.gitignore`, so pair it with `--no-save-key` when you need `--no-editor-setup`'s "nothing written into the repo" guarantee. |
| `--seed-from` | Seed the index from an explicit base checkout instead of the auto-detected one. Rarely needed: inside a linked git worktree the base is detected and seeded automatically. See [WORKTREES.md](../scale/WORKTREES.md). |
| `--no-seed` | Disable worktree auto-seeding and run a full init even inside a linked worktree. |
| `--yes` / `-y` | Skip confirmation prompts |
@@ -198,6 +199,7 @@ repowise init -x vendor/ -x "*.gen.go" # exclude patterns
repowise init --include-submodules # include submodules
repowise init --no-codex --no-agents # skip Codex project files
repowise init --no-editor-setup --yes # index only, leave global MCP config alone
+repowise init --provider openai --yes --no-save-key # CI: index, but never write the key to disk
repowise init . # workspace mode
repowise init . --no-prose -x "node_modules/" # workspace, no LLM
repowise init . --no-workspace # force single-repo, even in a workspace root
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index 3658006d3..ddbf55831 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -556,6 +556,20 @@ def _run_generation_phase(
"does not turn setup back on."
),
)
+ "--save-key/--no-save-key",
+ "save_key",
+ default=True,
+ help=(
+ "Save the provider API key this run authenticated with into "
+ ".repowise/.env (gitignored, owner-only). Default: on, because a scripted "
+ "init that succeeds must leave a repo whose MCP server can answer, "
+ "and the key would otherwise be lost with the shell that set it. Use "
+ "--no-save-key when the key is injected per-process (CI secrets, a "
+ "shared machine) and must not be written to disk. "
+ "REPOWISE_NO_SAVE_KEY=1 does the same for CI and sandboxes."
+ ),
+)
@click.option(
"--include-submodules",
is_flag=True,
@@ -716,6 +730,7 @@ def init_command(
codex_setup: bool | None,
distill_hook: bool | None,
editor_setup: bool,
+ save_key: bool,
include_submodules: bool,
no_workspace: bool,
init_all: bool,
@@ -862,6 +877,7 @@ def init_command(
codex_setup=codex_setup,
distill_hook=distill_hook,
editor_setup=editor_setup,
+ save_key=save_key,
include_submodules=include_submodules,
provider_name=provider_name,
model=model,
@@ -1612,6 +1628,7 @@ def init_command(
resolved_commit_limit=resolved_commit_limit,
resolved_reasoning=resolved_reasoning,
include_submodules=include_submodules,
+ save_key=save_key,
)
_record_init_outcome(
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
index ee5c3dbe0..d966761d1 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
@@ -311,6 +311,7 @@ def save_full_state_and_config(
resolved_commit_limit: int,
resolved_reasoning: str,
include_submodules: bool = False,
+ save_key: bool = True,
) -> None:
"""Persist state.json + config for a completed full-mode (docs) init run."""
@@ -387,6 +388,7 @@ def save_full_state_and_config(
exclude_patterns=exclude_patterns if exclude_patterns else None,
commit_limit=resolved_commit_limit if commit_limit is not None else None,
reasoning=resolved_reasoning,
+ save_key=save_key,
)
# Re-save state with the fingerprint now that config.yaml is written.
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
index eef6f65a8..bd827cf9b 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -280,6 +280,9 @@ class _WorkspaceCtx:
#: so --no-editor-setup has to reach every one of them, not just the
#: primary's client registration.
editor_setup: bool = True
+ #: Same reasoning for key persistence: each workspace repo gets its own
+ #: .repowise/, so each needs its own credential to be MCP-answerable.
+ save_key: bool = True
@dataclass
@@ -502,6 +505,7 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCt
exclude_patterns=ctx.exclude_patterns if ctx.exclude_patterns else None,
commit_limit=ctx.resolved_commit_limit,
reasoning=ctx.resolved_reasoning,
+ save_key=ctx.save_key,
)
# Persist the wiki style per repo so update/restyle honor it. Default
# omitted to keep config tidy — only an override is recorded.
@@ -561,6 +565,7 @@ def _workspace_init(
codex_setup: bool | None,
distill_hook: bool | None,
editor_setup: bool,
+ save_key: bool,
include_submodules: bool,
# Generation params (passed through from init_command)
provider_name: str | None = None,
@@ -760,6 +765,7 @@ def _workspace_init(
ws_config=ws_config,
editor_options=editor_options,
editor_setup=editor_setup,
+ save_key=save_key,
index_only=index_only,
dry_run=dry_run,
force=force,
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
index 9cc21a707..8c151ef2a 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -301,6 +301,17 @@ def _format_relative_time(iso_timestamp: str | None) -> str:
@click.option(
"--concurrency", type=int, default=10, help="Max concurrent LLM calls during doc generation."
)
+ "--save-key/--no-save-key",
+ "save_key",
+ default=True,
+ help=(
+ "Save the provider API key this run authenticated with into the added "
+ "repo's .repowise/.env (gitignored). Default: on, because each workspace repo "
+ "has its own .repowise/, so each needs its own key to be answerable by "
+ "the MCP server. Same switch as `repowise init --no-save-key`."
+ ),
+)
@click.option(
"--verbose",
"-v",
@@ -316,6 +327,7 @@ def workspace_add(
provider_name: str | None,
model: str | None,
concurrency: int,
+ save_key: bool,
verbose: bool,
) -> None:
"""Add a repo to the workspace and (by default) index + generate docs for it.
@@ -398,6 +410,7 @@ def workspace_add(
model=model,
concurrency=concurrency,
docs_skip_reason=docs_skip_reason,
+ save_key=save_key,
)
@@ -528,6 +541,7 @@ def _run_index_for_repo(
model: str | None = None,
concurrency: int = 10,
docs_skip_reason: str | None = None,
+ save_key: bool = True,
) -> None:
"""Run the ingestion pipeline on a single repo, optionally with LLM docs.
@@ -655,6 +669,7 @@ def _run_index_for_repo(
exclude_patterns=exclude_patterns or None,
commit_limit=int(commit_limit) if commit_limit else None,
reasoning=resolved_reasoning,
+ save_key=save_key,
)
# Update workspace config entry
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 5dfc068dd..59f431a79 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -54,6 +54,18 @@ err_console = Console(stderr=True, width=resolve_console_width(sys.stderr))
STATE_FILENAME = "state.json"
REPOWISE_DIR = ".repowise"
+# Suppresses mirroring the provider key into `.repowise/.env`. The env
+# spelling of `init --no-save-key`, mirroring REPOWISE_SKIP_EDITOR_SETUP: CI
+# and shared machines configure the process, not the command line. It is also
+# how the interactive key prompt records a "no": that answer is taken at the
+# start of the run and has to survive until config is written at the end.
+NO_SAVE_KEY_ENV = "REPOWISE_NO_SAVE_KEY"
+
+
+def _clean_flag(value: str | None) -> bool:
+ """Whether an env var is set to something meaning "on"."""
+ return (value or "").strip().lower() not in ("", "0", "false", "no")
+
# ---------------------------------------------------------------------------
# Logging / structlog helpers
@@ -634,6 +646,66 @@ def resolve_max_file_pages(
return value if value > 0 else None
+def _persist_provider_key(repo_path: Path, provider: str) -> None:
+ """Mirror ``provider``'s credential from the environment into ``.repowise/.env``.
+
+ Key persistence used to hang off the interactive key *prompt*, so it only
+ ran when the user typed a key. Supplying the key through the environment is
+ precisely the no-prompt case, which meant a scripted
+ ``init --provider openai --yes`` indexed fine and wrote ``provider:`` to
+ config.yaml but left no credential behind: ``repowise mcp`` against that
+ repo then answered ``degraded: "no-llm-provider"``. Scripted init is the
+ primary path for agents and CI, so a run that succeeds has to leave a repo
+ whose MCP server can actually answer.
+
+ The rule, stated out loud: a key that successfully indexed this repo is the
+ key this repo needs, so it is saved, with a notice naming the file and
+ ``--no-save-key`` to opt out. Nothing is written for a provider that needs
+ no credential.
+
+ Routed through :func:`save_repo_env_key` rather than writing the file here:
+ the ``.gitignore`` entry and the owner-only mode come with it, and a
+ hand-rolled write would leave a committable secret.
+
+ Best-effort by design. It runs at the tail of a completed init, after the
+ index has been paid for, and it is the first thing on that path to write
+ outside ``.repowise/``, so a read-only checkout or an unwritable
+ ``.gitignore`` must cost the user a warning, not the run.
+ """
+ from repowise.core.providers.llm.registry import PROVIDER_API_KEY_ENVS
+ from repowise.core.repo_config import save_repo_env_key
+
+ if _clean_flag(os.environ.get(NO_SAVE_KEY_ENV)):
+ return
+
+ # Keys only. ``provider_required_envs`` would also hand back ollama's
+ # OLLAMA_BASE_URL, and pinning an endpoint into the repo is a different
+ # decision from saving a credential: a later run on another network
+ # would silently reuse the stale URL.
+ #
+ # Some providers accept either of two vars (gemini: GEMINI_API_KEY /
+ # GOOGLE_API_KEY). Persist the one actually carrying the value, not both,
+ # so the var written is the var `provider_kwargs` will read back.
+ for env_var in PROVIDER_API_KEY_ENVS.get(provider, ()):
+ value = (os.environ.get(env_var) or "").strip()
+ if not value:
+ continue
+ try:
+ save_repo_env_key(repo_path, env_var, value)
+ except (OSError, ValueError) as exc:
+ err_console.print(
+ f"[yellow]Warning:[/yellow] could not save {env_var} to "
+ f".repowise/.env ({exc}). The index is complete, but "
+ f"`repowise mcp` will need {env_var} in its environment."
+ )
+ return
+ console.print(
+ f"[dim]Saved {env_var} to .repowise/.env (gitignored). "
+ f"--no-save-key or {NO_SAVE_KEY_ENV}=1 to skip.[/dim]"
+ )
+ return
+
+
def save_config(
repo_path: Path,
provider: str,
@@ -644,6 +716,7 @@ def save_config(
exclude_patterns: list[str] | None = None,
commit_limit: int | None = None,
reasoning: str | None = None,
+ save_key: bool = True,
) -> None:
"""Write provider/model/embedder (and optionally exclude_patterns) to ``.repowise/config.yaml``.
@@ -653,6 +726,12 @@ def save_config(
embedder used at init time — without it the server silently falls back to a
provider default (e.g. ``text-embedding-3-small``), which mismatches the
indexed vectors and breaks chat/search retrieval (issue #426).
+
+ ``save_key`` also mirrors the provider's credential into ``.repowise/.env``.
+ It belongs here because this function *is* the "this run committed to this
+ provider for this repo" moment, shared by all three flows that reach it
+ (single-repo init, workspace init, ``workspace add``). All three otherwise
+ leave an indexed repo their MCP server cannot authenticate against.
"""
ensure_repowise_dir(repo_path)
config_path = get_repowise_dir(repo_path) / CONFIG_FILENAME
@@ -687,6 +766,9 @@ def save_config(
lines.append(f"reasoning: {resolve_reasoning(reasoning)}")
config_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ if save_key:
+ _persist_provider_key(repo_path, provider)
+
def save_config_partial(
repo_path: Path,
diff --git a/packages/cli/src/repowise/cli/ui/provider_selection.py b/packages/cli/src/repowise/cli/ui/provider_selection.py
index 78f53ab4e..7bd2879db 100644
--- a/packages/cli/src/repowise/cli/ui/provider_selection.py
+++ b/packages/cli/src/repowise/cli/ui/provider_selection.py
@@ -722,6 +722,15 @@ def _prompt_api_key(
if save:
_save_key_to_dotenv(repo_path, env_var, key)
console.print(f" [{OK}]✓ Saved to .repowise/.env[/]")
+ else:
+ # A declined key must stay declined. The run puts the key in the
+ # environment (above) so indexing can use it, and init now mirrors
+ # the environment's key into .repowise/.env when it writes config,
+ # which would quietly overrule this exact answer. Record the "no"
+ # where that later step will see it.
+ from repowise.cli.helpers import NO_SAVE_KEY_ENV
+
+ os.environ[NO_SAVE_KEY_ENV] = "1"
console.print()
return key
diff --git a/packages/core/src/repowise/core/repo_config.py b/packages/core/src/repowise/core/repo_config.py
index 5a6dfa212..9e17bbb78 100644
--- a/packages/core/src/repowise/core/repo_config.py
+++ b/packages/core/src/repowise/core/repo_config.py
@@ -190,6 +190,13 @@ def save_repo_env_key(
elif not found:
existing_lines.append(f"{env_var}={value}")
+ # Ignore rule first, secret second. If the .gitignore write fails (a
+ # read-only checkout, a root-owned file) this raises before the key is on
+ # disk, rather than after. The failure then costs the user a saved key
+ # instead of leaving a committable one behind.
+ if ensure_gitignored and value is not None:
+ _ensure_env_gitignored(repo_path)
+
env_dir.mkdir(parents=True, exist_ok=True)
env_file.write_text("\n".join(existing_lines) + "\n", encoding="utf-8")
# The file holds API keys; keep it owner-only where the OS honours it
@@ -201,9 +208,6 @@ def save_repo_env_key(
except OSError:
pass
- if ensure_gitignored:
- _ensure_env_gitignored(repo_path)
-
def _ensure_env_gitignored(repo_path: Path | str) -> None:
"""Add ``.repowise/.env`` to the repo's ``.gitignore`` if not already listed."""
diff --git a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
index aa85c68e2..0b2456efd 100644
--- a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
+++ b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
@@ -22,6 +22,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
the API also rejects `max` for 5.6 (verified live against both `gpt-5.6-luna`
and `gpt-5.6-sol`), so it is not offered.
+### Fixed
+
+- **`init` now persists an API key supplied through the environment.** Key
+ persistence used to hang off the interactive key *prompt*, so
+ `repowise init --provider openai --yes` with `OPENAI_API_KEY` already exported
+ indexed fine and wrote `provider:` to `config.yaml`, but left no
+ `.repowise/.env`, and `repowise mcp` against that repo then answered
+ `degraded: "no-llm-provider"` with retrieval-only output. Scripted init is the
+ primary path for agents and CI, so a run that succeeds now leaves a repo whose
+ MCP server can actually answer. The key that indexed the repo is saved, with a
+ one-line notice naming the file; `--no-save-key` (or `REPOWISE_NO_SAVE_KEY=1`)
+ opts out, and answering No at the interactive prompt still wins. Covers
+ `init`, workspace init and `workspace add`. The `.gitignore` entry is now
+ written *before* the key, so a failure cannot leave a committable secret.
+
---
## [0.42.0] — 2026-08-13
diff --git a/tests/unit/cli/test_init_noninteractive.py b/tests/unit/cli/test_init_noninteractive.py
index ae04e63be..6186069eb 100644
--- a/tests/unit/cli/test_init_noninteractive.py
+++ b/tests/unit/cli/test_init_noninteractive.py
@@ -17,6 +17,7 @@ from click.testing import CliRunner
from repowise.cli import cost_gate
from repowise.cli.commands.init_cmd._interactive import offer_hook_install
+from repowise.cli.helpers import NO_SAVE_KEY_ENV, save_config
from repowise.cli.main import cli
@@ -202,3 +203,104 @@ class TestProseFlag:
result = runner.invoke(cli, ["init", str(tmp_path), "--prose", "--index-only"])
assert result.exit_code == 2
assert "contradicts" in result.output
+
+
+class TestNonInteractiveKeyPersistence:
+ """A scripted init that succeeds must leave an MCP-answerable repo.
+
+ Persistence used to hang off the interactive key *prompt*, so it only ran
+ when a human typed a key. Supplying the key through the environment is
+ exactly the no-prompt case, which meant `init --provider openai --yes`
+ indexed fine, wrote `provider: openai`, and left no credential — and
+ `get_answer` against that repo then returned
+ `degraded: "no-llm-provider"` with retrieval-only output.
+
+ These pin `save_config`, the one place all three flows (single-repo init,
+ workspace init, `workspace add`) commit to a provider for a repo.
+ """
+
+ def test_env_supplied_key_is_persisted(self, tmp_path, monkeypatch):
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-from-the-environment")
+ save_config(tmp_path, "openai", "gpt-5.4-nano", "openai")
+
+ env_file = tmp_path / ".repowise" / ".env"
+ assert env_file.exists(), "a key that indexed the repo was not saved"
+ assert "OPENAI_API_KEY=sk-from-the-environment" in env_file.read_text(encoding="utf-8")
+
+ def test_persisting_a_key_gitignores_it(self, tmp_path, monkeypatch):
+ """The secret and its ignore rule land together or not at all."""
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-from-the-environment")
+ save_config(tmp_path, "openai", "gpt-5.4-nano", "openai")
+
+ ignored = (tmp_path / ".gitignore").read_text(encoding="utf-8")
+ assert ".repowise/.env" in {line.strip() for line in ignored.splitlines()}
+
+ def test_no_save_key_leaves_nothing_behind(self, tmp_path, monkeypatch):
+ """The opt-out is for keys injected per-process that must not hit disk."""
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-from-the-environment")
+ save_config(tmp_path, "openai", "gpt-5.4-nano", "openai", save_key=False)
+
+ assert not (tmp_path / ".repowise" / ".env").exists()
+
+ def test_keyless_provider_writes_no_env_file(self, tmp_path, monkeypatch):
+ """Nothing to persist must mean no file, not an empty one."""
+ for var in ("OPENAI_API_KEY", "OLLAMA_BASE_URL"):
+ monkeypatch.delenv(var, raising=False)
+ save_config(tmp_path, "codex_cli", "codex_cli/default", "mock")
+
+ assert not (tmp_path / ".repowise" / ".env").exists()
+
+ def test_gemini_persists_only_the_variable_actually_set(self, tmp_path, monkeypatch):
+ """Gemini accepts either var; saving both would invent a credential."""
+ monkeypatch.delenv("GEMINI_API_KEY", raising=False)
+ monkeypatch.setenv("GOOGLE_API_KEY", "goog-key")
+ save_config(tmp_path, "gemini", "gemini-3.5-flash-lite", "gemini")
+
+ written = (tmp_path / ".repowise" / ".env").read_text(encoding="utf-8")
+ assert "GOOGLE_API_KEY=goog-key" in written
+ assert "GEMINI_API_KEY" not in written
+
+ def test_declined_interactive_key_is_not_persisted_later(self, tmp_path, monkeypatch):
+ """A "no" at the key prompt outranks the save-by-default rule.
+
+ The prompt puts the key in the environment so the run can index with
+ it, which is exactly what `save_config` mirrors to disk at the end. The
+ decline has to survive that gap or the user is asked and then overruled.
+ """
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-declined")
+ monkeypatch.setenv(NO_SAVE_KEY_ENV, "1")
+ save_config(tmp_path, "openai", "gpt-5.4-nano", "openai")
+
+ assert not (tmp_path / ".repowise" / ".env").exists()
+
+ def test_ollama_endpoint_is_not_persisted_as_a_credential(self, tmp_path, monkeypatch):
+ """Pinning an endpoint into a repo is a different decision from saving a key."""
+ monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:11434")
+ save_config(tmp_path, "ollama", "qwen3.5:4b", "ollama")
+
+ assert not (tmp_path / ".repowise" / ".env").exists()
+
+ def test_unwritable_gitignore_warns_but_does_not_lose_the_index(
+ self, tmp_path, monkeypatch, capsys
+ ):
+ """This runs after the index is paid for, so it must never abort the run.
+
+ It is also the first thing on the scripted path to write outside
+ `.repowise/`, so it is the first that can fail on a read-only checkout.
+ """
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-key")
+ (tmp_path / ".gitignore").mkdir() # a directory where a file must go
+
+ save_config(tmp_path, "openai", "gpt-5.4-nano", "openai")
+
+ assert (tmp_path / ".repowise" / "config.yaml").exists(), "the run's config was lost"
+ # And the key never reached disk without its ignore rule.
+ assert not (tmp_path / ".repowise" / ".env").exists()
+
+ def test_key_with_a_trailing_newline_is_stored_clean(self, tmp_path, monkeypatch):
+ """Secret stores and CI env-file loaders routinely keep the newline."""
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-newline\n")
+ save_config(tmp_path, "openai", "gpt-5.4-nano", "openai")
+
+ written = (tmp_path / ".repowise" / ".env").read_text(encoding="utf-8")
+ assert "OPENAI_API_KEY=sk-newline\n" in written