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(embed): resolve the embedder from the store, not the environment (#1007)

Raghav Chamadiyab3933fb8b584
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index baea85a31..e25ef7eaa 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -276,8 +276,14 @@ repowise generate --page file_page:src/app.py --cascade none # one page, nothi
repowise generate --stale # refresh pages whose code moved on
```
-> It does not build the vector store. If you want semantic search over the new
-> prose, run `repowise reindex` afterwards (embedding calls only, no LLM).
+> **Embedding.** `generate` embeds the pages it writes. On a repo indexed
+> without a key (`embedder: mock` in `config.yaml`), it re-resolves a real
+> embedder from your environment rather than honouring that pin, since you are
+> already paying a model to write the prose, and prints
+> `Embedder: openai (was mock, index-only's default)`. Switching embedder
+> changes the vector width, which rebuilds the store, so it then re-embeds the
+> whole wiki automatically (embedding calls only, no LLM) and records the
+> embedder in `config.yaml` so later `update` runs stay on it.
---
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 97ae99455..bf0c0ffd5 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -412,6 +412,17 @@ repowise init --embedder openai
repowise reindex --embedder gemini # switch embedder and rebuild index
```
+The `embedder` key in `config.yaml` is the record of what built the vector
+store, so it is what both writers and readers use. `search`, `serve`, and the
+MCP server resolve it from there first and only fall back to the environment
+when nothing is pinned; otherwise a repo indexed without a key would be queried
+with whatever API key happened to be exported, and the wider query vectors
+would match nothing in the narrower stored table.
+
+`reindex` writes the embedder it used back to `config.yaml`. Without that, the
+next `update` would read the old pin, write vectors at the old width, and the
+store would be rebuilt from scratch, discarding what the reindex just built.
+
`REPOWISE_EMBEDDING_MODEL` overrides the model for whichever embedder is
active. `REPOWISE_EMBEDDING_DIMS` and `REPOWISE_EMBEDDING_TIMEOUT` apply the
same way; the `OLLAMA_EMBEDDING_*` variants below are Ollama-specific
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
index 81d1c011b..2db3c1f67 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
@@ -450,11 +450,14 @@ def _run_repo_checks(
from repowise.core.persistence.models import Page
+ # Page's natural primary key is the column `id`; there
+ # is no `page_id` attribute, so the old spelling raised
+ # AttributeError and no repair ever ran.
rows = await session.execute(
- select(Page).where(Page.page_id.in_(list(missing_from_fts)))
+ select(Page).where(Page.id.in_(list(missing_from_fts)))
)
for page in rows.scalars().all():
- await fts.index(page.page_id, page.title, page.content)
+ await fts.index(page.id, page.title, page.content)
repaired += 1
for pid in orphaned_fts:
await fts.delete(pid)
@@ -464,14 +467,36 @@ def _run_repo_checks(
lance_dir = repowise_dir / "lancedb"
if lance_dir.exists() and (missing_from_vector or orphaned_vector):
try:
- from repowise.core.persistence.vector_store import LanceDBVectorStore
- from repowise.core.providers.embedding.base import MockEmbedder
-
- # Use mock embedder for repair to avoid API costs;
- # user can re-run `repowise reindex` for real embeddings
- embedder = MockEmbedder()
+ from repowise.cli.providers import (
+ build_embedder,
+ build_vector_store,
+ resolve_embedder_for_repo,
+ )
- vs = LanceDBVectorStore(str(lance_dir), embedder=embedder)
+ # Repair with the embedder that built this store, not a
+ # hardcoded mock. The mock was chosen to avoid API costs,
+ # but writing its 8-wide vectors into a real table makes
+ # LanceDB drop the table: a repair that deletes the index
+ # it was asked to fix. build_vector_store refuses that
+ # combination and returns None, so a repo whose embedder is
+ # unavailable is left alone instead of wrecked.
+ embedder_name = resolve_embedder_for_repo(repo_path)
+ embedder = build_embedder(embedder_name)
+ vs = build_vector_store(_DoctorPath(repo_path), embedder)
+ if vs is None:
+ raise RuntimeError(
+ "no embedder available that can write this store; "
+ "set an embedder key and run `repowise reindex`"
+ )
+ # This repair has never actually run (it raised on a column
+ # that does not exist), so a hosted embedder here is a new
+ # charge on a command people run to diagnose, not to spend.
+ # Say so. It is bounded by the missing pages, not the wiki.
+ if missing_from_vector and embedder_name != "mock":
+ console.print(
+ f" [dim]Embedding {len(missing_from_vector)} missing "
+ f"page(s) with {embedder_name}.[/dim]"
+ )
if missing_from_vector:
async with get_session(sf) as session:
@@ -480,11 +505,11 @@ def _run_repo_checks(
from repowise.core.persistence.models import Page
rows = await session.execute(
- select(Page).where(Page.page_id.in_(list(missing_from_vector)))
+ select(Page).where(Page.id.in_(list(missing_from_vector)))
)
for page in rows.scalars().all():
await vs.embed_and_upsert(
- page.page_id,
+ page.id,
page.content,
{
"title": page.title,
diff --git a/packages/cli/src/repowise/cli/commands/generate_cmd/command.py b/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
index 60062310c..ce5249d1f 100644
--- a/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
@@ -31,6 +31,7 @@ from repowise.cli.helpers import (
run_async,
save_state,
)
+from repowise.cli.providers import resolve_embedder
from repowise.cli.ui import load_dotenv
from repowise.core.docs_mode import docs_mode_state_fields, resolve_docs_mode
from repowise.core.generation.page_selection import PageSelectionIntent
@@ -294,7 +295,22 @@ def generate_command(
config = dataclasses.replace(config, tier1_top_n=tier1_top_n)
exclude_patterns = list(cfg.get("exclude_patterns") or [])
+
+ # A keyless init records `embedder: mock`, because that mode promises no
+ # spend and a hosted embedder is a real bill. The promise is void here: the
+ # user is already paying a model to write these pages. Honouring the pin
+ # would embed that paid prose as 8-dim SHA-256 hashes and leave semantic
+ # search as useless as it was before, with nothing in the output saying so.
+ # `update --full` has re-resolved here since it was written; `generate`
+ # never did. Same rule, same message.
embedder_name = cfg.get("embedder")
+ embedder_upgraded = False
+ if not embedder_name or embedder_name == "mock":
+ resolved = resolve_embedder(None)
+ if resolved != (embedder_name or "mock"):
+ console.print(f"Embedder: [cyan]{resolved}[/cyan] (was mock, index-only's default).")
+ embedder_name = resolved
+ embedder_upgraded = True
start = time.monotonic()
outcome = run_async(
@@ -331,6 +347,41 @@ def generate_command(
f"[bold green]Generated {len(outcome.generated_pages)} pages[/bold green] "
f"in {elapsed:.1f}s{stale_note}{tail}."
)
+ if embedder_upgraded:
+ _reembed_after_upgrade(repo_path, embedder_name)
+
+
+def _reembed_after_upgrade(repo_path: Path, embedder_name: str) -> None:
+ """Re-embed the whole wiki after the embedder was upgraded off the mock.
+
+ Switching vector width makes the LanceDB writer drop the old table, so at
+ this point the store holds only the pages this run happened to write. Every
+ page it did not touch is out of semantic search, which is the exact failure
+ this command's embedder fix exists to end — leaving the user a note to run
+ `reindex` themselves just moves the failure one step later.
+
+ So run it. It is the cheap half of the pipeline (embedding calls, no model)
+ and it persists the resolved embedder to config.yaml on the way out, which
+ is what keeps the next `update` from building a mock store against this
+ table. Best-effort: the pages are written and committed either way, so an
+ embedding failure is a degraded search index, not a failed generate.
+
+ Nothing is persisted on failure. The pin is a claim about what wrote the
+ table, and writing it after a run that wrote nothing makes it a false one.
+ Leaving it as it was keeps the store guarded rather than trusted.
+ """
+ from .. import reindex_cmd
+
+ console.print(f"\nRe-embedding the wiki with [cyan]{embedder_name}[/cyan] (no model calls)...")
+ tail = "The pages are written. Run [cyan]repowise reindex[/cyan] to finish the search index."
+ try:
+ run_async(reindex_cmd._reindex(repo_path, embedder_name, 32))
+ except click.Abort:
+ # _reindex already printed the reason and its own fix; str(Abort) is
+ # empty, so repeating it as "{exc}" would print a blank line instead.
+ console.print(tail)
+ except Exception as exc:
+ console.print(f"[yellow]Re-embedding failed:[/yellow] {exc}\n{tail}")
def _write_state(repo_path: Path, state: dict, provider: Any, outcome: Any) -> None:
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 23cf9356d..232c230a4 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -44,6 +44,7 @@ from repowise.cli.helpers import (
save_state,
)
from repowise.cli.providers import resolve_embedder
+from repowise.cli.providers.embedders import embedder_was_requested as _embedder_was_requested
from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json
from repowise.cli.ui import (
BRAND,
@@ -998,19 +999,7 @@ def init_command(
config["follow_renames"] = True
embedder_name_resolved = resolve_embedder(embedder_name)
- # Whether the user actually asked for this embedder, as opposed to
- # resolve_embedder inferring one from an LLM key it found lying around.
- # The deterministic generation phase needs the distinction: it advertises
- # itself as costing nothing, so it will not put a hosted embedder on the
- # user's bill unless they named it. A repo whose config already names one
- # counts as asked: the choice was made on an earlier run, and silently
- # dropping to the mock here would re-embed the whole store at a different
- # vector width, which the LanceDB writer resolves by dropping the table.
- embedder_was_requested = (
- bool(embedder_name)
- or bool(os.environ.get("REPOWISE_EMBEDDER", "").strip())
- or bool(config.get("embedder"))
- )
+ embedder_was_requested = _embedder_was_requested(embedder_name, config.get("embedder"))
# A template wiki overwrites a model-written one page for page: the upsert
# replaces content and stamps provider_name="template", keeping the old
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 9b0537d37..9ccbbacb1 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -173,9 +173,6 @@ def _run_workspace_deterministic_generation(
the generated pages plus the embedder actually used (persisted by the caller
so a later workspace update embeds the same way rather than re-deciding).
"""
- from repowise.core.generation import GenerationConfig
- from repowise.core.providers.llm.template import TemplateProvider
-
# "No key, no spend": a template run must not put a hosted embedder on the
# bill unless the user named it. ``resolve_embedder`` infers one from any LLM
# key in the environment, which is the wrong default here. Mirror the
@@ -184,9 +181,17 @@ def _run_workspace_deterministic_generation(
# A previously-persisted embedder on THIS repo counts as requested (re-init
# case): silently dropping it to the mock would re-embed the store at a
# different vector width, which the LanceDB writer resolves by dropping the
- # table (the single-repo phase reads config.get("embedder") for the same
- # reason; the workspace flag is computed once, before any repo config loads).
- requested = embedder_was_requested or bool(load_config(repo_path).get("embedder"))
+ # table. The workspace flag is computed once, before any repo config loads,
+ # so only the per-repo pin is folded in here — the flag already accounts for
+ # the flag and env var, and re-reading them would override a caller that
+ # decided otherwise. ``mock`` is not a pin anyone chose, so it does not count.
+ from repowise.cli.providers.embedders import pin_names_an_embedder
+ from repowise.core.generation import GenerationConfig
+ from repowise.core.providers.llm.template import TemplateProvider
+
+ requested = embedder_was_requested or pin_names_an_embedder(
+ load_config(repo_path).get("embedder")
+ )
hosted = embedder_name_resolved not in ("mock", "ollama")
embedder = "mock" if hosted and not requested else embedder_name_resolved
diff --git a/packages/cli/src/repowise/cli/commands/reindex_cmd.py b/packages/cli/src/repowise/cli/commands/reindex_cmd.py
index c2e8a7d4b..6693fb3ca 100644
--- a/packages/cli/src/repowise/cli/commands/reindex_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/reindex_cmd.py
@@ -203,6 +203,21 @@ async def _reindex(repo_path, embedder_name: str, batch_size: int) -> None:
await vector_store.close()
await engine.dispose()
+ # Record the embedder we actually built the table with. Without this, a
+ # repo indexed keyless keeps `embedder: mock` in config.yaml, and the next
+ # `repowise update` builds a mock store, writes 8-wide vectors into the
+ # 1536-wide table this run just built, and LanceDB resolves the mismatch by
+ # dropping the table — every page and decision vector gone, silently. The
+ # reindex undone by a routine update.
+ #
+ # Only when something was actually written: the pin describes the table, so
+ # a run where every item failed has nothing to describe, and claiming
+ # otherwise would point later writers at a width the table does not have.
+ if indexed:
+ from repowise.cli.helpers import save_config_partial
+
+ save_config_partial(Path(repo_path), embedder=embedder_name)
+
console.print(
f"\n[bold green]Done![/bold green] Indexed {indexed} items"
+ (f" ({failed} failed)" if failed else "")
diff --git a/packages/cli/src/repowise/cli/commands/search_cmd.py b/packages/cli/src/repowise/cli/commands/search_cmd.py
index 2b27911ea..ea9c439cd 100644
--- a/packages/cli/src/repowise/cli/commands/search_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/search_cmd.py
@@ -153,12 +153,13 @@ def _search_semantic(repo_path, query: str, limit: int) -> None:
lance_dir = Path(repo_path) / ".repowise" / "lancedb"
if lance_dir.exists():
try:
- from repowise.cli.commands.init_cmd import _resolve_embedder
- from repowise.cli.providers.embedders import build_embedder
+ from repowise.cli.providers.embedders import (
+ build_embedder,
+ resolve_embedder_for_repo,
+ )
from repowise.core.persistence.vector_store import LanceDBVectorStore
- embedder_name = _resolve_embedder(None)
- embedder = build_embedder(embedder_name)
+ embedder = build_embedder(resolve_embedder_for_repo(repo_path))
store = LanceDBVectorStore(str(lance_dir), embedder=embedder)
results = await store.search(query, limit=limit)
await store.close()
@@ -272,12 +273,13 @@ def _collect_semantic(repo_path, query: str, limit: int):
lance_dir = Path(repo_path) / ".repowise" / "lancedb"
if lance_dir.exists():
try:
- from repowise.cli.commands.init_cmd import _resolve_embedder
- from repowise.cli.providers.embedders import build_embedder
+ from repowise.cli.providers.embedders import (
+ build_embedder,
+ resolve_embedder_for_repo,
+ )
from repowise.core.persistence.vector_store import LanceDBVectorStore
- embedder_name = _resolve_embedder(None)
- embedder = build_embedder(embedder_name)
+ embedder = build_embedder(resolve_embedder_for_repo(repo_path))
store = LanceDBVectorStore(str(lance_dir), embedder=embedder)
results = await store.search(query, limit=limit)
await store.close()
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd.py b/packages/cli/src/repowise/cli/commands/serve_cmd.py
index 786a0a7c8..ed2dcaeec 100644
--- a/packages/cli/src/repowise/cli/commands/serve_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd.py
@@ -238,8 +238,13 @@ def _load_local_provider_config() -> None:
console.print(f"[dim]Using provider from config: {provider}[/dim]")
# 3) Embedder from config so chat/search work without an interactive prompt.
+ # Including "mock": that pin is not a preference to be talked out of, it is
+ # the width the table on disk was written at. Skipping it sent a keyless
+ # repo down _setup_embedder's detection path, which picks up any exported
+ # API key and queries an 8-wide table with 1536-wide vectors — search
+ # returns nothing, and nothing says why.
embedder = cfg.get("embedder")
- if embedder and embedder != "mock" and not os.environ.get("REPOWISE_EMBEDDER"):
+ if embedder and not os.environ.get("REPOWISE_EMBEDDER"):
os.environ["REPOWISE_EMBEDDER"] = str(embedder)
# 4) Embedding model from config — without this the server rebuilds the
diff --git a/packages/cli/src/repowise/cli/providers/__init__.py b/packages/cli/src/repowise/cli/providers/__init__.py
index b0ebd55f9..ed6c4a07f 100644
--- a/packages/cli/src/repowise/cli/providers/__init__.py
+++ b/packages/cli/src/repowise/cli/providers/__init__.py
@@ -13,15 +13,25 @@ from repowise.cli.providers.cost_tracking import (
flush_cost_tracker,
make_cost_tracker,
)
-from repowise.cli.providers.embedders import build_embedder, resolve_embedder
-from repowise.cli.providers.vector_store import build_vector_store
+from repowise.cli.providers.embedders import (
+ build_embedder,
+ embedder_was_requested,
+ pin_names_an_embedder,
+ resolve_embedder,
+ resolve_embedder_for_repo,
+)
+from repowise.cli.providers.vector_store import build_vector_store, existing_vector_dim
__all__ = [
"build_cost_tracker",
"build_embedder",
"build_vector_store",
"cost_tracking_disabled",
+ "embedder_was_requested",
+ "existing_vector_dim",
"flush_cost_tracker",
"make_cost_tracker",
+ "pin_names_an_embedder",
"resolve_embedder",
+ "resolve_embedder_for_repo",
]
diff --git a/packages/cli/src/repowise/cli/providers/embedders.py b/packages/cli/src/repowise/cli/providers/embedders.py
index 17bf2a451..f61d59a34 100644
--- a/packages/cli/src/repowise/cli/providers/embedders.py
+++ b/packages/cli/src/repowise/cli/providers/embedders.py
@@ -66,6 +66,66 @@ def resolve_embedder(embedder_flag: str | None) -> str:
return "mock"
+def pin_names_an_embedder(pinned_embedder: Any) -> bool:
+ """Whether a persisted ``embedder`` value represents a choice someone made.
+
+ A repo whose config pins one counts as asked: the choice was made on an
+ earlier run, and silently dropping to the mock would re-embed the store at
+ a different width, which the LanceDB writer resolves by dropping the table.
+
+ Except when the pin is ``mock``. That is what a keyless run persists on its
+ way out, not a choice anyone made, and counting it makes the second
+ ``repowise init`` on a machine that has since acquired an API key embed the
+ whole wiki through a paid endpoint, on a run whose own header promises no
+ model and no cost.
+ """
+ pinned = pinned_embedder.strip() if isinstance(pinned_embedder, str) else ""
+ return pinned not in ("", "mock")
+
+
+def embedder_was_requested(embedder_flag: str | None, pinned_embedder: Any = None) -> bool:
+ """Whether the user actually asked for an embedder, as opposed to one being
+ inferred from an LLM key that happens to be in the environment.
+
+ The keyless generation phase needs the distinction: it advertises itself as
+ costing nothing, so it will not put a hosted embedder on the bill unless
+ the user named it.
+ """
+ return (
+ bool(embedder_flag)
+ or bool(os.environ.get("REPOWISE_EMBEDDER", "").strip())
+ or pin_names_an_embedder(pinned_embedder)
+ )
+
+
+def resolve_embedder_for_repo(repo_path: Any) -> str:
+ """Return the embedder that can read *repo_path*'s vector store.
+
+ The pinned ``embedder`` in ``config.yaml`` is what wrote the table, so it
+ is what can query it. Readers used to resolve from the environment while
+ writers read the pin, which is how a repo indexed keyless ends up queried
+ with whatever API key happens to be exported: the 1536-wide query vector
+ finds nothing in an 8-wide table, and search just returns nothing.
+
+ Precedence matches :func:`resolve_embedder` and what ``serve`` already
+ does, so the same repo in the same shell never resolves two different ways:
+ an explicitly set ``REPOWISE_EMBEDDER`` wins (it is the documented escape
+ hatch after a manual re-embed), then the pin, then env detection.
+ """
+ from pathlib import Path
+
+ from repowise.cli.helpers import load_config
+
+ override = os.environ.get("REPOWISE_EMBEDDER", "").strip().lower()
+ if override:
+ return override
+ try:
+ pinned = load_config(Path(repo_path)).get("embedder")
+ except Exception:
+ pinned = None
+ return str(pinned) if pinned else resolve_embedder(None)
+
+
def build_embedder(embedder_name_resolved: str) -> Any:
"""Construct the configured embedder, falling back to MockEmbedder.
diff --git a/packages/cli/src/repowise/cli/providers/vector_store.py b/packages/cli/src/repowise/cli/providers/vector_store.py
index feb58ab8d..63be0f443 100644
--- a/packages/cli/src/repowise/cli/providers/vector_store.py
+++ b/packages/cli/src/repowise/cli/providers/vector_store.py
@@ -5,17 +5,81 @@ from __future__ import annotations
from pathlib import Path
from typing import Any
+_TABLE_NAME = "wiki_pages"
-def build_vector_store(repo_path: Path, embedder: Any) -> Any:
+
+def existing_vector_dim(lance_dir: Path) -> int | None:
+ """Return the width of the vectors already stored at *lance_dir*.
+
+ The table records what built it, which makes this the one embedder fact
+ that cannot drift from reality. ``None`` means "could not establish" — no
+ directory, no lancedb installed, no table yet, or a schema without a
+ fixed-width vector column — and every caller treats that as "do not act",
+ never as a difference.
+ """
+ if not lance_dir.exists():
+ return None
+ try:
+ import lancedb # type: ignore[import]
+
+ db = lancedb.connect(str(lance_dir))
+ if _TABLE_NAME not in db.table_names():
+ return None
+ field = db.open_table(_TABLE_NAME).schema.field("vector")
+ dim = getattr(field.type, "list_size", None)
+ except Exception:
+ return None
+ # pyarrow reports -1 for variable-length lists, which tells us nothing.
+ return dim if isinstance(dim, int) and dim > 0 else None
+
+
+def _mock_would_clobber(lance_dir: Path, embedder: Any) -> bool:
+ """True when writing *embedder* into the store at *lance_dir* would drop it.
+
+ The mock is the keyless default, and its 8-wide vectors written into a
+ table some earlier run filled at 1536 make the LanceDB writer drop the
+ table, taking every page *and* decision embedding with it. That is the
+ right call when a real embedder changes model, and never the right call
+ for the mock: nothing is gained, a working index is lost, and the user is
+ told nothing. So only the mock is refused here — a real-to-real width
+ change is still the intended rebuild.
+ """
+ from repowise.core.providers.embedding.base import MockEmbedder
+
+ if not isinstance(embedder, MockEmbedder):
+ return False
+ existing = existing_vector_dim(lance_dir)
+ return existing is not None and existing != embedder.dimensions
+
+
+def build_vector_store(repo_path: Path, embedder: Any) -> Any | None:
"""Build the repo-local vector store, preferring LanceDB.
Uses LanceDB at ``.repowise/lancedb`` so previously-embedded pages and
decisions stay matchable across runs; falls back to an in-memory store
(which only sees this run's vectors) when LanceDB isn't installed.
+
+ Returns ``None`` when handing back a store would destroy the existing one
+ (see :func:`_mock_would_clobber`). Every caller already treats ``None`` as
+ "embedding is off for this run"; full-text search is unaffected either way.
"""
from repowise.core.persistence.vector_store import InMemoryVectorStore
lance_dir = repo_path / ".repowise" / "lancedb"
+ if _mock_would_clobber(lance_dir, embedder):
+ # Say it once, here, rather than in each caller: skipping silently is
+ # how someone ends up wondering why search went quiet. Worded as
+ # "not updating" rather than "skipped" because the generation phase
+ # substitutes a throwaway in-memory store for a None one, so this run
+ # does still embed — it just does not persist anywhere.
+ from repowise.cli.helpers import console
+
+ console.print(
+ "[yellow]Search index left unchanged:[/yellow] this run has no real embedder, "
+ "and the\nexisting index was built with one. Kept it rather than overwrite it. "
+ "Set an\nembedder key and run [cyan]repowise reindex[/cyan] to refresh it."
+ )
+ return None
try:
from repowise.core.persistence.vector_store import LanceDBVectorStore
diff --git a/packages/cli/src/repowise/cli/upgrade.py b/packages/cli/src/repowise/cli/upgrade.py
index 16e08ae28..3a844b874 100644
--- a/packages/cli/src/repowise/cli/upgrade.py
+++ b/packages/cli/src/repowise/cli/upgrade.py
@@ -40,9 +40,21 @@ class _CliUpgradeContext:
async def reembed_vectors(self) -> None:
# Reuse the exact reindex path: rebuild vectors from existing wiki
# pages with the resolved embedder. No LLM calls, only embedding calls.
+ # Resolve through the repo's pin rather than "auto": the pin is what
+ # every writer uses, and re-embedding to whatever the environment
+ # happens to offer would leave the store readable by neither.
from .commands.reindex_cmd import _reindex
-
- await _reindex(self._repo_path, "auto", 20)
+ from .providers.embedders import resolve_embedder_for_repo
+
+ embedder = resolve_embedder_for_repo(self._repo_path)
+ if embedder == "mock":
+ # Nothing to gain and a wiki to lose: this would rewrite every
+ # vector as an 8-dim hash. The other auto-action (a model-name
+ # change) can reach here on a mock-pinned repo, so the refusal
+ # lives here rather than only in the check that proposed it.
+ log.debug("reembed_skipped_mock_embedder", repo=str(self._repo_path))
+ return
+ await _reindex(self._repo_path, embedder, 20)
def drop_parse_cache(self) -> None:
cache = self._repo_path / REPOWISE_DIR / "parse_cache.pkl"
@@ -60,19 +72,66 @@ def _current_embedding_model() -> str | None:
return None
+def _vector_dims(repo_path: Path) -> tuple[int | None, int | None]:
+ """Return ``(width of the stored table, width the pinned embedder makes)``.
+
+ Deliberately answers only one question: are these vectors still the mock's,
+ on a repo that now pins a real embedder? That is the drift left over from a
+ keyless index, and it is the only comparison here that rests on facts.
+
+ Everything else is refused on purpose. The stored width is ground truth —
+ it is read off the table. The current width is not: ``dimensions`` is a
+ lookup against a short hardcoded table, so ``OpenAIEmbedder`` reports 1536
+ for any model outside its three-entry dict and ``OllamaEmbedder`` reports
+ 768 for any name it does not recognise. Comparing two real widths would
+ therefore act on a guess, and acting means re-embedding, which writes the
+ *true* width back — so a wrong guess never converges. An Ollama user on an
+ unlisted model would re-embed their whole wiki on every single ``update``,
+ forever, and an OpenAI-compatible endpoint would bill them for it.
+
+ So: ``None`` unless the table is mock-width and the pin is real. That case
+ cannot loop (the re-embed replaces 8 with something that is not 8, whatever
+ it truly is) and cannot be wrong (no real embedder emits 8 dimensions).
+ Re-embedding *down* to the mock is never proposed either — it destroys a
+ working index and gains nothing.
+ """
+ from repowise.core.providers.embedding.base import MockEmbedder
+
+ from .providers.embedders import build_embedder, resolve_embedder_for_repo
+ from .providers.vector_store import existing_vector_dim
+
+ stored = existing_vector_dim(repo_path / REPOWISE_DIR / "lancedb")
+ if stored != MockEmbedder.dimensions:
+ return None, None
+ try:
+ embedder = build_embedder(resolve_embedder_for_repo(repo_path))
+ except Exception:
+ return None, None
+ if isinstance(embedder, MockEmbedder):
+ return None, None
+ current = getattr(embedder, "dimensions", None)
+ if not isinstance(current, int) or current <= 0 or current == stored:
+ return None, None
+ return stored, current
+
+
def assess_store(repo_path: Path) -> UpgradeVerdict:
"""Assess what upgrading this store to the running build requires.
- Pure read: loads ``state.json`` + ``config.yaml`` and the currently
- resolved embedding model, then defers the decision to the core layer.
+ Pure read: loads ``state.json`` + ``config.yaml``, the currently resolved
+ embedding model, and the stored-vs-current vector width, then defers the
+ decision to the core layer.
"""
state = load_state(repo_path)
config = load_config(repo_path)
recorded_model = config.get("embedding_model")
+ stored_dim, current_dim = _vector_dims(repo_path)
return assess(
state,
recorded_embedding_model=recorded_model if isinstance(recorded_model, str) else None,
current_embedding_model=_current_embedding_model(),
+ stored_vector_dim=stored_dim,
+ current_vector_dim=current_dim,
)
diff --git a/packages/core/src/repowise/core/upgrade/manager.py b/packages/core/src/repowise/core/upgrade/manager.py
index c7624642e..68f5bbab2 100644
--- a/packages/core/src/repowise/core/upgrade/manager.py
+++ b/packages/core/src/repowise/core/upgrade/manager.py
@@ -58,6 +58,8 @@ def assess(
current_store_version: int = STORE_FORMAT_VERSION,
recorded_embedding_model: str | None = None,
current_embedding_model: str | None = None,
+ stored_vector_dim: int | None = None,
+ current_vector_dim: int | None = None,
) -> UpgradeVerdict:
"""Decide what (if anything) upgrading this store requires.
@@ -70,6 +72,15 @@ def assess(
with (the pinned ``embedding_model`` in ``config.yaml``, its canonical home;
callers pass it explicitly). ``current_embedding_model`` is what the running
build resolves now; a difference triggers a re-embed.
+
+ ``stored_vector_dim`` / ``current_vector_dim`` catch the same drift one
+ level down, and are the check that actually fires in practice: the model
+ names above both come from ``REPOWISE_EMBEDDING_MODEL``, which almost
+ nobody sets, so both sides are usually ``None`` and the comparison no-ops.
+ Vector width is not opt-in — the table on disk records what built it, and a
+ width the running embedder cannot produce means every stored vector is
+ unreadable. Callers pass ``None`` for either when it cannot be determined,
+ which keeps the check quiet rather than guessing.
"""
from_version = _coerce_int(state.get(STORE_FORMAT_VERSION_KEY), default=0)
written_by = _coerce_str(state.get(WRITTEN_BY_VERSION_KEY))
@@ -107,6 +118,22 @@ def assess(
)
)
+ if (
+ stored_vector_dim is not None
+ and current_vector_dim is not None
+ and stored_vector_dim != current_vector_dim
+ ):
+ tier = max(tier, UpgradeTier.AUTO)
+ actions.append(
+ UpgradeAction(
+ kind=UpgradeActionKind.REEMBED_VECTORS,
+ reason=(
+ f"embedder changed (vectors are {stored_vector_dim}-wide, the configured "
+ f"embedder produces {current_vector_dim}); re-embedding so search can read them"
+ ),
+ )
+ )
+
user_notice = " ".join(notice_parts) if notice_parts else None
return UpgradeVerdict(
@@ -131,6 +158,11 @@ async def apply_auto(verdict: UpgradeVerdict, ctx: UpgradeContext) -> list[Upgra
"""
ran: list[UpgradeActionKind] = []
for action in verdict.actions:
+ # Two independent checks can both conclude "re-embed" (a model-name
+ # change and a vector-width change usually travel together). Running it
+ # twice bills the embedding API twice for an identical result.
+ if action.kind in ran:
+ continue
try:
if action.kind == UpgradeActionKind.REEMBED_VECTORS:
await ctx.reembed_vectors()
diff --git a/tests/unit/cli/test_embedder_resolution.py b/tests/unit/cli/test_embedder_resolution.py
new file mode 100644
index 000000000..c511dfc6e
--- /dev/null
+++ b/tests/unit/cli/test_embedder_resolution.py
@@ -0,0 +1,540 @@
+"""Embedder resolution across the keyless-init upgrade path.
+
+The path these cover is the one the keyless default exists to serve: index for
+free, decide it is useful, add a key, upgrade. Every writer used to read the
+pinned embedder from ``config.yaml`` while every reader resolved one from the
+environment, so the upgrade produced a fully written wiki that semantic search
+could not read, and nothing in the output said so.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+import yaml
+
+from repowise.cli import providers
+from repowise.core.providers.embedding.base import MockEmbedder
+from repowise.core.upgrade import UpgradeActionKind, UpgradeTier, assess
+from repowise.core.upgrade.version import STORE_FORMAT_VERSION
+
+lancedb = pytest.importorskip("lancedb")
+
+
+def _write_config(repo_path: Path, **keys: object) -> None:
+ repowise_dir = repo_path / ".repowise"
+ repowise_dir.mkdir(parents=True, exist_ok=True)
+ (repowise_dir / "config.yaml").write_text(yaml.safe_dump(keys), encoding="utf-8")
+
+
+def _read_config(repo_path: Path) -> dict:
+ return yaml.safe_load((repo_path / ".repowise" / "config.yaml").read_text(encoding="utf-8"))
+
+
+class _WideEmbedder:
+ """Stand-in for a hosted embedder, without the SDK or the key."""
+
+ dimensions = 1536
+
+ async def embed(self, texts: list[str]) -> list[list[float]]:
+ return [[0.0] * 1535 + [1.0] for _ in texts]
+
+
+async def _seed_store(repo_path: Path, embedder: object) -> None:
+ """Write one real row so the table exists at *embedder*'s width."""
+ store = providers.build_vector_store(repo_path, embedder)
+ assert store is not None
+ await store.embed_and_upsert("file_page:a.py", "hello", {"title": "a"})
+ await store.close()
+
+
+# --- the write guard: a mock must never drop a real table -------------------
+
+
+async def test_mock_store_is_refused_over_a_real_width_table(tmp_path: Path) -> None:
+ """The whole-store-wipe hazard, hoisted into the one shared constructor.
+
+ Writing 8-wide vectors into a 1536-wide table makes LanceDB drop the table,
+ taking every page *and* decision embedding with it. Silently.
+ """
+ await _seed_store(tmp_path, _WideEmbedder())
+ assert providers.existing_vector_dim(tmp_path / ".repowise" / "lancedb") == 1536
+
+ assert providers.build_vector_store(tmp_path, MockEmbedder()) is None
+
+ # And the real table is still there, unharmed.
+ assert providers.existing_vector_dim(tmp_path / ".repowise" / "lancedb") == 1536
+
+
+async def test_mock_store_is_allowed_over_a_mock_table(tmp_path: Path) -> None:
+ """Matching widths are not a conflict — the keyless path must still work."""
+ await _seed_store(tmp_path, MockEmbedder())
+ assert providers.build_vector_store(tmp_path, MockEmbedder()) is not None
+
+
+def test_mock_store_is_allowed_when_no_table_exists(tmp_path: Path) -> None:
+ """A first keyless init has nothing to clobber."""
+ assert providers.build_vector_store(tmp_path, MockEmbedder()) is not None
+
+
+async def test_real_embedder_still_rebuilds_a_differing_table(tmp_path: Path) -> None:
+ """Only the mock is refused; a real re-embed is the intended rebuild."""
+ await _seed_store(tmp_path, MockEmbedder())
+ assert providers.build_vector_store(tmp_path, _WideEmbedder()) is not None
+
+
+def test_existing_vector_dim_is_none_when_unreadable(tmp_path: Path) -> None:
+ """Unknown never means "different" — the guard stays quiet, not guessy."""
+ assert providers.existing_vector_dim(tmp_path / "nope") is None
+ (tmp_path / "empty").mkdir()
+ assert providers.existing_vector_dim(tmp_path / "empty") is None
+
+
+# --- readers resolve from the pin, not the environment ----------------------
+
+
+def test_reader_prefers_the_pinned_embedder_over_a_detected_key(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A keyless repo must not be queried with whatever key is exported.
+
+ The pin is what wrote the table, so it is what can read it. Resolving from
+ the environment sends 1536-wide query vectors at an 8-wide table.
+ """
+ _write_config(tmp_path, embedder="mock")
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+ monkeypatch.delenv("GEMINI_API_KEY", raising=False)
+ monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
+
+ assert providers.resolve_embedder_for_repo(tmp_path) == "mock"
+
+
+def test_an_explicit_env_override_still_beats_the_pin(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """``serve`` honours ``REPOWISE_EMBEDDER`` over the pin, so this must too.
+
+ Otherwise the same repo in the same shell resolves one embedder under
+ ``serve`` and a different one under ``search``.
+ """
+ _write_config(tmp_path, embedder="mock")
+ monkeypatch.setenv("REPOWISE_EMBEDDER", "openai")
+
+ assert providers.resolve_embedder_for_repo(tmp_path) == "openai"
+
+
+def test_semantic_search_reads_through_the_repo_resolver(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The call site, not just the helper.
+
+ Both ``search`` entry points used to resolve from the environment; a helper
+ test alone would keep passing if they were reverted.
+ """
+ from repowise.cli.commands import search_cmd
+
+ _write_config(tmp_path, embedder="mock")
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+ monkeypatch.delenv("GEMINI_API_KEY", raising=False)
+ monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
+ (tmp_path / ".repowise" / "lancedb").mkdir(parents=True, exist_ok=True)
+
+ seen: list[str] = []
+
+ def _record(name: str):
+ seen.append(name)
+ return MockEmbedder()
+
+ monkeypatch.setattr("repowise.cli.providers.embedders.build_embedder", _record)
+ monkeypatch.setattr(search_cmd, "_display_results", lambda *a, **k: None)
+ monkeypatch.setattr(search_cmd, "get_db_url_for_repo", lambda _p: "sqlite+aiosqlite://")
+
+ search_cmd._search_semantic(tmp_path, "anything", 5)
+ search_cmd._collect_semantic(tmp_path, "anything", 5)
+
+ assert seen == ["mock", "mock"], seen
+
+
+def test_serve_seeds_a_mock_pin_into_the_environment(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The pin is a width, not a preference to be talked out of.
+
+ Skipping "mock" here sent a keyless repo down the detection path, which
+ picks up any exported key and then queries an 8-wide table with 1536-wide
+ vectors.
+ """
+ from repowise.cli.commands import serve_cmd
+
+ _write_config(tmp_path, embedder="mock")
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+
+ serve_cmd._load_local_provider_config()
+
+ assert os.environ.get("REPOWISE_EMBEDDER") == "mock"
+
+
+def test_reader_falls_back_to_the_environment_when_nothing_is_pinned(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+ monkeypatch.delenv("GEMINI_API_KEY", raising=False)
+ monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
+
+ assert providers.resolve_embedder_for_repo(tmp_path) == "openai"
+
+
+# --- reindex records what it built the table with ---------------------------
+
+
+async def test_reindex_persists_its_resolved_embedder(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Without this, the next routine ``update`` wipes the store.
+
+ ``reindex`` builds a real 1536-wide table; ``update`` then reads
+ ``embedder: mock`` from config, builds a mock store, and the first write
+ hits the dimension mismatch and drops the table. The reindex is undone by
+ an update the user did not connect to it.
+ """
+ from repowise.cli.commands import reindex_cmd
+
+ _write_config(tmp_path, embedder="mock", language="en")
+
+ class _Page:
+ id = "file_page:a.py"
+ title = "a"
+ content = "hello"
+ page_type = "file_page"
+ target_path = "a.py"
+
+ class _Result:
+ def __init__(self, rows: list) -> None:
+ self._rows = rows
+
+ def scalars(self):
+ return self
+
+ def all(self):
+ return self._rows
+
+ class _Session:
+ _calls = 0
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *args):
+ return None
+
+ async def execute(self, _stmt):
+ type(self)._calls += 1
+ return _Result([_Page()] if type(self)._calls == 1 else [])
+
+ class _Engine:
+ async def dispose(self):
+ return None
+
+ monkeypatch.setattr(reindex_cmd, "get_db_url_for_repo", lambda _p: "sqlite+aiosqlite://")
+ monkeypatch.setattr("repowise.core.persistence.database.create_engine", lambda _u: _Engine())
+ monkeypatch.setattr("repowise.core.persistence.database.init_db", lambda _e: _noop_coro())
+ monkeypatch.setattr(
+ "sqlalchemy.ext.asyncio.async_sessionmaker", lambda *a, **k: lambda: _Session()
+ )
+ # _reindex imports build_embedder from this module inside the function, so
+ # the module attribute is the one that takes effect.
+ monkeypatch.setattr(
+ "repowise.cli.providers.embedders.build_embedder", lambda _n: _WideEmbedder()
+ )
+
+ await reindex_cmd._reindex(tmp_path, "openai", batch_size=8)
+
+ assert _read_config(tmp_path)["embedder"] == "openai"
+ # The unrelated key survives the merge.
+ assert _read_config(tmp_path)["language"] == "en"
+
+
+async def test_reindex_does_not_pin_an_embedder_that_wrote_nothing(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The pin describes the table, so a run with no pages describes nothing.
+
+ Writing it anyway points later writers at a width the table does not have.
+ """
+ from repowise.cli.commands import reindex_cmd
+
+ _write_config(tmp_path, embedder="mock")
+
+ class _Empty:
+ def scalars(self):
+ return self
+
+ def all(self):
+ return []
+
+ class _Session:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *args):
+ return None
+
+ async def execute(self, _stmt):
+ return _Empty()
+
+ class _Engine:
+ async def dispose(self):
+ return None
+
+ monkeypatch.setattr(reindex_cmd, "get_db_url_for_repo", lambda _p: "sqlite+aiosqlite://")
+ monkeypatch.setattr("repowise.core.persistence.database.create_engine", lambda _u: _Engine())
+ monkeypatch.setattr("repowise.core.persistence.database.init_db", lambda _e: _noop_coro())
+ monkeypatch.setattr(
+ "sqlalchemy.ext.asyncio.async_sessionmaker", lambda *a, **k: lambda: _Session()
+ )
+ monkeypatch.setattr(
+ "repowise.cli.providers.embedders.build_embedder", lambda _n: _WideEmbedder()
+ )
+
+ await reindex_cmd._reindex(tmp_path, "openai", batch_size=8)
+
+ assert _read_config(tmp_path)["embedder"] == "mock"
+
+
+async def _noop_coro() -> None:
+ return None
+
+
+# --- "mock" in config is not a choice anyone made ---------------------------
+
+
+def test_persisted_mock_does_not_count_as_a_requested_embedder(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A second ``init`` must not silently bill a hosted embedder.
+
+ ``embedder: mock`` is what a keyless run writes on its way out. Treating it
+ as an explicit request makes the re-init resolve a paid embedder and embed
+ the whole wiki through it, on a run whose own header says no model, no cost.
+ """
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+
+ for pinned in (None, "", " ", "mock"):
+ assert providers.embedder_was_requested(None, pinned) is False
+
+
+def test_a_real_pin_does_count_as_a_requested_embedder(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The re-init case the mock carve-out must not break.
+
+ Dropping a real pin to the mock would re-embed the store at a different
+ width, which the LanceDB writer resolves by dropping the table.
+ """
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+
+ for pinned in ("openai", "gemini", "ollama"):
+ assert providers.embedder_was_requested(None, pinned) is True
+ # An explicit flag or env var is a request regardless of the pin.
+ assert providers.embedder_was_requested("openai", "mock") is True
+ monkeypatch.setenv("REPOWISE_EMBEDDER", "gemini")
+ assert providers.embedder_was_requested(None, "mock") is True
+
+
+def test_pin_predicate_ignores_the_environment(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The workspace phase folds in the pin only, never the env, a second time.
+
+ Its caller has already weighed the flag and ``REPOWISE_EMBEDDER`` and passed
+ down a verdict. Re-reading them there would let a stray env var override a
+ caller that decided "not requested", and put a hosted embedder on the bill
+ for a run advertised as free.
+ """
+ monkeypatch.setenv("REPOWISE_EMBEDDER", "openai")
+
+ assert providers.pin_names_an_embedder("mock") is False
+ assert providers.pin_names_an_embedder(None) is False
+ assert providers.pin_names_an_embedder("gemini") is True
+
+
+# --- the upgrade layer detects a real embedder change -----------------------
+
+
+def test_width_mismatch_triggers_an_auto_reembed() -> None:
+ """The check that actually fires.
+
+ The model-name comparison it sits beside reads ``REPOWISE_EMBEDDING_MODEL``
+ on both sides, which almost nobody sets, so both are ``None`` and it
+ no-ops. Width is not opt-in.
+ """
+ verdict = assess(
+ {"store_format_version": STORE_FORMAT_VERSION},
+ stored_vector_dim=8,
+ current_vector_dim=1536,
+ )
+ assert verdict.tier == UpgradeTier.AUTO
+ assert UpgradeActionKind.REEMBED_VECTORS in [a.kind for a in verdict.actions]
+
+
+def test_matching_width_is_a_noop() -> None:
+ verdict = assess(
+ {"store_format_version": STORE_FORMAT_VERSION},
+ stored_vector_dim=1536,
+ current_vector_dim=1536,
+ )
+ assert verdict.is_noop
+
+
+def test_unknown_width_never_triggers() -> None:
+ """Either side unknown means "cannot tell", which must not mean "changed"."""
+ for stored, current in ((8, None), (None, 1536), (None, None)):
+ verdict = assess(
+ {"store_format_version": STORE_FORMAT_VERSION},
+ stored_vector_dim=stored,
+ current_vector_dim=current,
+ )
+ assert verdict.is_noop
+
+
+def _patch_stored_dim(monkeypatch: pytest.MonkeyPatch, dim: int | None) -> None:
+ # _vector_dims imports this locally, so the module attribute is the one
+ # that takes effect.
+ monkeypatch.setattr("repowise.cli.providers.vector_store.existing_vector_dim", lambda _d: dim)
+
+
+def test_mock_width_with_a_real_pin_proposes_a_re_embed(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The leftover-keyless-vectors case, which is the one worth acting on."""
+ from repowise.cli.upgrade import _vector_dims
+
+ _write_config(tmp_path, embedder="openai")
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+ _patch_stored_dim(monkeypatch, 8)
+ monkeypatch.setattr(
+ "repowise.cli.providers.embedders.build_embedder", lambda _n: _WideEmbedder()
+ )
+
+ assert _vector_dims(tmp_path) == (8, 1536)
+
+
+def test_two_real_widths_are_never_compared(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The re-embed loop this must not have.
+
+ ``dimensions`` is a lookup against a short hardcoded table, so an Ollama
+ model outside that table reports 768 when it really produces 1024. Acting
+ on that writes the true width back, so the next run sees the same
+ disagreement, forever — a full-wiki embedding bill on every ``update``.
+ Stored widths that are not the mock's are therefore never compared.
+ """
+ from repowise.cli.upgrade import _vector_dims
+
+ _write_config(tmp_path, embedder="ollama")
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+ _patch_stored_dim(monkeypatch, 1024)
+
+ class _MisreportingEmbedder:
+ dimensions = 768 # the hardcoded guess, not what it actually emits
+
+ async def embed(self, texts: list[str]) -> list[list[float]]:
+ return [[0.0] * 1024 for _ in texts]
+
+ monkeypatch.setattr(
+ "repowise.cli.providers.embedders.build_embedder", lambda _n: _MisreportingEmbedder()
+ )
+
+ assert _vector_dims(tmp_path) == (None, None)
+
+
+def test_mock_pin_never_proposes_re_embedding_a_real_store(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Re-embedding a real store down to 8-dim hashes is pure loss."""
+ from repowise.cli.upgrade import _vector_dims
+
+ _write_config(tmp_path, embedder="mock")
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+ _patch_stored_dim(monkeypatch, 1536)
+
+ assert _vector_dims(tmp_path) == (None, None)
+
+
+async def test_auto_reembed_refuses_to_run_with_a_mock_embedder(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The other auto-action can reach the executor on a mock-pinned repo.
+
+ Letting it through would rewrite every vector in the wiki as an 8-dim hash.
+ """
+ from repowise.cli import upgrade as upgrade_mod
+
+ _write_config(tmp_path, embedder="mock")
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+
+ called = False
+
+ async def _boom(*_a: object, **_k: object) -> None:
+ nonlocal called
+ called = True
+
+ monkeypatch.setattr("repowise.cli.commands.reindex_cmd._reindex", _boom)
+
+ await upgrade_mod._CliUpgradeContext(tmp_path).reembed_vectors()
+
+ assert called is False
+
+
+# --- doctor --fix referenced a column that does not exist ------------------
+
+
+def test_page_has_no_page_id_attribute() -> None:
+ """Why ``doctor --fix``'s repair never ran.
+
+ Both its FTS and vector branches filtered on ``Page.page_id``. The natural
+ primary key is spelled ``id``; ``page_id`` on the model is a *different*
+ table's foreign key. So the repair raised AttributeError every time, and
+ the vector branch's ``except`` reported it as "Vector repair skipped".
+ """
+ from repowise.core.persistence.models import Page
+
+ assert hasattr(Page, "id")
+ assert not hasattr(Page, "page_id")
+
+
+def test_duplicate_reembed_actions_run_once() -> None:
+ """Two checks can both conclude "re-embed"; the API bill should not double."""
+ import asyncio
+
+ from repowise.core.upgrade import UpgradeAction, UpgradeVerdict, apply_auto
+
+ calls = 0
+
+ class _Ctx:
+ async def reembed_vectors(self) -> None:
+ nonlocal calls
+ calls += 1
+
+ def drop_parse_cache(self) -> None:
+ return None
+
+ verdict = UpgradeVerdict(
+ tier=UpgradeTier.AUTO,
+ from_store_version=STORE_FORMAT_VERSION,
+ to_store_version=STORE_FORMAT_VERSION,
+ written_by=None,
+ actions=(
+ UpgradeAction(kind=UpgradeActionKind.REEMBED_VECTORS, reason="model changed"),
+ UpgradeAction(kind=UpgradeActionKind.REEMBED_VECTORS, reason="width changed"),
+ ),
+ user_notice=None,
+ reindex_command=None,
+ )
+ asyncio.run(apply_auto(verdict, _Ctx()))
+ assert calls == 1