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.
- ctxloop/__init__.py +2 -0
- ctxloop/__main__.py +4 -0
- ctxloop-0.3.0.dist-info/METADATA +551 -0
- ctxloop-0.3.0.dist-info/RECORD +33 -0
- ctxloop-0.3.0.dist-info/WHEEL +5 -0
- ctxloop-0.3.0.dist-info/entry_points.txt +3 -0
- ctxloop-0.3.0.dist-info/licenses/LICENSE +202 -0
- ctxloop-0.3.0.dist-info/licenses/NOTICE +7 -0
- ctxloop-0.3.0.dist-info/top_level.txt +2 -0
- graphsnip/__init__.py +3 -0
- graphsnip/__main__.py +4 -0
- graphsnip/ab.py +211 -0
- graphsnip/baseline.py +89 -0
- graphsnip/bench.py +208 -0
- graphsnip/cli.py +591 -0
- graphsnip/dashboard.py +765 -0
- graphsnip/engine.py +576 -0
- graphsnip/hooks.py +178 -0
- graphsnip/installer.py +445 -0
- graphsnip/ledger.py +107 -0
- graphsnip/mcp_server.py +305 -0
- graphsnip/memory_client.py +66 -0
- graphsnip/memory_eval.py +51 -0
- graphsnip/probe.py +83 -0
- graphsnip/project.py +503 -0
- graphsnip/py.typed +0 -0
- graphsnip/retrieval.py +77 -0
- graphsnip/router.py +175 -0
- graphsnip/semantic.py +335 -0
- graphsnip/shellfilter.py +116 -0
- graphsnip/slicer.py +217 -0
- graphsnip/tokens.py +35 -0
- graphsnip/usage.py +73 -0
graphsnip/slicer.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Symbol-level code slicing: given a file and the line Graphify recorded for a
|
|
2
|
+
node, return exactly that definition (tree-sitter when available, indentation /
|
|
3
|
+
brace matching otherwise)."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import importlib
|
|
7
|
+
import re
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from functools import lru_cache
|
|
10
|
+
|
|
11
|
+
_LANGS: dict[str, tuple[str, str]] = {
|
|
12
|
+
".py": ("python", "language"), ".pyi": ("python", "language"),
|
|
13
|
+
".js": ("javascript", "language"), ".jsx": ("javascript", "language"),
|
|
14
|
+
".mjs": ("javascript", "language"), ".cjs": ("javascript", "language"),
|
|
15
|
+
".ts": ("typescript", "language_typescript"), ".tsx": ("typescript", "language_tsx"),
|
|
16
|
+
".go": ("go", "language"), ".rs": ("rust", "language"), ".java": ("java", "language"),
|
|
17
|
+
".c": ("c", "language"), ".h": ("c", "language"),
|
|
18
|
+
".cc": ("cpp", "language"), ".cpp": ("cpp", "language"), ".hpp": ("cpp", "language"),
|
|
19
|
+
".rb": ("ruby", "language"), ".cs": ("c_sharp", "language"), ".kt": ("kotlin", "language"),
|
|
20
|
+
".php": ("php", "language_php"), ".swift": ("swift", "language"), ".lua": ("lua", "language"),
|
|
21
|
+
".sh": ("bash", "language"), ".bash": ("bash", "language"),
|
|
22
|
+
}
|
|
23
|
+
_DEF_HINTS = ("function", "method", "class", "struct", "interface", "enum", "trait", "impl",
|
|
24
|
+
"module", "constructor", "definition", "declaration", "declarator")
|
|
25
|
+
_DEF_SKIP = ("import", "param", "argument", "call", "decorator", "export_clause", "comment", "identifier")
|
|
26
|
+
_WRAPPERS = {"decorated_definition", "export_statement", "ambient_declaration", "decorated_declaration"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Slice:
|
|
31
|
+
start: int # 1-based, inclusive
|
|
32
|
+
end: int # 1-based, inclusive
|
|
33
|
+
text: str
|
|
34
|
+
exact: bool # True when tree-sitter located the definition
|
|
35
|
+
truncated: bool = False
|
|
36
|
+
total_lines: int = 0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@lru_cache(maxsize=32)
|
|
40
|
+
def _parser(suffix: str):
|
|
41
|
+
spec = _LANGS.get(suffix)
|
|
42
|
+
if not spec:
|
|
43
|
+
return None
|
|
44
|
+
try:
|
|
45
|
+
import tree_sitter
|
|
46
|
+
|
|
47
|
+
mod = importlib.import_module(f"tree_sitter_{spec[0]}")
|
|
48
|
+
fn = getattr(mod, spec[1], None) or getattr(mod, "language")
|
|
49
|
+
return tree_sitter.Parser(tree_sitter.Language(fn()))
|
|
50
|
+
except Exception:
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _is_def(node) -> bool:
|
|
55
|
+
t = node.type
|
|
56
|
+
return any(h in t for h in _DEF_HINTS) and not any(s in t for s in _DEF_SKIP)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _ts_range(source: str, suffix: str, line: int) -> tuple[int, int] | None:
|
|
60
|
+
parser = _parser(suffix)
|
|
61
|
+
if parser is None:
|
|
62
|
+
return None
|
|
63
|
+
try:
|
|
64
|
+
tree = parser.parse(source.encode("utf-8", "replace"))
|
|
65
|
+
except Exception:
|
|
66
|
+
return None
|
|
67
|
+
row = line - 1
|
|
68
|
+
best = None
|
|
69
|
+
stack = [tree.root_node]
|
|
70
|
+
while stack:
|
|
71
|
+
n = stack.pop()
|
|
72
|
+
if n.start_point[0] > row or n.end_point[0] < row:
|
|
73
|
+
continue
|
|
74
|
+
if n.start_point[0] == row and _is_def(n):
|
|
75
|
+
span = n.end_point[0] - n.start_point[0]
|
|
76
|
+
if best is None or span > best[0]:
|
|
77
|
+
best = (span, n)
|
|
78
|
+
stack.extend(n.children)
|
|
79
|
+
if best is None:
|
|
80
|
+
return None
|
|
81
|
+
node = best[1]
|
|
82
|
+
parent = node.parent
|
|
83
|
+
start = node.start_point[0]
|
|
84
|
+
if parent is not None and parent.type in _WRAPPERS and parent.start_point[0] < start:
|
|
85
|
+
start = parent.start_point[0]
|
|
86
|
+
end = node.end_point[0]
|
|
87
|
+
return start + 1, end + 1
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _python_block(lines: list[str], i: int) -> int:
|
|
91
|
+
def indent(s: str) -> int:
|
|
92
|
+
return len(s) - len(s.lstrip(" \t"))
|
|
93
|
+
|
|
94
|
+
base = indent(lines[i])
|
|
95
|
+
end = i
|
|
96
|
+
j = i + 1
|
|
97
|
+
while j < len(lines):
|
|
98
|
+
s = lines[j]
|
|
99
|
+
if s.strip() == "":
|
|
100
|
+
j += 1
|
|
101
|
+
continue
|
|
102
|
+
if indent(s) <= base and not s.lstrip().startswith((")", "]", "}")):
|
|
103
|
+
break
|
|
104
|
+
end = j
|
|
105
|
+
j += 1
|
|
106
|
+
return end
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _brace_block(lines: list[str], i: int, cap: int = 400) -> int | None:
|
|
110
|
+
depth = 0
|
|
111
|
+
seen = False
|
|
112
|
+
for j in range(i, min(len(lines), i + cap)):
|
|
113
|
+
for ch in lines[j]:
|
|
114
|
+
if ch == "{":
|
|
115
|
+
depth += 1
|
|
116
|
+
seen = True
|
|
117
|
+
elif ch == "}":
|
|
118
|
+
depth -= 1
|
|
119
|
+
if seen and depth <= 0:
|
|
120
|
+
return j
|
|
121
|
+
if not seen and j - i > 6:
|
|
122
|
+
return None
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def slice_symbol(source: str, suffix: str, line: int, max_lines: int | None = 120) -> Slice:
|
|
127
|
+
lines = source.splitlines()
|
|
128
|
+
n = len(lines)
|
|
129
|
+
line = max(1, min(line, max(n, 1)))
|
|
130
|
+
suffix = suffix.lower()
|
|
131
|
+
exact = False
|
|
132
|
+
rng = _ts_range(source, suffix, line)
|
|
133
|
+
if rng:
|
|
134
|
+
start, end = rng
|
|
135
|
+
exact = True
|
|
136
|
+
else:
|
|
137
|
+
start = line
|
|
138
|
+
i = line - 1
|
|
139
|
+
end_i: int | None = None
|
|
140
|
+
if suffix in (".py", ".pyi"):
|
|
141
|
+
end_i = _python_block(lines, i)
|
|
142
|
+
# include decorators sitting directly above
|
|
143
|
+
while start > 1 and lines[start - 2].lstrip().startswith("@"):
|
|
144
|
+
start -= 1
|
|
145
|
+
else:
|
|
146
|
+
end_i = _brace_block(lines, i)
|
|
147
|
+
end = (end_i + 1) if end_i is not None else min(n, line + 39)
|
|
148
|
+
end = max(start, min(end, n))
|
|
149
|
+
total = end - start + 1
|
|
150
|
+
truncated = False
|
|
151
|
+
if max_lines and total > max_lines:
|
|
152
|
+
end = start + max_lines - 1
|
|
153
|
+
truncated = True
|
|
154
|
+
text = "\n".join(lines[start - 1:end])
|
|
155
|
+
return Slice(start=start, end=end, text=text, exact=exact, truncated=truncated, total_lines=total)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def signature(source: str, suffix: str, line: int, max_lines: int = 3) -> str:
|
|
159
|
+
"""First few lines of a definition: enough to know what it is and how to call it."""
|
|
160
|
+
lines = source.splitlines()
|
|
161
|
+
i = max(0, line - 1)
|
|
162
|
+
out: list[str] = []
|
|
163
|
+
for j in range(i, min(len(lines), i + max_lines)):
|
|
164
|
+
out.append(lines[j].rstrip())
|
|
165
|
+
s = lines[j].rstrip()
|
|
166
|
+
if s.endswith((":", "{", ";")) or s.endswith(") =>") or "=>" in s:
|
|
167
|
+
break
|
|
168
|
+
return "\n".join(out)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def shorten_docstring(text: str, suffix: str, min_lines: int = 7) -> tuple[str, int]:
|
|
172
|
+
"""Collapse a long Python docstring to its first paragraph. Returns (text, omitted_line_count).
|
|
173
|
+
|
|
174
|
+
Only touches the first string statement right after a def/class line, and only
|
|
175
|
+
when it is long, so short docstrings and all code are left exactly as written."""
|
|
176
|
+
if suffix.lower() not in (".py", ".pyi"):
|
|
177
|
+
return text, 0
|
|
178
|
+
lines = text.split("\n")
|
|
179
|
+
# find end of the signature: first line ending with ':' (outside of continuation)
|
|
180
|
+
i = 0
|
|
181
|
+
while i < len(lines) and not lines[i].rstrip().endswith(":"):
|
|
182
|
+
i += 1
|
|
183
|
+
if i > 12:
|
|
184
|
+
return text, 0
|
|
185
|
+
j = i + 1
|
|
186
|
+
while j < len(lines) and lines[j].strip() == "":
|
|
187
|
+
j += 1
|
|
188
|
+
if j >= len(lines):
|
|
189
|
+
return text, 0
|
|
190
|
+
first = lines[j].lstrip()
|
|
191
|
+
m = re.match(r'^[rRbBuU]{0,2}("""|\'\'\')', first)
|
|
192
|
+
if not m:
|
|
193
|
+
return text, 0
|
|
194
|
+
q = m.group(1)
|
|
195
|
+
indent = lines[j][: len(lines[j]) - len(first)]
|
|
196
|
+
# single-line docstring
|
|
197
|
+
if first.count(q) >= 2:
|
|
198
|
+
return text, 0
|
|
199
|
+
k = j + 1
|
|
200
|
+
while k < len(lines) and q not in lines[k]:
|
|
201
|
+
k += 1
|
|
202
|
+
if k >= len(lines):
|
|
203
|
+
return text, 0
|
|
204
|
+
n_doc = k - j + 1
|
|
205
|
+
if n_doc < min_lines:
|
|
206
|
+
return text, 0
|
|
207
|
+
keep = [lines[j]]
|
|
208
|
+
t = j + 1
|
|
209
|
+
while t < k and lines[t].strip() != "" and len(keep) < 3:
|
|
210
|
+
keep.append(lines[t])
|
|
211
|
+
t += 1
|
|
212
|
+
omitted = k - j + 1 - len(keep) - 1
|
|
213
|
+
if omitted <= 0:
|
|
214
|
+
return text, 0
|
|
215
|
+
note = f'{indent}... [docstring shortened: {omitted} lines omitted; docs="full" shows them]'
|
|
216
|
+
new = lines[: j] + keep + [note, lines[k]] + lines[k + 1:]
|
|
217
|
+
return "\n".join(new), omitted
|
graphsnip/tokens.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Token counting. Uses tiktoken when installed, else a chars/4 estimate
|
|
2
|
+
(the same convention Graphify's own benchmark uses)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
_enc = None
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _encoder():
|
|
11
|
+
global _enc
|
|
12
|
+
if _enc is None:
|
|
13
|
+
try:
|
|
14
|
+
import tiktoken
|
|
15
|
+
|
|
16
|
+
_enc = tiktoken.get_encoding("cl100k_base")
|
|
17
|
+
except Exception:
|
|
18
|
+
_enc = False
|
|
19
|
+
return _enc
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def count_tokens(text: str) -> int:
|
|
23
|
+
if not text:
|
|
24
|
+
return 0
|
|
25
|
+
enc = _encoder()
|
|
26
|
+
if enc:
|
|
27
|
+
try:
|
|
28
|
+
return len(enc.encode(text, disallowed_special=()))
|
|
29
|
+
except Exception:
|
|
30
|
+
pass
|
|
31
|
+
return max(1, math.ceil(len(text) / 4))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def method() -> str:
|
|
35
|
+
return "tiktoken cl100k_base" if _encoder() else "estimate (chars / 4)"
|
graphsnip/usage.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Measured model mix from Claude Code session transcripts (~/.claude/projects/<project>/*.jsonl).
|
|
2
|
+
|
|
3
|
+
This is the check on routing: it reads which model actually produced each reply and its token usage.
|
|
4
|
+
Only Claude Code is supported; Copilot does not expose usage and Codex support is not implemented.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
_FAMILY_TIER = {"haiku": "light", "sonnet": "standard", "opus": "heavy"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def transcripts_dir(root: Path) -> Path:
|
|
17
|
+
base = Path(os.environ.get("CLAUDE_CONFIG_DIR") or (Path.home() / ".claude"))
|
|
18
|
+
return base / "projects" / re.sub(r"[^A-Za-z0-9]", "-", str(root))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def family(model: str) -> str:
|
|
22
|
+
m = (model or "").lower()
|
|
23
|
+
for f in _FAMILY_TIER:
|
|
24
|
+
if f in m:
|
|
25
|
+
return f
|
|
26
|
+
return "other"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def scan(root: Path, cfg: dict, directory: Path | None = None, since: str | None = None) -> dict | None:
|
|
30
|
+
d = directory or transcripts_dir(root)
|
|
31
|
+
if not d.is_dir():
|
|
32
|
+
return None
|
|
33
|
+
seen: set = set()
|
|
34
|
+
first = last = None
|
|
35
|
+
fam: dict[str, dict] = {}
|
|
36
|
+
for f in d.glob("*.jsonl"):
|
|
37
|
+
try:
|
|
38
|
+
lines = f.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
39
|
+
except OSError:
|
|
40
|
+
continue
|
|
41
|
+
for ln in lines:
|
|
42
|
+
try:
|
|
43
|
+
rec = json.loads(ln)
|
|
44
|
+
except Exception:
|
|
45
|
+
continue
|
|
46
|
+
if since and str(rec.get("timestamp", "")) < since:
|
|
47
|
+
continue
|
|
48
|
+
msg = rec.get("message") if isinstance(rec, dict) else None
|
|
49
|
+
if not isinstance(msg, dict) or not msg.get("model") or not isinstance(msg.get("usage"), dict):
|
|
50
|
+
continue
|
|
51
|
+
key = (msg.get("id"), rec.get("requestId"))
|
|
52
|
+
if key != (None, None):
|
|
53
|
+
if key in seen:
|
|
54
|
+
continue # streamed replies are logged more than once
|
|
55
|
+
seen.add(key)
|
|
56
|
+
u = msg["usage"]
|
|
57
|
+
ts = str(rec.get("timestamp", ""))
|
|
58
|
+
if ts:
|
|
59
|
+
first, last = min(first or ts, ts), max(last or ts, ts)
|
|
60
|
+
row = fam.setdefault(family(msg["model"]), {"messages": 0, "input": 0, "output": 0, "cache_read": 0})
|
|
61
|
+
row["messages"] += 1
|
|
62
|
+
row["input"] += int(u.get("input_tokens", 0)) + int(u.get("cache_creation_input_tokens", 0))
|
|
63
|
+
row["output"] += int(u.get("output_tokens", 0))
|
|
64
|
+
row["cache_read"] += int(u.get("cache_read_input_tokens", 0))
|
|
65
|
+
if not fam:
|
|
66
|
+
return None
|
|
67
|
+
total = 0.0
|
|
68
|
+
for name, row in fam.items():
|
|
69
|
+
tier = _FAMILY_TIER.get(name, cfg["baseline_tier"])
|
|
70
|
+
pin, pout = cfg["prices"][tier]
|
|
71
|
+
row["usd"] = round((row["input"] * pin + row["output"] * pout + row["cache_read"] * pin * 0.1) / 1_000_000, 4)
|
|
72
|
+
total += row["usd"]
|
|
73
|
+
return {"families": fam, "usd_total": round(total, 4), "dir": str(d), "first": first, "last": last, "since": since}
|