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/router.py ADDED
@@ -0,0 +1,175 @@
1
+ """Model routing: pick the cheapest model tier that can handle a task, and account for it honestly.
2
+
3
+ graphsnip cannot switch a host agent's model by itself (MCP servers have no such power). What it can do:
4
+ 1. decide - score a task from its wording and from graph signals (files and tokens a context pack needs)
5
+ 2. steer - ship a /graphsnip command pinned to the light model and a /graphsnip-deep command for the rest
6
+ 3. account - log every decision, whether the running model matched it, and the estimated dollars
7
+
8
+ Dollars are an estimate from the price table in .graphsnip/config.json ("routing.prices"); the defaults are
9
+ placeholders you should edit. Savings are credited only when the running tier matched the decision.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from dataclasses import dataclass, field
15
+
16
+ TIERS = ("light", "standard", "heavy")
17
+ _RANK = {t: i for i, t in enumerate(TIERS)}
18
+
19
+ DEFAULTS = {
20
+ "baseline_tier": "standard", # what you would run without routing
21
+ "prices": {"light": [1.0, 5.0], "standard": [3.0, 15.0], "heavy": [5.0, 25.0]}, # USD per million tokens [input, output]
22
+ "models": {"claude": {"light": "haiku", "standard": "sonnet", "heavy": "opus"}, "copilot": {}, "codex": {}},
23
+ "answer_tokens": 700, # assumed output tokens per routed task
24
+ "overhead_tokens": 500, # assumed prompt/system tokens per routed task
25
+ }
26
+
27
+ _HEAVY = re.compile(r"\b(refactor\w*|migrat\w*|redesign\w*|rewrit\w*|re-?architect\w*|implement\w*|debug\w*|race condition|"
28
+ r"deadlock|security|vulnerab\w*|performance|optimi[sz]\w*|memory leak|concurren\w*|fix (the |this )?bug|"
29
+ r"add (a |an )?(new )?(feature|endpoint|module))\b", re.I)
30
+ _LIGHT = re.compile(r"\b(where|which file|find|locate|list|show|who calls|what calls|outline|summari[sz]e|explain|what is|"
31
+ r"what does|how does|defined|used)\b", re.I)
32
+ _MULTI = re.compile(r"(\band then\b|;|\n\s*\d+[.)])", re.I)
33
+
34
+
35
+ def config(project) -> dict:
36
+ user = (project.config().get("routing") or {})
37
+ cfg = {k: (dict(v) if isinstance(v, dict) else v) for k, v in DEFAULTS.items()}
38
+ for k, v in user.items():
39
+ if isinstance(v, dict) and isinstance(cfg.get(k), dict):
40
+ cfg[k].update(v)
41
+ else:
42
+ cfg[k] = v
43
+ return cfg
44
+
45
+
46
+ def cost(cfg: dict, tier: str, tokens_in: int, tokens_out: int) -> float:
47
+ pin, pout = cfg["prices"].get(tier, cfg["prices"][cfg["baseline_tier"]])
48
+ return (tokens_in * pin + tokens_out * pout) / 1_000_000
49
+
50
+
51
+ @dataclass
52
+ class Route:
53
+ tier: str
54
+ score: int
55
+ reasons: list = field(default_factory=list)
56
+ tokens_in: int = 0
57
+ tokens_out: int = 0
58
+ files: int = 0
59
+
60
+
61
+ def decide(task: str, pack_files: int = 0, pack_tokens: int = 0, pack_budget: int = 4000, cfg: dict | None = None) -> Route:
62
+ score, why = 0, []
63
+ lookup_only = not _HEAVY.search(task) and bool(_LIGHT.search(task))
64
+ if _HEAVY.search(task):
65
+ score += 3
66
+ why.append(f"change/diagnosis wording ('{_HEAVY.search(task).group(0).lower()}') +3")
67
+ elif _LIGHT.search(task):
68
+ score -= 2
69
+ why.append(f"lookup/explain wording ('{_LIGHT.search(task).group(0).lower()}') -2")
70
+ if _MULTI.search(task):
71
+ score += 1
72
+ why.append("several steps in one request +1")
73
+ if len(task.split()) > 40:
74
+ score += 1
75
+ why.append("long request +1")
76
+ gpts, gwhy = 0, []
77
+ if pack_files >= 6:
78
+ gpts += 2
79
+ gwhy.append(f"graph: {pack_files} files involved +2")
80
+ elif pack_files >= 3:
81
+ gpts += 1
82
+ gwhy.append(f"graph: {pack_files} files involved +1")
83
+ if pack_tokens >= 0.8 * pack_budget:
84
+ gpts += 1
85
+ gwhy.append(f"graph: large context needed ({pack_tokens:,} tokens) +1")
86
+ if lookup_only and gpts > 1:
87
+ # a "where/find/explain" question naturally touches many files; that alone does not make it hard
88
+ gwhy.append(f"graph size capped at +1 for a lookup question (was +{gpts})")
89
+ gpts = 1
90
+ score += gpts
91
+ why += gwhy
92
+ tier = "light" if score <= 0 else "heavy" if score >= 4 else "standard"
93
+ cfg = cfg or DEFAULTS
94
+ return Route(tier=tier, score=score, reasons=why or ["no strong signal"], files=pack_files,
95
+ tokens_in=pack_tokens + cfg["overhead_tokens"], tokens_out=cfg["answer_tokens"])
96
+
97
+
98
+ def status_of(decided: str, running: str | None) -> str:
99
+ if running is None:
100
+ return "advisory" # decision made, nobody verified which model ran
101
+ if running == "session":
102
+ return "session" # ran on whatever the session uses; no routing claimed
103
+ if running not in _RANK:
104
+ return "advisory"
105
+ if running == decided:
106
+ return "routed"
107
+ return "escalate" if _RANK[running] < _RANK[decided] else "overpowered"
108
+
109
+
110
+ def account(cfg: dict, route: Route, status: str) -> dict:
111
+ base = cost(cfg, cfg["baseline_tier"], route.tokens_in, route.tokens_out)
112
+ chosen = cost(cfg, route.tier, route.tokens_in, route.tokens_out)
113
+ delta = round(base - chosen, 6) # negative when the task needed a pricier model than the baseline
114
+ return {"usd_baseline": round(base, 6), "usd_routed": round(chosen, 6),
115
+ "usd_saved": delta if status == "routed" else 0.0,
116
+ "usd_potential": delta if status in ("advisory", "session") else 0.0}
117
+
118
+
119
+ def summarize(records: list[dict], cfg: dict) -> dict:
120
+ allrows = [r for r in records if r.get("kind") == "route"]
121
+ rows = [r for r in allrows if not r.get("handoff")] # a handoff row only logs where an escalated task ran
122
+ handoffs = [r for r in allrows if r.get("handoff")]
123
+ by_tier = {t: 0 for t in TIERS}
124
+ by_status: dict[str, int] = {}
125
+ for r in rows:
126
+ by_tier[r.get("tier", "standard")] = by_tier.get(r.get("tier", "standard"), 0) + 1
127
+ by_status[r.get("status", "advisory")] = by_status.get(r.get("status", "advisory"), 0) + 1
128
+ routed = [r for r in allrows if r.get("status") == "routed"]
129
+ cheaper = [r for r in routed if _RANK.get(r["tier"], 1) < _RANK[cfg["baseline_tier"]]]
130
+ return {
131
+ "decisions": len(rows),
132
+ "by_tier": by_tier,
133
+ "by_status": by_status,
134
+ "routed": len(routed),
135
+ "routed_cheaper": len(cheaper),
136
+ "tokens_on_cheaper": sum(int(r.get("tokens_in", 0)) + int(r.get("tokens_out", 0)) for r in cheaper),
137
+ "usd_saved": round(sum(float(r.get("usd_saved", 0)) for r in routed), 4),
138
+ "usd_potential": round(sum(float(r.get("usd_potential", 0)) for r in rows if r.get("status") in ("advisory", "session")), 4),
139
+ "escalations": by_status.get("escalate", 0),
140
+ "handoffs": len(handoffs),
141
+ "recent": list(reversed(rows[-8:])),
142
+ }
143
+
144
+
145
+ def _m(cfg: dict, client: str, tier: str | None) -> str:
146
+ if not tier:
147
+ return "?"
148
+ name = (cfg["models"].get(client) or {}).get(tier)
149
+ return f"{tier} ({name})" if name else tier
150
+
151
+
152
+ def events(records: list[dict], cfg: dict, limit: int = 12) -> list[dict]:
153
+ """One row per routed task, in time order, describing what actually happened (switch, escalation, hand-off)."""
154
+ allrows = [r for r in records if r.get("kind") == "route"]
155
+ handoffs = [r for r in allrows if r.get("handoff")]
156
+ out = []
157
+ for r in allrows:
158
+ if r.get("handoff"):
159
+ continue
160
+ c, tier, run, st = r.get("client", "claude"), r.get("tier", "standard"), r.get("running"), r.get("status", "advisory")
161
+ if st == "routed":
162
+ path = f"ran on {_m(cfg, c, tier)}" + (" (graphsnip launched it)" if run == tier and c == "codex" else "")
163
+ elif st == "escalate":
164
+ h = next((x for x in handoffs if x.get("query") == r.get("query") and x.get("client") == c and x.get("ts", "") >= r.get("ts", "")), None)
165
+ path = f"started on {_m(cfg, c, run)} → too light → " + (f"handed off, finished on {_m(cfg, c, h.get('tier'))}" if h else "stopped, user had to re-run")
166
+ elif st == "session":
167
+ path = "ran on the session's own model (/graphsnip-deep)"
168
+ elif st == "overpowered":
169
+ path = f"ran on {_m(cfg, c, run)}; {tier} would have been enough"
170
+ else:
171
+ path = "decision only; which model ran was not verified"
172
+ out.append({"ts": r.get("ts", ""), "client": c, "query": r.get("query", ""), "tier": tier, "status": st,
173
+ "path": path, "saved": float(r.get("usd_saved", 0)) + sum(float(x.get("usd_saved", 0)) for x in handoffs
174
+ if st == "escalate" and x.get("query") == r.get("query"))})
175
+ return list(reversed(out))[:limit]
graphsnip/semantic.py ADDED
@@ -0,0 +1,335 @@
1
+ """Optional semantic layer: one vector per code symbol of the Graphify graph, stored beside the ledger.
2
+
3
+ Layout (all derived data, safe to delete, git-ignore it):
4
+ .graphsnip/semantic/vectors.npy one row per symbol (float16, L2-normalised)
5
+ .graphsnip/semantic/ids.json row -> graph node id, plus a hash of the text that was embedded
6
+ .graphsnip/semantic/meta.json model name, dimensions, version, build time
7
+
8
+ Nothing here is required: without the `semantic` extra or an index, retrieval is keyword-only exactly as before.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import json
14
+ import math
15
+ import os
16
+ import re
17
+ import sys
18
+ import time
19
+ from pathlib import Path
20
+
21
+ VERSION = 1
22
+ DEFAULT_MODEL = "BAAI/bge-small-en-v1.5"
23
+ BODY_LINES = 14
24
+ MAX_TEXT_CHARS = 1400
25
+ RRF_K = 60
26
+
27
+
28
+ class SemanticUnavailable(RuntimeError):
29
+ pass
30
+
31
+
32
+ # ------------------------------------------------------------------ text for one symbol
33
+ _SPLIT = re.compile(r"[A-Z]+(?![a-z])|[A-Z]?[a-z0-9]+")
34
+
35
+
36
+ def split_identifier(name: str) -> str:
37
+ return " ".join(w.lower() for w in _SPLIT.findall(name.replace("_", " ").replace("-", " ").replace(".", " ")))
38
+
39
+
40
+ def _labels(G, nodes) -> list[str]:
41
+ out, seen = [], set()
42
+ for n in nodes:
43
+ lab = re.sub(r"\(\)\s*$", "", str(G.nodes[n].get("label", ""))).strip(". ")
44
+ if lab and lab not in seen:
45
+ seen.add(lab)
46
+ out.append(lab)
47
+ return out
48
+
49
+
50
+ def node_text(project, G, nid: str, cache: dict) -> str:
51
+ """What gets embedded for a symbol: its name, where it lives, who it talks to, and the start of its body."""
52
+ from graphsnip.engine import _IN_REL, _OUT_REL
53
+ from graphsnip.project import parse_line
54
+
55
+ d = G.nodes[nid]
56
+ label = re.sub(r"\(\)\s*$", "", str(d.get("label", nid))).strip(". ")
57
+ rel = str(d.get("source_file", ""))
58
+ line = parse_line(d.get("source_location")) or 1
59
+ callees, callers = [], []
60
+ try:
61
+ callees = [v for _u, v, dd in G.out_edges(nid, data=True) if dd.get("relation") in _OUT_REL and v in G]
62
+ callers = [u for u, _v, dd in G.in_edges(nid, data=True) if dd.get("relation") in _IN_REL and u in G]
63
+ except Exception:
64
+ pass
65
+ if rel not in cache:
66
+ cache[rel] = (project.read(rel) or "").splitlines()
67
+ body = "\n".join(cache[rel][max(line - 1, 0): max(line - 1, 0) + BODY_LINES])
68
+ parts = [
69
+ f"{label} ({'class' if d.get('_callable_class') else 'function'}) in {rel}",
70
+ f"words: {split_identifier(label)} {split_identifier(Path(rel).stem)}",
71
+ ]
72
+ if callees:
73
+ parts.append("uses: " + ", ".join(_labels(G, callees)[:8]))
74
+ if callers:
75
+ parts.append("used by: " + ", ".join(_labels(G, callers)[:8]))
76
+ parts.append(body)
77
+ return "\n".join(parts)[:MAX_TEXT_CHARS]
78
+
79
+
80
+ def text_hash(text: str) -> str:
81
+ return hashlib.sha1(text.encode("utf-8", "replace")).hexdigest()[:16]
82
+
83
+
84
+ # ------------------------------------------------------------------ embedders
85
+ class Embedder:
86
+ name = "base"
87
+ dim = 0
88
+
89
+ def embed(self, texts: list[str]): # -> numpy float32 (n, dim), L2-normalised
90
+ raise NotImplementedError
91
+
92
+ def embed_query(self, text: str):
93
+ return self.embed([text])[0]
94
+
95
+
96
+ class FastEmbedder(Embedder):
97
+ """Small local ONNX model through `fastembed`: no server, no API key, code never leaves the machine."""
98
+
99
+ def __init__(self, model: str = DEFAULT_MODEL):
100
+ try:
101
+ from fastembed import TextEmbedding
102
+ except Exception as e:
103
+ raise SemanticUnavailable("semantic search needs the optional extra: pip install 'graphsnip[semantic]'") from e
104
+ self.name = model
105
+ try:
106
+ self._m = TextEmbedding(model_name=model)
107
+ except Exception as e:
108
+ raise SemanticUnavailable(f"could not load embedding model {model!r}: {type(e).__name__}: {e}") from e
109
+ self.dim = len(next(iter(self._m.embed(["probe"]))))
110
+
111
+ @staticmethod
112
+ def _norm(a):
113
+ import numpy as np
114
+
115
+ a = np.asarray(a, dtype="float32")
116
+ n = np.linalg.norm(a, axis=1, keepdims=True)
117
+ n[n == 0] = 1.0
118
+ return a / n
119
+
120
+ def embed(self, texts: list[str]):
121
+ import numpy as np
122
+
123
+ return self._norm(np.array(list(self._m.embed(texts))))
124
+
125
+ def embed_query(self, text: str):
126
+ qe = getattr(self._m, "query_embed", None)
127
+ if qe is not None:
128
+ import numpy as np
129
+
130
+ return self._norm(np.array(list(qe([text]))))[0]
131
+ return super().embed_query(text)
132
+
133
+
134
+ class HashEmbedder(Embedder):
135
+ """Dependency-free, deterministic bag-of-words hashing. Used for tests and offline checks, not for quality.
136
+ `aliases` maps a word to a shared concept token, which lets tests express 'these words mean the same thing'."""
137
+
138
+ def __init__(self, dim: int = 256, aliases: dict[str, str] | None = None):
139
+ self.name = f"hash-{dim}"
140
+ self.dim = dim
141
+ self.aliases = {k.lower(): v.lower() for k, v in (aliases or {}).items()}
142
+
143
+ def _vec(self, text: str):
144
+ import numpy as np
145
+
146
+ v = np.zeros(self.dim, dtype="float32")
147
+ for w in re.findall(r"[a-z0-9]+", split_identifier(text) + " " + text.lower()):
148
+ w = self.aliases.get(w, w)
149
+ if len(w) < 3:
150
+ continue
151
+ h = int(hashlib.md5(w.encode()).hexdigest(), 16)
152
+ v[h % self.dim] += 1.0 if (h >> 64) & 1 else -1.0
153
+ n = float(np.linalg.norm(v))
154
+ return v / n if n else v
155
+
156
+ def embed(self, texts: list[str]):
157
+ import numpy as np
158
+
159
+ return np.stack([self._vec(t) for t in texts]) if texts else np.zeros((0, self.dim), dtype="float32")
160
+
161
+
162
+ _EMBEDDERS: dict[str, Embedder] = {}
163
+
164
+
165
+ def get_embedder(project=None) -> Embedder:
166
+ name = os.environ.get("GRAPHSNIP_EMBEDDER") or (project.config().get("semantic_model") if project else None) or DEFAULT_MODEL
167
+ if name not in _EMBEDDERS:
168
+ _EMBEDDERS[name] = HashEmbedder() if name == "hash" else FastEmbedder(name)
169
+ return _EMBEDDERS[name]
170
+
171
+
172
+ # ------------------------------------------------------------------ store
173
+ def sem_dir(project) -> Path:
174
+ return project.gs_dir / "semantic"
175
+
176
+
177
+ def has_index(project) -> bool:
178
+ d = sem_dir(project)
179
+ return (d / "vectors.npy").exists() and (d / "ids.json").exists() and (d / "meta.json").exists()
180
+
181
+
182
+ def _load(project):
183
+ import numpy as np
184
+
185
+ d = sem_dir(project)
186
+ meta = json.loads((d / "meta.json").read_text(encoding="utf-8"))
187
+ ids = json.loads((d / "ids.json").read_text(encoding="utf-8"))
188
+ return meta, ids["ids"], ids["hashes"], np.load(d / "vectors.npy")
189
+
190
+
191
+ def _save(project, meta: dict, ids: list[str], hashes: list[str], mat) -> None:
192
+ import numpy as np
193
+
194
+ d = sem_dir(project)
195
+ d.mkdir(parents=True, exist_ok=True)
196
+ (d / ".gitignore").write_text("*\n", encoding="utf-8") # derived, per-machine and per-model: never commit
197
+ tmp = d / "vectors.tmp.npy"
198
+ np.save(tmp, mat.astype("float16"))
199
+ os.replace(tmp, d / "vectors.npy")
200
+ (d / "ids.json.tmp").write_text(json.dumps({"ids": ids, "hashes": hashes}), encoding="utf-8")
201
+ os.replace(d / "ids.json.tmp", d / "ids.json")
202
+ (d / "meta.json.tmp").write_text(json.dumps(meta), encoding="utf-8")
203
+ os.replace(d / "meta.json.tmp", d / "meta.json")
204
+
205
+
206
+ def refresh(project, embedder: Embedder | None = None, force: bool = False, batch: int = 64, progress=None) -> dict:
207
+ """Bring the vectors in line with the current graph, embedding only new or changed symbols."""
208
+ import numpy as np
209
+
210
+ t0 = time.time()
211
+ emb = embedder or get_embedder(project)
212
+ G = project.graph()
213
+ cache: dict = {}
214
+ want: list[tuple[str, str]] = [] # (node id, text)
215
+ for nid, _d in project.symbol_nodes():
216
+ want.append((nid, node_text(project, G, nid, cache)))
217
+ old_vec: dict[str, tuple[str, object]] = {}
218
+ if has_index(project) and not force:
219
+ try:
220
+ meta, ids, hashes, mat = _load(project)
221
+ if meta.get("model") == emb.name and meta.get("dim") == emb.dim and meta.get("v") == VERSION:
222
+ for i, nid in enumerate(ids):
223
+ old_vec[nid] = (hashes[i], mat[i])
224
+ except Exception:
225
+ old_vec = {}
226
+ todo = [(nid, t) for nid, t in want if old_vec.get(nid, ("", None))[0] != text_hash(t)]
227
+ new_vecs: dict[str, object] = {}
228
+ for i in range(0, len(todo), batch):
229
+ chunk = todo[i: i + batch]
230
+ vecs = emb.embed([t for _n, t in chunk])
231
+ for (nid, _t), v in zip(chunk, vecs):
232
+ new_vecs[nid] = v
233
+ if progress:
234
+ progress(min(i + batch, len(todo)), len(todo))
235
+ ids, hashes, rows = [], [], []
236
+ for nid, t in want:
237
+ h = text_hash(t)
238
+ if nid in new_vecs:
239
+ rows.append(new_vecs[nid])
240
+ else:
241
+ rows.append(old_vec[nid][1])
242
+ ids.append(nid)
243
+ hashes.append(h)
244
+ mat = np.stack(rows).astype("float32") if rows else np.zeros((0, emb.dim), dtype="float32")
245
+ sid = set(ids)
246
+ removed = len([n for n in old_vec if n not in sid])
247
+ meta = {"v": VERSION, "model": emb.name, "dim": emb.dim, "count": len(ids), "built": time.time()}
248
+ _save(project, meta, ids, hashes, mat)
249
+ _CACHE.pop(str(project.root), None)
250
+ return {"total": len(ids), "embedded": len(todo), "reused": len(ids) - len(todo), "removed": removed,
251
+ "seconds": round(time.time() - t0, 1), "model": emb.name}
252
+
253
+
254
+ def refresh_if_enabled(project) -> dict | None:
255
+ """Called after a graph refresh: keep an existing index current. Never builds one on its own."""
256
+ if os.environ.get("GRAPHSNIP_SEMANTIC", "").lower() == "off" or project.config().get("semantic") == "off":
257
+ return None
258
+ if not has_index(project):
259
+ return None
260
+ try:
261
+ return refresh(project)
262
+ except SemanticUnavailable as e:
263
+ sys.stderr.write(f"[graphsnip] {e}\n")
264
+ return None
265
+
266
+
267
+ _CACHE: dict[str, tuple[float, list[str], object]] = {}
268
+
269
+
270
+ def _matrix(project):
271
+ key = str(project.root)
272
+ mt = (sem_dir(project) / "vectors.npy").stat().st_mtime
273
+ hit = _CACHE.get(key)
274
+ if hit and hit[0] == mt:
275
+ return hit[1], hit[2], None
276
+ meta, ids, _h, mat = _load(project)
277
+ mat = mat.astype("float32")
278
+ _CACHE[key] = (mt, ids, mat)
279
+ return ids, mat, meta
280
+
281
+
282
+ def status(project) -> dict:
283
+ if not has_index(project):
284
+ return {"present": False}
285
+ try:
286
+ meta = json.loads((sem_dir(project) / "meta.json").read_text(encoding="utf-8"))
287
+ except Exception:
288
+ return {"present": False}
289
+ G = project.graph() if project.has_graph() else None
290
+ pending = None
291
+ if G is not None:
292
+ try:
293
+ _m, ids, hashes, _mat = _load(project)
294
+ have = dict(zip(ids, hashes))
295
+ cache: dict = {}
296
+ pending = sum(1 for nid, _d in project.symbol_nodes() if have.get(nid) != text_hash(node_text(project, G, nid, cache)))
297
+ except Exception:
298
+ pending = None
299
+ return {"present": True, "model": meta.get("model"), "dim": meta.get("dim"), "count": meta.get("count"),
300
+ "built": meta.get("built"), "pending": pending}
301
+
302
+
303
+ # ------------------------------------------------------------------ search and fusion
304
+ def search(project, query: str, k: int = 20, embedder: Embedder | None = None) -> list[tuple[str, float]]:
305
+ """Nearest symbols to the query by cosine similarity: [(node id, score)], best first. [] when unavailable."""
306
+ import numpy as np
307
+
308
+ if os.environ.get("GRAPHSNIP_SEMANTIC", "").lower() == "off" or project.config().get("semantic") == "off":
309
+ return []
310
+ if not has_index(project):
311
+ return []
312
+ try:
313
+ emb = embedder or get_embedder(project)
314
+ ids, mat, _meta = _matrix(project)
315
+ if mat.shape[0] == 0 or mat.shape[1] != emb.dim:
316
+ return []
317
+ q = np.asarray(emb.embed_query(query), dtype="float32")
318
+ scores = mat @ q
319
+ except SemanticUnavailable as e:
320
+ sys.stderr.write(f"[graphsnip] {e}\n")
321
+ return []
322
+ k = min(k, len(ids))
323
+ top = np.argpartition(-scores, k - 1)[:k]
324
+ top = top[np.argsort(-scores[top])]
325
+ G = project.graph()
326
+ return [(ids[i], float(scores[i])) for i in top if ids[i] in G and not math.isnan(float(scores[i]))]
327
+
328
+
329
+ def rrf(*ranked: list[str], k: int = RRF_K) -> list[tuple[str, float]]:
330
+ """Reciprocal rank fusion: merge several best-first lists of ids without tuning weights."""
331
+ score: dict[str, float] = {}
332
+ for lst in ranked:
333
+ for r, nid in enumerate(lst):
334
+ score[nid] = score.get(nid, 0.0) + 1.0 / (k + r + 1)
335
+ return sorted(score.items(), key=lambda kv: -kv[1])
@@ -0,0 +1,116 @@
1
+ """Shell-output compression. Test, build and git logs often cost more tokens than
2
+ the code they are about. `graphsnip run -- <cmd>` runs a command, keeps the
3
+ exit code, and prints a compressed version of its output. The saving is
4
+ measured exactly (raw tokens vs compressed tokens), not estimated."""
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ import subprocess
9
+ import sys
10
+
11
+ from graphsnip import ledger as _ledger
12
+ from graphsnip.project import Project
13
+ from graphsnip.tokens import count_tokens
14
+
15
+ _ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
16
+ _NOISE = re.compile(r"^\s*(\d{1,3}%|[#=>\-\.\s\|/\\█▏▎▍▌▋▊▉]{12,})\s*$")
17
+ _IMPORTANT = re.compile(r"(error|fail|failed|traceback|exception|panic|assert|warning|fatal|✗|✘|FAILED|ERROR|cannot|denied|not found)", re.I)
18
+ _SUMMARY = re.compile(r"(passed|failed|errors?|tests? ran|test suites?|total|ok\b|finished|compiled|built in|exit code)", re.I)
19
+
20
+
21
+ _NUM = re.compile(r"\d+|0x[0-9a-fA-F]+")
22
+
23
+
24
+ def _collapse_similar(lines: list[str], min_run: int = 5) -> list[str]:
25
+ """Runs of lines identical up to numbers (progress, 'item 17 ... ok') become first, count, last."""
26
+ out: list[str] = []
27
+ i = 0
28
+ while i < len(lines):
29
+ key = _NUM.sub("#", lines[i])
30
+ j = i + 1
31
+ while j < len(lines) and lines[j] != "" and _NUM.sub("#", lines[j]) == key and not _IMPORTANT.search(lines[j]):
32
+ j += 1
33
+ run = j - i
34
+ if run >= min_run and lines[i] != "" and not _IMPORTANT.search(lines[i]):
35
+ out += [lines[i], f"… {run - 2} similar lines …", lines[j - 1]]
36
+ else:
37
+ out += lines[i:j]
38
+ i = j
39
+ return out
40
+
41
+
42
+ def compress(text: str, max_lines: int = 120, head: int = 20, tail: int = 30) -> str:
43
+ text = _ANSI.sub("", text).replace("\r\n", "\n")
44
+ text = re.sub(r"[^\n]*\r(?!\n)", "", text) # carriage-return progress redraws
45
+ lines = [ln.rstrip() for ln in text.split("\n")]
46
+ # drop progress noise
47
+ lines = [ln for ln in lines if not _NOISE.match(ln)]
48
+ # collapse consecutive duplicates
49
+ out: list[str] = []
50
+ prev, n = None, 0
51
+ for ln in lines + [None]:
52
+ if ln == prev:
53
+ n += 1
54
+ continue
55
+ if prev is not None:
56
+ out.append(prev if n == 1 else f"{prev} (×{n})")
57
+ prev, n = ln, 1
58
+ lines = _collapse_similar(out)
59
+ # trim leading/trailing blank runs and collapse blank runs
60
+ cleaned: list[str] = []
61
+ for ln in lines:
62
+ if ln == "" and cleaned and cleaned[-1] == "":
63
+ continue
64
+ cleaned.append(ln)
65
+ lines = cleaned
66
+ if len(lines) <= max_lines:
67
+ return "\n".join(lines).strip("\n")
68
+ keep = set(range(min(head, len(lines))))
69
+ keep |= set(range(max(0, len(lines) - tail), len(lines)))
70
+ budget = max_lines - len(keep)
71
+ for i, ln in enumerate(lines):
72
+ if budget <= 0:
73
+ break
74
+ if i in keep:
75
+ continue
76
+ if _IMPORTANT.search(ln) or _SUMMARY.search(ln):
77
+ for j in (i - 1, i, i + 1):
78
+ if 0 <= j < len(lines) and j not in keep and budget > 0:
79
+ keep.add(j)
80
+ budget -= 1
81
+ res: list[str] = []
82
+ last = -1
83
+ for i in sorted(keep):
84
+ if i != last + 1:
85
+ res.append(f"… {i - last - 1} lines omitted …")
86
+ res.append(lines[i])
87
+ last = i
88
+ if last != len(lines) - 1:
89
+ res.append(f"… {len(lines) - 1 - last} lines omitted …")
90
+ return "\n".join(res).strip("\n")
91
+
92
+
93
+ def run(argv: list[str], root: str = ".") -> int:
94
+ if not argv:
95
+ sys.stderr.write("usage: graphsnip run -- <command> [args...]\n")
96
+ return 2
97
+ try:
98
+ r = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace")
99
+ except FileNotFoundError:
100
+ sys.stderr.write(f"graphsnip run: command not found: {argv[0]}\n")
101
+ return 127
102
+ raw = r.stdout or ""
103
+ small = compress(raw)
104
+ raw_t, small_t = count_tokens(raw), count_tokens(small)
105
+ if small_t >= raw_t:
106
+ small, small_t = raw, raw_t
107
+ sys.stdout.write(small + ("\n" if small and not small.endswith("\n") else ""))
108
+ if small_t < raw_t:
109
+ sys.stdout.write(f"[graphsnip: output compressed {raw_t} → {small_t} tokens]\n")
110
+ try:
111
+ _ledger.Ledger(Project(root).gs_dir).record(
112
+ kind="call", tool="shell", query=" ".join(argv)[:160], returned=small_t, baseline=raw_t,
113
+ files=[], source="shell", session="shell", deduped=False)
114
+ except Exception:
115
+ pass
116
+ return r.returncode