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
fix(generation): persist a subject reuse key so interrupted runs can be topped up (#1961)
Nehal K1b5e699c7729
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_generate.py b/packages/cli/src/repowise/cli/commands/init_cmd/_generate.pyindex 4cfcc972c..fc61f5957 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/_generate.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_generate.py@@ -261,6 +261,7 @@ def _run_generation_phase(test_run: bool,timings: Any | None = None,warnings: list[str] | None = None,+ reuse_prior_pages: bool = True,folder_coverage_rules: tuple[str, ...] = (),) -> tuple[bool, bool]:"""Run the LLM generation phase for a single-repo init.@@ -269,6 +270,9 @@ def _run_generation_phase(and the caller should return immediately; ``cost_declined`` is True when theuser declined the cost gate (generation skipped, index still saved). Mutates``result`` in place with the generated pages, vector store, and enriched KG.++ ``reuse_prior_pages=False`` is ``--force``: every page is regenerated+ instead of reused from the prior run (issue #1089)."""from repowise.core.generation import GenerationConfig@@ -287,6 +291,7 @@ def _run_generation_phase(enable_onboarding=onboarding,wiki_style=wiki_style,max_file_pages=max_file_pages,+ reuse_prior_pages=reuse_prior_pages,**folder_coverage_override(folder_coverage_rules),)plans, est = estimate_generation(@@ -393,6 +398,9 @@ def _generate_with_model(run: InitRun) -> bool:warnings=run.run_warnings,test_run=opts.test_run,timings=run.recorder.table,+ # ``--force`` regenerates every page: the reuse gate is off, so+ # nothing is carried over from the prior run (issue #1089).+ reuse_prior_pages=not opts.force,)if gen_stop:return Truediff --git a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py b/packages/cli/src/repowise/cli/commands/init_cmd/generation.pyindex 20adf7678..acdeef62c 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py@@ -318,6 +318,10 @@ def run_repo_generation(generation wrapper, enriches the KG, and flushes buffered cost rows in onetransaction (kept out of the contended generation window, issue #326).+ ``gen_config.reuse_prior_pages=False`` (``repowise init --force``) disables the+ cross-run reuse gate so every page is regenerated, as the flag's help+ text has always promised (issue #1089).+Mutates ``result`` in place with ``generated_pages``, ``preserved_page_ids``(the pages a resumed run skipped, which persistence must not sweep) and``vector_store``@@ -421,6 +425,7 @@ def run_repo_generation(progress=gen_callback,resume=resume,preserved_page_ids=preserved_page_ids,+ reuse_prior_pages=getattr(gen_config, "reuse_prior_pages", True),cost_tracker=cost_tracker,generation_config=gen_config,# In-memory curated modules: on a fresh init thediff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex a0720d399..67286b621 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -110,6 +110,7 @@ def _run_workspace_generation(onboarding: bool = True,wiki_style: str = DEFAULT_STYLE,language: str = "en",+ reuse_prior_pages: bool = True,) -> list[Any]:"""Run LLM generation for a single repo in the workspace init flow.@@ -117,6 +118,9 @@ def _run_workspace_generation(the user declines the cost gate (caller persists the index without docs);other errors propagate so the caller can log per-repo failures withoutaborting the whole workspace run.++ ``reuse_prior_pages=False`` is ``--force``: every page is regenerated+ instead of reused from the prior run (issue #1089)."""from repowise.core.generation import GenerationConfig@@ -130,6 +134,7 @@ def _run_workspace_generation(# No question is asked in the workspace flow, so this only picks up a cap# already recorded for this repo (by a single-repo init, or by hand).max_file_pages=resolve_max_file_pages(config=load_config(repo_path)),+ reuse_prior_pages=reuse_prior_pages,)plans, est = estimate_generation(result=result,@@ -505,6 +510,7 @@ def _generate_repo_with_model(onboarding=ctx.onboarding,wiki_style=ctx.wiki_style,language=ctx.language,+ reuse_prior_pages=not ctx.force,)result.generated_pages = generated_pages# ``result.vector_store`` is set inside the generation call.diff --git a/packages/core/alembic/versions/0120_wiki_pages_content_hash.py b/packages/core/alembic/versions/0120_wiki_pages_content_hash.pynew file mode 100644index 000000000..f464aaf02--- /dev/null+++ b/packages/core/alembic/versions/0120_wiki_pages_content_hash.py@@ -0,0 +1,45 @@+"""Add content_hash to wiki_pages.++The cross-run reuse key for a model-written page: a stable digest of the+page's subject (file bytes, group membership, repo name) folded with a+renderer fingerprint. Unlike ``source_hash`` it survives RAG-context drift+between runs, so an unchanged page is reused instead of re-billed on every+full run — the gap that made a provider-outage-interrupted run impossible to+top up cheaply (issue #1089). Existing rows default to empty, which the+reuse gate treats as "no subject key yet" and falls back to the prompt hash.++Revision ID: 0120+Revises: 0119+Create Date: 2026-08-28+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "0120"+down_revision: str | None = "0119"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def _columns() -> set[str]:+ inspector = sa.inspect(op.get_bind())+ return {c["name"] for c in inspector.get_columns("wiki_pages")}+++def upgrade() -> None:+ # Guarded: ``init_db``'s reconciler may already have added it on Postgres.+ if "content_hash" not in _columns():+ op.add_column(+ "wiki_pages",+ sa.Column("content_hash", sa.String(64), nullable=False, server_default=""),+ )+++def downgrade() -> None:+ if "content_hash" in _columns():+ op.drop_column("wiki_pages", "content_hash")diff --git a/packages/core/src/repowise/core/generation/models.py b/packages/core/src/repowise/core/generation/models.pyindex 282d46056..5ba7c49c3 100644--- a/packages/core/src/repowise/core/generation/models.py+++ b/packages/core/src/repowise/core/generation/models.py@@ -344,6 +344,9 @@ class GenerationConfig:# Page key -> explicit repository-relative files to add. Supported keys are# ``repo_overview`` and ``onboarding/<slot>``.source_evidence_files: Mapping[str, tuple[str, ...]] = field(default_factory=dict)+ # False on ``init --force``: no prior pages are loaded, so the reuse gate+ # has nothing to carry over and every page is regenerated (issue #1089).+ reuse_prior_pages: bool = Truedef to_dict(self) -> dict[str, Any]:"""Return the supported plain, rehydratable configuration snapshot."""diff --git a/packages/core/src/repowise/core/generation/page_generator/README.md b/packages/core/src/repowise/core/generation/page_generator/README.mdindex 16f73b25d..6b6d4fc48 100644--- a/packages/core/src/repowise/core/generation/page_generator/README.md+++ b/packages/core/src/repowise/core/generation/page_generator/README.md@@ -49,6 +49,8 @@ from repowise.core.generation.page_generator import PageGenerator, SYSTEM_PROMPT- `levels.py` — pure per-level coroutine builders reading the run state.- `structural.py` — renderers that build a page from structure with no modelcall: the sole renderers (file pages among them) and the keyless stubs.+- `reuse.py` — cross-run reuse of model pages: the subject reuse key and the+ gate that decides whether a prior run's page is returned instead of a call.- `prompts.py`, `validation.py`, `helpers.py` — constants and pure helpers.## Extension pointsdiff --git a/packages/core/src/repowise/core/generation/page_generator/core.py b/packages/core/src/repowise/core/generation/page_generator/core.pyindex c60e4e778..c38c2bafe 100644--- a/packages/core/src/repowise/core/generation/page_generator/core.py+++ b/packages/core/src/repowise/core/generation/page_generator/core.py@@ -25,7 +25,6 @@ import structlogfrom repowise.core.ingestion.models import ParsedFile, RepoStructurefrom repowise.core.providers.llm.base import BaseProvider, CacheHint, GeneratedResponse-from ..agent_digest import rejoin_questionsfrom ..context.evidence import (EvidenceItem,EvidenceSelection,@@ -41,7 +40,6 @@ from ..models import (GeneratedPage,GenerationConfig,compute_page_id,- compute_source_hash,)from ..report import reset_house_termsfrom ..structural_labels import resolve_structural_labels, structural_page_title@@ -49,6 +47,7 @@ from ..styles import ONBOARDING_PAGE_TYPE, resolve_stylefrom .helpers import _extract_summary, _now_iso, collapse_empty_duplicate_headingsfrom .pertype import PerTypeGenerationMixinfrom .prompts import CORRECTIVE_RETRY_DIRECTIVE, SUPPORTED_LANGUAGES, SYSTEM_PROMPTS+from .reuse import reuse_prior_responsefrom .structural import (StructuralRenderMixin,register_filters,@@ -119,15 +118,20 @@ def _attach_file_provenance(page: GeneratedPage, ctx: FilePageContext) -> None:class PriorPage:"""Snapshot of a previously-generated page used for cross-run reuse.- Lives in :class:`PageGenerator` keyed by ``page_id``. When the freshly- rendered prompt produces a matching ``source_hash`` under the same- ``model_name``, the LLM call is skipped and ``content`` is reused.+ Lives in :class:`PageGenerator` keyed by ``page_id``. Reuse happens when+ the freshly rendered page still matches on the *subject* the page+ documents — ``content_hash`` when both sides have one, else the rendered+ prompt's ``source_hash`` under the same ``model_name`` — and the row was+ actually written by a model (``provider_name != 'template'``).``content_hash`` is the preferred reuse key when both sides have one: it- stays stable across runs even when the rendered prompt drifts (RAG context- is rebuilt and populated concurrently each run, so ``source_hash`` alone- almost never matches on a reindex). Structural pages compute theirs in- :meth:`StructuralRenderMixin._structural_content_hash`.+ stays stable across runs even when the rendered prompt drifts (RAG+ context is rebuilt and populated concurrently each run, so ``source_hash``+ alone almost never matches on a reindex — the defect that made every full+ run re-bill every page, issue #1089). Structural pages compute theirs in+ :meth:`StructuralRenderMixin._structural_content_hash`; model pages+ compute it from their subject material (see+ :func:`.reuse.model_reuse_key`)."""source_hash: str@@ -140,6 +144,10 @@ class PriorPage:content_hash: str = ""#: The stored page's metadata, for facts a reused page must carry forward.metadata: Mapping[str, Any] = field(default_factory=dict)+ #: Persisted ``provider_name``. A row stamped ``template`` was never+ #: written by a model — a keyless stub, or a stub a failed provider call+ #: left behind — so it must never be reused as if it were prose.+ provider_name: str = ""class PageGenerator(PerTypeGenerationMixin, StructuralRenderMixin):@@ -381,6 +389,7 @@ class PageGenerator(PerTypeGenerationMixin, StructuralRenderMixin):request_id: str,target_path: str | None = None,source_salt: str = "",+ reuse_content_hash: str = "",) -> GeneratedResponse:"""Call the provider with caching, optionally prefixing a language instruction.@@ -389,33 +398,37 @@ class PageGenerator(PerTypeGenerationMixin, StructuralRenderMixin):generation-version salt so a builder/template upgrade forces a one-timeregen even when the rendered prompt is byte-identical. Empty for everyother page type, so their reuse hashes are unchanged.++ *reuse_content_hash* is the stable subject digest this page's prose is+ keyed on (issue #1089). When the caller provides one, the persistent+ reuse gate prefers it over ``source_hash``: the prompt drifts run to+ run (RAG context is rebuilt concurrently), so a source-hash-only gate+ re-billed every page on every full run, while the subject digest stays+ put for an unchanged file/group/repo. When the prior row was never+ actually written by a model (``provider_name == 'template'`` — a+ keyless stub, or a stub left by a failed provider call), it is never+ reused: copying a placeholder over a placeholder would keep the page+ unwritten forever and hide the failure from ``repowise generate``."""# Persistent cross-run cache: if the page exists from a prior run, was- # produced by the same model, and the prompt's source_hash matches,- # reuse the stored content without an LLM call.+ # produced by the same model, and still matches on its subject, reuse+ # the stored content without an LLM call.if self._config.cache_enabled and target_path is not None:- page_id = compute_page_id(page_type, target_path)- prior = self._prior_pages.get(page_id)- if (- prior is not None- and prior.model_name == self._provider.model_name- and prior.source_hash == compute_source_hash(user_prompt + source_salt)- ):+ reused = reuse_prior_response(+ self._prior_pages.get(compute_page_id(page_type, target_path)),+ model_name=self._provider.model_name,+ reuse_content_hash=reuse_content_hash,+ prompt=user_prompt + source_salt,+ )+ if reused is not None:self._reuse_count += 1log.debug("page_cache.persistent_hit",page_type=page_type,target_path=target_path,+ key="subject" if reuse_content_hash else "prompt",)- return GeneratedResponse(- # The stored body lost its questions to the digest; the- # response it was split from carried them.- content=rejoin_questions(prior.content, prior.digest),- input_tokens=0,- output_tokens=0,- cached_tokens=0,- usage={"reused_from_prior_run": True},- )+ return reusedkey = self._compute_cache_key(page_type, user_prompt)if self._config.cache_enabled and key in self._cache:diff --git a/packages/core/src/repowise/core/generation/page_generator/pertype.py b/packages/core/src/repowise/core/generation/page_generator/pertype.pyindex e8463e1a3..c1a26de44 100644--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py@@ -8,6 +8,7 @@ each module under the project's 400-line ceiling.from __future__ import annotations+import hashlibimport reimport uuidfrom collections.abc import Sequence@@ -51,6 +52,7 @@ from ..overview_tables import ()from ..page_sources import lint_sourcesfrom ..structural_labels import structural_page_title+from .reuse import files_digest, group_material, model_reuse_keylog = structlog.get_logger(__name__)@@ -159,8 +161,8 @@ def _with_capability_table(class PerTypeGenerationMixin:"""Per-type ``generate_*`` methods. Requires the host to provide- ``_assembler``, ``_render``, ``_call_provider`` and- ``_build_generated_page`` (all supplied by :class:`PageGenerator`).+ ``_assembler``, ``_render``, ``_call_provider`` and ``_build_generated_page``+ (all supplied by :class:`PageGenerator`)."""async def generate_file_page(@@ -384,12 +386,28 @@ class PerTypeGenerationMixin:return pageif self._config.deterministic:+page = self._stub_module_page(ctx, page_target, title)return _stamp_concept(_with_digest(page))user_prompt = self._render("module_page.j2", ctx=ctx)+ # The page's subject is its group: the membership ``structural_key``+ # hashes, plus each member file's bytes, so an unchanged group reuses+ # its prose across RAG drift while an edited member regenerates it+ # (issue #1089). Folded with the renderer fingerprint, so a+ # prompt/template/style upgrade still forces a one-time regen.+ reuse_key = model_reuse_key(+ self,+ group_material(structural_key, members, source_map),+ "module_page",+ "module_page.j2",+ )try:response = await self._call_provider(- "module_page", user_prompt, str(uuid.uuid4()), target_path=page_target+ "module_page",+ user_prompt,+ str(uuid.uuid4()),+ target_path=page_target,+ reuse_content_hash=reuse_key,)except Exception as exc:stub = self._stub_module_page(ctx, page_target, title)@@ -401,6 +419,7 @@ class PerTypeGenerationMixin:response,compute_source_hash(user_prompt),GENERATION_LEVELS["module_page"],+ content_hash=reuse_key,)# Citations of a missing file, or one its section never names, go.# Diagrams are checked for every page of the run in ``sanitize_pages``.@@ -510,9 +529,26 @@ class PerTypeGenerationMixin:user_prompt, evidence = self._append_source_evidence(user_prompt, "repo_overview", source_map or {})+ # The overview's subject is the repository: its name, the system map it+ # names, and the source evidence it quotes. RAG drift alone reuses the+ # prose; a changed map or evidence file regenerates it (issue #1089).+ map_digest = hashlib.sha256(+ (naming_payload(system_map) if system_map else "").encode()+ ).hexdigest()+ evidence_files = files_digest((item.path for item in evidence.included), source_map or {})+ reuse_key = model_reuse_key(+ self,+ f"{repo_name}|{map_digest}|{evidence_files}",+ "repo_overview",+ "repo_overview.j2",+ )try:response = await self._call_provider(- "repo_overview", user_prompt, str(uuid.uuid4()), target_path=repo_name+ "repo_overview",+ user_prompt,+ str(uuid.uuid4()),+ target_path=repo_name,+ reuse_content_hash=reuse_key,)except Exception as exc:stub = self._stub_repo_overview(@@ -581,10 +617,12 @@ class PerTypeGenerationMixin:response,compute_source_hash(user_prompt),GENERATION_LEVELS["repo_overview"],+ content_hash=reuse_key,)page = _with_system_map(page, system_map, repo_name, names)return self._attach_source_evidence(page, "repo_overview", evidence)+async def generate_api_contract(self,parsed: ParsedFile,@@ -659,9 +697,28 @@ class PerTypeGenerationMixin:# Fold the onboarding generation version into the reuse hash so a# builder/template upgrade forces a one-time regen of cached pages.salt = _onboarding.ONBOARDING_GENERATION_VERSION+ # Subject: the slot's evidence files. Their raw bytes are the+ # volatile input (they are what the page narrates), and they are+ # stable across runs when unchanged — the one part of the prompt that+ # must not silently age out (issue #1089). The slot's own name rides+ # along so two slots sharing a file still get distinct keys.+ evidence_files = files_digest(+ (item.path for item in evidence.included), signals.source_map+ )+ reuse_key = model_reuse_key(+ self,+ spec.slot + "|" + evidence_files,+ "onboarding",+ template_name,+ )try:response = await self._call_provider(- "onboarding", user_prompt, str(uuid.uuid4()), target_path=target, source_salt=salt+ "onboarding",+ user_prompt,+ str(uuid.uuid4()),+ target_path=target,+ source_salt=salt,+ reuse_content_hash=reuse_key,)except Exception as exc:# ``_stub_onboarding_page`` stamps the subkind metadata itself, so@@ -694,6 +751,7 @@ class PerTypeGenerationMixin:response,compute_source_hash(user_prompt + salt),GENERATION_LEVELS["onboarding"],+ content_hash=reuse_key,)# Subkind discriminator lives in metadata; page_type alone is shared# across all six generated onboarding slots.diff --git a/packages/core/src/repowise/core/generation/page_generator/reuse.py b/packages/core/src/repowise/core/generation/page_generator/reuse.pynew file mode 100644index 000000000..6f182a0d4--- /dev/null+++ b/packages/core/src/repowise/core/generation/page_generator/reuse.py@@ -0,0 +1,133 @@+"""Cross-run reuse of model-written pages (issue #1089).++A model page is reused from the prior run when it still matches on the+*subject* it documents: ``content_hash`` when both sides have one, else the+rendered prompt's ``source_hash`` under the same model. The prompt drifts run+to run (RAG context is rebuilt concurrently), so a prompt-only gate re-billed+every page on every full run; the subject digest stays put for an unchanged+file, group or repo.+"""++from __future__ import annotations++import hashlib+from collections.abc import Iterable, Mapping+from typing import TYPE_CHECKING, Any++import jinja2++from repowise.core.providers.llm.base import GeneratedResponse+from repowise.core.providers.llm.template import TEMPLATE_PROVIDER_NAME++from ..agent_digest import rejoin_questions+from ..models import compute_source_hash+from .prompts import SYSTEM_PROMPTS++if TYPE_CHECKING:+ from .core import PriorPage++# Bumped by hand when a change to the model-page reuse fingerprint must force+# a one-time regeneration of subject-keyed pages whose renderer bytes did not+# change: a prompt-template edit is picked up automatically (the template+# source is hashed), so this only covers the cases hashing cannot see, the+# same convention as ``STRUCTURAL_GENERATION_VERSION``.+MODEL_PAGE_GENERATION_VERSION = "1"+++def files_digest(paths: Iterable[str], source_map: Mapping[str, bytes]) -> str:+ """``path:sha256(bytes)`` per file, sorted and joined: a page's file subject.++ A file missing from *source_map* hashes as empty (stable, not an error),+ so the key covers the files the prompt actually carried.+ """+ parts = {f"{p}:{hashlib.sha256(source_map.get(p) or b'').hexdigest()}" for p in paths}+ return "\x1f".join(sorted(parts))+++def group_material(+ structural_key: str, members: Iterable[str] | None, source_map: Mapping[str, bytes] | None+) -> str:+ """A module page's subject: its membership key plus its members' bytes.++ Empty without a ``structural_key``, which keeps the page on the+ prompt-hash gate.+ """+ if not structural_key:+ return ""+ return f"{structural_key}|{files_digest(members or (), source_map or {})}"+++def model_reuse_key(generator: Any, material: str, page_type: str, template: str) -> str:+ """Stable reuse key for a model-written page's subject.++ ``material`` is the page's subject in a form that does not drift between+ runs: the documented file's byte hash, a group's sorted member list, the+ repo's name. It is folded with a renderer fingerprint (the resolved+ prompt-template source, through the Jinja loader so a custom style's+ override fingerprints itself, plus system prompt, language, style and+ :data:`MODEL_PAGE_GENERATION_VERSION`), so a template or style upgrade+ forces a one-time regen like the structural pages' ``render_key``.++ An empty *material* yields an empty key, which keeps the page out of+ subject-keyed reuse and falls back to the prompt-hash gate.+ """+ if not material:+ return ""+ env = generator._jinja_env+ try:+ loader = getattr(env, "loader", None)+ source = loader.get_source(env, template)[0] if loader else None+ except (jinja2.TemplateNotFound, OSError):+ source = None+ fingerprint = hashlib.sha256(+ "\x00".join(+ [+ MODEL_PAGE_GENERATION_VERSION,+ page_type,+ template,+ source or "",+ SYSTEM_PROMPTS.get(page_type, ""),+ generator._language or "en",+ generator._style.fingerprint,+ ]+ ).encode()+ ).hexdigest()+ return hashlib.sha256(f"{material}:{fingerprint}".encode()).hexdigest()+++def reuse_prior_response(+ prior: PriorPage | None,+ *,+ model_name: str,+ reuse_content_hash: str,+ prompt: str,+) -> GeneratedResponse | None:+ """The prior run's response for this page when it may be reused, else None.++ *prompt* is the rendered prompt plus any salt, hashed only when the+ subject digest is missing on either side. A row stamped ``template`` is a+ stub, never prose: reusing it would present a placeholder as the finished+ page and, because stubs are kept out of the resume ledger, let the run+ claim the page was written when nothing wrote it.+ """+ if prior is None or prior.model_name != model_name:+ return None+ if prior.provider_name == TEMPLATE_PROVIDER_NAME:+ return None+ if reuse_content_hash and prior.content_hash:+ matched = prior.content_hash == reuse_content_hash+ else:+ # Pre-key pages, or a caller that could not derive a digest: the+ # gate's historical rendered-prompt comparison.+ matched = prior.source_hash == compute_source_hash(prompt)+ if not matched:+ return None+ return GeneratedResponse(+ # The stored body lost its questions to the digest; the response it+ # was split from carried them.+ content=rejoin_questions(prior.content, prior.digest),+ input_tokens=0,+ output_tokens=0,+ cached_tokens=0,+ usage={"reused_from_prior_run": True},+ )diff --git a/packages/core/src/repowise/core/generation/page_generator/structural.py b/packages/core/src/repowise/core/generation/page_generator/structural.pyindex 60d3fcc75..4cf752d70 100644--- a/packages/core/src/repowise/core/generation/page_generator/structural.py+++ b/packages/core/src/repowise/core/generation/page_generator/structural.py@@ -556,10 +556,9 @@ FILE_PAGE_TEMPLATE = "file_page.j2"SYMBOL_SPOTLIGHT_TEMPLATE = "symbol_spotlight.j2"# Metadata key holding a structural page's render fingerprint. It lives in-# metadata rather than in a column of its own because ``GeneratedPage`` already-# has a ``content_hash`` field that is never persisted (nothing populates it-# when prior pages are loaded), and a second unpersisted hash would be worse-# than none. metadata_json is written and read back on every page already.+# metadata rather than in a column of its own because ``wiki_pages.content_hash``+# is already the model pages' subject reuse key (issue #1089), a different+# digest. metadata_json is written and read back on every page already.RENDER_KEY = "render_key"diff --git a/packages/core/src/repowise/core/persistence/crud/pages.py b/packages/core/src/repowise/core/persistence/crud/pages.pyindex d17e6159c..02ef22b58 100644--- a/packages/core/src/repowise/core/persistence/crud/pages.py+++ b/packages/core/src/repowise/core/persistence/crud/pages.py@@ -65,6 +65,7 @@ def _apply_page_upsert(digest: str,target_path: str,source_hash: str,+ content_hash: str,model_name: str,provider_name: str,input_tokens: int,@@ -151,6 +152,11 @@ def _apply_page_upsert(existing.display_order = display_orderexisting.section_number = section_numberexisting.structural_key = structural_key+ # The reuse key describes the *subject*, so it can change while+ # the bytes do not (the same file documented under a new style).+ # Refresh it on the touch path so an unchanged page still picks+ # up the current renderer fingerprint (issue #1089).+ existing.content_hash = content_hash or existing.content_hashreturn existing# Archive the current state before overwriting@@ -180,6 +186,7 @@ def _apply_page_upsert(existing.digest = digestexisting.target_path = target_pathexisting.source_hash = source_hash+ existing.content_hash = content_hash or existing.content_hashexisting.model_name = model_nameexisting.provider_name = provider_nameexisting.input_tokens = input_tokens@@ -207,6 +214,7 @@ def _apply_page_upsert(digest=digest,target_path=target_path,source_hash=source_hash,+ content_hash=content_hash,model_name=model_name,provider_name=provider_name,input_tokens=input_tokens,@@ -240,6 +248,7 @@ async def upsert_page(digest: str = "",target_path: str,source_hash: str,+ content_hash: str = "",model_name: str,provider_name: str,input_tokens: int = 0,@@ -261,6 +270,11 @@ async def upsert_page(First call → inserts Page at version=1.Subsequent → archives the current Page as a PageVersion, then updates thePage in-place (version += 1, created_at preserved).++ ``content_hash`` is the cross-run reuse key: a stable digest of the page's+ subject folded with a renderer fingerprint, surviving RAG-context drift+ that invalidates ``source_hash`` on every full run (issue #1089). Empty+ when the caller has no subject digest (pre-key callers keep working)."""now = _now_utc()meta_json = json.dumps(metadata or {})@@ -281,6 +295,7 @@ async def upsert_page(digest=digest,target_path=target_path,source_hash=source_hash,+ content_hash=content_hash,model_name=model_name,provider_name=provider_name,input_tokens=input_tokens,@@ -309,9 +324,13 @@ async def load_prior_pages("""Return a ``page_id → PriorPage`` map for cross-run cache reuse.Loads every existing wiki page for the repository so the generator can- short-circuit the LLM call when the freshly rendered prompt produces a- matching ``source_hash`` under the same model. Returns an empty dict if- nothing has been generated yet.+ short-circuit the LLM call when the page's subject still matches under+ the same model — keyed on ``content_hash`` when one is stored, else on+ the freshly rendered prompt's ``source_hash``. Returns an empty dict if+ nothing has been generated yet. Rows a model never wrote (``template``+ provider — keyless stubs, or stubs left by failed provider calls) carry+ their ``provider_name`` so the reuse gate can refuse to copy them+ (issue #1089)."""# Import lazily — keeps persistence independent of generation models at# module-load time.@@ -332,6 +351,7 @@ async def load_prior_pages(continueprior[row.id] = PriorPage(source_hash=row.source_hash,+ content_hash=row.content_hash or "",model_name=row.model_name,content=row.content,digest=row.digest or "",@@ -339,6 +359,7 @@ async def load_prior_pages(output_tokens=row.output_tokens,cached_tokens=row.cached_tokens,metadata=metadata,+ provider_name=row.provider_name,)return prior@@ -366,6 +387,7 @@ async def upsert_page_from_generated(digest=getattr(gp, "digest", "") or "",target_path=gp.target_path, # type: ignore[attr-defined]source_hash=gp.source_hash, # type: ignore[attr-defined]+ content_hash=getattr(gp, "content_hash", "") or "",model_name=gp.model_name, # type: ignore[attr-defined]provider_name=gp.provider_name, # type: ignore[attr-defined]input_tokens=gp.input_tokens, # type: ignore[attr-defined]@@ -449,6 +471,7 @@ async def upsert_pages_from_generated(digest=getattr(gp, "digest", "") or "",target_path=gp.target_path,source_hash=gp.source_hash,+ content_hash=getattr(gp, "content_hash", "") or "",model_name=gp.model_name,provider_name=gp.provider_name,input_tokens=gp.input_tokens,diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 5254cd6f2..559c40913 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -213,6 +213,13 @@ class Page(Base):digest: Mapped[str] = mapped_column(Text, nullable=False, default="", server_default="")target_path: Mapped[str] = mapped_column(Text, nullable=False)source_hash: Mapped[str] = mapped_column(String(64), nullable=False)+ # Cross-run reuse key: a stable digest of the page's subject (the file /+ # group / repo it documents) folded with a fingerprint of the renderer+ # (prompt template, system prompt, language, style). Unlike ``source_hash``+ # it survives RAG-context drift between runs, so an unchanged page is+ # reused instead of re-billed on every full run. Empty for pages written+ # before the key existed, or for a page with no stable subject.+ content_hash: Mapped[str] = mapped_column(String(64), nullable=False, default="")model_name: Mapped[str] = mapped_column(String(128), nullable=False)provider_name: Mapped[str] = mapped_column(String(64), nullable=False)input_tokens: Mapped[int] = mapped_column(Integer, nullable=False, default=0)diff --git a/packages/core/src/repowise/core/pipeline/scoped_generation.py b/packages/core/src/repowise/core/pipeline/scoped_generation.pyindex 2d90720b5..3b8ea354d 100644--- a/packages/core/src/repowise/core/pipeline/scoped_generation.py+++ b/packages/core/src/repowise/core/pipeline/scoped_generation.py@@ -31,6 +31,7 @@ from pathlib import Pathfrom typing import Anyimport structlog+from sqlalchemy.exc import SQLAlchemyErrorfrom repowise.core.generation.page_selection import PageRecordfrom repowise.core.generation.scope import (@@ -206,8 +207,19 @@ async def execute_scoped_generation(provider, and optional embedder / vector store / FTS / progress / costtracker. ``plan`` is a resolved:class:`~repowise.core.generation.scope.ScopePlan`.++ Prior pages are loaded and handed to the generator so a page the run is+ asked to refill (a stub, or one whose subject is unchanged) is reused+ rather than re-billed — the same cross-run gate ``init`` and ``update``+ use (issue #1089). A stub row is deliberately never reused, so a+ ``generate`` targeting the pages a failed run left behind still calls+ the model for them."""- from repowise.core.persistence import get_session, upsert_pages_from_generated+ from repowise.core.persistence import (+ get_session,+ load_prior_pages,+ upsert_pages_from_generated,+ )from repowise.core.persistence.crud import backfill_related_pagesfrom repowise.core.pipeline import run_generationfrom repowise.core.pipeline.persist import (@@ -221,6 +233,14 @@ async def execute_scoped_generation(if cost_tracker is not None:provider._cost_tracker = cost_tracker+ try:+ async with get_session(session_factory) as session:+ prior_pages = await load_prior_pages(session, repo_id)+ except (SQLAlchemyError, OSError):+ # Without prior pages the subject-hash skip is off and every requested+ # page re-bills; generation itself must not fail over the cache.+ prior_pages = {}+generated_pages = await run_generation(repo_path=repo_path,parsed_files=rehydrated.parsed_files,@@ -236,6 +256,7 @@ async def execute_scoped_generation(cost_tracker=cost_tracker,generation_config=generation_config,only_page_ids=plan.generate_ids,+ prior_pages=prior_pages,)if cost_tracker is not None:await cost_tracker.flush()diff --git a/tests/unit/cli/test_generation_persist.py b/tests/unit/cli/test_generation_persist.pyindex 87e4cce18..9e4660293 100644--- a/tests/unit/cli/test_generation_persist.py+++ b/tests/unit/cli/test_generation_persist.py@@ -219,6 +219,43 @@ async def test_non_resume_run_passes_no_persisted_ids(repo_dir, monkeypatch):await run_generation_with_persistence(repo_path=repo_dir, repo_name=repo_dir.name)assert seen["persisted"] is None++async def test_reuse_prior_pages_disabled_skips_the_prior_load(repo_dir, monkeypatch):+ """``--force`` (``reuse_prior_pages=False``) must not load prior pages:+ a forced run regenerates everything, so the load is pure waste — and+ worse, would feed the reuse gate pages the run is supposed to replace."""++ async def fake_run_generation(*, repo_path, on_page_ready=None, prior_pages=None, **_kw):+ assert prior_pages == {} # nothing loaded+ return []++ monkeypatch.setattr(+ "repowise.core.pipeline.run_generation", fake_run_generation, raising=True+ )+ await run_generation_with_persistence(+ repo_path=repo_dir, repo_name=repo_dir.name, reuse_prior_pages=False+ )+++async def test_reuse_prior_pages_enabled_loads_prior_pages(repo_dir, monkeypatch):+ """The default (no ``--force``) loads the prior map so the subject-keyed+ gate can reuse unchanged pages."""++ async def first_run(*, repo_path, on_page_ready=None, prior_pages=None, **_kw):+ on_page_ready(_page("gamma"))+ return [_page("gamma")]++ async def second_run(*, repo_path, on_page_ready=None, prior_pages=None, **_kw):+ assert prior_pages and "gamma" in prior_pages+ return []++ monkeypatch.setattr("repowise.core.pipeline.run_generation", first_run, raising=True)+ await run_generation_with_persistence(repo_path=repo_dir, repo_name=repo_dir.name)++ monkeypatch.setattr("repowise.core.pipeline.run_generation", second_run, raising=True)+ await run_generation_with_persistence(repo_path=repo_dir, repo_name=repo_dir.name)++async def test_generation_completion_callback_reports_only_current_run_failures(repo_dir, monkeypatch):diff --git a/tests/unit/generation/test_reuse_gate.py b/tests/unit/generation/test_reuse_gate.pynew file mode 100644index 000000000..37ba72902--- /dev/null+++ b/tests/unit/generation/test_reuse_gate.py@@ -0,0 +1,380 @@+"""Cross-run reuse gate for model-written pages (issue #1089).++The headline defect: a run interrupted by a provider outage could never be+topped up cheaply. Two halves:++* the reuse gate keyed only on the rendered prompt's ``source_hash``, which+ drifts run to run because RAG context is rebuilt concurrently — so every+ full run re-billed every page ("pages are always regenerated");+* a stub left by the failed provider call was indistinguishable from a+ written page, so a later run could copy the placeholder over itself+ instead of actually writing it ("the missing ones are unreachable" —+ that half was closed by the stub fallback itself).++These tests pin the repaired gate: subject-keyed reuse that survives prompt+drift, and a hard refusal to reuse any row a model never wrote.+"""++from __future__ import annotations++from dataclasses import replace++import networkx as nx++from repowise.core.generation.architecture_map import build_system_map+from repowise.core.generation.context_assembler import ContextAssembler, FilePageContext+from repowise.core.generation.models import STUB_FALLBACK_ERROR+from repowise.core.generation.page_generator import PageGenerator+from repowise.core.generation.page_generator.core import PriorPage+from repowise.core.generation.page_generator.reuse import group_material, model_reuse_key+from repowise.core.providers.llm.mock import MockProvider+++def _ctx(path: str = "pkg/resolvers/context.py") -> FilePageContext:+ return FilePageContext(+ file_path=path,+ language="python",+ docstring=None,+ symbols=[],+ imports=[],+ exports=[],+ pagerank_score=0.1,+ betweenness_score=0.0,+ community_id=0,+ dependents=[],+ dependencies=[],+ is_api_contract=False,+ is_entry_point=False,+ is_test=False,+ parse_errors=[],+ estimated_tokens=10,+ )+++def _module_page(+ gen: PageGenerator,+ *,+ structural_key: str,+ contexts: list[FilePageContext],+ target_path: str = "pkg/resolvers",+ title: str = "Resolvers",+ **kwargs,+):+ return gen.generate_module_page(+ title,+ "python",+ contexts,+ nx.DiGraph(),+ target_path=target_path,+ structural_key=structural_key,+ **kwargs,+ )+++def _prior_from(page) -> dict[str, PriorPage]:+ return {+ page.page_id: PriorPage(+ source_hash=page.source_hash,+ content_hash=page.content_hash,+ model_name=page.model_name,+ content=page.content,+ provider_name=page.provider_name,+ metadata=page.metadata,+ )+ }+++async def test_subject_keyed_reuse_survives_prompt_drift(sample_config):+ """The "pages are always regenerated" half of #1089.++ Run 1 writes the page. Run 2 renders a *different* prompt for the same+ group — the assembled context moved (RAG rebuild, a dependency summary+ landing) — so the old source-hash-only gate missed and re-billed it. The+ subject key (the group's ``structural_key`` and its members' bytes, folded+ with the renderer fingerprint) is unchanged, so the page is reused without+ a provider call.+ """+ gen = PageGenerator(MockProvider(), ContextAssembler(sample_config), sample_config)+ first = await _module_page(gen, structural_key="concept-resolvers", contexts=[_ctx("a.py")])+ assert first.content_hash # the key must actually be computed and stamped++ prior = {+ first.page_id: PriorPage(+ source_hash=first.source_hash,+ content_hash=first.content_hash,+ model_name=first.model_name,+ content=first.content,+ provider_name=first.provider_name,+ )+ }+ # Run 2: context around the group moved (another member's page summary+ # landed), so the rendered prompt and its source_hash change, while the+ # group's membership and file bytes hold.+ drift_provider = MockProvider()+ drift_gen = PageGenerator(+ drift_provider, ContextAssembler(sample_config), sample_config, prior_pages=prior+ )+ second = await _module_page(+ drift_gen,+ structural_key="concept-resolvers",+ contexts=[_ctx("a.py")],+ page_summaries={"a.py": "Resolves context for a request."},+ )++ assert second.source_hash != first.source_hash # prompt drifted+ assert drift_provider.call_count == 0 # but the page was not re-billed+ assert second.metadata.get("reused_from_prior_run") is True+ assert second.content == first.content+++async def test_a_stub_row_is_never_reused_on_a_top_up_run(sample_config):+ """The headline #1089 scenario: the missing pages are actually completed.++ Run 1's provider call failed, leaving a stub row+ (``provider_name='template'`` + ``STUB_FALLBACK_ERROR``). A later run+ asked for that page again must call the model — copying the placeholder+ over itself would keep the page unwritten forever while looking done.+ """+ gen = PageGenerator(MockProvider(), ContextAssembler(sample_config), sample_config)+ # Compute the exact subject key the generator will look up, so the match+ # would succeed if not for the stub guard.+ stub_key = model_reuse_key(+ gen, group_material("concept-resolvers", None, None), "module_page", "module_page.j2"+ )+ prior = {+ "module_page:pkg/resolvers": PriorPage(+ source_hash="prompt-hash-from-run-1",+ content_hash=stub_key,+ model_name=gen._provider.model_name,+ content="# Resolvers\n\n(stub — the provider was down)",+ provider_name="template", # never written by a model+ )+ }+ refill_provider = MockProvider()+ refill_gen = PageGenerator(+ refill_provider, ContextAssembler(sample_config), sample_config, prior_pages=prior+ )++ page = await _module_page(+ refill_gen, structural_key="concept-resolvers", contexts=[_ctx("a.py")]+ )++ assert page.content_hash == stub_key # the subject matched; only the guard refused+ assert refill_provider.call_count == 1+ assert page.metadata.get("reused_from_prior_run") is None+ assert page.content != "# Resolvers\n\n(stub — the provider was down)"+ assert STUB_FALLBACK_ERROR not in page.metadata+++async def test_a_keyless_stub_row_is_never_reused_either(sample_config):+ """Same refusal for the other template row: an index-only wiki's stub.++ A user who ran ``init --no-prose`` then ``update --full`` must get real+ prose, not their own placeholder echoed back at them.+ """+ gen = PageGenerator(MockProvider(), ContextAssembler(sample_config), sample_config)+ prior = {+ "module_page:pkg/resolvers": PriorPage(+ source_hash="k",+ content_hash="",+ model_name=gen._provider.model_name,+ content="# Resolvers (template stub)",+ provider_name="template",+ )+ }+ provider = MockProvider()+ refill_gen = PageGenerator(+ provider, ContextAssembler(sample_config), sample_config, prior_pages=prior+ )++ page = await _module_page(+ refill_gen, structural_key="concept-resolvers", contexts=[_ctx("a.py")]+ )++ assert provider.call_count == 1+ assert page.metadata.get("reused_from_prior_run") is None+++async def test_prompt_hash_gate_still_reuses_a_written_page(sample_config):+ """The historical gate keeps working for callers with no subject key.++ A pre-key row (``content_hash=''``) whose rendered prompt still hashes to+ the stored value under the same model is reused exactly as before — this+ is the path every existing store takes on its first run with the new+ code, and it must not regress.+ """+ gen = PageGenerator(MockProvider(), ContextAssembler(sample_config), sample_config)+ first = await _module_page(gen, structural_key="concept-resolvers", contexts=[_ctx("a.py")])+ prior = {+ first.page_id: PriorPage(+ source_hash=first.source_hash,+ content_hash="", # pre-key row+ model_name=first.model_name,+ content=first.content,+ provider_name=first.provider_name,+ )+ }+ provider = MockProvider()+ reuse_gen = PageGenerator(+ provider, ContextAssembler(sample_config), sample_config, prior_pages=prior+ )+ second = await _module_page(+ reuse_gen, structural_key="concept-resolvers", contexts=[_ctx("a.py")]+ )++ assert provider.call_count == 0+ assert second.metadata.get("reused_from_prior_run") is True+++async def test_a_different_model_never_reuses(sample_config):+ """The model name stays part of the gate: a provider switch (exactly what+ an outage forces) invalidates nothing about the *subject* key, but a+ different model writing the same page is a different page."""+ gen = PageGenerator(MockProvider(), ContextAssembler(sample_config), sample_config)+ first = await _module_page(gen, structural_key="concept-resolvers", contexts=[_ctx("a.py")])+ prior = {+ first.page_id: PriorPage(+ source_hash=first.source_hash,+ content_hash=first.content_hash,+ model_name=first.model_name,+ content=first.content,+ provider_name=first.provider_name,+ )+ }+ other = MockProvider(model="other-model")+ other_gen = PageGenerator(+ other, ContextAssembler(sample_config), sample_config, prior_pages=prior+ )+ page = await _module_page(+ other_gen, structural_key="concept-resolvers", contexts=[_ctx("a.py")]+ )++ assert other.call_count == 1+ assert page.metadata.get("reused_from_prior_run") is None+ assert page.content_hash == first.content_hash # same subject, same key+++async def test_reuse_key_changes_when_the_subject_changes(sample_config):+ """A group whose membership changed is a different page: the key must+ follow the subject, or a re-grouped module would silently keep prose+ written for the old one."""+ gen = PageGenerator(MockProvider(), ContextAssembler(sample_config), sample_config)+ first = await _module_page(gen, structural_key="concept-resolvers", contexts=[_ctx("a.py")])+ prior = {+ first.page_id: PriorPage(+ source_hash=first.source_hash,+ content_hash=first.content_hash,+ model_name=first.model_name,+ content=first.content,+ provider_name=first.provider_name,+ )+ }+ provider = MockProvider()+ regrouped_gen = PageGenerator(+ provider, ContextAssembler(sample_config), sample_config, prior_pages=prior+ )+ # The grouper re-cut the module: same target path, new membership key.+ page = await _module_page(+ regrouped_gen, structural_key="concept-resolvers-v2", contexts=[_ctx("a.py")]+ )++ assert page.content_hash != first.content_hash+ assert provider.call_count == 1+++async def test_a_changed_member_file_regenerates_the_module_page(sample_config):+ """Membership alone is not the subject: an edited member file's bytes+ change the key, so its module page is rewritten rather than reused."""+ gen = PageGenerator(MockProvider(), ContextAssembler(sample_config), sample_config)+ first = await _module_page(+ gen,+ structural_key="concept-resolvers",+ contexts=[_ctx("a.py")],+ members=["a.py"],+ source_map={"a.py": b"def resolve(): return 1"},+ )+ provider = MockProvider()+ edited_gen = PageGenerator(+ provider, ContextAssembler(sample_config), sample_config, prior_pages=_prior_from(first)+ )+ page = await _module_page(+ edited_gen,+ structural_key="concept-resolvers",+ contexts=[_ctx("a.py")],+ members=["a.py"],+ source_map={"a.py": b"def resolve(): return 2"},+ )++ assert page.content_hash != first.content_hash+ assert provider.call_count == 1+ assert page.metadata.get("reused_from_prior_run") is None+++def _system_map(store: str = "core/store.py"):+ return build_system_map(+ {"cli/main.py": "python", "core/engine.py": "python", store: "python"},+ [("cli/main.py", "core/engine.py", "imports"), ("core/engine.py", store, "calls")],+ repo_name="demo",+ manifests=["cli/pyproject.toml", "core/pyproject.toml"],+ entry_points=["cli/main.py"],+ )+++async def _overview(gen, repo_structure, *, system_map, readme: bytes, git_meta_map=None):+ return await gen.generate_repo_overview(+ repo_structure,+ pagerank={},+ sccs=[],+ community={},+ git_meta_map=git_meta_map,+ repo_name="demo",+ system_map=system_map,+ source_map={"README.md": readme},+ )+++def _evidence_config(sample_config):+ return replace(sample_config, source_evidence_files={"repo_overview": ("README.md",)})+++async def test_overview_reuse_follows_its_map_and_evidence(sample_config, sample_repo_structure):+ """The overview reuses across prompt drift alone (git activity moved), and+ regenerates when the system map or a quoted evidence file changes."""+ config = _evidence_config(sample_config)+ gen = PageGenerator(MockProvider(), ContextAssembler(config), config)+ first = await _overview(+ gen, sample_repo_structure, system_map=_system_map(), readme=b"Demo indexes code."+ )+ prior = _prior_from(first)++ def _fresh():+ provider = MockProvider()+ return provider, PageGenerator(+ provider, ContextAssembler(config), config, prior_pages=prior+ )++ provider, drift_gen = _fresh()+ drifted = await _overview(+ drift_gen,+ sample_repo_structure,+ system_map=_system_map(),+ readme=b"Demo indexes code.",+ git_meta_map={"cli/main.py": {"file_path": "cli/main.py", "commit_count_90d": 3}},+ )+ assert drifted.source_hash != first.source_hash+ assert provider.call_count == 0++ provider, readme_gen = _fresh()+ await _overview(+ readme_gen, sample_repo_structure, system_map=_system_map(), readme=b"Demo ships docs."+ )+ assert provider.call_count == 1++ provider, map_gen = _fresh()+ await _overview(+ map_gen,+ sample_repo_structure,+ system_map=_system_map("core/cache.py"),+ readme=b"Demo indexes code.",+ )+ assert provider.call_count == 1diff --git a/tests/unit/generation/test_structural_salt.py b/tests/unit/generation/test_structural_salt.pyindex 97ab99a37..4cea90ca6 100644--- a/tests/unit/generation/test_structural_salt.py+++ b/tests/unit/generation/test_structural_salt.py@@ -170,15 +170,17 @@ def test_only_the_files_whose_bytes_moved_are_stale():def test_the_render_key_is_stored_where_it_survives_a_restart():"""The salt is worthless if it is not persisted.- ``GeneratedPage.content_hash`` looks like the natural home and is not one:- nothing writes it to the database and nothing reads it back, so a key kept- there would be silently absent on the next run and no page would ever look- stale. Metadata round-trips, so the key lives there.+ The structural render key lives in metadata (``render_key``), which+ round-trips through the page row. ``content_hash`` is a real column too,+ but it is the *subject* reuse key (issue #1089) — written by the reuse+ gate and read back by ``load_prior_pages`` — not a home for the render+ salt. A key stored in neither place would be silently absent on the next+ run and no page would ever look stale."""from repowise.core.persistence.models import Page- assert not hasattr(Page, "content_hash")- assert RENDER_KEY == "render_key"+ assert hasattr(Page, "content_hash") # the subject key is persisted now+ assert RENDER_KEY == "render_key" # but the structural salt rides in metadatadef test_a_style_switch_makes_every_page_stale():diff --git a/tests/unit/persistence/test_content_hash_roundtrip.py b/tests/unit/persistence/test_content_hash_roundtrip.pynew file mode 100644index 000000000..ddaa63f73--- /dev/null+++ b/tests/unit/persistence/test_content_hash_roundtrip.py@@ -0,0 +1,160 @@+"""The subject reuse key survives the persistence round-trip (issue #1089).++``content_hash`` is only useful if it is actually written and read back:+``load_prior_pages`` feeds the reuse gate, so a key dropped on write would+silently degrade every later run back to the source-hash gate that re-bills+everything.+"""++from __future__ import annotations++from datetime import UTC, datetime++import pytest+from sqlalchemy import select++from repowise.core.generation.models import GeneratedPage+from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ load_prior_pages,+ upsert_page,+ upsert_repository,+)+from repowise.core.persistence.crud import upsert_pages_from_generated+from repowise.core.persistence.models import Page+++def _generated(page_id: str, *, content_hash: str, provider: str = "mock") -> GeneratedPage:+ now = datetime.now(UTC).isoformat()+ return GeneratedPage(+ page_id=page_id,+ page_type="module_page",+ title=f"Title {page_id}",+ content="# Body",+ source_hash="source-hash",+ content_hash=content_hash,+ model_name="mock-model",+ provider_name=provider,+ input_tokens=10,+ output_tokens=5,+ cached_tokens=0,+ generation_level=4,+ target_path="pkg/resolvers",+ created_at=now,+ updated_at=now,+ )+++async def repo_dir(tmp_path, monkeypatch):+ (tmp_path / ".repowise").mkdir(parents=True, exist_ok=True)+ db = tmp_path / ".repowise" / "wiki.db"+ monkeypatch.setenv("REPOWISE_DB_URL", f"sqlite+aiosqlite:///{db.as_posix()}")+ return tmp_path+++async def test_content_hash_round_trips_through_upsert_and_load(repo_dir):+ """Write via ``upsert_page`` (the single-page path), read via+ ``load_prior_pages`` — the exact pair the generator + resume wrapper use."""+ import os++ engine = create_engine(os.environ["REPOWISE_DB_URL"])+ await init_db(engine)+ sf = create_session_factory(engine)+ try:+ async with get_session(sf) as session:+ repo = await upsert_repository(session, name=repo_dir.name, local_path=str(repo_dir))+ repo_id = repo.id+ await upsert_page(+ session,+ page_id="module_page:pkg/resolvers",+ repository_id=repo_id,+ page_type="module_page",+ title="Resolvers",+ content="# Resolvers\n\nprose",+ summary="",+ target_path="pkg/resolvers",+ source_hash="prompt-hash",+ content_hash="subject-key-123",+ model_name="mock-model",+ provider_name="mock",+ )++ async with get_session(sf) as session:+ prior = await load_prior_pages(session, repo_id)++ entry = prior["module_page:pkg/resolvers"]+ assert entry.content_hash == "subject-key-123"+ assert entry.provider_name == "mock" # the stub-refusal guard's input+ assert entry.model_name == "mock-model"+ assert entry.content == "# Resolvers\n\nprose"+ finally:+ await engine.dispose()+++async def test_content_hash_round_trips_through_batch_upsert(repo_dir):+ """The batch path (``upsert_pages_from_generated``) — what the full+ persistence sweep and ``generate`` both use — keeps the key too."""+ import os++ engine = create_engine(os.environ["REPOWISE_DB_URL"])+ await init_db(engine)+ sf = create_session_factory(engine)+ try:+ async with get_session(sf) as session:+ repo = await upsert_repository(session, name=repo_dir.name, local_path=str(repo_dir))+ repo_id = repo.id+ await upsert_pages_from_generated(+ session, [_generated("module_page:pkg", content_hash="key-batch")], repo_id+ )++ async with get_session(sf) as session:+ row = (+ await session.execute(select(Page).where(Page.id == "module_page:pkg"))+ ).scalar_one()+ assert row.content_hash == "key-batch"++ async with get_session(sf) as session:+ prior = await load_prior_pages(session, repo_id)+ assert prior["module_page:pkg"].content_hash == "key-batch"+ assert prior["module_page:pkg"].provider_name == "mock"+ finally:+ await engine.dispose()+++async def test_legacy_row_without_key_loads_with_empty_content_hash(repo_dir):+ """A store written before this column existed has no key: the gate falls+ back to the prompt hash instead of exploding."""+ import os+++ engine = create_engine(os.environ["REPOWISE_DB_URL"])+ await init_db(engine)+ sf = create_session_factory(engine)+ try:+ async with get_session(sf) as session:+ repo = await upsert_repository(session, name=repo_dir.name, local_path=str(repo_dir))+ # Simulate the pre-migration row: the ORM writes the default, and+ # the schema reconciler back-filled the column with ''.+ await upsert_page(+ session,+ page_id="module_page:old",+ repository_id=repo.id,+ page_type="module_page",+ title="Old",+ content="old prose",+ summary="",+ target_path="old",+ source_hash="h",+ model_name="m",+ provider_name="mock",+ )++ async with get_session(sf) as session:+ prior = await load_prior_pages(session, repo.id)+ assert prior["module_page:old"].content_hash == ""+ finally:+ await engine.dispose()diff --git a/tests/unit/persistence/test_wiki_pages_content_hash_migration.py b/tests/unit/persistence/test_wiki_pages_content_hash_migration.pynew file mode 100644index 000000000..b6e883714--- /dev/null+++ b/tests/unit/persistence/test_wiki_pages_content_hash_migration.py@@ -0,0 +1,54 @@+"""Migration 0120: the ``content_hash`` reuse key on wiki_pages (issue #1089)."""++from __future__ import annotations++import asyncio+import sqlite3+from pathlib import Path+++def _columns(db_path: Path) -> set[str]:+ conn = sqlite3.connect(db_path)+ try:+ return {row[1] for row in conn.execute('PRAGMA table_info("wiki_pages")')}+ finally:+ conn.close()+++def _alembic_config(db_path: Path):+ from alembic.config import Config++ root = Path(__file__).resolve().parents[3] / "packages" / "core"+ config = Config()+ config.set_main_option("script_location", str(root / "alembic"))+ config.set_main_option("sqlalchemy.url", f"sqlite+aiosqlite:///{db_path}")+ return config+++def test_the_migration_adds_and_drops_the_column(tmp_path: Path) -> None:+ from alembic import command++ db_path = tmp_path / "wiki.db"+ config = _alembic_config(db_path)+ command.upgrade(config, "0120")+ assert "content_hash" in _columns(db_path)+ command.downgrade(config, "0119")+ assert "content_hash" not in _columns(db_path)+++def test_the_migration_and_the_model_agree(tmp_path: Path) -> None:+ from alembic import command++ from repowise.core.persistence.database import create_engine, init_db++ migrated = tmp_path / "migrated.db"+ command.upgrade(_alembic_config(migrated), "head")+ declared = tmp_path / "declared.db"++ async def _build() -> None:+ engine = create_engine(f"sqlite+aiosqlite:///{declared}")+ await init_db(engine)+ await engine.dispose()++ asyncio.run(_build())+ assert _columns(migrated) == _columns(declared)diff --git a/tests/unit/pipeline/test_scoped_generation_prior_pages.py b/tests/unit/pipeline/test_scoped_generation_prior_pages.pynew file mode 100644index 000000000..b2d91c044--- /dev/null+++ b/tests/unit/pipeline/test_scoped_generation_prior_pages.py@@ -0,0 +1,174 @@+"""``repowise generate`` feeds prior pages into the reuse gate (issue #1089).++Scope resolution runs over persisted page records, so a page a failed run+left as a stub IS reachable — the stub-fallback change. But unless the+generator is handed the persisted rows, the reuse gate has nothing to+compare against and every refill re-bills even unchanged pages. These tests+pin the wiring: ``execute_scoped_generation`` loads ``prior_pages`` and+passes them to ``run_generation``.+"""++from __future__ import annotations++from datetime import UTC, datetime+from types import SimpleNamespace+from unittest.mock import patch++import pytest+from sqlalchemy.exc import OperationalError++from repowise.core.generation.models import GeneratedPage+from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+)+from repowise.core.pipeline.scoped_generation import (+ ScopedGenerationResult,+ execute_scoped_generation,+)+++def _page(page_id: str) -> GeneratedPage:+ now = datetime.now(UTC).isoformat()+ return GeneratedPage(+ page_id=page_id,+ page_type="module_page",+ title=f"Title {page_id}",+ content="# Body",+ source_hash="h",+ content_hash="key",+ model_name="mock-model",+ provider_name="mock",+ input_tokens=1,+ output_tokens=1,+ cached_tokens=0,+ generation_level=4,+ target_path=page_id,+ created_at=now,+ updated_at=now,+ )+++async def _insert_page(sf, repo_id: str, page: GeneratedPage) -> None:+ from repowise.core.persistence import upsert_pages_from_generated++ async with get_session(sf) as session:+ await upsert_pages_from_generated(session, [page], repo_id)+++async def engine_and_sf(tmp_path, monkeypatch):+ (tmp_path / ".repowise").mkdir(parents=True, exist_ok=True)+ db = tmp_path / ".repowise" / "wiki.db"+ url = f"sqlite+aiosqlite:///{db.as_posix()}"+ monkeypatch.setenv("REPOWISE_DB_URL", url)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)+ yield engine, sf+ await engine.dispose()+++async def _minimal_rehydrated():+ from repowise.core.generation.page_selection import PageRecord+ from repowise.core.pipeline.scoped_generation import RehydratedRepo++ return RehydratedRepo(+ graph_builder=SimpleNamespace(),+ git_meta_map={},+ parsed_files=[],+ source_map={},+ repo_structure=SimpleNamespace(),+ records=[+ PageRecord(+ page_id="module_page:a",+ page_type="module_page",+ target_path="a",+ is_template=True,+ freshness_status="fresh",+ )+ ],+ kg_ctx=SimpleNamespace(available=False),+ deps=SimpleNamespace(),+ repo_name="demo",+ )+++async def test_scoped_generation_passes_prior_pages_to_run_generation(+ engine_and_sf,+):+ """A generate run targeting a stub page still has the persisted rows+ available, so an unchanged sibling is reused instead of re-billed."""+ _engine, sf = engine_and_sf+ async with get_session(sf) as session:+ repo = await upsert_repository(session, name="demo", local_path="/tmp/demo")+ repo_id = repo.id+ await _insert_page(sf, repo_id, _page("module_page:a"))+ plan = SimpleNamespace(generate_ids={"module_page:a"}, stale_ids=set())+ seen: dict = {}++ async def fake_run_generation(*, prior_pages=None, **_kw):+ seen["prior_pages"] = prior_pages+ return [_page("module_page:a")]++ with patch(+ "repowise.core.pipeline.run_generation",+ new=fake_run_generation,+ ):+ await execute_scoped_generation(+ session_factory=sf,+ repo_id=repo_id,+ repo_path="/tmp/demo",+ rehydrated=await _minimal_rehydrated(),+ plan=plan,+ provider=SimpleNamespace(_cost_tracker=None),+ generation_config=SimpleNamespace(),+ concurrency=1,+ )++ prior = seen.get("prior_pages") or {}+ assert "module_page:a" in prior+ entry = prior["module_page:a"]+ assert entry.content_hash == "key" # the subject key survived the round-trip+ assert entry.provider_name == "mock" # a written row, reusable+++async def test_scoped_generation_prior_load_failure_does_not_abort(engine_and_sf):+ """A broken prior-pages load degrades to no-reuse, never a failed run."""+ _engine, sf = engine_and_sf+ async with get_session(sf) as session:+ repo = await upsert_repository(session, name="demo", local_path="/tmp/demo")+ repo_id = repo.id++ plan = SimpleNamespace(generate_ids=set(), stale_ids=set())+ ran = False++ async def fake_run_generation(*, prior_pages=None, **_kw):+ nonlocal ran+ ran = True+ assert prior_pages == {}+ return []++ with patch(+ "repowise.core.pipeline.run_generation",+ new=fake_run_generation,+ ), patch(+ "repowise.core.persistence.load_prior_pages",+ side_effect=OperationalError("SELECT", {}, Exception("db down")),+ ):+ result = await execute_scoped_generation(+ session_factory=sf,+ repo_id=repo_id,+ repo_path="/tmp/demo",+ rehydrated=await _minimal_rehydrated(),+ plan=plan,+ provider=SimpleNamespace(_cost_tracker=None),+ generation_config=SimpleNamespace(),+ concurrency=1,+ )++ assert ran+ assert isinstance(result, ScopedGenerationResult)