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/plan.py
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
"""From issues to work: ranked tasks, each with where, concrete steps, the tests to run, how to know it's done, and a
|
|
2
|
+
self-contained prompt for Claude Code (or any agent). Related issues become one task: a group of copies is one merge,
|
|
3
|
+
a function's loop calls are one batching job, dead code is one cleanup.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
from collections import defaultdict
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from .brief import View
|
|
13
|
+
from .paths import is_script, is_test
|
|
14
|
+
|
|
15
|
+
BASE = {
|
|
16
|
+
"cycle": 90,
|
|
17
|
+
"layer_violation": 80,
|
|
18
|
+
"io_in_loop": 70,
|
|
19
|
+
"duplicate": 60,
|
|
20
|
+
"similar": 45,
|
|
21
|
+
"unused": 35,
|
|
22
|
+
"sequential_await": 18,
|
|
23
|
+
"quadratic_scan": 14,
|
|
24
|
+
"test_only": 12,
|
|
25
|
+
"long_function": 8,
|
|
26
|
+
}
|
|
27
|
+
SCRIPT_EXT = (".js", ".mjs", ".cjs", ".jsx")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def batch_name(name: str, file: str) -> str:
|
|
31
|
+
"""The batched variant's name in the code's own style: get_order -> get_orders_batch(ids), getOrder -> getOrderMany(ids)."""
|
|
32
|
+
if "_" in name or name.islower() or file.endswith((".py", ".rb", ".rs", ".ex", ".exs")):
|
|
33
|
+
return f"{name}_batch(ids)"
|
|
34
|
+
return f"{name}Many(ids)"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _id(kind: str, parts: list[str]) -> str:
|
|
38
|
+
return hashlib.sha1(f"{kind}|{'|'.join(sorted(parts))}".encode("utf-8", "surrogatepass")).hexdigest()[:6]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Planner:
|
|
42
|
+
def __init__(self, g: dict, changes: dict[str, int] | None = None):
|
|
43
|
+
self.g, self.v = g, View(g)
|
|
44
|
+
self.changes = changes or {} # file -> commits in the last 12 months (hotspots.py)
|
|
45
|
+
self.layer_rank = {name: i for i, name in enumerate(g["layers"])} # right = more depended upon
|
|
46
|
+
self.idx = {id(f): i for i, f in enumerate(g["flags"])}
|
|
47
|
+
from .owners import load as load_owners
|
|
48
|
+
|
|
49
|
+
self.owners = load_owners(Path(g["root"])) if g.get("root") and Path(g["root"]).is_dir() else None
|
|
50
|
+
|
|
51
|
+
# -- helpers ---------------------------------------------------------------------------------------------------
|
|
52
|
+
def at(self, fid: str, line: int | None = None) -> dict:
|
|
53
|
+
fn = self.v.fn.get(fid)
|
|
54
|
+
if not fn:
|
|
55
|
+
return {"file": fid, "line": line or 0, "name": ""}
|
|
56
|
+
return {"file": fn["file"], "line": line or fn["line"], "name": "" if fn["kind"] == "module" else fn["qualname"]}
|
|
57
|
+
|
|
58
|
+
def callers_of(self, fid: str) -> list[str]:
|
|
59
|
+
return sorted({self.v.where(e["src"]) for e in self.v.callers[fid]})
|
|
60
|
+
|
|
61
|
+
def tests_for(self, ids: list[str]) -> list[str]:
|
|
62
|
+
dep = self.v.dependents(ids) | set(ids)
|
|
63
|
+
files = {self.v.fn[d]["file"] for d in dep if d in self.v.fn}
|
|
64
|
+
for i in ids:
|
|
65
|
+
fn = self.v.fn.get(i)
|
|
66
|
+
if fn:
|
|
67
|
+
files |= self.v.importers.get(fn["file"], set())
|
|
68
|
+
return sorted(f for f in files if is_test(f))[:12]
|
|
69
|
+
|
|
70
|
+
def weight(self, files: list[str]) -> float:
|
|
71
|
+
"""Tests and one-off scripts matter less than the product's code."""
|
|
72
|
+
if files and all(is_test(f) for f in files):
|
|
73
|
+
return 0.3
|
|
74
|
+
if files and all(is_script(f) for f in files):
|
|
75
|
+
return 0.5
|
|
76
|
+
return 1.0
|
|
77
|
+
|
|
78
|
+
@staticmethod
|
|
79
|
+
def fmt(w: dict) -> str:
|
|
80
|
+
return f"`{w['file']}:{w['line']}`" + (f" {w['name']}" if w["name"] else "")
|
|
81
|
+
|
|
82
|
+
# -- tasks -----------------------------------------------------------------------------------------------------
|
|
83
|
+
def copies(self) -> list[dict]:
|
|
84
|
+
out, seen = [], set()
|
|
85
|
+
by_target: dict[tuple[str, str], list[dict]] = {} # (kind, function) -> its copy flags: one pass, not one per group
|
|
86
|
+
for x in self.g["flags"]:
|
|
87
|
+
if x["kind"] in ("duplicate", "similar"):
|
|
88
|
+
by_target.setdefault((x["kind"], x["target"]), []).append(x)
|
|
89
|
+
for f in self.g["flags"]:
|
|
90
|
+
if f["kind"] not in ("duplicate", "similar"):
|
|
91
|
+
continue
|
|
92
|
+
group = frozenset([f["target"], *f.get("related", [])])
|
|
93
|
+
if group in seen:
|
|
94
|
+
continue
|
|
95
|
+
seen.add(group)
|
|
96
|
+
members = [self.v.fn[i] for i in group if i in self.v.fn]
|
|
97
|
+
if len(members) < 2:
|
|
98
|
+
continue
|
|
99
|
+
flags = [x for t in group for x in by_target.get((f["kind"], t), [])]
|
|
100
|
+
exact = f["kind"] == "duplicate"
|
|
101
|
+
# keep the copy in the layer the others can depend on (rightmost), then the most-called one
|
|
102
|
+
home = max(
|
|
103
|
+
members,
|
|
104
|
+
key=lambda m: (
|
|
105
|
+
not is_test(m["file"]),
|
|
106
|
+
self.layer_rank.get(self.v.file[m["file"]]["layer"], 0),
|
|
107
|
+
not m["file"].endswith(SCRIPT_EXT),
|
|
108
|
+
len(self.v.callers[m["id"]]),
|
|
109
|
+
),
|
|
110
|
+
)
|
|
111
|
+
others = [m for m in members if m is not home]
|
|
112
|
+
code = lambda m: max(1, m["loc"] - m.get("doc", 0)) # noqa: E731 docstrings aren't copied logic
|
|
113
|
+
saved = sum(code(m) for m in members) - max(code(m) for m in members)
|
|
114
|
+
# different names in one file: kept apart on purpose (separate entry points); share the body instead
|
|
115
|
+
# (each name used or exported: a copy nobody calls is just a copy to delete)
|
|
116
|
+
named_apart = (
|
|
117
|
+
len({m["file"] for m in members}) == 1
|
|
118
|
+
and len({m["name"] for m in members}) == len(members)
|
|
119
|
+
and all(self.v.callers[m["id"]] or m.get("exported") or m.get("public") for m in members)
|
|
120
|
+
)
|
|
121
|
+
sim = "identical" if exact else f"{round(max(x.get('score', 0) for x in flags) * 100)}% similar"
|
|
122
|
+
if named_apart:
|
|
123
|
+
names = ", ".join(f"`{m['qualname']}`" for m in members)
|
|
124
|
+
steps = [
|
|
125
|
+
f"{names} in `{home['file']}` have the same body under different names, which usually means "
|
|
126
|
+
"separate entry points kept on purpose: keep every name.",
|
|
127
|
+
"Move the shared body into one private helper in the same file and make each of them a one-line "
|
|
128
|
+
"call to it (keep their docstrings), so a fix to the body reaches all of them.",
|
|
129
|
+
"If they're expected to diverge, silence it instead: `codefactory: ignore duplicate — <why>`.",
|
|
130
|
+
]
|
|
131
|
+
else:
|
|
132
|
+
steps = [
|
|
133
|
+
f"Keep `{home['qualname']}` in `{home['file']}:{home['line']}` as the one version "
|
|
134
|
+
f"(layer {self.v.file[home['file']]['layer']}, which the other copies' callers can import)."
|
|
135
|
+
]
|
|
136
|
+
if not exact:
|
|
137
|
+
steps.append(
|
|
138
|
+
"The copies differ: compare them line by line, and fold each difference into a parameter "
|
|
139
|
+
"(or keep the variant every caller needs) before merging."
|
|
140
|
+
)
|
|
141
|
+
for m in [] if named_apart else others:
|
|
142
|
+
callers = self.callers_of(m["id"])
|
|
143
|
+
steps.append(
|
|
144
|
+
f"Replace `{m['qualname']}` in `{m['file']}:{m['line']}` with an import of the kept one; "
|
|
145
|
+
f"its callers: {', '.join(f'`{c}`' for c in callers[:6]) or 'none found'}"
|
|
146
|
+
+ (" …" if len(callers) > 6 else "")
|
|
147
|
+
+ ". Then delete it."
|
|
148
|
+
)
|
|
149
|
+
if m["file"].endswith(SCRIPT_EXT) != home["file"].endswith(SCRIPT_EXT):
|
|
150
|
+
steps.append(
|
|
151
|
+
f"Note: `{m['file']}` is plain JavaScript and `{home['file']}` isn't (or the other way "
|
|
152
|
+
"round), so one may not be able to import the other directly. Either move the shared "
|
|
153
|
+
"function into a module both can import, or keep both and silence this with "
|
|
154
|
+
"`codefactory: ignore duplicate — <why>` above one of them."
|
|
155
|
+
)
|
|
156
|
+
files = [m["file"] for m in members]
|
|
157
|
+
score = (BASE["duplicate"] if exact else BASE["similar"]) + min(25, saved) + 3 * len(others)
|
|
158
|
+
out.append(
|
|
159
|
+
self.task(
|
|
160
|
+
f["kind"],
|
|
161
|
+
[m["id"] for m in members],
|
|
162
|
+
score * self.weight(files),
|
|
163
|
+
f"Share one body between {', '.join(sorted(m['name'] for m in members))} ({sim}, ~{saved} lines)"
|
|
164
|
+
if named_apart
|
|
165
|
+
else f"Merge {len(members)} copies of {home['qualname']} ({sim}, ~{saved} lines)",
|
|
166
|
+
f"The same logic lives in {len(members)} places ({sim}). A fix in one copy silently misses "
|
|
167
|
+
f"the others; merging saves ~{saved} lines.",
|
|
168
|
+
[self.at(m["id"]) for m in members],
|
|
169
|
+
steps,
|
|
170
|
+
[m["id"] for m in members],
|
|
171
|
+
f"codefactory flags --kind {f['kind']}",
|
|
172
|
+
flags,
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
return out
|
|
176
|
+
|
|
177
|
+
def loops(self) -> list[dict]:
|
|
178
|
+
out = []
|
|
179
|
+
by_fn = defaultdict(list)
|
|
180
|
+
for f in self.g["flags"]:
|
|
181
|
+
if f["kind"] == "io_in_loop":
|
|
182
|
+
by_fn[f["target"]].append(f)
|
|
183
|
+
for fid, flags in by_fn.items():
|
|
184
|
+
fn = self.v.fn.get(fid)
|
|
185
|
+
if not fn:
|
|
186
|
+
continue
|
|
187
|
+
warn = any(f["severity"] == "warn" for f in flags)
|
|
188
|
+
name = self.at(fid)["name"] or f"top-level code in {fn['file']}"
|
|
189
|
+
where = [self.at(fid, f.get("line")) for f in flags]
|
|
190
|
+
steps = []
|
|
191
|
+
for f in flags:
|
|
192
|
+
callee = f.get("related", [None])[0] if f.get("related") else None
|
|
193
|
+
msg = f["message"].split(": ", 1)
|
|
194
|
+
steps.append(f"Line {f.get('line')}: {msg[0]}.")
|
|
195
|
+
if callee and callee in self.v.fn:
|
|
196
|
+
c = self.v.fn[callee]
|
|
197
|
+
steps.append(
|
|
198
|
+
f" The I/O happens in `{c['qualname']}` (`{c['file']}:{c['line']}`): add a batched variant "
|
|
199
|
+
f"that takes all items at once (e.g. `{batch_name(c['name'], c['file'])}`), call it once before "
|
|
200
|
+
f"the loop, and read results from a {'dict' if c['file'].endswith('.py') else 'Map'} inside "
|
|
201
|
+
"the loop."
|
|
202
|
+
)
|
|
203
|
+
if warn:
|
|
204
|
+
steps.append(
|
|
205
|
+
"Reads / network: collect the keys first, load everything with one query (WHERE id IN (…), "
|
|
206
|
+
"a JOIN) or one request, then loop over the results in memory."
|
|
207
|
+
)
|
|
208
|
+
else:
|
|
209
|
+
steps.append(
|
|
210
|
+
"Writes / files: make sure the whole loop runs inside one transaction; if it can be long, "
|
|
211
|
+
"use one multi-row INSERT/UPDATE. If the loop is small and bounded, silence it with "
|
|
212
|
+
"`codefactory: ignore io_in_loop — <why>`."
|
|
213
|
+
)
|
|
214
|
+
score = (BASE["io_in_loop"] if warn else 25) + 4 * (len(flags) - 1) + min(10, len(self.v.callers[fid]))
|
|
215
|
+
out.append(
|
|
216
|
+
self.task(
|
|
217
|
+
"io_in_loop",
|
|
218
|
+
[fid],
|
|
219
|
+
score * self.weight([fn["file"]]),
|
|
220
|
+
f"{'Batch the queries' if warn else 'Batch the writes'} in {name}",
|
|
221
|
+
"It talks to the database, network or disk once per item. "
|
|
222
|
+
+ (
|
|
223
|
+
"With N items that's N round trips where one would do (the N+1 pattern)."
|
|
224
|
+
if warn
|
|
225
|
+
else "Usually fine inside one transaction, slow if the loop grows."
|
|
226
|
+
),
|
|
227
|
+
where,
|
|
228
|
+
steps,
|
|
229
|
+
[fid],
|
|
230
|
+
"codefactory flags --kind io_in_loop",
|
|
231
|
+
flags,
|
|
232
|
+
)
|
|
233
|
+
)
|
|
234
|
+
return out
|
|
235
|
+
|
|
236
|
+
def grouped(self, kind: str, title: str, why: str, step: str) -> list[dict]:
|
|
237
|
+
flags = [f for f in self.g["flags"] if f["kind"] == kind]
|
|
238
|
+
code = [f for f in flags if not is_test(self.at(f["target"])["file"])]
|
|
239
|
+
if not code:
|
|
240
|
+
return []
|
|
241
|
+
where = [self.at(f["target"], f.get("line")) for f in code]
|
|
242
|
+
steps = [step] + [f"{self.fmt(w)}: {f['message']}" for w, f in zip(where, code, strict=True)]
|
|
243
|
+
ids = [f["target"] for f in code]
|
|
244
|
+
return [
|
|
245
|
+
self.task(
|
|
246
|
+
kind,
|
|
247
|
+
ids,
|
|
248
|
+
BASE[kind] + min(20, 2 * len(code)),
|
|
249
|
+
title.format(n=len(code)),
|
|
250
|
+
why,
|
|
251
|
+
where,
|
|
252
|
+
steps,
|
|
253
|
+
ids,
|
|
254
|
+
f"codefactory flags --kind {kind}",
|
|
255
|
+
code,
|
|
256
|
+
)
|
|
257
|
+
]
|
|
258
|
+
|
|
259
|
+
def per_flag(self, kind: str, title, why: str, steps_for) -> list[dict]:
|
|
260
|
+
out = []
|
|
261
|
+
for f in self.g["flags"]:
|
|
262
|
+
if f["kind"] != kind:
|
|
263
|
+
continue
|
|
264
|
+
w = self.at(f["target"], f.get("line"))
|
|
265
|
+
out.append(
|
|
266
|
+
self.task(
|
|
267
|
+
kind,
|
|
268
|
+
[f["target"], str(f.get("line"))],
|
|
269
|
+
BASE[kind] * self.weight([w["file"]]),
|
|
270
|
+
title(f, w),
|
|
271
|
+
why,
|
|
272
|
+
[w],
|
|
273
|
+
steps_for(f, w),
|
|
274
|
+
[f["target"]],
|
|
275
|
+
f"codefactory flags --kind {kind}",
|
|
276
|
+
[f],
|
|
277
|
+
)
|
|
278
|
+
)
|
|
279
|
+
return out
|
|
280
|
+
|
|
281
|
+
def cycles(self) -> list[dict]:
|
|
282
|
+
out, seen = [], set()
|
|
283
|
+
for f in self.g["flags"]:
|
|
284
|
+
if f["kind"] != "cycle":
|
|
285
|
+
continue
|
|
286
|
+
group = frozenset([f["target"], *f.get("related", [])])
|
|
287
|
+
if group in seen:
|
|
288
|
+
continue
|
|
289
|
+
seen.add(group)
|
|
290
|
+
files = sorted(group)
|
|
291
|
+
flags = [x for x in self.g["flags"] if x["kind"] == "cycle" and x["target"] in group]
|
|
292
|
+
steps = [
|
|
293
|
+
"Find the import that closes the loop: for each file below, check which of the others it imports "
|
|
294
|
+
"(`codefactory context <file>` lists imports).",
|
|
295
|
+
"Move what both sides need into a new module that imports neither, or pass the dependency in "
|
|
296
|
+
"(a parameter or callback) instead of importing it.",
|
|
297
|
+
*[f"`{x}`" for x in files],
|
|
298
|
+
]
|
|
299
|
+
out.append(
|
|
300
|
+
self.task(
|
|
301
|
+
"cycle",
|
|
302
|
+
files,
|
|
303
|
+
BASE["cycle"] + 2 * len(files),
|
|
304
|
+
f"Break the import loop between "
|
|
305
|
+
f"{len(files)} files ({', '.join(x.split('/')[-1] for x in files[:3])}{' …' if len(files) > 3 else ''})",
|
|
306
|
+
"Files that import each other load in a fragile order and can't be understood or tested alone.",
|
|
307
|
+
[{"file": x, "line": 1, "name": ""} for x in files],
|
|
308
|
+
steps,
|
|
309
|
+
[],
|
|
310
|
+
"codefactory flags --kind cycle",
|
|
311
|
+
flags,
|
|
312
|
+
)
|
|
313
|
+
)
|
|
314
|
+
return out
|
|
315
|
+
|
|
316
|
+
def task(self, kind, key_parts, score, title, why, where, steps, ids, verify, flags) -> dict:
|
|
317
|
+
tests = self.tests_for([i for i in ids if i in self.v.fn])
|
|
318
|
+
t = {
|
|
319
|
+
"id": _id(kind, key_parts),
|
|
320
|
+
"kind": kind,
|
|
321
|
+
"score": round(score, 1),
|
|
322
|
+
"severity": min((f["severity"] for f in flags), key=["high", "warn", "info"].index),
|
|
323
|
+
"title": title,
|
|
324
|
+
"why": why,
|
|
325
|
+
"where": where,
|
|
326
|
+
"steps": steps,
|
|
327
|
+
"tests": tests,
|
|
328
|
+
"verify": verify,
|
|
329
|
+
"flags": sorted(self.idx[id(f)] for f in flags if id(f) in self.idx),
|
|
330
|
+
}
|
|
331
|
+
if self.owners: # who to hand it to (CODEOWNERS)
|
|
332
|
+
t["owners"] = sorted({o for w in where for o in self.owners.of(w["file"])})
|
|
333
|
+
t["prompt"] = prompt_for(t)
|
|
334
|
+
return t
|
|
335
|
+
|
|
336
|
+
def plan(self) -> list[dict]:
|
|
337
|
+
tasks = [*self.cycles()]
|
|
338
|
+
tasks += self.per_flag(
|
|
339
|
+
"layer_violation",
|
|
340
|
+
lambda f, w: f"Remove the forbidden import in {w['file'].split('/')[-1]}",
|
|
341
|
+
"factory.toml forbids this layer from importing that one.",
|
|
342
|
+
lambda f, w: [
|
|
343
|
+
f["message"],
|
|
344
|
+
"Move the code that needs it into an allowed layer, or invert the "
|
|
345
|
+
"dependency (pass it in), then remove the import.",
|
|
346
|
+
],
|
|
347
|
+
)
|
|
348
|
+
tasks += self.loops() + self.copies()
|
|
349
|
+
tasks += self.grouped(
|
|
350
|
+
"unused",
|
|
351
|
+
"Remove {n} unused functions",
|
|
352
|
+
"Dead code costs reading time and keeps dependencies alive.",
|
|
353
|
+
"For each: search the repo for its name, including in strings and "
|
|
354
|
+
"config (frameworks can call code by name). If nothing uses it, delete it; if something does, "
|
|
355
|
+
"silence it with `codefactory: ignore unused — <who calls it>`.",
|
|
356
|
+
)
|
|
357
|
+
tasks += self.grouped(
|
|
358
|
+
"test_only",
|
|
359
|
+
"Decide on {n} functions only tests call",
|
|
360
|
+
"They're dead in the product but kept alive by tests.",
|
|
361
|
+
"For each: if the product should use it, wire it in; if not, delete "
|
|
362
|
+
"it and its tests; if it's a test helper, move it next to the tests.",
|
|
363
|
+
)
|
|
364
|
+
tasks += self.per_flag(
|
|
365
|
+
"sequential_await",
|
|
366
|
+
lambda f, w: f"Run independent awaits together in {w['name'] or w['file']}",
|
|
367
|
+
"Each round of the loop waits for the previous one.",
|
|
368
|
+
lambda f, w: [
|
|
369
|
+
f["message"],
|
|
370
|
+
"If the iterations don't depend on each other (and aren't "
|
|
371
|
+
"ordered writes on one connection), start them all and await Promise.all / "
|
|
372
|
+
"asyncio.gather, with a concurrency limit for network calls.",
|
|
373
|
+
],
|
|
374
|
+
)
|
|
375
|
+
scans = defaultdict(list)
|
|
376
|
+
for f in self.g["flags"]:
|
|
377
|
+
if f["kind"] == "quadratic_scan":
|
|
378
|
+
scans[self.at(f["target"])["file"]].append(f)
|
|
379
|
+
for file, flags in scans.items():
|
|
380
|
+
where = [self.at(f["target"], f.get("line")) for f in flags]
|
|
381
|
+
tasks.append(
|
|
382
|
+
self.task(
|
|
383
|
+
"quadratic_scan",
|
|
384
|
+
[file],
|
|
385
|
+
(BASE["quadratic_scan"] + len(flags)) * self.weight([file]),
|
|
386
|
+
f"Replace {len(flags)} search(es) in loops in {file.split('/')[-1]}",
|
|
387
|
+
"Searching an array inside a loop is O(n²): fine for short lists, slow for long ones.",
|
|
388
|
+
where,
|
|
389
|
+
[
|
|
390
|
+
"Only worth it if these lists can grow past a few hundred items. Build a Map "
|
|
391
|
+
"or Set once before the loop and look items up in it:"
|
|
392
|
+
]
|
|
393
|
+
+ [f"{self.fmt(w)}: {f['message'].split(':')[0]}" for w, f in zip(where, flags, strict=True)],
|
|
394
|
+
[f["target"] for f in flags],
|
|
395
|
+
"codefactory flags --kind quadratic_scan",
|
|
396
|
+
flags,
|
|
397
|
+
)
|
|
398
|
+
)
|
|
399
|
+
tasks += self.per_flag(
|
|
400
|
+
"long_function",
|
|
401
|
+
lambda f, w: f"Split {w['name']} ({self.v.fn[f['target']]['loc']} lines)",
|
|
402
|
+
"Long functions are hard to read, test and change safely.",
|
|
403
|
+
lambda f, w: [
|
|
404
|
+
f"{self.fmt(w)} is {self.v.fn[f['target']]['loc']} lines.",
|
|
405
|
+
"Pull out the parts that have a name of their own (a calculation, a block of "
|
|
406
|
+
"UI, a load/save step) into separate functions; keep behaviour identical.",
|
|
407
|
+
],
|
|
408
|
+
)
|
|
409
|
+
if self.changes: # the same problem costs more where people keep working: up to twice the score
|
|
410
|
+
for task in tasks:
|
|
411
|
+
n = max((self.changes.get(w["file"], 0) for w in task["where"]), default=0)
|
|
412
|
+
if n >= 3:
|
|
413
|
+
task["changes"] = n
|
|
414
|
+
task["score"] = round(task["score"] * (1 + min(n, 20) / 20), 1)
|
|
415
|
+
tasks.sort(key=lambda t: (-t["score"], t["title"]))
|
|
416
|
+
return tasks
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def prompt_for(t: dict) -> str:
|
|
420
|
+
where = "\n".join(f"- {Planner.fmt(w)}" for w in t["where"][:15]) + (
|
|
421
|
+
f"\n- … {len(t['where']) - 15} more" if len(t["where"]) > 15 else ""
|
|
422
|
+
)
|
|
423
|
+
steps = "\n".join(f"{i}. {s}" if not s.startswith(" ") else f" {s.strip()}" for i, s in enumerate(t["steps"], 1))
|
|
424
|
+
tests = (
|
|
425
|
+
("\n".join(f"- {x}" for x in t["tests"]) + "\n- and the project's full test command")
|
|
426
|
+
if t["tests"]
|
|
427
|
+
else "- the project's full test command"
|
|
428
|
+
)
|
|
429
|
+
return f"""Task (codefactory plan {t["id"]}): {t["title"]}
|
|
430
|
+
|
|
431
|
+
Why: {t["why"]}
|
|
432
|
+
|
|
433
|
+
Where:
|
|
434
|
+
{where}
|
|
435
|
+
|
|
436
|
+
Steps:
|
|
437
|
+
{steps}
|
|
438
|
+
|
|
439
|
+
Constraints:
|
|
440
|
+
- Keep behaviour identical. Make the smallest change that does the job.
|
|
441
|
+
- Don't rename or change the signature of anything other code calls unless you update every caller
|
|
442
|
+
(`codefactory context <name>` lists them, with the tests that exercise it).
|
|
443
|
+
|
|
444
|
+
Done when:
|
|
445
|
+
- `{t["verify"]}` no longer lists these
|
|
446
|
+
- These tests pass:
|
|
447
|
+
{tests}
|
|
448
|
+
"""
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def make_plan(g: dict, changes: dict[str, int] | None = None) -> list[dict]:
|
|
452
|
+
"""Ranked tasks; with `changes` (commits per file), work in code that keeps changing ranks higher."""
|
|
453
|
+
return Planner(g, changes).plan()
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def plan_markdown(tasks: list[dict], top: int) -> str:
|
|
457
|
+
lines = [
|
|
458
|
+
f"# Plan: {len(tasks)} tasks, highest payoff first",
|
|
459
|
+
"",
|
|
460
|
+
"Each has an id: `codefactory prompt <id>` prints a ready-to-paste prompt for Claude Code.",
|
|
461
|
+
"",
|
|
462
|
+
]
|
|
463
|
+
for i, t in enumerate(tasks[:top], 1):
|
|
464
|
+
hot = f" · changed {t['changes']}× in 12 months" if t.get("changes") else ""
|
|
465
|
+
lines.append(f"## {i}. {t['title']} `{t['id']}` · {t['severity']} · score {t['score']}{hot}")
|
|
466
|
+
lines.append(t["why"])
|
|
467
|
+
lines += [""] + [f"- [ ] {s}" if not s.startswith(" ") else f" {s.strip()}" for s in t["steps"][:12]]
|
|
468
|
+
if len(t["steps"]) > 12:
|
|
469
|
+
lines.append(f"- [ ] … {len(t['steps']) - 12} more (see the prompt)")
|
|
470
|
+
if t["tests"]:
|
|
471
|
+
lines.append(f"- [ ] Run: {', '.join(t['tests'][:6])}{' …' if len(t['tests']) > 6 else ''}")
|
|
472
|
+
lines.append(f"- [ ] Check: `{t['verify']}`")
|
|
473
|
+
lines.append("")
|
|
474
|
+
if len(tasks) > top:
|
|
475
|
+
lines.append(f"… {len(tasks) - top} more tasks: `codefactory plan --top {len(tasks)}`")
|
|
476
|
+
return "\n".join(lines) + "\n"
|