codefactory-cli 0.20.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codefactory/__init__.py +3 -0
- codefactory/__main__.py +5 -0
- codefactory/accept.py +68 -0
- codefactory/analyzers/__init__.py +55 -0
- codefactory/analyzers/generic.py +392 -0
- codefactory/analyzers/parallel.py +113 -0
- codefactory/analyzers/python.py +279 -0
- codefactory/analyzers/python_parse.py +402 -0
- codefactory/analyzers/treewalk.py +299 -0
- codefactory/analyzers/ts_helper.js +483 -0
- codefactory/analyzers/typescript.py +118 -0
- codefactory/apple.py +80 -0
- codefactory/audit.py +227 -0
- codefactory/baseline.py +58 -0
- codefactory/brief.py +330 -0
- codefactory/cache.py +93 -0
- codefactory/checks.py +608 -0
- codefactory/cli.py +782 -0
- codefactory/config.py +157 -0
- codefactory/coverage.py +104 -0
- codefactory/deps.py +182 -0
- codefactory/diff.py +197 -0
- codefactory/efficiency.py +250 -0
- codefactory/flags.py +263 -0
- codefactory/graph.py +95 -0
- codefactory/hotspots.py +344 -0
- codefactory/infra.py +242 -0
- codefactory/intent.py +106 -0
- codefactory/layers.py +143 -0
- codefactory/org.py +131 -0
- codefactory/owners.py +72 -0
- codefactory/patch.py +81 -0
- codefactory/paths.py +93 -0
- codefactory/plan.py +476 -0
- codefactory/privacy.py +221 -0
- codefactory/profile.py +667 -0
- codefactory/rerank.py +161 -0
- codefactory/review.py +1504 -0
- codefactory/rules.py +50 -0
- codefactory/sarif.py +661 -0
- codefactory/sbom.py +78 -0
- codefactory/security.py +537 -0
- codefactory/similar.py +199 -0
- codefactory/skill.py +144 -0
- codefactory/skill_template/SKILL.md +68 -0
- codefactory/skill_template/__init__.py +0 -0
- codefactory/sqlgraph.py +109 -0
- codefactory/suppress.py +92 -0
- codefactory/taint.py +439 -0
- codefactory/trace.py +72 -0
- codefactory/viewer/__init__.py +19 -0
- codefactory/viewer/dashboard.html +43 -0
- codefactory/viewer/factory.css +61 -0
- codefactory/viewer/factory.js +665 -0
- codefactory/viewer/template.html +47 -0
- codefactory_cli-0.20.1.dist-info/METADATA +250 -0
- codefactory_cli-0.20.1.dist-info/RECORD +61 -0
- codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
- codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
- codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
- codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
codefactory/similar.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Near-duplicate functions: copies that were edited afterwards, so their structure is mostly, not exactly, the same.
|
|
2
|
+
|
|
3
|
+
Each function's structure tokens are cut into overlapping 4-token shingles; one-permutation MinHash with banding
|
|
4
|
+
(LSH) finds likely pairs without comparing every pair, then the exact Jaccard similarity of the shingle sets decides.
|
|
5
|
+
Pairs that are exact copies are left to the duplicate check; a function and one nested inside it aren't compared.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import zlib
|
|
11
|
+
from collections import defaultdict
|
|
12
|
+
from operator import eq
|
|
13
|
+
|
|
14
|
+
from .config import Config
|
|
15
|
+
from .graph import Flag, Graph
|
|
16
|
+
from .paths import platform_variants
|
|
17
|
+
|
|
18
|
+
K = 4 # tokens per shingle
|
|
19
|
+
PERMS = 64
|
|
20
|
+
BANDS, ROWS = 16, 4 # PERMS = BANDS * ROWS
|
|
21
|
+
# Matching signature positions estimate the similarity (standard deviation ≈ 0.054 at 0.75 with 64 positions); a pair
|
|
22
|
+
# estimated 0.2 below the threshold (≈3.7 deviations) is skipped without building its shingle sets.
|
|
23
|
+
ESTIMATE_MARGIN = 0.2
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def shingles(tokens: str) -> set[int]:
|
|
27
|
+
t = tokens.split()
|
|
28
|
+
return {zlib.crc32(" ".join(t[i : i + K]).encode("utf-8", "surrogatepass")) for i in range(max(0, len(t) - K + 1))}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
MASK = (1 << 64) - 1
|
|
32
|
+
LOW = (1 << 58) - 1
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def signature(sh: set[int]) -> list[int]:
|
|
36
|
+
"""One-permutation MinHash: each shingle is hashed once into one of PERMS bins, which keep their minimum; empty
|
|
37
|
+
bins borrow the next filled bin's value (densification). As good as PERMS separate hashes for finding pairs, and
|
|
38
|
+
PERMS times cheaper, which matters on millions of lines."""
|
|
39
|
+
sig: list[int | None] = [None] * PERMS
|
|
40
|
+
for x in sh:
|
|
41
|
+
h = ((x + 0x632BE59BD9B4E019) * 0x9E3779B97F4A7C15) & MASK
|
|
42
|
+
h ^= h >> 31
|
|
43
|
+
h = (h * 0xBF58476D1CE4E5B9) & MASK
|
|
44
|
+
b, v = h >> 58, h & LOW # the high bits pick the bin (they're the best mixed), the rest are the value
|
|
45
|
+
cur = sig[b]
|
|
46
|
+
if cur is None or v < cur:
|
|
47
|
+
sig[b] = v
|
|
48
|
+
if all(s is None for s in sig):
|
|
49
|
+
return [0] * PERMS
|
|
50
|
+
out = []
|
|
51
|
+
for i in range(PERMS):
|
|
52
|
+
j, dist = i, 0
|
|
53
|
+
while sig[j] is None:
|
|
54
|
+
j, dist = (j + 1) % PERMS, dist + 1
|
|
55
|
+
out.append(sig[j] + dist * 0x5BD1E995 if dist else sig[j])
|
|
56
|
+
return out
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def jaccard(a: set[int], b: set[int]) -> float:
|
|
60
|
+
return len(a & b) / len(a | b) if a and b else 0.0
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _sig_of(tokens: str) -> list[int]:
|
|
64
|
+
return signature(shingles(tokens))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def signatures(g: Graph, fns: list) -> dict[str, list[int]]:
|
|
68
|
+
"""Each function's signature, reused from `.codefactory/minhash.json` for code that didn't change (keyed by a hash
|
|
69
|
+
of its tokens) and computed on every core for the rest."""
|
|
70
|
+
import hashlib
|
|
71
|
+
import json
|
|
72
|
+
from pathlib import Path
|
|
73
|
+
|
|
74
|
+
from .analyzers.parallel import MIN_PARALLEL, workers
|
|
75
|
+
|
|
76
|
+
path = Path(g.root) / ".codefactory" / "minhash.json" if g.root else None
|
|
77
|
+
try:
|
|
78
|
+
old = json.loads(path.read_text(encoding="utf-8")) if path else {}
|
|
79
|
+
old = old if old.get("v") == 1 else {}
|
|
80
|
+
except (OSError, ValueError):
|
|
81
|
+
old = {}
|
|
82
|
+
keys = {f.id: hashlib.sha1(f.tokens.encode("utf-8", "surrogatepass")).hexdigest()[:20] for f in fns}
|
|
83
|
+
sigs = old.get("sigs", {})
|
|
84
|
+
missing = sorted({keys[f.id]: f.tokens for f in fns if keys[f.id] not in sigs}.items())
|
|
85
|
+
if len(missing) >= MIN_PARALLEL * 8 and workers() > 1:
|
|
86
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
with ProcessPoolExecutor(max_workers=workers()) as pool:
|
|
90
|
+
computed = list(pool.map(_sig_of, [tok for _, tok in missing], chunksize=64))
|
|
91
|
+
except (OSError, RuntimeError, ImportError):
|
|
92
|
+
computed = [_sig_of(tok) for _, tok in missing]
|
|
93
|
+
else:
|
|
94
|
+
computed = [_sig_of(tok) for _, tok in missing]
|
|
95
|
+
sigs.update({k: s for (k, _), s in zip(missing, computed, strict=True)})
|
|
96
|
+
live = {keys[f.id] for f in fns}
|
|
97
|
+
if path and (missing or len(sigs) > len(live)):
|
|
98
|
+
try:
|
|
99
|
+
path.parent.mkdir(exist_ok=True)
|
|
100
|
+
path.write_text(json.dumps({"v": 1, "sigs": {k: v for k, v in sigs.items() if k in live}}), encoding="utf-8")
|
|
101
|
+
except OSError:
|
|
102
|
+
pass
|
|
103
|
+
return {f.id: sigs[keys[f.id]] for f in fns}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def similar_pairs(g: Graph, min_tokens: int = 40, threshold: float = 0.75) -> dict[tuple[str, str], float]:
|
|
107
|
+
fns = [f for f in g.functions if f.tokens and len(f.tokens.split()) >= min_tokens]
|
|
108
|
+
sets: dict[str, set[int]] = {} # built only for functions that land in a bucket with another
|
|
109
|
+
|
|
110
|
+
def shingled(fid: str) -> set[int]:
|
|
111
|
+
if fid not in sets:
|
|
112
|
+
sets[fid] = shingles(by_id[fid].tokens)
|
|
113
|
+
return sets[fid]
|
|
114
|
+
|
|
115
|
+
by_id = {f.id: f for f in fns}
|
|
116
|
+
sig_of = signatures(g, fns)
|
|
117
|
+
buckets = defaultdict(list)
|
|
118
|
+
for f in fns:
|
|
119
|
+
sig = sig_of[f.id]
|
|
120
|
+
for band in range(BANDS):
|
|
121
|
+
buckets[(band, tuple(sig[band * ROWS : (band + 1) * ROWS]))].append(f.id)
|
|
122
|
+
pairs: dict[tuple[str, str], float] = {}
|
|
123
|
+
for ids in buckets.values():
|
|
124
|
+
if len(ids) < 2 or len(ids) > 200: # a giant bucket is boilerplate everyone shares, not copies
|
|
125
|
+
continue
|
|
126
|
+
for i, a in enumerate(ids):
|
|
127
|
+
for b in ids[i + 1 :]:
|
|
128
|
+
key = (a, b) if a < b else (b, a)
|
|
129
|
+
if key in pairs:
|
|
130
|
+
continue
|
|
131
|
+
fa, fb = by_id[a], by_id[b]
|
|
132
|
+
if fa.shape and fa.shape == fb.shape:
|
|
133
|
+
continue # an exact copy: reported as a duplicate
|
|
134
|
+
if platform_variants(fa.file, fb.file):
|
|
135
|
+
continue # the same file for another platform: copied on purpose
|
|
136
|
+
if fa.file == fb.file and fa.name == fb.name:
|
|
137
|
+
continue # overloads (indexOf(int[]), indexOf(long[])): one method per type, as Java requires
|
|
138
|
+
if fa.file == fb.file and (
|
|
139
|
+
fa.qualname.startswith(fb.qualname + ".") or fb.qualname.startswith(fa.qualname + ".")
|
|
140
|
+
):
|
|
141
|
+
continue # one holds the other
|
|
142
|
+
sga, sgb = sig_of[a], sig_of[b]
|
|
143
|
+
if sum(map(eq, sga, sgb)) < (threshold - ESTIMATE_MARGIN) * PERMS:
|
|
144
|
+
continue # the signatures already say it's far below the threshold
|
|
145
|
+
sa, sb = shingled(a), shingled(b)
|
|
146
|
+
na, nb = len(sa), len(sb)
|
|
147
|
+
if min(na, nb) / max(na, nb) < 0.6:
|
|
148
|
+
continue
|
|
149
|
+
sim = jaccard(sa, sb)
|
|
150
|
+
if sim >= threshold:
|
|
151
|
+
pairs[key] = sim
|
|
152
|
+
return pairs
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def near_duplicates(g: Graph, cfg: Config) -> list[Flag]:
|
|
156
|
+
pairs = similar_pairs(g, threshold=cfg.similar_threshold)
|
|
157
|
+
if not pairs:
|
|
158
|
+
return []
|
|
159
|
+
parent: dict[str, str] = {}
|
|
160
|
+
|
|
161
|
+
def find(x: str) -> str:
|
|
162
|
+
parent.setdefault(x, x)
|
|
163
|
+
while parent[x] != x:
|
|
164
|
+
parent[x] = parent[parent[x]]
|
|
165
|
+
x = parent[x]
|
|
166
|
+
return x
|
|
167
|
+
|
|
168
|
+
for a, b in pairs:
|
|
169
|
+
parent[find(a)] = find(b)
|
|
170
|
+
groups = defaultdict(list)
|
|
171
|
+
for x in parent:
|
|
172
|
+
groups[find(x)].append(x)
|
|
173
|
+
by_id = {f.id: f for f in g.functions}
|
|
174
|
+
best: dict[str, float] = defaultdict(float)
|
|
175
|
+
for (a, b), sim in pairs.items():
|
|
176
|
+
best[a] = max(best[a], sim)
|
|
177
|
+
best[b] = max(best[b], sim)
|
|
178
|
+
out = []
|
|
179
|
+
for members in groups.values():
|
|
180
|
+
members.sort()
|
|
181
|
+
for m in members:
|
|
182
|
+
others = [o for o in members if o != m]
|
|
183
|
+
sims = [pairs.get((m, o) if m < o else (o, m)) for o in others]
|
|
184
|
+
known = [s for s in sims if s]
|
|
185
|
+
names = ", ".join(by_id[o].qualname for o in others[:4]) + (" …" if len(others) > 4 else "")
|
|
186
|
+
lo, hi = round(min(known) * 100), round(max(known) * 100)
|
|
187
|
+
pct = f"{lo}–{hi}%" if lo != hi else f"{hi}%"
|
|
188
|
+
out.append(
|
|
189
|
+
Flag(
|
|
190
|
+
"similar",
|
|
191
|
+
"warn" if best[m] >= 0.85 else "info",
|
|
192
|
+
m,
|
|
193
|
+
f"{pct} similar to {names}: likely a copy that was edited",
|
|
194
|
+
others,
|
|
195
|
+
line=by_id[m].line,
|
|
196
|
+
score=round(best[m], 3),
|
|
197
|
+
)
|
|
198
|
+
)
|
|
199
|
+
return out
|
codefactory/skill.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Keeps Claude Code's codefactory current in a repository.
|
|
2
|
+
|
|
3
|
+
- The skill (.claude/skills/codefactory/SKILL.md) teaches Claude when and how to use each command. It carries the
|
|
4
|
+
version that wrote it. The session hook, `codefactory skill` and `codefactory update` rewrite it when its
|
|
5
|
+
instructions changed; other commands only say so, because they must never change the repository they analyze.
|
|
6
|
+
- The session-start hook (.claude/hooks/codefactory.sh, registered in .claude/settings.json) installs codefactory if
|
|
7
|
+
it's missing and upgrades it at most once a day, then refreshes the skill. It never blocks or fails a session.
|
|
8
|
+
- `codefactory update` upgrades the installed tool on demand.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
from importlib.resources import files
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from . import __version__
|
|
21
|
+
|
|
22
|
+
SOURCE = "codefactory[languages] @ git+https://github.com/dominickkubica/codefactory"
|
|
23
|
+
STAMP = re.compile(r"<!-- codefactory skill (\S+) -->")
|
|
24
|
+
HOOK_NAME = "codefactory.sh"
|
|
25
|
+
HOOK_COMMAND = f'"$CLAUDE_PROJECT_DIR"/.claude/hooks/{HOOK_NAME}'
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def skill_path(repo: Path) -> Path:
|
|
29
|
+
return repo / ".claude" / "skills" / "codefactory" / "SKILL.md"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def skill_text() -> str:
|
|
33
|
+
text = (files("codefactory") / "skill_template" / "SKILL.md").read_text(encoding="utf-8")
|
|
34
|
+
# the stamp goes right after the front matter, which must stay first for Claude Code to read the skill
|
|
35
|
+
head, sep, body = text.partition("\n---\n")
|
|
36
|
+
return f"{head}{sep}<!-- codefactory skill {__version__} -->\n{body}" if sep else text
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def install_skill(repo: Path) -> Path:
|
|
40
|
+
if not repo.is_dir():
|
|
41
|
+
raise ValueError(f"{repo} is not a folder")
|
|
42
|
+
target = skill_path(repo)
|
|
43
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
target.write_text(skill_text(), encoding="utf-8")
|
|
45
|
+
return target
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def skill_outdated(repo: Path) -> bool:
|
|
49
|
+
"""The repository's skill was written for different instructions than this version's. Read-only: ordinary commands
|
|
50
|
+
must never change files in the repository they analyze (a clean checkout or CI run would end up dirty)."""
|
|
51
|
+
try:
|
|
52
|
+
target = skill_path(repo)
|
|
53
|
+
if not target.is_file():
|
|
54
|
+
return False
|
|
55
|
+
return STAMP.sub("", target.read_text(encoding="utf-8")) != STAMP.sub("", skill_text())
|
|
56
|
+
except OSError:
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def refresh_skill(repo: Path) -> bool:
|
|
61
|
+
"""Rewrites the repository's skill if an older codefactory wrote it. True if it did. Never raises."""
|
|
62
|
+
try:
|
|
63
|
+
target = skill_path(repo)
|
|
64
|
+
if not target.is_file():
|
|
65
|
+
return False
|
|
66
|
+
text = target.read_text(encoding="utf-8")
|
|
67
|
+
current = STAMP.search(text)
|
|
68
|
+
if current and current.group(1) == __version__:
|
|
69
|
+
return False
|
|
70
|
+
if current and STAMP.sub("", text) == STAMP.sub("", skill_text()):
|
|
71
|
+
return False # same instructions: don't leave a version-only diff in the repository
|
|
72
|
+
target.write_text(skill_text(), encoding="utf-8")
|
|
73
|
+
return True
|
|
74
|
+
except OSError:
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
HOOK_SCRIPT = """#!/bin/bash
|
|
79
|
+
# codefactory for Claude Code (installed by `codefactory skill --hook`).
|
|
80
|
+
# At each session start: install codefactory if it's missing, upgrade it at most once a day, and refresh this
|
|
81
|
+
# repository's codefactory skill. Any failure is ignored: this never blocks or breaks a session.
|
|
82
|
+
set -u
|
|
83
|
+
cd "${CLAUDE_PROJECT_DIR:-.}" || exit 0
|
|
84
|
+
|
|
85
|
+
SOURCE="__SOURCE__"
|
|
86
|
+
PY=""
|
|
87
|
+
for c in python3 python py; do # the first that really runs (Windows has a python3 stub that doesn't)
|
|
88
|
+
if command -v "$c" >/dev/null 2>&1 && "$c" -c "" >/dev/null 2>&1; then PY="$c"; break; fi
|
|
89
|
+
done
|
|
90
|
+
[ -n "$PY" ] || exit 0
|
|
91
|
+
STAMP="${HOME:-/tmp}/.cache/codefactory/last-update"
|
|
92
|
+
mkdir -p "$(dirname "$STAMP")" 2>/dev/null
|
|
93
|
+
|
|
94
|
+
install() { # $1: what to install
|
|
95
|
+
if command -v timeout >/dev/null 2>&1; then timeout 180 "$PY" -m pip install --quiet --upgrade "$1" >/dev/null 2>&1
|
|
96
|
+
else "$PY" -m pip install --quiet --upgrade "$1" >/dev/null 2>&1; fi
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if [ -f ../codefactory/pyproject.toml ]; then
|
|
100
|
+
# a checkout of codefactory next to this repository (a cloud session with both attached): use it as is
|
|
101
|
+
"$PY" -c "import codefactory" 2>/dev/null || install -e "../codefactory[languages]"
|
|
102
|
+
elif ! "$PY" -c "import codefactory" 2>/dev/null || [ -z "$(find "$STAMP" -mmin -1440 2>/dev/null)" ]; then
|
|
103
|
+
install "$SOURCE" && touch "$STAMP"
|
|
104
|
+
fi
|
|
105
|
+
|
|
106
|
+
if "$PY" -c "import codefactory" 2>/dev/null; then
|
|
107
|
+
"$PY" -m codefactory skill . >/dev/null 2>&1
|
|
108
|
+
V="$("$PY" -c 'import codefactory; print(codefactory.__version__)')"
|
|
109
|
+
echo "codefactory $V is installed: see .claude/skills/codefactory/SKILL.md"
|
|
110
|
+
fi
|
|
111
|
+
exit 0
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def install_hook(repo: Path) -> tuple[Path, Path]:
|
|
116
|
+
"""Writes the hook script and registers it as a SessionStart hook, keeping everything else in settings.json."""
|
|
117
|
+
hook = repo / ".claude" / "hooks" / HOOK_NAME
|
|
118
|
+
hook.parent.mkdir(parents=True, exist_ok=True)
|
|
119
|
+
hook.write_text(HOOK_SCRIPT.replace("__SOURCE__", SOURCE), encoding="utf-8", newline="\n")
|
|
120
|
+
hook.chmod(0o755)
|
|
121
|
+
settings_file = repo / ".claude" / "settings.json"
|
|
122
|
+
try:
|
|
123
|
+
settings = json.loads(settings_file.read_text(encoding="utf-8")) if settings_file.is_file() else {}
|
|
124
|
+
except ValueError as e:
|
|
125
|
+
raise ValueError(f"{settings_file} isn't valid JSON ({e}); fix it, then run this again") from None
|
|
126
|
+
groups = settings.setdefault("hooks", {}).setdefault("SessionStart", [])
|
|
127
|
+
registered = any(h.get("command") == HOOK_COMMAND for g in groups for h in g.get("hooks", []))
|
|
128
|
+
if not registered:
|
|
129
|
+
groups.append({"hooks": [{"type": "command", "command": HOOK_COMMAND, "timeout": 240}]})
|
|
130
|
+
settings_file.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8")
|
|
131
|
+
return hook, settings_file
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def update(source: str = SOURCE) -> tuple[str, str]:
|
|
135
|
+
"""Upgrades codefactory with this Python's pip. Returns (old version, new version)."""
|
|
136
|
+
proc = subprocess.run(
|
|
137
|
+
[sys.executable, "-m", "pip", "install", "--quiet", "--upgrade", source], capture_output=True, text=True
|
|
138
|
+
)
|
|
139
|
+
if proc.returncode != 0:
|
|
140
|
+
raise RuntimeError(f"pip couldn't upgrade codefactory:\n{proc.stderr.strip()[-1500:]}")
|
|
141
|
+
new = subprocess.run(
|
|
142
|
+
[sys.executable, "-c", "import codefactory; print(codefactory.__version__)"], capture_output=True, text=True
|
|
143
|
+
).stdout.strip()
|
|
144
|
+
return __version__, new or "?"
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: codefactory
|
|
3
|
+
description: Map this codebase's structure (layers, who calls what) and find copied code, database/network calls inside loops (N+1), dead code, import loops, and security, reliability and delivery problems. Use before restructuring, deduplicating or optimizing; when asked to review the codebase; before changing or deleting a function or file (to see callers, impact and which tests to run); and when debugging how one part reaches another.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# codefactory
|
|
7
|
+
|
|
8
|
+
`codefactory` statically analyzes this repo into a call graph and lists issues with `file:line`. The first run takes a few seconds to ~30 s; later runs reuse `.codefactory/graph.json` until a source
|
|
9
|
+
file changes. Run it from the repo root. If the command isn't found, use `python -m codefactory`; if it isn't
|
|
10
|
+
installed at all, `pip install "codefactory[languages] @ git+https://github.com/dominickkubica/codefactory"`.
|
|
11
|
+
It reads Python and TypeScript/JavaScript precisely; Go, Java, Kotlin, Swift, Rust, C/C++, C#, Ruby, PHP and others
|
|
12
|
+
through tree-sitter, matching calls by name, so for those languages treat call, impact and unused findings as leads
|
|
13
|
+
to confirm in the code. Big repositories are fine: files are parsed in parallel and cached per file. If a command below is missing or
|
|
14
|
+
an option is rejected, run `codefactory update` (it also refreshes this file to match the installed version).
|
|
15
|
+
|
|
16
|
+
## When to use which command
|
|
17
|
+
|
|
18
|
+
| Situation | Command |
|
|
19
|
+
|---|---|
|
|
20
|
+
| Starting a restructure, cleanup or performance pass | `codefactory brief` (layers, most-used code, issues grouped by what to do, copied-code groups with lines saved) |
|
|
21
|
+
| Asked to review the codebase (architecture, security, reliability, quality) | `codefactory review --for-ai` (add `--online` to check dependencies for known vulnerabilities, if the user agrees to send package names to OSV.dev), then confirm or reject each finding from its cited lines and judge the risky code it includes; read other files only when a finding needs it |
|
|
22
|
+
| Deciding what to work on | `codefactory plan` (ranked tasks with steps and tests); `codefactory prompt <id or rank>` prints one task as a full brief to follow |
|
|
23
|
+
| About to change, move, rename or delete a function or file | `codefactory context <name or path>` (callers, what it calls, how many functions/files depend on it, tests that exercise it) |
|
|
24
|
+
| Debugging: what does X eventually do? | `codefactory trace <function>` |
|
|
25
|
+
| Debugging: how does A end up calling B? | `codefactory path <A> <B>` |
|
|
26
|
+
| A list to work through | `codefactory flags --kind similar --kind duplicate`, `--kind io_in_loop`, `--min warn`; add `--json` to parse |
|
|
27
|
+
| Any other question | `codefactory query "SELECT … FROM function_stats …"` (tables files, functions, edges, flags; views function_stats(fan_in, fan_out, caller_files), file_deps) |
|
|
28
|
+
| Security work: which endpoints exist, which check auth, what they change | `codefactory surface` (method, path, auth found, changes data, risky code reached); the review ranks risky lines by whether a request reaches them |
|
|
29
|
+
| What kind of project is this, and what's risky about it? | `codefactory profile` (kind, where it runs, users, sensitive data, with evidence; the review ranks findings for it) |
|
|
30
|
+
| Where does change happen / what to refactor first? | `codefactory hotspots` (complex code changed often, files that change together without importing each other) |
|
|
31
|
+
| Reviewing a branch or pull request: what does this change add? | `codefactory diff --base main` (new and fixed findings, matched by identity, not line) |
|
|
32
|
+
| Checking a patch or proposed change without the repository | `codefactory diff --patch change.diff` (or `-` for stdin): the line checks on the lines it adds |
|
|
33
|
+
| Dependency inventory or supply-chain questions | `codefactory sbom -o sbom.cdx.json` (CycloneDX, every pinned dependency with its package URL; offline) |
|
|
34
|
+
| A finding is intended (confirmed safe, deliberate) | `codefactory accept <kind> <file> --why "…"` or `codefactory accept <plan task id> --why "…"` (writes a rule to `factory.toml`; the user decides whether to commit it) |
|
|
35
|
+
| Showing the human | `codefactory view -o <file>.html` (an interactive factory-floor map; lenses for duplication, efficiency, size) |
|
|
36
|
+
|
|
37
|
+
## Working rules
|
|
38
|
+
|
|
39
|
+
1. **Check impact before editing.** Run `context` on what you'll change. If it has many callers or a large impact,
|
|
40
|
+
keep its signature, or update every caller it lists.
|
|
41
|
+
2. **Copied code (`duplicate`, `similar`).** Merge into one function in the lowest layer that all copies' callers can
|
|
42
|
+
import (usually `lib`/`utils`), then point each copy's callers at it. `brief` lists groups by lines saved.
|
|
43
|
+
3. **Calls in loops (`io_in_loop`).** `warn` = reads or network: replace the per-item call with one batched query
|
|
44
|
+
(`WHERE id IN (…)`, a JOIN) or one request. `info` = writes, files or programs: batch only if many items. Writes
|
|
45
|
+
already inside a transaction (also one opened by every caller) and sleeps aren't reported, so a reported write
|
|
46
|
+
is outside one: wrapping the loop in a transaction is usually the fix.
|
|
47
|
+
4. **`unused`, `test_only` and "no test reaches it" are hints, not proof** (exact only when the review says it
|
|
48
|
+
measured coverage from a report). Frameworks call some code by name (routes, handlers, exports
|
|
49
|
+
loaded by convention). Search for the name (including strings) before deleting.
|
|
50
|
+
5. **Static analysis misses dynamic calls** (getattr, callbacks stored in variables, untyped `obj.method()`). Treat
|
|
51
|
+
"no callers" as "no callers found".
|
|
52
|
+
6. **After changing, verify.** Run `codefactory check` if the repo has a `codefactory-baseline.json` (it fails on
|
|
53
|
+
issues your change introduced), otherwise re-run `codefactory flags --min warn` and compare with before. Run the
|
|
54
|
+
tests `context` (or the task) listed, plus the project's test command.
|
|
55
|
+
7. **An issue that's intended** (a bounded loop, a deliberate copy, code a framework calls by name): don't contort the
|
|
56
|
+
code. Add a comment on the line above the function or the flagged line, saying why:
|
|
57
|
+
`// codefactory: ignore io_in_loop — one query per table, there are 7` (or `# …` in Python). It moves to
|
|
58
|
+
`codefactory flags --silenced` with its reason. Where editing the code isn't wanted, `codefactory accept` records
|
|
59
|
+
the same in `factory.toml`; ask the user before accepting findings on their behalf.
|
|
60
|
+
8. **Don't update the baseline yourself** (`codefactory baseline`) unless the user asks: it's the line that new
|
|
61
|
+
issues are measured against.
|
|
62
|
+
|
|
63
|
+
## Interpreting severities
|
|
64
|
+
|
|
65
|
+
- `high`: import loops, layer violations (from `factory.toml`). Fix.
|
|
66
|
+
- `warn`: copies, N+1 loops, dead code. Worth fixing while working nearby.
|
|
67
|
+
- `info`: long functions, hubs, searches/awaits in loops, writes, file and program operations in loops. Context for
|
|
68
|
+
decisions.
|
|
File without changes
|
codefactory/sqlgraph.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""The graph as a SQLite database, so any question about the code is a SQL query.
|
|
2
|
+
|
|
3
|
+
Tables: files, functions, edges, flags. Views: function_stats (fan-in/out per function), file_deps (calls between
|
|
4
|
+
files). Saved queries in factory.toml run against the same database and become flags.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import sqlite3
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
SCHEMA = """
|
|
13
|
+
CREATE TABLE files (id TEXT PRIMARY KEY, module TEXT, loc INTEGER, layer TEXT);
|
|
14
|
+
CREATE TABLE functions (id TEXT PRIMARY KEY, file TEXT REFERENCES files(id), name TEXT, qualname TEXT,
|
|
15
|
+
line INTEGER, end_line INTEGER, loc INTEGER, kind TEXT, decorated INTEGER, exported INTEGER, dynamic INTEGER);
|
|
16
|
+
CREATE TABLE edges (src TEXT, dst TEXT, kind TEXT, count INTEGER);
|
|
17
|
+
CREATE TABLE flags (kind TEXT, severity TEXT, target TEXT, message TEXT, line INTEGER);
|
|
18
|
+
CREATE INDEX edges_src ON edges(src, kind);
|
|
19
|
+
CREATE INDEX edges_dst ON edges(dst, kind);
|
|
20
|
+
CREATE INDEX functions_file ON functions(file);
|
|
21
|
+
CREATE VIEW function_stats AS
|
|
22
|
+
SELECT f.id, f.file, f.qualname, f.loc,
|
|
23
|
+
(SELECT COUNT(*) FROM edges e WHERE e.dst = f.id AND e.kind = 'call') AS fan_in,
|
|
24
|
+
(SELECT COUNT(*) FROM edges e WHERE e.src = f.id AND e.kind = 'call') AS fan_out,
|
|
25
|
+
(SELECT COUNT(DISTINCT c.file) FROM edges e JOIN functions c ON c.id = e.src
|
|
26
|
+
WHERE e.dst = f.id AND e.kind = 'call' AND c.file != f.file) AS caller_files
|
|
27
|
+
FROM functions f WHERE f.kind != 'module';
|
|
28
|
+
CREATE VIEW file_deps AS
|
|
29
|
+
SELECT a.file AS src_file, b.file AS dst_file, SUM(e.count) AS calls
|
|
30
|
+
FROM edges e JOIN functions a ON a.id = e.src JOIN functions b ON b.id = e.dst
|
|
31
|
+
WHERE e.kind = 'call' AND a.file != b.file GROUP BY a.file, b.file;
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def to_sqlite(graph: dict, path: str | Path = ":memory:") -> sqlite3.Connection:
|
|
36
|
+
if path != ":memory:":
|
|
37
|
+
Path(path).unlink(missing_ok=True)
|
|
38
|
+
db = sqlite3.connect(str(path))
|
|
39
|
+
db.executescript(SCHEMA)
|
|
40
|
+
db.executemany(
|
|
41
|
+
"INSERT INTO files VALUES (?, ?, ?, ?)", [(f["id"], f["module"], f["loc"], f["layer"]) for f in graph["files"]]
|
|
42
|
+
)
|
|
43
|
+
db.executemany(
|
|
44
|
+
"INSERT INTO functions VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
45
|
+
[
|
|
46
|
+
(
|
|
47
|
+
f["id"],
|
|
48
|
+
f["file"],
|
|
49
|
+
f["name"],
|
|
50
|
+
f["qualname"],
|
|
51
|
+
f["line"],
|
|
52
|
+
f["end"],
|
|
53
|
+
f["loc"],
|
|
54
|
+
f["kind"],
|
|
55
|
+
int(f["decorated"]),
|
|
56
|
+
int(f["exported"]),
|
|
57
|
+
int(f.get("dynamic", False)),
|
|
58
|
+
)
|
|
59
|
+
for f in graph["functions"]
|
|
60
|
+
],
|
|
61
|
+
)
|
|
62
|
+
db.executemany("INSERT INTO edges VALUES (?, ?, ?, ?)", [(e["src"], e["dst"], e["kind"], e["count"]) for e in graph["edges"]])
|
|
63
|
+
db.executemany(
|
|
64
|
+
"INSERT INTO flags VALUES (?, ?, ?, ?, ?)",
|
|
65
|
+
[(f["kind"], f["severity"], f["target"], f["message"], f.get("line", 0)) for f in graph["flags"]],
|
|
66
|
+
)
|
|
67
|
+
db.commit()
|
|
68
|
+
return db
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def run_query(db: sqlite3.Connection, sql: str) -> tuple[list[str], list[tuple]]:
|
|
72
|
+
cur = db.execute(sql)
|
|
73
|
+
cols = [d[0] for d in cur.description or []]
|
|
74
|
+
return cols, cur.fetchall()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def query_flags(graph: dict, queries: list[dict]) -> list[dict]:
|
|
78
|
+
"""Saved queries -> flags. Each row is one issue: a `target` column (file or function id), and optionally
|
|
79
|
+
`message`; any other columns are added to the message."""
|
|
80
|
+
if not queries:
|
|
81
|
+
return []
|
|
82
|
+
db = to_sqlite(graph)
|
|
83
|
+
try:
|
|
84
|
+
return _rows_to_flags(db, queries)
|
|
85
|
+
finally:
|
|
86
|
+
db.close()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _rows_to_flags(db: sqlite3.Connection, queries: list[dict]) -> list[dict]:
|
|
90
|
+
out = []
|
|
91
|
+
for q in queries:
|
|
92
|
+
# codefactory: ignore io_in_loop — one query per saved query in factory.toml, on an in-memory database
|
|
93
|
+
cols, rows = run_query(db, q["sql"])
|
|
94
|
+
if "target" not in cols:
|
|
95
|
+
raise ValueError(f"Saved query {q['name']!r} must return a 'target' column")
|
|
96
|
+
for row in rows:
|
|
97
|
+
r = dict(zip(cols, row, strict=True))
|
|
98
|
+
extra = ", ".join(f"{k} {v}" for k, v in r.items() if k not in ("target", "message"))
|
|
99
|
+
msg = r.get("message") or q.get("message") or q["name"]
|
|
100
|
+
out.append(
|
|
101
|
+
{
|
|
102
|
+
"kind": q["name"],
|
|
103
|
+
"severity": q.get("severity", "warn"),
|
|
104
|
+
"target": str(r["target"]),
|
|
105
|
+
"message": f"{msg} ({extra})" if extra else str(msg),
|
|
106
|
+
"related": [],
|
|
107
|
+
}
|
|
108
|
+
)
|
|
109
|
+
return out
|
codefactory/suppress.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Silencing issues that are intended, so the list stays worth reading.
|
|
2
|
+
|
|
3
|
+
In code, on the function's line, the flagged line, or the line above either (any comment style):
|
|
4
|
+
// codefactory: ignore io_in_loop — one query per table, there are 7
|
|
5
|
+
# codefactory: ignore unused, test_only: called by the router by name
|
|
6
|
+
// codefactory: ignore — everything on this function
|
|
7
|
+
Anywhere in a file, for the whole file:
|
|
8
|
+
// codefactory: ignore-file duplicate — generated code
|
|
9
|
+
In factory.toml:
|
|
10
|
+
[[silence]]
|
|
11
|
+
kind = "io_in_loop" # or "*" (the default)
|
|
12
|
+
where = "src/db/backup.ts" # a file or file::function glob
|
|
13
|
+
reason = "bounded by the number of tables"
|
|
14
|
+
|
|
15
|
+
Silenced issues leave the list but stay in the graph (Graph.silenced) with their reason, so nothing hides quietly.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import re
|
|
21
|
+
from fnmatch import fnmatch
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from .config import Config
|
|
25
|
+
from .graph import Graph
|
|
26
|
+
|
|
27
|
+
MARK = re.compile(r"codefactory:\s*ignore(-file)?\b([^\n]*)", re.I)
|
|
28
|
+
KIND_WORD = re.compile(r"[a-z_]+")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _parse(rest: str) -> tuple[set[str], str]:
|
|
32
|
+
"""'io_in_loop, unused — reason' -> ({io_in_loop, unused}, 'reason'). No kinds = every kind."""
|
|
33
|
+
m = re.match(r"\s*([a-z_,\s]*?)\s*(?:[—–:]|\s-\s|$)(.*)", rest, re.I)
|
|
34
|
+
kinds_part, reason = (m.group(1), m.group(2).strip()) if m else ("", rest.strip())
|
|
35
|
+
kinds = {k.lower() for k in KIND_WORD.findall(kinds_part)} - {"all"}
|
|
36
|
+
return kinds, reason.strip(" -—–:")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _Sources:
|
|
40
|
+
def __init__(self, root: Path):
|
|
41
|
+
self.root, self.cache, self.rules = root, {}, {}
|
|
42
|
+
|
|
43
|
+
def lines(self, file: str) -> list[str]:
|
|
44
|
+
"""The file's lines, or none when it has no codefactory comment at all (most files: nothing to look up)."""
|
|
45
|
+
if file not in self.cache:
|
|
46
|
+
try:
|
|
47
|
+
text = (self.root / file).read_text(encoding="utf-8", errors="replace")
|
|
48
|
+
except OSError:
|
|
49
|
+
text = ""
|
|
50
|
+
self.cache[file] = text.splitlines() if MARK.search(text) else []
|
|
51
|
+
return self.cache[file]
|
|
52
|
+
|
|
53
|
+
def file_rules(self, file: str) -> list[tuple[set[str], str]]:
|
|
54
|
+
if file not in self.rules:
|
|
55
|
+
self.rules[file] = [_parse(m.group(2)) for line in self.lines(file) if (m := MARK.search(line)) and m.group(1)]
|
|
56
|
+
return self.rules[file]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def apply_suppressions(g: Graph, root: Path, cfg: Config) -> None:
|
|
60
|
+
src = _Sources(root)
|
|
61
|
+
by_id = {fn.id: fn for fn in g.functions}
|
|
62
|
+
keep = []
|
|
63
|
+
for f in g.flags:
|
|
64
|
+
fn = by_id.get(f.target)
|
|
65
|
+
file = fn.file if fn else f.target
|
|
66
|
+
reason = _match(f, fn, file, src, cfg)
|
|
67
|
+
if reason is None:
|
|
68
|
+
keep.append(f)
|
|
69
|
+
else:
|
|
70
|
+
f.reason = reason or "marked as intended"
|
|
71
|
+
g.silenced.append(f)
|
|
72
|
+
g.flags = keep
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _match(f, fn, file: str, src: _Sources, cfg: Config) -> str | None:
|
|
76
|
+
lines = src.lines(file)
|
|
77
|
+
spots = {f.line, f.line - 1}
|
|
78
|
+
if fn and fn.kind != "module":
|
|
79
|
+
spots |= {fn.line, fn.line - 1}
|
|
80
|
+
for ln in sorted(spots):
|
|
81
|
+
if 1 <= ln <= len(lines) and (m := MARK.search(lines[ln - 1])) and not m.group(1):
|
|
82
|
+
kinds, reason = _parse(m.group(2))
|
|
83
|
+
if not kinds or f.kind in kinds:
|
|
84
|
+
return reason
|
|
85
|
+
for kinds, reason in src.file_rules(file):
|
|
86
|
+
if not kinds or f.kind in kinds:
|
|
87
|
+
return reason
|
|
88
|
+
target = f"{file}::{fn.qualname}" if fn and fn.kind != "module" else file
|
|
89
|
+
for rule in cfg.silence:
|
|
90
|
+
if rule["kind"] in ("*", f.kind) and (fnmatch(target, rule["where"]) or fnmatch(file, rule["where"])):
|
|
91
|
+
return rule["reason"]
|
|
92
|
+
return None
|