devkb 0.2.0__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. devkb/__init__.py +11 -0
  2. devkb/audit.py +173 -0
  3. devkb/bench/add_packs.py +52 -0
  4. devkb/bench/cli_tasks.py +105 -0
  5. devkb/bench/confirm_tasks.py +149 -0
  6. devkb/bench/module_truth.py +249 -0
  7. devkb/bench/oco_tasks.py +216 -0
  8. devkb/bench/pipeline.py +313 -0
  9. devkb/bench/process_tasks.py +135 -0
  10. devkb/bench/report.py +74 -0
  11. devkb/bench/run.py +174 -0
  12. devkb/bench/truth_check.py +148 -0
  13. devkb/bench/workflow_report.py +64 -0
  14. devkb/bench/workflow_run.py +206 -0
  15. devkb/bench/workflow_tasks.py +227 -0
  16. devkb/build.py +258 -0
  17. devkb/build_symbols.py +1394 -0
  18. devkb/call_recall.py +159 -0
  19. devkb/cli.py +53 -0
  20. devkb/coverage.py +155 -0
  21. devkb/edge_truth.py +272 -0
  22. devkb/extractors/backlog.py +113 -0
  23. devkb/extractors/component_subsystem.py +116 -0
  24. devkb/extractors/configuration.py +267 -0
  25. devkb/extractors/files_tests.py +220 -0
  26. devkb/extractors/flows.py +117 -0
  27. devkb/extractors/lifecycle.py +258 -0
  28. devkb/extractors/members.py +160 -0
  29. devkb/extractors/pull_requests.py +271 -0
  30. devkb/extractors/releases.py +49 -0
  31. devkb/extractors/source_baseline.py +66 -0
  32. devkb/extractors/spec_docs.py +220 -0
  33. devkb/extractors/symbol_tests.py +131 -0
  34. devkb/extractors/test_inventory.py +38 -0
  35. devkb/extractors/ticket_similarity.py +193 -0
  36. devkb/extractors/tickets_git.py +151 -0
  37. devkb/extractors/warnings.py +230 -0
  38. devkb/extractors/work_units.py +90 -0
  39. devkb/github.py +515 -0
  40. devkb/gitutil.py +16 -0
  41. devkb/index.py +51 -0
  42. devkb/init.py +178 -0
  43. devkb/mcp_server.py +216 -0
  44. devkb/model.py +221 -0
  45. devkb/module_file_bridge.py +57 -0
  46. devkb/ontology.md +178 -0
  47. devkb/packs.py +462 -0
  48. devkb/process_api.py +1601 -0
  49. devkb/project_context.py +191 -0
  50. devkb/query.py +251 -0
  51. devkb/service.py +324 -0
  52. devkb/startup.py +103 -0
  53. devkb/test_discovery.py +76 -0
  54. devkb/ts_symbols.py +291 -0
  55. devkb-0.2.0.dist-info/METADATA +162 -0
  56. devkb-0.2.0.dist-info/RECORD +61 -0
  57. devkb-0.2.0.dist-info/WHEEL +5 -0
  58. devkb-0.2.0.dist-info/entry_points.txt +2 -0
  59. devkb-0.2.0.dist-info/licenses/LICENSE +202 -0
  60. devkb-0.2.0.dist-info/licenses/NOTICE +11 -0
  61. devkb-0.2.0.dist-info/top_level.txt +1 -0
devkb/packs.py ADDED
@@ -0,0 +1,462 @@
1
+ #!/usr/bin/env python3
2
+ """Predefined graph packs: the answer to a chain-or-join question, written before the session starts (ODSF-313).
3
+
4
+ The workflow benchmark (docs/workflow-benchmark-odsf310.md) showed where a graph pays: walking call chains and joining
5
+ code to tests. It also showed why it often does not: every graph turn pays for tool definitions and a reply, and the
6
+ agent re-reads the code to check the answer anyway. A pack removes both. It is generated from what a ticket or task
7
+ already names (an error message, a function, a role), goes into the prompt, so no MCP server or tool definitions are
8
+ loaded, and it carries what makes checking unnecessary:
9
+
10
+ evidence every caller, handler and test given as `path:line` with the line of code that makes the call
11
+ coverage either every call site under the name was attributed, or the files holding the ones that were not
12
+ freshness the commit the graph was built at, and which of the listed files changed since in the working tree
13
+ shape sections in the order the deliverable needs them
14
+
15
+ python3 devkb/packs.py --project OCO error "workflow needs a non-empty 'states' object"
16
+ python3 devkb/packs.py --project OCO change revoke_user_sessions
17
+ python3 devkb/packs.py --project OCO refactor add_edge --role BE
18
+ python3 devkb/packs.py --project OCO ticket GH-123 a ticket's pull requests, commits, changed functions, tests
19
+ python3 devkb/packs.py --project OCO pr 456 a pull request's commits, changed functions, tests, issues closed
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import re
25
+ import subprocess
26
+ import sys
27
+ from pathlib import Path
28
+
29
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
30
+
31
+ from devkb.process_api import ProcessAPI, is_test_path # noqa: E402
32
+ from devkb.service import GraphNotBuilt # noqa: E402
33
+
34
+ MAX_DEPTH = 6
35
+
36
+
37
+ class Packer:
38
+ def __init__(self, api: ProcessAPI) -> None:
39
+ self.api, self.idx = api, api.idx
40
+ self._lines: dict[str, list[str]] = {}
41
+
42
+ # ── evidence ──────────────────────────────────────────────────────────────
43
+ def _file(self, rel: str) -> list[str]:
44
+ if rel not in self._lines:
45
+ try:
46
+ self._lines[rel] = (self.api.root / rel).read_text(errors="replace").splitlines()
47
+ except OSError:
48
+ self._lines[rel] = []
49
+ return self._lines[rel]
50
+
51
+ def call_site(self, caller: int, name: str) -> str:
52
+ """`path:line: code` for the first line in `caller`'s body that calls `name`, or the caller's own line."""
53
+ key = self.api._key(caller)
54
+ rel = key.split("::")[0]
55
+ p = self.idx.props[caller]
56
+ start, end = int(p.get("line_start") or 1), int(p.get("line_end") or p.get("line_start") or 1)
57
+ lines = self._file(rel)
58
+ rx = re.compile(r"\b" + re.escape(name) + r"\s*\(")
59
+ for n in range(start, min(end, len(lines)) + 1):
60
+ if rx.search(lines[n - 1]):
61
+ return f"{rel}:{n}: {lines[n - 1].strip()[:140]}"
62
+ return f"{rel}:{start}: (def {key.split('::')[-1]})"
63
+
64
+ def def_line(self, sym: int) -> str:
65
+ key = self.api._key(sym)
66
+ rel, start = key.split("::")[0], int(self.idx.props[sym].get("line_start") or 1)
67
+ lines = self._file(rel)
68
+ return f"{rel}:{start}: {lines[start - 1].strip()[:140] if 0 < start <= len(lines) else ''}"
69
+
70
+ def _name(self, sym: int) -> str:
71
+ return self.api._key(sym).split("::")[-1].split(".")[-1]
72
+
73
+ def freshness(self, files: list[str]) -> str:
74
+ head = self.idx.git_head
75
+ try:
76
+ changed = set(subprocess.run(["git", "diff", "--name-only", head], cwd=self.api.root, capture_output=True,
77
+ text=True, timeout=10).stdout.split())
78
+ except (OSError, subprocess.SubprocessError):
79
+ changed = set()
80
+ hit = sorted(set(files) & changed)
81
+ return (f"Built from the dev-process graph at commit `{head[:10]}`. "
82
+ + (f"**Changed since, re-read these:** {', '.join(f'`{f}`' for f in hit)}." if hit
83
+ else "None of the files below has changed since; the line numbers are current."))
84
+
85
+ def coverage(self, syms: list[int], shown: set[str]) -> str:
86
+ c = self.api._coverage(syms, shown)
87
+ if c.get("complete"):
88
+ return "**Complete.** Every call site under these names was attributed to its target; nothing else calls them."
89
+ names = {self.api._key(x).split("::")[-1].split(".")[-1] for x in syms}
90
+ name = next(iter(names)) if len(names) == 1 else ""
91
+ listed = c.get("search_files", [])
92
+ total = max(c.get("search_file_count") or 0, len(listed))
93
+ files = ", ".join(f"`{f}`" for f in listed) or "(files not recorded)"
94
+ shared = f" {c['shared_by']} symbols share the name, so most may be calls to the others." if c.get("shared_by") else ""
95
+ head = f"**Incomplete: {c['unresolved_calls']} call site(s) under this name could not be attributed.**{shared} "
96
+ if c.get("in_listed_files"):
97
+ return head + "They are in files already listed above; check those files' other calls under this name."
98
+ if total <= len(listed):
99
+ return head + f"Search only these files for them: {files}."
100
+ return head + (f"They are in {total} files; the {len(listed)} with the most: {files}. Search the whole "
101
+ f"repository for the rest" + (f" (`grep -rn '{name}(' --include='*.py' .`)" if name else "") + ".")
102
+
103
+ # ── walking ───────────────────────────────────────────────────────────────
104
+ def up(self, start: set[int]) -> dict[int, int]:
105
+ """Every production function that reaches `start` through calls: {caller: the callee it calls on the way}."""
106
+ parent: dict[int, int] = {}
107
+ frontier = set(start)
108
+ for _ in range(MAX_DEPTH):
109
+ nxt = set()
110
+ for s in frontier:
111
+ for c in set(self.idx.sources("CALLS", s)) | set(self.idx.sources("CALLS_API", s)):
112
+ if c in parent or c in start or is_test_path(self.api._key(c).split("::")[0]):
113
+ continue
114
+ parent[c] = s
115
+ nxt.add(c)
116
+ frontier = nxt
117
+ if not frontier:
118
+ break
119
+ return parent
120
+
121
+ def _reachers(self, parent: dict[int, int], cap: int = 40) -> list[str]:
122
+ """Every production function that reaches the subject through calls, each with the call that proves it. A
123
+ repository without route handlers (a command-line tool, a library) has no other answer to "what reaches it"."""
124
+ keys = sorted(parent, key=self.api._key)
125
+ out = ["", f"## Functions that reach it, at any depth ({len(keys)})"]
126
+ out += [f"- `{self.api._key(c)}` — `{self.call_site(c, self._name(parent[c]))}`" for c in keys[:cap]]
127
+ if len(keys) > cap:
128
+ out.append(f"- … {len(keys) - cap} more")
129
+ return out if keys else out + ["- none the graph resolves"]
130
+
131
+ def handlers(self, parent: dict[int, int], start: set[int]) -> list[tuple[int, list[int]]]:
132
+ out = []
133
+ for c in sorted(set(parent) | start, key=self.api._key):
134
+ if self.idx.ep_by_owner.get(self.api._key(c)):
135
+ path, x = [c], c
136
+ while x in parent:
137
+ x = parent[x]
138
+ path.append(x)
139
+ out.append((c, path))
140
+ return out
141
+
142
+ def tests(self, syms: set[int]) -> dict[str, list[tuple[int, int]]]:
143
+ """Test files with (test function, the symbol it calls) for every test that calls any of `syms`."""
144
+ out: dict[str, list[tuple[int, int]]] = {}
145
+ for s in syms:
146
+ for c in set(self.idx.sources("CALLS", s)):
147
+ rel = self.api._key(c).split("::")[0]
148
+ if is_test_path(rel):
149
+ out.setdefault(rel, []).append((c, s))
150
+ return out
151
+
152
+ def _tests_section(self, tests: dict[str, list[tuple[int, int]]]) -> list[str]:
153
+ lines = []
154
+ for rel in sorted(tests):
155
+ c, s = tests[rel][0]
156
+ more = f" (+{len(tests[rel]) - 1} more tests)" if len(tests[rel]) > 1 else ""
157
+ lines.append(f"- `{rel}`{more} — `{self.call_site(c, self._name(s))}`")
158
+ return lines or ["- none in the graph"]
159
+
160
+ def _run(self, files: list[str]) -> str:
161
+ return self.api._run_line(sorted(files)) if files else ""
162
+
163
+ # ── the three packs ───────────────────────────────────────────────────────
164
+ def error(self, message: str) -> str:
165
+ r = self.api.rca_trace(message)
166
+ if "error" in r:
167
+ return f"# Graph pack: error\n\nThe graph has no error matching \"{message}\". Search the code."
168
+ raisers = [self.api._resolve(k)[0] for k in r["raisers"]]
169
+ raisers = [x for x in raisers if x is not None]
170
+ parent = self.up(set(raisers))
171
+ hs = self.handlers(parent, set(raisers))
172
+ closure = set(parent) | set(raisers)
173
+ tests = self.tests(closure)
174
+ out = [f"# Graph pack: error \"{message[:80]}\"", "", self.freshness(sorted({self.api._key(x).split('::')[0] for x in closure})), "",
175
+ "## Raised by"]
176
+ out += [f"- `{self.api._key(x)}` — `{self.def_line(x)}`" for x in raisers]
177
+ out += self._reachers(parent)
178
+ if self.idx.ep_by_owner:
179
+ out += ["", f"## Route handlers that reach it ({len(hs)})"]
180
+ for h, path in hs:
181
+ chain = " → ".join(f"`{self.api._key(p).split('::')[-1]}`" for p in path)
182
+ out.append(f"- `{self.api._key(h)}` ({', '.join(self.api._key(e) for e in self.idx.ep_by_owner[self.api._key(h)][:2])})")
183
+ for a, b in zip(path, path[1:]):
184
+ out.append(f" - `{self.call_site(a, self._name(b))}`")
185
+ out.append(f" - path: {chain}")
186
+ if not hs and self.idx.ep_by_owner:
187
+ out.append("- none: no route handler reaches it through calls the graph resolves")
188
+ out += ["", f"## Test files on those paths ({len(tests)})"] + self._tests_section(tests)
189
+ if tests:
190
+ out += ["", f"Run: `{self._run(list(tests))}`"]
191
+ out += ["", "## Coverage", self.coverage(sorted(closure, key=self.api._key)[:40], set(tests) | {self.api._key(x).split('::')[0] for x in closure})]
192
+ return "\n".join(out + ["", HOW_TO_USE])
193
+
194
+ def change(self, name: str, path: str = "") -> str:
195
+ i, err = self.api._resolve(f"{path}::{name}" if path and "::" not in name else name)
196
+ if i is None and path:
197
+ cands = [s for s in self.idx.short.get(name, []) if self.api._key(s).startswith(path + "::")]
198
+ i = cands[0] if len(cands) == 1 else None
199
+ if i is None:
200
+ return f"# Graph pack: change\n\nThe graph cannot resolve `{name}`" + (f" in `{path}`" if path else "") + ". Search the code."
201
+ parent = self.up({i})
202
+ hs = self.handlers(parent, {i})
203
+ closure = set(parent) | {i}
204
+ tests = self.tests(closure)
205
+ out = [f"# Graph pack: changing `{self.api._key(i)}`", "",
206
+ self.freshness(sorted({self.api._key(x).split('::')[0] for x in closure})), "", f"Defined at `{self.def_line(i)}`."]
207
+ out += self._reachers(parent)
208
+ if self.idx.ep_by_owner:
209
+ out += ["", f"## Route handlers that reach it ({len(hs)})"]
210
+ for h, path_ in hs:
211
+ out.append(f"- `{self.api._key(h)}` ({', '.join(self.api._key(e) for e in self.idx.ep_by_owner[self.api._key(h)][:2])}) — path: "
212
+ + " → ".join(f"`{self.api._key(p).split('::')[-1]}`" for p in path_))
213
+ for a, b in zip(path_, path_[1:]):
214
+ out.append(f" - `{self.call_site(a, self._name(b))}`")
215
+ if not hs and self.idx.ep_by_owner:
216
+ out.append("- none: no route handler reaches it through calls the graph resolves")
217
+ out += ["", f"## Test files to run ({len(tests)}): every test calling it or a function on those paths"] + self._tests_section(tests)
218
+ if tests:
219
+ out += ["", f"Run: `{self._run(list(tests))}`"]
220
+ out += ["", "## Coverage", self.coverage(sorted(closure, key=self.api._key)[:40], set(tests) | {self.api._key(x).split('::')[0] for x in closure})]
221
+ return "\n".join(out + ["", HOW_TO_USE])
222
+
223
+ def file(self, path: str, cap: int = 25) -> str:
224
+ """Before editing a file: which of its functions other files depend on (each with the call that proves it),
225
+ the tests that exercise it, and what the graph could not attribute. A file's contract is what is called from
226
+ outside it, so those functions come first and its private helpers are only counted."""
227
+ path = path.strip().lstrip("./")
228
+ syms = list(self.idx.sym_by_file.get(path, []))
229
+ if not syms:
230
+ return f"# Graph pack: file\n\nThe graph has no code in `{path}`. Search the code."
231
+ rows = []
232
+ for i in syms:
233
+ outside: dict[str, int] = {}
234
+ for c in self.idx.sources("CALLS", i):
235
+ f = self.api._key(c).split("::")[0]
236
+ if f != path:
237
+ outside.setdefault(f, c)
238
+ rows.append((i, outside))
239
+ used = sorted((r for r in rows if r[1]), key=lambda r: (-len(r[1]), self.api._key(r[0])))
240
+ tests = self.tests(set(syms) | set(self.up(set(syms)))) # tests that reach the file through calls at any depth
241
+ dependants = sorted({f for _, o in used for f in o})
242
+ out = [f"# Graph pack: before editing `{path}`", "", self.freshness([path] + dependants[:40]), "",
243
+ f"## Functions other files call ({len(used)} of {len(syms)})"]
244
+ for i, outside in used[:cap]:
245
+ f, c = next(iter(sorted(outside.items())))
246
+ more = f" and {len(outside) - 1} more file(s)" if len(outside) > 1 else ""
247
+ out.append(f"- `{self.api._key(i).split('::', 1)[1]}` — {len(outside)} file(s): `{self.call_site(c, self._name(i))}`{more}")
248
+ if len(used) > cap:
249
+ out.append(f"- … {len(used) - cap} more")
250
+ if not used:
251
+ out.append("- none: nothing outside this file calls into it through calls the graph resolves")
252
+ out += ["", f"## Files that depend on it ({len(dependants)})"] + [f"- `{f}`" for f in dependants[:40]]
253
+ out += ["", f"## Tests that exercise it, directly or through callers ({len(tests)})"] + self._tests_section(tests)
254
+ if tests:
255
+ out += ["", f"Run: `{self._run(list(tests))}`"]
256
+ out += ["", "## Coverage", self.coverage(sorted(syms, key=self.api._key)[:40], set(dependants) | set(tests))]
257
+ return "\n".join(out + ["", HOW_TO_USE])
258
+
259
+ def refactor(self, name: str, role: str = "", path: str = "") -> str:
260
+ i, err = self.api._resolve(f"{path}::{name}" if path and "::" not in name else name)
261
+ if i is None:
262
+ cands = [s for s in self.idx.short.get(name, []) if not path or self.api._key(s).startswith(path + "::")]
263
+ i = cands[0] if len(cands) == 1 else None
264
+ if i is None:
265
+ return f"# Graph pack: refactor\n\nThe graph cannot resolve `{name}` unambiguously. Search the code."
266
+ callers = sorted(set(self.idx.sources("CALLS", i)), key=self.api._key)
267
+ by_file: dict[str, list[int]] = {}
268
+ for c in callers:
269
+ by_file.setdefault(self.api._key(c).split("::")[0], []).append(c)
270
+ own = self.api._key(i).split("::")[0]
271
+ # Calls made outside any function (import time, class bodies) have no caller Symbol; the graph keeps their files.
272
+ at_module = sorted(f for f in (self.idx.props[i].get("module_callers") or []) if f != own and f not in by_file)
273
+ dnt = self.api._role_table().get(role, {}).get("dnt", []) if role else []
274
+ files = sorted(set(by_file) | set(at_module))
275
+ blocked = sorted(f for f in files if any(f.startswith(p) for p in dnt))
276
+ tests = sorted(f for f in files if is_test_path(f))
277
+ out = [f"# Graph pack: changing the signature of `{self.api._key(i)}`" + (f" as role {role}" if role else ""), "",
278
+ self.freshness(files), "", f"Defined at `{self.def_line(i)}`.", "",
279
+ f"## Files with a direct caller ({len(files)}, tests included)"]
280
+ for f in files:
281
+ if f not in by_file:
282
+ out.append(f"- `{f}` — called at module level, outside any function")
283
+ continue
284
+ c = by_file[f][0]
285
+ more = f" (+{len(by_file[f]) - 1} more)" if len(by_file[f]) > 1 else ""
286
+ out.append(f"- `{f}`{more} — `{self.call_site(c, self._name(i))}`")
287
+ out += ["", f"## Test files among them ({len(tests)})"] + ([f"- `{f}`" for f in tests] or ["- none"])
288
+ if role:
289
+ out += ["", f"## Files role {role} must not edit ({len(blocked)})"] + ([f"- `{f}`" for f in blocked] or ["- none"])
290
+ if own not in by_file:
291
+ out += ["", f"(The defining file `{own}` is not counted as a caller.)"]
292
+ out += ["", "## Coverage", self.coverage([i], set(files))]
293
+ return "\n".join(out + ["", HOW_TO_USE])
294
+
295
+
296
+ # ── ADDENDUM-1 S2: process joins (ODSF-316) ────────────────────────────────
297
+ def _changed_by(self, commits: list[int]) -> dict[int, str]:
298
+ """Module-level production functions, still present, that these commits changed: {symbol: short hash}."""
299
+ changed: dict[int, str] = {}
300
+ for c in commits:
301
+ r = self.api.review_pack(self.api._key(c)[:12])
302
+ for key in r.get("changed_symbols", []):
303
+ path, _, qual = key.partition("::")
304
+ i = self.idx.node("Symbol", key)
305
+ if i is not None and "." not in qual and not is_test_path(path) and self.idx.props[i].get("kind") == "function":
306
+ changed.setdefault(i, self.idx.props[c].get("short_hash", self.api._key(c)[:10]))
307
+ return changed
308
+
309
+ def _pr_commits_to_read(self, prs: list[int]) -> list[int]:
310
+ """Each pull request's commits, minus the ones a merge commit already contains: a merge commit's diff is the
311
+ whole pull request, so reading its second-parent commits too would only repeat it."""
312
+ out: list[int] = []
313
+ for p in prs:
314
+ cs = sorted(set(self.idx.targets("MERGES", p)), key=lambda c: (self.idx.props[c].get("date", ""), self.api._key(c)))
315
+ merge = self.idx.props[p].get("merge_commit")
316
+ m = self.idx.node("Commit", merge) if merge else None
317
+ out += [m] if m is not None and m in cs and self.idx.props[p].get("merge_style") == "merge" else cs
318
+ return out
319
+
320
+ def _pr_lines(self, prs: list[int], ticket: int | None = None, cap: int = 15) -> list[str]:
321
+ lines = []
322
+ for p in prs[:cap]:
323
+ props = self.idx.props[p]
324
+ how = ", ".join(x for x in (props.get("state"), props.get("merge_style")) if x)
325
+ mark = ""
326
+ if ticket is not None:
327
+ conf, unverified = self.api._link("CLOSES", p, ticket)
328
+ if conf is not None:
329
+ mark = f" — closes it at confidence {conf}" + (", **unverified**: the number may be a pull request, not an issue" if unverified else "")
330
+ lines.append(f"- `{self.api._key(p)}` ({how}) {(props.get('title') or '')[:90]}{mark}")
331
+ if len(prs) > cap:
332
+ lines.append(f"- … {len(prs) - cap} more")
333
+ return lines or ["- none in the graph"]
334
+
335
+ def _pr_coverage_text(self, unverified: list[str]) -> str:
336
+ cov = self.api.pr_coverage(unverified)
337
+ if cov is None:
338
+ return "the repository has no GitHub remote, so no pull-request links were looked for."
339
+ head = ("**Complete.** The GitHub layer was fetched; the links above are GitHub's own record." if cov["complete"]
340
+ else f"**Incomplete** (GitHub layer: {cov['github']}).")
341
+ note = f" {cov['note']}." if cov.get("note") and not cov["complete"] else ""
342
+ unv = f" Not verified: {', '.join(f'`{u}`' for u in cov['unverified'])}." if cov.get("unverified") else ""
343
+ return head + note + unv
344
+
345
+ def ticket(self, ticket_id: str) -> str:
346
+ """A ticket's commits (its own and its pull requests'), the module-level functions they changed that exist now,
347
+ and the tests that call them."""
348
+ t = self.idx.node("Ticket", ticket_id)
349
+ if t is None:
350
+ return f"# Graph pack: ticket {ticket_id}\n\nThe graph has no ticket {ticket_id}. Search the history."
351
+ prs = self.api._ticket_prs(t)
352
+ referencing = set(self.idx.sources("REFERENCES", t))
353
+ via_prs = {c for p in prs for c in self.idx.targets("MERGES", p)}
354
+ commits = sorted(referencing | via_prs, key=lambda c: self.idx.props[c].get("date", ""))
355
+ read = sorted(referencing | set(self._pr_commits_to_read(prs)), key=lambda c: self.idx.props[c].get("date", ""))
356
+ changed = self._changed_by(read)
357
+ tests = self.tests(set(changed))
358
+ out = [f"# Graph pack: ticket {ticket_id} ({(self.idx.props[t].get('title') or '')[:90]})", "",
359
+ self.freshness(sorted({self.api._key(i).split('::')[0] for i in changed})), ""]
360
+ if prs or self.api.pr_coverage() is not None:
361
+ out += [f"## Pull requests that close it ({len(prs)})"] + self._pr_lines(prs, t) + [""]
362
+ out += [f"## Commits referencing it or brought in by its pull requests ({len(commits)})"]
363
+ out += [f"- `{self.idx.props[c].get('short_hash', '')}` {self.idx.props[c].get('date', '')} {(self.idx.props[c].get('subject') or '')[:90]}"
364
+ for c in commits[:15]]
365
+ out += ["", f"## Module-level functions those commits changed, still present ({len(changed)})"]
366
+ out += [f"- `{self.api._key(i)}` (changed in `{h}`) — `{self.def_line(i)}`" for i, h in sorted(changed.items(), key=lambda p: self.api._key(p[0]))]
367
+ out += ["", f"## Test files that call them ({len(tests)})"] + self._tests_section(tests)
368
+ out += ["", "## Coverage", self.coverage(sorted(changed, key=self.api._key), set(tests))]
369
+ if self.api.pr_coverage() is not None:
370
+ out += ["", "Pull-request links: " + self._pr_coverage_text(self.api._pr_unverified(t, prs))]
371
+ return "\n".join(out + ["", HOW_TO_USE])
372
+
373
+ def pr(self, number: str) -> str:
374
+ """A pull request: its commits, the functions it changed, the tests that call them, the issues it closes."""
375
+ p, err = self.api._pr_ref(number)
376
+ if err:
377
+ gh = self.idx.github
378
+ hint = ("" if gh and gh.get("status") == "ok" else
379
+ " It may be a rebase merge, which leaves no trace in git (build with --github), or outside the history the graph covers.")
380
+ return f"# Graph pack: pull request {number}\n\nThe graph has no pull request {number}.{hint} Search the history."
381
+ props = self.idx.props[p]
382
+ commits = sorted(set(self.idx.targets("MERGES", p)), key=lambda c: (self.idx.props[c].get("date", ""), self.api._key(c)))
383
+ closes = sorted(set(self.idx.targets("CLOSES", p)), key=self.api._key)
384
+ changed = self._changed_by(self._pr_commits_to_read([p]))
385
+ tests = self.tests(set(changed))
386
+ facts = [f"{k}: {props[k]}" for k in ("state", "merge_style", "merged_at", "base", "head", "url") if props.get(k)]
387
+ out = [f"# Graph pack: pull request {self.api._key(p)} ({(props.get('title') or '')[:90]})", "",
388
+ self.freshness(sorted({self.api._key(i).split('::')[0] for i in changed})), "", "; ".join(facts) + ".",
389
+ "", f"## Commits it brought in ({len(commits)})"]
390
+ for c in commits[:25]:
391
+ conf = self.api._link("MERGES", p, c)[0]
392
+ out.append(f"- `{self.idx.props[c].get('short_hash', '')}` {self.idx.props[c].get('date', '')} "
393
+ f"{(self.idx.props[c].get('subject') or '')[:90]} (confidence {conf})")
394
+ if len(commits) > 25:
395
+ out.append(f"- … {len(commits) - 25} more")
396
+ if not commits:
397
+ out.append("- none in the graph")
398
+ out += ["", f"## Issues it closes ({len(closes)})"]
399
+ for t in closes:
400
+ conf, unv = self.api._link("CLOSES", p, t)
401
+ out.append(f"- `{self.api._key(t)}` {(self.idx.props[t].get('title') or '')[:80]} (confidence {conf}"
402
+ + (", **unverified**: offline, the number may be a pull request" if unv else "") + ")")
403
+ if not closes:
404
+ out.append("- none in the graph")
405
+ out += ["", f"## Module-level functions it changed, still present ({len(changed)})"]
406
+ out += [f"- `{self.api._key(i)}` (changed in `{h}`) — `{self.def_line(i)}`" for i, h in sorted(changed.items(), key=lambda x: self.api._key(x[0]))]
407
+ out += ["", f"## Tests to run: test files that call them ({len(tests)})"] + self._tests_section(tests)
408
+ if tests:
409
+ out += ["", f"Run: `{self._run(list(tests))}`"]
410
+ out += ["", "## Coverage", self.coverage(sorted(changed, key=self.api._key), set(tests)),
411
+ "", "Pull-request links: " + self._pr_coverage_text([self.api._key(t) for t in closes if self.api._link("CLOSES", p, t)[1]])]
412
+ return "\n".join(out + ["", HOW_TO_USE])
413
+
414
+ def commit_trace(self, commit: str) -> str:
415
+ """A commit's ticket, that ticket's epic and specification, as the graph records them."""
416
+ cands = [i for (typ, k), i in self.idx.by_key.items() if typ == "Commit" and k.startswith(commit)]
417
+ if len(cands) != 1:
418
+ return f"# Graph pack: commit {commit}\n\nThe graph has no single commit `{commit}`. Search the history."
419
+ c = cands[0]
420
+ tickets = sorted({self.api._key(x) for x in self.idx.targets("REFERENCES", c)})
421
+ out = [f"# Graph pack: commit `{commit}` — {(self.idx.props[c].get('subject') or '')[:90]}", "",
422
+ f"Built from the dev-process graph at commit `{self.idx.git_head[:10]}`.", "", f"## Tickets it references ({len(tickets)})"]
423
+ for tk in tickets:
424
+ ti = self.idx.node("Ticket", tk)
425
+ epics = [self.api._key(x) for x in self.idx.targets("CHILD_OF", ti)]
426
+ specs = [self.idx.props[x].get("spec_id") or self.api._key(x) for x in self.idx.targets("IMPLEMENTS", ti)]
427
+ out.append(f"- `{tk}`: epic {', '.join(f'`{e}`' for e in epics) or 'not in the graph'}; "
428
+ f"specification {', '.join(f'`{s}`' for s in specs) or 'not in the graph'}")
429
+ if not tickets:
430
+ out.append("- none in the graph")
431
+ out += ["", "## Coverage", "Links come from the ticket's own Trace table as the graph extracted it; 'not in the graph' means "
432
+ "the link was not extracted, not that it does not exist: read the ticket file for it."]
433
+ return "\n".join(out + ["", HOW_TO_USE])
434
+
435
+
436
+ HOW_TO_USE = ("---\nThis pack was extracted from the source by the dev-process graph; each item carries the line that proves it. "
437
+ "Treat it as the answer: re-read a file only if it is listed as changed, and search only where Coverage says the "
438
+ "answer is incomplete.")
439
+
440
+
441
+ def main() -> int:
442
+ ap = argparse.ArgumentParser(description="write a predefined graph pack")
443
+ ap.add_argument("--project", required=True)
444
+ ap.add_argument("kind", choices=("file", "error", "change", "refactor", "ticket", "pr"))
445
+ ap.add_argument("subject", nargs="+")
446
+ ap.add_argument("--role", default="")
447
+ ap.add_argument("--path", default="")
448
+ ns = ap.parse_args()
449
+ try:
450
+ p = Packer(ProcessAPI(ns.project, telemetry=False))
451
+ except GraphNotBuilt as e:
452
+ print(f"devkb pack: {e}", file=sys.stderr)
453
+ return 2
454
+ subject = " ".join(ns.subject)
455
+ print({"file": lambda: p.file(subject), "error": lambda: p.error(subject), "change": lambda: p.change(subject, ns.path),
456
+ "refactor": lambda: p.refactor(subject, ns.role, ns.path), "ticket": lambda: p.ticket(subject),
457
+ "pr": lambda: p.pr(subject)}[ns.kind]())
458
+ return 0
459
+
460
+
461
+ if __name__ == "__main__":
462
+ sys.exit(main())