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 @@ -92,6 +92,8 @@ Machine-readable output (`report --stdout`, `--format json`, `scan --out -`, `co

`uvx srcly compare [base] [head]` compares two refs (default: merge-base → working tree; `pr:<n>` for a PR). A metric that is unavailable stays `null`, never 0. A file measured on one side only is a coverage change: it has no delta, stays out of the totals, and is counted under `coverage` (and `coverageLost` / `coverageGained` per metric), so lost measurement never looks like an improvement. A file missing from a side's dependency graph has unknown fan-in and fan-out.

`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 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`; `report --quadrant <preset>`) | `server/app/run.py` (`_run_headless`) → `server/app/services/reporting.py` |
| Headless commands (`scan`, `report`, `hotspots`, `explain`, `changes`, `refs`; `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 @@ -364,6 +364,7 @@ Open work: backlog area `area-symbol-graph` in `pgm/data`.
| Path between two symbols: `GET /api/symbols/path?from=&to=&kinds=&tests=` (shortest chain, forward then backward, or none); `?symbols=<from>&to=<id>` draws the chain from the focus (steps layered to the side the chain runs to), a Path chip with ×, `P` on a box, Shift+Enter in the palette, the rail's "Path from the focus" | `server/app/services/symbols/index.py` (`path`, `_shortest`), `routers/symbols.py:get_symbol_path`; `client/src/viz/deps/symbols/adapter.ts` (`symbolPathToViewModel`), `SymbolsView.tsx` (`pathTo`) |
| Dead and hub overlays: every node carries `refs` (`none`: nothing references it, `tests`: only test files do), drawn as the box stroke and in its note; `GET /api/symbols/stats` lists unreferenced symbols (private first, then largest), test-only ones and the top hubs; the rail lists them under the focus, each row centring on it | `server/app/services/symbols/index.py` (`refs_of`, `stats`), `routers/symbols.py:get_symbol_stats`; `client/src/viz/deps/symbols/adapter.ts` (`noteOf`, `statusOf`), `SymbolInspector.tsx` (`HitRows`) |
| HTTP seam: FastAPI / Flask handlers from `@router.<verb>(path)` and `@app.route(rule, methods=)` with `APIRouter(prefix=)` / `Blueprint(url_prefix=)` and `include_router` / `register_blueprint` mounting; client requests from `fetch(path, {method})`, `new URL(path, …)` and `api.<verb>(path)` (template `${}` segments as `*`); joined by method and path segments into `http` references carrying `GET /api/x` (`via`), a guess when more than one handler answers; `httpLinks` / `httpUnmatched` in the index info; drawn dashed with the request as label, an HTTP chip | `server/app/services/symbols/python.py` (`_note_router`, `_note_include`, `_note_route`), `typescript.py` (`_note_request`), `index.py` (`_link_http`); `client/src/viz/deps/symbols/adapter.ts` |
| `srcly refs <name\|file::symbol>`: every declaration a name matches (exported first) and the references to each, grouped by referencing symbol; `--format json`, `--no-tests` | `server/app/services/symbols/refs.py` (`match`, `build`, `render`); CLI in `server/app/run.py`; test `server/tests/test_symbol_refs.py` |
| Client API and contract | `client/src/symbols/api.ts`, `client/src/symbols/contract.ts` |
| Browser smoke for Symbols mode (focus, filters, a hop opened, inspector, palette, a file focus, a missing symbol) | `client/e2e/symbols.spec.ts` |

Expand Down
16 changes: 15 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", "trace", "impact"}:
if argv and argv[0] in {"scan", "report", "hotspots", "explain", "compare", "changes", "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 Down Expand Up @@ -502,6 +502,15 @@ def _run_headless(argv: list[str]) -> None:
"--budget", default=None, help="The size_budget.json to compare with. Defaults to <path>/.srcly/size_budget.json."
)

refs_parser = subparsers.add_parser(
"refs", help="List every declaration of a name and what references each one, from the symbol index."
)
refs_parser.add_argument("query", help="A name (every declaration with it), file#Qualified.name, or file::Qualified.name.")
refs_parser.add_argument("path", nargs="?", help="Project folder. Defaults to the enclosing Git repo root.")
refs_parser.add_argument("--format", choices=("md", "json"), default="md", help="md (default) or json.")
refs_parser.add_argument("--limit", type=_positive_int, default=20, help="Referencing symbols shown per declaration (default 20).")
refs_parser.add_argument("--no-tests", action="store_true", help="Leave references from test files out.")

_add_trace_parsers(subparsers)

args = parser.parse_args(argv)
Expand All @@ -524,6 +533,11 @@ def _dispatch(args) -> None:

print(fixes.run(_resolve_target_path(args.path), set(args.rule or ()), apply=args.write))
return
if args.command == "refs":
from app.services.symbols import refs

print(refs.run(_resolve_target_path(args.path), args.query, args.format, args.limit, tests=not args.no_tests))
return
if args.command == "check":
from app.services import size_budget

Expand Down
113 changes: 113 additions & 0 deletions server/app/services/symbols/refs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""`srcly refs`: every declaration a name or id matches, and what references each one.

The terminal view of the symbol index (`/api/symbols/*`): an agent uses it to
map callers before it moves or deletes a symbol. A name matches every
declaration with that name, so copies of one type in several files show
side by side.
"""

from __future__ import annotations

import json
from collections import defaultdict
from pathlib import Path
from typing import Dict, List

from app.services.symbols.index import SymbolIndex, build_symbol_index
from app.services.symbols.model import Symbol


def match(idx: SymbolIndex, query: str) -> List[Symbol]:
"""`file#Qualified`, `file::Qualified`, else every symbol whose name or qualified name equals the query."""
q = query.strip()
sym_id = q.replace("::", "#", 1)
if sym_id in idx.symbols:
return [idx.symbols[sym_id]]
hits = [s for s in idx.symbols.values() if s.kind != "module" and q in (s.name, s.qualified)]
return sorted(hits, key=lambda s: (not s.exported, idx.is_test(s), s.file, s.line))


def _incoming(idx: SymbolIndex, sym: Symbol, tests: bool) -> List[dict]:
rows = []
for i in idx.inc.get(sym.id, []):
r = idx.references[i]
src = idx.symbols.get(r.source)
file = src.file if src else r.source.partition("#")[0]
is_test = bool(src and idx.is_test(src))
if is_test and not tests:
continue
rows.append(
{
"source": r.source,
"file": file,
"line": r.line,
"kind": r.kind,
"resolution": r.resolution,
"test": is_test,
}
)
return sorted(rows, key=lambda row: (row["test"], row["file"], row["line"], row["kind"]))


def build(idx: SymbolIndex, query: str, tests: bool = True) -> dict:
found = match(idx, query)
return {
"query": query,
"root": str(idx.root),
"declarations": [
{
"id": s.id,
"name": s.name,
"kind": s.kind,
"file": s.file,
"line": s.line,
"exported": s.exported,
"refs": idx.refs_of(s),
"references": _incoming(idx, s, tests),
}
for s in found
],
"suggestions": [] if found else [h.id for h in idx.search(query, limit=8)],
}


def _count(n: int, noun: str) -> str:
return f"{n} {noun}" if n == 1 else f"{n} {noun}s"


def render(payload: dict, limit: int) -> str:
decls = payload["declarations"]
if not decls:
lines = [f"No symbol is named {payload['query']!r}."]
if payload["suggestions"]:
lines.append("Did you mean: " + ", ".join(payload["suggestions"]))
return "\n".join(lines)
out = [f"{payload['query']}: {_count(len(decls), 'declaration')}"]
for d in decls:
flag = "exported" if d["exported"] else "not exported"
out.append("")
out.append(f"## {d['file']}:{d['line']} · {d['kind']} {d['id'].partition('#')[2]} ({flag})")
refs = d["references"]
if not refs:
out.append("No references." if d["refs"] == "none" else "No references outside tests.")
continue
by_source: Dict[str, List[dict]] = defaultdict(list)
for r in refs:
by_source[r["source"]].append(r)
out.append(f"{_count(len(refs), 'reference')} from {_count(len(by_source), 'symbol')}:")
for shown, (source, rows) in enumerate(by_source.items()):
if shown == limit:
out.append(f"- … {len(by_source) - limit} more symbols")
break
first = rows[0]
kinds = ", ".join(sorted({f"{r['kind']} {r['resolution']}" for r in rows}))
where = ", ".join(str(r["line"]) for r in rows)
name = source.partition("#")[2] or "(module)"
test = " [test]" if first["test"] else ""
out.append(f"- {first['file']}:{where} {name} · {kinds}{test}")
return "\n".join(out)


def run(root: Path, query: str, fmt: str = "md", limit: int = 20, tests: bool = True) -> str:
payload = build(build_symbol_index(root, use_cache=False), query, tests=tests)
return json.dumps(payload, indent=2) if fmt == "json" else render(payload, limit)
32 changes: 32 additions & 0 deletions server/tests/test_symbol_refs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from pathlib import Path

from app.services.symbols import refs
from app.services.symbols.index import build_symbol_index


def write(root: Path, rel: str, text: str) -> None:
p = root / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text, encoding="utf-8")


def test_a_name_lists_every_copy_with_its_references(tmp_path: Path):
write(tmp_path, "src/api.ts", "export type Doc = { id: string };\nexport const load = (): Doc => ({ id: '1' });\n")
write(
tmp_path,
"src/view.ts",
"import { load } from './api';\ntype Doc = { id: string };\nexport function show(): Doc { return load() as Doc; }\n",
)
write(tmp_path, "src/unused.ts", "export type Lonely = { x: number };\n")
idx = build_symbol_index(tmp_path, use_cache=False)

payload = refs.build(idx, "Doc")
decls = {d["id"]: d for d in payload["declarations"]}
assert list(decls) == ["src/api.ts#Doc", "src/view.ts#Doc"] # the exported copy first
assert {r["source"] for r in decls["src/api.ts#Doc"]["references"]} == {"src/api.ts#load"}
assert {r["source"] for r in decls["src/view.ts#Doc"]["references"]} == {"src/view.ts#show"}

# An id picks one declaration; `::` is the CLI spelling of `#`.
assert [d["id"] for d in refs.build(idx, "src/api.ts::load")["declarations"]] == ["src/api.ts#load"]
assert "No references." in refs.render(refs.build(idx, "Lonely"), limit=5)
assert refs.build(idx, "Missing")["declarations"] == []
1 change: 1 addition & 0 deletions site/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export const COMMANDS: [string, string][] = [
['srcly [path]', 'Scan and open the app. --host and --port pick the bind address.'],
['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 <name>', 'Every declaration of a name and what references each one. file::symbol picks one.'],
['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:<n> names a PR.'],
['srcly fix', 'Print a diff of safe fixes for srcly\'s own findings; --write applies them.'],
Expand Down
7 changes: 7 additions & 0 deletions site/src/docs/pages/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ uvx srcly explain . --at src/app.tsx
uvx srcly explain . --at "src/app.tsx::App"
```

`refs` lists every declaration of a name and the symbols that reference each one, from the symbol index. Run it before you move or delete a symbol, and again after, to see that no caller is left. A bare name shows every copy, so a type declared in three files shows three times. `file::symbol` picks one declaration:

```bash
uvx srcly refs DocDetail .
uvx srcly refs "src/services/docs.queries.ts::fetchDoc" . --format json
```

You can also pass a `path:line name` Start at location printed by the report. `explain` reports scan provenance and checker coverage so you can see whether it reused a scan and what remains unmeasured.

## Compare refs
Expand Down
1 change: 1 addition & 0 deletions skills/srcly-code-quality/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,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 <name> .` (`file::symbol` picks one)
- 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`)
Expand Down
Loading