Skip to content

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

fix(refactoring): run a JS/TS plan's tests from the package that owns them (#3486)

Raghav Chamadiya03976f8a8940
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index 76e3aa21a..ad1ee49b4 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -70,6 +70,9 @@ selectors (`tests/test_orders.py::test_total`), and its command runs only the
files they live in. When no test reaches the change, the plan has no command and
asks for a characterization test first; it also asks when tests reach the file
but none reaches the changed function.
+A JavaScript or TypeScript test runs from the package whose `package.json`
+declares its `test` script (`npm --prefix ui-tui test -- src/a.test.ts`), and a
+test that no package can run gets no command.
In a plan with several steps, such as a performance fix at several call sites,
plan detail adds a `verify` to each step whose tests differ from the plan's: the
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
index c258bff61..f12c363a9 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
@@ -168,7 +168,7 @@ def _load_recommendations(
if repo is None:
return []
recommendations = await hydrate_recommendations(
- session, repo.id, suggestions, metric_rows=metrics
+ session, repo.id, suggestions, metric_rows=metrics, checkout=str(repo_path)
)
return serialize_recommendations(recommendations)
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py b/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py
index 95bfc719f..1c09e48ae 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py
@@ -26,7 +26,7 @@ from ....co_change import parse_partners
from ....persistence.crud.analysis.dead_code import get_dead_code_findings
from ....persistence.crud.authority import governing_decisions_by_file
from ....persistence.crud.git import get_git_metadata_bulk
-from ....persistence.models import GitCommit, GitFunctionBlame, GraphNode, Repository
+from ....persistence.models import GitCommit, GitFunctionBlame, GraphNode
from ..queue.eligibility import DeadSpan, dead_spans, dead_target
from .extract_helper import ACTIVE_CO_CHANGE
from .models import RefactoringSuggestion
@@ -373,13 +373,13 @@ async def load_annotation_facts(
repository_id: str,
suggestions: Sequence[RefactoringSuggestion],
tests: Iterable[str] = (),
+ *,
+ root: str | None = None,
) -> AnnotationFacts:
"""Every fact :func:`annotate` reads, for the whole plan set at once;
- *tests* are the ones the Extract Method plans run."""
+ *tests* are the ones the Extract Method plans run, and *root* is the
+ checkout the caller already looked up (None reads no test sources)."""
files = sorted({item.file_path for item in suggestions if item.file_path})
- root = await session.scalar(
- select(Repository.local_path).where(Repository.id == repository_id)
- )
metadata = await get_git_metadata_bulk(session, repository_id, files)
dead = await get_dead_code_findings(session, repository_id)
recent = await _recent_commits(session, repository_id)
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/batches.py b/packages/core/src/repowise/core/analysis/health/refactoring/batches.py
index c0746701b..cb5d6f857 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/batches.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/batches.py
@@ -74,7 +74,11 @@ def stage_batches(
return None
lead = [s["n"] for s in steps if s["n"] < numbers[0]]
tests, total = _batch_tests(detail)
- commands = commands_for_tests(tests, total=total)
+ # Each JS/TS test runs from the package the plan stored for it.
+ packages = _validation(detail).get("js_packages")
+ commands = commands_for_tests(
+ tests, total=total, packages=packages if isinstance(packages, Mapping) else None
+ )
check = _check(tests, detail)
sizes = _sizes(len(numbers))
out: list[dict[str, Any]] = []
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/commands.py b/packages/core/src/repowise/core/analysis/health/refactoring/commands.py
index 36dc39f19..1c521e185 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/commands.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/commands.py
@@ -2,8 +2,91 @@
from __future__ import annotations
+import json
+import re
+from collections.abc import Iterable, Mapping
+from pathlib import Path
-def commands_for_tests(tests: list[str], *, total: int | None = None) -> list[str]:
+from ....ingestion.package_roots import owning_package
+from ...test_selection import JS_SUFFIXES, PYTHON_SUFFIXES
+
+#: Each JS/TS test file's package: the directory (``""`` is the repository
+#: root) whose package.json declares a ``test`` script, or None when no
+#: package.json above the file does. A file the map does not hold is None too.
+JsPackages = Mapping[str, str | None]
+
+
+def _file(test: str) -> str:
+ return test.split("::", 1)[0]
+
+
+def _is_js(test: str) -> bool:
+ return _file(test).lower().endswith(JS_SUFFIXES)
+
+
+def _arg(path: str) -> str:
+ # Double quotes hold a space in sh, PowerShell and cmd alike. Ceiling: a
+ # path with ``"``, ``$`` or a backtick is left as is; upgrade by quoting
+ # per shell once a plan names its shell.
+ return f'"{path}"' if re.search(r"\s", path) and not re.search(r'["$`]', path) else path
+
+
+def _declares_test(manifest: Path) -> bool:
+ try:
+ scripts = json.loads(manifest.read_text(encoding="utf-8")).get("scripts")
+ except (OSError, ValueError, AttributeError):
+ return False
+ script = scripts.get("test") if isinstance(scripts, dict) else None
+ # npm init's placeholder exits 1 without running anything.
+ return isinstance(script, str) and bool(script) and "no test specified" not in script
+
+
+def js_test_packages(
+ root: Path, manifests: Mapping[str, frozenset[str]], tests: Iterable[str]
+) -> dict[str, str | None]:
+ """The package that runs each JS/TS test in *tests*: the nearest package
+ root (*manifests*, from :func:`scan_package_manifests`) whose package.json
+ declares a test script. Blocking file reads: an async caller uses a thread.
+ """
+ declares: dict[str, bool] = {}
+
+ def accepts(directory: str) -> bool:
+ if directory not in declares:
+ declares[directory] = _declares_test(root / directory / "package.json")
+ return declares[directory]
+
+ return {
+ path: owning_package(path, manifests, "package.json", accepts)
+ for path in {_file(test) for test in tests if _is_js(test)}
+ }
+
+
+def plan_packages(tests: Iterable[str], packages: JsPackages | None) -> dict[str, str | None]:
+ """The part of *packages* a plan's *tests* use, stored on the plan so a
+ later read (batches, a served plan) needs no checkout. Empty without a map."""
+ if packages is None:
+ return {}
+ return {path: packages.get(path) for path in {_file(test) for test in tests if _is_js(test)}}
+
+
+def _js_commands(tests: list[str], packages: JsPackages | None) -> list[str]:
+ """``npm test`` from the package each test belongs to; a test no package
+ can run gets no command. Without *packages* every test runs from the root."""
+ groups: dict[str, list[str]] = {}
+ for test in tests:
+ owner = packages.get(_file(test)) if packages is not None else ""
+ if owner is not None:
+ groups.setdefault(owner, []).append(test[len(owner) + 1 :] if owner else test)
+ return [
+ ("npm test -- " if not owner else f"npm --prefix {_arg(owner)} test -- ")
+ + " ".join(map(_arg, paths))
+ for owner, paths in sorted(groups.items())
+ ]
+
+
+def commands_for_tests(
+ tests: list[str], *, total: int | None = None, packages: JsPackages | None = None
+) -> list[str]:
"""A command that runs at least everything the plan says validates it.
When the displayed list is capped, enumerating only the shown tests would
@@ -13,22 +96,20 @@ def commands_for_tests(tests: list[str], *, total: int | None = None) -> list[st
An empty list means the plan has no command to suggest. Every command names
its tests: with none found, a bare ``pytest`` or ``npm test`` would run a
- whole suite as if it guarded the change. Nothing here looks at the
- repository's tooling, so a language other than Python or JS/TS gets none in
- place of a guess that would fail when run.
+ whole suite as if it guarded the change. A JS/TS test runs from the package
+ whose ``test`` script owns it (*packages*), with its path relative to that
+ package; a test no package.json can run gets no command. A language other
+ than Python or JS/TS gets none in place of a guess that would fail when run.
"""
if total is not None and total > len(tests):
- tests = sorted({test.split("::", 1)[0] for test in tests})
- python_tests = sorted(test for test in tests if ".py" in test)
- js_tests = sorted(
- test for test in tests if any(ext in test for ext in (".ts", ".tsx", ".js", ".jsx"))
- )
+ tests = sorted({_file(test) for test in tests})
+ python_tests = sorted(test for test in tests if _file(test).endswith(PYTHON_SUFFIXES))
+ js_tests = sorted(test for test in tests if _is_js(test))
commands: list[str] = []
if python_tests:
- commands.append("pytest " + " ".join(python_tests))
- if js_tests:
- commands.append("npm test -- " + " ".join(js_tests))
+ commands.append("pytest " + " ".join(map(_arg, python_tests)))
+ commands.extend(_js_commands(js_tests, packages))
return commands
-__all__ = ["commands_for_tests"]
+__all__ = ["JsPackages", "commands_for_tests", "js_test_packages", "plan_packages"]
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
index 4e99b38e0..adcf5de80 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
@@ -41,7 +41,7 @@ from repowise.core.code_origin import ship_rank
from repowise.core.test_paths import is_test_support_path, names_test_for, paired_test_names
from .annotations import PlanAnnotations, partner_rows
-from .commands import commands_for_tests
+from .commands import JsPackages, commands_for_tests, plan_packages
from .models import RefactoringSuggestion
from .render import list_plan
@@ -309,6 +309,9 @@ class ValidationPlan:
# differs from the plan's, else ``None``; empty when none differs. Kept out
# of :meth:`as_dict`, which every list serves; plan detail reads it.
step_verify: list[dict[str, Any] | None] = field(default_factory=list)
+ # The package each shown JS/TS test runs from (``commands.JsPackages``),
+ # so a later read builds the same commands without a checkout.
+ js_packages: dict[str, str | None] = field(default_factory=dict)
def as_dict(self) -> dict[str, Any]:
return {
@@ -323,6 +326,7 @@ class ValidationPlan:
"targets": [target.as_dict() for target in self.targets],
"reasons": self.reasons,
"prerequisite": self.prerequisite,
+ **({"js_packages": self.js_packages} if self.js_packages else {}),
}
@@ -340,6 +344,7 @@ class ValidationEvidence:
(``function_facts.tests_json``); an absent id was never mapped.
``hubs`` are the files no reach walk passes through (:func:`hub_files`), and
``siblings`` each directory's files, which decide whose test a name is.
+ ``js_packages`` is the package each JS/TS test runs from; absent, from the root.
"""
symbols: Mapping[str, Sequence[SymbolSpan]] = field(default_factory=dict)
@@ -348,6 +353,7 @@ class ValidationEvidence:
function_tests: Mapping[str, tuple[MappedTest, ...]] = field(default_factory=dict)
hubs: frozenset[str] = frozenset()
siblings: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
+ js_packages: JsPackages | None = None
@dataclass(frozen=True, slots=True)
@@ -896,11 +902,13 @@ def build_validation_plan(
reasons = {test.selector: _runs_reason(test, symbol) for test, symbol in direct[:cap]}
# Each quoted test's file, whole: shorter than naming every function,
# and it runs at least the tests the plan quotes.
- commands = commands_for_tests(sorted({test.split("::", 1)[0] for test in shown}))
+ commands = commands_for_tests(
+ sorted({test.split("::", 1)[0] for test in shown}), packages=facts.js_packages
+ )
else:
shown = ordered_tests[:cap]
reasons = {test: best[test][1] for test in shown}
- commands = commands_for_tests(shown, total=aggregate_total)
+ commands = commands_for_tests(shown, total=aggregate_total, packages=facts.js_packages)
files = affected_files(suggestion)
return ValidationPlan(
basis=aggregate_basis,
@@ -913,6 +921,7 @@ def build_validation_plan(
commands=commands,
targets=target_rows,
reasons=reasons if order_tests else {},
+ js_packages=plan_packages(shown, facts.js_packages),
# Also when tests reach the file but none reaches a function it changes.
prerequisite=(
_characterization_step(suggestion)
diff --git a/packages/core/src/repowise/core/ingestion/package_roots.py b/packages/core/src/repowise/core/ingestion/package_roots.py
index 31dd1154a..1efda8caa 100644
--- a/packages/core/src/repowise/core/ingestion/package_roots.py
+++ b/packages/core/src/repowise/core/ingestion/package_roots.py
@@ -26,7 +26,8 @@ Closing that needs glob support in the manifest list, which is its own change.
from __future__ import annotations
import os
-from collections.abc import Callable
+import subprocess
+from collections.abc import Callable, Mapping
from pathlib import Path
from ..fs_walk import walk_repo
@@ -97,6 +98,49 @@ def scan_package_manifests(
checkouts, for a traverser opted into indexing them.
"""
root = Path(repo_root)
+ if is_pruned is not None or not prune_nested_git:
+ return _walk_manifests(root, is_pruned, prune_nested_git)
+ key = (str(root.resolve()), _head_commit(root))
+ if key[1] is None:
+ return _walk_manifests(root, None, True)
+ cached = _SCANS.pop(key, None)
+ if cached is None:
+ cached = _walk_manifests(root, None, True)
+ _SCANS[key] = cached
+ while len(_SCANS) > _SCAN_CACHE_SIZE:
+ del _SCANS[next(iter(_SCANS))]
+ return dict(cached)
+
+
+#: Stock-settings scans by (checkout, HEAD commit), most recent last: health,
+#: the plan finalizers and Fix first share one walk per update, and another
+#: checkout or commit scans again. Ceiling: a manifest added or removed without
+#: a new commit keeps the cached roots until the next commit; upgrade by
+#: keying on the manifests' mtimes if working-tree updates need it.
+_SCANS: dict[tuple[str, str | None], dict[str, frozenset[str]]] = {}
+_SCAN_CACHE_SIZE = 4
+
+
+def _head_commit(root: Path) -> str | None:
+ """The commit *root* is checked out at, or None outside git."""
+ try:
+ done = subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=root,
+ capture_output=True,
+ stdin=subprocess.DEVNULL,
+ text=True,
+ timeout=10,
+ )
+ except (subprocess.TimeoutExpired, OSError):
+ return None
+ sha = done.stdout.strip()
+ return sha if done.returncode == 0 and sha else None
+
+
+def _walk_manifests(
+ root: Path, is_pruned: Callable[[Path], bool] | None, prune_nested_git: bool
+) -> dict[str, frozenset[str]]:
names = package_manifest_names()
prune = is_pruned if is_pruned is not None else _default_prune(root)
roots: dict[str, frozenset[str]] = {}
@@ -149,6 +193,28 @@ def module_for(rel_path: str, package_roots: set[str]) -> str | None:
return head or None
+def owning_package(
+ rel_path: str,
+ manifests: Mapping[str, frozenset[str]],
+ manifest_name: str,
+ accepts: Callable[[str], bool],
+) -> str | None:
+ """The deepest package root above *rel_path* holding *manifest_name* that
+ *accepts* takes, else the repository root (``""``) when it does, else None.
+
+ *manifests* is :func:`scan_package_manifests`'s map, which leaves the root
+ out; *accepts* gets a root directory and reads whatever its language needs
+ from that manifest (a JS test script, say). One lookup for any ecosystem.
+ """
+ roots = {root for root, names in manifests.items() if manifest_name in names}
+ current = rel_path.replace("\\", "/")
+ while (owner := module_for(current, roots)) in roots:
+ if accepts(owner):
+ return owner
+ current = owner
+ return "" if accepts("") else None
+
+
def package_roots_from_paths(all_paths: set[str]) -> set[str]:
"""Package roots inferred from a file list, for callers with no checkout.
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
index 44dcc693a..a92cbaab4 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
@@ -72,7 +72,7 @@ from ...models import (
from ...read_snapshots import decode_or_none, read_snapshot, refresh_snapshot, snapshot_key
from ...sql import json_text
from .plain_rows import plain_rows, row_shape
-from .refactoring_recommendations import validation_inputs
+from .refactoring_recommendations import repository_checkout, validation_inputs
#: Files read for plan-less finding items, by open code-shape deduction.
#: Ceiling: a file past this rank never becomes a finding item. The queue
@@ -460,8 +460,13 @@ async def _finding_validator(
if not spans:
return lambda *_: None
suggestions = [_span_suggestion(p, f.function_name, s, e) for (p, s, e), f in spans.items()]
+ # Built once per store write, so the checkout's package.json reads are too.
inputs = await validation_inputs(
- session, repo_id, suggestions, sorted({s.file_path for s in suggestions})
+ session,
+ repo_id,
+ suggestions,
+ sorted({s.file_path for s in suggestions}),
+ checkout=await repository_checkout(session, repo_id),
)
def validate(path: str, function: Any, start: Any, end: Any) -> dict[str, Any] | None:
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
index 8527e5487..f2c9745c2 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
@@ -360,13 +360,14 @@ async def _plan_facts(
it fell back to an empty profile that read as "no tests" for every plan.
"""
from ....analysis.health.refactoring.recommendations import steps_with_verify
- from .refactoring_recommendations import hydrate_recommendations
+ from .refactoring_recommendations import hydrate_recommendations, repository_checkout
if not rows:
return {}
facts: dict[str, dict[str, Any]] = {}
+ checkout = await repository_checkout(session, repository_id)
for recommendation in await hydrate_recommendations(
- session, repository_id, rows, step_verify=True
+ session, repository_id, rows, step_verify=True, checkout=checkout
):
suggestion = recommendation.suggestion
facts[suggestion.plan["opportunity_id"]] = {
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
index f8545abfd..43da1a493 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
@@ -293,7 +293,7 @@ async def _rank_live_plans(
from ....analysis.health.refactoring.annotations import annotate, load_annotation_facts
from .refactoring import shown_plan_predicate, store_plan_ranks
- from .refactoring_recommendations import hydrate_recommendations
+ from .refactoring_recommendations import hydrate_recommendations, repository_checkout
rows = (
await session.execute(
@@ -304,8 +304,9 @@ async def _rank_live_plans(
)
)
).scalars()
+ checkout = await repository_checkout(session, repository_id)
ranked = await hydrate_recommendations(
- session, repository_id, list(rows), step_verify=True, findings=findings
+ session, repository_id, list(rows), step_verify=True, findings=findings, checkout=checkout
)
facts = await load_annotation_facts(
session,
@@ -317,6 +318,7 @@ async def _rank_live_plans(
if item.suggestion.refactoring_type == "extract_method"
for test in item.validation.tests
],
+ root=checkout,
)
ranked = [
dataclasses.replace(
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py
index 660052c49..91fdab1a2 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py
@@ -8,13 +8,16 @@ never adds SQL statements.
from __future__ import annotations
+import asyncio
import dataclasses
from collections.abc import Mapping, Sequence
+from pathlib import Path
from typing import Any
from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.health.refactoring.commands import JsPackages, js_test_packages
from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
from repowise.core.analysis.health.refactoring.recommendations import (
DEFAULT_TEST_LIMIT,
@@ -45,8 +48,9 @@ from repowise.core.analysis.test_reachability import (
tests_matching_by_name,
tests_reaching_by_tier,
)
+from repowise.core.ingestion.package_roots import scan_package_manifests
-from ...models import GraphMetric, GraphNode, HealthFileMetric
+from ...models import GraphMetric, GraphNode, HealthFileMetric, Repository
from ..graph import get_graph_metrics
from .coverage_map import tests_covering_files
from .function_facts import tests_in_files
@@ -63,6 +67,7 @@ async def hydrate_recommendations(
test_limit: int = DEFAULT_TEST_LIMIT,
step_verify: bool = False,
findings: Sequence[Any] | None = None,
+ checkout: str | None = None,
) -> list[Recommendation]:
"""Hydrate, enrich, validate, rank, and serialize-ready all *rows*.
@@ -74,7 +79,8 @@ async def hydrate_recommendations(
(:func:`with_step_verify`). Finalize asks, so it is stored once; a live
read never rebuilds it and serves the plan-level answer. Finalize also
passes the repository's *findings*, so a plan that leaves a function at
- the break-up bar is marked and ranked after the rest.
+ the break-up bar is marked and ranked after the rest. Index-time callers
+ pass the *checkout*, so each JS/TS test's command runs from its package.
"""
if not rows:
return []
@@ -95,6 +101,7 @@ async def hydrate_recommendations(
test_limit=test_limit,
in_degree=centrality,
step_verify=step_verify,
+ checkout=checkout,
)
recommendations = build_recommendations(
suggestions,
@@ -114,13 +121,14 @@ async def _validation_plans(
test_limit: int,
in_degree: Mapping[str, float] | None = None,
step_verify: bool = False,
+ checkout: str | None = None,
) -> list[ValidationPlan]:
"""One validation plan per suggestion, every read batched across the set."""
target_files = sorted(
{path for suggestion in suggestions for path in affected_files(suggestion)}
)
inputs = await validation_inputs(
- session, repository_id, suggestions, target_files, in_degree=in_degree
+ session, repository_id, suggestions, target_files, in_degree=in_degree, checkout=checkout
)
evidence = await _validation_evidence(
session, repository_id, suggestions, target_files, inputs.test_files, inputs.evidence
@@ -157,10 +165,13 @@ async def validation_inputs(
target_files: Sequence[str],
*,
in_degree: Mapping[str, float] | None = None,
+ checkout: str | None = None,
) -> ValidationInputs:
"""Measured coverage and the tiered reachability walk for every plan's files.
*in_degree* is the stored fan-in a caller already read; without it, read here.
+ With the *checkout*, each JS/TS test's package is read, for the plans to
+ store; without it, commands run from the repository root.
"""
measured = await tests_covering_files(session, repository_id, set(target_files))
@@ -210,6 +221,7 @@ async def validation_inputs(
siblings=_siblings(in_degree),
symbols=await _symbol_spans(session, repository_id, target_files),
function_tests=await tests_in_files(session, repository_id, target_files),
+ js_packages=await _js_packages(checkout, test_files),
),
)
return ValidationInputs(
@@ -250,6 +262,20 @@ async def _validation_evidence(
)
+async def repository_checkout(session: AsyncSession, repository_id: str) -> str | None:
+ """The repository's checkout path, in one read."""
+ return await session.scalar(select(Repository.local_path).where(Repository.id == repository_id))
+
+
+async def _js_packages(checkout: str | None, test_files: set[str]) -> JsPackages | None:
+ root = Path(checkout) if checkout else None
+ if root is None or not root.is_dir():
+ return None
+ # The health pass already scanned this commit's package roots; this reuses it.
+ manifests = await asyncio.to_thread(scan_package_manifests, root)
+ return await asyncio.to_thread(js_test_packages, root, manifests, test_files)
+
+
async def _symbol_spans(
session: AsyncSession, repository_id: str, files: Sequence[str]
) -> dict[str, list[SymbolSpan]]:
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index 1fdbcd941..f8b632dd5 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -43,6 +43,10 @@ export interface RecommendationValidation {
/** Set when no test reaches the change: the step to take before the edit.
* Absent on a payload from an older server. */
prerequisite?: string | null;
+ /** The package directory each shown JS/TS test runs from ("" is the root,
+ * null when none can run it). Absent when the plan was validated without
+ * a checkout or names no JS/TS test. */
+ js_packages?: Record<string, string | null>;
}
/** How a step's tests were found: coverage runs its lines, the graph reaches
diff --git a/tests/unit/cli/test_health_recommendations_checkout.py b/tests/unit/cli/test_health_recommendations_checkout.py
new file mode 100644
index 000000000..9ad8176ab
--- /dev/null
+++ b/tests/unit/cli/test_health_recommendations_checkout.py
@@ -0,0 +1,50 @@
+"""The CLI's plan fallback validates from the checkout, so JS/TS commands run from their package."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands.health_cmd.persist import _load_recommendations
+from repowise.cli.helpers import run_async
+from repowise.core.persistence.crud.analysis import refactoring_recommendations
+
+
+async def _store_repo(repo_path: Path) -> None:
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+
+ (repo_path / ".repowise").mkdir()
+ engine = create_engine(
+ f"sqlite+aiosqlite:///{(repo_path / '.repowise' / 'wiki.db').as_posix()}"
+ )
+ try:
+ await init_db(engine)
+ async with get_session(create_session_factory(engine)) as session:
+ await upsert_repository(session, name="repo", local_path=str(repo_path))
+ finally:
+ await engine.dispose()
+
+
+def test_the_cli_fallback_passes_its_checkout(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
+ root = tmp_path.resolve()
+ run_async(_store_repo(root))
+ seen: dict[str, object] = {}
+
+ async def hydrate(session, repository_id, rows, **kwargs):
+ seen.update(kwargs)
+ return []
+
+ monkeypatch.setattr(refactoring_recommendations, "hydrate_recommendations", hydrate)
+ assert _load_recommendations(root, [], []) == []
+ assert seen["checkout"] == str(root)
diff --git a/tests/unit/health/test_refactoring_commands.py b/tests/unit/health/test_refactoring_commands.py
new file mode 100644
index 000000000..df8facff3
--- /dev/null
+++ b/tests/unit/health/test_refactoring_commands.py
@@ -0,0 +1,175 @@
+"""A plan's JS/TS test command runs from the package whose test script owns the test."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from repowise.core.agent_prompts import render_plan
+from repowise.core.analysis.health.refactoring.batches import stage_batches
+from repowise.core.analysis.health.refactoring.commands import (
+ commands_for_tests,
+ js_test_packages,
+ plan_packages,
+)
+from repowise.core.analysis.health.refactoring.recommendations import (
+ ValidationEvidence,
+ build_validation_plan,
+)
+from repowise.core.analysis.health.refactoring.serving import validation_from_profile
+from repowise.core.analysis.test_reachability import ReachedBy
+from repowise.core.ingestion.package_roots import owning_package, scan_package_manifests
+from tests.unit.health.test_recommendations import _plan
+
+
+def _packages(root: Path, tests: list[str]) -> dict[str, str | None]:
+ return js_test_packages(root, scan_package_manifests(root), tests)
+
+
+def _package(root: Path, directory: str, scripts: dict[str, str] | None = None) -> None:
+ folder = root / directory
+ folder.mkdir(parents=True, exist_ok=True)
+ body = {"name": directory or "root", **({"scripts": scripts} if scripts else {})}
+ (folder / "package.json").write_text(json.dumps(body), encoding="utf-8")
+
+
+NESTED = "ui-tui/src/__tests__/virtualHeights.test.ts"
+
+
+def test_nested_package_runs_from_its_own_directory(tmp_path: Path) -> None:
+ # The root declares workspaces but no test script, as in the reported repo.
+ _package(tmp_path, "", None)
+ _package(tmp_path, "ui-tui", {"test": "vitest run"})
+ packages = _packages(tmp_path, [NESTED])
+ assert packages == {NESTED: "ui-tui"}
+ assert commands_for_tests([NESTED], packages=packages) == [
+ "npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts"
+ ]
+
+
+def test_root_package_keeps_the_root_command(tmp_path: Path) -> None:
+ _package(tmp_path, "", {"test": "jest"})
+ tests = ["src/a.test.ts", "tests/test_b.py"]
+ packages = _packages(tmp_path, tests)
+ assert packages == {"src/a.test.ts": ""}
+ assert commands_for_tests(tests, packages=packages) == [
+ "pytest tests/test_b.py",
+ "npm test -- src/a.test.ts",
+ ]
+
+
+def test_nearest_package_without_a_script_defers_to_the_one_above(tmp_path: Path) -> None:
+ _package(tmp_path, "web", {"test": "vitest run"})
+ _package(tmp_path, "web/packages/ink", None)
+ test = "web/packages/ink/src/x.test.tsx"
+ packages = _packages(tmp_path, [f"{test}::renders"])
+ assert packages == {test: "web"}
+ assert commands_for_tests([f"{test}::renders"], packages=packages) == [
+ "npm --prefix web test -- packages/ink/src/x.test.tsx::renders"
+ ]
+
+
+def test_no_package_with_a_test_script_gets_no_command(tmp_path: Path) -> None:
+ _package(tmp_path, "", {"test": 'echo "Error: no test specified" && exit 1'})
+ _package(tmp_path, "app", {"build": "tsc"})
+ tests = ["app/src/a.test.ts", "tests/test_b.py"]
+ packages = _packages(tmp_path, tests)
+ assert packages == {"app/src/a.test.ts": None}
+ assert commands_for_tests(tests, packages=packages) == ["pytest tests/test_b.py"]
+
+
+def test_two_packages_get_one_command_each(tmp_path: Path) -> None:
+ _package(tmp_path, "web", {"test": "vitest run"})
+ _package(tmp_path, "ui-tui", {"test": "vitest run"})
+ tests = ["web/a.test.ts", NESTED]
+ commands = commands_for_tests(tests, packages=_packages(tmp_path, tests))
+ assert commands == [
+ "npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts",
+ "npm --prefix web test -- a.test.ts",
+ ]
+
+
+def test_without_a_checkout_the_command_runs_from_the_root() -> None:
+ assert commands_for_tests([NESTED]) == [f"npm test -- {NESTED}"]
+ assert plan_packages([NESTED], None) == {}
+
+
+def test_a_test_the_map_does_not_hold_gets_no_command() -> None:
+ assert commands_for_tests(["web/a.test.ts", NESTED], packages={NESTED: "ui-tui"}) == [
+ "npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts"
+ ]
+
+
+def test_suffixes_decide_the_runner_not_substrings() -> None:
+ tests = ["fixtures/data.json", "fixtures/rows.jsonl", "stubs/mod.pyi", "tests/test_a.py"]
+ assert commands_for_tests(tests, packages={}) == ["pytest tests/test_a.py"]
+
+
+def test_a_path_with_a_space_is_quoted() -> None:
+ packages = {"my app/a.test.ts": "my app"}
+ assert commands_for_tests(["my app/a.test.ts", "tests/test b.py"], packages=packages) == [
+ 'pytest "tests/test b.py"',
+ 'npm --prefix "my app" test -- a.test.ts',
+ ]
+
+
+def test_the_plan_stores_its_packages_and_reads_them_back() -> None:
+ suggestion = _plan("estimatedMsgHeight", file_path="ui-tui/src/lib/virtualHeights.ts")
+ inferred = {suggestion.file_path: ReachedBy([NESTED], "import-graph", 1)}
+ plan = build_validation_plan(
+ suggestion, {}, inferred, evidence=ValidationEvidence(js_packages={NESTED: "ui-tui"})
+ )
+ assert plan.commands == ["npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts"]
+ stored = plan.as_dict()
+ assert stored["js_packages"] == {NESTED: "ui-tui"}
+ assert validation_from_profile(stored).js_packages == {NESTED: "ui-tui"}
+ unmapped = build_validation_plan(suggestion, {}, inferred)
+ assert "js_packages" not in unmapped.as_dict()
+
+
+def test_a_plan_no_package_can_run_renders_without_a_run_block() -> None:
+ detail = {
+ "id": "rp_js",
+ "refactoring_type": "extract_method",
+ "file_path": "app/src/a.ts",
+ "target_symbol": "app/src/a.ts::run",
+ "line_start": 1,
+ "line_end": 40,
+ "plan": {},
+ "validation": {
+ "tests": ["app/src/a.test.ts"],
+ "total": 1,
+ "commands": commands_for_tests(["app/src/a.test.ts"], packages={}),
+ "basis": "inferred",
+ },
+ }
+ assert detail["validation"]["commands"] == []
+ text = render_plan(detail)
+ assert "`app/src/a.test.ts`" in text
+ assert "Run:" not in text and "```" not in text
+
+
+def test_a_batch_runs_its_tests_from_the_plans_package() -> None:
+ tests = [f"{NESTED}::case{n}" for n in range(4)]
+ detail = {
+ "refactoring_type": "extract_method",
+ "validation": {
+ "tests": tests,
+ "total": 4,
+ "commands": ["npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts"],
+ "js_packages": {NESTED: "ui-tui"},
+ },
+ }
+ steps = [{"n": n, "action": "extract"} for n in range(1, 8)]
+ batches = stage_batches(detail, steps)
+ assert batches is not None
+ assert batches[0]["commands"] == [
+ "npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts"
+ ]
+
+
+def test_the_owner_lookup_takes_any_manifest() -> None:
+ manifests = {"svc": frozenset({"go.mod"}), "svc/web": frozenset({"package.json"})}
+ assert owning_package("svc/web/a_test.go", manifests, "go.mod", lambda d: True) == "svc"
+ assert owning_package("lib/a_test.go", manifests, "go.mod", lambda d: d == "") == ""
+ assert owning_package("lib/a_test.go", manifests, "go.mod", lambda d: False) is None
diff --git a/tests/unit/ingestion/test_package_roots.py b/tests/unit/ingestion/test_package_roots.py
index 60460c05c..f600758b3 100644
--- a/tests/unit/ingestion/test_package_roots.py
+++ b/tests/unit/ingestion/test_package_roots.py
@@ -167,3 +167,29 @@ def test_a_nested_gitignore_prunes_the_scan(tmp_path):
traverser = FileTraverser(tmp_path)
assert traverser.dir_chain_skipped(Path("packages/tool/.test-fixtures"))
assert traverser.package_root_dirs() == {"packages/tool"}
+
+
+def test_one_commit_is_walked_once_and_a_new_commit_again(tmp_path: Path, monkeypatch) -> None:
+ import subprocess
+
+ import repowise.core.ingestion.package_roots as package_roots
+
+ _write(tmp_path, "web/package.json", '{"name":"web"}')
+ git = ["git", "-c", "user.name=t", "-c", "user.email=t@t"]
+ subprocess.run([*git, "init", "-q"], cwd=tmp_path, check=True)
+ subprocess.run([*git, "add", "-A"], cwd=tmp_path, check=True)
+ subprocess.run([*git, "commit", "-qm", "a"], cwd=tmp_path, check=True)
+ walks: list[Path] = []
+ walk = package_roots._walk_manifests
+ monkeypatch.setattr(package_roots, "_SCANS", {})
+ monkeypatch.setattr(
+ package_roots, "_walk_manifests", lambda root, *a: walks.append(root) or walk(root, *a)
+ )
+ assert package_roots.scan_package_roots(tmp_path) == {"web"}
+ assert package_roots.scan_package_manifests(tmp_path) == {"web": frozenset({"package.json"})}
+ assert len(walks) == 1
+ _write(tmp_path, "api/package.json", '{"name":"api"}')
+ subprocess.run([*git, "add", "-A"], cwd=tmp_path, check=True)
+ subprocess.run([*git, "commit", "-qm", "b"], cwd=tmp_path, check=True)
+ assert package_roots.scan_package_roots(tmp_path) == {"web", "api"}
+ assert len(walks) == 2