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(workspace): reuse unchanged repos and re-run cross-repo analysis when its settings change (#4485)
Raghav Chamadiya70e0418d31c3
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 850caea96..55b36f075 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -45,7 +45,7 @@ Grouped by task; `PATH` and flags are in each command's section.[`hook health-gate`](#repowise-hook-health-gate-installuninstallstatus), [`augment`](#repowise-augment)- **Server:** [`serve`](#repowise-serve-path), [`mcp`](#repowise-mcp-path)- **Workspace:** [`workspace list`](#repowise-workspace-list), [`workspace add`](#repowise-workspace-add-path),- [`workspace remove`](#repowise-workspace-remove-alias), [`workspace scan`](#repowise-workspace-scan-path), [`workspace+ [`workspace remove`](#repowise-workspace-remove-alias), [`workspace scan`](#repowise-workspace-scan-path), [`workspace update`](#repowise-workspace-update), [`workspaceset-default`](#repowise-workspace-set-default-alias), [`workspace diagnostics`](#repowise-workspace-diagnostics),[`workspace check`](#repowise-workspace-check), [`workspace metrics`](#repowise-workspace-metrics-path), [`workspaceimpacted-tests`](#repowise-workspace-impacted-tests-repopath)@@ -1727,6 +1727,14 @@ repowise workspace scan --yes| `--exclude` | Skip paths matching this glob, relative to the workspace root (e.g. `'test-repos/*'`). Repeatable. | || `--verbose`, `-v` | Debug logs. | off |+### `repowise workspace update`++The same command as `repowise update --workspace`, with the same flags. It updates the stale repos, then re-runs the cross-repo analysis when a repo changed or the `contracts:` or `conformance:` settings did.++```bash+repowise workspace update --index-only+```+### `repowise workspace set-default <alias>`Set the default repo for MCP queries.diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 211ac599e..b283bc01c 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -619,6 +619,7 @@ No. Repowise searches upward for `.repowise-workspace.yaml` and uses the first o```bashrepowise update # Update the primary reporepowise update --workspace # Update all workspace repos+repowise workspace update # The same command```Each stale repo picks docs vs index-only the same way a single-repo update does, from its own `docs_enabled` (set at init) plus any override on the command. Repos with docs enabled regenerate their wiki (pages, diagrams, decisions) through the full docs path, so a workspace wiki stays as fresh as one you update repo by repo; the rest just refresh the index. Force docs everywhere with `repowise update --workspace --docs` (each repo needs an LLM provider/key, or pass `--provider`), or keep it index-only with `--no-docs`.@@ -631,7 +632,7 @@ repowise watch --workspace### How do I re-run just the cross-repo analysis?-Cross-repo analysis runs during `repowise init .` and `repowise update --workspace`. To force a re-run, run `repowise init .` again; it detects existing indexes and only re-runs what is needed.+Cross-repo analysis runs during `repowise init .` and `repowise update --workspace`. An update re-runs it when any repo changed, or when the `contracts:` or `conformance:` block of `.repowise-workspace.yaml` changed with every repo up to date. Editing `service_bases` or `manual_links` re-links the stored contracts without re-reading any repo; the other `contracts:` settings re-extract every repo. `repowise init .` re-indexes every repo, so it is not the way to refresh this.### Does the MCP server handle multiple repos?diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.pyindex 51503d0c9..cb157ebb6 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py@@ -113,6 +113,7 @@ def _workspace_update(if scan.stale_count == 0:console.print("[green]All repos are up to date.[/green]")if not dry_run:+ _rerun_analysis_if_config_changed(ws_root, ws_config, started_at)_refresh_workspace_editor_project_files(ws_root=ws_root,ws_config=ws_config,@@ -161,6 +162,29 @@ def _workspace_update()+def _rerun_analysis_if_config_changed(ws_root: Path, ws_config: Any, started_at: datetime) -> None:+ """Re-run the cross-repo analysis when only its settings changed.++ An edited ``contracts:`` or ``conformance:`` block moves no repo, so the+ staleness scan alone would leave the edit without effect until some repo+ changed. Settings that only affect matching re-link the stored contracts+ without reading any repo.+ """+ from repowise.core.workspace.update import analysis_config_changed, run_cross_repo_hooks++ if not analysis_config_changed(ws_config, ws_root):+ return+ console.print("Workspace settings changed: re-running cross-repo analysis...")+ try:+ run_async(run_cross_repo_hooks(ws_config, ws_root, []))+ except Exception as exc:+ # The editor files still refresh; the next update retries the analysis.+ console.print(f"[yellow]Cross-repo analysis failed: {exc}[/yellow]")+ return+ console.print("[green]Cross-repo analysis updated.[/green]")+ _print_breaking_changes(ws_root, started_at)++@dataclassclass _WorkspaceScan:"""Which workspace repos need an update, and how."""@@ -472,6 +496,7 @@ def _workspace_docs_update(from repowise.cli.commands.workspace_cmd import inherit_workspace_distill_verdictfrom repowise.core.workspace.update import (+ analysis_config_changed,run_cross_repo_hooks,sync_workspace_state_from_disk,)@@ -523,8 +548,11 @@ def _workspace_docs_update(with suppress(Exception):inherit_workspace_distill_verdict((ws_root / entry.path).resolve())- # Cross-repo hooks once, over the union of index-only and docs repos.- if changed_aliases and len(ws_config.repos) >= 2:+ # Cross-repo hooks once, over the union of index-only and docs repos, or+ # for an edited contracts: or conformance: block with no repo changed.+ if len(ws_config.repos) >= 2 and (+ changed_aliases or analysis_config_changed(ws_config, ws_root)+ ):console.print("Running cross-repo analysis...")with suppress(Exception):run_async(run_cross_repo_hooks(ws_config, ws_root, changed_aliases))diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/__init__.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/__init__.pyindex 1df4c642c..4762133d3 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/__init__.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/__init__.py@@ -6,6 +6,7 @@ Modules:* :mod:`._index`: indexing (and optional docs) for a freshly added repo* :mod:`.diagnostics`, :mod:`.check`, :mod:`.metrics`, :mod:`.impacted`:the read-only reports over the system graph+* :mod:`.update`: ``workspace update``, the same command as ``update --workspace``* :mod:`._shared`: workspace loading and artifact provenanceImporting the report modules registers their subcommands on the group. The@@ -15,7 +16,7 @@ names other commands and the test-suite import fromfrom __future__ import annotations-from . import check, diagnostics, impacted, metrics # noqa: F401 (registers subcommands)+from . import check, diagnostics, impacted, metrics, update # noqa: F401 (registers subcommands)from ._index import (_generate_docs_for_added_repo,_inherit_distill_verdict,diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/update.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/update.pynew file mode 100644index 000000000..10997eb65--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/update.py@@ -0,0 +1,28 @@+"""``repowise workspace update``: the same command as ``repowise update --workspace``."""++from __future__ import annotations++import click++from .group import workspace_group+++@workspace_group.command(+ "update",+ context_settings={"ignore_unknown_options": True, "allow_extra_args": True},+ add_help_option=False,+)[email protected]_context+def workspace_update(ctx: click.Context) -> None:+ """Update stale repos and the cross-repo analysis (same as `repowise update --workspace`)."""+ # Imported on use: the update command's module is heavy, and every other+ # workspace subcommand would pay for it at startup. Its options, --help+ # included, pass through unchanged.+ from repowise.cli.commands.update_cmd.command import update_command++ code = update_command.main(+ args=["--workspace", *ctx.args],+ prog_name="repowise workspace update",+ standalone_mode=False,+ )+ ctx.exit(code if isinstance(code, int) else 0)diff --git a/packages/core/src/repowise/core/ingestion/change_detector.py b/packages/core/src/repowise/core/ingestion/change_detector.pyindex e016e6e0a..4f2e48fa3 100644--- a/packages/core/src/repowise/core/ingestion/change_detector.py+++ b/packages/core/src/repowise/core/ingestion/change_detector.py@@ -23,7 +23,7 @@ from typing import Literalimport structlogfrom .models import FileInfo, ParsedFile, Symbol-from .traverser import is_candidate_source_path+from .traverser import is_candidate_source_path, is_repowise_outputlog = structlog.get_logger(__name__)@@ -176,7 +176,7 @@ class ChangeDetector:# covers staged and unstaged changes in one pass.for item in head_commit.diff(None):path = (item.b_path or item.a_path or "").replace("\\", "/")- if not is_candidate_source_path(path, self.repo_path, output_dirs):+ if not _counts_as_change(path, self.repo_path, output_dirs, item):continueresults.append(self._file_diff_from_item(item))untracked = list(repo.untracked_files)@@ -186,7 +186,7 @@ class ChangeDetector:for rel_path in untracked:path = rel_path.replace("\\", "/")- if not is_candidate_source_path(path, self.repo_path, output_dirs):+ if not _counts_as_change(path, self.repo_path, output_dirs):continueabs_path = self.repo_path / pathif not abs_path.is_file():@@ -605,13 +605,15 @@ def has_working_tree_changes(repo_path: Path) -> bool:except Exception:return Falsetry:- changed = (- item.b_path or item.a_path or "" for item in repo.head.commit.diff(None)- )output_dirs: dict[Path, bool] = {}return any(- is_candidate_source_path(p.replace("\\", "/"), repo_path, output_dirs)- for p in (*changed, *repo.untracked_files)+ _counts_as_change(+ (item.b_path or item.a_path or "").replace("\\", "/"), repo_path, output_dirs, item+ )+ for item in repo.head.commit.diff(None)+ ) or any(+ _counts_as_change(p.replace("\\", "/"), repo_path, output_dirs)+ for p in repo.untracked_files)except Exception as exc:log.warning("working tree check failed", path=str(repo_path), error=str(exc))@@ -620,6 +622,31 @@ def has_working_tree_changes(repo_path: Path) -> bool:repo.close()+def _counts_as_change(+ path: str, repo_path: Path, output_dirs: dict[Path, bool], item: object | None = None+) -> bool:+ """Whether a working-tree path is a change the index has to see.++ A path the index would read, unless repowise wrote the change itself: its+ own ``.claude/CLAUDE.md`` block left untracked or refreshed in a tracked+ file is not the user's work, and counting it marked every repo with an+ editor file dirty on every run. *item* is the ``HEAD`` diff entry of a+ tracked path, whose committed text tells a refreshed block from an edit.+ """+ if not is_candidate_source_path(path, repo_path, output_dirs):+ return False+ a_blob = getattr(item, "a_blob", None)+ committed = (+ (lambda: a_blob.data_stream.read().decode("utf-8", "replace")) if a_blob else None+ )+ try:+ return not is_repowise_output(repo_path / path, path, committed)+ except Exception:+ # An unreadable committed blob (LFS pointer, missing object) must not+ # hide the repo's other changes; counting this one is the safe side.+ return True++def merge_file_diffs(*sources: list[FileDiff]) -> list[FileDiff]:"""Union FileDiffs from several change sources, first mention winning.diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex cb12a28cb..09312dc26 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -804,7 +804,7 @@ class FileTraverser:return "skipped_dir_ignore"if self._blocked_patterns.match_file(rel_str):return "skipped_blocked_pattern"- if _is_repowise_output(abs_path, rel_str):+ if is_repowise_output(abs_path, rel_str):return "skipped_repowise_output"return None@@ -1813,11 +1813,16 @@ def in_blocked_dir()-def _is_repowise_output(abs_path: Path, rel_str: str) -> bool:+def is_repowise_output(+ abs_path: Path, rel_str: str, committed: Callable[[], str] | None = None+) -> bool:"""Whether repowise wrote the whole file: an owned path, or a shared one holding only its part.A shared file (``CLAUDE.md``, ``.mcp.json``) with anything the user wrotestays indexed, repowise's block included, since the user's part is theirs.+ *committed* returns the file's text at ``HEAD``, so a working-tree check+ can tell repowise's refresh of a tracked file from the user's edit; it is+ only called for a managed file."""if _OWNED_SPEC.match_file(rel_str):return True@@ -1827,7 +1832,7 @@ def _is_repowise_output(abs_path: Path, rel_str: str) -> bool:text = abs_path.read_text(encoding="utf-8")except (OSError, UnicodeDecodeError):return False- return only_repowise_differs(rel_str, "", text)+ return only_repowise_differs(rel_str, committed() if committed else "", text)def is_candidate_source_path(diff --git a/packages/core/src/repowise/core/workspace/code_api.py b/packages/core/src/repowise/core/workspace/code_api.pyindex fb047bc2f..499c7f4ff 100644--- a/packages/core/src/repowise/core/workspace/code_api.py+++ b/packages/core/src/repowise/core/workspace/code_api.py@@ -42,7 +42,7 @@ from repowise.core.fsutils import repo_relativefrom repowise.core.pyparse import parse_pythonif TYPE_CHECKING:- from collections.abc import Callable+ from collections.abc import Callable, Collectionfrom pathlib import Pathfrom repowise.core.workspace.repo_index import IndexedSymbol, RepoIndex, WorkspaceIndex@@ -430,16 +430,40 @@ class CodeSurface:return self.by_repo.get(alias, [])+def find_workspace_packages(+ repo_paths: dict[str, Path],+) -> tuple[list[PublishedPackage], dict[str, dict[str, int]]]:+ """Every package the workspace repos publish, plus per-repo skip counters.++ Read from manifests alone, so it needs no repo's index open.+ """+ published: list[PublishedPackage] = []+ stats: dict[str, dict[str, int]] = {}+ for alias, repo_path in repo_paths.items():+ packages, counts = find_published_packages(alias, repo_path)+ published.extend(packages)+ if counts:+ stats.setdefault(alias, {}).update(counts)+ return published, stats++def build_code_surface(repo_paths: dict[str, Path],workspace_index: WorkspaceIndex | None,exclude: Callable[[str], bool],+ *,+ packages: tuple[list[PublishedPackage], dict[str, dict[str, int]]] | None = None,+ consumers: Collection[str] | None = None,) -> CodeSurface:"""Build every ``code`` contract in the workspace, providers before consumers.Workspace-wide by necessity, not by preference: a consumer contract onlyexists when the package it imports is published by *some* repo, so neitherhalf can be decided inside a single repo's extraction.++ *packages* is :func:`find_workspace_packages` already run. *consumers*+ limits the consumer rows to those repos (every repo by default): a caller+ reusing a repo's stored rows needs none built for it."""from repowise.core.workspace.contracts import Contractfrom repowise.core.workspace.extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_INDEX@@ -448,12 +472,9 @@ def build_code_surface(if workspace_index is None:return surface- published: list[PublishedPackage] = []- for alias, repo_path in repo_paths.items():- packages, counts = find_published_packages(alias, repo_path)- published.extend(packages)- if counts:- surface.stats.setdefault(alias, {}).update(counts)+ published, manifest_stats = packages or find_workspace_packages(repo_paths)+ for alias, counts in manifest_stats.items():+ surface.stats.setdefault(alias, {}).update(counts)# -- providers ---------------------------------------------------------by_name: dict[str, PublishedPackage] = {}@@ -510,7 +531,7 @@ def build_code_surface(stats["code_provider_symbols"] = stats.get("code_provider_symbols", 0) + len(seen)# -- consumers ---------------------------------------------------------- for alias in repo_paths:+ for alias in repo_paths if consumers is None else [a for a in repo_paths if a in consumers]:index = workspace_index.get(alias)if index is None:continuediff --git a/packages/core/src/repowise/core/workspace/config.py b/packages/core/src/repowise/core/workspace/config.pyindex 92d71af0a..1afe539dc 100644--- a/packages/core/src/repowise/core/workspace/config.py+++ b/packages/core/src/repowise/core/workspace/config.py@@ -6,10 +6,12 @@ Pure data module with no CLI or DB dependencies. Handles thefrom __future__ import annotations+import hashlib+import jsonimport loggingimport osimport re-from dataclasses import dataclass, field+from dataclasses import dataclass, field, fieldsfrom pathlib import Pathfrom typing import Any@@ -120,29 +122,46 @@ def _valid_pattern(value: Any) -> str:return str(value)+#: The cross-repo pass a contract setting feeds, declared on each+#: :class:`ContractConfig` field. Changing an extraction setting re-extracts+#: every repo; changing a matching setting re-links the stored contracts and+#: reads no repo. A new setting declares one or a test fails.+STAGE_EXTRACTION = "extraction"+STAGE_MATCHING = "matching"+_EXTRACTION = {"stage": STAGE_EXTRACTION}+_MATCHING = {"stage": STAGE_MATCHING}++@dataclassclass ContractConfig:"""Configuration for contract detection (Phase 4)."""- detect_http: bool = True- detect_grpc: bool = True- detect_socket: bool = True- detect_topics: bool = True- detect_data: bool = True+ detect_http: bool = field(default=True, metadata=_EXTRACTION)+ detect_grpc: bool = field(default=True, metadata=_EXTRACTION)+ detect_socket: bool = field(default=True, metadata=_EXTRACTION)+ detect_topics: bool = field(default=True, metadata=_EXTRACTION)+ detect_data: bool = field(default=True, metadata=_EXTRACTION)#: A library's public API as a contract (``contract_type="code"``).- detect_code_api: bool = True- manual_links: list[ManualContractLink] = field(default_factory=list)+ detect_code_api: bool = field(default=True, metadata=_EXTRACTION)+ manual_links: list[ManualContractLink] = field(default_factory=list, metadata=_MATCHING)# Map a consumer base token or absolute host to the repo alias it targets,# so a ``fetch(`${API_BASE}/users`)`` whose base resolves to ``backend`` links# to that service as an exact match. Keys are env-var identifiers# (``API_BASE``, ``VITE_API_URL``) or hosts (``api.example.com``).- service_bases: dict[str, str] = field(default_factory=dict)+ service_bases: dict[str, str] = field(default_factory=dict, metadata=_MATCHING)# Extra glob patterns (added to the built-in test/spec defaults) whose files# are skipped during contract extraction.- exclude_globs: list[str] = field(default_factory=list)+ exclude_globs: list[str] = field(default_factory=list, metadata=_EXTRACTION)# A directory name matching this regex (in full, ignoring case) marks a .NET# project whose types are MassTransit message contracts.- contract_project_pattern: str = DEFAULT_CONTRACT_PROJECT_PATTERN+ contract_project_pattern: str = field(+ default=DEFAULT_CONTRACT_PROJECT_PATTERN, metadata=_EXTRACTION+ )++ def stage_dict(self, stage: str) -> dict[str, Any]:+ """The :meth:`to_dict` entries whose field declares *stage*."""+ stages = {f.name: f.metadata.get("stage") for f in fields(self)}+ return {k: v for k, v in self.to_dict().items() if stages[k] == stage}def to_dict(self) -> dict[str, Any]:d: dict[str, Any] = {@@ -261,22 +280,10 @@ class WorkspaceConfig:"default_repo": self.default_repo,"repos": [r.to_dict() for r in self.repos],}- # Only include contracts section if non-default+ # Only include contracts section if non-default. Compared whole, so a+ # setting added later is never dropped from the file on save.contracts_d = self.contracts.to_dict()- if (- self.contracts.manual_links- or self.contracts.service_bases- or self.contracts.exclude_globs- or not all(- [- self.contracts.detect_http,- self.contracts.detect_grpc,- self.contracts.detect_socket,- self.contracts.detect_topics,- self.contracts.detect_data,- ]- )- ):+ if contracts_d != ContractConfig().to_dict():d["contracts"] = contracts_d# Only include conformance section when rules are declared.if self.conformance.rules:@@ -304,6 +311,15 @@ class WorkspaceConfig:conformance=conformance,)+ def analysis_fingerprint(self) -> str:+ """Hash of the settings the cross-repo analysis reads.++ Compared with the one the last analysis run stamped, so editing the+ ``contracts:`` or ``conformance:`` block re-runs it with no repo changed.+ """+ payload = [self.contracts.to_dict(), self.conformance.to_dict()]+ return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()[:16]+def save(self, workspace_root: Path) -> Path:"""Write config to ``workspace_root / .repowise-workspace.yaml``.diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex 8138c11ce..29985047b 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -546,7 +546,7 @@ async def run_contract_extraction(mislabel both. Matching is dict-indexed and costs milliseconds againstseconds of extraction, so scoping it would buy nothing and risk everything."""- from .code_api import CodeSurface, build_code_surface+ from .code_api import CodeSurface, build_code_surface, find_workspace_packagesfrom .extractors import build_message_type_indexfrom .extractors.base import make_exclude_predicatefrom .extractors.masstransit import MessageTypeIndex@@ -560,13 +560,13 @@ async def run_contract_extraction(if len(repo_paths) < 2:return ContractStore()- # Built once, workspace-wide: a code consumer only exists when some *other*- # repo publishes the package it imports, so neither half of it can be- # decided inside one repo's extraction.- code_surface = (- await asyncio.to_thread(build_code_surface, repo_paths, workspace_index, exclude)- if contract_config.detect_code_api- else CodeSurface()+ # Workspace-wide: a code consumer only exists when some *other* repo+ # publishes the package it imports. Manifests alone name the packages; the+ # symbol indexes behind them are opened below, only when a repo is extracted.+ packages = (+ await asyncio.to_thread(find_workspace_packages, repo_paths)+ if contract_config.detect_code_api and workspace_index is not None+ else ([], {}))# A MassTransit consumer resolves its message type against every repo's@@ -580,7 +580,9 @@ async def run_contract_extraction()prior = previous_store or ContractStore()- config_fp = _extraction_config_fingerprint(contract_config, code_surface, message_types)+ config_fp = _extraction_config_fingerprint(+ contract_config, {p.name for p in packages[0]}, message_types+ )heads: dict[str, str | None] = {}reusable = await _reusable_repos(repo_paths, previous_store, prior, set(changed_repos), config_fp, heads@@ -588,6 +590,21 @@ async def run_contract_extraction(to_extract = {alias: path for alias, path in repo_paths.items() if alias not in reusable}await _probe_missing_heads(to_extract, heads)+ # A reused repo keeps its stored rows, so only the extracted repos, and the+ # packages they may import, need their symbols loaded.+ code_surface = CodeSurface()+ if to_extract and workspace_index is not None:+ await workspace_index.ensure({*to_extract, *(p.repo for p in packages[0])})+ if contract_config.detect_code_api:+ code_surface = await asyncio.to_thread(+ build_code_surface,+ repo_paths,+ workspace_index,+ exclude,+ packages=packages,+ consumers=to_extract,+ )+extraction = _RepoExtraction(contract_config=contract_config,exclude=exclude,@@ -652,16 +669,24 @@ def _indexed_repo_paths(ws_config: WorkspaceConfig, workspace_root: Path) -> dicdef _extraction_config_fingerprint(- contract_config: Any, code_surface: CodeSurface, message_types: MessageTypeIndex+ contract_config: Any, package_names: set[str], message_types: MessageTypeIndex) -> str:"""Fingerprint of everything that decides what extraction looks for.- The contract settings, plus the published-package and message-type sets:- both depend on *other* repos, so a change there moves no HEAD here.+ The contract settings that feed extraction, plus the published-package and+ message-type sets: both depend on *other* repos, so a change there moves no+ HEAD here. Matching settings stay out: they re-link the stored rows, which+ every run does anyway, so editing one re-extracts nothing."""+ from .config import STAGE_EXTRACTION+return hashlib.sha256(json.dumps(- [contract_config.to_dict(), sorted(code_surface.members), sorted(message_types.fqns)],+ [+ contract_config.stage_dict(STAGE_EXTRACTION),+ sorted(package_names),+ sorted(message_types.fqns),+ ],sort_keys=True,).encode()).hexdigest()[:16]diff --git a/packages/core/src/repowise/core/workspace/cross_repo.py b/packages/core/src/repowise/core/workspace/cross_repo.pyindex 1e0c3314c..f6af98c1a 100644--- a/packages/core/src/repowise/core/workspace/cross_repo.py+++ b/packages/core/src/repowise/core/workspace/cross_repo.py@@ -666,6 +666,27 @@ def load_overlay(workspace_root: Path) -> CrossRepoOverlay | None:# ---------------------------------------------------------------------------+def _current_overlay(workspace_root: Path, repo_paths: dict[str, Path]) -> CrossRepoOverlay | None:+ """The stored overlay, when it covers *repo_paths* and is newer than each repo's index."""+ from .config import WORKSPACE_DATA_DIR++ stored = load_overlay(workspace_root)+ if stored is None or set(stored.repo_summaries) != set(repo_paths):+ return None+ try:+ written = (workspace_root / WORKSPACE_DATA_DIR / CROSS_REPO_EDGES_FILENAME).stat().st_mtime+ # Every index run rewrites state.json, so a later one means new commits.+ if any(+ (path / ".repowise" / "state.json").stat().st_mtime > written+ for path in repo_paths.values()+ if (path / ".repowise" / "state.json").is_file()+ ):+ return None+ except OSError:+ return None+ return stored++async def run_cross_repo_analysis(ws_config: WorkspaceConfig,workspace_root: Path,@@ -693,6 +714,15 @@ async def run_cross_repo_analysis(_log.debug("Skipping cross-repo analysis — fewer than 2 indexed repos")return CrossRepoOverlay()+ # Co-changes and package deps come from git history and manifests, which+ # move only with a repo. With none changed (a settings edit) the stored+ # overlay is still the answer, as long as it covers exactly these repos and+ # no repo was re-indexed after it was written.+ if not changed_repos:+ stored = _current_overlay(workspace_root, repo_paths)+ if stored is not None:+ return stored+_log.info("Running cross-repo analysis across %d repos (changed: %s)",len(repo_paths),diff --git a/packages/core/src/repowise/core/workspace/repo_index.py b/packages/core/src/repowise/core/workspace/repo_index.pyindex 443f8794b..1bde22ac6 100644--- a/packages/core/src/repowise/core/workspace/repo_index.py+++ b/packages/core/src/repowise/core/workspace/repo_index.py@@ -293,14 +293,32 @@ class RepoIndex:class WorkspaceIndex:- """The open :class:`RepoIndex` for each workspace repo that has one."""+ """The open :class:`RepoIndex` for each workspace repo that has one.- def __init__(self, repos: dict[str, RepoIndex]) -> None:+ *openable* names repos not opened yet (alias to checkout path);+ :meth:`ensure` opens the ones a caller turns out to need, so a run that+ reads two repos does not load the symbols of two hundred.+ """++ def __init__(self, repos: dict[str, RepoIndex], openable: dict[str, Path] | None = None) -> None:self._repos = repos+ self._openable = dict(openable or {})def get(self, alias: str) -> RepoIndex | None:return self._repos.get(alias)+ async def ensure(self, aliases: Collection[str]) -> None:+ """Open the index of each alias in *aliases* not opened yet. A repo that fails is skipped."""+ todo = [(a, self._openable.pop(a)) for a in sorted(aliases) if a in self._openable]+ opened = await asyncio.gather(+ *(open_repo_index(alias, path) for alias, path in todo), return_exceptions=True+ )+ for (alias, _path), index in zip(todo, opened, strict=True):+ if isinstance(index, BaseException):+ _log.warning("Could not open the index for '%s'", alias, exc_info=index)+ elif index is not None:+ self._repos[alias] = index+async def close(self) -> None:for repo in self._repos.values():try:@@ -364,23 +382,20 @@ async def open_workspace_index(workspace_root: Path,*,aliases: Collection[str] | None = None,+ deferred: bool = False,) -> WorkspaceIndex:"""Open every indexed repo in the workspace. A repo that fails is skipped.- *aliases*, when given, restricts the open to those repos.+ *aliases*, when given, restricts the open to those repos. *deferred* opens+ none of them yet: the caller opens what it needs with+ :meth:`WorkspaceIndex.ensure`."""- entries = [e for e in ws_config.repos if aliases is None or e.alias in aliases]- opened = await asyncio.gather(- *(- open_repo_index(e.alias, (workspace_root / e.path).resolve())- for e in entries- ),- return_exceptions=True,- )- repos: dict[str, RepoIndex] = {}- for entry, index in zip(entries, opened, strict=True):- if isinstance(index, BaseException):- _log.warning("Could not open the index for '%s'", entry.alias, exc_info=index)- elif index is not None:- repos[entry.alias] = index- return WorkspaceIndex(repos)+ openable = {+ e.alias: (workspace_root / e.path).resolve()+ for e in ws_config.repos+ if aliases is None or e.alias in aliases+ }+ index = WorkspaceIndex({}, openable)+ if not deferred:+ await index.ensure(list(openable))+ return indexdiff --git a/packages/core/src/repowise/core/workspace/update/__init__.py b/packages/core/src/repowise/core/workspace/update/__init__.pyindex 05f01a570..b6315fa9b 100644--- a/packages/core/src/repowise/core/workspace/update/__init__.py+++ b/packages/core/src/repowise/core/workspace/update/__init__.py@@ -16,6 +16,7 @@ from .phases import (_refresh_contract_facts,_run_phases,_system_graph_phase,+ analysis_config_changed,run_cross_repo_hooks,)from .repo import (@@ -69,6 +70,7 @@ from .workspace_pass import (__all__ = ["IndexedCommit","RepoUpdateResult",+ "analysis_config_changed","check_repo_staleness","clear_stale_update_pending","commit_exists",diff --git a/packages/core/src/repowise/core/workspace/update/phases.py b/packages/core/src/repowise/core/workspace/update/phases.pyindex 07cd11782..197f34531 100644--- a/packages/core/src/repowise/core/workspace/update/phases.py+++ b/packages/core/src/repowise/core/workspace/update/phases.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import json as _jsonimport loggingfrom collections.abc import Awaitablefrom pathlib import Path@@ -20,6 +21,10 @@ if TYPE_CHECKING:_log = logging.getLogger("repowise.workspace.update")+#: Which ``contracts:`` and ``conformance:`` settings the last cross-repo+#: analysis ran with, in ``.repowise-workspace/``.+ANALYSIS_CONFIG_FILENAME = "analysis_config.json"+def _log_phase(timings: PhaseTimingRecorder, phase: str, **counts: int) -> None:"""Emit one structured line for a finished cross-repo phase.@@ -59,14 +64,18 @@ async def run_cross_repo_hooks(timings = PhaseTimingRecorder()# One read connection per repo serves all five phases; only the HTTP- # extractor reads it, so nothing is opened when that is off.+ # extractor reads it, so nothing is opened when that is off. Deferred:+ # extraction opens only the repos it re-extracts and the packages they+ # import, so a run with one repo changed loads one repo's symbols.workspace_index = (- await open_workspace_index(ws_config, workspace_root)+ await open_workspace_index(ws_config, workspace_root, deferred=True)if ws_config.contracts.detect_httpelse WorkspaceIndex({}))try:- await _run_phases(ws_config, workspace_root, changed_repos, timings, workspace_index)+ settled = await _run_phases(+ ws_config, workspace_root, changed_repos, timings, workspace_index+ )finally:await workspace_index.close()@@ -81,6 +90,11 @@ async def run_cross_repo_hooks(timings.on_phase_done("workspace_store")_log_phase(timings, "workspace_store")+ # A failed extraction or graph is retried on the next update rather than+ # stamped as having run under these settings.+ if settled:+ stamp_analysis_config(ws_config, workspace_root)+# Each updated repo snapshotted its components before contracts were# extracted at its new commit; measure them now.for alias in changed_repos:@@ -89,6 +103,43 @@ async def run_cross_repo_hooks(await _refresh_contract_facts((workspace_root / entry.path).resolve())+def analysis_config_changed(ws_config: WorkspaceConfig, workspace_root: Path) -> bool:+ """Whether the cross-repo settings differ from those the last analysis ran with.++ No stamp counts as changed: the analysis never ran, or ran before stamps+ existed, and one run settles it. A workspace too small for the analysis+ never changes.+ """+ if len(ws_config.repos) < 2:+ return False+ try:+ stamp = _json.loads(_stamp_path(workspace_root).read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return True+ return not isinstance(stamp, dict) or stamp.get("fingerprint") != ws_config.analysis_fingerprint()+++def stamp_analysis_config(ws_config: WorkspaceConfig, workspace_root: Path) -> None:+ """Record the cross-repo settings this analysis ran with. Best-effort."""+ from ...fsutils import atomic_write_text+ from ..config import WORKSPACE_DATA_DIR++ try:+ (workspace_root / WORKSPACE_DATA_DIR).mkdir(parents=True, exist_ok=True)+ atomic_write_text(+ _stamp_path(workspace_root),+ _json.dumps({"fingerprint": ws_config.analysis_fingerprint()}),+ )+ except OSError:+ _log.warning("Could not stamp the cross-repo analysis config", exc_info=True)+++def _stamp_path(workspace_root: Path) -> Path:+ from ..config import WORKSPACE_DATA_DIR++ return workspace_root / WORKSPACE_DATA_DIR / ANALYSIS_CONFIG_FILENAME++async def _refresh_contract_facts(repo_path: Path) -> None:"""Best-effort: a failure leaves the run's contracts unavailable."""from ...events.store import refresh_contract_facts@@ -116,8 +167,11 @@ async def _run_phases(changed_repos: list[str],timings: PhaseTimingRecorder,workspace_index: WorkspaceIndex,-) -> None:- """The five cross-repo phases, over an already-open workspace index."""+) -> bool:+ """The five cross-repo phases, over an already-open workspace index.++ True when extraction and the system graph both succeeded.+ """from ..contracts import ContractStore, load_contract_storeboundaries_by_repo = await _boundaries_phase(ws_config, workspace_root, timings)@@ -149,6 +203,7 @@ async def _run_phases(_conformance_phase(ws_config, workspace_root, timings, system_graph)_log.info("Cross-repo phase timings (seconds): %s", timings.timings)+ return extraction_ok and system_graph is not Noneasync def _boundaries_phase(diff --git a/packages/core/src/repowise/core/workspace/update/workspace_pass.py b/packages/core/src/repowise/core/workspace/update/workspace_pass.pyindex ba1721d7f..fbece9cad 100644--- a/packages/core/src/repowise/core/workspace/update/workspace_pass.py+++ b/packages/core/src/repowise/core/workspace/update/workspace_pass.py@@ -39,7 +39,7 @@ from ...ingestion.git_indexer import ()from ...ingestion.git_indexer._constants import _DEFAULT_COMMIT_LIMITfrom ..config import RepoEntry, WorkspaceConfig-from .phases import run_cross_repo_hooks+from .phases import analysis_config_changed, run_cross_repo_hooksfrom .repo import RepoUpdateResult, _has_persisted_repo_index, update_single_repo_indexfrom .state import (check_repo_staleness,@@ -126,7 +126,10 @@ async def update_workspace(sync_workspace_state_from_disk(workspace_root, ws_config)stale_repos = await _select_stale_repos(workspace_root, entries, include_working_tree, results)- if dry_run or not stale_repos:+ # An edited contracts: or conformance: block is work too, with no repo stale.+ if dry_run or not (+ stale_repos or (run_hooks and analysis_config_changed(ws_config, workspace_root))+ ):return results# Workspace single-flight: concurrent hook-triggered passes defer to the@@ -134,6 +137,8 @@ async def update_workspace(# running pass rolls forward instead of a second full pass starting.workspace_owner = _try_acquire_workspace_lock(workspace_root)if workspace_owner is not None:+ if not stale_repos:+ return resultsreturn _defer_to_running_workspace_update(workspace_owner, stale_repos)# The workspace lock is held until every member has been attempted.@@ -464,11 +469,14 @@ async def _finish_workspace_pass(changed_aliases: list[str],run_hooks: bool,) -> None:- """Save the updated workspace config, then run the cross-repo hooks."""+ """Save the updated workspace config, then run the cross-repo hooks.++ The hooks run when a repo changed or the cross-repo settings did.+ """if changed_aliases:ws_config.save(workspace_root)# ``run_hooks`` lets the CLI defer these so they run once over the union# of index-only and docs repos, rather than on this partial set.- if changed_aliases and run_hooks:+ if run_hooks and (changed_aliases or analysis_config_changed(ws_config, workspace_root)):await run_cross_repo_hooks(ws_config, workspace_root, changed_aliases)diff --git a/tests/unit/cli/test_workspace_update_alias.py b/tests/unit/cli/test_workspace_update_alias.pynew file mode 100644index 000000000..7ce6e71a3--- /dev/null+++ b/tests/unit/cli/test_workspace_update_alias.py@@ -0,0 +1,52 @@+"""`repowise workspace update`, and the up-to-date path re-running edited settings."""++from __future__ import annotations++from datetime import UTC, datetime+from pathlib import Path+from unittest.mock import AsyncMock++import pytest+from click.testing import CliRunner++from repowise.cli.commands.update_cmd import workspace as ws_update+from repowise.cli.main import cli+from repowise.core.workspace.config import RepoEntry, WorkspaceConfig+++def test_workspace_update_runs_update_in_workspace_mode(monkeypatch: pytest.MonkeyPatch) -> None:+ from repowise.cli.commands.update_cmd import command++ calls: list[dict] = []+ monkeypatch.setattr(command, "run_update", lambda **kw: calls.append(kw))++ result = CliRunner().invoke(cli, ["workspace", "update", "--index-only", "--repo", "api"])++ assert result.exit_code == 0, result.output+ assert calls[0]["workspace"] is True+ assert calls[0]["index_only"] is True+ assert calls[0]["repo_alias"] == "api"+++def test_workspace_update_rejects_an_unknown_option() -> None:+ result = CliRunner().invoke(cli, ["workspace", "update", "--bogus"])+ assert result.exit_code == 2+ assert "--bogus" in result.output++[email protected]("changed", [True, False])+def test_up_to_date_workspace_reruns_analysis_only_when_settings_changed(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, changed: bool+) -> None:+ from repowise.core.workspace import update++ ws_config = WorkspaceConfig(+ repos=[RepoEntry(path="api", alias="api"), RepoEntry(path="web", alias="web")]+ )+ hooks = AsyncMock()+ monkeypatch.setattr(update, "run_cross_repo_hooks", hooks)+ monkeypatch.setattr(update, "analysis_config_changed", lambda *_: changed)++ ws_update._rerun_analysis_if_config_changed(tmp_path, ws_config, datetime.now(UTC))++ assert hooks.await_count == (1 if changed else 0)diff --git a/tests/unit/ingestion/test_working_tree_changes.py b/tests/unit/ingestion/test_working_tree_changes.pyindex 75c2e54cf..cfc1e39ed 100644--- a/tests/unit/ingestion/test_working_tree_changes.py+++ b/tests/unit/ingestion/test_working_tree_changes.py@@ -162,6 +162,50 @@ class TestHasWorkingTreeChanges:def test_false_on_a_non_git_directory(self, tmp_path: Path) -> None:assert has_working_tree_changes(tmp_path) is False+ def test_repowise_editor_file_is_not_the_users_change(self, repo: Path) -> None:+ # init writes .claude/CLAUDE.md untracked; counting it marked every+ # repo with editor setup dirty on every run.+ _write_claude_md(repo, "")++ assert has_working_tree_changes(repo) is False+ assert ChangeDetector(repo).get_working_tree_changes() == []++ def test_refreshed_block_in_a_tracked_editor_file_does_not_count(self, repo: Path) -> None:+ _write_claude_md(repo, "Team notes.\n\n", block="Last indexed: monday")+ r = gitpython.Repo(repo)+ r.index.add([".claude/CLAUDE.md"])+ r.index.commit("add claude md")+ r.close()+ _write_claude_md(repo, "Team notes.\n\n", block="Last indexed: tuesday")++ assert has_working_tree_changes(repo) is False+ assert ChangeDetector(repo).get_working_tree_changes() == []++ def test_users_edit_of_an_editor_file_still_counts(self, repo: Path) -> None:+ _write_claude_md(repo, "Always run the linter.\n\n")++ assert has_working_tree_changes(repo) is True+ assert [d.path for d in ChangeDetector(repo).get_working_tree_changes()] == [+ ".claude/CLAUDE.md"+ ]+++def _write_claude_md(repo: Path, user_text: str, block: str = "Last indexed: today") -> None:+ """``.claude/CLAUDE.md`` as the generator writes it, with *user_text* above the block."""+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator as Gen+ from repowise.core.generation.editor_files.claude_md import ClaudeMdGenerator++ tag = ClaudeMdGenerator.marker_tag+ text = (+ (user_text or ClaudeMdGenerator.user_placeholder)+ + Gen.MARKER_START_FMT.format(tag=tag)+ + f"\n{block}\n"+ + Gen.MARKER_END_FMT.format(tag=tag)+ + "\n"+ )+ (repo / ".claude").mkdir(exist_ok=True)+ (repo / ".claude" / "CLAUDE.md").write_text(text, encoding="utf-8")+def _diff(path: str, status: str) -> FileDiff:return FileDiff(diff --git a/tests/unit/workspace/test_contract_config.py b/tests/unit/workspace/test_contract_config.pyindex 6674e85e3..fc1be8b0a 100644--- a/tests/unit/workspace/test_contract_config.py+++ b/tests/unit/workspace/test_contract_config.py@@ -154,3 +154,47 @@ class TestContractProjectPattern:def test_invalid_regex_falls_back_to_the_default(self) -> None:cfg = ContractConfig.from_dict({"contract_project_pattern": "(unclosed"})assert cfg.contract_project_pattern == ContractConfig().contract_project_pattern+++class TestSettingStages:+ """Each contract setting says whether it feeds extraction or only matching."""++ def test_every_setting_declares_its_stage(self) -> None:+ from dataclasses import fields++ from repowise.core.workspace.config import STAGE_EXTRACTION, STAGE_MATCHING++ undeclared = [+ f.name+ for f in fields(ContractConfig)+ if f.metadata.get("stage") not in {STAGE_EXTRACTION, STAGE_MATCHING}+ ]+ assert undeclared == []++ def test_matching_settings_stay_out_of_the_extraction_half(self) -> None:+ from repowise.core.workspace.config import STAGE_EXTRACTION, STAGE_MATCHING++ cfg = ContractConfig(+ service_bases={"API_BASE": "api"},+ manual_links=[ManualContractLink("a", "b", "http", "http::GET::/x")],+ )+ assert cfg.stage_dict(STAGE_EXTRACTION) == ContractConfig().to_dict()+ assert set(cfg.stage_dict(STAGE_MATCHING)) == {"service_bases", "manual_links"}++ def test_a_lone_non_default_setting_survives_save(self, tmp_path) -> None:+ ws = WorkspaceConfig(+ repos=[RepoEntry(path="a", alias="a")],+ contracts=ContractConfig(detect_code_api=False),+ )+ ws.save(tmp_path)+ assert WorkspaceConfig.load(tmp_path).contracts.detect_code_api is False++ def test_analysis_fingerprint_follows_settings_not_repos(self) -> None:+ base = WorkspaceConfig(repos=[RepoEntry(path="a", alias="a")])+ moved = WorkspaceConfig(repos=[RepoEntry(path="a", alias="a", last_commit_at_index="f00")])+ edited = WorkspaceConfig(+ repos=[RepoEntry(path="a", alias="a")],+ contracts=ContractConfig(service_bases={"API_BASE": "a"}),+ )+ assert base.analysis_fingerprint() == moved.analysis_fingerprint()+ assert base.analysis_fingerprint() != edited.analysis_fingerprint()diff --git a/tests/unit/workspace/test_cross_repo.py b/tests/unit/workspace/test_cross_repo.pyindex 2e5e61851..8f2a7708f 100644--- a/tests/unit/workspace/test_cross_repo.py+++ b/tests/unit/workspace/test_cross_repo.py@@ -760,3 +760,72 @@ class TestOverlayPersistence:path = save_overlay(overlay, tmp_path)assert path.is_file()assert (tmp_path / ".repowise-workspace").is_dir()+++# ---------------------------------------------------------------------------+# run_cross_repo_analysis with no repo changed+# ---------------------------------------------------------------------------+++def _indexed_workspace(tmp_path: Path, aliases: list[str]):+ from repowise.core.workspace.config import RepoEntry, WorkspaceConfig++ for alias in aliases:+ (tmp_path / alias / ".repowise").mkdir(parents=True)+ return WorkspaceConfig(repos=[RepoEntry(path=a, alias=a) for a in aliases])+++def test_no_changed_repo_reuses_the_stored_overlay(tmp_path: Path) -> None:+ """A settings edit moves no git history, so nothing is walked again."""+ import asyncio++ from repowise.core.workspace.cross_repo import run_cross_repo_analysis, save_overlay++ ws_config = _indexed_workspace(tmp_path, ["api", "web"])+ stored = CrossRepoOverlay(repo_summaries={"api": {}, "web": {}}, total_co_changes=7)+ save_overlay(stored, tmp_path)++ with patch("repowise.core.workspace.cross_repo.detect_cross_repo_co_changes") as walk:+ overlay = asyncio.run(run_cross_repo_analysis(ws_config, tmp_path, []))++ walk.assert_not_called()+ assert overlay.total_co_changes == 7+++def test_stored_overlay_for_other_repos_is_recomputed(tmp_path: Path) -> None:+ import asyncio++ from repowise.core.workspace.cross_repo import run_cross_repo_analysis, save_overlay++ ws_config = _indexed_workspace(tmp_path, ["api", "web"])+ save_overlay(CrossRepoOverlay(repo_summaries={"api": {}, "gone": {}}), tmp_path)++ with patch(+ "repowise.core.workspace.cross_repo.detect_cross_repo_co_changes", return_value=([], 0)+ ) as walk:+ overlay = asyncio.run(run_cross_repo_analysis(ws_config, tmp_path, []))++ walk.assert_called_once()+ assert set(overlay.repo_summaries) == {"api", "web"}+++def test_repo_re_indexed_after_the_overlay_is_recomputed(tmp_path: Path) -> None:+ """A repo updated on its own since the overlay was written has new history."""+ import asyncio+ import os++ from repowise.core.workspace.cross_repo import run_cross_repo_analysis, save_overlay++ ws_config = _indexed_workspace(tmp_path, ["api", "web"])+ out = save_overlay(CrossRepoOverlay(repo_summaries={"api": {}, "web": {}}), tmp_path)+ state = tmp_path / "web" / ".repowise" / "state.json"+ state.write_text("{}", encoding="utf-8")+ later = out.stat().st_mtime + 10+ os.utime(state, (later, later))++ with patch(+ "repowise.core.workspace.cross_repo.detect_cross_repo_co_changes", return_value=([], 0)+ ) as walk:+ asyncio.run(run_cross_repo_analysis(ws_config, tmp_path, []))++ walk.assert_called_once()diff --git a/tests/unit/workspace/test_incremental_extraction.py b/tests/unit/workspace/test_incremental_extraction.pyindex 39d5ed5f4..5339c9ef0 100644--- a/tests/unit/workspace/test_incremental_extraction.py+++ b/tests/unit/workspace/test_incremental_extraction.py@@ -227,8 +227,7 @@ async def test_changed_contract_config_forces_re_extraction() -> None:"""Rows extracted under a different question must not be reused.- Turning a detector off, or adding a ``service_bases`` mapping, changes what- extraction looks for and how consumers resolve — but it moves no commit, so+ Turning a detector off changes what extraction looks for — but it moves no commit, sothe HEAD check alone would happily carry the old answers forward and theconfig change would appear to do nothing until someone committed."""@@ -619,3 +618,88 @@ async def test_changed_contract_project_pattern_re_extracts_every_repo(assert sorted(extracted) == ["alpha", "beta"]assert _topic_ids(second, "beta") == ["topic::sample.contracts:ping"]+++# ---------------------------------------------------------------------------+# Matching settings, repowise's own files, and which indexes are opened+# ---------------------------------------------------------------------------+++async def test_matching_settings_relink_without_re_extracting(+ workspace: WorkspaceConfig, tmp_path: Path, no_save: None, extracted: list[str]+) -> None:+ """service_bases and manual_links decide links, not what a repo holds."""+ from repowise.core.workspace.config import ManualContractLink++ first = await _first_run(workspace, tmp_path)+ extracted.clear()++ relinked = WorkspaceConfig(+ repos=list(workspace.repos),+ contracts=ContractConfig(+ service_bases={"API_BASE": "beta"},+ manual_links=[ManualContractLink("alpha", "beta", "http", "http::GET::/manual")],+ ),+ )+ second = await run_contract_extraction(relinked, tmp_path, [], None, first)++ assert extracted == []+ assert second.contracts == first.contracts+ assert any(lk.contract_id == "http::GET::/manual" for lk in second.contract_links)+++async def test_repowise_editor_file_keeps_the_repo_reusable(+ workspace: WorkspaceConfig, tmp_path: Path, no_save: None, extracted: list[str]+) -> None:+ """init writes .claude/CLAUDE.md untracked; that is not a change to the repo."""+ from repowise.core.generation.editor_files.base import BaseEditorFileGenerator as Gen+ from repowise.core.generation.editor_files.claude_md import ClaudeMdGenerator++ first = await _first_run(workspace, tmp_path)+ tag = ClaudeMdGenerator.marker_tag+ claude_md = tmp_path / "beta" / ".claude" / "CLAUDE.md"+ claude_md.parent.mkdir()+ claude_md.write_text(+ ClaudeMdGenerator.user_placeholder+ + Gen.MARKER_START_FMT.format(tag=tag)+ + "Last indexed: today"+ + Gen.MARKER_END_FMT.format(tag=tag),+ encoding="utf-8",+ )+ extracted.clear()++ await run_contract_extraction(workspace, tmp_path, [], None, first)++ assert extracted == []+++class _RecordingIndex:+ """A workspace index that holds nothing and records what it was asked to open."""++ def __init__(self) -> None:+ self.ensured: list[set[str]] = []++ def get(self, alias: str) -> None:+ return None++ async def ensure(self, aliases) -> None:+ self.ensured.append(set(aliases))+++async def test_indexes_open_only_for_extracted_repos(+ workspace: WorkspaceConfig, tmp_path: Path, no_save: None+) -> None:+ """Loading every repo's symbols was most of the time a run with nothing to extract took."""+ index = _RecordingIndex()+ first = await run_contract_extraction(workspace, tmp_path, [], None, None, index)+ assert index.ensured == [{"alpha", "beta"}]++ index = _RecordingIndex()+ await run_contract_extraction(workspace, tmp_path, [], None, first, index)+ assert index.ensured == []++ (tmp_path / "beta" / "svc" / "api.py").write_text("x = 1\n", encoding="utf-8")+ index = _RecordingIndex()+ await run_contract_extraction(workspace, tmp_path, [], None, first, index)+ # beta, plus the repos publishing a package beta may import (both ship "svc").+ assert index.ensured == [{"alpha", "beta"}]diff --git a/tests/unit/workspace/test_update.py b/tests/unit/workspace/test_update.pyindex 82883128b..ee887ee29 100644--- a/tests/unit/workspace/test_update.py+++ b/tests/unit/workspace/test_update.py@@ -1073,3 +1073,101 @@ class TestSavedExcludeSources:_merge_settings_excludes(patterns, "{not json")assert patterns == ["dist/**"]assert "saved exclude patterns not applied" in caplog.text+++# ---------------------------------------------------------------------------+# Cross-repo settings edited with every repo up to date+# ---------------------------------------------------------------------------+++class TestAnalysisConfigChange:+ """An edited contracts: or conformance: block moves no repo, and used to do nothing."""++ def _workspace(self, tmp_path: Path) -> WorkspaceConfig:+ for name in ("api", "web"):+ repo = _make_git_repo(tmp_path, name)+ _write_state(repo, get_head_commit(repo))+ return WorkspaceConfig(+ repos=[RepoEntry(path="api", alias="api"), RepoEntry(path="web", alias="web")]+ )++ def _run(+ self, tmp_path: Path, ws_config: WorkspaceConfig, monkeypatch: pytest.MonkeyPatch+ ) -> AsyncMock:+ import asyncio++ from repowise.core.workspace.update import workspace_pass++ hooks = AsyncMock()+ monkeypatch.setattr(workspace_pass, "run_cross_repo_hooks", hooks)+ asyncio.run(update_workspace(tmp_path, ws_config))+ return hooks++ def test_settings_edit_runs_the_hooks_and_the_stamp_settles_it(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from repowise.core.workspace.config import ContractConfig+ from repowise.core.workspace.update.phases import stamp_analysis_config++ ws_config = self._workspace(tmp_path)+ stamp_analysis_config(ws_config, tmp_path)+ assert not self._run(tmp_path, ws_config, monkeypatch).await_count++ ws_config.contracts = ContractConfig(service_bases={"API_BASE": "api"})+ hooks = self._run(tmp_path, ws_config, monkeypatch)+ hooks.assert_awaited_once_with(ws_config, tmp_path, [])++ def test_no_stamp_runs_the_hooks_once(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """No stamp: the analysis never ran under these settings, so it runs."""+ ws_config = self._workspace(tmp_path)+ assert self._run(tmp_path, ws_config, monkeypatch).await_count == 1++ def test_run_hooks_false_leaves_them_to_the_caller(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ import asyncio++ from repowise.core.workspace.update import workspace_pass++ ws_config = self._workspace(tmp_path)+ hooks = AsyncMock()+ monkeypatch.setattr(workspace_pass, "run_cross_repo_hooks", hooks)+ asyncio.run(update_workspace(tmp_path, ws_config, run_hooks=False))+ hooks.assert_not_awaited()++ def test_hooks_stamp_the_settings_they_ran_with(self, tmp_path: Path) -> None:+ import asyncio++ from repowise.core.workspace.update import analysis_config_changed++ ws_config = WorkspaceConfig(+ repos=[RepoEntry(path="api", alias="api"), RepoEntry(path="web", alias="web")]+ )+ assert analysis_config_changed(ws_config, tmp_path)+ with (+ patch("repowise.core.workspace.update.phases._run_phases", AsyncMock()),+ patch("repowise.core.workspace.store.refresh_workspace_store", AsyncMock()),+ ):+ asyncio.run(run_cross_repo_hooks(ws_config, tmp_path, []))+ assert not analysis_config_changed(ws_config, tmp_path)++ def test_failed_analysis_is_not_stamped(self, tmp_path: Path) -> None:+ """A failed extraction is retried on the next update, not settled."""+ import asyncio++ from repowise.core.workspace.update import analysis_config_changed++ ws_config = WorkspaceConfig(+ repos=[RepoEntry(path="api", alias="api"), RepoEntry(path="web", alias="web")]+ )+ with (+ patch(+ "repowise.core.workspace.update.phases._run_phases",+ AsyncMock(return_value=False),+ ),+ patch("repowise.core.workspace.store.refresh_workspace_store", AsyncMock()),+ ):+ asyncio.run(run_cross_repo_hooks(ws_config, tmp_path, []))+ assert analysis_config_changed(ws_config, tmp_path)