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): localize the deterministic structural wiki pages (#1092) (#1102)
Loi Nguyen41fc3884a9b9
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.mdindex edf4ef815..27a57a51e 100644--- a/docs/reference/CONFIG.md+++ b/docs/reference/CONFIG.md@@ -247,8 +247,12 @@ regenerates the wiki). Power users can define their own style underNote: hand-editing `wiki_style` here and running `update` does not regenerateexisting pages, use `restyle`.-`language` controls the natural language of generated wiki content (prose only;-code, file paths, and symbol names stay untranslated). Set it with+`language` controls the natural language of generated wiki content (code, file+paths, and symbol names stay untranslated). It reaches both the model-written+pages and the headings and fixed sentences of the template-rendered ones — file,+symbol, infrastructure, cycle and API-contract pages — for the languages that+have a label catalog. A language without one keeps the English headings on those+pages while the model-written prose is still translated. Set it with`init --language <code>` or pick it in advanced interactive mode; it persistshere so `update` regenerates changed pages in the same language. Unknown codesfall back to English with a warning. As with `wiki_style`, changing it laterdiff --git a/packages/core/src/repowise/core/generation/languages.py b/packages/core/src/repowise/core/generation/languages.pyindex 93e7d11f8..558372954 100644--- a/packages/core/src/repowise/core/generation/languages.py+++ b/packages/core/src/repowise/core/generation/languages.py@@ -26,3 +26,17 @@ SUPPORTED_LANGUAGES = {"ar": "Arabic","hi": "Hindi",}+++def sanitize_language_code(language: str | None) -> str:+ """Return *language* lowered, stripped and reduced to ``[a-z0-9_]``.++ The configured code reaches a system prompt and a label lookup, so it is+ scrubbed before either sees it: without this a config value could inject+ newlines and extra instructions into the prompt. Validation against+ :data:`SUPPORTED_LANGUAGES` is the caller's, because the two callers+ differ on what an unknown code means: the prompt path warns, the label+ path silently falls back to English.+ """+ raw = (language or "en").lower().strip()+ return "".join(ch for ch in raw if ch.isalnum() or ch == "_")diff --git a/packages/core/src/repowise/core/generation/page_generator/core.py b/packages/core/src/repowise/core/generation/page_generator/core.pyindex ad19ed250..a66607c4c 100644--- a/packages/core/src/repowise/core/generation/page_generator/core.py+++ b/packages/core/src/repowise/core/generation/page_generator/core.py@@ -33,6 +33,7 @@ from ..context.evidence import ()from ..context_assembler import ContextAssembler, FilePageContextfrom ..house_vocabulary import cell+from ..languages import sanitize_language_codefrom ..models import (MODEL_PAGE_CONFIDENCE,GeneratedPage,@@ -41,6 +42,7 @@ from ..models import (compute_source_hash,)from ..report import reset_house_terms+from ..structural_labels import resolve_structural_labels, structural_page_titlefrom ..styles import ONBOARDING_PAGE_TYPE, resolve_stylefrom .helpers import _extract_summary, _now_iso, collapse_empty_duplicate_headingsfrom .pertype import PerTypeGenerationMixin@@ -208,6 +210,13 @@ class PageGenerator(PerTypeGenerationMixin, StructuralRenderMixin):# quotes a shell pipeline. Without this every column to the right of# one shifts.self._jinja_env.filters.setdefault("table_cell", cell)+ # Fixed copy for the deterministic templates, in the configured+ # language. A global rather than a per-render kwarg because every+ # structural render path would otherwise have to remember to pass it,+ # and under StrictUndefined the one that forgot would raise. Assigned,+ # not setdefault-ed: an env handed to two generators must end up with+ # the language of the one rendering through it.+ self._jinja_env.globals["labels"] = resolve_structural_labels(self._language)# ------------------------------------------------------------------# generate_all — orchestration (delegates to orchestrate.py)@@ -310,7 +319,7 @@ class PageGenerator(PerTypeGenerationMixin, StructuralRenderMixin):page = self._structural_page(page_type="file_page",target_path=parsed.file_info.path,- title=f"File: {parsed.file_info.path}",+ title=structural_page_title(self._language, "file_page", parsed.file_info.path),template="file_page.j2",subject_hash=parsed.content_hash or "",ctx=ctx,@@ -403,11 +412,10 @@ class PageGenerator(PerTypeGenerationMixin, StructuralRenderMixin):base_system = base_system + self._style.system_prompt_suffix(is_onboarding=page_type == ONBOARDING_PAGE_TYPE)- # Sanitize the configured language code: lower, strip, drop anything that isn't- # alphanumeric or underscore. Prevents user-supplied config from injecting- # newlines or extra instructions into the system prompt.- raw = (self._language or "en").lower().strip()- lang_code = "".join(ch for ch in raw if ch.isalnum() or ch == "_")+ # Sanitized before it reaches the prompt: user-supplied config must not be+ # able to inject newlines or extra instructions here. Shared with the+ # structural-label lookup so both paths agree on what " DE " means.+ lang_code = sanitize_language_code(self._language)if lang_code not in SUPPORTED_LANGUAGES:if lang_code != "en":log.warning("unknown_language_code", code=lang_code, fallback="en")diff --git a/packages/core/src/repowise/core/generation/page_generator/levels.py b/packages/core/src/repowise/core/generation/page_generator/levels.pyindex c3b642864..017334fa4 100644--- a/packages/core/src/repowise/core/generation/page_generator/levels.py+++ b/packages/core/src/repowise/core/generation/page_generator/levels.py@@ -187,7 +187,7 @@ async def build_level2_coros(run: _GenerationRun) -> list[tuple[str, Any]]:return coros-def _scc_titles(scc_groups: list[Any]) -> dict[str, str]:+def _scc_titles(scc_groups: list[Any], language: str | None = None) -> dict[str, str]:"""``scc id -> title``, unique across the run's cycles.Names are computed here rather than per page because uniqueness is a@@ -200,16 +200,18 @@ def _scc_titles(scc_groups: list[Any]) -> dict[str, str]:run gives a cycle the same name a full one does."""from ..concept_tree.naming import disambiguate_titles, scc_where+ from ..structural_labels import resolve_structural_labels+ kind = resolve_structural_labels(language)["circular_dependency"]pairs: list[tuple[str, str]] = []for scc_id, scc_files in scc_groups:where = scc_where(sorted(scc_files))- pairs.append((f"Circular Dependency: {where}" if where else "Circular Dependency", scc_id))+ pairs.append((f"{kind}: {where}" if where else kind, scc_id))# Ties break on the cycle's own id, which is a hash of its members, so the# discriminator is stable for an unchanged cycle.titles = disambiguate_titles(pairs)return {- scc_id: (title if title != "Circular Dependency" else f"Circular Dependency: {scc_id}")+ scc_id: (title if title != kind else f"{kind}: {scc_id}")for title, (_t, scc_id) in zip(titles, pairs, strict=True)}@@ -218,7 +220,7 @@ def build_level3_coros(run: _GenerationRun) -> list[tuple[str, Any]]:"""Level 3 (scc_page), allow-set filtered."""gen = run.gencoros: list[tuple[str, Any]] = []- titles = _scc_titles(list(run.sel_scc_groups))+ titles = _scc_titles(list(run.sel_scc_groups), gen._language)for scc_id, scc_files in run.sel_scc_groups:fc_list = [run.file_page_contexts[f] for f in scc_files if f in run.file_page_contexts]pid = compute_page_id("scc_page", scc_id)diff --git a/packages/core/src/repowise/core/generation/page_generator/pertype.py b/packages/core/src/repowise/core/generation/page_generator/pertype.pyindex e39e741a3..a23e5f36f 100644--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py@@ -35,6 +35,7 @@ from ..overview_tables import (embed_capability_table,embed_package_table,)+from ..structural_labels import structural_page_titlelog = structlog.get_logger(__name__)@@ -178,7 +179,7 @@ class PerTypeGenerationMixin:return self._structural_symbol_spotlight(ctx,target,- f"Symbol: {symbol.qualified_name}",+ structural_page_title(self._language, "symbol_spotlight", symbol.qualified_name),subject_hash=parsed.content_hash or "",)@@ -366,7 +367,7 @@ class PerTypeGenerationMixin:# collision it cannot see is one two identical names would have had.if not title:where = scc_where(members)- title = f"Circular Dependency: {where}" if where else f"Circular Dependency: {scc_id}"+ title = structural_page_title(self._language, "scc_page", where or scc_id)page = self._structural_scc_page(ctx, scc_id, title)page.metadata["file_paths"] = membersreturn page@@ -538,7 +539,9 @@ class PerTypeGenerationMixin:) -> GeneratedPage:ctx = self._assembler.assemble_api_contract(parsed, source_bytes)return self._structural_api_contract(- ctx, parsed.file_info.path, f"API Contract: {parsed.file_info.path}"+ ctx,+ parsed.file_info.path,+ structural_page_title(self._language, "api_contract", parsed.file_info.path),)async def generate_onboarding_page(@@ -665,5 +668,7 @@ class PerTypeGenerationMixin:) -> GeneratedPage:ctx = self._assembler.assemble_infra_page(parsed, source_bytes)return self._structural_infra_page(- ctx, parsed.file_info.path, f"Infrastructure: {parsed.file_info.path}"+ ctx,+ parsed.file_info.path,+ structural_page_title(self._language, "infra_page", parsed.file_info.path),)diff --git a/packages/core/src/repowise/core/generation/structural_labels.py b/packages/core/src/repowise/core/generation/structural_labels.pynew file mode 100644index 000000000..11985a7cd--- /dev/null+++ b/packages/core/src/repowise/core/generation/structural_labels.py@@ -0,0 +1,303 @@+"""Localized fixed text for the deterministic structural wiki pages.++Structural pages are rendered from a Jinja template with no model in the+loop, so the ``language`` setting — which reaches the model-written pages as a+system-prompt instruction — never reached them at all (#1092). This module is+where their fixed copy lives instead.++Two rules make the fallback safe under ``StrictUndefined``:++* :data:`ENGLISH_LABELS` is the complete catalog. Every key a template reads+ is defined here, so a language with no entry of its own renders exactly what+ it renders today rather than a partial mix or a lookup error.+* A localized catalog is *overlaid* on the English one, never substituted for+ it, so a language that translates half the keys still renders the other half+ in English rather than blowing up.++Sentences that vary by more than a heading are stored whole with ``{}``+placeholders and interpolated with ``str.format`` in the template, so a+translation can move the parts around; assembling them from fragments would+pin every language to English word order. ``format`` ignores placeholders a+translation does not use, which is what lets German drop the English+article in ``symbol_overview``.++Code, file paths, symbol names and language names stay untranslated, matching+what the system prompt already tells the model to do.+"""++from __future__ import annotations++from .languages import sanitize_language_code++ENGLISH_LABELS: dict[str, str] = {+ # -- shared ------------------------------------------------------------+ "overview": "Overview",+ "source": "Source",+ "footer": (+ "*Built from the code itself: parsed symbols, the import graph, git history and\n"+ "the knowledge graph. Every statement here is checked against the source rather\n"+ "than written about it.*"+ ),+ "and_more": "and {count} more.",+ "file": "File",+ "file_singular": "file",+ "file_plural": "files",+ "symbol": "Symbol",+ "kind": "Kind",+ "signature": "Signature",+ "questions_heading": "Questions this page answers",+ # -- file page ---------------------------------------------------------+ # The overview sentence is assembled from fragments rather than stored+ # whole: four independent optional clauses would need sixteen variants as+ # one string. A translation that needs a different order pays for it here.+ "is_a": "is a",+ "entry_point": "entry-point",+ "test": "test",+ "source_file": "source file",+ "in_layer": "in the {layer} layer",+ "part_of_module_cluster_intro": "part of the {community} module cluster",+ "exposes_symbols": "It exposes {symbol_count} {symbol_word}.",+ "exposes_symbols_and_depends": (+ "It exposes {symbol_count} {symbol_word} and depends on {file_count} {file_word}."+ ),+ "public_symbol_singular": "public symbol",+ "public_symbol_plural": "public symbols",+ "other_file_singular": "other file",+ "other_file_plural": "other files",+ "public_api": "Public API",+ "depends_on": "Depends on",+ "used_by": "Used by",+ "imported_by_files": "Imported by {count} {file_word} in this repository.",+ "usage_notes": "Usage Notes",+ "part_of_module_cluster": "Part of the **{community}** module cluster.",+ "layer": "Layer",+ "role": "Role",+ "in_the_code": "In the code",+ "question_exports": "What does `{path}` export?",+ "question_where_defined": "Where is `{symbol}` defined?",+ "question_what_imports": "What imports `{path}`?",+ "question_depends_on": "What does `{path}` depend on?",+ # -- symbol spotlight --------------------------------------------------+ "defined_in": "Defined in",+ "async_marker": "async",+ "estimated_complexity": "Estimated complexity",+ "symbol_overview": (+ "`{symbol}` is {article} {kind} defined in `{path}`. It carries no docstring."+ ),+ "article_a": "a",+ "article_an": "an",+ "symbol_kind_fallback": "symbol",+ "decorators": "Decorators",+ "where_used": "Where it is used",+ "importers_summary": (+ "{count} {file_word} {import_verb} the module that defines it. "+ "These are import-level references, not confirmed call sites."+ ),+ "import_verb_singular": "imports",+ "import_verb_plural": "import",+ "implementation": "Implementation",+ "question_what_is": "What is `{symbol}`?",+ "question_which_files_import": ("Which files import the module that defines `{symbol}`?"),+ # -- infrastructure page -----------------------------------------------+ "infrastructure": "Infrastructure",+ "type": "Type",+ "declared_targets": "Declared targets",+ "infra_overview_intro": "`{path}` is an infrastructure file ({language}).",+ "infra_targets_sentence": "It declares {count} {target_word}, listed below.",+ "infra_overview_outro": (+ "Its behaviour is not derivable from structure, so the source is reproduced in full."+ ),+ "target_singular": "named target",+ "target_plural": "named targets",+ # -- API contract page -------------------------------------------------+ "api_contract": "API Contract",+ "language": "Language",+ "operations": "Operations",+ "types": "Types",+ "api_contract_overview": (+ "`{path}` was classified as an API surface. It declares {endpoint_count} "+ "{endpoint_word} and {schema_count} {schema_word}. The list below is taken from "+ "the parsed symbols, so it reflects what the file *declares*; request and "+ "response semantics are not derivable from structure alone."+ ),+ "callable_singular": "callable",+ "callable_plural": "callables",+ "type_singular": "type",+ "type_plural": "types",+ # -- circular-dependency page ------------------------------------------+ "circular_dependency": "Circular Dependency",+ "cycle_overview": (+ "{count} files import each other in a loop, directly or transitively. Nothing in "+ "this group can be loaded, tested or extracted without the rest of it."+ ),+ "cycle_id": "Cycle id",+ "files_in_cycle": "Files in the cycle",+ "and_more_edges": "and {count} more edges.",+ "the_loop": "The loop",+ "where_to_break": "Where to break it",+ "decouple_ranking_description": (+ "Ranked by how many of the cycle's edges each file carries. The file at the top is "+ "the most entangled, so it is usually where an extracted interface or a moved "+ "import buys the most."+ ),+ "imports_in_cycle": "Imports in cycle",+ "imported_by": "Imported by",+ "total": "Total",+ "symbols_defined_in_cycle": "Symbols defined in the cycle",+ "remaining_symbols": ("Symbols for the remaining {count} files are on their own file pages."),+ "total_symbols_in_cycle": "Total symbols in cycle",+}+++# code → partial overlay on ENGLISH_LABELS. A code absent here, and any key a+# present code omits, renders English.+LOCALIZED_LABELS: dict[str, dict[str, str]] = {+ "de": {+ "overview": "Überblick",+ "source": "Quelltext",+ "footer": (+ "*Aus dem Code selbst erstellt: geparste Symbole, der Importgraph, die "+ "Git-Historie\nund der Wissensgraph. Jede Aussage hier wird gegen den "+ "Quelltext geprüft, statt\nnur darüber geschrieben zu werden.*"+ ),+ "and_more": "und {count} weitere.",+ "file": "Datei",+ "file_singular": "Datei",+ "file_plural": "Dateien",+ "symbol": "Symbol",+ "kind": "Art",+ "signature": "Signatur",+ "questions_heading": "Fragen, die diese Seite beantwortet",+ "is_a": "ist eine",+ "entry_point": "Einstiegspunkt",+ "test": "Test",+ "source_file": "Quelldatei",+ "in_layer": "in der Schicht {layer}",+ "part_of_module_cluster_intro": "Teil des Modulclusters {community}",+ "exposes_symbols": "Sie stellt {symbol_count} {symbol_word} bereit.",+ "exposes_symbols_and_depends": (+ "Sie stellt {symbol_count} {symbol_word} bereit und hängt von {file_count} "+ "{file_word} ab."+ ),+ "public_symbol_singular": "öffentliches Symbol",+ "public_symbol_plural": "öffentliche Symbole",+ "other_file_singular": "weiteren Datei",+ "other_file_plural": "weiteren Dateien",+ "public_api": "Öffentliche API",+ "depends_on": "Abhängigkeiten",+ "used_by": "Wird verwendet von",+ "imported_by_files": "Importiert von {count} {file_word} in diesem Repository.",+ "usage_notes": "Nutzungshinweise",+ "part_of_module_cluster": "Teil des Modulclusters **{community}**.",+ "layer": "Schicht",+ "role": "Rolle",+ "in_the_code": "Im Code",+ "question_exports": "Was exportiert `{path}`?",+ "question_where_defined": "Wo ist `{symbol}` definiert?",+ "question_what_imports": "Was importiert `{path}`?",+ "question_depends_on": "Wovon hängt `{path}` ab?",+ "defined_in": "Definiert in",+ "async_marker": "asynchron",+ "estimated_complexity": "Geschätzte Komplexität",+ # No {article}: German article agreement does not follow the English+ # vowel rule, and ``str.format`` drops the placeholder we do not use.+ "symbol_overview": (+ "`{symbol}` ist ein {kind}, definiert in `{path}`. Es enthält keinen Docstring."+ ),+ "symbol_kind_fallback": "Symbol",+ "decorators": "Dekoratoren",+ "where_used": "Wo es verwendet wird",+ "importers_summary": (+ "{count} {file_word} {import_verb} das Modul, das es definiert. "+ "Dies sind Referenzen auf Importebene, keine bestätigten Aufrufstellen."+ ),+ "import_verb_singular": "importiert",+ "import_verb_plural": "importieren",+ "implementation": "Implementierung",+ "question_what_is": "Was ist `{symbol}`?",+ "question_which_files_import": (+ "Welche Dateien importieren das Modul, das `{symbol}` definiert?"+ ),+ "infrastructure": "Infrastruktur",+ "type": "Typ",+ "declared_targets": "Deklarierte Ziele",+ "infra_overview_intro": "`{path}` ist eine Infrastrukturdatei ({language}).",+ "infra_targets_sentence": "Sie deklariert {count} {target_word}, unten aufgeführt.",+ "infra_overview_outro": (+ "Ihr Verhalten lässt sich nicht aus der Struktur ableiten, daher wird der "+ "Quelltext vollständig wiedergegeben."+ ),+ "target_singular": "benanntes Ziel",+ "target_plural": "benannte Ziele",+ "api_contract": "API-Vertrag",+ "language": "Sprache",+ "operations": "Operationen",+ "types": "Typen",+ "api_contract_overview": (+ "`{path}` wurde als API-Oberfläche eingestuft. Sie deklariert {endpoint_count} "+ "{endpoint_word} und {schema_count} {schema_word}. Die folgende Liste stammt "+ "aus den geparsten Symbolen und zeigt daher, was die Datei *deklariert*; "+ "Anfrage- und Antwortsemantik lassen sich nicht allein aus der Struktur "+ "ableiten."+ ),+ "callable_singular": "aufrufbare Operation",+ "callable_plural": "aufrufbare Operationen",+ "type_singular": "Typ",+ "type_plural": "Typen",+ "circular_dependency": "Zyklische Abhängigkeit",+ "cycle_overview": (+ "{count} Dateien importieren einander direkt oder transitiv in einer Schleife. "+ "Nichts in dieser Gruppe kann ohne den Rest geladen, getestet oder extrahiert "+ "werden."+ ),+ "cycle_id": "Zyklus-ID",+ "files_in_cycle": "Dateien im Zyklus",+ "and_more_edges": "und {count} weitere Kanten.",+ "the_loop": "Die Schleife",+ "where_to_break": "Wo sie aufgebrochen werden kann",+ "decouple_ranking_description": (+ "Sortiert danach, wie viele Kanten des Zyklus jede Datei trägt. Die oberste "+ "Datei ist am stärksten verflochten; dort bringt eine extrahierte Schnittstelle "+ "oder ein verschobener Import gewöhnlich am meisten."+ ),+ "imports_in_cycle": "Importe im Zyklus",+ "imported_by": "Importiert von",+ "total": "Gesamt",+ "symbols_defined_in_cycle": "Im Zyklus definierte Symbole",+ "remaining_symbols": (+ "Symbole der verbleibenden {count} Dateien stehen auf ihren eigenen Dateiseiten."+ ),+ "total_symbols_in_cycle": "Symbole insgesamt im Zyklus",+ },+}+++# page_type → the catalog key naming that page type. The page heading and the+# stored page title come from the same entry, so a wiki cannot show a German+# heading under an English title.+_TITLE_LABEL_KEYS: dict[str, str] = {+ "file_page": "file",+ "symbol_spotlight": "symbol",+ "scc_page": "circular_dependency",+ "api_contract": "api_contract",+ "infra_page": "infrastructure",+}+++def resolve_structural_labels(language: str | None) -> dict[str, str]:+ """Return the complete label catalog for *language*.++ English for an absent, malformed or unsupported code, and English for any+ individual key a supported language has not translated.+ """+ labels = ENGLISH_LABELS.copy()+ labels.update(LOCALIZED_LABELS.get(sanitize_language_code(language), {}))+ return labels+++def structural_page_title(language: str | None, page_type: str, target: str) -> str:+ """Return the stored page title for a deterministic structural page.++ *target* is a path or a qualified symbol name and is never translated.+ """+ return f"{resolve_structural_labels(language)[_TITLE_LABEL_KEYS[page_type]]}: {target}"diff --git a/packages/core/src/repowise/core/generation/templates/_footer.j2 b/packages/core/src/repowise/core/generation/templates/_footer.j2index 64d204586..b14bc3e22 100644--- a/packages/core/src/repowise/core/generation/templates/_footer.j2+++ b/packages/core/src/repowise/core/generation/templates/_footer.j2@@ -1,5 +1,3 @@----*Built from the code itself: parsed symbols, the import graph, git history and-the knowledge graph. Every statement here is checked against the source rather-than written about it.*+{{ labels.footer }}diff --git a/packages/core/src/repowise/core/generation/templates/api_contract.j2 b/packages/core/src/repowise/core/generation/templates/api_contract.j2index 7a83de17c..f6485d511 100644--- a/packages/core/src/repowise/core/generation/templates/api_contract.j2+++ b/packages/core/src/repowise/core/generation/templates/api_contract.j2@@ -6,30 +6,30 @@accept, return or do. Listing the shapes and the source is the most thispage can truthfully offer until a model rewrites it.-#}-# API Contract: {{ ctx.file_path }}+# {{ labels.api_contract }}: {{ ctx.file_path }}-**Language:** {{ ctx.language }} | **Operations:** {{ ctx.endpoints | length }} | **Types:** {{ ctx.schemas | length }}+**{{ labels.language }}:** {{ ctx.language }} | **{{ labels.operations }}:** {{ ctx.endpoints | length }} | **{{ labels.types }}:** {{ ctx.schemas | length }}-## Overview+## {{ labels.overview }}-`{{ ctx.file_path }}` was classified as an API surface. It declares {{ ctx.endpoints | length }} callable{{ "s" if ctx.endpoints | length != 1 else "" }} and {{ ctx.schemas | length }} type{{ "s" if ctx.schemas | length != 1 else "" }}. The list below is taken from the parsed symbols, so it reflects what the file *declares*; request and response semantics are not derivable from structure alone.+{{ labels.api_contract_overview.format(path=ctx.file_path, endpoint_count=ctx.endpoints | length, endpoint_word=labels.callable_plural if ctx.endpoints | length != 1 else labels.callable_singular, schema_count=ctx.schemas | length, schema_word=labels.type_plural if ctx.schemas | length != 1 else labels.type_singular) }}{% if ctx.endpoints %}-## Operations+## {{ labels.operations }}{% for e in ctx.endpoints %}- `{{ e | oneline(160) }}`{% endfor %}{% endif %}{% if ctx.schemas %}-## Types+## {{ labels.types }}{% for s in ctx.schemas %}- `{{ s }}`{% endfor %}{% endif %}{% if ctx.raw_content %}-## Source+## {{ labels.source }}```{{ ctx.language }}{{ ctx.raw_content }}diff --git a/packages/core/src/repowise/core/generation/templates/file_page.j2 b/packages/core/src/repowise/core/generation/templates/file_page.j2index a1d245d77..667609fea 100644--- a/packages/core/src/repowise/core/generation/templates/file_page.j2+++ b/packages/core/src/repowise/core/generation/templates/file_page.j2@@ -21,16 +21,17 @@{%- set public_syms = ctx.symbols | selectattr("visibility", "equalto", "public") | list -%}# {{ ctx.file_path }}-## Overview+## {{ labels.overview }}-{% if ctx.docstring %}{{ ctx.docstring | as_markdown }}{% else %}`{{ ctx.file_path }}` is a {{ ctx.language }} {% if ctx.is_entry_point %}entry-point {% endif %}{% if ctx.is_test %}test {% endif %}source file{% if ctx.kg_layer_name %} in the {{ ctx.kg_layer_name }} layer{% endif %}{% if ctx.community_label %}, part of the {{ ctx.community_label }} module cluster{% endif %}.{% endif %}+{% if ctx.docstring %}{{ ctx.docstring | as_markdown }}{% else %}`{{ ctx.file_path }}` {{ labels.is_a }} {{ ctx.language }} {% if ctx.is_entry_point %}{{ labels.entry_point }} {% endif %}{% if ctx.is_test %}{{ labels.test }} {% endif %}{{ labels.source_file }}{% if ctx.kg_layer_name %} {{ labels.in_layer.format(layer=ctx.kg_layer_name) }}{% endif %}{% if ctx.community_label %}, {{ labels.part_of_module_cluster_intro.format(community=ctx.community_label) }}{% endif %}.{% endif %}{%- if public_syms %}+{%- set symbol_word = labels.public_symbol_plural if public_syms | length != 1 else labels.public_symbol_singular %}-It exposes {{ public_syms | length }} public symbol{{ "s" if public_syms | length != 1 else "" }}{% if ctx.dependencies %} and depends on {{ ctx.dependencies | length }} other file{{ "s" if ctx.dependencies | length != 1 else "" }}{% endif %}.+{% if ctx.dependencies %}{{ labels.exposes_symbols_and_depends.format(symbol_count=public_syms | length, symbol_word=symbol_word, file_count=ctx.dependencies | length, file_word=labels.other_file_plural if ctx.dependencies | length != 1 else labels.other_file_singular) }}{% else %}{{ labels.exposes_symbols.format(symbol_count=public_syms | length, symbol_word=symbol_word) }}{% endif %}-## Public API+## {{ labels.public_api }}-| Symbol | Kind | Signature |+| {{ labels.symbol }} | {{ labels.kind }} | {{ labels.signature }} || --- | --- | --- |{%- for s in public_syms %}| `{{ s.name }}` | {{ s.kind }} | {{ (s.signature or "") | signature | replace("|", "\\|") }} |@@ -38,36 +39,36 @@ It exposes {{ public_syms | length }} public symbol{{ "s" if public_syms | lengt{%- endif %}{%- if ctx.dependencies %}-## Depends on+## {{ labels.depends_on }}{% for dep in ctx.dependencies[:25] %}- `{{ dep }}`{%- endfor %}{%- if ctx.dependencies | length > 25 %}-_and {{ ctx.dependencies | length - 25 }} more._+_{{ labels.and_more.format(count=ctx.dependencies | length - 25) }}_{%- endif %}{%- endif %}{%- if ctx.dependents %}-## Used by+## {{ labels.used_by }}-Imported by {{ ctx.dependents | length }} file{{ "s" if ctx.dependents | length != 1 else "" }} in this repository.+{{ labels.imported_by_files.format(count=ctx.dependents | length, file_word=labels.file_plural if ctx.dependents | length != 1 else labels.file_singular) }}{% for dep in ctx.dependents[:25] %}- `{{ dep }}`{%- endfor %}{%- if ctx.dependents | length > 25 %}-_and {{ ctx.dependents | length - 25 }} more._+_{{ labels.and_more.format(count=ctx.dependents | length - 25) }}_{%- endif %}{%- endif %}{%- if ctx.community_label or ctx.kg_layer_name %}-## Usage Notes+## {{ labels.usage_notes }}{% if ctx.community_label %}-Part of the **{{ ctx.community_label }}** module cluster.+{{ labels.part_of_module_cluster.format(community=ctx.community_label) }}{%- endif %}{%- if ctx.kg_layer_name %}-**Layer:** {{ ctx.kg_layer_name }}{% if ctx.kg_layer_role %} | **Role:** {{ ctx.kg_layer_role }}{% endif %}+**{{ labels.layer }}:** {{ ctx.kg_layer_name }}{% if ctx.kg_layer_role %} | **{{ labels.role }}:** {{ ctx.kg_layer_role }}{% endif %}{%- endif %}{%- endif %}{#- Question-shaped text, built from structure rather than prose.@@ -89,18 +90,18 @@ Part of the **{{ ctx.community_label }}** module cluster.-#}{%- set questions = [] -%}{%- if public_syms -%}-{%- set _ = questions.append("What does `" ~ ctx.file_path ~ "` export?") -%}-{%- set _ = questions.append("Where is `" ~ public_syms[0].name ~ "` defined?") -%}+{%- set _ = questions.append(labels.question_exports.format(path=ctx.file_path)) -%}+{%- set _ = questions.append(labels.question_where_defined.format(symbol=public_syms[0].name)) -%}{%- endif -%}{%- if ctx.dependents -%}-{%- set _ = questions.append("What imports `" ~ ctx.file_path ~ "`?") -%}+{%- set _ = questions.append(labels.question_what_imports.format(path=ctx.file_path)) -%}{%- endif -%}{%- if ctx.dependencies -%}-{%- set _ = questions.append("What does `" ~ ctx.file_path ~ "` depend on?") -%}+{%- set _ = questions.append(labels.question_depends_on.format(path=ctx.file_path)) -%}{%- endif -%}{%- if questions %}-## Questions this page answers+## {{ labels.questions_heading }}{% for q in questions[:3] %}- {{ q }}{%- endfor %}@@ -125,7 +126,7 @@ Part of the **{{ ctx.community_label }}** module cluster.-#}{%- if ctx.file_vocabulary %}-## In the code+## {{ labels.in_the_code }}{{ ctx.file_vocabulary }}{%- endif %}diff --git a/packages/core/src/repowise/core/generation/templates/infra_page.j2 b/packages/core/src/repowise/core/generation/templates/infra_page.j2index 1f6d85a24..ff8d5bd28 100644--- a/packages/core/src/repowise/core/generation/templates/infra_page.j2+++ b/packages/core/src/repowise/core/generation/templates/infra_page.j2@@ -6,23 +6,23 @@per-format extraction or a model, and this path has neither. So the pageis explicitly a source view rather than an explanation.-#}-# Infrastructure: {{ ctx.file_path }}+# {{ labels.infrastructure }}: {{ ctx.file_path }}-**Type:** {{ ctx.language }}{% if ctx.targets %} | **Declared targets:** {{ ctx.targets | length }}{% endif %}+**{{ labels.type }}:** {{ ctx.language }}{% if ctx.targets %} | **{{ labels.declared_targets }}:** {{ ctx.targets | length }}{% endif %}-## Overview+## {{ labels.overview }}-`{{ ctx.file_path }}` is an infrastructure file ({{ ctx.language }}).{% if ctx.targets %} It declares {{ ctx.targets | length }} named target{{ "s" if ctx.targets | length != 1 else "" }}, listed below.{% endif %} Its behaviour is not derivable from structure, so the source is reproduced in full.+{{ labels.infra_overview_intro.format(path=ctx.file_path, language=ctx.language) }}{% if ctx.targets %} {{ labels.infra_targets_sentence.format(count=ctx.targets | length, target_word=labels.target_plural if ctx.targets | length != 1 else labels.target_singular) }}{% endif %} {{ labels.infra_overview_outro }}{% if ctx.targets %}-## Declared targets+## {{ labels.declared_targets }}{% for t in ctx.targets %}- `{{ t }}`{% endfor %}{% endif %}{% if ctx.raw_content %}-## Source+## {{ labels.source }}```{{ ctx.language }}{{ ctx.raw_content }}diff --git a/packages/core/src/repowise/core/generation/templates/scc_page.j2 b/packages/core/src/repowise/core/generation/templates/scc_page.j2index 3caeb1edb..c49663909 100644--- a/packages/core/src/repowise/core/generation/templates/scc_page.j2+++ b/packages/core/src/repowise/core/generation/templates/scc_page.j2@@ -8,17 +8,17 @@{#- ``default(..., true)`` so an absent *or* empty title both fall back: thecaller names the whole set at once and a caller that does not is stillentitled to a page. #}-# {{ page_title | default("Circular Dependency: " ~ ctx.scc_id, true) }}+# {{ page_title | default(labels.circular_dependency ~ ": " ~ ctx.scc_id, true) }}-{{ ctx.files | length }} files import each other in a loop, directly or transitively. Nothing in this group can be loaded, tested or extracted without the rest of it.+{{ labels.cycle_overview.format(count=ctx.files | length) }}{#- The id is no longer in the heading, and it is what logs, links and thedependency tooling call this cycle, so it is stated once rather than beingfindable only in the URL. #}-**Cycle id:** `{{ ctx.scc_id }}`+**{{ labels.cycle_id }}:** `{{ ctx.scc_id }}`-## Files in the cycle+## {{ labels.files_in_cycle }}{# Capped, here and in the two listings below: a test-suite cycle routedthrough a shared conftest can run to 80+ files and 200+ edges, and a pagethat dumps all of them is 50KB of noise. The decouple ranking is the part@@ -27,25 +27,25 @@- `{{ f }}`{% endfor %}{%- if ctx.files | length > 30 %}-- ...and {{ ctx.files | length - 30 }} more.+- ...{{ labels.and_more.format(count=ctx.files | length - 30) }}{% endif %}{% if ctx.cross_imports %}-## The loop+## {{ labels.the_loop }}{% for edge in ctx.cross_imports[:40] %}- `{{ edge.from }}` → `{{ edge.to }}`{% endfor %}{%- if ctx.cross_imports | length > 40 %}-- ...and {{ ctx.cross_imports | length - 40 }} more edges.+- ...{{ labels.and_more_edges.format(count=ctx.cross_imports | length - 40) }}{% endif %}{% endif %}{% if decouple_ranking %}-## Where to break it+## {{ labels.where_to_break }}-Ranked by how many of the cycle's edges each file carries. The file at the top is the most entangled, so it is usually where an extracted interface or a moved import buys the most.+{{ labels.decouple_ranking_description }}-| File | Imports in cycle | Imported by | Total |+| {{ labels.file }} | {{ labels.imports_in_cycle }} | {{ labels.imported_by }} | {{ labels.total }} || --- | --- | --- | --- |{% for r in decouple_ranking -%}| `{{ r.path }}` | {{ r.out }} | {{ r["in"] }} | {{ r.total }} |@@ -53,7 +53,7 @@ Ranked by how many of the cycle's edges each file carries. The file at the top i{% endif %}{% if ctx.member_symbols %}-## Symbols defined in the cycle+## {{ labels.symbols_defined_in_cycle }}{% for m in ctx.member_symbols[:20] %}### `{{ m.file_path }}`{% for s in m.symbols[:15] %}@@ -61,9 +61,9 @@ Ranked by how many of the cycle's edges each file carries. The file at the top i{% endfor %}{% endfor %}{% if ctx.member_symbols | length > 20 %}-*Symbols for the remaining {{ ctx.member_symbols | length - 20 }} files are on their own file pages.*+*{{ labels.remaining_symbols.format(count=ctx.member_symbols | length - 20) }}*{% endif %}{% endif %}-**Total symbols in cycle:** {{ ctx.total_symbols }}+**{{ labels.total_symbols_in_cycle }}:** {{ ctx.total_symbols }}{% include "_footer.j2" %}diff --git a/packages/core/src/repowise/core/generation/templates/symbol_spotlight.j2 b/packages/core/src/repowise/core/generation/templates/symbol_spotlight.j2index 5ac5446ba..e3d3d1053 100644--- a/packages/core/src/repowise/core/generation/templates/symbol_spotlight.j2+++ b/packages/core/src/repowise/core/generation/templates/symbol_spotlight.j2@@ -17,7 +17,7 @@-#}# {{ ctx.qualified_name }}-**Kind:** {{ ctx.kind }}{% if ctx.is_async %} (async){% endif %} | **Defined in:** `{{ ctx.file_path }}`{% if ctx.complexity_estimate %} | **Estimated complexity:** {{ ctx.complexity_estimate }}{% endif %}+**{{ labels.kind }}:** {{ ctx.kind }}{% if ctx.is_async %} ({{ labels.async_marker }}){% endif %} | **{{ labels.defined_in }}:** `{{ ctx.file_path }}`{% if ctx.complexity_estimate %} | **{{ labels.estimated_complexity }}:** {{ ctx.complexity_estimate }}{% endif %}{%- if ctx.signature %}```@@ -25,28 +25,28 @@```{%- endif %}-## Overview+## {{ labels.overview }}-{% if ctx.docstring %}{{ ctx.docstring | as_markdown }}{% else %}`{{ ctx.symbol_name }}` is {{ "an" if ctx.kind and ctx.kind[0] in "aeiou" else "a" }} {{ ctx.kind or "symbol" }} defined in `{{ ctx.file_path }}`. It carries no docstring.{% endif %}+{% if ctx.docstring %}{{ ctx.docstring | as_markdown }}{% else %}{{ labels.symbol_overview.format(symbol=ctx.symbol_name, article=labels.article_an if ctx.kind and ctx.kind[0] in "aeiou" else labels.article_a, kind=ctx.kind or labels.symbol_kind_fallback, path=ctx.file_path) }}{% endif %}{%- if ctx.decorators %}-## Decorators+## {{ labels.decorators }}{% for d in ctx.decorators %}- `{{ d }}`{%- endfor %}{%- endif %}{%- if ctx.callers %}-## Where it is used+## {{ labels.where_used }}-{{ ctx.callers | length }} file{{ "s" if ctx.callers | length != 1 else "" }} import{{ "" if ctx.callers | length != 1 else "s" }} the module that defines it. These are import-level references, not confirmed call sites.+{{ labels.importers_summary.format(count=ctx.callers | length, file_word=labels.file_plural if ctx.callers | length != 1 else labels.file_singular, import_verb=labels.import_verb_plural if ctx.callers | length != 1 else labels.import_verb_singular) }}{% for c in ctx.callers %}- `{{ c }}`{%- endfor %}{%- endif %}{%- if ctx.source_body %}-## Implementation+## {{ labels.implementation }}```{{ ctx.source_body }}@@ -63,12 +63,12 @@importers — fewer than the file page, and honest rather than padded.#}-## Questions this page answers+## {{ labels.questions_heading }}-- Where is `{{ ctx.symbol_name }}` defined?-- What is `{{ ctx.qualified_name }}`?+- {{ labels.question_where_defined.format(symbol=ctx.symbol_name) }}+- {{ labels.question_what_is.format(symbol=ctx.qualified_name) }}{%- if ctx.callers %}-- Which files import the module that defines `{{ ctx.symbol_name }}`?+- {{ labels.question_which_files_import.format(symbol=ctx.symbol_name) }}{%- endif %}{% include "_footer.j2" %}diff --git a/tests/unit/generation/test_deterministic_templates.py b/tests/unit/generation/test_deterministic_templates.pyindex dc33e44c6..b19d796df 100644--- a/tests/unit/generation/test_deterministic_templates.py+++ b/tests/unit/generation/test_deterministic_templates.py@@ -11,7 +11,14 @@ from __future__ import annotationsimport pytest-from repowise.core.generation.context_assembler import ApiContractContext, ContextAssembler+from repowise.core.generation.context_assembler import (+ ApiContractContext,+ ContextAssembler,+ FilePageContext,+ InfraPageContext,+ SccPageContext,+ SymbolSpotlightContext,+)from repowise.core.generation.models import GenerationConfigfrom repowise.core.generation.onboarding.subkinds.active_landscape import (ActiveLandscapeContext,@@ -23,6 +30,7 @@ from repowise.core.generation.onboarding.subkinds.getting_started import (ReadmeSection,)from repowise.core.generation.page_generator import PageGenerator+from repowise.core.generation.structural_labels import structural_page_titlefrom repowise.core.providers.llm.template import TemplateProvider@@ -32,6 +40,19 @@ def generator() -> PageGenerator:return PageGenerator(TemplateProvider(), ContextAssembler(config), config)+def german_generator() -> PageGenerator:+ config = GenerationConfig(deterministic=True, language="de")+ return PageGenerator(TemplateProvider(), ContextAssembler(config), config)+++def klingon_generator() -> PageGenerator:+ """A configured language with no label catalog of its own."""+ config = GenerationConfig(deterministic=True, language="tlh")+ return PageGenerator(TemplateProvider(), ContextAssembler(config), config)++def _onboarding_spec(slot: str, template: str):from repowise.core.generation.onboarding.registry import SubkindSpec@@ -357,3 +378,205 @@ def test_module_page_of_root_files_says_so(generator):assert "Repository root" in page.contentassert "`.`" not in page.content+++# ---------------------------------------------------------------------------+# Localization (#1092). These pages are rendered from a template with no model+# in the loop, so the ``language`` setting reaches them through the label+# catalog or not at all.+# ---------------------------------------------------------------------------+++def _file_ctx() -> FilePageContext:+ return FilePageContext(+ file_path="src/service/parser.py",+ language="python",+ docstring=None,+ symbols=[+ {+ "name": "parse_file",+ "kind": "function",+ "visibility": "public",+ "signature": "def parse_file(p: str) -> Parsed",+ }+ ],+ imports=[],+ exports=[],+ pagerank_score=0.0,+ betweenness_score=0.0,+ community_id=0,+ dependents=["src/pipeline.py"],+ dependencies=["src/models.py"],+ is_api_contract=False,+ is_entry_point=True,+ is_test=False,+ parse_errors=[],+ estimated_tokens=0,+ community_label="parsing",+ kg_layer_name="ingestion",+ kg_layer_role="parses source",+ file_vocabulary="tokenizer visitor",+ )+++def _symbol_ctx() -> SymbolSpotlightContext:+ return SymbolSpotlightContext(+ symbol_name="parse_file",+ qualified_name="parser.ASTParser.parse_file",+ kind="method",+ signature="def parse_file(self, fi, src) -> ParsedFile",+ docstring=None,+ file_path="src/parser.py",+ decorators=["@lru_cache"],+ is_async=True,+ complexity_estimate=7,+ callers=["src/pipeline.py"],+ source_body="def parse_file(self):\n return ...",+ )+++def _scc_ctx() -> SccPageContext:+ return SccPageContext(+ scc_id="scc-001",+ files=["src/a.py", "src/b.py"],+ cycle_description="",+ total_symbols=2,+ member_symbols=[{"file_path": "src/a.py", "symbols": [{"name": "f", "signature": ""}]}],+ cross_imports=[{"from": "src/a.py", "to": "src/b.py"}],+ )+++def test_file_page_renders_german_headings_and_prose(german_generator):+ ctx = _file_ctx()+ page = german_generator._structural_page(+ page_type="file_page",+ target_path=ctx.file_path,+ title=structural_page_title("de", "file_page", ctx.file_path),+ template="file_page.j2",+ ctx=ctx,+ )++ assert page.title == "Datei: src/service/parser.py"+ for heading in (+ "## Überblick",+ "## Öffentliche API",+ "## Abhängigkeiten",+ "## Wird verwendet von",+ "## Nutzungshinweise",+ "## Fragen, die diese Seite beantwortet",+ "## Im Code",+ ):+ assert heading in page.content, heading+ assert "Sie stellt 1 öffentliches Symbol bereit" in page.content+ assert "Importiert von 1 Datei in diesem Repository." in page.content+ # Identifiers are never translated, in any language.+ assert "`src/service/parser.py`" in page.content+ assert "`parse_file`" in page.content+ assert "| `src/models.py`" not in page.content and "- `src/models.py`" in page.content+++def test_symbol_spotlight_renders_german(german_generator):+ page = german_generator._structural_symbol_spotlight(+ _symbol_ctx(),+ "src/parser.py::parse_file",+ structural_page_title("de", "symbol_spotlight", "parser.ASTParser.parse_file"),+ )++ assert page.title == "Symbol: parser.ASTParser.parse_file"+ assert "**Art:** method (asynchron)" in page.content+ assert "## Wo es verwendet wird" in page.content+ assert "## Implementierung" in page.content+ assert "keine bestätigten Aufrufstellen" in page.content+++def test_infra_and_api_contract_pages_render_german(german_generator):+ infra = german_generator._structural_infra_page(+ InfraPageContext(+ file_path="Dockerfile", language="dockerfile", raw_content="FROM x\n", targets=["build"]+ ),+ "Dockerfile",+ structural_page_title("de", "infra_page", "Dockerfile"),+ )+ assert infra.title == "Infrastruktur: Dockerfile"+ assert infra.content.startswith("# Infrastruktur: Dockerfile")+ assert "## Deklarierte Ziele" in infra.content+ assert "Sie deklariert 1 benanntes Ziel, unten aufgeführt." in infra.content+ assert "## Quelltext" in infra.content++ api = german_generator._structural_api_contract(+ ApiContractContext(+ file_path="api/routes.py",+ language="python",+ raw_content="",+ endpoints=["def create() -> Response"],+ schemas=["Payload"],+ ),+ "api/routes.py",+ structural_page_title("de", "api_contract", "api/routes.py"),+ )+ assert api.title == "API-Vertrag: api/routes.py"+ assert "## Operationen" in api.content+ assert "## Typen" in api.content+ assert "1 aufrufbare Operation und 1 Typ" in api.content+++def test_scc_page_renders_german(german_generator):+ page = german_generator._structural_scc_page(+ _scc_ctx(), "scc-001", structural_page_title("de", "scc_page", "scc-001")+ )++ assert page.title == "Zyklische Abhängigkeit: scc-001"+ assert "**Zyklus-ID:** `scc-001`" in page.content+ assert "## Dateien im Zyklus" in page.content+ assert "## Die Schleife" in page.content+ assert "**Symbole insgesamt im Zyklus:** 2" in page.content+++def test_the_footer_is_localized_on_every_structural_page(german_generator):+ ctx = _file_ctx()+ page = german_generator._structural_page(+ page_type="file_page",+ target_path=ctx.file_path,+ title="x",+ template="file_page.j2",+ ctx=ctx,+ )+ assert "Aus dem Code selbst erstellt" in page.content+ assert "Built from the code itself" not in page.content+++def test_an_unsupported_language_renders_exactly_what_english_does(generator, klingon_generator):+ """The acceptance criterion from #1092: never a partial mix, never a raise."""+ ctx = _file_ctx()+ english = generator._structural_page(+ page_type="file_page",+ target_path=ctx.file_path,+ title="x",+ template="file_page.j2",+ ctx=ctx,+ )+ klingon = klingon_generator._structural_page(+ page_type="file_page",+ target_path=ctx.file_path,+ title="x",+ template="file_page.j2",+ ctx=ctx,+ )+ assert klingon.content == english.content+ assert structural_page_title("tlh", "file_page", "src/a.py") == structural_page_title(+ None, "file_page", "src/a.py"+ )+++def test_a_template_change_re_renders_structural_pages_for_the_right_reason(+ generator, german_generator+):+ """Language is folded into the structural fingerprint, so switching it+ marks the page as rendered by an older configuration and ``update``+ redoes it. Asserted here so a future reuse-hash change cannot quietly make+ a German repository keep its English pages."""+ english_key = generator._structural_content_hash("file_page.j2", "subject-hash")+ german_key = german_generator._structural_content_hash("file_page.j2", "subject-hash")++ assert english_key and german_key+ assert english_key != german_keydiff --git a/tests/unit/generation/test_file_vocabulary.py b/tests/unit/generation/test_file_vocabulary.pyindex d796f7b27..03d1e2eee 100644--- a/tests/unit/generation/test_file_vocabulary.py+++ b/tests/unit/generation/test_file_vocabulary.py@@ -36,6 +36,7 @@ from repowise.core.generation.page_generator.structural import (oneline,signature,)+from repowise.core.generation.structural_labels import resolve_structural_labelsfrom repowise.core.persistence.crud import upsert_page, upsert_repositoryfrom repowise.core.persistence.database import init_dbfrom repowise.core.persistence.search import FullTextSearch@@ -180,6 +181,7 @@ def jinja_env() -> jinja2.Environment:env.filters.setdefault("oneline", oneline)env.filters.setdefault("as_markdown", as_markdown)env.filters.setdefault("signature", signature)+ env.globals["labels"] = resolve_structural_labels(None)return envdiff --git a/tests/unit/generation/test_kg_aware_file_pages.py b/tests/unit/generation/test_kg_aware_file_pages.pyindex b213e90cf..e3ea8634e 100644--- a/tests/unit/generation/test_kg_aware_file_pages.py+++ b/tests/unit/generation/test_kg_aware_file_pages.py@@ -311,6 +311,7 @@ class TestFilePageTemplate:oneline,signature,)+ from repowise.core.generation.structural_labels import resolve_structural_labelstemplate_dir = (Path(__file__).resolve().parents[3]@@ -328,6 +329,7 @@ class TestFilePageTemplate:env.filters["oneline"] = onelineenv.filters["as_markdown"] = as_markdownenv.filters["signature"] = signature+ env.globals["labels"] = resolve_structural_labels(None)return envdef test_file_page_renders_kg_layer(self, jinja_env):diff --git a/tests/unit/generation/test_question_text_reaches_search.py b/tests/unit/generation/test_question_text_reaches_search.pyindex f60de508c..d456b7d37 100644--- a/tests/unit/generation/test_question_text_reaches_search.py+++ b/tests/unit/generation/test_question_text_reaches_search.py@@ -27,6 +27,7 @@ from repowise.core.generation.page_generator.structural import (oneline,signature,)+from repowise.core.generation.structural_labels import resolve_structural_labelsfrom repowise.core.persistence.crud import upsert_page, upsert_repositoryfrom repowise.core.persistence.database import init_dbfrom repowise.core.persistence.search import FullTextSearch@@ -54,6 +55,7 @@ def jinja_env() -> jinja2.Environment:env.filters.setdefault("oneline", oneline)env.filters.setdefault("as_markdown", as_markdown)env.filters.setdefault("signature", signature)+ env.globals["labels"] = resolve_structural_labels(None)return envdiff --git a/tests/unit/generation/test_structural_labels.py b/tests/unit/generation/test_structural_labels.pynew file mode 100644index 000000000..5438a83cf--- /dev/null+++ b/tests/unit/generation/test_structural_labels.py@@ -0,0 +1,122 @@+"""The label catalog behind localized deterministic structural pages (#1092).++The catalog's contract is narrow and the templates render under+``StrictUndefined``, so the interesting cases are the ones where a lookup+could come back missing rather than merely untranslated.+"""++from __future__ import annotations++import re+from pathlib import Path++import pytest++from repowise.core.generation.structural_labels import (+ ENGLISH_LABELS,+ LOCALIZED_LABELS,+ resolve_structural_labels,+ structural_page_title,+)++TEMPLATE_DIR = (+ Path(__file__).resolve().parents[3]+ / "packages"+ / "core"+ / "src"+ / "repowise"+ / "core"+ / "generation"+ / "templates"+)++STRUCTURAL_TEMPLATES = [+ "_footer.j2",+ "api_contract.j2",+ "file_page.j2",+ "infra_page.j2",+ "scc_page.j2",+ "symbol_spotlight.j2",+]+++def test_german_labels_are_used_where_they_exist() -> None:+ assert resolve_structural_labels("de")["overview"] == "Überblick"++[email protected]("code", [None, "", "xx", "klingon", " ", "de-DE"])+def test_an_absent_or_unsupported_code_renders_the_full_english_catalog(code: str | None) -> None:+ # Never a partial mix and never a missing key: a template reading any label+ # under StrictUndefined has to get a string back.+ assert resolve_structural_labels(code) == ENGLISH_LABELS++[email protected]("code", ["DE", " de ", "de\n"])+def test_a_code_is_sanitized_before_lookup(code: str) -> None:+ # The same scrubbing the system prompt applies, so a config value that+ # localizes the model-written pages localizes these too.+ assert resolve_structural_labels(code)["overview"] == "Überblick"+++def test_a_partial_translation_falls_back_per_key_not_wholesale() -> None:+ labels = resolve_structural_labels("de")+ assert labels.keys() == ENGLISH_LABELS.keys()+ missing = ENGLISH_LABELS.keys() - LOCALIZED_LABELS["de"].keys()+ for key in missing:+ assert labels[key] == ENGLISH_LABELS[key]+++def test_a_translation_only_defines_keys_the_english_catalog_has() -> None:+ # A typo'd key in a translation would otherwise be silently dead.+ for code, catalog in LOCALIZED_LABELS.items():+ assert catalog.keys() <= ENGLISH_LABELS.keys(), code+++def test_no_label_key_shadows_a_dict_attribute() -> None:+ # Templates read labels with dot access, which resolves an attribute+ # before an item: a key named ``items`` or ``copy`` would render a bound+ # method rather than the text.+ assert not [key for key in ENGLISH_LABELS if hasattr({}, key)]+++def test_every_key_the_templates_read_is_in_the_catalog() -> None:+ read = set()+ for name in STRUCTURAL_TEMPLATES:+ source = (TEMPLATE_DIR / name).read_text(encoding="utf-8")+ read.update(re.findall(r"\blabels\.([a-z_]+)", source))+ assert read <= ENGLISH_LABELS.keys(), read - ENGLISH_LABELS.keys()+++def test_no_catalog_key_is_unread_by_any_template() -> None:+ read = set()+ for name in STRUCTURAL_TEMPLATES:+ source = (TEMPLATE_DIR / name).read_text(encoding="utf-8")+ read.update(re.findall(r"\blabels\.([a-z_]+)", source))+ # Titles are built in Python rather than in a template.+ read.update({"file", "symbol", "circular_dependency", "api_contract", "infrastructure"})+ assert ENGLISH_LABELS.keys() <= read, ENGLISH_LABELS.keys() - read+++def test_a_translation_keeps_every_placeholder_the_english_string_uses() -> None:+ # ``str.format`` raises KeyError on a placeholder the caller does not+ # supply, so a translation may drop one but never invent one.+ for code, catalog in LOCALIZED_LABELS.items():+ for key, text in catalog.items():+ english = set(re.findall(r"\{(\w+)\}", ENGLISH_LABELS[key]))+ translated = set(re.findall(r"\{(\w+)\}", text))+ assert translated <= english, (code, key, translated - english)+++def test_page_titles_come_from_the_same_catalog_as_the_headings() -> None:+ assert structural_page_title("de", "file_page", "src/service.py") == "Datei: src/service.py"+ assert structural_page_title("de", "api_contract", "src/api.py") == "API-Vertrag: src/api.py"+ assert structural_page_title("de", "infra_page", "Dockerfile") == "Infrastruktur: Dockerfile"+++def test_page_titles_fall_back_to_english_and_never_translate_the_target() -> None:+ assert structural_page_title("xx", "symbol_spotlight", "service.parse_file") == (+ "Symbol: service.parse_file"+ )+ assert structural_page_title("de", "symbol_spotlight", "service.parse_file") == (+ "Symbol: service.parse_file"+ )diff --git a/tests/unit/generation/test_templates.py b/tests/unit/generation/test_templates.pyindex 9dfbf2a46..a5dd6aa70 100644--- a/tests/unit/generation/test_templates.py+++ b/tests/unit/generation/test_templates.py@@ -23,6 +23,7 @@ from repowise.core.generation.page_generator.structural import (oneline,signature,)+from repowise.core.generation.structural_labels import resolve_structural_labelsfrom repowise.core.ingestion.models import PackageInfo# ---------------------------------------------------------------------------@@ -54,6 +55,7 @@ def jinja_env() -> jinja2.Environment:env.filters.setdefault("oneline", oneline)env.filters.setdefault("as_markdown", as_markdown)env.filters.setdefault("signature", signature)+ env.globals["labels"] = resolve_structural_labels(None)return env