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.
Files changed (61) hide show
  1. codefactory/__init__.py +3 -0
  2. codefactory/__main__.py +5 -0
  3. codefactory/accept.py +68 -0
  4. codefactory/analyzers/__init__.py +55 -0
  5. codefactory/analyzers/generic.py +392 -0
  6. codefactory/analyzers/parallel.py +113 -0
  7. codefactory/analyzers/python.py +279 -0
  8. codefactory/analyzers/python_parse.py +402 -0
  9. codefactory/analyzers/treewalk.py +299 -0
  10. codefactory/analyzers/ts_helper.js +483 -0
  11. codefactory/analyzers/typescript.py +118 -0
  12. codefactory/apple.py +80 -0
  13. codefactory/audit.py +227 -0
  14. codefactory/baseline.py +58 -0
  15. codefactory/brief.py +330 -0
  16. codefactory/cache.py +93 -0
  17. codefactory/checks.py +608 -0
  18. codefactory/cli.py +782 -0
  19. codefactory/config.py +157 -0
  20. codefactory/coverage.py +104 -0
  21. codefactory/deps.py +182 -0
  22. codefactory/diff.py +197 -0
  23. codefactory/efficiency.py +250 -0
  24. codefactory/flags.py +263 -0
  25. codefactory/graph.py +95 -0
  26. codefactory/hotspots.py +344 -0
  27. codefactory/infra.py +242 -0
  28. codefactory/intent.py +106 -0
  29. codefactory/layers.py +143 -0
  30. codefactory/org.py +131 -0
  31. codefactory/owners.py +72 -0
  32. codefactory/patch.py +81 -0
  33. codefactory/paths.py +93 -0
  34. codefactory/plan.py +476 -0
  35. codefactory/privacy.py +221 -0
  36. codefactory/profile.py +667 -0
  37. codefactory/rerank.py +161 -0
  38. codefactory/review.py +1504 -0
  39. codefactory/rules.py +50 -0
  40. codefactory/sarif.py +661 -0
  41. codefactory/sbom.py +78 -0
  42. codefactory/security.py +537 -0
  43. codefactory/similar.py +199 -0
  44. codefactory/skill.py +144 -0
  45. codefactory/skill_template/SKILL.md +68 -0
  46. codefactory/skill_template/__init__.py +0 -0
  47. codefactory/sqlgraph.py +109 -0
  48. codefactory/suppress.py +92 -0
  49. codefactory/taint.py +439 -0
  50. codefactory/trace.py +72 -0
  51. codefactory/viewer/__init__.py +19 -0
  52. codefactory/viewer/dashboard.html +43 -0
  53. codefactory/viewer/factory.css +61 -0
  54. codefactory/viewer/factory.js +665 -0
  55. codefactory/viewer/template.html +47 -0
  56. codefactory_cli-0.20.1.dist-info/METADATA +250 -0
  57. codefactory_cli-0.20.1.dist-info/RECORD +61 -0
  58. codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
  59. codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
  60. codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
  61. codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
codefactory/cli.py ADDED
@@ -0,0 +1,782 @@
1
+ """codefactory command line: map a codebase, list its issues, query it with SQL, trace calls, brief an AI agent, or
2
+ open the factory view."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import contextlib
8
+ import functools
9
+ import json
10
+ import os
11
+ import sys
12
+ import webbrowser
13
+ from pathlib import Path
14
+
15
+ from . import __version__
16
+ from .analyzers import LANGUAGES, analyze
17
+ from .baseline import baseline_path, compare, read_baseline, write_baseline
18
+ from .brief import brief_markdown, context_data, context_markdown
19
+ from .cache import load_cached, save_cache
20
+ from .checks import scan_sources
21
+ from .config import load_config
22
+ from .flags import SEVERITY_ORDER, run_flags
23
+ from .graph import Flag, Graph
24
+ from .layers import assign_layers
25
+ from .plan import make_plan, plan_markdown
26
+ from .review import review_markdown
27
+ from .sarif import build_sarif, github_annotations
28
+ from .skill import SOURCE as SKILL_SOURCE
29
+ from .skill import install_hook, install_skill, refresh_skill, skill_outdated, update
30
+ from .sqlgraph import query_flags, run_query, to_sqlite
31
+ from .suppress import apply_suppressions
32
+ from .trace import find_function, shortest_path, trace
33
+ from .viewer import render_html
34
+
35
+
36
+ def build(root: Path, languages: list[str] | None = None, cache: bool = True) -> Graph:
37
+ cfg = load_config(root)
38
+ g = analyze(root, cfg.ignore, languages, cache)
39
+ assign_layers(g, cfg)
40
+ run_flags(g, cfg)
41
+ if any(f.id.endswith(".py") for f in g.files):
42
+ from .taint import taint_flags
43
+
44
+ g.flags += taint_flags(g, root)
45
+ if cfg.rules:
46
+ from .rules import custom_flags
47
+
48
+ g.flags += custom_flags(g, root, cfg)
49
+ if cfg.queries:
50
+ g.flags += [Flag(**f) for f in query_flags(g.to_dict(), cfg.queries)]
51
+ g.flags.sort(key=lambda f: (SEVERITY_ORDER[f.severity], f.kind, f.target))
52
+ apply_suppressions(g, root, cfg)
53
+ return g
54
+
55
+
56
+ def load_graph(path: Path, languages: list[str] | None = None, cache: bool = True) -> dict:
57
+ """A graph from a saved .json, or by analyzing a folder (reusing .codefactory/graph.json while no source changed)."""
58
+ if path.is_file() and path.suffix == ".json":
59
+ return json.loads(path.read_text(encoding="utf-8"))
60
+ if not path.is_dir():
61
+ raise SystemExit(f"codefactory: {path} is not a folder or a graph .json file")
62
+ root = path.resolve()
63
+ ignore = load_config(root).ignore
64
+ if cache and not languages:
65
+ hit = load_cached(root, ignore)
66
+ if hit is not None:
67
+ return hit
68
+ graph = build(root, languages, cache).to_dict()
69
+ if cache and not languages:
70
+ save_cache(root, ignore, graph)
71
+ return graph
72
+
73
+
74
+ def _table(cols: list[str], rows: list[tuple], limit: int = 200) -> str:
75
+ rows = [tuple("" if v is None else str(v) for v in r) for r in rows[:limit]]
76
+ widths = [min(60, max([len(c)] + [len(r[i]) for r in rows])) for i, c in enumerate(cols)]
77
+ line = lambda vals: " ".join(v[:w].ljust(w) for v, w in zip(vals, widths, strict=True)) # noqa: E731
78
+ return "\n".join([line(cols), line(["-" * w for w in widths]), *map(line, rows)])
79
+
80
+
81
+ def _write(path: Path, text: str) -> None:
82
+ """Writes an output file, or explains plainly why it can't (the folder doesn't exist, no permission)."""
83
+ if not path.parent.exists():
84
+ raise SystemExit(
85
+ f"codefactory: can't save {path}: the folder {path.parent} doesn't exist. "
86
+ "Pick an existing folder with -o (on Windows, a OneDrive-synced Desktop is under OneDrive\\Desktop)."
87
+ )
88
+ try:
89
+ path.write_text(text, encoding="utf-8")
90
+ except OSError as e:
91
+ raise SystemExit(f"codefactory: can't save {path}: {e.strerror or e}") from None
92
+
93
+
94
+ def _one_function(graph: dict, name: str) -> dict:
95
+ hits = find_function(graph, name)
96
+ if not hits:
97
+ raise SystemExit(f"codefactory: no function matches {name!r}")
98
+ if len(hits) > 1:
99
+ raise SystemExit(
100
+ f"codefactory: {name!r} matches {len(hits)} functions; use the full id:\n " + "\n ".join(h["id"] for h in hits[:20])
101
+ )
102
+ return hits[0]
103
+
104
+
105
+ def _safe_stdout() -> None:
106
+ """Output piped or redirected on Windows defaults to a code page without → or ·: write UTF-8 there instead, and
107
+ never crash on a character a console can't show."""
108
+ out = sys.stdout
109
+ if not hasattr(out, "reconfigure"):
110
+ return
111
+ with contextlib.suppress(ValueError, OSError):
112
+ out.reconfigure(encoding="utf-8") if not out.isatty() else out.reconfigure(errors="replace")
113
+
114
+
115
+ def _split(values: list[str], wanted: int) -> tuple[str, list[str]]:
116
+ """Commands that take names also take the repo first: `trace fn` or `trace path/to/repo fn`."""
117
+ if len(values) == wanted:
118
+ return ".", values
119
+ if len(values) == wanted + 1:
120
+ return values[0], values[1:]
121
+ raise SystemExit(f"codefactory: expected {wanted} value(s) (optionally after the repo path), got {len(values)}")
122
+
123
+
124
+ _FN_INDEX: dict[int, tuple[dict, dict]] = {}
125
+
126
+
127
+ def _function(graph: dict, fid: str) -> dict | None:
128
+ """The function with this id, from an index built once per graph (a search per finding was quadratic: 54 s for
129
+ 17,700 findings on 1.7M lines)."""
130
+ cached = _FN_INDEX.get(id(graph))
131
+ if cached is None or cached[0] is not graph:
132
+ cached = (graph, {x["id"]: x for x in graph["functions"]})
133
+ _FN_INDEX.clear()
134
+ _FN_INDEX[id(graph)] = cached
135
+ return cached[1].get(fid)
136
+
137
+
138
+ def _flag_dict(graph: dict, f: dict) -> dict:
139
+ fn = _function(graph, f["target"])
140
+ file = fn["file"] if fn else f["target"]
141
+ owners = _owners(Path(graph["root"]))
142
+ return {
143
+ "owners": owners.of(file) if owners else [],
144
+ "severity": f["severity"],
145
+ "kind": f["kind"],
146
+ "file": fn["file"] if fn else f["target"],
147
+ "line": f.get("line") or (fn["line"] if fn else 0),
148
+ "function": fn["qualname"] if fn else None,
149
+ "message": f["message"],
150
+ "related": f.get("related", []),
151
+ }
152
+
153
+
154
+ @functools.lru_cache(maxsize=8)
155
+ def _owners(root: Path):
156
+ from .owners import load
157
+
158
+ return load(root)
159
+
160
+
161
+ # ---- commands ----------------------------------------------------------------------------------------------------
162
+
163
+
164
+ def cmd_analyze(a) -> int:
165
+ graph = load_graph(Path(a.path), a.lang, not a.no_cache)
166
+ text = json.dumps(graph, indent=1)
167
+ if a.output:
168
+ _write(Path(a.output), text)
169
+ print(f"Wrote {a.output}: {len(graph['files'])} files, {len(graph['flags'])} issues")
170
+ else:
171
+ print(text)
172
+ return 0
173
+
174
+
175
+ def _repo(path: str) -> Path:
176
+ p = Path(path)
177
+ return p if p.is_dir() else p.parent
178
+
179
+
180
+ def _new_only(graph: dict, path: str) -> list[dict]:
181
+ base = read_baseline(baseline_path(_repo(path)))
182
+ if base is None:
183
+ raise SystemExit("codefactory: no baseline yet. Run `codefactory baseline` first (and commit the file).")
184
+ return compare(graph, base)[0]
185
+
186
+
187
+ def cmd_flags(a) -> int:
188
+ graph = load_graph(Path(a.path), a.lang, not a.no_cache)
189
+ limit = SEVERITY_ORDER[a.min]
190
+ pool = _new_only(graph, a.path) if a.new else graph["flags"]
191
+ if a.silenced:
192
+ pool = graph.get("silenced", [])
193
+ shown = [f for f in pool if SEVERITY_ORDER[f["severity"]] <= limit and (not a.kind or f["kind"] in a.kind)]
194
+ if a.json:
195
+ print(json.dumps([_flag_dict(graph, f) for f in shown], indent=1))
196
+ elif a.github:
197
+ print(github_annotations(graph, shown))
198
+ else:
199
+ for f in shown:
200
+ d = _flag_dict(graph, f)
201
+ print(f"{f['severity']:<5} {f['kind']:<16} {d['file']}:{d['line']}" + (f" {d['function']}" if d["function"] else ""))
202
+ print(f" {f['message']}" + (f"\n silenced: {f['reason']}" if a.silenced else ""))
203
+ counts = {s: sum(1 for f in graph["flags"] if f["severity"] == s) for s in SEVERITY_ORDER}
204
+ quiet = len(graph.get("silenced", []))
205
+ print(
206
+ f"\n{len(graph['files'])} files · "
207
+ + " · ".join(f"{n} {s}" for s, n in counts.items())
208
+ + (f" · {quiet} silenced (--silenced lists them)" if quiet else "")
209
+ + (f" · showing {len(shown)} new since the baseline" if a.new else "")
210
+ )
211
+ fail = a.fail_on and any(SEVERITY_ORDER[f["severity"]] <= SEVERITY_ORDER[a.fail_on] for f in graph["flags"])
212
+ return 1 if fail else 0
213
+
214
+
215
+ def cmd_view(a) -> int:
216
+ graph = load_graph(Path(a.path), a.lang, not a.no_cache)
217
+ graph = {**graph, "tasks": [{k: t[k] for k in ("id", "title", "prompt", "flags", "score")} for t in make_plan(graph)]}
218
+ out = Path(a.output or "factory.html")
219
+ _write(out, render_html(graph))
220
+ print(f"Wrote {out}: {len(graph['files'])} machines, {len(graph['flags'])} issues")
221
+ if not a.no_open:
222
+ webbrowser.open(out.resolve().as_uri())
223
+ return 0
224
+
225
+
226
+ def cmd_sql(a) -> int:
227
+ graph = load_graph(Path(a.path), a.lang, not a.no_cache)
228
+ if not Path(a.output).resolve().parent.exists():
229
+ raise SystemExit(f"codefactory: can't save {a.output}: its folder doesn't exist")
230
+ to_sqlite(graph, a.output).close()
231
+ print(f"Wrote {a.output}: tables files, functions, edges, flags; views function_stats, file_deps")
232
+ return 0
233
+
234
+
235
+ def cmd_query(a) -> int:
236
+ path, (sql,) = _split(a.values, 1)
237
+ if Path(path).suffix == ".db": # a database written by `sql`
238
+ import sqlite3
239
+
240
+ db = sqlite3.connect(path)
241
+ else:
242
+ db = to_sqlite(load_graph(Path(path), a.lang, not a.no_cache))
243
+ try:
244
+ cols, rows = run_query(db, sql)
245
+ except Exception as e: # sqlite3.Error, shown plainly
246
+ raise SystemExit(f"codefactory: query failed: {e}") from None
247
+ finally:
248
+ db.close()
249
+ if a.json:
250
+ print(json.dumps([dict(zip(cols, r, strict=True)) for r in rows], indent=1))
251
+ return 0
252
+ print(_table(cols, rows) if cols else "(no result)")
253
+ if len(rows) > 200:
254
+ print(f"… {len(rows) - 200} more rows")
255
+ return 0
256
+
257
+
258
+ def cmd_trace(a) -> int:
259
+ path, (name,) = _split(a.values, 1)
260
+ graph = load_graph(Path(path), a.lang, not a.no_cache)
261
+ fn = _one_function(graph, name)
262
+ t = trace(graph, fn["id"], ("call", "ref") if a.refs else ("call",))
263
+ if a.json:
264
+ print(json.dumps(t, indent=1))
265
+ return 0
266
+ print(f"{fn['id']} ({fn['loc']} lines)")
267
+ print(f"reaches {len(t['functions'])} functions in {len(t['files'])} files · depth {t['depth']} · {t['loc']} lines of code\n")
268
+ for f in t["functions"]:
269
+ print(f"{' ' * f['depth']}{f['qualname']} · {f['file']}:{f['line']} ({f['loc']} lines)")
270
+ if t["calls_back"]:
271
+ print(f"\ncalls back into {fn['qualname']} (a call loop): " + ", ".join(t["calls_back"]))
272
+ return 0
273
+
274
+
275
+ def cmd_path(a) -> int:
276
+ path, (source, target) = _split(a.values, 2)
277
+ graph = load_graph(Path(path), a.lang, not a.no_cache)
278
+ src, dst = _one_function(graph, source), _one_function(graph, target)
279
+ steps = shortest_path(graph, src["id"], dst["id"], ("call", "ref") if a.refs else ("call",))
280
+ if a.json:
281
+ print(json.dumps({"path": steps}, indent=1))
282
+ return 0 if steps else 1
283
+ if not steps:
284
+ print(f"{src['qualname']} never reaches {dst['qualname']} (through calls the analyzer could resolve)")
285
+ return 1
286
+ print(f"{len(steps) - 1} step(s):")
287
+ for i, fid in enumerate(steps):
288
+ print(f"{' ' * i}{'└ ' if i else ''}{fid}")
289
+ return 0
290
+
291
+
292
+ def cmd_brief(a) -> int:
293
+ text = brief_markdown(load_graph(Path(a.path), a.lang, not a.no_cache), a.limit)
294
+ if a.output:
295
+ _write(Path(a.output), text)
296
+ print(f"Wrote {a.output}")
297
+ else:
298
+ print(text, end="")
299
+ return 0
300
+
301
+
302
+ def cmd_context(a) -> int:
303
+ path, (target,) = _split(a.values, 1)
304
+ graph = load_graph(Path(path), a.lang, not a.no_cache)
305
+ if a.json:
306
+ data = context_data(graph, target, a.limit)
307
+ print(json.dumps(data, indent=1))
308
+ return 1 if "error" in data else 0
309
+ text = context_markdown(graph, target, a.limit)
310
+ print(text, end="")
311
+ return 0
312
+
313
+
314
+ def cmd_baseline(a) -> int:
315
+ graph = load_graph(Path(a.path), a.lang, not a.no_cache)
316
+ out = baseline_path(_repo(a.path)) if not a.output else Path(a.output)
317
+ n = write_baseline(graph, out)
318
+ print(f"Wrote {out}: {n} issues as the baseline. Commit it; `codefactory check` then fails only on new ones.")
319
+ return 0
320
+
321
+
322
+ def cmd_check(a) -> int:
323
+ """For CI and pre-commit hooks: new issues since the baseline (or, without one, high-severity ones) fail."""
324
+ graph = load_graph(Path(a.path), a.lang, not a.no_cache)
325
+ base = read_baseline(baseline_path(_repo(a.path)))
326
+ level = SEVERITY_ORDER[a.fail_on]
327
+ if base is None:
328
+ blocking = [f for f in graph["flags"] if f["severity"] == "high"]
329
+ fixed = {}
330
+ print("No baseline (codefactory baseline): checking for high-severity issues only.")
331
+ else:
332
+ new, fixed = compare(graph, base)
333
+ blocking = [f for f in new if SEVERITY_ORDER[f["severity"]] <= level]
334
+ if a.github and blocking:
335
+ print(github_annotations(graph, blocking))
336
+ for f in blocking:
337
+ d = _flag_dict(graph, f)
338
+ print(f"{f['severity']:<5} {f['kind']:<16} {d['file']}:{d['line']}" + (f" {d['function']}" if d["function"] else ""))
339
+ print(f" {f['message']}")
340
+ summary = f"{len(blocking)} new issue(s)" + (f" at {a.fail_on} or worse" if base is not None else "")
341
+ if fixed:
342
+ summary += f" · {sum(fixed.values())} fixed since the baseline (run `codefactory baseline` to lock that in)"
343
+ print(("FAIL: " if blocking else "OK: ") + summary)
344
+ if blocking:
345
+ print("Fix them, or if one is intended, add `codefactory: ignore <kind> — <why>` above it.")
346
+ return 1 if blocking else 0
347
+
348
+
349
+ def cmd_plan(a) -> int:
350
+ from .hotspots import read as read_history
351
+
352
+ graph = load_graph(Path(a.path), a.lang, not a.no_cache)
353
+ root = _repo(a.path)
354
+ tasks = make_plan(graph, {path: fh.commits for path, fh in read_history(root).files.items()})
355
+ if a.json:
356
+ print(json.dumps(tasks[: a.top], indent=1))
357
+ else:
358
+ print(plan_markdown(tasks, a.top), end="")
359
+ return 0
360
+
361
+
362
+ def cmd_org(a) -> int:
363
+ """Many repositories: a dashboard of health, findings and trends, and findings per owning team."""
364
+ from . import org
365
+
366
+ paths = list(a.repos)
367
+ if a.list:
368
+ paths += [
369
+ ln.strip() for ln in Path(a.list).read_text(encoding="utf-8").splitlines() if ln.strip() and not ln.startswith("#")
370
+ ]
371
+ if not paths:
372
+ raise ValueError("give the repositories to include (folders), or --list FILE with one folder per line")
373
+ snaps, histories = [], {}
374
+ for p in paths:
375
+ root = Path(p).resolve()
376
+ if not root.is_dir():
377
+ print(f"codefactory: skipping {p}: not a folder", file=sys.stderr)
378
+ continue
379
+ snap = org.snapshot(root, load_graph(root, a.lang, not a.no_cache))
380
+ histories[snap["path"]] = org.record(root, snap)
381
+ snaps.append(snap)
382
+ print(
383
+ f"{snap['grade']:<9} {snap['repo']} " + " ".join(f"{k[0]}{v}" for k, v in snap["findings"].items()), file=sys.stderr
384
+ )
385
+ if a.json:
386
+ print(json.dumps({"repositories": snaps}, indent=1))
387
+ else:
388
+ _write(Path(a.output), org.page(snaps, histories))
389
+ print(f"Wrote {a.output}: {len(snaps)} repositories")
390
+ return 0
391
+
392
+
393
+ def cmd_diff(a) -> int:
394
+ """What this change adds: new findings compared with the base branch (merge-base), for pull requests."""
395
+ from . import diff
396
+
397
+ if a.patch: # a unified diff on its own: check the lines it adds
398
+ from .patch import check
399
+
400
+ text = sys.stdin.read() if a.patch == "-" else Path(a.patch).read_text(encoding="utf-8", errors="replace")
401
+ result = check(text)
402
+ root = Path(a.path)
403
+ else:
404
+ root = _repo(a.path)
405
+ base = a.base or diff.default_base(root)
406
+ result = diff.run(root, base, lambda p: load_graph(p, a.lang, not a.no_cache))
407
+ level = SEVERITY_ORDER.get(a.fail_on, -1) # "never": nothing blocks
408
+ blocking = [i for i in result["new"] if SEVERITY_ORDER.get(i.severity, 2) <= level]
409
+ if a.json:
410
+ print(
411
+ json.dumps({**result, "new": [vars(i) for i in result["new"]], "fixed": [vars(i) for i in result["fixed"]]}, indent=1)
412
+ )
413
+ elif a.github:
414
+ for i in result["new"]:
415
+ kind = {"high": "error", "warn": "warning"}.get(i.severity, "notice")
416
+ print(f"::{kind} file={i.file},line={max(1, i.line)},title=codefactory {i.kind}::{i.message}")
417
+ else:
418
+ print(diff.markdown(result, owners=_owners(root.resolve())), end="")
419
+ if a.comment:
420
+ _write(Path(a.comment), diff.markdown(result, owners=_owners(root.resolve())))
421
+ return 1 if blocking else 0
422
+
423
+
424
+ def cmd_surface(a) -> int:
425
+ from .brief import View
426
+ from .security import SINK_KINDS, function_at, surface, writes
427
+
428
+ root = Path(a.path).resolve()
429
+ graph = load_graph(root, a.lang, not a.no_cache)
430
+ v = View(graph)
431
+ s = surface(root, graph, v)
432
+ writers = writes(v)
433
+ scan = scan_sources(root, [f["id"] for f in graph["files"]])
434
+ sinks = {} # function id -> risky kinds in it
435
+ for kind in SINK_KINDS:
436
+ for e in scan[kind].hits:
437
+ if fid := function_at(v, e.file, e.line):
438
+ sinks.setdefault(fid, set()).add(kind)
439
+ rows = []
440
+ for i, e in enumerate(s.entries):
441
+ reached = {f for f, (j, _) in s.reach.items() if j == i} | _reachable_from(graph, e.fn)
442
+ rows.append({
443
+ "method": e.method, "path": e.path, "framework": e.framework, "handler": f"{e.file}:{e.line}",
444
+ "auth": e.auth, "changes_data": any(f in writers for f in reached),
445
+ "risky": sorted({k for f in reached for k in sinks.get(f, ())}),
446
+ }) # fmt: skip
447
+ if a.json:
448
+ print(json.dumps({"exposure": s.exposure, "evidence": s.exposure_evidence, "endpoints": rows}, indent=1))
449
+ return 0
450
+ if not rows:
451
+ print(
452
+ "No HTTP endpoints found (recognised: FastAPI, Flask, Django/DRF, Express-style, Next.js, Spring, Go, "
453
+ "Rails, Sinatra)."
454
+ )
455
+ return 0
456
+ print(f"{len(rows)} endpoints · listening: {s.exposure}" + (f" ({s.exposure_evidence})" if s.exposure_evidence else ""))
457
+ print(_table(["method", "path", "auth", "changes data", "risky code", "handler"],
458
+ [(r["method"], r["path"], r["auth"] or "none found", "yes" if r["changes_data"] else "",
459
+ ", ".join(r["risky"]), r["handler"]) for r in rows], limit=500)) # fmt: skip
460
+ return 0
461
+
462
+
463
+ def _reachable_from(graph: dict, start: str) -> set[str]:
464
+ out_edges: dict[str, list[str]] = {}
465
+ for e in graph["edges"]:
466
+ if e["kind"] in ("call", "ref"):
467
+ out_edges.setdefault(e["src"], []).append(e["dst"])
468
+ seen, q = {start}, [start]
469
+ while q:
470
+ for nxt in out_edges.get(q.pop(), ()):
471
+ if nxt not in seen:
472
+ seen.add(nxt)
473
+ q.append(nxt)
474
+ return seen
475
+
476
+
477
+ def cmd_accept(a) -> int:
478
+ from .accept import append_rules, known_kinds, normalize_where, rules_for_task
479
+
480
+ values = list(a.values)
481
+ root = Path(values.pop(0)) if len(values) > 1 and Path(values[0]).is_dir() else Path(".")
482
+ rest = values
483
+ if not rest:
484
+ raise ValueError("say what to accept: a plan task (`codefactory accept 3f9a2c`) or a kind and where")
485
+ if len(rest) == 1: # a plan task: every finding behind it
486
+ graph = load_graph(root, a.lang, not a.no_cache)
487
+ tasks = make_plan(graph)
488
+ key = rest[0]
489
+ task = tasks[int(key) - 1] if key.isdigit() and len(key) < 4 and 0 < int(key) <= len(tasks) else None
490
+ task = task or next((t for t in tasks if t["id"] == key), None)
491
+ if not task:
492
+ raise ValueError(f"no plan task {key!r}; for a single finding give its kind and where: accept sql_built src/db.py")
493
+ rules = rules_for_task(task, graph)
494
+ else:
495
+ kind, where = rest[0], normalize_where(rest[1])
496
+ if kind not in known_kinds():
497
+ raise ValueError(f"unknown kind {kind!r}; one of: {', '.join(sorted(known_kinds()))}")
498
+ rules = [(kind, where)]
499
+ file = append_rules(root, rules, a.why)
500
+ for kind, where in rules:
501
+ print(f"accepted {kind} at {where}: {a.why}")
502
+ print(f"Recorded in {file}; commit it so everyone (and CI) sees the same list. `codefactory flags --silenced` lists them.")
503
+ return 0
504
+
505
+
506
+ def cmd_prompt(a) -> int:
507
+ path, (task_id,) = _split(a.values, 1)
508
+ tasks = make_plan(load_graph(Path(path), a.lang, not a.no_cache))
509
+ if task_id.isdigit() and len(task_id) < 4: # "1" = the first task of the plan
510
+ task = tasks[int(task_id) - 1] if 0 < int(task_id) <= len(tasks) else None
511
+ else:
512
+ task = next((t for t in tasks if t["id"] == task_id), None)
513
+ if not task:
514
+ raise SystemExit(f"codefactory: no task {task_id!r}. `codefactory plan` lists them.")
515
+ print(task["prompt"], end="")
516
+ return 0
517
+
518
+
519
+ def cmd_review(a) -> int:
520
+ path = Path(a.path)
521
+ if not path.is_dir():
522
+ raise SystemExit("codefactory: review needs the repository folder (it reads manifests, CI files and source text)")
523
+ text = review_markdown(load_graph(path, a.lang, not a.no_cache), path.resolve(), a.for_ai, a.online)
524
+ if a.output:
525
+ _write(Path(a.output), text)
526
+ print(f"Wrote {a.output}")
527
+ else:
528
+ print(text, end="")
529
+ return 0
530
+
531
+
532
+ def cmd_sarif(a) -> int:
533
+ path = Path(a.path)
534
+ graph = load_graph(path, a.lang, not a.no_cache)
535
+ new_keys = None
536
+ base = read_baseline(baseline_path(_repo(a.path)))
537
+ if base is not None:
538
+ from collections import Counter
539
+
540
+ from .baseline import issue_key
541
+
542
+ fns = {f["id"]: f for f in graph["functions"]}
543
+ new_keys = Counter(issue_key(graph, f, fns) for f in compare(graph, base)[0])
544
+ doc = build_sarif(graph, path.resolve() if path.is_dir() and not a.no_source_checks else None, new_keys, a.min)
545
+ if a.new and new_keys is not None:
546
+ doc["runs"][0]["results"] = [
547
+ r for r in doc["runs"][0]["results"] if r.get("baselineState", "new") == "new" and "suppressions" not in r
548
+ ]
549
+ out = Path(a.output or "codefactory.sarif")
550
+ _write(out, json.dumps(doc, indent=1))
551
+ n = len(doc["runs"][0]["results"])
552
+ quiet = sum(1 for r in doc["runs"][0]["results"] if "suppressions" in r)
553
+ print(
554
+ f"Wrote {out}: {n} results ({quiet} silenced, shown as suppressed). Upload it to GitHub code scanning, or open "
555
+ "it in VS Code with the SARIF Viewer extension."
556
+ )
557
+ return 0
558
+
559
+
560
+ def cmd_sbom(a) -> int:
561
+ """A CycloneDX software bill of materials from the lockfiles."""
562
+ from .sbom import write
563
+
564
+ root = _repo(a.path)
565
+ text = write(root, Path(a.output) if a.output else None)
566
+ if a.output:
567
+ count = len(json.loads(text)["components"])
568
+ print(f"Wrote {a.output} ({count} components)")
569
+ else:
570
+ print(text, end="")
571
+ return 0
572
+
573
+
574
+ def cmd_profile(a) -> int:
575
+ """What kind of project this is, where it runs, who uses it and what data it holds, with the evidence."""
576
+ from .profile import detect, markdown
577
+
578
+ root = _repo(a.path)
579
+ p = detect(root, load_graph(Path(a.path), a.lang, not a.no_cache))
580
+ print(json.dumps(p.to_dict(), indent=1) if a.json else "\n".join(markdown(p)))
581
+ return 0
582
+
583
+
584
+ def cmd_hotspots(a) -> int:
585
+ """Where change happens: complex code changed often, files that change together, code one person owns."""
586
+ from . import hotspots
587
+
588
+ root = _repo(a.path)
589
+ s = hotspots.analyze(root, load_graph(Path(a.path), a.lang, not a.no_cache))
590
+ if a.json:
591
+ print(json.dumps({"commits": s.history.commits, "people": len(s.history.people), "note": s.history.note,
592
+ "hotspots": [vars(x) for x in s.hot], "coupling": [vars(c) for c in s.coupled],
593
+ "single_owner": [dict(zip(("file", "person", "share", "changes"), o, strict=True)) for o in s.owners]},
594
+ indent=1)) # fmt: skip
595
+ else:
596
+ print("\n".join(hotspots.markdown(s)))
597
+ return 0
598
+
599
+
600
+ def cmd_skill(a) -> int:
601
+ repo = Path(a.path)
602
+ path = install_skill(repo)
603
+ print(f"Wrote {path}. Claude Code in that repo now knows when and how to use codefactory.")
604
+ if a.hook:
605
+ hook, settings = install_hook(repo)
606
+ print(
607
+ f"Wrote {hook} and registered it in {settings}: each Claude Code session now starts with codefactory "
608
+ "installed, upgraded (at most once a day) and its skill current. Commit .claude/."
609
+ )
610
+ return 0
611
+
612
+
613
+ def cmd_update(a) -> int:
614
+ old, new = update(a.source)
615
+ print(f"codefactory {old} -> {new}" if old != new else f"codefactory {new} is already the latest.")
616
+ if refresh_skill(Path(".")):
617
+ print("Refreshed .claude/skills/codefactory/SKILL.md for the new version.")
618
+ return 0
619
+
620
+
621
+ COMMANDS = {
622
+ "analyze": (cmd_analyze, "write the graph as JSON"),
623
+ "flags": (cmd_flags, "list issues (file:line), or --json for tools"),
624
+ "view": (cmd_view, "write the factory view (HTML) and open it"),
625
+ "sql": (cmd_sql, "write the graph as a SQLite database (tables files, functions, edges, flags)"),
626
+ "query": (cmd_query, 'run a SQL query on the graph: query [repo] "SELECT …"'),
627
+ "trace": (cmd_trace, "everything a function eventually calls (like SQL EXPLAIN): trace [repo] name"),
628
+ "path": (cmd_path, "the shortest call path between two functions: path [repo] from to"),
629
+ "brief": (cmd_brief, "a Markdown map of the repo for an AI agent: layers, hubs, issues by what to do"),
630
+ "context": (cmd_context, "before changing a file or function: callers, calls, impact, tests: context [repo] name"),
631
+ "review": (cmd_review, "a full technical review (summary, system map, findings by severity, gaps), no AI needed"),
632
+ "plan": (cmd_plan, "ranked tasks with steps, tests and a fix prompt each: the work list"),
633
+ "prompt": (cmd_prompt, "a ready-to-paste Claude Code prompt for one task: prompt [repo] <id or rank>"),
634
+ "baseline": (cmd_baseline, "save today's issues (codefactory-baseline.json, commit it) so only new ones fail"),
635
+ "check": (cmd_check, "for CI / pre-commit: fail on issues new since the baseline"),
636
+ "sarif": (cmd_sarif, "write issues as SARIF 2.1.0 for GitHub code scanning, VS Code and CI tools"),
637
+ "org": (cmd_org, "a dashboard across many repositories: health, findings, trends and findings per owning team"),
638
+ "diff": (cmd_diff, "what a change adds: new and fixed findings compared with the base branch (for pull requests)"),
639
+ "surface": (
640
+ cmd_surface,
641
+ "the attack surface: every HTTP endpoint, its auth check, and whether it changes data or reaches risky code",
642
+ ),
643
+ "accept": (cmd_accept, "mark a finding as intended, with the reason (writes a [[silence]] rule to factory.toml)"),
644
+ "profile": (
645
+ cmd_profile,
646
+ "what kind of project this is (kind, where it runs, users, sensitive data): findings are ranked for it",
647
+ ),
648
+ "hotspots": (cmd_hotspots, "where change happens (git history): complex code changed often, files that change together"),
649
+ "sbom": (cmd_sbom, "a CycloneDX software bill of materials (every pinned dependency, with package URLs)"),
650
+ "update": (cmd_update, "upgrade codefactory to the latest version (and refresh this repo's skill)"),
651
+ "skill": (cmd_skill, "teach Claude Code in a repo to use codefactory (writes .claude/skills/codefactory/SKILL.md)"),
652
+ }
653
+
654
+
655
+ def parser() -> argparse.ArgumentParser:
656
+ p = argparse.ArgumentParser(
657
+ prog="codefactory",
658
+ description="See a codebase as a factory floor, find its problems, and turn them into work.",
659
+ formatter_class=argparse.RawDescriptionHelpFormatter,
660
+ epilog="""examples:
661
+ codefactory view open the factory view of this folder in your browser
662
+ codefactory review -o review.md a technical review of this repository
663
+ codefactory plan ranked tasks; then: codefactory prompt 1
664
+ codefactory context <name> before changing a function: callers, impact, tests
665
+ codefactory baseline && codefactory check fail CI only on new issues
666
+
667
+ Run `codefactory <command> --help` for a command's options.""",
668
+ )
669
+ p.add_argument("--version", action="version", version=f"codefactory {__version__}")
670
+ p.add_argument("--debug", action="store_true", help="show full tracebacks (for reporting a bug)")
671
+ sub = p.add_subparsers(dest="cmd", required=True)
672
+ for name, (_, text) in COMMANDS.items():
673
+ s = sub.add_parser(name, help=text, description=text)
674
+ if name in ("query", "trace", "path", "context", "prompt", "accept"):
675
+ s.add_argument("values", nargs="+", metavar="value")
676
+ elif name == "org":
677
+ s.add_argument("repos", nargs="*", help="the repositories (folders) to include")
678
+ s.add_argument("--list", metavar="FILE", help="a file with one repository folder per line")
679
+ s.add_argument("-o", "--output", default="codefactory-dashboard.html", help="where to write the dashboard")
680
+ else:
681
+ s.add_argument("path", nargs="?", default=".", help="the codebase folder (default: here), or a graph .json")
682
+ if name == "diff":
683
+ s.add_argument("--base", help="the branch, tag or commit to compare with (default: origin/HEAD, main or master)")
684
+ s.add_argument("--comment", metavar="FILE", help="also write the pull-request comment (Markdown) to FILE")
685
+ s.add_argument("--patch", metavar="FILE",
686
+ help="check the lines a unified diff adds (a .diff or .patch file, - for stdin)") # fmt: skip
687
+ s.add_argument("--github", action="store_true", help="print GitHub Actions annotations for new findings")
688
+ s.add_argument("--fail-on", choices=["high", "warn", "info", "never"], default="never",
689
+ help="exit 1 when new findings at this level or worse appear (default: never)") # fmt: skip
690
+ if name == "accept":
691
+ s.add_argument("--why", required=True, help="why it's intended (kept with the rule, shown by flags --silenced)")
692
+ if name == "skill":
693
+ s.add_argument("--hook", action="store_true", help="also add a session-start hook that keeps codefactory current")
694
+ if name == "update":
695
+ s.add_argument("--source", default=SKILL_SOURCE, help="where to install from (default: the GitHub repository)")
696
+ if name == "sbom":
697
+ s.add_argument("-o", "--output", help="output file (default: print it)")
698
+ if name not in ("skill", "update", "sbom"):
699
+ s.add_argument(
700
+ "--lang",
701
+ action="append",
702
+ choices=LANGUAGES,
703
+ help="only these analyzers (other = every language but Python and TypeScript)",
704
+ )
705
+ s.add_argument("--no-cache", action="store_true", help="analyze again even if nothing changed")
706
+ if name in ("flags", "query", "trace", "path", "context", "plan", "surface", "diff", "org", "profile", "hotspots"):
707
+ s.add_argument("--json", action="store_true", help="machine-readable output")
708
+ if name in ("trace", "path"):
709
+ s.add_argument("--refs", action="store_true", help="also follow functions passed by name (callbacks)")
710
+ if name in ("analyze", "view", "brief", "baseline", "review", "sarif"):
711
+ s.add_argument("-o", "--output", help="output file")
712
+ if name in ("brief", "context"):
713
+ s.add_argument("--limit", type=int, default=12 if name == "brief" else 20, help="items per list")
714
+ if name == "flags":
715
+ s.add_argument("--min", choices=list(SEVERITY_ORDER), default="info", help="lowest severity to show")
716
+ s.add_argument("--kind", action="append", help="only these kinds (e.g. --kind io_in_loop --kind similar)")
717
+ s.add_argument("--fail-on", choices=list(SEVERITY_ORDER), help="exit 1 if any issue is this severe (for CI)")
718
+ s.add_argument("--new", action="store_true", help="only issues not in the baseline")
719
+ s.add_argument("--silenced", action="store_true", help="list the silenced issues and why")
720
+ s.add_argument("--github", action="store_true", help="print GitHub Actions annotations (::warning file=…)")
721
+ if name == "sarif":
722
+ s.add_argument("--min", choices=list(SEVERITY_ORDER), default="info", help="lowest severity to include")
723
+ s.add_argument("--new", action="store_true", help="only results new since the baseline")
724
+ s.add_argument(
725
+ "--no-source-checks", action="store_true", help="only the graph's issues, not secrets/SQL/… line checks"
726
+ )
727
+ if name == "check":
728
+ s.add_argument("--github", action="store_true", help="also print GitHub Actions annotations for new issues")
729
+ s.add_argument(
730
+ "--fail-on", choices=list(SEVERITY_ORDER), default="warn", help="lowest new severity that fails (default warn)"
731
+ )
732
+ if name == "review":
733
+ s.add_argument("--for-ai", action="store_true", help="append an evidence pack for an AI to finish the review")
734
+ s.add_argument(
735
+ "--online",
736
+ action="store_true",
737
+ help="also check dependencies for known vulnerabilities at OSV.dev (sends package names and versions only)",
738
+ )
739
+ if name == "plan":
740
+ s.add_argument("--top", type=int, default=10, help="how many tasks (default 10)")
741
+ if name == "view":
742
+ s.add_argument("--no-open", action="store_true", help="don't open the browser")
743
+ if name == "sql":
744
+ s.add_argument("-o", "--output", default="codefactory.db", help="database file (default: codefactory.db)")
745
+ return p
746
+
747
+
748
+ def main(argv: list[str] | None = None) -> int:
749
+ """Runs a command. Problems a user can fix (a bad factory.toml, a missing folder, TypeScript not installed) end
750
+ with a one-line message; anything unexpected says how to get the full traceback (--debug) to report it."""
751
+ _safe_stdout()
752
+ a = parser().parse_args(argv)
753
+ debug = a.debug or bool(os.environ.get("CODEFACTORY_DEBUG"))
754
+ repo = Path(getattr(a, "path", None) or ".")
755
+ if a.cmd not in ("skill", "update") and skill_outdated(repo if repo.is_dir() else repo.parent):
756
+ print(
757
+ "codefactory: .claude/skills/codefactory/SKILL.md is from an older version; `codefactory skill` updates it.",
758
+ file=sys.stderr,
759
+ )
760
+ try:
761
+ return COMMANDS[a.cmd][0](a)
762
+ except KeyboardInterrupt:
763
+ print("codefactory: stopped.", file=sys.stderr)
764
+ return 130
765
+ except (ValueError, RuntimeError, OSError) as e:
766
+ if debug:
767
+ raise
768
+ print(f"codefactory: {e}", file=sys.stderr)
769
+ return 2
770
+ except Exception as e: # a bug: say so plainly, and how to report it
771
+ if debug:
772
+ raise
773
+ print(
774
+ f"codefactory: unexpected error ({type(e).__name__}: {e}).\n"
775
+ " Run the same command with --debug for the full traceback, and please report it.",
776
+ file=sys.stderr,
777
+ )
778
+ return 2
779
+
780
+
781
+ if __name__ == "__main__":
782
+ sys.exit(main())