Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ Machine-readable output (`report --stdout`, `--format json`, `scan --out -`, `co

`uvx srcly refs <name>` 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.
Expand Down
3 changes: 2 additions & 1 deletion docs/CODE_MAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <preset>`) | `server/app/run.py` (`_run_headless`) → `server/app/services/reporting.py` |
| Headless commands (`scan`, `report`, `hotspots`, `explain`, `changes`, `refs`, `findings`; `report --quadrant <preset>`) | `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`) |
Expand Down Expand Up @@ -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 <id>`: 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
Expand Down
Original file line number Diff line number Diff line change
@@ -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"
]
}
Original file line number Diff line number Diff line change
@@ -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"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
id: area-findings-checker-coverage
label: "Findings: checker coverage"
type: area
status: planned
---
Original file line number Diff line number Diff line change
@@ -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`.

23 changes: 22 additions & 1 deletion server/app/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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"
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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

Expand Down
25 changes: 23 additions & 2 deletions server/app/services/findings/astgrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import json
import os
import re
import shutil
import tempfile
from pathlib import Path
Expand All @@ -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"))

Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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]:
Expand All @@ -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)]
2 changes: 2 additions & 0 deletions server/app/services/findings/async_loops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions server/app/services/findings/builtin_ts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions server/app/services/findings/duplicate_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading