From 38c6a4f46ee64f4aef6c594de5a7c87feda2fd4e Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Mon, 30 Nov 2026 11:09:02 +0800 Subject: [PATCH 01/13] Index TypeScript monorepos by member project, not the umbrella root Expand a solution-style root tsconfig to its referenced projects so scip-typescript does not load the whole graph in one process. On a delta, index only the projects that contain the window's files, and fall back to the full set when a shared config or lockfile changes. Closes #1678 Signed-off-by: yuzhou <1991039819@qq.com> --- docs/architecture/code-index-architecture.md | 2 +- scripts/scip_harness/run_typescript_delta.sh | 21 +- scripts/scip_harness/scip_ts_projects.py | 220 ++++++++++++++++++ .../test_run_typescript_delta_umbrella.py | 107 +++++++++ tests/unit/test_scip_ts_projects.py | 105 +++++++++ 5 files changed, 451 insertions(+), 4 deletions(-) create mode 100755 scripts/scip_harness/scip_ts_projects.py create mode 100644 tests/unit/test_run_typescript_delta_umbrella.py create mode 100644 tests/unit/test_scip_ts_projects.py diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index e0c983936f1..cdae53dac05 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -351,7 +351,7 @@ delta gives the same live set. | Producer | Language | Watermark | Workers | How it runs | | ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | | `scip-clang` | C++ | `scip_commit` | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly. | -| `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Whole-workspace index per pass, bounded to the window's files by the converter. | +| `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Indexes named projects, or the members of an umbrella root tsconfig; a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed. The converter still bounds the output to those files. | | `scip-go` | Go | `scip_commit_go` | `code_scip_go_delta` | One build per module (`run_go_monorepo_delta.sh`). | | `scip-python` | Python | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply` | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree. | diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index e735120d1ce..e1e32bd6199 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -12,9 +12,10 @@ # delta; no upload, no watermark read. Exits 0 with no file # when no TypeScript file changed in the window. # -# scip-typescript has no per-file mode — it indexes the workspace (langfuse: -# 4,603 files in ~4 min, a 384 MB index) — so both modes run the full index and -# let the converter's --changed-files bound the DELTA to the window's files. +# scip-typescript has no per-file mode, so a named or discovered project is +# indexed as a whole. A delta still bounds the converted output with +# --changed-files, and only the projects that contain those files are indexed +# unless a shared config or lockfile changed. # # Env: LOOM_API_KEY (writer; upload mode), SCIP_TYPESCRIPT (bin; `npm i -g # @sourcegraph/scip-typescript@0.4.0`, node 22 or 24), PYTHON (venv python), @@ -44,6 +45,11 @@ if [[ -n "${SCIP_TS_PROJECTS:-}" ]]; then read -r -a PROJECTS <<<"$SCIP_TS_PROJECTS" WORKSPACES="" # every target below has a tsconfig; inference would write one into the tree SCIP_TS_PATHS=0 # the dist-export rewrite is for an unbuilt workspace, not named projects +elif discovered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" discover "$CHECKOUT") && [[ -n "$discovered" ]]; then + # umbrella root tsconfig: index member projects instead of loading the root + read -r -a PROJECTS <<<"$discovered" + WORKSPACES="" + SCIP_TS_PATHS=0 fi if [[ -z "${WORKSPACES+x}" ]]; then @@ -136,6 +142,15 @@ CONVERT_ARGS=(--index "$WORK/index.scip" --commit "$HEAD_SHA") if [[ "$BASE" != "--full" ]]; then require_base "$BASE" window_files "$WORK" "$BASE" "$HEAD_SHA" "${TS_GLOBS[@]}" + if [[ ${#PROJECTS[@]} -gt 0 ]]; then + filter_args=() + [[ -s "$WORK/changed.txt" ]] && filter_args+=(--changed-file-list "$WORK/changed.txt") + [[ -s "$WORK/deleted.txt" ]] && filter_args+=(--deleted-file-list "$WORK/deleted.txt") + filtered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" filter "${filter_args[@]}" -- "${PROJECTS[@]}") + if [[ -n "$filtered" ]]; then + read -r -a PROJECTS <<<"$filtered" + fi + fi if [[ ! -s "$WORK/changed.txt" && ! -s "$WORK/deleted.txt" ]]; then echo ">> no TypeScript changes in $BASE..$HEAD_SHA" if [[ -n "${DELTA_OUT:-}" ]]; then exit 0; fi # the worker advances the watermark itself diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py new file mode 100755 index 00000000000..ff098b136a6 --- /dev/null +++ b/scripts/scip_harness/scip_ts_projects.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +"""Discover and narrow TypeScript projects for scip-typescript. + +An umbrella (solution-style) root tsconfig — one that only references other +projects, typically with `"files": []` — cannot be indexed as a single +workspace: scip-typescript loads every referenced project at once and can +exhaust the heap. This helper expands that root to its member project +directories, and on a delta pass keeps only the members that contain a +changed path. A change to a shared config or lockfile falls back to the +full member set. +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +from pathlib import Path + +TS_SUFFIXES = (".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs") +LOCKFILE_NAMES = { + "package-lock.json", + "yarn.lock", + "pnpm-lock.yaml", + "bun.lock", + "bun.lockb", + "npm-shrinkwrap.json", +} +ROOT_SHARED_NAMES = { + "package.json", + "pnpm-workspace.yaml", + "lerna.json", + "nx.json", + "turbo.json", + "rush.json", +} + +_COMMENT_LINE = re.compile(r"^\s*//.*$", re.MULTILINE) +_COMMENT_BLOCK = re.compile(r"/\*.*?\*/", re.DOTALL) +_TRAILING_COMMA = re.compile(r",(\s*[}\]])") + + +def load_tsconfig(path: Path) -> dict: + text = path.read_text(encoding="utf-8") + try: + data = json.loads(text) + except json.JSONDecodeError: + stripped = _COMMENT_BLOCK.sub("", _COMMENT_LINE.sub("", text)) + stripped = _TRAILING_COMMA.sub(r"\1", stripped) + data = json.loads(stripped) + if not isinstance(data, dict): + raise ValueError(f"{path} is not a JSON object") + return data + + +def is_umbrella_tsconfig(data: dict) -> bool: + references = data.get("references") + if not isinstance(references, list) or not references: + return False + files = data.get("files") + include = data.get("include") + if files == [] and include in (None, []): + return True + if files is None and include == []: + return True + return False + + +def _reference_path(entry: object) -> str | None: + if isinstance(entry, str): + return entry + if isinstance(entry, dict) and isinstance(entry.get("path"), str): + return entry["path"] + return None + + +def _project_dir_for_reference(base: Path, rel: str) -> Path | None: + target = (base / rel).resolve() + if target.is_file(): + return target.parent + if target.is_dir(): + return target + # a missing directory still names a project the harness can skip + if rel: + return (base / rel).resolve() + return None + + +def discover_umbrella_projects(checkout: Path, tsconfig: Path | None = None) -> list[str]: + """Member project directories of an umbrella root, or an empty list if + the root tsconfig is a regular project.""" + checkout = checkout.resolve() + root = tsconfig or (checkout / "tsconfig.json") + if not root.is_file(): + return [] + try: + data = load_tsconfig(root) + except (OSError, ValueError, json.JSONDecodeError): + return [] + if not is_umbrella_tsconfig(data): + return [] + return _expand_references(checkout, root, data, seen=set()) + + +def _expand_references(checkout: Path, tsconfig: Path, data: dict, seen: set[Path]) -> list[str]: + checkout = checkout.resolve() + tsconfig = tsconfig.resolve() + if tsconfig in seen: + return [] + seen.add(tsconfig) + base = tsconfig.parent + out: list[str] = [] + for entry in data.get("references") or []: + rel = _reference_path(entry) + if not rel: + continue + project_dir = _project_dir_for_reference(base, rel) + if project_dir is None: + continue + member_tsconfig = project_dir / "tsconfig.json" + if rel.endswith(".json") and (base / rel).is_file(): + member_tsconfig = (base / rel).resolve() + if member_tsconfig.is_file(): + try: + member = load_tsconfig(member_tsconfig) + except (OSError, ValueError, json.JSONDecodeError): + member = {} + if is_umbrella_tsconfig(member): + out.extend(_expand_references(checkout, member_tsconfig, member, seen)) + continue + try: + rel_proj = str(project_dir.relative_to(checkout)) + except ValueError: + continue + if rel_proj in (".", ""): + continue + if rel_proj not in out: + out.append(rel_proj) + return out + + +def posix_path(path: str) -> str: + return path.replace("\\", "/").lstrip("./") + + +def project_owns(project: str, relpath: str) -> bool: + proj = posix_path(project).rstrip("/") + path = posix_path(relpath) + if not proj: + return False + return path == proj or path.startswith(proj + "/") + + +def is_typescript_path(relpath: str) -> bool: + name = posix_path(relpath) + return name.endswith(TS_SUFFIXES) + + +def is_shared_change(relpath: str) -> bool: + path = posix_path(relpath) + name = Path(path).name + if name in LOCKFILE_NAMES: + return True + if "/" in path: + return False + if name in ROOT_SHARED_NAMES: + return True + return name.startswith("tsconfig") and name.endswith(".json") + + +def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> list[str]: + """Projects to index for this window. Shared config/lockfile changes, or + TypeScript changes that sit outside every named project, keep the full set.""" + if not projects: + return [] + if any(is_shared_change(path) for path in changed_paths): + return list(projects) + selected = [ + project + for project in projects + if any(project_owns(project, path) for path in changed_paths) + ] + if not selected and any(is_typescript_path(path) for path in changed_paths): + return list(projects) + return selected + + +def _read_lines(path: Path | None) -> list[str]: + if path is None or not path.is_file(): + return [] + return [line.strip() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="cmd", required=True) + + discover = sub.add_parser("discover", help="print umbrella member directories") + discover.add_argument("checkout", type=Path) + + filt = sub.add_parser("filter", help="narrow projects to the delta's changed paths") + filt.add_argument("--changed-file-list", type=Path) + filt.add_argument("--deleted-file-list", type=Path) + filt.add_argument("projects", nargs="*") + + args = parser.parse_args(argv) + if args.cmd == "discover": + projects = discover_umbrella_projects(args.checkout) + else: + changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) + projects = select_projects_for_delta(list(args.projects), changed) + sys.stdout.write(" ".join(projects)) + if projects: + sys.stdout.write("\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py new file mode 100644 index 00000000000..1d2dd97a77a --- /dev/null +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -0,0 +1,107 @@ +"""run_typescript_delta.sh expands an umbrella root and indexes only the +projects touched by a delta. scip-typescript and the converter are stubs.""" + +from __future__ import annotations + +import json +import os +import subprocess +from pathlib import Path + +_SCRIPT = ( + Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "run_typescript_delta.sh" +) + +_FAKE_SCIP = """#!/usr/bin/env bash +echo "args $*" >>"$CALLS" +while [[ $# -gt 0 ]]; do [[ "$1" == "--output" ]] && : >"$2"; shift; done +""" + +_FAKE_PYTHON = """#!/usr/bin/env bash +# Forward discover/filter to the real helper; stub only the converter. +if [[ "${1-}" == *scip_ts_projects.py ]]; then + exec "$REAL_PYTHON" "$@" +fi +while [[ $# -gt 0 ]]; do [[ "$1" == "--dry-run" ]] && echo '{}' >"$2"; shift; done +""" + + +def _git(cwd: Path, *args: str) -> str: + return subprocess.run( + ["git", "-C", str(cwd), *args], check=True, capture_output=True, text=True + ).stdout.strip() + + +def _repo(tmp_path: Path) -> Path: + repo = tmp_path / "repo" + files = { + "tsconfig.json": json.dumps( + {"files": [], "references": [{"path": "packages/app"}, {"path": "packages/lib"}]} + ), + "packages/app/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/app/src/a.ts": "export const a = 1;\n", + "packages/lib/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/lib/src/b.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + return repo + + +def _run(tmp_path: Path, repo: Path, base: str, head: str) -> str: + bin_dir = tmp_path / "bin" + bin_dir.mkdir(exist_ok=True) + calls = tmp_path / "calls" + for name, body in (("scip-typescript", _FAKE_SCIP), ("python", _FAKE_PYTHON)): + dest = bin_dir / name + dest.write_text(body) + dest.chmod(0o755) + import shutil + + # The wrapper must call the real helper; record its path. + env = { + **os.environ, + "CALLS": str(calls), + "DELTA_OUT": str(tmp_path / "delta.json"), + "PYTHON": str(bin_dir / "python"), + "REAL_PYTHON": shutil.which("python3") or "python3", + "SCIP_TYPESCRIPT": str(bin_dir / "scip-typescript"), + } + # Don't leak a parent SCIP_TS_PROJECTS into the test. + env.pop("SCIP_TS_PROJECTS", None) + subprocess.run( + ["bash", str(_SCRIPT), str(repo), base, head], + env=env, + check=True, + capture_output=True, + text=True, + ) + return calls.read_text() if calls.exists() else "" + + +def test_umbrella_root_is_indexed_as_member_projects(tmp_path: Path) -> None: + repo = _repo(tmp_path) + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + args = next(line for line in log.splitlines() if line.startswith("args ")).split() + assert args[1:4] == ["index", "packages/app", "packages/lib"] + assert "--pnpm-workspaces" not in args + assert "--infer-tsconfig" not in args + + +def test_delta_indexes_only_the_project_that_changed(tmp_path: Path) -> None: + repo = _repo(tmp_path) + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "touch app") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + args = next(line for line in log.splitlines() if line.startswith("args ")).split() + assert "packages/app" in args + assert "packages/lib" not in args diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py new file mode 100644 index 00000000000..042f1e3929c --- /dev/null +++ b/tests/unit/test_scip_ts_projects.py @@ -0,0 +1,105 @@ +"""Umbrella-root discovery and delta project selection for the TypeScript tier.""" + +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path + +_SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_ts_projects.py" +_SPEC = importlib.util.spec_from_file_location("scip_ts_projects", _SCRIPT) +_MOD = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(_MOD) +discover_umbrella_projects = _MOD.discover_umbrella_projects +is_umbrella_tsconfig = _MOD.is_umbrella_tsconfig +load_tsconfig = _MOD.load_tsconfig +select_projects_for_delta = _MOD.select_projects_for_delta + + +def _write(root: Path, rel: str, text: str) -> None: + path = root / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + +def test_solution_style_root_is_an_umbrella() -> None: + assert is_umbrella_tsconfig({"files": [], "references": [{"path": "packages/app"}]}) + assert is_umbrella_tsconfig({"files": [], "include": [], "references": [{"path": "a"}]}) + assert not is_umbrella_tsconfig( + {"files": [], "include": ["src"], "references": [{"path": "a"}]} + ) + assert not is_umbrella_tsconfig({"compilerOptions": {}, "include": ["src"]}) + assert not is_umbrella_tsconfig({"references": [{"path": "packages/app"}]}) + + +def test_load_tsconfig_tolerates_comments_and_trailing_commas(tmp_path: Path) -> None: + path = tmp_path / "tsconfig.json" + path.write_text( + """{ + // solution-style root + "files": [], + "references": [ + { "path": "packages/app" }, + ], +} +""" + ) + data = load_tsconfig(path) + assert data["files"] == [] + assert data["references"][0]["path"] == "packages/app" + + +def test_discover_expands_umbrella_and_nested_umbrellas(tmp_path: Path) -> None: + _write( + tmp_path, + "tsconfig.json", + json.dumps({"files": [], "references": [{"path": "packages/app"}, {"path": "libs"}]}), + ) + _write(tmp_path, "packages/app/tsconfig.json", json.dumps({"include": ["src"]})) + _write( + tmp_path, + "libs/tsconfig.json", + json.dumps({"files": [], "references": [{"path": "core"}, {"path": "util"}]}), + ) + _write(tmp_path, "libs/core/tsconfig.json", json.dumps({"include": ["src"]})) + _write(tmp_path, "libs/util/tsconfig.json", json.dumps({"include": ["src"]})) + assert discover_umbrella_projects(tmp_path) == [ + "packages/app", + "libs/core", + "libs/util", + ] + + +def test_plain_root_tsconfig_is_not_expanded(tmp_path: Path) -> None: + _write(tmp_path, "tsconfig.json", json.dumps({"include": ["src"], "compilerOptions": {}})) + _write(tmp_path, "src/index.ts", "export {}\n") + assert discover_umbrella_projects(tmp_path) == [] + + +def test_delta_keeps_only_projects_that_own_the_changed_files() -> None: + projects = ["packages/app", "packages/lib", "packages/cli"] + assert select_projects_for_delta(projects, ["packages/lib/src/a.ts"]) == ["packages/lib"] + assert select_projects_for_delta( + projects, ["packages/app/src/a.ts", "packages/cli/bin.ts"] + ) == [ + "packages/app", + "packages/cli", + ] + # a sibling with a shared prefix must not pull in packages/app + assert select_projects_for_delta( + ["packages/app", "packages/app-extra"], + ["packages/app-extra/src/a.ts"], + ) == ["packages/app-extra"] + + +def test_shared_config_or_lockfile_keeps_the_full_set() -> None: + projects = ["packages/app", "packages/lib"] + assert select_projects_for_delta(projects, ["package.json"]) == projects + assert select_projects_for_delta(projects, ["tsconfig.base.json"]) == projects + assert select_projects_for_delta(projects, ["packages/app/pnpm-lock.yaml"]) == projects + assert select_projects_for_delta(projects, ["packages/app/package.json"]) == ["packages/app"] + + +def test_non_typescript_changes_do_not_force_a_full_set() -> None: + projects = ["packages/app", "packages/lib"] + assert select_projects_for_delta(projects, ["README.md"]) == [] From 315c4d730d8781f39b9be052eca5996f27422c61 Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Mon, 30 Nov 2026 12:58:09 +0800 Subject: [PATCH 02/13] Fix TypeScript umbrella discovery and delta fallbacks Preserve explicit tsconfig file references through discovery and the indexer invocation. Parse JSONC with string-aware comment stripping so inline comments and paths globs like @/* still expand to members. Pass the full delta window (not only TypeScript globs) into the project filter so a shared config change falls back to every member, and do the same when any changed TypeScript path is unowned. Signed-off-by: yuzhou <1991039819@qq.com> --- docs/architecture/code-index-architecture.md | 2 +- scripts/scip_harness/run_typescript_delta.sh | 13 ++- scripts/scip_harness/scip_ts_projects.py | 96 +++++++++++++++---- .../test_run_typescript_delta_umbrella.py | 79 +++++++++++++++ tests/unit/test_scip_ts_projects.py | 43 +++++++++ 5 files changed, 211 insertions(+), 22 deletions(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index cdae53dac05..1f8ff7cc254 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -351,7 +351,7 @@ delta gives the same live set. | Producer | Language | Watermark | Workers | How it runs | | ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | | `scip-clang` | C++ | `scip_commit` | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly. | -| `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Indexes named projects, or the members of an umbrella root tsconfig; a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed. The converter still bounds the output to those files. | +| `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Indexes named projects, or the members of an umbrella root tsconfig (including explicit tsconfig file references); a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed, or a changed TypeScript path sits outside every member. The converter still bounds the output to the TypeScript window. | | `scip-go` | Go | `scip_commit_go` | `code_scip_go_delta` | One build per module (`run_go_monorepo_delta.sh`). | | `scip-python` | Python | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply` | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree. | diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index e1e32bd6199..b2e2b2cb0c5 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -110,6 +110,11 @@ index_workspace() { fi for proj in "${PROJECTS[@]}"; do proj=${proj%/} + # An umbrella reference may name a tsconfig file (e.g. tsconfig.build.json). + if [[ -f "$proj" ]]; then + targets+=("$proj") + continue + fi [[ -d "$proj" ]] || { echo ">> project $proj is not in the tree — skipped" >&2 continue @@ -143,9 +148,13 @@ if [[ "$BASE" != "--full" ]]; then require_base "$BASE" window_files "$WORK" "$BASE" "$HEAD_SHA" "${TS_GLOBS[@]}" if [[ ${#PROJECTS[@]} -gt 0 ]]; then + # The convert window is TypeScript-only; the project filter also needs + # shared configs and lockfiles so a mixed window falls back to every member. + mkdir -p "$WORK/project-window" + window_files "$WORK/project-window" "$BASE" "$HEAD_SHA" filter_args=() - [[ -s "$WORK/changed.txt" ]] && filter_args+=(--changed-file-list "$WORK/changed.txt") - [[ -s "$WORK/deleted.txt" ]] && filter_args+=(--deleted-file-list "$WORK/deleted.txt") + [[ -s "$WORK/project-window/changed.txt" ]] && filter_args+=(--changed-file-list "$WORK/project-window/changed.txt") + [[ -s "$WORK/project-window/deleted.txt" ]] && filter_args+=(--deleted-file-list "$WORK/project-window/deleted.txt") filtered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" filter "${filter_args[@]}" -- "${PROJECTS[@]}") if [[ -n "$filtered" ]]; then read -r -a PROJECTS <<<"$filtered" diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index ff098b136a6..e322ec13701 100755 --- a/scripts/scip_harness/scip_ts_projects.py +++ b/scripts/scip_harness/scip_ts_projects.py @@ -5,9 +5,9 @@ projects, typically with `"files": []` — cannot be indexed as a single workspace: scip-typescript loads every referenced project at once and can exhaust the heap. This helper expands that root to its member project -directories, and on a delta pass keeps only the members that contain a -changed path. A change to a shared config or lockfile falls back to the -full member set. +directories or explicit tsconfig files, and on a delta pass keeps only the +members that contain a changed path. A change to a shared config or lockfile, +or a TypeScript path that no member owns, falls back to the full member set. """ from __future__ import annotations @@ -36,18 +36,56 @@ "rush.json", } -_COMMENT_LINE = re.compile(r"^\s*//.*$", re.MULTILINE) -_COMMENT_BLOCK = re.compile(r"/\*.*?\*/", re.DOTALL) _TRAILING_COMMA = re.compile(r",(\s*[}\]])") +def strip_jsonc(text: str) -> str: + """Remove // and /* */ comments without treating text inside strings as comments.""" + out: list[str] = [] + i = 0 + n = len(text) + in_str = False + escape = False + while i < n: + ch = text[i] + if in_str: + out.append(ch) + if escape: + escape = False + elif ch == "\\": + escape = True + elif ch == '"': + in_str = False + i += 1 + continue + if ch == '"': + in_str = True + out.append(ch) + i += 1 + continue + if ch == "/" and i + 1 < n and text[i + 1] == "/": + i += 2 + while i < n and text[i] not in "\n\r": + i += 1 + continue + if ch == "/" and i + 1 < n and text[i + 1] == "*": + i += 2 + while i + 1 < n and not (text[i] == "*" and text[i + 1] == "/"): + i += 1 + i = min(i + 2, n) + out.append(" ") + continue + out.append(ch) + i += 1 + return "".join(out) + + def load_tsconfig(path: Path) -> dict: text = path.read_text(encoding="utf-8") try: data = json.loads(text) except json.JSONDecodeError: - stripped = _COMMENT_BLOCK.sub("", _COMMENT_LINE.sub("", text)) - stripped = _TRAILING_COMMA.sub(r"\1", stripped) + stripped = _TRAILING_COMMA.sub(r"\1", strip_jsonc(text)) data = json.loads(stripped) if not isinstance(data, dict): raise ValueError(f"{path} is not a JSON object") @@ -88,8 +126,8 @@ def _project_dir_for_reference(base: Path, rel: str) -> Path | None: def discover_umbrella_projects(checkout: Path, tsconfig: Path | None = None) -> list[str]: - """Member project directories of an umbrella root, or an empty list if - the root tsconfig is a regular project.""" + """Member project directories or explicit tsconfig paths of an umbrella + root, or an empty list if the root tsconfig is a regular project.""" checkout = checkout.resolve() root = tsconfig or (checkout / "tsconfig.json") if not root.is_file(): @@ -115,12 +153,15 @@ def _expand_references(checkout: Path, tsconfig: Path, data: dict, seen: set[Pat rel = _reference_path(entry) if not rel: continue - project_dir = _project_dir_for_reference(base, rel) - if project_dir is None: - continue - member_tsconfig = project_dir / "tsconfig.json" - if rel.endswith(".json") and (base / rel).is_file(): - member_tsconfig = (base / rel).resolve() + explicit = (base / rel).resolve() if rel.endswith(".json") else None + if explicit is not None and explicit.is_file(): + member_tsconfig = explicit + project_dir = explicit.parent + else: + project_dir = _project_dir_for_reference(base, rel) + if project_dir is None: + continue + member_tsconfig = project_dir / "tsconfig.json" if member_tsconfig.is_file(): try: member = load_tsconfig(member_tsconfig) @@ -130,7 +171,10 @@ def _expand_references(checkout: Path, tsconfig: Path, data: dict, seen: set[Pat out.extend(_expand_references(checkout, member_tsconfig, member, seen)) continue try: - rel_proj = str(project_dir.relative_to(checkout)) + if explicit is not None and explicit.is_file(): + rel_proj = str(explicit.relative_to(checkout)) + else: + rel_proj = str(project_dir.relative_to(checkout)) except ValueError: continue if rel_proj in (".", ""): @@ -144,8 +188,17 @@ def posix_path(path: str) -> str: return path.replace("\\", "/").lstrip("./") +def project_scope(project: str) -> str: + """Directory a discovered target owns: the file's parent for an explicit tsconfig.""" + path = posix_path(project).rstrip("/") + if path.endswith(".json"): + parent = str(Path(path).parent) + return "" if parent in (".", "") else posix_path(parent) + return path + + def project_owns(project: str, relpath: str) -> bool: - proj = posix_path(project).rstrip("/") + proj = project_scope(project) path = posix_path(relpath) if not proj: return False @@ -171,7 +224,7 @@ def is_shared_change(relpath: str) -> bool: def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> list[str]: """Projects to index for this window. Shared config/lockfile changes, or - TypeScript changes that sit outside every named project, keep the full set.""" + any TypeScript path that no named project owns, keep the full set.""" if not projects: return [] if any(is_shared_change(path) for path in changed_paths): @@ -181,7 +234,12 @@ def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> for project in projects if any(project_owns(project, path) for path in changed_paths) ] - if not selected and any(is_typescript_path(path) for path in changed_paths): + unowned_ts = [ + path + for path in changed_paths + if is_typescript_path(path) and not any(project_owns(project, path) for project in projects) + ] + if unowned_ts: return list(projects) return selected diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 1d2dd97a77a..d8b926ec5df 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -105,3 +105,82 @@ def test_delta_indexes_only_the_project_that_changed(tmp_path: Path) -> None: args = next(line for line in log.splitlines() if line.startswith("args ")).split() assert "packages/app" in args assert "packages/lib" not in args + + +def test_delta_with_shared_config_indexes_every_member(tmp_path: Path) -> None: + repo = _repo(tmp_path) + (repo / "package.json").write_text('{"name": "root", "private": true}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add package") + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + (repo / "package.json").write_text('{"name": "root", "private": true, "version": "1.0.0"}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "app and package") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + args = next(line for line in log.splitlines() if line.startswith("args ")).split() + assert args[1:4] == ["index", "packages/app", "packages/lib"] + + +def test_inline_jsonc_umbrella_is_expanded(tmp_path: Path) -> None: + repo = _repo(tmp_path) + (repo / "tsconfig.json").write_text( + """{ + "files": [], // solution-style + "compilerOptions": { "paths": { "@/*": ["./src/*"] } }, + "references": [ + { "path": "packages/app" }, + { "path": "packages/lib" }, + ], +} +""" + ) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "jsonc root") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + args = next(line for line in log.splitlines() if line.startswith("args ")).split() + assert args[1:4] == ["index", "packages/app", "packages/lib"] + + +def test_explicit_tsconfig_file_is_passed_to_the_indexer(tmp_path: Path) -> None: + repo = tmp_path / "repo" + files = { + "tsconfig.json": json.dumps( + {"files": [], "references": [{"path": "packages/app/tsconfig.build.json"}]} + ), + "packages/app/tsconfig.build.json": json.dumps( + {"include": ["src/index.ts"], "compilerOptions": {"strict": True}} + ), + "packages/app/src/index.ts": "export const a = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + args = next(line for line in log.splitlines() if line.startswith("args ")).split() + assert "packages/app/tsconfig.build.json" in args + assert "packages/app/tsconfig.scip.json" not in args + assert not (repo / "packages/app/tsconfig.scip.json").exists() + + +def test_delta_with_owned_and_unowned_typescript_indexes_every_member(tmp_path: Path) -> None: + repo = _repo(tmp_path) + (repo / "outside.ts").write_text("export const o = 1;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "outside") + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + (repo / "outside.ts").write_text("export const o = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "mixed") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + args = next(line for line in log.splitlines() if line.startswith("args ")).split() + assert args[1:4] == ["index", "packages/app", "packages/lib"] diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py index 042f1e3929c..f85ce78f78a 100644 --- a/tests/unit/test_scip_ts_projects.py +++ b/tests/unit/test_scip_ts_projects.py @@ -103,3 +103,46 @@ def test_shared_config_or_lockfile_keeps_the_full_set() -> None: def test_non_typescript_changes_do_not_force_a_full_set() -> None: projects = ["packages/app", "packages/lib"] assert select_projects_for_delta(projects, ["README.md"]) == [] + + +def test_load_tsconfig_accepts_inline_comments_and_paths_globs(tmp_path: Path) -> None: + path = tmp_path / "tsconfig.json" + path.write_text( + """{ + "files": [], // umbrella root + "compilerOptions": { + "paths": { "@/*": ["./src/*"] } + }, + "references": [ + { "path": "packages/app" }, /* app */ + ], +} +""" + ) + data = load_tsconfig(path) + assert data["files"] == [] + assert data["compilerOptions"]["paths"]["@/*"] == ["./src/*"] + assert data["references"][0]["path"] == "packages/app" + + +def test_discover_preserves_explicit_tsconfig_file_references(tmp_path: Path) -> None: + _write( + tmp_path, + "tsconfig.json", + json.dumps({"files": [], "references": [{"path": "packages/app/tsconfig.build.json"}]}), + ) + _write( + tmp_path, + "packages/app/tsconfig.build.json", + json.dumps({"include": ["src/index.ts"], "compilerOptions": {"strict": True}}), + ) + assert discover_umbrella_projects(tmp_path) == ["packages/app/tsconfig.build.json"] + + +def test_delta_falls_back_when_any_typescript_path_is_unowned() -> None: + projects = ["packages/app", "packages/lib"] + assert select_projects_for_delta(projects, ["packages/app/src/a.ts", "outside.ts"]) == projects + assert select_projects_for_delta( + ["packages/app/tsconfig.build.json", "packages/lib"], + ["packages/app/src/a.ts"], + ) == ["packages/app/tsconfig.build.json"] From c0d7465c20e6d21512852a0272778adac8a2f663 Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Mon, 30 Nov 2026 17:04:29 +0800 Subject: [PATCH 03/13] Isolate TypeScript member index runs and keep paths with spaces scip-typescript shares its source-file cache across every target in one process, so a full umbrella pass that passed every member as arguments kept the same heap growth as indexing the root. Run one member per process and merge the indexes. Discover and filter print one path per line so a member directory with a space is not split in the shell. Signed-off-by: yuzhou <1991039819@qq.com> --- scripts/scip_harness/run_typescript_delta.sh | 30 ++++- scripts/scip_harness/scip_merge_indexes.py | 62 +++++++++ scripts/scip_harness/scip_ts_projects.py | 7 +- .../test_run_typescript_delta_projects.py | 23 +++- .../test_run_typescript_delta_umbrella.py | 122 +++++++++++++++--- tests/unit/test_scip_merge_indexes.py | 50 +++++++ 6 files changed, 261 insertions(+), 33 deletions(-) create mode 100644 scripts/scip_harness/scip_merge_indexes.py create mode 100644 tests/unit/test_scip_merge_indexes.py diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index b2e2b2cb0c5..3abd9ea116b 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -46,8 +46,9 @@ if [[ -n "${SCIP_TS_PROJECTS:-}" ]]; then WORKSPACES="" # every target below has a tsconfig; inference would write one into the tree SCIP_TS_PATHS=0 # the dist-export rewrite is for an unbuilt workspace, not named projects elif discovered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" discover "$CHECKOUT") && [[ -n "$discovered" ]]; then - # umbrella root tsconfig: index member projects instead of loading the root - read -r -a PROJECTS <<<"$discovered" + # umbrella root tsconfig: index member projects instead of loading the root. + # One path per line (a member directory may contain a space). + mapfile -t PROJECTS <<<"$discovered" WORKSPACES="" SCIP_TS_PATHS=0 fi @@ -138,8 +139,27 @@ JSONEOF done local ws=() [[ -n "$WORKSPACES" ]] && ws=("$WORKSPACES") - NODE_OPTIONS="--max-old-space-size=$NODE_HEAP_MB" \ - "$SCIP_TYPESCRIPT" index "${ws[@]}" "${targets[@]}" --output "$WORK/index.scip" >&2 + # One indexer process per member: scip-typescript walks every target in a + # single process and shares its source-file cache across them, so passing + # the whole umbrella as arguments keeps the same heap growth the root + # pass already hits. Isolated runs drop that cache between members. + local parts=() target part i=0 + if [[ ${#targets[@]} -eq 0 ]]; then + : >"$WORK/index.scip" + return + fi + for target in "${targets[@]}"; do + part="$WORK/index.part.$i.scip" + NODE_OPTIONS="--max-old-space-size=$NODE_HEAP_MB" \ + "$SCIP_TYPESCRIPT" index "${ws[@]}" "$target" --output "$part" >&2 + parts+=("$part") + i=$((i + 1)) + done + if [[ ${#parts[@]} -eq 1 ]]; then + mv "${parts[0]}" "$WORK/index.scip" + else + "$PYTHON" "$HARNESS_DIR/scip_merge_indexes.py" --output "$WORK/index.scip" "${parts[@]}" + fi } cd "$CHECKOUT" @@ -157,7 +177,7 @@ if [[ "$BASE" != "--full" ]]; then [[ -s "$WORK/project-window/deleted.txt" ]] && filter_args+=(--deleted-file-list "$WORK/project-window/deleted.txt") filtered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" filter "${filter_args[@]}" -- "${PROJECTS[@]}") if [[ -n "$filtered" ]]; then - read -r -a PROJECTS <<<"$filtered" + mapfile -t PROJECTS <<<"$filtered" fi fi if [[ ! -s "$WORK/changed.txt" && ! -s "$WORK/deleted.txt" ]]; then diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py new file mode 100644 index 00000000000..127af6b08b8 --- /dev/null +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Merge SCIP Index files into one index. + +Each input is a complete Index (scip-typescript --output). Documents and +external symbols are concatenated; metadata is taken from the first non-empty +input. An all-empty input list, or only empty files, writes a zero-byte +output so the converter treats it as an empty index. +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +_VENDOR = Path(__file__).resolve().parent / "vendor" + + +def _ensure_scip_pb2(): + if str(_VENDOR) not in sys.path: + sys.path.insert(0, str(_VENDOR)) + try: + import scip_pb2 + except Exception as e: # ImportError, or protobuf VersionError + raise SystemExit( + f"cannot load vendor/scip_pb2.py ({e}): merging indexes needs protobuf>=7.35.1" + ) from e + return scip_pb2 + + +def merge_indexes(paths: list[Path], output: Path) -> None: + scip_pb2 = _ensure_scip_pb2() + merged = scip_pb2.Index() + has_payload = False + for path in paths: + data = path.read_bytes() if path.is_file() else b"" + if not data: + continue + idx = scip_pb2.Index() + idx.ParseFromString(data) + if not has_payload and idx.HasField("metadata"): + merged.metadata.CopyFrom(idx.metadata) + merged.documents.extend(idx.documents) + merged.external_symbols.extend(idx.external_symbols) + has_payload = True + if not has_payload: + output.write_bytes(b"") + return + output.write_bytes(merged.SerializeToString()) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("indexes", nargs="+", type=Path) + args = parser.parse_args(argv) + merge_indexes(args.indexes, args.output) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index e322ec13701..d523569eccc 100755 --- a/scripts/scip_harness/scip_ts_projects.py +++ b/scripts/scip_harness/scip_ts_projects.py @@ -268,9 +268,10 @@ def main(argv: list[str] | None = None) -> int: else: changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) projects = select_projects_for_delta(list(args.projects), changed) - sys.stdout.write(" ".join(projects)) - if projects: - sys.stdout.write("\n") + # One path per line so a member whose path contains a space is not split + # by the shell when it loads the list. + for project in projects: + sys.stdout.write(f"{project}\n") return 0 diff --git a/tests/unit/test_run_typescript_delta_projects.py b/tests/unit/test_run_typescript_delta_projects.py index 6cec2be801a..3d5f5a7bd97 100644 --- a/tests/unit/test_run_typescript_delta_projects.py +++ b/tests/unit/test_run_typescript_delta_projects.py @@ -14,7 +14,11 @@ ) _FAKE_SCIP = """#!/usr/bin/env bash -echo "args $*" >>"$CALLS" +{ + printf 'run' + for a in "$@"; do printf '\t%s' "$a"; done + printf '\n' +} >>"$CALLS" for f in plug/tsconfig.scip.json plug/package.json lib/tsconfig.scip.json lib/package.json; do [[ -f "$f" ]] && echo "present $f $(head -c 40 "$f")" >>"$CALLS" done @@ -22,6 +26,9 @@ """ _FAKE_PYTHON = """#!/usr/bin/env bash +case "${1-}" in + *scip_merge_indexes.py|*scip_ts_projects.py) exec "$REAL_PYTHON" "$@" ;; +esac while [[ $# -gt 0 ]]; do [[ "$1" == "--dry-run" ]] && echo '{}' >"$2"; shift; done """ @@ -55,11 +62,14 @@ def test_named_projects_are_indexed_through_their_own_or_a_generated_tsconfig( (bin_dir / name).write_text(body) (bin_dir / name).chmod(0o755) calls = tmp_path / "calls" + import shutil + env = { **os.environ, "CALLS": str(calls), "DELTA_OUT": str(tmp_path / "delta.json"), "PYTHON": str(bin_dir / "python"), + "REAL_PYTHON": shutil.which("python3") or "python3", "SCIP_TYPESCRIPT": str(bin_dir / "scip-typescript"), "SCIP_TS_PROJECTS": "app plug lib missing", } @@ -71,9 +81,14 @@ def test_named_projects_are_indexed_through_their_own_or_a_generated_tsconfig( text=True, ) log = calls.read_text().splitlines() - args = next(line for line in log if line.startswith("args ")).split() - assert args[1:5] == ["index", "app", "plug/tsconfig.scip.json", "lib/tsconfig.scip.json"] - assert "--infer-tsconfig" not in args, "inference writes a tsconfig.json into the tree" + runs = [line.split("\t")[1:] for line in log if line.startswith("run")] + targets = [] + for run in runs: + assert run[0] == "index" + assert run[2] == "--output" + targets.append(run[1]) + assert "--infer-tsconfig" not in run, "inference writes a tsconfig.json into the tree" + assert targets == ["app", "plug/tsconfig.scip.json", "lib/tsconfig.scip.json"] present = {line.split()[1]: line for line in log if line.startswith("present ")} assert set(present) == { "plug/tsconfig.scip.json", diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index d8b926ec5df..8efdabaae36 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -13,15 +13,19 @@ ) _FAKE_SCIP = """#!/usr/bin/env bash -echo "args $*" >>"$CALLS" +{ + printf 'run' + for a in "$@"; do printf '\\t%s' "$a"; done + printf '\\n' +} >>"$CALLS" while [[ $# -gt 0 ]]; do [[ "$1" == "--output" ]] && : >"$2"; shift; done """ _FAKE_PYTHON = """#!/usr/bin/env bash -# Forward discover/filter to the real helper; stub only the converter. -if [[ "${1-}" == *scip_ts_projects.py ]]; then - exec "$REAL_PYTHON" "$@" -fi +# Forward discover/filter/merge to the real helpers; stub only the converter. +case "${1-}" in + *scip_ts_projects.py|*scip_merge_indexes.py) exec "$REAL_PYTHON" "$@" ;; +esac while [[ $# -gt 0 ]]; do [[ "$1" == "--dry-run" ]] && echo '{}' >"$2"; shift; done """ @@ -57,6 +61,7 @@ def _run(tmp_path: Path, repo: Path, base: str, head: str) -> str: bin_dir = tmp_path / "bin" bin_dir.mkdir(exist_ok=True) calls = tmp_path / "calls" + calls.unlink(missing_ok=True) for name, body in (("scip-typescript", _FAKE_SCIP), ("python", _FAKE_PYTHON)): dest = bin_dir / name dest.write_text(body) @@ -84,14 +89,33 @@ def _run(tmp_path: Path, repo: Path, base: str, head: str) -> str: return calls.read_text() if calls.exists() else "" +def _runs(log: str) -> list[list[str]]: + """Indexer invocations, each a list of argv (tabs, so a path may contain a space).""" + runs = [] + for line in log.splitlines(): + if line.startswith("run"): + runs.append(line.split("\t")[1:]) + return runs + + +def _targets(runs: list[list[str]]) -> list[str]: + out = [] + for run in runs: + assert run[0] == "index" + output_at = run.index("--output") + # One process per member: a single target between `index` and `--output`. + assert output_at == 2, run + out.append(run[1]) + return out + + def test_umbrella_root_is_indexed_as_member_projects(tmp_path: Path) -> None: repo = _repo(tmp_path) head = _git(repo, "rev-parse", "HEAD") log = _run(tmp_path, repo, "--full", head) - args = next(line for line in log.splitlines() if line.startswith("args ")).split() - assert args[1:4] == ["index", "packages/app", "packages/lib"] - assert "--pnpm-workspaces" not in args - assert "--infer-tsconfig" not in args + runs = _runs(log) + assert _targets(runs) == ["packages/app", "packages/lib"] + assert all("--pnpm-workspaces" not in run and "--infer-tsconfig" not in run for run in runs) def test_delta_indexes_only_the_project_that_changed(tmp_path: Path) -> None: @@ -102,9 +126,7 @@ def test_delta_indexes_only_the_project_that_changed(tmp_path: Path) -> None: _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "touch app") head = _git(repo, "rev-parse", "HEAD") log = _run(tmp_path, repo, base, head) - args = next(line for line in log.splitlines() if line.startswith("args ")).split() - assert "packages/app" in args - assert "packages/lib" not in args + assert _targets(_runs(log)) == ["packages/app"] def test_delta_with_shared_config_indexes_every_member(tmp_path: Path) -> None: @@ -119,8 +141,7 @@ def test_delta_with_shared_config_indexes_every_member(tmp_path: Path) -> None: _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "app and package") head = _git(repo, "rev-parse", "HEAD") log = _run(tmp_path, repo, base, head) - args = next(line for line in log.splitlines() if line.startswith("args ")).split() - assert args[1:4] == ["index", "packages/app", "packages/lib"] + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] def test_inline_jsonc_umbrella_is_expanded(tmp_path: Path) -> None: @@ -140,8 +161,7 @@ def test_inline_jsonc_umbrella_is_expanded(tmp_path: Path) -> None: _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "jsonc root") head = _git(repo, "rev-parse", "HEAD") log = _run(tmp_path, repo, "--full", head) - args = next(line for line in log.splitlines() if line.startswith("args ")).split() - assert args[1:4] == ["index", "packages/app", "packages/lib"] + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] def test_explicit_tsconfig_file_is_passed_to_the_indexer(tmp_path: Path) -> None: @@ -164,9 +184,7 @@ def test_explicit_tsconfig_file_is_passed_to_the_indexer(tmp_path: Path) -> None _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") head = _git(repo, "rev-parse", "HEAD") log = _run(tmp_path, repo, "--full", head) - args = next(line for line in log.splitlines() if line.startswith("args ")).split() - assert "packages/app/tsconfig.build.json" in args - assert "packages/app/tsconfig.scip.json" not in args + assert _targets(_runs(log)) == ["packages/app/tsconfig.build.json"] assert not (repo / "packages/app/tsconfig.scip.json").exists() @@ -182,5 +200,67 @@ def test_delta_with_owned_and_unowned_typescript_indexes_every_member(tmp_path: _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "mixed") head = _git(repo, "rev-parse", "HEAD") log = _run(tmp_path, repo, base, head) - args = next(line for line in log.splitlines() if line.startswith("args ")).split() - assert args[1:4] == ["index", "packages/app", "packages/lib"] + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] + + +def test_member_path_with_a_space_survives_full_and_delta_passes(tmp_path: Path) -> None: + repo = tmp_path / "repo" + files = { + "tsconfig.json": json.dumps( + { + "files": [], + "references": [{"path": "packages/my app"}, {"path": "packages/lib"}], + } + ), + "packages/my app/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/my app/src/a.ts": "export const a = 1;\n", + "packages/lib/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/lib/src/b.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + assert _targets(_runs(log)) == ["packages/my app", "packages/lib"] + + base = head + (repo / "packages/my app/src/a.ts").write_text("export const a = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "touch spaced") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/my app"] + + +def test_full_pass_starts_one_indexer_process_per_member(tmp_path: Path) -> None: + """A full pass must not hand every member to one scip-typescript process. + + The pinned indexer shares its source-file cache across targets in one + process; isolating runs is what drops that heap between members. + """ + repo = tmp_path / "repo" + references = [] + files: dict[str, str] = {} + names = [f"packages/pkg{i:02d}" for i in range(24)] + for name in names: + references.append({"path": name}) + files[f"{name}/tsconfig.json"] = json.dumps({"include": ["src"]}) + files[f"{name}/src/index.ts"] = "export const n = 1;\n" + files["tsconfig.json"] = json.dumps({"files": [], "references": references}) + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + runs = _runs(log) + assert len(runs) == 24 + assert _targets(runs) == names diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py new file mode 100644 index 00000000000..56c6d07bc53 --- /dev/null +++ b/tests/unit/test_scip_merge_indexes.py @@ -0,0 +1,50 @@ +"""Merge isolated scip-typescript Index files into one index.""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +_SCRIPT = ( + Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_merge_indexes.py" +) +_SPEC = importlib.util.spec_from_file_location("scip_merge_indexes", _SCRIPT) +_MOD = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(_MOD) + + +def _index_with_docs(relative_paths: list[str]) -> bytes: + scip_pb2 = _MOD._ensure_scip_pb2() + idx = scip_pb2.Index() + idx.metadata.project_root = "file:///repo" + for path in relative_paths: + doc = idx.documents.add() + doc.relative_path = path + return idx.SerializeToString() + + +def test_merge_concatenates_documents_and_skips_empty_parts(tmp_path: Path) -> None: + a = tmp_path / "a.scip" + b = tmp_path / "b.scip" + empty = tmp_path / "empty.scip" + a.write_bytes(_index_with_docs(["packages/app/src/a.ts"])) + b.write_bytes(_index_with_docs(["packages/lib/src/b.ts"])) + empty.write_bytes(b"") + out = tmp_path / "merged.scip" + _MOD.merge_indexes([a, empty, b], out) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + assert merged.metadata.project_root == "file:///repo" + assert [d.relative_path for d in merged.documents] == [ + "packages/app/src/a.ts", + "packages/lib/src/b.ts", + ] + + +def test_merge_of_only_empty_files_is_zero_bytes(tmp_path: Path) -> None: + empty = tmp_path / "empty.scip" + empty.write_bytes(b"") + out = tmp_path / "merged.scip" + _MOD.merge_indexes([empty], out) + assert out.read_bytes() == b"" From 7a6c9a271858108c8218b0d39bb39496cb8cceff Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Mon, 30 Nov 2026 18:46:40 +0800 Subject: [PATCH 04/13] Index a regular root TypeScript project as the workspace An empty member list wrote a zero-byte index and skipped scip-typescript, so a checkout with an ordinary root tsconfig produced no compiler symbols. Restore the workspace invocation for that case, and cover a full pass and a one-file delta with the stub indexer. Signed-off-by: yuzhou <1991039819@qq.com> --- docs/architecture/code-index-architecture.md | 10 ++--- scripts/scip_harness/run_typescript_delta.sh | 11 ++++- .../test_run_typescript_delta_umbrella.py | 45 +++++++++++++++++++ tests/unit/test_scip_merge_indexes.py | 4 +- 4 files changed, 61 insertions(+), 9 deletions(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 1f8ff7cc254..564f0763501 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -348,12 +348,12 @@ applies it. Per touched file the apply upserts what the delta emits and tombston file's `scip` rows it no longer emits; a deleted file is tombstoned whole. Re-applying a delta gives the same live set. -| Producer | Language | Watermark | Workers | How it runs | -| ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | -| `scip-clang` | C++ | `scip_commit` | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly. | +| Producer | Language | Watermark | Workers | How it runs | +| ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `scip-clang` | C++ | `scip_commit` | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly. | | `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Indexes named projects, or the members of an umbrella root tsconfig (including explicit tsconfig file references); a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed, or a changed TypeScript path sits outside every member. The converter still bounds the output to the TypeScript window. | -| `scip-go` | Go | `scip_commit_go` | `code_scip_go_delta` | One build per module (`run_go_monorepo_delta.sh`). | -| `scip-python` | Python | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply` | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree. | +| `scip-go` | Go | `scip_commit_go` | `code_scip_go_delta` | One build per module (`run_go_monorepo_delta.sh`). | +| `scip-python` | Python | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply` | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree. | `code/domain/index/compiler_tiers.py` (`TIERS`) is the one table of watermark, label and workers per producer; status handlers and the dashboard read it. A delta worker diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 3abd9ea116b..f4f7eac8067 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -145,7 +145,16 @@ JSONEOF # pass already hits. Isolated runs drop that cache between members. local parts=() target part i=0 if [[ ${#targets[@]} -eq 0 ]]; then - : >"$WORK/index.scip" + # No member list: a regular root tsconfig (or a pnpm/yarn workspace) + # is indexed by invoking scip-typescript on the checkout with only the + # workspace flags. An umbrella whose members were all skipped still + # writes an empty index. + if [[ ${#PROJECTS[@]} -eq 0 ]]; then + NODE_OPTIONS="--max-old-space-size=$NODE_HEAP_MB" \ + "$SCIP_TYPESCRIPT" index "${ws[@]}" --output "$WORK/index.scip" >&2 + else + : >"$WORK/index.scip" + fi return fi for target in "${targets[@]}"; do diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 8efdabaae36..b79ce449792 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -264,3 +264,48 @@ def test_full_pass_starts_one_indexer_process_per_member(tmp_path: Path) -> None runs = _runs(log) assert len(runs) == 24 assert _targets(runs) == names + + +def _root_repo(tmp_path: Path) -> Path: + repo = tmp_path / "repo" + files = { + "tsconfig.json": json.dumps({"compilerOptions": {"strict": True}, "include": ["src"]}), + "src/a.ts": "export const a = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + return repo + + +def _project_args(run: list[str]) -> list[str]: + output_at = run.index("--output") + return [a for a in run[1:output_at] if not a.startswith("-")] + + +def test_regular_root_tsconfig_is_indexed_as_the_workspace_on_a_full_pass(tmp_path: Path) -> None: + repo = _root_repo(tmp_path) + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + runs = _runs(log) + assert len(runs) == 1 + assert runs[0][0] == "index" + assert _project_args(runs[0]) == [] + + +def test_regular_root_tsconfig_is_indexed_as_the_workspace_on_a_delta(tmp_path: Path) -> None: + repo = _root_repo(tmp_path) + base = _git(repo, "rev-parse", "HEAD") + (repo / "src/a.ts").write_text("export const a = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "edit a") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + runs = _runs(log) + assert len(runs) == 1 + assert runs[0][0] == "index" + assert _project_args(runs[0]) == [] diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 56c6d07bc53..a9d9512d364 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -5,9 +5,7 @@ import importlib.util from pathlib import Path -_SCRIPT = ( - Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_merge_indexes.py" -) +_SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_merge_indexes.py" _SPEC = importlib.util.spec_from_file_location("scip_merge_indexes", _SCRIPT) _MOD = importlib.util.module_from_spec(_SPEC) _SPEC.loader.exec_module(_MOD) From 61465f5468be4252339810ff61ad08d08782b93c Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Mon, 30 Nov 2026 18:57:49 +0800 Subject: [PATCH 05/13] Dedupe merged TypeScript indexes and keep hidden member paths Isolated scip-typescript runs follow project references, so a dependency's documents can appear in more than one part. Merge by relative_path and keep the copy from the owning member. posix_path no longer uses lstrip("./"), which was stripping the leading dot from hidden directories such as .storybook. Signed-off-by: yuzhou <1991039819@qq.com> --- scripts/scip_harness/run_typescript_delta.sh | 13 ++-- scripts/scip_harness/scip_merge_indexes.py | 72 ++++++++++++++++--- scripts/scip_harness/scip_ts_projects.py | 6 +- tests/unit/test_scip_merge_indexes.py | 73 +++++++++++++++++++- tests/unit/test_scip_ts_projects.py | 23 ++++++ 5 files changed, 169 insertions(+), 18 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index f4f7eac8067..690fa7f0c45 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -164,11 +164,14 @@ JSONEOF parts+=("$part") i=$((i + 1)) done - if [[ ${#parts[@]} -eq 1 ]]; then - mv "${parts[0]}" "$WORK/index.scip" - else - "$PYTHON" "$HARNESS_DIR/scip_merge_indexes.py" --output "$WORK/index.scip" "${parts[@]}" - fi + # Always merge so a single member that followed project references + # also drops documents it does not own. + local merge_args=() t + for t in "${targets[@]}"; do + merge_args+=(--project "$t") + done + "$PYTHON" "$HARNESS_DIR/scip_merge_indexes.py" --output "$WORK/index.scip" \ + "${merge_args[@]}" "${parts[@]}" } cd "$CHECKOUT" diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 127af6b08b8..556a521d8e6 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -1,22 +1,45 @@ #!/usr/bin/env python3 """Merge SCIP Index files into one index. -Each input is a complete Index (scip-typescript --output). Documents and -external symbols are concatenated; metadata is taken from the first non-empty -input. An all-empty input list, or only empty files, writes a zero-byte -output so the converter treats it as an empty index. +Each input is a complete Index (scip-typescript --output). Documents are +keyed by relative_path so a file emitted by more than one isolated run +appears once. When --project is given for each input, a document is taken +from the member that owns it (the longest matching project scope); that +drops copies a dependent emitted by following TypeScript project +references. Metadata is taken from the first non-empty input. External +symbols are concatenated. An all-empty input list, or only empty files, +writes a zero-byte output so the converter treats it as an empty index. """ from __future__ import annotations import argparse +import importlib.util import sys from pathlib import Path +from typing import Any -_VENDOR = Path(__file__).resolve().parent / "vendor" +_HARNESS = Path(__file__).resolve().parent +_VENDOR = _HARNESS / "vendor" -def _ensure_scip_pb2(): +def _load_ts_projects() -> Any: + spec = importlib.util.spec_from_file_location( + "scip_ts_projects", _HARNESS / "scip_ts_projects.py" + ) + if spec is None or spec.loader is None: + raise SystemExit(f"cannot load {_HARNESS / 'scip_ts_projects.py'}") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +_ts_projects = _load_ts_projects() +project_owns = _ts_projects.project_owns +project_scope = _ts_projects.project_scope + + +def _ensure_scip_pb2() -> Any: if str(_VENDOR) not in sys.path: sys.path.insert(0, str(_VENDOR)) try: @@ -28,11 +51,21 @@ def _ensure_scip_pb2(): return scip_pb2 -def merge_indexes(paths: list[Path], output: Path) -> None: +def _preferred_owner(projects: list[str], relpath: str) -> str | None: + owners = [project for project in projects if project_owns(project, relpath)] + if not owners: + return None + return max(owners, key=lambda project: (len(project_scope(project)), len(project))) + + +def merge_indexes(paths: list[Path], output: Path, projects: list[str] | None = None) -> None: + if projects is not None and len(projects) != len(paths): + raise SystemExit("--project count must match the number of indexes") scip_pb2 = _ensure_scip_pb2() merged = scip_pb2.Index() + documents: dict[str, object] = {} has_payload = False - for path in paths: + for i, path in enumerate(paths): data = path.read_bytes() if path.is_file() else b"" if not data: continue @@ -40,21 +73,40 @@ def merge_indexes(paths: list[Path], output: Path) -> None: idx.ParseFromString(data) if not has_payload and idx.HasField("metadata"): merged.metadata.CopyFrom(idx.metadata) - merged.documents.extend(idx.documents) + project = projects[i] if projects is not None else None + for doc in idx.documents: + rel = doc.relative_path + if projects is not None and project is not None: + owner = _preferred_owner(projects, rel) + if owner is not None and owner != project: + continue + copied = scip_pb2.Document() + copied.CopyFrom(doc) + documents[rel] = copied merged.external_symbols.extend(idx.external_symbols) has_payload = True if not has_payload: output.write_bytes(b"") return + for doc in documents.values(): + merged.documents.append(doc) output.write_bytes(merged.SerializeToString()) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", required=True, type=Path) + parser.add_argument( + "--project", + action="append", + default=[], + help="member path for the corresponding index (same order); " + "documents are kept from the owning member", + ) parser.add_argument("indexes", nargs="+", type=Path) args = parser.parse_args(argv) - merge_indexes(args.indexes, args.output) + projects = args.project or None + merge_indexes(args.indexes, args.output, projects) return 0 diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index d523569eccc..438f8801884 100755 --- a/scripts/scip_harness/scip_ts_projects.py +++ b/scripts/scip_harness/scip_ts_projects.py @@ -185,7 +185,11 @@ def _expand_references(checkout: Path, tsconfig: Path, data: dict, seen: set[Pat def posix_path(path: str) -> str: - return path.replace("\\", "/").lstrip("./") + """Normalize slashes and a `./` prefix; keep a leading hidden-directory dot.""" + path = path.replace("\\", "/") + while path.startswith("./"): + path = path[2:] + return path def project_scope(project: str) -> str: diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index a9d9512d364..dde55b2ecc5 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -11,13 +11,15 @@ _SPEC.loader.exec_module(_MOD) -def _index_with_docs(relative_paths: list[str]) -> bytes: +def _index_with_docs(relative_paths: list[str], texts: list[str] | None = None) -> bytes: scip_pb2 = _MOD._ensure_scip_pb2() idx = scip_pb2.Index() idx.metadata.project_root = "file:///repo" - for path in relative_paths: + for i, path in enumerate(relative_paths): doc = idx.documents.add() doc.relative_path = path + if texts is not None: + doc.text = texts[i] return idx.SerializeToString() @@ -46,3 +48,70 @@ def test_merge_of_only_empty_files_is_zero_bytes(tmp_path: Path) -> None: out = tmp_path / "merged.scip" _MOD.merge_indexes([empty], out) assert out.read_bytes() == b"" + + +def test_merge_drops_referenced_documents_in_favor_of_the_owner(tmp_path: Path) -> None: + dependent = tmp_path / "app.scip" + owner = tmp_path / "lib.scip" + # An isolated run on app still follows the reference into lib. + dependent.write_bytes( + _index_with_docs( + ["packages/app/src/a.ts", "packages/lib/src/b.ts"], + ["from-app", "from-app-ref"], + ) + ) + owner.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["from-lib"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [dependent, owner], + out, + projects=["packages/app", "packages/lib"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == { + "packages/app/src/a.ts": "from-app", + "packages/lib/src/b.ts": "from-lib", + } + + +def test_merge_without_projects_keeps_the_last_copy_of_a_path(tmp_path: Path) -> None: + first = tmp_path / "first.scip" + second = tmp_path / "second.scip" + first.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["first"])) + second.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["second"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([first, second], out) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == ["packages/lib/src/b.ts"] + assert merged.documents[0].text == "second" + + +def test_merge_prefers_the_longest_project_scope(tmp_path: Path) -> None: + app = tmp_path / "app.scip" + widget = tmp_path / "widget.scip" + app.write_bytes( + _index_with_docs( + ["packages/app/src/a.ts", "packages/app/widget/src/w.ts"], + ["app", "from-app"], + ) + ) + widget.write_bytes(_index_with_docs(["packages/app/widget/src/w.ts"], ["from-widget"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [app, widget], + out, + projects=["packages/app", "packages/app/widget"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == { + "packages/app/src/a.ts": "app", + "packages/app/widget/src/w.ts": "from-widget", + } diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py index f85ce78f78a..e3ec39c69e1 100644 --- a/tests/unit/test_scip_ts_projects.py +++ b/tests/unit/test_scip_ts_projects.py @@ -146,3 +146,26 @@ def test_delta_falls_back_when_any_typescript_path_is_unowned() -> None: ["packages/app/tsconfig.build.json", "packages/lib"], ["packages/app/src/a.ts"], ) == ["packages/app/tsconfig.build.json"] + + +def test_posix_path_keeps_a_hidden_member_directory() -> None: + posix_path = _MOD.posix_path + assert posix_path(".storybook") == ".storybook" + assert posix_path("./.storybook/main.ts") == ".storybook/main.ts" + assert posix_path("./packages/app") == "packages/app" + assert posix_path("packages\\app\\src\\a.ts") == "packages/app/src/a.ts" + + +def test_hidden_member_is_not_confused_with_an_unhidden_sibling() -> None: + project_owns = _MOD.project_owns + assert project_owns(".storybook", ".storybook/main.ts") + assert not project_owns("storybook", ".storybook/main.ts") + assert not project_owns(".storybook", "storybook/main.ts") + assert select_projects_for_delta( + [".storybook", "storybook"], + [".storybook/main.ts"], + ) == [".storybook"] + assert select_projects_for_delta( + [".storybook", "storybook"], + ["storybook/src/a.ts"], + ) == ["storybook"] From ff137739bcd34924032ff75df06f102f9a07f4f8 Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Tue, 1 Dec 2026 09:29:51 +0800 Subject: [PATCH 06/13] Keep sibling tsconfig documents and reindex config-only windows Explicit tsconfigs in the same directory share a project scope, so picking an owner by filename dropped the other sibling's documents. When the longest scope is tied, each member keeps what it emitted. A window that only changes a shared config selected every member, then exited before indexing because the TypeScript window was empty. Reindex the selected members and convert the full member indexes so module-resolution changes rebuild compiler rows. Signed-off-by: yuzhou <1991039819@qq.com> --- scripts/scip_harness/run_typescript_delta.sh | 21 +++++++-- scripts/scip_harness/scip_merge_indexes.py | 17 +++++-- .../test_run_typescript_delta_umbrella.py | 44 +++++++++++++++++++ tests/unit/test_scip_merge_indexes.py | 42 ++++++++++++++++++ 4 files changed, 116 insertions(+), 8 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 690fa7f0c45..891fa896421 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -10,7 +10,8 @@ # DELTA_OUT DELTA_OUT=/path/delta.json run_typescript_delta.sh # the in-server worker's mode: index, convert, write the JSON # delta; no upload, no watermark read. Exits 0 with no file -# when no TypeScript file changed in the window. +# when no TypeScript file changed and no shared config or +# lockfile selected members to reindex. # # scip-typescript has no per-file mode, so a named or discovered project is # indexed as a whole. A delta still bounds the converted output with @@ -176,6 +177,7 @@ JSONEOF cd "$CHECKOUT" CONVERT_ARGS=(--index "$WORK/index.scip" --commit "$HEAD_SHA") +CONFIG_ONLY_REBUILD=0 if [[ "$BASE" != "--full" ]]; then require_base "$BASE" window_files "$WORK" "$BASE" "$HEAD_SHA" "${TS_GLOBS[@]}" @@ -190,20 +192,31 @@ if [[ "$BASE" != "--full" ]]; then filtered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" filter "${filter_args[@]}" -- "${PROJECTS[@]}") if [[ -n "$filtered" ]]; then mapfile -t PROJECTS <<<"$filtered" + if [[ ! -s "$WORK/changed.txt" && ! -s "$WORK/deleted.txt" ]]; then + # Shared config or other non-TS change selected members: index them + # and convert the full member indexes so resolution changes rebuild + # compiler rows instead of advancing the watermark with an empty delta. + CONFIG_ONLY_REBUILD=1 + fi fi fi - if [[ ! -s "$WORK/changed.txt" && ! -s "$WORK/deleted.txt" ]]; then + if [[ ! -s "$WORK/changed.txt" && ! -s "$WORK/deleted.txt" && "$CONFIG_ONLY_REBUILD" != "1" ]]; then echo ">> no TypeScript changes in $BASE..$HEAD_SHA" if [[ -n "${DELTA_OUT:-}" ]]; then exit 0; fi # the worker advances the watermark itself echo ">> advancing watermark via empty delta" fi - CONVERT_ARGS+=(--base "$BASE" --changed-files "$WORK/changed.txt" --deleted-files "$WORK/deleted.txt") + if [[ "$CONFIG_ONLY_REBUILD" == "1" ]]; then + echo ">> config-only window — reindexing selected members" + CONVERT_ARGS+=(--base "$BASE") + else + CONVERT_ARGS+=(--base "$BASE" --changed-files "$WORK/changed.txt" --deleted-files "$WORK/deleted.txt") + fi else echo ">> no scip_commit_ts watermark — full TypeScript backfill" CONVERT_ARGS+=(--full) fi -if [[ "$BASE" != "--full" && ! -s "$WORK/changed.txt" ]]; then +if [[ "$BASE" != "--full" && ! -s "$WORK/changed.txt" && "$CONFIG_ONLY_REBUILD" != "1" ]]; then # nothing to read from an index: a zero-byte file is an empty Index, and # the delta carries only the window's deletions : >"$WORK/index.scip" diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 556a521d8e6..59c0e9e1dc6 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -4,9 +4,12 @@ Each input is a complete Index (scip-typescript --output). Documents are keyed by relative_path so a file emitted by more than one isolated run appears once. When --project is given for each input, a document is taken -from the member that owns it (the longest matching project scope); that -drops copies a dependent emitted by following TypeScript project -references. Metadata is taken from the first non-empty input. External +from the member that uniquely owns it (the longest matching project +scope); that drops copies a dependent emitted by following TypeScript +project references. Sibling tsconfigs in the same directory share a +scope, so each keeps the documents it emitted and a path present in more +than one of those indexes keeps the last copy. Metadata is taken from +the first non-empty input. External symbols are concatenated. An all-empty input list, or only empty files, writes a zero-byte output so the converter treats it as an empty index. """ @@ -55,7 +58,13 @@ def _preferred_owner(projects: list[str], relpath: str) -> str | None: owners = [project for project in projects if project_owns(project, relpath)] if not owners: return None - return max(owners, key=lambda project: (len(project_scope(project)), len(project))) + best_scope = max(len(project_scope(project)) for project in owners) + tied = [project for project in owners if len(project_scope(project)) == best_scope] + if len(tied) != 1: + # Sibling explicit tsconfigs share a directory scope; none of them + # is a unique owner, so each keeps the documents it emitted. + return None + return tied[0] def merge_indexes(paths: list[Path], output: Path, projects: list[str] | None = None) -> None: diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index b79ce449792..02bb5c8898e 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -26,6 +26,11 @@ case "${1-}" in *scip_ts_projects.py|*scip_merge_indexes.py) exec "$REAL_PYTHON" "$@" ;; esac +{ + printf 'convert' + for a in "$@"; do printf '\\t%s' "$a"; done + printf '\\n' +} >>"$CALLS" while [[ $# -gt 0 ]]; do [[ "$1" == "--dry-run" ]] && echo '{}' >"$2"; shift; done """ @@ -309,3 +314,42 @@ def test_regular_root_tsconfig_is_indexed_as_the_workspace_on_a_delta(tmp_path: assert len(runs) == 1 assert runs[0][0] == "index" assert _project_args(runs[0]) == [] + + +def test_delta_config_only_reindexes_every_member(tmp_path: Path) -> None: + """A root package.json change must still index members and write a delta.""" + repo = _repo(tmp_path) + (repo / "package.json").write_text('{"name": "root", "private": true}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add package") + base = _git(repo, "rev-parse", "HEAD") + (repo / "package.json").write_text('{"name": "root", "private": true, "version": "1.0.0"}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "bump version") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] + assert (tmp_path / "delta.json").is_file() + convert_lines = [line for line in log.splitlines() if line.startswith("convert")] + assert convert_lines, log + convert_args = convert_lines[-1].split("\t")[1:] + assert "--changed-files" not in convert_args + assert "--deleted-files" not in convert_args + assert "--base" in convert_args + + +def test_delta_with_only_an_unrelated_non_ts_change_skips_the_indexer( + tmp_path: Path, +) -> None: + repo = _repo(tmp_path) + (repo / "README.md").write_text("hello\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "readme") + base = _git(repo, "rev-parse", "HEAD") + (repo / "README.md").write_text("hello world\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "edit readme") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _runs(log) == [] + assert not (tmp_path / "delta.json").exists() diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index dde55b2ecc5..e00574f7a14 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -115,3 +115,45 @@ def test_merge_prefers_the_longest_project_scope(tmp_path: Path) -> None: "packages/app/src/a.ts": "app", "packages/app/widget/src/w.ts": "from-widget", } + + +def test_merge_keeps_documents_from_sibling_tsconfigs(tmp_path: Path) -> None: + """Explicit tsconfigs in one directory share project_scope; unique docs must stay.""" + app = tmp_path / "app.scip" + test = tmp_path / "test.scip" + app.write_bytes(_index_with_docs(["packages/app/src/a.ts"], ["from-app"])) + test.write_bytes(_index_with_docs(["packages/app/src/a.spec.ts"], ["from-test"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [app, test], + out, + projects=["packages/app/tsconfig.app.json", "packages/app/tsconfig.test.json"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == { + "packages/app/src/a.ts": "from-app", + "packages/app/src/a.spec.ts": "from-test", + } + + +def test_merge_sibling_tsconfigs_keep_the_last_copy_of_an_overlapping_path( + tmp_path: Path, +) -> None: + first = tmp_path / "app.scip" + second = tmp_path / "test.scip" + first.write_bytes(_index_with_docs(["packages/app/src/shared.ts"], ["from-app"])) + second.write_bytes(_index_with_docs(["packages/app/src/shared.ts"], ["from-test"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [first, second], + out, + projects=["packages/app/tsconfig.app.json", "packages/app/tsconfig.test.json"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == ["packages/app/src/shared.ts"] + assert merged.documents[0].text == "from-test" From 2c7d09affa5a3392e8974805c599b78cabed2891 Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Tue, 1 Dec 2026 11:05:52 +0800 Subject: [PATCH 07/13] Convert full member indexes on mixed TypeScript windows A shared-config change plus a TypeScript edit indexed every member, but the converter still received only the edited TypeScript path, so compiler rows in the other members could stay stale. Convert the full member indexes in that case and keep TypeScript deletions. A non-config change inside a member, such as a README, no longer selects that member for a full rebuild. Isolated merges also drop documents followed through project references when the owning package is not in the current run. Signed-off-by: yuzhou <1991039819@qq.com> --- scripts/scip_harness/run_typescript_delta.sh | 21 +++++--- scripts/scip_harness/scip_merge_indexes.py | 6 +++ scripts/scip_harness/scip_ts_projects.py | 31 +++++++++++- .../test_run_typescript_delta_umbrella.py | 50 +++++++++++++++++++ tests/unit/test_scip_merge_indexes.py | 18 +++++++ tests/unit/test_scip_ts_projects.py | 14 ++++++ 6 files changed, 131 insertions(+), 9 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 891fa896421..dbe50650c45 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -192,12 +192,12 @@ if [[ "$BASE" != "--full" ]]; then filtered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" filter "${filter_args[@]}" -- "${PROJECTS[@]}") if [[ -n "$filtered" ]]; then mapfile -t PROJECTS <<<"$filtered" - if [[ ! -s "$WORK/changed.txt" && ! -s "$WORK/deleted.txt" ]]; then - # Shared config or other non-TS change selected members: index them - # and convert the full member indexes so resolution changes rebuild - # compiler rows instead of advancing the watermark with an empty delta. - CONFIG_ONLY_REBUILD=1 - fi + fi + # A shared config or lockfile can change resolution in every selected + # member. Convert the full member indexes; keep TypeScript deletions + # so removed files still drop out of the compiler rows. + if "$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" has-shared "${filter_args[@]}"; then + CONFIG_ONLY_REBUILD=1 fi fi if [[ ! -s "$WORK/changed.txt" && ! -s "$WORK/deleted.txt" && "$CONFIG_ONLY_REBUILD" != "1" ]]; then @@ -206,8 +206,15 @@ if [[ "$BASE" != "--full" ]]; then echo ">> advancing watermark via empty delta" fi if [[ "$CONFIG_ONLY_REBUILD" == "1" ]]; then - echo ">> config-only window — reindexing selected members" + if [[ -s "$WORK/changed.txt" || -s "$WORK/deleted.txt" ]]; then + echo ">> mixed window with shared config — converting full member indexes" + else + echo ">> config-only window — reindexing selected members" + fi CONVERT_ARGS+=(--base "$BASE") + if [[ -s "$WORK/deleted.txt" ]]; then + CONVERT_ARGS+=(--deleted-files "$WORK/deleted.txt") + fi else CONVERT_ARGS+=(--base "$BASE" --changed-files "$WORK/changed.txt" --deleted-files "$WORK/deleted.txt") fi diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 59c0e9e1dc6..9734b0dd940 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -86,6 +86,12 @@ def merge_indexes(paths: list[Path], output: Path, projects: list[str] | None = for doc in idx.documents: rel = doc.relative_path if projects is not None and project is not None: + # Keep documents this member owns. Documents followed through + # TypeScript project references into another package are + # dropped even when that package is not in this merge, so a + # subset rebuild cannot overwrite the other package's rows. + if not project_owns(project, rel): + continue owner = _preferred_owner(projects, rel) if owner is not None and owner != project: continue diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index 438f8801884..91240e7e665 100755 --- a/scripts/scip_harness/scip_ts_projects.py +++ b/scripts/scip_harness/scip_ts_projects.py @@ -226,9 +226,26 @@ def is_shared_change(relpath: str) -> bool: return name.startswith("tsconfig") and name.endswith(".json") +def is_project_config_change(relpath: str) -> bool: + """A package manifest, lockfile, or tsconfig that can change resolution.""" + name = Path(posix_path(relpath)).name + if name in LOCKFILE_NAMES or name in ROOT_SHARED_NAMES: + return True + return name.startswith("tsconfig") and name.endswith(".json") + + +def is_index_trigger(relpath: str) -> bool: + """A path that should select its owning member for (re)indexing.""" + return is_typescript_path(relpath) or is_project_config_change(relpath) + + def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> list[str]: """Projects to index for this window. Shared config/lockfile changes, or - any TypeScript path that no named project owns, keep the full set.""" + any TypeScript path that no named project owns, keep the full set. + + A non-TypeScript, non-config change inside a member (a README, for + example) does not select that member. + """ if not projects: return [] if any(is_shared_change(path) for path in changed_paths): @@ -236,7 +253,7 @@ def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> selected = [ project for project in projects - if any(project_owns(project, path) for path in changed_paths) + if any(project_owns(project, path) and is_index_trigger(path) for path in changed_paths) ] unowned_ts = [ path @@ -266,9 +283,19 @@ def main(argv: list[str] | None = None) -> int: filt.add_argument("--deleted-file-list", type=Path) filt.add_argument("projects", nargs="*") + shared = sub.add_parser( + "has-shared", + help="exit 0 if the window contains a shared config or lockfile", + ) + shared.add_argument("--changed-file-list", type=Path) + shared.add_argument("--deleted-file-list", type=Path) + args = parser.parse_args(argv) if args.cmd == "discover": projects = discover_umbrella_projects(args.checkout) + elif args.cmd == "has-shared": + changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) + return 0 if any(is_shared_change(path) for path in changed) else 1 else: changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) projects = select_projects_for_delta(list(args.projects), changed) diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 02bb5c8898e..d44457ce824 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -353,3 +353,53 @@ def test_delta_with_only_an_unrelated_non_ts_change_skips_the_indexer( log = _run(tmp_path, repo, base, head) assert _runs(log) == [] assert not (tmp_path / "delta.json").exists() + + +def _convert_args(log: str) -> list[str]: + convert_lines = [line for line in log.splitlines() if line.startswith("convert")] + assert convert_lines, log + return convert_lines[-1].split("\t")[1:] + + +def test_mixed_window_converts_full_member_indexes_and_keeps_deletions( + tmp_path: Path, +) -> None: + """A root package.json plus a TypeScript edit must not pass --changed-files. + + Both members are indexed because resolution may have changed. The converter + still receives TypeScript deletions so those rows drop out. + """ + repo = _repo(tmp_path) + (repo / "package.json").write_text('{"name": "root", "private": true}\n') + (repo / "packages/app/src/gone.ts").write_text("export const gone = 1;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add package and gone") + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + (repo / "packages/app/src/gone.ts").unlink() + (repo / "package.json").write_text('{"name": "root", "private": true, "version": "1.0.0"}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "mixed window") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] + convert_args = _convert_args(log) + assert "--changed-files" not in convert_args + assert "--base" in convert_args + assert "--deleted-files" in convert_args + + +def test_member_readme_change_skips_the_indexer(tmp_path: Path) -> None: + repo = _repo(tmp_path) + readme = repo / "packages/app/README.md" + readme.write_text("hello\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add member readme") + base = _git(repo, "rev-parse", "HEAD") + readme.write_text("hello world\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "edit member readme") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _runs(log) == [] + assert not (tmp_path / "delta.json").exists() diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index e00574f7a14..c8edf95cf33 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -157,3 +157,21 @@ def test_merge_sibling_tsconfigs_keep_the_last_copy_of_an_overlapping_path( merged.ParseFromString(out.read_bytes()) assert [d.relative_path for d in merged.documents] == ["packages/app/src/shared.ts"] assert merged.documents[0].text == "from-test" + + +def test_merge_drops_unowned_references_when_the_owner_is_absent(tmp_path: Path) -> None: + """A subset rebuild must not keep documents from a package that was not indexed.""" + dependent = tmp_path / "app.scip" + dependent.write_bytes( + _index_with_docs( + ["packages/app/src/a.ts", "packages/lib/src/b.ts"], + ["from-app", "from-app-ref"], + ) + ) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([dependent], out, projects=["packages/app"]) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"packages/app/src/a.ts": "from-app"} diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py index e3ec39c69e1..cd1f9b720a6 100644 --- a/tests/unit/test_scip_ts_projects.py +++ b/tests/unit/test_scip_ts_projects.py @@ -169,3 +169,17 @@ def test_hidden_member_is_not_confused_with_an_unhidden_sibling() -> None: [".storybook", "storybook"], ["storybook/src/a.ts"], ) == ["storybook"] + + +def test_member_readme_does_not_select_its_project() -> None: + projects = ["packages/app", "packages/lib"] + assert select_projects_for_delta(projects, ["packages/app/README.md"]) == [] + assert select_projects_for_delta( + projects, ["packages/app/README.md", "packages/lib/src/b.ts"] + ) == ["packages/lib"] + + +def test_member_package_json_still_selects_its_project() -> None: + projects = ["packages/app", "packages/lib"] + assert select_projects_for_delta(projects, ["packages/app/package.json"]) == ["packages/app"] + assert select_projects_for_delta(projects, ["packages/app/tsconfig.json"]) == ["packages/app"] From 2eade0f94ddd197a0e9443f21f8c3ad34f9d369f Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Tue, 1 Dec 2026 13:12:44 +0800 Subject: [PATCH 08/13] Keep documents from root-level tsconfigs and rebuild on member config changes A root-level explicit tsconfig such as tsconfig.app.json had an empty project_scope, so merge dropped every document and deltas only kept those members via the unowned fallback. Own the checkout root instead. A nested tsconfig or package.json change selected its member but still took the empty TypeScript-window exit, or passed --changed-files on a mixed window. Treat any project-config change as a config rebuild. Signed-off-by: yuzhou <1991039819@qq.com> --- scripts/scip_harness/run_typescript_delta.sh | 11 +++--- scripts/scip_harness/scip_ts_projects.py | 23 ++++++++++-- .../test_run_typescript_delta_umbrella.py | 34 ++++++++++++++++++ tests/unit/test_scip_merge_indexes.py | 36 +++++++++++++++++++ tests/unit/test_scip_ts_projects.py | 23 ++++++++++++ 5 files changed, 120 insertions(+), 7 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index dbe50650c45..d289f68b537 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -193,10 +193,11 @@ if [[ "$BASE" != "--full" ]]; then if [[ -n "$filtered" ]]; then mapfile -t PROJECTS <<<"$filtered" fi - # A shared config or lockfile can change resolution in every selected - # member. Convert the full member indexes; keep TypeScript deletions - # so removed files still drop out of the compiler rows. - if "$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" has-shared "${filter_args[@]}"; then + # A package manifest, lockfile, or tsconfig — at the root or in a + # selected member — can change resolution. Convert the full member + # indexes; keep TypeScript deletions so removed files still drop out + # of the compiler rows. + if "$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" has-config "${filter_args[@]}"; then CONFIG_ONLY_REBUILD=1 fi fi @@ -207,7 +208,7 @@ if [[ "$BASE" != "--full" ]]; then fi if [[ "$CONFIG_ONLY_REBUILD" == "1" ]]; then if [[ -s "$WORK/changed.txt" || -s "$WORK/deleted.txt" ]]; then - echo ">> mixed window with shared config — converting full member indexes" + echo ">> mixed window with a config change — converting full member indexes" else echo ">> config-only window — reindexing selected members" fi diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index 91240e7e665..48a1d08e210 100755 --- a/scripts/scip_harness/scip_ts_projects.py +++ b/scripts/scip_harness/scip_ts_projects.py @@ -193,11 +193,18 @@ def posix_path(path: str) -> str: def project_scope(project: str) -> str: - """Directory a discovered target owns: the file's parent for an explicit tsconfig.""" + """Directory a discovered target owns: the file's parent for an explicit tsconfig. + + A root-level file such as tsconfig.app.json owns the checkout root ('.'). + An empty scope would make project_owns reject every document, and merge + would drop the index for the common Vite/Angular solution-style layout. + """ path = posix_path(project).rstrip("/") if path.endswith(".json"): parent = str(Path(path).parent) - return "" if parent in (".", "") else posix_path(parent) + if parent in (".", ""): + return "." + return posix_path(parent) return path @@ -206,6 +213,8 @@ def project_owns(project: str, relpath: str) -> bool: path = posix_path(relpath) if not proj: return False + if proj == ".": + return True return path == proj or path.startswith(proj + "/") @@ -290,12 +299,22 @@ def main(argv: list[str] | None = None) -> int: shared.add_argument("--changed-file-list", type=Path) shared.add_argument("--deleted-file-list", type=Path) + config = sub.add_parser( + "has-config", + help="exit 0 if the window contains a package manifest, lockfile, or tsconfig", + ) + config.add_argument("--changed-file-list", type=Path) + config.add_argument("--deleted-file-list", type=Path) + args = parser.parse_args(argv) if args.cmd == "discover": projects = discover_umbrella_projects(args.checkout) elif args.cmd == "has-shared": changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) return 0 if any(is_shared_change(path) for path in changed) else 1 + elif args.cmd == "has-config": + changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) + return 0 if any(is_project_config_change(path) for path in changed) else 1 else: changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) projects = select_projects_for_delta(list(args.projects), changed) diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index d44457ce824..4860fd501ac 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -403,3 +403,37 @@ def test_member_readme_change_skips_the_indexer(tmp_path: Path) -> None: log = _run(tmp_path, repo, base, head) assert _runs(log) == [] assert not (tmp_path / "delta.json").exists() + + +def test_delta_member_tsconfig_only_reindexes_that_member(tmp_path: Path) -> None: + """A nested tsconfig change must not take the empty-delta early exit.""" + repo = _repo(tmp_path) + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/tsconfig.json").write_text(json.dumps({"include": ["src", "extra"]})) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "member tsconfig") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app"] + assert (tmp_path / "delta.json").is_file() + convert_args = _convert_args(log) + assert "--changed-files" not in convert_args + assert "--base" in convert_args + + +def test_mixed_member_tsconfig_and_typescript_converts_full_member_index( + tmp_path: Path, +) -> None: + """A member tsconfig plus a TypeScript edit must not pass --changed-files.""" + repo = _repo(tmp_path) + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/tsconfig.json").write_text(json.dumps({"include": ["src", "extra"]})) + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "member config and ts") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app"] + convert_args = _convert_args(log) + assert "--changed-files" not in convert_args + assert "--base" in convert_args diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index c8edf95cf33..60d1e39eb9f 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -175,3 +175,39 @@ def test_merge_drops_unowned_references_when_the_owner_is_absent(tmp_path: Path) merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} assert docs == {"packages/app/src/a.ts": "from-app"} + + +def test_merge_keeps_documents_from_a_root_level_tsconfig(tmp_path: Path) -> None: + """A root tsconfig.app.json must not have its documents dropped as unowned.""" + app = tmp_path / "app.scip" + app.write_bytes(_index_with_docs(["src/main.ts"], ["from-app"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([app], out, projects=["tsconfig.app.json"]) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"src/main.ts": "from-app"} + + +def test_merge_prefers_a_nested_member_over_a_root_tsconfig(tmp_path: Path) -> None: + root = tmp_path / "root.scip" + app = tmp_path / "app.scip" + root.write_bytes( + _index_with_docs( + ["src/main.ts", "packages/app/src/a.ts"], + ["from-root", "from-root-ref"], + ) + ) + app.write_bytes(_index_with_docs(["packages/app/src/a.ts"], ["from-app"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [root, app], + out, + projects=["tsconfig.app.json", "packages/app"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"src/main.ts": "from-root", "packages/app/src/a.ts": "from-app"} diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py index cd1f9b720a6..98cf5f5bab7 100644 --- a/tests/unit/test_scip_ts_projects.py +++ b/tests/unit/test_scip_ts_projects.py @@ -183,3 +183,26 @@ def test_member_package_json_still_selects_its_project() -> None: projects = ["packages/app", "packages/lib"] assert select_projects_for_delta(projects, ["packages/app/package.json"]) == ["packages/app"] assert select_projects_for_delta(projects, ["packages/app/tsconfig.json"]) == ["packages/app"] + + +def test_root_level_tsconfig_owns_documents_at_the_checkout_root() -> None: + """Vite/Angular roots use tsconfig.app.json at the checkout root.""" + assert _MOD.project_scope("tsconfig.app.json") == "." + assert _MOD.project_scope("packages/app/tsconfig.app.json") == "packages/app" + owns = _MOD.project_owns + assert owns("tsconfig.app.json", "src/main.ts") + assert owns("tsconfig.app.json", "main.ts") + # Root scope covers nested paths too; merge prefers a longer member scope. + assert owns("tsconfig.app.json", "packages/app/src/a.ts") + assert owns("packages/app/tsconfig.app.json", "packages/app/src/a.ts") + assert not owns("packages/app/tsconfig.app.json", "src/main.ts") + + +def test_delta_selects_a_root_tsconfig_for_a_root_source_change() -> None: + projects = ["tsconfig.app.json", "packages/lib"] + assert select_projects_for_delta(projects, ["src/main.ts"]) == ["tsconfig.app.json"] + # The root tsconfig also owns packages/lib; merge prefers the longer scope. + assert select_projects_for_delta(projects, ["packages/lib/src/b.ts"]) == [ + "tsconfig.app.json", + "packages/lib", + ] From 6e7231225dfd1940301e79f28f361249f6e2a2e4 Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Tue, 1 Dec 2026 14:07:31 +0800 Subject: [PATCH 09/13] Drop followed root-tsconfig docs and skip unowned config rebuilds A root-level tsconfig owns every path, so a subset rebuild that indexes it alone could keep documents followed into other packages. Merge now uses the full discovered member set for ownership and drops those rows when a more specific member exists. An unowned package.json or tsconfig no longer leaves the filter empty while keeping the full project list, so it takes the empty-delta exit instead of reindexing every member. Signed-off-by: yuzhou <1991039819@qq.com> --- scripts/scip_harness/run_typescript_delta.sh | 19 +++++++++++--- scripts/scip_harness/scip_merge_indexes.py | 24 +++++++++++++++--- .../test_run_typescript_delta_umbrella.py | 18 +++++++++++++ tests/unit/test_scip_merge_indexes.py | 25 +++++++++++++++++++ 4 files changed, 79 insertions(+), 7 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index d289f68b537..3372a0eb74b 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -53,6 +53,9 @@ elif discovered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" discover "$CHECKO WORKSPACES="" SCIP_TS_PATHS=0 fi +# Ownership uses the full discovered set even when a delta indexes a subset, +# so a root-level tsconfig cannot keep documents a more specific member owns. +ALL_PROJECTS=("${PROJECTS[@]}") if [[ -z "${WORKSPACES+x}" ]]; then if [[ -f "$CHECKOUT/pnpm-workspace.yaml" ]]; then @@ -171,6 +174,9 @@ JSONEOF for t in "${targets[@]}"; do merge_args+=(--project "$t") done + for t in "${ALL_PROJECTS[@]}"; do + merge_args+=(--known-project "$t") + done "$PYTHON" "$HARNESS_DIR/scip_merge_indexes.py" --output "$WORK/index.scip" \ "${merge_args[@]}" "${parts[@]}" } @@ -192,12 +198,17 @@ if [[ "$BASE" != "--full" ]]; then filtered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" filter "${filter_args[@]}" -- "${PROJECTS[@]}") if [[ -n "$filtered" ]]; then mapfile -t PROJECTS <<<"$filtered" + else + # An empty filter is a real empty selection (e.g. an unowned + # package.json). Do not keep the full member set. + PROJECTS=() fi - # A package manifest, lockfile, or tsconfig — at the root or in a - # selected member — can change resolution. Convert the full member + # A package manifest, lockfile, or tsconfig in a selected member (or a + # shared root config) can change resolution. Convert the full selected # indexes; keep TypeScript deletions so removed files still drop out - # of the compiler rows. - if "$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" has-config "${filter_args[@]}"; then + # of the compiler rows. An unowned config does not rebuild anyone. + if [[ ${#PROJECTS[@]} -gt 0 ]] && \ + "$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" has-config "${filter_args[@]}"; then CONFIG_ONLY_REBUILD=1 fi fi diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 9734b0dd940..111dfdee63f 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -67,7 +67,12 @@ def _preferred_owner(projects: list[str], relpath: str) -> str | None: return tied[0] -def merge_indexes(paths: list[Path], output: Path, projects: list[str] | None = None) -> None: +def merge_indexes( + paths: list[Path], + output: Path, + projects: list[str] | None = None, + known_projects: list[str] | None = None, +) -> None: if projects is not None and len(projects) != len(paths): raise SystemExit("--project count must match the number of indexes") scip_pb2 = _ensure_scip_pb2() @@ -90,9 +95,13 @@ def merge_indexes(paths: list[Path], output: Path, projects: list[str] | None = # TypeScript project references into another package are # dropped even when that package is not in this merge, so a # subset rebuild cannot overwrite the other package's rows. + # known_projects is the full discovered set: a root-level + # tsconfig owns every path, so ownership still prefers a + # longer member that was not indexed in this run. if not project_owns(project, rel): continue - owner = _preferred_owner(projects, rel) + owners = known_projects if known_projects is not None else projects + owner = _preferred_owner(owners, rel) if owner is not None and owner != project: continue copied = scip_pb2.Document() @@ -118,10 +127,19 @@ def main(argv: list[str] | None = None) -> int: help="member path for the corresponding index (same order); " "documents are kept from the owning member", ) + parser.add_argument( + "--known-project", + action="append", + default=[], + help="full discovered member set used for ownership; a document is " + "dropped when a more specific member owns it, even if that member " + "was not indexed in this run", + ) parser.add_argument("indexes", nargs="+", type=Path) args = parser.parse_args(argv) projects = args.project or None - merge_indexes(args.indexes, args.output, projects) + known = args.known_project or None + merge_indexes(args.indexes, args.output, projects, known) return 0 diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 4860fd501ac..1890760170b 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -437,3 +437,21 @@ def test_mixed_member_tsconfig_and_typescript_converts_full_member_index( convert_args = _convert_args(log) assert "--changed-files" not in convert_args assert "--base" in convert_args + + +def test_unowned_package_json_skips_the_indexer(tmp_path: Path) -> None: + """A config path no member owns must not reindex the full member set.""" + repo = _repo(tmp_path) + other = repo / "tools/cli/package.json" + other.parent.mkdir(parents=True, exist_ok=True) + other.write_text('{"name": "cli"}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add unowned package") + base = _git(repo, "rev-parse", "HEAD") + other.write_text('{"name": "cli", "version": "1.0.0"}\n') + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "edit unowned package") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _runs(log) == [] + assert not (tmp_path / "delta.json").exists() diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 60d1e39eb9f..6c85df3d383 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -211,3 +211,28 @@ def test_merge_prefers_a_nested_member_over_a_root_tsconfig(tmp_path: Path) -> N merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} assert docs == {"src/main.ts": "from-root", "packages/app/src/a.ts": "from-app"} + + +def test_merge_drops_followed_docs_from_a_root_tsconfig_when_the_member_is_absent( + tmp_path: Path, +) -> None: + """A subset rebuild of tsconfig.app.json must not keep packages/app rows.""" + root = tmp_path / "root.scip" + root.write_bytes( + _index_with_docs( + ["src/main.ts", "packages/app/src/a.ts"], + ["from-root", "from-root-ref"], + ) + ) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [root], + out, + projects=["tsconfig.app.json"], + known_projects=["tsconfig.app.json", "packages/app"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"src/main.ts": "from-root"} From 9dd7f4279d84ae0c6babf35db2173242fa41a819 Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Tue, 1 Dec 2026 15:33:02 +0800 Subject: [PATCH 10/13] Format the has-config guard the way shfmt expects The format job failed on `&& \` at the end of the line. Move the operator to the continued line so `shfmt -d` is clean. Signed-off-by: yuzhou <1991039819@qq.com> --- scripts/scip_harness/run_typescript_delta.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 3372a0eb74b..2353888518d 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -207,8 +207,8 @@ if [[ "$BASE" != "--full" ]]; then # shared root config) can change resolution. Convert the full selected # indexes; keep TypeScript deletions so removed files still drop out # of the compiler rows. An unowned config does not rebuild anyone. - if [[ ${#PROJECTS[@]} -gt 0 ]] && \ - "$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" has-config "${filter_args[@]}"; then + if [[ ${#PROJECTS[@]} -gt 0 ]] \ + && "$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" has-config "${filter_args[@]}"; then CONFIG_ONLY_REBUILD=1 fi fi From 53f1006a649ddeb37f261951e8115f7de505d45f Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Tue, 1 Dec 2026 16:29:43 +0800 Subject: [PATCH 11/13] Keep merge docs when a generated tsconfig.scip.json matches a known dir Ownership compared the raw --project and --known-project strings, so a member named dir/tsconfig.scip.json dropped every document when the known project was dir. Compare project_scope instead. Signed-off-by: yuzhou <1991039819@qq.com> --- scripts/scip_harness/scip_merge_indexes.py | 5 ++++- tests/unit/test_scip_merge_indexes.py | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 111dfdee63f..36cf28ab9cd 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -102,7 +102,10 @@ def merge_indexes( continue owners = known_projects if known_projects is not None else projects owner = _preferred_owner(owners, rel) - if owner is not None and owner != project: + # Compare scopes, not raw project strings: a generated + # member target is dir/tsconfig.scip.json, while + # --known-project still names dir. + if owner is not None and project_scope(owner) != project_scope(project): continue copied = scip_pb2.Document() copied.CopyFrom(doc) diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 6c85df3d383..80839584585 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -236,3 +236,23 @@ def test_merge_drops_followed_docs_from_a_root_tsconfig_when_the_member_is_absen merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} assert docs == {"src/main.ts": "from-root"} + + +def test_merge_keeps_docs_when_project_is_a_generated_tsconfig_scip_json( + tmp_path: Path, +) -> None: + """A member named dir/tsconfig.scip.json must match known-project dir.""" + app = tmp_path / "app.scip" + app.write_bytes(_index_with_docs(["packages/app/src/a.ts"], ["from-app"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [app], + out, + projects=["packages/app/tsconfig.scip.json"], + known_projects=["packages/app"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"packages/app/src/a.ts": "from-app"} From e8fbb336d0d1da4c2d824f31e8dae8e77c5a93a5 Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Tue, 1 Dec 2026 17:03:19 +0800 Subject: [PATCH 12/13] Keep the most specific directory when sibling tsconfigs tie With a root tsconfig and two explicit configs under packages/app, _preferred_owner returned None on the tie, so a root index merged last could replace the app document. Return a longest-scope owner so sibling configs still keep their docs and the root is dropped. Signed-off-by: yuzhou <1991039819@qq.com> --- scripts/scip_harness/scip_merge_indexes.py | 7 ++--- tests/unit/test_scip_merge_indexes.py | 36 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 36cf28ab9cd..1f34074c012 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -60,10 +60,9 @@ def _preferred_owner(projects: list[str], relpath: str) -> str | None: return None best_scope = max(len(project_scope(project)) for project in owners) tied = [project for project in owners if len(project_scope(project)) == best_scope] - if len(tied) != 1: - # Sibling explicit tsconfigs share a directory scope; none of them - # is a unique owner, so each keeps the documents it emitted. - return None + # Sibling explicit tsconfigs share a directory scope. Returning one of + # them still lets each sibling keep its documents (scopes match) while + # a shorter ancestor, such as a root tsconfig, is dropped. return tied[0] diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 80839584585..17de82eb56c 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -256,3 +256,39 @@ def test_merge_keeps_docs_when_project_is_a_generated_tsconfig_scip_json( merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} assert docs == {"packages/app/src/a.ts": "from-app"} + + +def test_merge_drops_root_docs_when_sibling_app_configs_share_the_owner_scope( + tmp_path: Path, +) -> None: + """A root index merged last must not replace docs from a more specific dir.""" + app = tmp_path / "app.scip" + test = tmp_path / "test.scip" + root = tmp_path / "root.scip" + app.write_bytes(_index_with_docs(["packages/app/src/a.ts"], ["from-app"])) + test.write_bytes(_index_with_docs(["packages/app/src/a.spec.ts"], ["from-test"])) + root.write_bytes( + _index_with_docs( + ["src/main.ts", "packages/app/src/a.ts"], + ["from-root", "from-root-ref"], + ) + ) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [app, test, root], + out, + projects=[ + "packages/app/tsconfig.app.json", + "packages/app/tsconfig.test.json", + "tsconfig.app.json", + ], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == { + "packages/app/src/a.ts": "from-app", + "packages/app/src/a.spec.ts": "from-test", + "src/main.ts": "from-root", + } From d848bd1a740db2e082683986b45df91f26e619aa Mon Sep 17 00:00:00 2001 From: yuzhou <1991039819@qq.com> Date: Tue, 1 Dec 2026 18:40:56 +0800 Subject: [PATCH 13/13] Prefer a one-character member over a root tsconfig on a length tie A root scope '.' has string length 1, the same as a one-character member directory. Treating the root as specificity 0 keeps the member's documents even when the root is listed first. Signed-off-by: yuzhou <1991039819@qq.com> --- scripts/scip_harness/scip_merge_indexes.py | 13 +++++++++-- tests/unit/test_scip_merge_indexes.py | 25 ++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 1f34074c012..c4a32d9fb21 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -54,12 +54,21 @@ def _ensure_scip_pb2() -> Any: return scip_pb2 +def _scope_specificity(project: str) -> int: + """Longer directory scopes win. The root scope '.' has length 1, which + would otherwise tie a one-character member directory such as 'a'.""" + scope = project_scope(project) + if scope in (".", ""): + return 0 + return len(scope) + + def _preferred_owner(projects: list[str], relpath: str) -> str | None: owners = [project for project in projects if project_owns(project, relpath)] if not owners: return None - best_scope = max(len(project_scope(project)) for project in owners) - tied = [project for project in owners if len(project_scope(project)) == best_scope] + best_scope = max(_scope_specificity(project) for project in owners) + tied = [project for project in owners if _scope_specificity(project) == best_scope] # Sibling explicit tsconfigs share a directory scope. Returning one of # them still lets each sibling keep its documents (scopes match) while # a shorter ancestor, such as a root tsconfig, is dropped. diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 17de82eb56c..45c2990217f 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -292,3 +292,28 @@ def test_merge_drops_root_docs_when_sibling_app_configs_share_the_owner_scope( "packages/app/src/a.spec.ts": "from-test", "src/main.ts": "from-root", } + + +def test_merge_prefers_a_one_character_member_over_a_root_tsconfig(tmp_path: Path) -> None: + """A root scope '.' must not tie a one-character member directory.""" + root = tmp_path / "root.scip" + member = tmp_path / "a.scip" + root.write_bytes( + _index_with_docs( + ["src/main.ts", "a/src/a.ts"], + ["from-root", "from-root-ref"], + ) + ) + member.write_bytes(_index_with_docs(["a/src/a.ts"], ["from-a"])) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [root, member], + out, + projects=["tsconfig.app.json", "a"], + known_projects=["tsconfig.app.json", "a"], + ) + scip_pb2 = _MOD._ensure_scip_pb2() + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"src/main.ts": "from-root", "a/src/a.ts": "from-a"}