diff --git a/README.md b/README.md index 89930e59..7ec5617a 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,8 @@ Machine-readable output (`report --stdout`, `--format json`, `scan --out -`, `co `uvx srcly refs ` lists every declaration of a name and what references each one (`file::symbol` picks one). Use it to find every caller before you move or delete a symbol. +`uvx srcly findings --rule duplicate-type` lists one rule's findings as `path:line rule message`, then the count. Repeat `--rule` for more rules, leave it out for all of them, or add `--format json`. Run it before and after a cleanup: the count reads N/A, with the reason, when a checker that could report the rule did not run, and for a ruff or eslint rule with no finding. + `uvx srcly fix` prints a diff of the safe fixes for srcly's own findings, and `--write` applies them: it drops an `export` that only its own file uses, and rewrites a cleanup function returned from `onMount`/`createEffect` (which Solid ignores) to `onCleanup()`. Deleting unreachable files runs only when you name the rule: `srcly fix --rule unreachable-file --write`. Reachability walks the TS import graph from detected entries; add entry globs in `srcly.toml` at the Git root under `[reachability] entries = [...]`. `srcly report` also writes `size_budget.json`: each code file over 5,000 tokens (bytes / 4), with a baseline that only goes down. `uvx srcly check --ratchet` exits 1 when one of those files grows, or a new file goes over the budget, so a pre-commit or CI step can stop big files from getting bigger. diff --git a/docs/CODE_MAP.md b/docs/CODE_MAP.md index cf02c3ae..4f83bcaf 100644 --- a/docs/CODE_MAP.md +++ b/docs/CODE_MAP.md @@ -43,7 +43,7 @@ Browser | --- | --- | | CLI entry point, arg parsing, port pick, browser open | `server/app/run.py` (`main`) | | Startup banner and `--version`: version, paths, client build, cache, data-flow engine, `SRCLY_*` overrides | `server/app/startup_info.py` | -| Headless commands (`scan`, `report`, `hotspots`, `explain`, `changes`, `refs`; `report --quadrant `) | `server/app/run.py` (`_run_headless`) → `server/app/services/reporting.py` | +| Headless commands (`scan`, `report`, `hotspots`, `explain`, `changes`, `refs`, `findings`; `report --quadrant `) | `server/app/run.py` (`_run_headless`) → `server/app/services/reporting.py` | | `explain --at` scopes (folder rollups, file symbols, `file::symbol`, `file::name@line` for same-named symbols, a pasted `path:line name` start-at value), file classes (code/test/docs/style/fixture/…) that the findings queue and folder scores use; the `Analysis:` provenance line (reused or fresh scan, HEAD, uncommitted files, checker coverage) that `explain` and `report` print | `server/app/services/scopes.py` (`find`, `_at_line`, `provenance`, `provenance_line`); per-symbol branch shape (statements vs `&&`/`||`/`?:`, deepest lines, from the analyzer markers) and tests that import or name a file or symbol in `server/app/services/scope_evidence.py`; `server/app/services/file_classes.py`; CLI reuses the analysis cache in `reporting.py` (`scan_tree` sets the root's private `_analysis`); `report`'s printed summary in `run.py` (`_format_quiet_report_summary`) | | FastAPI app, CORS, static SPA mount | `server/app/main.py` | | Ctrl+C / SIGTERM: cancel running scans, then uvicorn shutdown | `server/app/main.py` (`lifespan`, `_install_scan_cancelling_signal_handlers`); CLI exit code in `server/app/run.py` (`main`) | @@ -87,6 +87,7 @@ Browser | Await-in-loop rule (`await-in-loop`, `[db]` rank when the loop walks an awaited `prisma.*`/`findMany` result); skips pagination/retry/chain loops, `tx.*` in transactions, `Promise.all` chunks, sleeps and tests | `server/app/services/findings/async_loops.py` | | Duplicate-type rule (`duplicate-type`): a non-exported top-level object type (`type X = {…}` or `interface`) whose name another non-test file exports, when at least 3 of its fields, and at least half, match that type by name and declared type text; tests and `.d.ts` skipped | `server/app/services/findings/duplicate_types.py` (`object_types`, `find_copies`, `DuplicateTypeTool`); test `server/tests/test_duplicate_types.py` | | Rule-pack runner: a project's ast-grep YAML rules in `.srcly/rules/` (`ast-grep scan --json=stream`, binary from `SRCLY_AST_GREP`, `node_modules/.bin`, or PATH; missing → N/A); starter rules in `docs/rule-packs/` | `server/app/services/findings/astgrep.py` (`plan`, `AstGrepTool`, `parse_output`) | +| `srcly findings [path] --rule `: every finding as `path:line rule message` with a count per rule (`--format json`); a count is N/A with the reason when a checker that could report the rule failed or checked no file (srcly tools and ast-grep declare `Tool.rules`; `typescript.unscheduled` lists configured checks that were not planned) | `server/app/services/findings/listing.py` (`build`, `render`, `run`); CLI in `server/app/run.py`; test `server/tests/test_findings_listing.py` | | `srcly fix`: findings carry `fix` (byte edits or a file delete); diff by default, `--write` applies, deletes only with `--rule unreachable-file`; fixers are `reachability.py` (drop `export`, delete file) and `solid.py` (`onCleanup`) | `server/app/services/findings/fixes.py` (`plan`, `diff`, `run`); CLI in `server/app/run.py`; proof in `server/tests/test_fixes.py` (real `tsc` before and after) | ### API surface diff --git a/pgm/data/projects/srcly-backlog/history/20261128T042432357Z-0000-c37dea40-95ae-4cc0-979a-93d4c1908cf4.json b/pgm/data/projects/srcly-backlog/history/20261128T042432357Z-0000-c37dea40-95ae-4cc0-979a-93d4c1908cf4.json new file mode 100644 index 00000000..868174a9 --- /dev/null +++ b/pgm/data/projects/srcly-backlog/history/20261128T042432357Z-0000-c37dea40-95ae-4cc0-979a-93d4c1908cf4.json @@ -0,0 +1,14 @@ +{ + "id": "c37dea40-95ae-4cc0-979a-93d4c1908cf4", + "kind": "node.created", + "actor": { + "kind": "agent", + "id": "token:f3edbd", + "label": "Agent token ...f3edbd" + }, + "createdAt": "2026-11-28T04:24:32.357Z", + "summary": "Created \"Findings: checker coverage\".", + "nodeIds": [ + "area-findings-checker-coverage" + ] +} diff --git a/pgm/data/projects/srcly-backlog/history/20261128T042438625Z-0000-17af3177-f65b-4edf-ba64-e535a9a47b49.json b/pgm/data/projects/srcly-backlog/history/20261128T042438625Z-0000-17af3177-f65b-4edf-ba64-e535a9a47b49.json new file mode 100644 index 00000000..db1f83fb --- /dev/null +++ b/pgm/data/projects/srcly-backlog/history/20261128T042438625Z-0000-17af3177-f65b-4edf-ba64-e535a9a47b49.json @@ -0,0 +1,15 @@ +{ + "id": "17af3177-f65b-4edf-ba64-e535a9a47b49", + "kind": "node.created", + "actor": { + "kind": "agent", + "id": "token:0efa82", + "label": "Agent token ...0efa82" + }, + "createdAt": "2026-11-28T04:24:38.625Z", + "summary": "Created \"Checkers record which rules ran on which files\" under \"Findings: checker coverage\".", + "nodeIds": [ + "task-checkers-record-which-rules-ran-on-which-files", + "area-findings-checker-coverage" + ] +} diff --git a/pgm/data/projects/srcly-backlog/nodes/area-findings-checker-coverage.md b/pgm/data/projects/srcly-backlog/nodes/area-findings-checker-coverage.md new file mode 100644 index 00000000..00ea02eb --- /dev/null +++ b/pgm/data/projects/srcly-backlog/nodes/area-findings-checker-coverage.md @@ -0,0 +1,6 @@ +--- +id: area-findings-checker-coverage +label: "Findings: checker coverage" +type: area +status: planned +--- diff --git a/pgm/data/projects/srcly-backlog/nodes/task-checkers-record-which-rules-ran-on-which-files.md b/pgm/data/projects/srcly-backlog/nodes/task-checkers-record-which-rules-ran-on-which-files.md new file mode 100644 index 00000000..62680028 --- /dev/null +++ b/pgm/data/projects/srcly-backlog/nodes/task-checkers-record-which-rules-ran-on-which-files.md @@ -0,0 +1,30 @@ +--- +id: task-checkers-record-which-rules-ran-on-which-files +label: Checkers record which rules ran on which files +type: task +status: planned +parent: area-findings-checker-coverage +--- +Checkers do not record which rules ran on which files, so `srcly findings` (and every findings total) infers coverage from tool names and file lists. + +## Evidence + +Codex review of `srcly findings`, round 3. Recompute: in `server/`, `uv run python -m app.run findings . --rule F401` reads N/A although ruff runs F401 on every file and finds none. + +- A ruff or eslint rule with no finding is always N/A, so such a cleanup cannot prove zero. +- The unfiltered total accepts "any checker checked a file": a tsc run that listed no file in the target is masked by another checker. +- An ast-grep pack has one file list, so a TypeScript rule gets credit for Python files in a mixed pack. A quoted `"id":` key is not read as an id. An ast-grep id equal to a ruff or tsc code hides that tool's failure. +- Older gaps below the command: ESLint or ruff parse errors still give clean counts; `tsc` project errors are dropped when `--listFiles` prints files; nested flat ESLint configs are dropped without a reason; the cache fingerprint misses checker inputs outside the scan; an unreadable file is skipped by `duplicate-type`. + +## Design + +Each checker returns a coverage record per rule: files checked, files excluded, why incomplete. `listing.py` derives counts from those records only. Reuse a cached record only when the checker inputs still match. + +## Files + +`server/app/services/findings/` (`listing.py`, `model.py`, `runner.py`, `typescript.py`, `ruff.py`, `astgrep.py`, `duplicate_types.py`). + +## Done + +In `server/`, `findings . --rule F401` reads 0, and reads N/A when the project config switches F401 off. Each evidence case above gives N/A. Per-rule counts on Visual Notes `app` sum to the per-tool counts of `srcly report`. + diff --git a/server/app/run.py b/server/app/run.py index e9243b50..d7aa699a 100644 --- a/server/app/run.py +++ b/server/app/run.py @@ -80,7 +80,7 @@ def _main(argv: list[str] | None = None) -> None: - Opens the default browser to the app URL. """ argv = list(argv) if argv is not None else sys.argv[1:] - if argv and argv[0] in {"scan", "report", "hotspots", "explain", "compare", "changes", "fix", "check", "refs", "trace", "impact"}: + if argv and argv[0] in {"scan", "report", "hotspots", "explain", "compare", "changes", "findings", "fix", "check", "refs", "trace", "impact"}: # stderr, so JSON on stdout stays clean. print(startup_info.version_line(), file=sys.stderr, flush=True) _run_headless(argv) @@ -100,6 +100,7 @@ def _main(argv: list[str] | None = None) -> None: " hotspots rank files or functions by one metric\n" " compare metric and dependency changes between two git refs\n" " changes the code chunks a branch or time window edited, and what to review first\n" + " findings every finding, one per line, with a count per rule (--rule)\n" " fix show, then apply (--write), safe fixes for srcly's own findings\n" " check --ratchet: fail when a file over the size budget grows\n" " trace where a value comes from and goes (data flow), or --effects\n" @@ -493,6 +494,21 @@ def _run_headless(argv: list[str]) -> None: ) fix_parser.add_argument("--write", action="store_true", help="Apply the fixes. Without it, print the diff.") + findings_parser = subparsers.add_parser( + "findings", help="List every lint, type and srcly finding as path:line rule message, with a count per rule." + ) + findings_parser.add_argument("path", nargs="?", help="Folder to check. Defaults to the enclosing Git repo root.") + findings_parser.add_argument( + "--rule", + action="append", + default=None, + help="Only this rule, such as duplicate-type or F401. May be repeated.", + ) + findings_parser.add_argument("--format", choices=("md", "json"), default="md", help="md (default) or json.") + findings_parser.add_argument( + "--refresh", action="store_true", help="Rerun lint and type checks instead of reusing cached results." + ) + check_parser = subparsers.add_parser("check", help="Fail when a code file over the size budget grows.") check_parser.add_argument("path", nargs="?", help="Path to check. Defaults to the enclosing Git repo root.") check_parser.add_argument( @@ -533,6 +549,11 @@ def _dispatch(args) -> None: print(fixes.run(_resolve_target_path(args.path), set(args.rule or ()), apply=args.write)) return + if args.command == "findings": + from app.services.findings import listing + + print(listing.run(_resolve_target_path(args.path), args.rule or (), args.format, refresh=args.refresh)) + return if args.command == "refs": from app.services.symbols import refs diff --git a/server/app/services/findings/astgrep.py b/server/app/services/findings/astgrep.py index 58f2d6e2..ba63d3a2 100644 --- a/server/app/services/findings/astgrep.py +++ b/server/app/services/findings/astgrep.py @@ -11,6 +11,7 @@ import json import os +import re import shutil import tempfile from pathlib import Path @@ -32,6 +33,10 @@ } +# ``id: name``, quoted or not, with or without a trailing comment. +_RULE_ID = re.compile(r"""^id:[ \t]*["']?([^"'#\s]+)""", re.M) + + def rule_files(rules_dir: Path) -> list[Path]: return sorted(p for p in rules_dir.glob("*.y*ml") if p.suffix in (".yml", ".yaml")) @@ -47,6 +52,15 @@ def _languages(rules: list[Path]) -> tuple[str, ...]: return tuple(out) +def rule_ids(rules: list[Path]) -> tuple[str, ...]: + """Each rule's ``id:`` line.""" + return tuple( + match + for path in rules + for match in _RULE_ID.findall(path.read_text(encoding="utf-8", errors="replace")) + ) + + def find_binary(root: Path, stop: Optional[Path]) -> Optional[Path]: env = os.environ.get("SRCLY_AST_GREP") if env: @@ -100,6 +114,7 @@ def __init__(self, root: Path, binary: Path, rules_dir: Path) -> None: ) self.binary = binary self.rules_dir = rules_dir + self.rules = rule_ids(rules) def check(self): cwd = self.root if self.root.is_dir() else self.root.parent @@ -110,7 +125,11 @@ def check(self): # ast-grep exits 1 when an error-severity rule matches; that is a result, not a failure. if out.returncode not in (0, 1) or (out.returncode == 1 and not out.stdout.strip()): raise ToolFailed(first_line(out.stderr) or f"exit code {out.returncode}") - return parse_output(out.stdout, cwd, self.id), None + from app.services.analysis import discover_files + + # No file in a rule's language means the pack checked nothing here. + files = [f for f in discover_files(self.root).files if f.endswith(self.extensions)] if self.extensions else [] + return parse_output(out.stdout, cwd, self.id), files def plan(root: Path, stop: Optional[Path] = None) -> list[Tool]: @@ -120,5 +139,7 @@ def plan(root: Path, stop: Optional[Path] = None) -> list[Tool]: binary = find_binary(root, stop) if binary is None: reason = "ast-grep is not installed (pnpm add -D @ast-grep/cli, or set SRCLY_AST_GREP)" - return [MissingTool("ast-grep", "ast-grep", "ast-grep", root, _languages(rule_files(rules_dir)), reason)] + missing = MissingTool("ast-grep", "ast-grep", "ast-grep", root, _languages(rule_files(rules_dir)), reason) + missing.rules = rule_ids(rule_files(rules_dir)) + return [missing] return [AstGrepTool(root, binary, rules_dir)] diff --git a/server/app/services/findings/async_loops.py b/server/app/services/findings/async_loops.py index ec36eeb1..da063267 100644 --- a/server/app/services/findings/async_loops.py +++ b/server/app/services/findings/async_loops.py @@ -247,6 +247,8 @@ def check_source(path: str, source: bytes, tool_id: str) -> list[Finding]: class AwaitInLoopTool(Tool): + rules = (RULE,) + def __init__(self, root: Path, files: Optional[list[str]] = None) -> None: super().__init__( id="srcly-async", diff --git a/server/app/services/findings/builtin_ts.py b/server/app/services/findings/builtin_ts.py index 3fff8c34..00fb558c 100644 --- a/server/app/services/findings/builtin_ts.py +++ b/server/app/services/findings/builtin_ts.py @@ -91,6 +91,8 @@ def add(node, rule: str, message: str) -> None: class BuiltinTsTool(Tool): + rules = ("explicit-any", "ts-nocheck", "ts-ignore-without-reason", "non-null-chain") + def __init__(self, root: Path, skip_dirs: Iterable[Path] = (), files: Optional[list[str]] = None) -> None: super().__init__( id="srcly-ts", diff --git a/server/app/services/findings/duplicate_types.py b/server/app/services/findings/duplicate_types.py index 6f88ba3a..c4ddae99 100644 --- a/server/app/services/findings/duplicate_types.py +++ b/server/app/services/findings/duplicate_types.py @@ -235,6 +235,8 @@ def check_files(root: Path, files: list[str], tool_id: str, deadline: float) -> class DuplicateTypeTool(Tool): + rules = ("duplicate-type",) + def __init__(self, root: Path, files: Optional[list[str]] = None) -> None: super().__init__( id="srcly-dup-types", diff --git a/server/app/services/findings/listing.py b/server/app/services/findings/listing.py new file mode 100644 index 00000000..621f79e5 --- /dev/null +++ b/server/app/services/findings/listing.py @@ -0,0 +1,144 @@ +"""``srcly findings``: every finding, one per line, filtered by rule, with a count per rule. + +A count is a number only when every checker that could report the rule ran. +Otherwise it is N/A with the reason, so a before/after check never reads a +failed or empty run as 0. A ruff or eslint rule with no finding is N/A too: +srcly cannot tell whether the project's settings switch it on. +""" + +from __future__ import annotations + +import json +import re +from collections import Counter +from pathlib import Path +from typing import Optional, Sequence + +from app.services.findings import typescript +from app.services.findings.model import FindingsResult, ToolRun +from app.services.findings.runner import collect, plan_tools +from app.services.findings.tools import Tool + +Skipped = Sequence[tuple[str, str, str]] +"""Configured checks that were not planned: (tool, label, reason).""" + + +def _family(rule: str) -> str: + """The project tool that names rules this way.""" + if re.fullmatch(r"TS\d+", rule): + return "tsc" + if re.fullmatch(r"[A-Z]+\d+", rule) or rule in ("syntax", "invalid-syntax"): + return "ruff" + return "eslint" + + +def _blockers( + rule: Optional[str], tools: Sequence[Tool], runs: dict[str, ToolRun], skipped: Skipped, reporters: set[str] +) -> list[str]: + """ + Why the count for ``rule`` (``None``: all rules) is not complete; empty + when it is. ``reporters``: the tools that found something for ``rule``. + """ + checkers, left_out, name = list(tools), list(skipped), "checker" + if rule is not None: + owners = [t for t in tools if rule in t.rules] + # An ast-grep id is the project's choice, so it may also be an eslint rule's name. + shared = all(t.tool == "ast-grep" for t in owners) + family = _family(rule) if not owners else "eslint" if shared else None + checkers = [t for t in tools if t in owners or t.tool == family or t.id in reporters] + left_out = [s for s in skipped if s[0] == family] + name = " or ".join(t.label for t in owners) or f"{family} run" + why = [runs[t.id].reason for t in checkers if not runs[t.id].ok] + why += [f"{label} not run: {reason}" for _, label, reason in left_out] + # ``files`` is None when a tool does not say what it checked. + if not why and not any(runs[t.id].files != [] for t in checkers): + why = [f"no {name} checked a file"] + if not why and rule is not None and not reporters and not owners and family != "tsc": + why = [f"no finding, and srcly cannot tell whether {family} has this rule switched on"] + return why + + +def build( + root: Path, result: FindingsResult, tools: Sequence[Tool], rules: Sequence[str] = (), skipped: Skipped = () +) -> dict: + """The payload both formats print. Paths are relative to ``root``.""" + runs = {r.id: r for r in result.tools} + wanted = list(dict.fromkeys(rules)) + rows = [] + for f in result.findings: + if wanted and f.rule not in wanted: + continue + path = Path(f.path) + rows.append( + { + "path": path.relative_to(root).as_posix() if path.is_relative_to(root) else f.path, + "line": f.line, + "column": f.column, + "rule": f.rule, + "severity": f.severity, + "tool": f.tool, + "message": " ".join(f.message.split()), + } + ) + found = Counter(row["rule"] for row in rows) + + reporters: dict[str, set[str]] = {} + for row in rows: + reporters.setdefault(row["rule"], set()).add(row["tool"]) + + def entry(of: Sequence[Optional[str]], n: int) -> dict: + why = list( + dict.fromkeys( + reason for rule in of for reason in _blockers(rule, tools, runs, skipped, reporters.get(rule, set())) + ) + ) + return {"count": None if why else n, "found": n, "reason": "; ".join(why)} + + known = sorted({r for t in tools for r in t.rules}) + return { + "root": str(root), + "filter": wanted, + # The total over the wanted rules (all rules without a filter). + **entry(wanted or [None], len(rows)), + "rules": [{"rule": rule, **entry([rule], found[rule])} for rule in wanted or sorted(found)], + # A misspelled rule would otherwise read as a clean 0. + "unknown_rules": [r for r in wanted if r not in known and not found[r]], + "known_rules": known, + "findings": rows, + "not_checked": [{"checker": r.label, "reason": r.reason} for r in result.tools if not r.ok] + + [{"checker": label, "reason": reason} for _, label, reason in skipped], + } + + +def render(payload: dict) -> str: + def count(e: dict) -> str: + if e["count"] is not None: + return str(e["count"]) + return f"N/A ({e['reason']}; {e['found']} found by the checkers that ran)" + + lines = [f"{f['path']}:{f['line']} {f['rule']} {f['message']}" for f in payload["findings"]] + if lines: + lines.append("") + lines += [f"{e['rule']}: {count(e)}" for e in payload["rules"]] + if len(payload["filter"]) != 1: + lines.append(f"Total: {count(payload)}") + lines += [f"Not checked: {t['checker']}: {t['reason']}" for t in payload["not_checked"]] + if payload["unknown_rules"]: + lines.append( + f"No finding and not a known rule: {', '.join(payload['unknown_rules'])}. Check the spelling. " + f"Known rules: {', '.join(payload['known_rules'])}." + ) + return "\n".join(lines) + + +def run(root: Path, rules: Sequence[str] = (), fmt: str = "md", refresh: bool = False) -> str: + """The findings for ``root`` (from the cache ``report`` fills while files are unchanged).""" + from app.services import cache + from app.services.analysis import find_repo_root + + root = root.resolve() + stop = find_repo_root(root if root.is_dir() else root.parent) + tools = plan_tools(root, stop=stop) + result = collect(root, fingerprint=cache.fingerprint(root), tools=tools, use_cache=not refresh) + payload = build(root, result, tools, rules, typescript.unscheduled(root, stop)) + return json.dumps(payload, indent=2) if fmt == "json" else render(payload) diff --git a/server/app/services/findings/reachability.py b/server/app/services/findings/reachability.py index 456801db..fefb6ee0 100644 --- a/server/app/services/findings/reachability.py +++ b/server/app/services/findings/reachability.py @@ -406,6 +406,8 @@ def add(path: Path, line: int, end: int, col: int, rule: str, message: str, fix: class ReachabilityTool(Tool): + rules = RULES + def __init__(self, root: Path, files: Optional[list[str]] = None) -> None: super().__init__( id="srcly-reach", diff --git a/server/app/services/findings/solid.py b/server/app/services/findings/solid.py index ab9d9e85..32e8c4f0 100644 --- a/server/app/services/findings/solid.py +++ b/server/app/services/findings/solid.py @@ -127,6 +127,8 @@ def check_source(path: str, source: bytes, tool_id: str) -> list[Finding]: class SolidTool(Tool): + rules = ("solid-returned-cleanup",) + def __init__(self, root: Path, files: Optional[list[str]] = None) -> None: super().__init__( id="srcly-solid", diff --git a/server/app/services/findings/tools.py b/server/app/services/findings/tools.py index e1402762..0ad608ac 100644 --- a/server/app/services/findings/tools.py +++ b/server/app/services/findings/tools.py @@ -8,7 +8,7 @@ import time from dataclasses import dataclass, field from pathlib import Path -from typing import Optional, Sequence +from typing import ClassVar, Optional, Sequence from app.services.findings.model import Finding, Source, ToolRun @@ -53,6 +53,9 @@ class Tool: """Binary and config files whose change should invalidate cached findings.""" exclude_dirs: tuple[Path, ...] = field(default_factory=tuple) """Folders left to other tools.""" + rules: ClassVar[tuple[str, ...]] = () + """Every rule this tool can report, when known ahead (srcly's own tools and + the ast-grep pack). Empty for tsc, eslint and ruff.""" def check(self) -> tuple[list[Finding], Optional[list[str]]]: """Run and return (findings, files checked or None). Raise ``ToolFailed``.""" diff --git a/server/app/services/findings/typescript.py b/server/app/services/findings/typescript.py index f973e429..8b75aa79 100644 --- a/server/app/services/findings/typescript.py +++ b/server/app/services/findings/typescript.py @@ -251,19 +251,39 @@ def check(self): # -- planning ---------------------------------------------------------------- +def _configured(root: Path, stop: Optional[Path]) -> list[tuple[str, Path, Optional[Path], str]]: + """Every tsc and eslint config: (tool, config, binary, why it is not run; empty when it is).""" + out: list[tuple[str, Path, Optional[Path], str]] = [] + for tool, configs, limit in ( + ("tsc", tsconfigs(root, stop), MAX_TSC_PROJECTS), + ("eslint", eslint_configs(root, stop), MAX_ESLINT_PROJECTS), + ): + for index, config in enumerate(configs): + binary = find_up(config.parent, f"node_modules/.bin/{tool}") + why = "" + if index >= limit: + why = f"over the limit of {limit} {tool} projects" + elif binary is None: + why = f"no node_modules/.bin/{tool}" + out.append((tool, config, binary, why)) + return out + + def plan(root: Path, stop: Optional[Path] = None) -> list[Tool]: """Project tsc/eslint runs for ``root`` (none when the project has neither).""" label_base = stop or root - tools: list[Tool] = [] - for config in tsconfigs(root, stop)[:MAX_TSC_PROJECTS]: - binary = find_up(config.parent, "node_modules/.bin/tsc") - if binary is not None: - tools.append(TscTool(root, config, binary, label_base)) - for config in eslint_configs(root, stop)[:MAX_ESLINT_PROJECTS]: - binary = find_up(config.parent, "node_modules/.bin/eslint") - if binary is not None: - tools.append(EslintTool(root, config, binary, label_base)) - return tools + kinds = {"tsc": TscTool, "eslint": EslintTool} + return [kinds[tool](root, config, binary, label_base) for tool, config, binary, why in _configured(root, stop) if not why] + + +def unscheduled(root: Path, stop: Optional[Path] = None) -> list[tuple[str, str, str]]: + """Configured checks that ``plan`` leaves out: (tool, label, reason).""" + label_base = stop or root + return [ + (tool, f"{tool} ({rel_label(config, label_base)})", why) + for tool, config, _, why in _configured(root, stop) + if why + ] def project_dirs(tools: list[Tool]) -> list[Path]: diff --git a/server/tests/test_findings_listing.py b/server/tests/test_findings_listing.py new file mode 100644 index 00000000..89b75e5a --- /dev/null +++ b/server/tests/test_findings_listing.py @@ -0,0 +1,69 @@ +import json +from pathlib import Path + +from app.run import main +from app.services.findings import listing +from app.services.findings.astgrep import rule_ids +from app.services.findings.duplicate_types import DuplicateTypeTool +from app.services.findings.runner import run_tools +from app.services.findings.tools import MissingTool + +DOC = "{ id: string; title: string; createdAt: string }" + + +def test_findings_lists_one_rule_with_a_count_and_never_reads_a_failed_checker_as_zero(tmp_path: Path, capsys): + root = tmp_path.resolve() + (root / "api.ts").write_text(f"export type Doc = {DOC};\n", encoding="utf-8") + (root / "view.ts").write_text(f"const x: any = 1;\ntype Doc = {DOC};\n", encoding="utf-8") + + main(["findings", str(root), "--rule", "duplicate-type", "--format", "json"]) + payload = json.loads(capsys.readouterr().out) + assert payload["count"] == 1 + assert [(f["path"], f["line"], f["rule"]) for f in payload["findings"]] == [("view.ts", 2, "duplicate-type")] + + main(["findings", str(root), "--rule", "duplicate-type"]) + out = capsys.readouterr().out + assert out.startswith("view.ts:2 duplicate-type `Doc` copies") + assert "duplicate-type: 1\n" in out + + # The project's eslint cannot run: srcly's own rule still has a count, an eslint rule does not. + tools = [DuplicateTypeTool(root), MissingTool("eslint", "eslint", "eslint", root, (".ts",), "eslint is not installed")] + got = listing.build(root, run_tools(root, tools), tools, ["duplicate-type", "no-debugger"]) + assert [(r["rule"], r["count"]) for r in got["rules"]] == [("duplicate-type", 1), ("no-debugger", None)] + assert got["count"] is None + assert "no-debugger: N/A (eslint failed: eslint is not installed" in listing.render(got) + + # The rule's own checker failed: N/A, not 0. + broken = MissingTool("srcly-dup-types", "srcly-dup-types", "srcly duplicate types", root, (".ts",), "timed out") + broken.rules = DuplicateTypeTool.rules + assert "duplicate-type: N/A (srcly duplicate types failed: timed out" in listing.render(listing.build(root, run_tools(root, [broken]), [broken], ["duplicate-type"])) + + # An ast-grep id may also be an eslint rule's name: a failed eslint blocks it. A trailing comment is not part of the id. + (root / "pack.yml").write_text('id: no-debugger # ours\nlanguage: typescript\n', encoding="utf-8") + assert rule_ids([root / "pack.yml"]) == ("no-debugger",) + pack = MissingTool("ast-grep", "ast-grep", "ast-grep", root, (".ts",), "") + pack.rules = ("no-debugger",) + pack.check = lambda: ([], [str(root / "view.ts")]) + both = [pack, tools[1]] + assert listing.build(root, run_tools(root, both), both, ["no-debugger"])["count"] is None + + # A tsconfig without tsc: its rules and the unfiltered total are N/A, srcly's own rule is not. + (root / "tsconfig.json").write_text("{}", encoding="utf-8") + main(["findings", str(root), "--rule", "TS2322", "--rule", "duplicate-type", "--format", "json"]) + got = json.loads(capsys.readouterr().out) + assert [(r["rule"], r["count"]) for r in got["rules"]] == [("TS2322", None), ("duplicate-type", 1)] + assert "no node_modules/.bin/tsc" in got["rules"][0]["reason"] + main(["findings", str(root)]) + assert "Total: N/A (tsc (tsconfig.json) not run" in capsys.readouterr().out + + # ruff ran, but its settings may leave the rule off: no finding is N/A, not 0. + (root / "ok.py").write_text("x = 1\n", encoding="utf-8") + main(["findings", str(root), "--rule", "B006"]) + assert "B006: N/A (no finding, and srcly cannot tell whether ruff has this rule switched on" in capsys.readouterr().out + + # A checker that found no file to check says nothing about the code. + (root / "api.ts").unlink() + (root / "view.ts").unlink() + empty = [DuplicateTypeTool(root)] + for rules in (["duplicate-type"], ["F401"], []): + assert listing.build(root, run_tools(root, empty), empty, rules)["count"] is None diff --git a/site/src/commands.ts b/site/src/commands.ts index 4d4156af..f7f611bc 100644 --- a/site/src/commands.ts +++ b/site/src/commands.ts @@ -4,6 +4,7 @@ export const COMMANDS: [string, string][] = [ ['srcly report', 'Write report.md and JSON artifacts: findings, folders, hotspots, a tree summary, the metric schema and an agent guide. --quadrant adds a 2×2.'], ['srcly explain --at', 'Drill into the repo, a folder, a file, or file::symbol. Any printed "start at" value works.'], ['srcly refs ', 'Every declaration of a name and what references each one. file::symbol picks one.'], + ['srcly findings', 'Every lint, type and srcly finding as path:line rule message, with a count per rule. --rule filters; --format json for scripts.'], ['srcly hotspots', 'Rank files or functions by one metric. --format json for scripts.'], ['srcly compare [base] [head]', 'Metric and dependency changes between two refs. Defaults to the merge base against the working tree; pr: names a PR.'], ['srcly fix', 'Print a diff of safe fixes for srcly\'s own findings; --write applies them.'], diff --git a/site/src/docs/pages/cli.md b/site/src/docs/pages/cli.md index d4809b7c..1d1d2a04 100644 --- a/site/src/docs/pages/cli.md +++ b/site/src/docs/pages/cli.md @@ -87,6 +87,19 @@ uvx srcly changes . --window custom --since 2026-11-01T00:00:00 --until 2026-11- `--window` is `branch` (the default: this branch against its merge base), `24h`, `7d`, or `custom` with `--base`/`--head` or `--since`/`--until`. `--mode touched` (the default) lists every chunk a commit changed, with reverted work; `--mode net` compares the base and head snapshots only. `--ref` picks the branch whose first-parent history is read. Uncommitted edits are included when the head is the checked-out commit; `--no-worktree` leaves them out. `--json` prints the same payload the app reads. See [Review changes](../changes/) for the window, chunk and bucket rules. +## List findings + +`findings` prints each lint, type and srcly finding as `path:line rule message`, then a count per rule. Paths are relative to the analyzed folder. `--rule` filters by rule id (`duplicate-type`, `F401`, `TS2322`) and may be repeated: + +```bash +uvx srcly findings . --rule duplicate-type +uvx srcly findings . --rule duplicate-type --rule await-in-loop --format json +``` + +It runs the same checks as `report` and shares their cache, so a second run on unchanged files is quick. The first run takes as long as all the checks, even with `--rule`. `--refresh` reruns them. + +A count is N/A, with the reason, when a checker that could report the rule failed, timed out, was configured but not run (no `node_modules/.bin` binary, or over the project limit) or checked no file. In JSON, `count` is then `null` and `found` holds what the other checkers reported. Only the rule's own checkers matter: Srcly's own rules and ast-grep rule ids are known, a `TS2322` rule belongs to tsc, an `F401` rule to ruff, and any other name to eslint. An ast-grep id may also name an eslint rule, so eslint must have run too. A ruff or eslint rule with no finding is N/A, because Srcly cannot tell whether the project switches the rule on; run that linter with the rule selected to prove a zero. The total without `--rule` needs every checker. A misspelled rule is named in a note (`unknown_rules`). The exit code is 0 either way, so read the count. + ## Fix and check `fix` prints a diff of supported mechanical fixes. It applies changes only with `--write`: diff --git a/skills/srcly-code-quality/SKILL.md b/skills/srcly-code-quality/SKILL.md index 3ff68232..4533a08c 100644 --- a/skills/srcly-code-quality/SKILL.md +++ b/skills/srcly-code-quality/SKILL.md @@ -58,6 +58,7 @@ Use `uvx srcly scan . --out -` only when a caller explicitly wants raw tree JSON - Broad review: `uvx srcly report . --out .srcly --format both` - Review a branch or a coding session: `uvx srcly changes . --window branch` (or `24h`, `7d`; `--mode net` drops work that was put back; `--json` for the payload). It lists the edited functions and sections, before → after complexity, and two review buckets: already complex and changed, and new hotspots (complexity crossed 10). Paths are relative to the Git repo root. - Every declaration of a name and its callers (before you move or delete a symbol): `uvx srcly refs .` (`file::symbol` picks one) +- One rule's findings and count (a cleanup's before/after done check): `uvx srcly findings . --rule duplicate-type` (repeat `--rule`; `--format json`). An N/A count proves nothing; for a ruff or eslint rule, no finding reads N/A, so run that linter to prove zero - Single metric list: `uvx srcly hotspots . --metric complexity --limit 20` (any non-neutral id from `metrics.schema.json`; `--cohort function` ranks functions) - Report ranked by another metric: `uvx srcly report . --out .srcly --metric comment_noise` - Named 2x2 (members per quadrant in `report.md` + `quadrants.json`): `uvx srcly report . --out .srcly --quadrant activity` ("Hot mess" = complex and changing often; also `blast_radius`, `component_weight`, `comment_noise`) @@ -92,7 +93,7 @@ Progress, version banners and cache warnings go to stderr, so stdout stays parse - High LOC: look for separable responsibilities; do not split files blindly. - TSX render branching, prop count, inline handlers, and nesting: UI complexity and test-surface risk. - `any` usage and TS ignore directives: type-safety debt. -- `duplicate-type`: a local type copies one another file exports. Run `srcly refs `, move the callers to the exported type, delete the copy and any casts that hid it, all in one change. +- `duplicate-type`: a local type copies one another file exports. Run `srcly refs `, move the callers to the exported type, delete the copy and any casts that hid it, all in one change. Compare `srcly findings . --rule duplicate-type` before and after. - Import coupling and dependency graph density: dependency-boundary review targets. - TODOs in complex files: maintenance markers worth validating. - Low comment density only matters when paired with complexity, public API behavior, or non-obvious domain logic.