ctxloop 0.3.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.
graphsnip/engine.py ADDED
@@ -0,0 +1,576 @@
1
+ """Engine: the tools an agent (or a human) calls. Every call is priced against
2
+ the honest baseline and written to the ledger."""
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import math
7
+ import re
8
+ import uuid
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ from graphsnip import ledger as _ledger
13
+ from graphsnip import semantic
14
+ from graphsnip.baseline import Baseline, query_terms
15
+ from graphsnip.project import CODE_EXTS, GraphError, Project, parse_line
16
+ from graphsnip.slicer import shorten_docstring, signature, slice_symbol
17
+ from graphsnip.tokens import count_tokens
18
+
19
+ _FENCE = {".py": "python", ".pyi": "python", ".js": "javascript", ".jsx": "jsx", ".mjs": "javascript",
20
+ ".ts": "typescript", ".tsx": "tsx", ".go": "go", ".rs": "rust", ".java": "java", ".c": "c",
21
+ ".h": "c", ".cpp": "cpp", ".cc": "cpp", ".hpp": "cpp", ".rb": "ruby", ".cs": "csharp",
22
+ ".kt": "kotlin", ".php": "php", ".swift": "swift", ".lua": "lua", ".sh": "bash", ".vue": "vue",
23
+ ".svelte": "svelte"}
24
+ _OUT_REL = ("calls", "indirect_call", "uses", "inherits", "extends", "implements")
25
+ _IN_REL = ("calls", "indirect_call", "references", "uses")
26
+ _REL_W = {"calls": 0.6, "indirect_call": 0.4, "method": 0.7, "inherits": 0.6, "extends": 0.6,
27
+ "implements": 0.5, "uses": 0.4, "references": 0.3, "contains": 0.25, "imports_from": 0.15}
28
+
29
+
30
+ @dataclass
31
+ class Result:
32
+ text: str
33
+ returned: int
34
+ baseline: int = 0
35
+ files: list = field(default_factory=list)
36
+ ok: bool = True
37
+ deduped: bool = False
38
+
39
+ @property
40
+ def saved(self) -> int:
41
+ return self.baseline - self.returned
42
+
43
+
44
+ class Engine:
45
+ def __init__(self, root=".", session: str | None = None, source: str = "cli", auto_refresh: bool = True,
46
+ background: bool = False):
47
+ self.p = Project(root)
48
+ self.ledger = _ledger.Ledger(self.p.gs_dir)
49
+ self.base = Baseline(self.p)
50
+ self.session = session or uuid.uuid4().hex[:8]
51
+ self.source = source
52
+ self.auto_refresh = auto_refresh
53
+ self.background = background # long-lived servers refresh the graph without blocking the query
54
+ self._seen: dict[tuple, str] = {}
55
+ self.last_retrieval = "keyword"
56
+
57
+ # ------------------------------------------------------------ plumbing
58
+ def _graph(self):
59
+ self.p.ensure_graph(self.auto_refresh, background=self.background)
60
+ return self.p.graph()
61
+
62
+ def _finish(self, tool: str, query: str, text: str, baseline: int, files: list[str],
63
+ ok: bool = True, deduped: bool = False) -> Result:
64
+ if ok and self.background and self.p.refreshing():
65
+ text = text.rstrip() + "\n\n(the graph is refreshing in the background; this answer uses the previous snapshot)"
66
+ ret = count_tokens(text)
67
+ if ok:
68
+ self.ledger.record(kind="call", tool=tool, query=query[:200], returned=ret, baseline=baseline,
69
+ files=files[:12], source=self.source, session=self.session, deduped=deduped)
70
+ return Result(text=text, returned=ret, baseline=baseline, files=files, ok=ok, deduped=deduped)
71
+
72
+ def _fail(self, text: str) -> Result:
73
+ return Result(text=text, returned=count_tokens(text), ok=False)
74
+
75
+ def _src(self, rel: str, cache: dict) -> str:
76
+ if rel not in cache:
77
+ cache[rel] = self.p.read(rel) or ""
78
+ return cache[rel]
79
+
80
+ def _display(self, G, nid: str) -> str:
81
+ return self.p.display(nid)
82
+
83
+ def _kind(self, d: dict) -> str:
84
+ return "class" if d.get("_callable_class") else "function"
85
+
86
+ # ------------------------------------------------------------ find
87
+ def find(self, question: str, budget: int = 1500, depth: int = 2) -> Result:
88
+ try:
89
+ G = self._graph()
90
+ from graphify.serve import _query_graph_text
91
+
92
+ self.last_retrieval = "keyword"
93
+ q = question
94
+ sem = semantic.search(self.p, question, k=3) if semantic.has_index(self.p) else []
95
+ if sem:
96
+ q = question + " " + " ".join(re.sub(r"\(\)\s*$", "", str(G.nodes[n].get("label", ""))).strip(". ") for n, _s in sem)
97
+ self.last_retrieval = "hybrid"
98
+ text = _query_graph_text(G, q, mode="bfs", depth=depth, token_budget=budget,
99
+ graph_path=str(self.p.graph_json))
100
+ except GraphError as e:
101
+ return self._fail(str(e))
102
+ except Exception as e: # graphify internals can change between versions
103
+ return self._fail(f"find failed: {type(e).__name__}: {e}")
104
+ if text.startswith("No matching nodes"):
105
+ return self._fail(text + " Try other keywords, or fall back to grep.")
106
+ text = text.rstrip() + "\n\n→ gs_symbol(name) returns exact code; gs_pack(task) returns a ready code bundle."
107
+ base, files = self.base.grep_read(query_terms(question))
108
+ return self._finish("find", question, text, base, files)
109
+
110
+ # ------------------------------------------------------------ symbol
111
+ def _neighbors(self, G, nid: str) -> tuple[list[str], list[str], list[str]]:
112
+ def lab(n):
113
+ return str(G.nodes[n].get("label", n))
114
+
115
+ outs, ins, members = [], [], []
116
+ try:
117
+ for _u, v, d in G.out_edges(nid, data=True):
118
+ r = d.get("relation")
119
+ if r in _OUT_REL:
120
+ outs.append(lab(v))
121
+ elif r == "method":
122
+ members.append(lab(v))
123
+ for u, _v, d in G.in_edges(nid, data=True):
124
+ if d.get("relation") in _IN_REL:
125
+ ins.append(lab(u))
126
+ except Exception:
127
+ pass
128
+
129
+ def uniq(xs):
130
+ seen, out = set(), []
131
+ for x in xs:
132
+ if x not in seen and x:
133
+ seen.add(x)
134
+ out.append(x)
135
+ return out
136
+
137
+ return uniq(outs), uniq(ins), uniq(members)
138
+
139
+ @staticmethod
140
+ def _short(names: list[str], cap: int) -> str:
141
+ if not names:
142
+ return "-"
143
+ shown = ", ".join(names[:cap])
144
+ return shown + (f" (+{len(names) - cap})" if len(names) > cap else "")
145
+
146
+ def symbol(self, name: str, max_lines: int = 120, docs: str = "short") -> Result:
147
+ try:
148
+ G = self._graph()
149
+ from graphify.serve import _resolve_single_node
150
+
151
+ nid, err = _resolve_single_node(G, name)
152
+ except GraphError as e:
153
+ return self._fail(str(e))
154
+ except Exception as e:
155
+ return self._fail(f"symbol lookup failed: {type(e).__name__}: {e}")
156
+ if err:
157
+ return self._fail(err)
158
+ d = G.nodes[nid]
159
+ rel = str(d.get("source_file", ""))
160
+ if self.p.is_file_node(d):
161
+ r = self.outline(rel)
162
+ r.text = f"('{name}' is a file; showing its outline.)\n" + r.text
163
+ return r
164
+ line = parse_line(d.get("source_location")) or 1
165
+ src = self.p.read(rel)
166
+ if src is None:
167
+ return self._fail(f"Could not read {rel}.")
168
+ suffix = Path(rel).suffix
169
+ sl = slice_symbol(src, suffix, line, max_lines=max_lines)
170
+ outs, ins, members = self._neighbors(G, nid)
171
+ label = self._display(G, nid)
172
+ shown_text, omitted = (shorten_docstring(sl.text, suffix) if docs != "full" else (sl.text, 0))
173
+ head = f"## {label} ({self._kind(d)}) — {rel}:{sl.start}-{sl.end}"
174
+ if sl.truncated:
175
+ head += f" [showing {max_lines} of {sl.total_lines} lines]"
176
+ lang = _FENCE.get(suffix.lower(), "")
177
+ body = f"```{lang}\n{shown_text}\n```"
178
+ nav = []
179
+ if members:
180
+ nav.append(f"methods: {self._short(members, 12)}")
181
+ nav.append(f"calls/uses: {self._short(outs, 8)}")
182
+ nav.append(f"used by: {self._short(ins, 8)}")
183
+ if sl.truncated:
184
+ nav.append(f"… +{sl.total_lines - max_lines} more lines — call again with max_lines={sl.total_lines}")
185
+ full = "\n".join([head, body, *nav])
186
+
187
+ file_tokens = self.base.file_tokens(rel) # what Read(file) would have cost
188
+ key = (rel, sl.start, sl.end)
189
+ digest = hashlib.sha1(shown_text.encode("utf-8", "replace")).hexdigest() # what the agent was actually shown
190
+ if self._seen.get(key) == digest:
191
+ short = (f"✓ {label} ({rel}:{sl.start}-{sl.end}) was already returned earlier in this session "
192
+ f"and is unchanged. Reuse that code.")
193
+ if count_tokens(short) < 0.6 * count_tokens(full): # a pointer must actually be cheaper than the code
194
+ return self._finish("symbol", name, short, file_tokens, [rel], deduped=True)
195
+ self._seen[key] = digest
196
+ return self._finish("symbol", name, full, file_tokens, [rel])
197
+
198
+ # ------------------------------------------------------------ pack
199
+ _TEST_RE = None
200
+
201
+ def _is_test_path(self, rel: str) -> bool:
202
+ import re
203
+
204
+ if Engine._TEST_RE is None:
205
+ Engine._TEST_RE = re.compile(r"(^|/)(tests?|__tests__|specs?|e2e)(/|$)|(^|/)test_|_test\.|\.test\.|\.spec\.")
206
+ return bool(Engine._TEST_RE.search(rel))
207
+
208
+ def _class_skeleton(self, G, nid: str, src: str, suffix: str, line: int, sl, max_methods: int = 30) -> str:
209
+ """For a big class: header + short docstring + one signature line per method."""
210
+ head_text, _ = shorten_docstring(slice_symbol(src, suffix, line, max_lines=14).text, suffix, min_lines=5)
211
+ head = "\n".join(head_text.split("\n")[:8])
212
+ rows = []
213
+ try:
214
+ for _u, v, d in G.out_edges(nid, data=True):
215
+ if d.get("relation") == "method" and v in G:
216
+ ln = parse_line(G.nodes[v].get("source_location"))
217
+ if ln:
218
+ rows.append((ln, v))
219
+ except Exception:
220
+ pass
221
+ rows.sort()
222
+ out = [head, f" # ... class body is {sl.total_lines} lines; {len(rows)} methods. Signatures:"]
223
+ for ln, _v in rows[:max_methods]:
224
+ out.append(signature(src, suffix, ln, max_lines=2).split("\n")[0].rstrip())
225
+ if len(rows) > max_methods:
226
+ out.append(f" # ... +{len(rows) - max_methods} more methods")
227
+ return "\n".join(out)
228
+
229
+ def pack(self, task: str, budget: int = 4000) -> Result:
230
+ import re
231
+
232
+ try:
233
+ G = self._graph()
234
+ from graphify.serve import _pick_seeds, _query_terms, _score_query
235
+
236
+ terms = _query_terms(task)
237
+ qs = _score_query(G, terms, collect_per_term_seeds=True)
238
+ seeds = _pick_seeds(qs.ranked, max_k=4, G=G, best_seed_by_term=qs.best_seed_by_term,
239
+ term_order=tuple(terms))
240
+ sem_raw = semantic.search(self.p, task, k=20) if semantic.has_index(self.p) else []
241
+ except GraphError as e:
242
+ return self._fail(str(e))
243
+ except Exception as e:
244
+ return self._fail(f"pack failed: {type(e).__name__}: {e}")
245
+ self.last_retrieval = "hybrid" if sem_raw else "keyword"
246
+ if not seeds and not qs.ranked and not sem_raw:
247
+ return self._fail("No symbols matched this task. Try different keywords, or fall back to grep.")
248
+
249
+ def deg(n):
250
+ try:
251
+ return G.degree(n)
252
+ except Exception:
253
+ return 0
254
+
255
+ def is_sym(n):
256
+ d = G.nodes[n]
257
+ return (d.get("file_type") == "code" and parse_line(d.get("source_location")) is not None
258
+ and d.get("source_file") and Path(str(d.get("source_file"))).suffix.lower() in CODE_EXTS
259
+ and not self.p.is_file_node(d))
260
+
261
+ def resolve(n):
262
+ """Rationale/docstring nodes point at the symbol they describe."""
263
+ if n not in G:
264
+ return []
265
+ d = G.nodes[n]
266
+ if d.get("file_type") == "rationale":
267
+ try:
268
+ return [v for _u, v, dd in G.out_edges(n, data=True) if dd.get("relation") == "rationale_for" and v in G]
269
+ except Exception:
270
+ return []
271
+ return [n]
272
+
273
+ cand: dict[str, float] = {}
274
+ seed_syms: list[str] = []
275
+ for i, s in enumerate(seeds):
276
+ w = 1.0 / (1.0 + 0.25 * i)
277
+ for n in resolve(s):
278
+ if is_sym(n):
279
+ seed_syms.append(n)
280
+ cand[n] = max(cand.get(n, 0), w)
281
+ elif G.nodes[n].get("file_type") == "code" and G.nodes[n].get("source_file"):
282
+ sf = G.nodes[n].get("source_file")
283
+ inside = [m for m, dd in self.p.symbol_nodes() if dd.get("source_file") == sf]
284
+ inside.sort(key=lambda m: -deg(m))
285
+ for m in inside[:6]:
286
+ seed_syms.append(m)
287
+ cand[m] = max(cand.get(m, 0), w * 0.8)
288
+ # direct lexical hits from Graphify's ranking, so a strong name match is never lost to graph proximity
289
+ rank_i = 0
290
+ for _score, n in qs.ranked[:40]:
291
+ for m in resolve(n):
292
+ if is_sym(m):
293
+ cand[m] = max(cand.get(m, 0), 0.9 / (1.0 + 0.12 * rank_i))
294
+ rank_i += 1
295
+
296
+ sem_rank: dict[str, int] = {}
297
+ if sem_raw:
298
+ sem_ids = []
299
+ for n, _sc in sem_raw:
300
+ for m in resolve(n):
301
+ if is_sym(m) and m not in sem_ids:
302
+ sem_ids.append(m)
303
+ lex_ids: list[str] = []
304
+ for _score, n in qs.ranked[:40]:
305
+ for m in resolve(n):
306
+ if is_sym(m) and m not in lex_ids:
307
+ lex_ids.append(m)
308
+ for i, (n, _sc) in enumerate(semantic.rrf(lex_ids, sem_ids)[:30]):
309
+ cand[n] = max(cand.get(n, 0), 0.9 / (1.0 + 0.12 * i))
310
+ if i < 4:
311
+ seed_syms.append(n)
312
+ for i, n in enumerate(sem_ids[:8]):
313
+ sem_rank[n] = i
314
+
315
+ def expand(n: str, w: float, hop: int):
316
+ edges = []
317
+ try:
318
+ edges += [(v, d.get("relation")) for _u, v, d in G.out_edges(n, data=True)]
319
+ edges += [(u, d.get("relation")) for u, _v, d in G.in_edges(n, data=True)]
320
+ except Exception:
321
+ return
322
+ for m, rel in edges:
323
+ rw = _REL_W.get(rel)
324
+ if rw is None or m not in G or not is_sym(m):
325
+ continue
326
+ nw = w * rw / (1.0 + 0.35 * math.log2(1 + deg(m)))
327
+ if nw > cand.get(m, 0):
328
+ cand[m] = nw
329
+ if hop == 1 and rel in ("calls", "method"):
330
+ expand(m, nw * 0.5, 2)
331
+
332
+ for s in list(dict.fromkeys(seed_syms)):
333
+ expand(s, cand[s], 1)
334
+
335
+ # relevance re-ranking: boost labels that contain query words, demote tests
336
+ def stem(w: str) -> str:
337
+ w = w.lower()
338
+ if w.startswith("error") or w.startswith("exception") or w == "fail" or w == "failure":
339
+ return "exception"
340
+ for suf in ("ing", "ed", "es", "s"):
341
+ if w.endswith(suf) and len(w) - len(suf) >= 4:
342
+ return w[: -len(suf)]
343
+ return w
344
+
345
+ tq = [stem(t) for t in query_terms(task) if len(t) >= 3]
346
+ wants_tests = any(t.startswith("test") for t in tq)
347
+ final: dict[str, float] = {}
348
+ for n, w in cand.items():
349
+ d = G.nodes[n]
350
+ raw = str(d.get("label", "")).replace("_", " ")
351
+ toks = [stem(x) for x in re.findall(r"[A-Z]+(?![a-z])|[A-Z]?[a-z0-9]+", raw)]
352
+ hit = 0.0
353
+ for t in tq:
354
+ if t in toks:
355
+ hit += 1.0
356
+ elif any(len(t) >= 5 and (tok.startswith(t[:5]) or t.startswith(tok)) and len(tok) >= 5 for tok in toks):
357
+ hit += 0.5
358
+ boost = 1.0 + 2.0 * (hit / max(len(tq), 1))
359
+ if n in sem_rank: # a close semantic match counts even when no word of the question appears in the name
360
+ boost *= 1.0 + 1.5 / (1.0 + sem_rank[n])
361
+ pen = 0.35 if (not wants_tests and self._is_test_path(str(d.get("source_file")))) else 1.0
362
+ final[n] = w * boost * pen
363
+ ordered = sorted(final, key=lambda n: -final[n])[:60]
364
+ n_core = 3
365
+ core_ids = set(ordered[:n_core])
366
+
367
+ used = 0
368
+ full_budget = int(budget * 0.9)
369
+ core: list[str] = []
370
+ support: list[str] = []
371
+ sigs: list[str] = []
372
+ related: list[str] = []
373
+ files: list[str] = []
374
+ cache: dict[str, str] = {}
375
+ n_full = 0
376
+ for idx, n in enumerate(ordered):
377
+ d = G.nodes[n]
378
+ rel = str(d.get("source_file"))
379
+ line = parse_line(d.get("source_location")) or 1
380
+ src = self._src(rel, cache)
381
+ if not src:
382
+ continue
383
+ suffix = Path(rel).suffix
384
+ is_core = n in core_ids
385
+ sl = slice_symbol(src, suffix, line, max_lines=110 if is_core else 60)
386
+ label = self._display(G, n)
387
+ lang = _FENCE.get(suffix.lower(), "")
388
+ is_big_class = bool(d.get("_callable_class")) and sl.total_lines > 60
389
+ if is_big_class:
390
+ body_text = self._class_skeleton(G, n, src, suffix, line, sl)
391
+ head = f"### {label} — {rel}:{line}-{line + sl.total_lines - 1} [class skeleton]"
392
+ else:
393
+ body_text = shorten_docstring(sl.text, suffix)[0]
394
+ head = f"### {label} — {rel}:{sl.start}-{sl.end}" + (" [truncated]" if sl.truncated else "")
395
+ block = f"{head}\n```{lang}\n{body_text}\n```"
396
+ t = count_tokens(block)
397
+ if idx == 0 and t > full_budget: # the top hit always goes in, trimmed to fit
398
+ keep = max(12, int(sl.total_lines * full_budget / max(t, 1)))
399
+ sl = slice_symbol(src, suffix, line, max_lines=keep)
400
+ block = f"### {label} — {rel}:{sl.start}-{sl.end} [truncated to fit budget]\n```{lang}\n{shorten_docstring(sl.text, suffix)[0]}\n```"
401
+ t = count_tokens(block)
402
+ if used + t <= full_budget:
403
+ (core if is_core else support).append(block)
404
+ used += t
405
+ n_full += 1
406
+ if rel not in files:
407
+ files.append(rel)
408
+ continue
409
+ sig = signature(src, suffix, line)
410
+ sig_line = f"- `{label}` — {rel}:{line}\n ```{lang}\n " + sig.replace("\n", "\n ") + "\n ```"
411
+ st = count_tokens(sig_line)
412
+ if used + st <= budget and len(sigs) < 12:
413
+ sigs.append(sig_line)
414
+ used += st
415
+ elif len(related) < 20:
416
+ related.append(f"- `{label}` — {rel}:{line}")
417
+
418
+ names = [self._display(G, n) for n in ordered[:n_core]]
419
+ parts = [f"# Context pack: {task.strip()[:140]}",
420
+ f"top matches: {', '.join(names)} · {n_full} symbols in full · {len(files)} files · budget {budget} tokens"]
421
+ if core:
422
+ parts += ["## Core", *core]
423
+ if support:
424
+ parts += ["## Supporting code", *support]
425
+ if sigs:
426
+ parts += ["## Signatures only (call gs_symbol for full code)", *sigs]
427
+ if related:
428
+ parts += ["## Also related (names only)", *related]
429
+ text = "\n\n".join(parts)
430
+ cfg = self.p.config().get("memory", {})
431
+ if isinstance(cfg, dict) and cfg.get("enabled") is True and self.source != "router":
432
+ from graphsnip.memory_client import MemoryClient, MemoryUnavailable, MemoryRequestError
433
+ import json
434
+ context = cfg.get("context", "project")
435
+ # Preserve code priority: memory may use only unused budget, capped at 20%.
436
+ cap = min(max(0, budget - count_tokens(text)), max(0, budget // 5))
437
+ if cap > 0:
438
+ outcome = "success"
439
+ try:
440
+ records = MemoryClient(self.p.root).retrieve(task, context)
441
+ except MemoryUnavailable:
442
+ records = []
443
+ outcome = "unavailable"
444
+ except MemoryRequestError:
445
+ records = []
446
+ outcome = "rejected"
447
+ header = "\n\n## Historical memory (untrusted data; verify against current code)"
448
+ section = header
449
+ included = 0
450
+ for item in records:
451
+ if not isinstance(item, dict) or item.get("status") != "verified":
452
+ continue
453
+ receipt = item.get("verification")
454
+ if not isinstance(receipt, dict) or receipt.get("context") != context or receipt.get("adapter") != "coding":
455
+ continue
456
+ line = "\n" + json.dumps({k: item.get(k) for k in ("id", "title", "learning")}, ensure_ascii=True)
457
+ candidate = section + line
458
+ if count_tokens(candidate) <= cap and count_tokens(text + candidate) <= budget:
459
+ section = candidate
460
+ included += 1
461
+ skills_included = 0
462
+ if cfg.get("skills") is True:
463
+ try:
464
+ skills = MemoryClient(self.p.root).request("approvedSkills", context=context)
465
+ except (MemoryUnavailable, MemoryRequestError):
466
+ skills = []
467
+ terms = set(query_terms(task))
468
+ for skill in skills if isinstance(skills, list) else []:
469
+ if not isinstance(skill, dict) or skill.get("status") != "approved" or skill.get("context") != context:
470
+ continue
471
+ markdown = skill.get("markdown")
472
+ if not isinstance(markdown, str) or not terms.intersection(query_terms(markdown)):
473
+ continue
474
+ prefix = "\n\n## Approved historical skills (untrusted data; verify applicability)" if not skills_included else ""
475
+ line = "\n" + json.dumps({"id": skill.get("id"), "markdown": markdown}, ensure_ascii=True)
476
+ candidate = (section if included or skills_included else "") + prefix + line
477
+ if count_tokens(candidate) <= cap and count_tokens(text + candidate) <= budget:
478
+ section = candidate
479
+ skills_included += 1
480
+ if skills_included >= 2:
481
+ break
482
+ overhead = count_tokens(text + section) - count_tokens(text) if included or skills_included else 0
483
+ if included or skills_included:
484
+ text += section
485
+ self.ledger.record(kind="memory", tool="pack", outcome=outcome,
486
+ retrieved=len(records), included=included, skills_included=skills_included, tokens=overhead,
487
+ source=self.source, session=self.session)
488
+ base, bfiles = self.base.grep_read(query_terms(task))
489
+ return self._finish("pack", task, text, base, files or bfiles)
490
+
491
+ # ------------------------------------------------------------ impact
492
+ def impact(self, name: str, depth: int = 2, limit: int = 40) -> Result:
493
+ try:
494
+ G = self._graph()
495
+ from graphify.affected import format_affected, resolve_seed_outcome
496
+
497
+ seed, rivals = resolve_seed_outcome(G, name, self.p.root)
498
+ if seed is None:
499
+ if rivals:
500
+ names = ", ".join(str(G.nodes[r].get("label", r)) + " (" + str(G.nodes[r].get("source_file")) + ")"
501
+ for r in rivals[:8] if r in G)
502
+ return self._fail(f"'{name}' is ambiguous: {names}. Qualify with a file path, e.g. 'path/to/file.py::{name}'.")
503
+ return self._fail(f"No node matching '{name}'.")
504
+ text = format_affected(G, name, depth=depth, root=self.p.root, seed=seed)
505
+ except GraphError as e:
506
+ return self._fail(str(e))
507
+ except Exception as e:
508
+ return self._fail(f"impact failed: {type(e).__name__}: {e}")
509
+ lines = text.splitlines()
510
+ if len(lines) > limit + 3:
511
+ text = "\n".join(lines[: limit + 3] + [f"… +{len(lines) - limit - 3} more affected nodes (raise depth/limit or narrow the name)"])
512
+ base, files = self.base.symbol_name_files(name)
513
+ return self._finish("impact", name, text, base, files)
514
+
515
+ # ------------------------------------------------------------ outline
516
+ def outline(self, path: str, limit: int = 200) -> Result:
517
+ try:
518
+ G = self._graph()
519
+ except GraphError as e:
520
+ return self._fail(str(e))
521
+ rel = self.p.rel(self.p.root / path) if not Path(path).is_absolute() else self.p.rel(path)
522
+ rows = []
523
+ for nid, d in self.p.symbol_nodes():
524
+ if str(d.get("source_file")) == rel:
525
+ rows.append((parse_line(d.get("source_location")) or 0, str(d.get("label")), self._kind(d)))
526
+ if not rows:
527
+ return self._fail(f"No indexed symbols in '{path}'. It may be unsupported, ignored, or newer than the graph.")
528
+ rows.sort()
529
+ lines = [f"## {rel} — {len(rows)} symbols (from the Graphify graph)"]
530
+ for ln, lab, kind in rows[:limit]:
531
+ lines.append(f"L{ln:<5} {lab}{' [class]' if kind == 'class' else ''}")
532
+ if len(rows) > limit:
533
+ lines.append(f"… +{len(rows) - limit} more")
534
+ lines.append("→ gs_symbol(name) for the code, or Read with offset/limit around a line.")
535
+ return self._finish("outline", path, "\n".join(lines), self.base.file_tokens(rel), [rel])
536
+
537
+ # ------------------------------------------------------------ savings
538
+ def route(self, task: str, client: str = "claude", running_tier: str | None = None, handoff: bool = False) -> Result:
539
+ """Pick a model tier for the task, log the decision, and say what to do about it."""
540
+ from graphsnip import router
541
+
542
+ cfg = router.config(self.p)
543
+ sizing = Engine(self.p.root, session=self.session, source="router", auto_refresh=False).pack(task, budget=4000)
544
+ r = router.decide(task, pack_files=len(sizing.files) if sizing.ok else 0,
545
+ pack_tokens=sizing.returned if sizing.ok else 0, cfg=cfg)
546
+ if running_tier == "auto": # graphsnip itself launches the agent on the chosen tier, so the match is certain
547
+ running_tier = r.tier
548
+ status = router.status_of(r.tier, running_tier)
549
+ acct = router.account(cfg, r, status)
550
+ model = (cfg["models"].get(client) or {}).get(r.tier)
551
+ self.ledger.record(kind="route", tool="gs_route", query=task[:200], tier=r.tier, score=r.score, status=status,
552
+ client=client, running=running_tier, model=model, tokens_in=r.tokens_in,
553
+ tokens_out=r.tokens_out, reasons=r.reasons, handoff=handoff, source=self.source, session=self.session, **acct)
554
+ lines = [f"route: {r.tier} (score {r.score})" + (f" -> {model}" if model else ""), "why: " + "; ".join(r.reasons)]
555
+ if status == "escalate":
556
+ lines.append(f"ESCALATE to {r.tier}" + (f" ({model})" if model else "")
557
+ + f": this task needs a stronger model than the {running_tier} one you are running on.")
558
+ elif status == "overpowered":
559
+ lines.append(f"note: a {r.tier} tier model would be enough; the user is running {running_tier}.")
560
+ elif status == "routed":
561
+ lines.append("ok: the running model matches; continue.")
562
+ else:
563
+ lines.append("advisory only: nothing verified which model is running.")
564
+ text = "\n".join(lines)
565
+ return Result(text=text, returned=count_tokens(text))
566
+
567
+ def savings(self) -> Result:
568
+ recs = self.ledger.read()
569
+ s = _ledger.summarize(recs, self.p.config().get("price_per_mtok", 3.0), sources={"agent", "cli", "shell"})
570
+ if not s["calls"]:
571
+ return self._fail("No calls recorded yet.")
572
+ lines = [f"graphsnip savings: {s['calls']} calls · returned {s['returned']:,} tokens vs {s['baseline']:,} "
573
+ f"for grep+read (baseline) → saved {s['saved']:,} tokens ({s['pct']}%), ≈ ${s['usd_saved']}."]
574
+ for tool, t in sorted(s["by_tool"].items(), key=lambda kv: -(kv[1]["baseline"] - kv[1]["returned"])):
575
+ lines.append(f" {tool:<8} {t['calls']:>3} calls · {t['returned']:>7,} vs {t['baseline']:>8,} tokens")
576
+ return Result(text="\n".join(lines), returned=count_tokens("\n".join(lines)))