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/dashboard.py
ADDED
|
@@ -0,0 +1,765 @@
|
|
|
1
|
+
"""Self-contained HTML dashboard: token savings, benchmark, and the Graphify map.
|
|
2
|
+
|
|
3
|
+
No external requests (works offline and on a projector). Charts are inline SVG.
|
|
4
|
+
The interactive knowledge graph is Graphify's own graph.html, embedded by
|
|
5
|
+
relative path (or copied next to the dashboard with --bundle).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import html
|
|
10
|
+
import json
|
|
11
|
+
import shutil
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from graphsnip import __version__
|
|
16
|
+
from graphsnip import ledger as _ledger
|
|
17
|
+
from graphsnip.project import Project
|
|
18
|
+
from graphsnip.tokens import method
|
|
19
|
+
|
|
20
|
+
e = html.escape
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def n(x) -> str:
|
|
24
|
+
try:
|
|
25
|
+
return f"{int(x):,}"
|
|
26
|
+
except Exception:
|
|
27
|
+
return "-"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _bars(items: list[tuple[str, int, str, str]], width: int = 980) -> str:
|
|
31
|
+
"""items: (label, value, css_class, note). Horizontal bars, longest = full bar width."""
|
|
32
|
+
mx = max((v for _l, v, _c, _n in items), default=1) or 1
|
|
33
|
+
row_h, gap, left, right = 30, 14, 200, 340
|
|
34
|
+
h = len(items) * (row_h + gap)
|
|
35
|
+
out = [f'<svg viewBox="0 0 {width} {h}" role="img" aria-label="Tokens per approach" class="chart">']
|
|
36
|
+
for i, (lab, v, cls, note) in enumerate(items):
|
|
37
|
+
y = i * (row_h + gap)
|
|
38
|
+
w = max(3, (width - left - right) * v / mx)
|
|
39
|
+
out.append(f'<text x="0" y="{y + 20}" class="lbl">{e(lab)}</text>')
|
|
40
|
+
out.append(f'<rect x="{left}" y="{y}" width="{w:.1f}" height="{row_h}" rx="5" class="{cls}"/>')
|
|
41
|
+
out.append(f'<text x="{left + w + 10:.1f}" y="{y + 20}" class="val"><tspan class="num">{n(v)}</tspan>'
|
|
42
|
+
f'{(" · " + e(note)) if note else ""}</text>')
|
|
43
|
+
out.append("</svg>")
|
|
44
|
+
return "".join(out)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _lines(timeline: list[dict], width: int = 720, height: int = 260) -> str:
|
|
48
|
+
if len(timeline) < 2:
|
|
49
|
+
return '<p class="muted">Not enough calls yet to draw a curve. Use the tools (or run <code>graphsnip bench</code>) and re-generate.</p>'
|
|
50
|
+
pad_l, pad_r, pad_t, pad_b = 54, 14, 14, 34
|
|
51
|
+
W, H = width - pad_l - pad_r, height - pad_t - pad_b
|
|
52
|
+
mx = max(t["baseline"] for t in timeline) or 1
|
|
53
|
+
k = len(timeline)
|
|
54
|
+
|
|
55
|
+
def X(i):
|
|
56
|
+
return pad_l + W * i / (k - 1)
|
|
57
|
+
|
|
58
|
+
def Y(v):
|
|
59
|
+
return pad_t + H * (1 - v / mx)
|
|
60
|
+
|
|
61
|
+
base = " ".join(f"{X(i):.1f},{Y(t['baseline']):.1f}" for i, t in enumerate(timeline))
|
|
62
|
+
ret = " ".join(f"{X(i):.1f},{Y(t['returned']):.1f}" for i, t in enumerate(timeline))
|
|
63
|
+
area = base + " " + " ".join(f"{X(i):.1f},{Y(t['returned']):.1f}" for i, t in reversed(list(enumerate(timeline))))
|
|
64
|
+
out = [f'<svg viewBox="0 0 {width} {height}" role="img" aria-label="Cumulative tokens with and without graphsnip" class="chart">']
|
|
65
|
+
for frac in (0, 0.25, 0.5, 0.75, 1):
|
|
66
|
+
y = pad_t + H * (1 - frac)
|
|
67
|
+
out.append(f'<line x1="{pad_l}" x2="{width - pad_r}" y1="{y:.1f}" y2="{y:.1f}" class="grid"/>')
|
|
68
|
+
out.append(f'<text x="{pad_l - 8}" y="{y + 4:.1f}" text-anchor="end" class="axis">{n(mx * frac)}</text>')
|
|
69
|
+
out.append(f'<polygon points="{area}" class="area"/>')
|
|
70
|
+
out.append(f'<polyline points="{base}" class="l-base" fill="none"/>')
|
|
71
|
+
out.append(f'<polyline points="{ret}" class="l-ret" fill="none"/>')
|
|
72
|
+
out.append(f'<text x="{pad_l}" y="{height - 8}" class="axis">call 1</text>')
|
|
73
|
+
out.append(f'<text x="{width - pad_r}" y="{height - 8}" text-anchor="end" class="axis">call {k}</text>')
|
|
74
|
+
out.append("</svg>")
|
|
75
|
+
return "".join(out)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _fmt_tok(v: float) -> str:
|
|
79
|
+
return f"{v / 1e6:g}M" if v >= 1e6 else f"{v / 1e3:g}k" if v >= 1e3 else f"{v:g}"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _percall(series: list[dict], width: int = 760, height: int = 330) -> str:
|
|
83
|
+
"""Paired bars per call on a log axis, so a 2% result is as visible as a 100% one, with the multiplier on top."""
|
|
84
|
+
import math
|
|
85
|
+
|
|
86
|
+
pts = [x for x in series if x["baseline"] > 0 and x["returned"] > 0]
|
|
87
|
+
if not pts:
|
|
88
|
+
return '<p class="muted">No calls recorded yet. Use the tools (or run <code>graphsnip bench</code>) and re-generate.</p>'
|
|
89
|
+
pl, pr, pt, pb = 52, 10, 22, 40
|
|
90
|
+
W, H = width - pl - pr, height - pt - pb
|
|
91
|
+
vals = [x["returned"] for x in pts] + [x["baseline"] for x in pts]
|
|
92
|
+
lo, hi = 10 ** math.floor(math.log10(max(1, min(vals)))), 10 ** math.ceil(math.log10(max(vals)))
|
|
93
|
+
if lo == hi:
|
|
94
|
+
hi = lo * 10
|
|
95
|
+
|
|
96
|
+
def Y(v):
|
|
97
|
+
return pt + H * (1 - (math.log10(v) - math.log10(lo)) / (math.log10(hi) - math.log10(lo)))
|
|
98
|
+
|
|
99
|
+
k = len(pts)
|
|
100
|
+
slot = W / k
|
|
101
|
+
bw = max(3.0, min(26.0, slot * 0.38))
|
|
102
|
+
out = [f'<svg viewBox="0 0 {width} {height}" role="img" aria-label="Tokens per call with and without graphsnip, log scale" class="chart">']
|
|
103
|
+
e10 = int(math.log10(lo))
|
|
104
|
+
while 10 ** e10 <= hi:
|
|
105
|
+
y = Y(10 ** e10)
|
|
106
|
+
out.append(f'<line x1="{pl}" x2="{width - pr}" y1="{y:.1f}" y2="{y:.1f}" class="grid"/>'
|
|
107
|
+
f'<text x="{pl - 7}" y="{y + 4:.1f}" text-anchor="end" class="axis">{_fmt_tok(10 ** e10)}</text>')
|
|
108
|
+
e10 += 1
|
|
109
|
+
for i, x in enumerate(pts):
|
|
110
|
+
cx = pl + slot * (i + 0.5)
|
|
111
|
+
yb, yr = Y(x["baseline"]), Y(x["returned"])
|
|
112
|
+
mult = x["baseline"] / x["returned"]
|
|
113
|
+
tip = f'{x["tool"]}: {x["query"]} | baseline {x["baseline"]:,} vs graphsnip {x["returned"]:,} tokens ({mult:.0f}x fewer)'
|
|
114
|
+
out.append(f'<g><title>{e(tip)}</title><rect x="{cx - bw - 1:.1f}" y="{yb:.1f}" width="{bw:.1f}" height="{pt + H - yb:.1f}" class="b-grep" rx="2"/>'
|
|
115
|
+
f'<rect x="{cx + 1:.1f}" y="{yr:.1f}" width="{bw:.1f}" height="{pt + H - yr:.1f}" class="b-cg" rx="2"/>')
|
|
116
|
+
if slot >= 34:
|
|
117
|
+
out.append(f'<text x="{cx:.1f}" y="{yb - 5:.1f}" text-anchor="middle" class="num" style="font-size:12px">{mult:.0f}×</text>')
|
|
118
|
+
out.append("</g>")
|
|
119
|
+
if k <= 12 or i % max(1, k // 10) == 0:
|
|
120
|
+
out.append(f'<text x="{cx:.1f}" y="{height - 22}" text-anchor="middle" class="axis">{e(x["tool"].replace("gs_", ""))}</text>'
|
|
121
|
+
f'<text x="{cx:.1f}" y="{height - 9}" text-anchor="middle" class="axis">#{i + 1}</text>')
|
|
122
|
+
out.append("</svg>")
|
|
123
|
+
return "".join(out)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _saved_line(timeline: list[dict], width: int = 760, height: int = 300) -> str:
|
|
127
|
+
"""Cumulative tokens SAVED: one line that visibly climbs, instead of two lines where one hugs zero."""
|
|
128
|
+
if len(timeline) < 2:
|
|
129
|
+
return '<p class="muted">Not enough calls yet to draw a curve.</p>'
|
|
130
|
+
pl, pr, pt, pb = 58, 70, 18, 34
|
|
131
|
+
W, H = width - pl - pr, height - pt - pb
|
|
132
|
+
sv = [t["baseline"] - t["returned"] for t in timeline]
|
|
133
|
+
mx = max(sv) or 1
|
|
134
|
+
k = len(sv)
|
|
135
|
+
X = lambda i: pl + W * i / (k - 1) # noqa: E731
|
|
136
|
+
Y = lambda v: pt + H * (1 - v / mx) # noqa: E731
|
|
137
|
+
line = " ".join(f"{X(i):.1f},{Y(v):.1f}" for i, v in enumerate(sv))
|
|
138
|
+
out = [f'<svg viewBox="0 0 {width} {height}" role="img" aria-label="Cumulative tokens saved" class="chart">']
|
|
139
|
+
for frac in (0, 0.25, 0.5, 0.75, 1):
|
|
140
|
+
y = pt + H * (1 - frac)
|
|
141
|
+
out.append(f'<line x1="{pl}" x2="{width - pr}" y1="{y:.1f}" y2="{y:.1f}" class="grid"/><text x="{pl - 7}" y="{y + 4:.1f}" text-anchor="end" class="axis">{n(mx * frac)}</text>')
|
|
142
|
+
out.append(f'<polygon points="{pl},{pt + H} {line} {X(k - 1):.1f},{pt + H}" class="area" style="opacity:.28"/><polyline points="{line}" class="l-ret" fill="none"/>')
|
|
143
|
+
out.append(f'<circle cx="{X(k - 1):.1f}" cy="{Y(sv[-1]):.1f}" r="4.5" fill="var(--cg)"/><text x="{X(k - 1) + 8:.1f}" y="{Y(sv[-1]) + 4:.1f}" class="num" style="font-size:13px">{n(sv[-1])}</text>')
|
|
144
|
+
out.append(f'<text x="{pl}" y="{height - 8}" class="axis">call 1</text><text x="{X(k - 1):.1f}" y="{height - 8}" text-anchor="end" class="axis">call {k}</text></svg>')
|
|
145
|
+
return "".join(out)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _tradeoff(bench: dict, width: int = 760, height: int = 320) -> str:
|
|
149
|
+
"""Efficiency vs accuracy: tokens (log, left = cheaper) against tasks answered. Up and to the left wins."""
|
|
150
|
+
import math
|
|
151
|
+
|
|
152
|
+
t = bench["totals"]
|
|
153
|
+
nt = max(1, t["tasks"])
|
|
154
|
+
pts = [("graphsnip", t["graphsnip_tokens"], t["answered"] / nt, "var(--cg)", "answered with exact code"),
|
|
155
|
+
("grep + read", t["naive_tokens"], t["naive_answered"] / nt, "var(--grep)", "whole files"),
|
|
156
|
+
("Graphify + read", t["graphify_read_tokens"], t["graphify_answered"] / nt, "var(--gfyread)", "map, then whole files"),
|
|
157
|
+
("Graphify alone", t["graphify_tokens"], t["graphify_answered"] / nt, "var(--gfy)", "map only, no source code")]
|
|
158
|
+
pts = [x for x in pts if x[1] > 0]
|
|
159
|
+
if not pts:
|
|
160
|
+
return '<p class="muted">Run <code>graphsnip bench</code> to see this view.</p>'
|
|
161
|
+
pl, pr, pt, pb = 52, 24, 26, 44
|
|
162
|
+
W, H = width - pl - pr, height - pt - pb
|
|
163
|
+
ymin = max(0.0, math.floor(min(x[2] for x in pts) * 10 - 2) / 10) # zoom the accuracy axis; labelled on the chart
|
|
164
|
+
lo = 10 ** math.floor(math.log10(min(x[1] for x in pts)))
|
|
165
|
+
hi = 10 ** math.ceil(math.log10(max(x[1] for x in pts)))
|
|
166
|
+
X = lambda v: pl + W * (math.log10(v) - math.log10(lo)) / max(1e-9, math.log10(hi) - math.log10(lo)) # noqa: E731
|
|
167
|
+
Y = lambda a: pt + H * (1 - (a - ymin) / (1 - ymin)) # noqa: E731
|
|
168
|
+
out = [f'<svg viewBox="0 0 {width} {height}" role="img" aria-label="Tokens versus tasks answered" class="chart">']
|
|
169
|
+
for a in [ymin + (1 - ymin) * f for f in (0, 0.25, 0.5, 0.75, 1)]:
|
|
170
|
+
out.append(f'<line x1="{pl}" x2="{width - pr}" y1="{Y(a):.1f}" y2="{Y(a):.1f}" class="grid"/><text x="{pl - 7}" y="{Y(a) + 4:.1f}" text-anchor="end" class="axis">{a * 100:.0f}%</text>')
|
|
171
|
+
if ymin > 0:
|
|
172
|
+
out.append(f'<text x="{pl + 8}" y="{pt + H - 8}" class="axis">y axis: tasks answered, zoomed (starts at {ymin * 100:.0f}%, not 0)</text>')
|
|
173
|
+
e10 = int(math.log10(lo))
|
|
174
|
+
while 10 ** e10 <= hi:
|
|
175
|
+
out.append(f'<text x="{X(10 ** e10):.1f}" y="{height - 24}" text-anchor="middle" class="axis">{_fmt_tok(10 ** e10)}</text>')
|
|
176
|
+
e10 += 1
|
|
177
|
+
out.append(f'<text x="{pl + W / 2:.0f}" y="{height - 6}" text-anchor="middle" class="axis">tokens put in context for the benchmark tasks (log scale, fewer is better →)</text>')
|
|
178
|
+
pts.sort(key=lambda x: x[1])
|
|
179
|
+
for i, (name, tok, acc, col, note) in enumerate(pts):
|
|
180
|
+
x, y = X(tok), Y(acc)
|
|
181
|
+
lvl = i % 2 # stagger labels on two rows below the points so ties never overlap
|
|
182
|
+
ly = y + 34 + lvl * 40
|
|
183
|
+
anchor = "end" if x > pl + W * 0.72 else "start"
|
|
184
|
+
dx = -6 if anchor == "end" else 6
|
|
185
|
+
out.append(f'<g><title>{e(name)}: {tok:,} tokens, {acc * 100:.0f}% answered ({note})</title>'
|
|
186
|
+
f'<line x1="{x:.1f}" x2="{x:.1f}" y1="{y + 8:.1f}" y2="{ly - 14:.1f}" stroke="{col}" stroke-width="1.5" stroke-dasharray="3 3"/>'
|
|
187
|
+
f'<circle cx="{x:.1f}" cy="{y:.1f}" r="8" fill="{col}"/>'
|
|
188
|
+
f'<text x="{x + dx:.1f}" y="{ly:.1f}" text-anchor="{anchor}" class="lbl" style="font-size:13px;font-weight:600">{e(name)}</text>'
|
|
189
|
+
f'<text x="{x + dx:.1f}" y="{ly + 15:.1f}" text-anchor="{anchor}" class="axis">{tok:,} tokens · {acc * 100:.0f}% answered</text></g>')
|
|
190
|
+
out.append("</svg>")
|
|
191
|
+
return "".join(out)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _chart_card(head: dict, head_label: str, bench: dict | None) -> str:
|
|
195
|
+
ser = head.get("series") or []
|
|
196
|
+
ratios = sorted(x["baseline"] / x["returned"] for x in ser if x["baseline"] > 0 and x["returned"] > 0)
|
|
197
|
+
med = ratios[len(ratios) // 2] if ratios else 0
|
|
198
|
+
tabs = [("pc", "Per call", _percall(ser),
|
|
199
|
+
f'Each pair is one tool call: grey = what grep + read would have cost, teal = what graphsnip returned (log scale). '
|
|
200
|
+
+ (f'<b>Typical call: {med:.0f}× fewer tokens.</b>' if med else "")),
|
|
201
|
+
("sv", "Tokens saved", _saved_line(head["timeline"]), "Running total of tokens kept out of the context window.")]
|
|
202
|
+
if bench:
|
|
203
|
+
t = bench["totals"]
|
|
204
|
+
tabs.append(("ea", "Efficiency vs accuracy", _tradeoff(bench),
|
|
205
|
+
f'Same {t["tasks"]} questions, four approaches. <b>graphsnip answered {t["answered"]}/{t["tasks"]} with exact source code using '
|
|
206
|
+
f'{100 - t["saved_pct"]:.0f}% of the tokens</b> of grep + read ({t["naive_answered"]}/{t["tasks"]}). "Answered" = expected symbol present; for graphsnip its source code must be too. '
|
|
207
|
+
f'Graphify alone finds the symbol but returns no code.'))
|
|
208
|
+
tabs.append(("cu", "Cumulative", _lines(head["timeline"]), "Both running totals on one linear axis; the graphsnip line hugs zero because it is so small."))
|
|
209
|
+
btns = "".join(f'<button type="button" class="tab{" on" if i == 0 else ""}" data-t="{k}">{e(lbl)}</button>' for i, (k, lbl, _, _) in enumerate(tabs))
|
|
210
|
+
panels = "".join(f'<div class="tp" data-p="{k}"{"" if i == 0 else " hidden"}>{svg}<p class="sub" style="margin-top:6px">{cap}</p></div>'
|
|
211
|
+
for i, (k, _, svg, cap) in enumerate(tabs))
|
|
212
|
+
legend = ('<div class="legend"><span><i class="dot" style="background:var(--grep)"></i>without graphsnip (baseline)</span>'
|
|
213
|
+
'<span><i class="dot" style="background:var(--cg)"></i>with graphsnip</span></div>')
|
|
214
|
+
return (f'<section class="card"><h2>Efficiency and accuracy</h2><div class="sub">{e(head_label)}</div>'
|
|
215
|
+
f'<div class="tabs">{btns}</div>{panels}{legend}</section>')
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _kpi(label: str, value: str, sub: str = "", accent: bool = False) -> str:
|
|
219
|
+
return (f'<div class="kpi{" accent" if accent else ""}"><div class="k-l">{e(label)}</div>'
|
|
220
|
+
f'<div class="k-v">{value}</div><div class="k-s">{e(sub)}</div></div>')
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
TAB_JS = '''<script>document.querySelectorAll(".card").forEach(function(c){var b=c.querySelectorAll(".tab");b.forEach(function(x){x.onclick=function(){b.forEach(function(y){y.classList.toggle("on",y===x)});c.querySelectorAll(".tp").forEach(function(p){p.hidden=p.dataset.p!==x.dataset.t})}})})</script>'''
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _fold(fid: str, title: str, summary: str, body: str, open_: bool = False) -> str:
|
|
227
|
+
return (f'<section class="card fold" id="{fid}"><details{" open" if open_ else ""}><summary><span class="ft">{e(title)}</span>'
|
|
228
|
+
f'<span class="fs">{e(summary)}</span></summary><div class="fb">{body}</div></details></section>')
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
CSS = """
|
|
232
|
+
:root{--bg:#f6f7f9;--card:#fff;--ink:#121826;--mut:#5b6577;--line:#e3e6ec;--brand:#0f766e;--brand2:#14b8a6;
|
|
233
|
+
--grep:#94a3b8;--gfy:#60a5fa;--gfyread:#6366f1;--cg:#0f766e;--bad:#b91c1c;--ok:#15803d;--warn:#b45309}
|
|
234
|
+
@media (prefers-color-scheme:dark){:root{--bg:#0b0f17;--card:#121826;--ink:#e8ecf4;--mut:#93a0b6;--line:#243049;--brand:#2dd4bf;--brand2:#5eead4;
|
|
235
|
+
--grep:#64748b;--gfy:#60a5fa;--gfyread:#818cf8;--cg:#2dd4bf;--bad:#f87171;--ok:#4ade80;--warn:#fbbf24}}
|
|
236
|
+
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
237
|
+
.wrap{max-width:1180px;margin:0 auto;padding:28px 18px 60px}
|
|
238
|
+
header{display:flex;flex-wrap:wrap;gap:14px;align-items:center;justify-content:space-between;margin-bottom:22px}
|
|
239
|
+
.brand{display:flex;align-items:center;gap:12px}.logo{width:38px;height:38px;border-radius:10px;background:linear-gradient(135deg,var(--brand),var(--brand2));display:grid;place-items:center;color:#fff;font-weight:800}
|
|
240
|
+
h1{font-size:22px;margin:0}h2{font-size:17px;margin:0 0 4px}.sub{color:var(--mut);font-size:13px}
|
|
241
|
+
.chips{display:flex;flex-wrap:wrap;gap:8px}.chip{background:var(--card);border:1px solid var(--line);border-radius:999px;padding:4px 11px;font-size:12.5px;color:var(--mut)}
|
|
242
|
+
.chip b{color:var(--ink)}
|
|
243
|
+
.badge{display:inline-block;border-radius:6px;padding:2px 8px;font-size:12px;font-weight:600;background:color-mix(in srgb,var(--brand) 14%,transparent);color:var(--brand)}
|
|
244
|
+
.badge.warn{background:color-mix(in srgb,var(--warn) 16%,transparent);color:var(--warn)}
|
|
245
|
+
.grid4{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:14px;margin-bottom:18px}
|
|
246
|
+
.kpi{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:16px 18px}
|
|
247
|
+
.kpi.accent{background:linear-gradient(135deg,var(--brand),var(--brand2));color:#fff;border:none}.kpi.accent .k-l,.kpi.accent .k-s{color:rgba(255,255,255,.88)}
|
|
248
|
+
.k-l{font-size:12.5px;color:var(--mut);text-transform:uppercase;letter-spacing:.04em}.k-v{font-size:34px;font-weight:750;line-height:1.15;margin:4px 0}.k-s{font-size:12.5px;color:var(--mut)}
|
|
249
|
+
.card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:18px 20px;margin-bottom:18px}
|
|
250
|
+
.two{display:grid;grid-template-columns:1fr 1fr;gap:18px}@media(max-width:900px){.two{grid-template-columns:1fr}}
|
|
251
|
+
.chart{width:100%;height:auto;display:block}.chart .lbl{font-size:14px;fill:var(--ink)}.chart .val{font-size:13px;fill:var(--mut)}.chart .num{fill:var(--ink);font-weight:700}
|
|
252
|
+
.chart .axis{font-size:11px;fill:var(--mut)}.chart .grid{stroke:var(--line);stroke-width:1}
|
|
253
|
+
.b-grep{fill:var(--grep)}.b-gfy{fill:var(--gfy)}.b-gfyread{fill:var(--gfyread)}.b-cg{fill:var(--cg)}
|
|
254
|
+
.area{fill:var(--cg);opacity:.16}.l-base{stroke:var(--grep);stroke-width:2.4}.l-ret{stroke:var(--cg);stroke-width:2.8}
|
|
255
|
+
.legend{display:flex;gap:16px;flex-wrap:wrap;font-size:12.5px;color:var(--mut);margin-top:6px}.dot{display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:6px;vertical-align:-1px}
|
|
256
|
+
table{width:100%;border-collapse:collapse;font-size:13.5px}th,td{padding:8px 10px;border-bottom:1px solid var(--line);text-align:left}th{color:var(--mut);font-weight:600;font-size:12px;text-transform:uppercase;letter-spacing:.03em}
|
|
257
|
+
td.r,th.r{text-align:right;font-variant-numeric:tabular-nums}.ok{color:var(--ok);font-weight:700}.no{color:var(--bad);font-weight:700}
|
|
258
|
+
.muted{color:var(--mut)}code{background:color-mix(in srgb,var(--mut) 15%,transparent);padding:1px 6px;border-radius:5px;font-size:12.5px}
|
|
259
|
+
iframe{width:100%;height:560px;border:1px solid var(--line);border-radius:10px;background:var(--card)}
|
|
260
|
+
.btn{display:inline-block;border:1px solid var(--line);border-radius:8px;padding:6px 12px;font-size:13px;color:var(--ink);text-decoration:none;background:var(--card)}
|
|
261
|
+
.btn:hover{border-color:var(--brand)}
|
|
262
|
+
details{margin-top:6px}summary{cursor:pointer;color:var(--brand);font-weight:600}
|
|
263
|
+
.callout{border-left:4px solid var(--brand);background:color-mix(in srgb,var(--brand) 8%,transparent);padding:10px 14px;border-radius:0 8px 8px 0;font-size:14px}
|
|
264
|
+
details>summary{list-style:none}details>summary::-webkit-details-marker{display:none}
|
|
265
|
+
.fold{padding:0}.fold>details{margin:0}.fold>details>summary{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;padding:14px 20px;color:var(--ink)}
|
|
266
|
+
.fold>details>summary::after{content:"Show ▾";color:var(--brand);font-size:13px;font-weight:600;margin-left:auto}.fold>details[open]>summary::after{content:"Hide ▴"}
|
|
267
|
+
.ft{font-weight:700;font-size:16px}.fs{color:var(--mut);font-size:13px;font-weight:400}.fb{padding:0 20px 18px}
|
|
268
|
+
.nav{position:sticky;top:0;z-index:5;display:flex;gap:6px;flex-wrap:wrap;padding:8px 0;margin:-8px 0 14px;background:color-mix(in srgb,var(--bg) 92%,transparent);backdrop-filter:blur(6px)}
|
|
269
|
+
.nav a{border:1px solid var(--line);background:var(--card);border-radius:999px;padding:4px 12px;font-size:13px;color:var(--mut);text-decoration:none}.nav a:hover{color:var(--brand);border-color:var(--brand)}
|
|
270
|
+
html{scroll-behavior:smooth}.flow{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:10px 0}.flow .st{border:1px solid var(--line);border-radius:10px;padding:6px 10px;font-size:13px;background:var(--card)}
|
|
271
|
+
.flow .st.g{border-color:var(--brand);background:color-mix(in srgb,var(--brand) 9%,transparent)}.flow .st.w{border-color:var(--warn);background:color-mix(in srgb,var(--warn) 10%,transparent)}.flow .ar{color:var(--mut)}
|
|
272
|
+
.tabs{display:flex;gap:6px;flex-wrap:wrap;margin:10px 0 8px}.tab{border:1px solid var(--line);background:var(--card);color:var(--mut);border-radius:8px;padding:5px 12px;font:inherit;font-size:13px;cursor:pointer}
|
|
273
|
+
.tab.on{background:var(--brand);border-color:var(--brand);color:#fff}.tp[hidden]{display:none}@media(max-width:900px){.two{grid-template-columns:1fr!important}}
|
|
274
|
+
footer{color:var(--mut);font-size:12.5px;margin-top:26px}
|
|
275
|
+
.views>[hidden],details[hidden]{display:none!important}.nav a[aria-current=page]{background:color-mix(in srgb,var(--brand) 12%,var(--card));color:var(--brand);font-weight:650;border-color:transparent}.nav-icon{display:inline-block;width:23px;font-size:17px}.record-search{display:block;width:100%;padding:10px 12px;border:1px solid var(--line);border-radius:8px;background:var(--card);color:var(--ink);font:inherit;margin:12px 0}.views #memory .grid4{grid-template-columns:repeat(2,minmax(0,1fr))}
|
|
276
|
+
.record{white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px;padding:12px;background:var(--bg);border-radius:8px}
|
|
277
|
+
@media(min-width:1100px){.wrap{max-width:1500px;padding-left:220px;position:relative}.nav{position:fixed;left:max(12px,calc((100vw - 1500px)/2 + 12px));top:24px;width:185px;display:flex;flex-direction:column;gap:7px;margin:0;padding:12px;background:var(--card);border:1px solid var(--line);border-radius:12px}.nav a{border-radius:7px;padding:8px 10px}}
|
|
278
|
+
"""
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _usd(v: float) -> str:
|
|
282
|
+
return f"-${abs(v):.4f}" if v < 0 else f"${v:.4f}"
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _load_ab(project: Project) -> dict | None:
|
|
286
|
+
p = project.gs_dir / "ab.json"
|
|
287
|
+
try:
|
|
288
|
+
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else None
|
|
289
|
+
except Exception:
|
|
290
|
+
return None
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _retrieval_card(project: Project) -> str:
|
|
294
|
+
p = project.gs_dir / "retrieval.json"
|
|
295
|
+
try:
|
|
296
|
+
res = json.loads(p.read_text(encoding="utf-8")) if p.exists() else None
|
|
297
|
+
except Exception:
|
|
298
|
+
res = None
|
|
299
|
+
if not res:
|
|
300
|
+
return ""
|
|
301
|
+
t = res["totals"]
|
|
302
|
+
rows = ""
|
|
303
|
+
for r in res["tasks"]:
|
|
304
|
+
k, h = r["keyword"], r["hybrid"]
|
|
305
|
+
cell = lambda a: ('<span class="badge">found</span>' if a["hit"] else '<span class="badge warn">missed</span>') # noqa: E731
|
|
306
|
+
rows += (f"<tr><td>{e(r['question'][:80])}</td><td class='r'>{cell(k)}</td><td class='r'>{cell(h)}</td>"
|
|
307
|
+
f"<td class='r'>{k['tokens']:,} → {h['tokens']:,}</td></tr>")
|
|
308
|
+
warn = ('<p class="sub" style="color:var(--bad)">Hybrid missed questions that keyword search found: do not ship this model or setting for this repo.</p>'
|
|
309
|
+
if t["lost"] else "")
|
|
310
|
+
body = (f'<p class="sub">Same questions asked of <code>gs_pack</code> twice: keyword only, then keyword + semantic ({e(str(res.get("model")))}). '
|
|
311
|
+
f'Found means every expected symbol or string is in the result. Run <code>graphsnip eval</code> to refresh.</p>'
|
|
312
|
+
f'<div style="overflow:auto"><table><thead><tr><th>Question</th><th class="r">Keyword</th><th class="r">Hybrid</th><th class="r">Tokens returned</th></tr></thead>'
|
|
313
|
+
f'<tbody>{rows}</tbody></table></div>{warn}')
|
|
314
|
+
return _fold("retrieval", "Semantic search: keyword vs hybrid",
|
|
315
|
+
f"found {t['keyword_hits']}/{t['n']} → {t['hybrid_hits']}/{t['n']} · gained {t['gained']}, lost {t['lost']}", body, open_=True)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _signed(v: float, digits: int = 4) -> str:
|
|
319
|
+
return f"-${abs(v):.{digits}f}" if v < 0 else f"${v:.{digits}f}"
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _ab_card(project: Project) -> str:
|
|
323
|
+
ab = _load_ab(project)
|
|
324
|
+
if not ab:
|
|
325
|
+
return ('<section class="card" id="ab"><h2>Measured A/B</h2><p class="sub">Not run yet. <code>graphsnip ab --yes</code> answers your benchmark questions in '
|
|
326
|
+
'headless Claude Code with and without graphsnip and records the <b>real</b> tokens and cost the CLI reports. It spends real usage '
|
|
327
|
+
'(capped; default $5), so it is never run automatically.</p></section>')
|
|
328
|
+
t = ab["totals"]
|
|
329
|
+
kp = "".join([
|
|
330
|
+
_kpi("Measured cost saved" if t["cost_saved"] >= 0 else "Measured cost INCREASE", _signed(abs(t["cost_saved"])),
|
|
331
|
+
f"${t['control_cost']:.4f} → ${t['treat_cost']:.4f} ({abs(t['cost_saved_pct'])}% {'less' if t['cost_saved'] >= 0 else 'more'})", accent=t["cost_saved"] >= 0),
|
|
332
|
+
_kpi("Context tokens saved" if t["context_saved"] >= 0 else "Context tokens increase", n(abs(t["context_saved"])),
|
|
333
|
+
f"{n(t['control_context'])} → {n(t['treat_context'])} ({abs(t['context_saved_pct'])}%)"),
|
|
334
|
+
_kpi("Expected symbols found", f"{t['treat_hits']}/{t['hit_known']}", f"without graphsnip {t['control_hits']}/{t['hit_known']}"),
|
|
335
|
+
_kpi("Runs", n(ab["paired_tasks"] * ab["repeats"] * 2), f"{ab['repeats']} per task per arm · model {ab['model']}"),
|
|
336
|
+
])
|
|
337
|
+
rows = ""
|
|
338
|
+
for r in ab["tasks"]:
|
|
339
|
+
c, g = r["control"], r["treat"]
|
|
340
|
+
if not (c["runs"] and g["runs"]):
|
|
341
|
+
continue
|
|
342
|
+
sv = f"{100 * (c['cost'] - g['cost']) / c['cost']:.0f}%" if c["cost"] else "-"
|
|
343
|
+
tv = lambda a, b: f"{a:g} → {b:g}" if (a or b) else "-" # noqa: E731
|
|
344
|
+
rows += (f"<tr><td>{e(r['question'][:60])}</td><td class='r'>${c['cost']:.4f}</td><td class='r'>${g['cost']:.4f}</td><td class='r'>{sv}</td>"
|
|
345
|
+
f"<td class='r'>{n(c['context'])} → {n(g['context'])}</td><td class='r'>{tv(c.get('turns', 0), g.get('turns', 0))}</td>"
|
|
346
|
+
f"<td class='r'>{n(c.get('cache_creation', 0))} → {n(g.get('cache_creation', 0))}</td><td class='r'>{n(c['output'])} → {n(g['output'])}</td>"
|
|
347
|
+
f"<td class='r'>{c['hits']}/{c['hit_known']} · {g['hits']}/{g['hit_known']}</td></tr>")
|
|
348
|
+
note = (f"<p class='sub'>Real usage and cost reported by <code>claude -p --output-format json</code>, including caching and every turn. Medians over repeats. "
|
|
349
|
+
f"Both arms read-only, same model and prompt, fresh session each run. “Found” only checks the expected symbols appear; the answers are saved in "
|
|
350
|
+
f"<code>{e(str(ab['answers_dir']))}</code> so you can judge quality yourself. Run {e(ab['ts'])}"
|
|
351
|
+
+ (f"; <b>{e(ab['aborted'])}</b>" if ab.get("aborted") else "") + (f"; {ab['failed_runs']} failed run(s) excluded" if ab.get("failed_runs") else "") + ".</p>")
|
|
352
|
+
return (f'<section class="card fold" id="ab"><details open><summary><span class="ft">Measured A/B (real runs)</span>'
|
|
353
|
+
f'<span class="fs">cost ${t["control_cost"]:.2f} → ${t["treat_cost"]:.2f} · {abs(t["cost_saved_pct"])}% {"saved" if t["cost_saved"] >= 0 else "more"}</span></summary><div class="fb">'
|
|
354
|
+
f'<div class="grid4" style="margin-top:6px">{kp}</div>'
|
|
355
|
+
f'<div style="overflow:auto"><table><thead><tr><th>Question</th><th class="r">Without $</th><th class="r">With $</th><th class="r">Saved</th>'
|
|
356
|
+
f'<th class="r">Context tokens</th><th class="r">Turns</th><th class="r">Cache-write tokens</th><th class="r">Output tokens</th><th class="r">Found</th></tr></thead><tbody>{rows}</tbody></table></div>'
|
|
357
|
+
f'<p class="sub">Arrows read without → with graphsnip. If cost is up while context is flat, look at turns, cache-write (billed at a premium for each fresh session) and output.</p>{note}</div></details></section>')
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _routing_card(project: Project, recs: list[dict], price: float) -> str:
|
|
361
|
+
from graphsnip import router, usage
|
|
362
|
+
|
|
363
|
+
cfg = router.config(project)
|
|
364
|
+
rs = router.summarize(recs, cfg)
|
|
365
|
+
firsts = [r.get("ts") for r in recs if r.get("source") in ("agent", "cli") and r.get("ts")]
|
|
366
|
+
u = usage.scan(project.root, cfg, since=min(firsts) if firsts else None)
|
|
367
|
+
mod = lambda c, t: (cfg["models"].get(c) or {}).get(t) or "-" # noqa: E731
|
|
368
|
+
|
|
369
|
+
# ---- explainer (collapsed)
|
|
370
|
+
flow = ('<div class="flow"><span class="st">Task typed in /graphsnip</span><span class="ar">→</span><span class="st">gs_route scores it<br>(wording + graph size)</span>'
|
|
371
|
+
'<span class="ar">→</span><span class="st g">light enough: the cheap model (e.g. Haiku) answers</span></div>'
|
|
372
|
+
'<div class="flow"><span class="st">gs_route says it is too hard</span><span class="ar">→</span>'
|
|
373
|
+
'<span class="st w">prints "Escalating to <model>…"</span><span class="ar">→</span>'
|
|
374
|
+
'<span class="st w">a stronger-model subagent (Sonnet / Opus) does the work</span><span class="ar">→</span><span class="st g">same answer, no re-typing</span></div>')
|
|
375
|
+
status_rows = "".join(f"<tr><td><code>{k}</code></td><td>{v}</td></tr>" for k, v in [
|
|
376
|
+
("routed", "the running tier matched the decision; savings are credited"),
|
|
377
|
+
("escalate", "the pinned light model was too weak, so the task was handed to a stronger one (or stopped, on clients that cannot hand off)"),
|
|
378
|
+
("session", "ran on the session's own model on purpose (/graphsnip-deep); counted as a missed downgrade if a cheaper tier would do"),
|
|
379
|
+
("overpowered", "ran on a stronger tier than needed"),
|
|
380
|
+
("advisory", "decision only; nothing verified which model ran, so no savings are claimed")])
|
|
381
|
+
client_rows = "".join(f"<tr><td>{c}</td><td>{h}</td><td>{v}</td></tr>" for c, h, v in [
|
|
382
|
+
("Claude Code", "<code>/graphsnip</code> pinned to the light model; hard tasks hand off to a Sonnet/Opus subagent automatically", "transcripts (<code>graphsnip usage</code>)"),
|
|
383
|
+
("Copilot (VS Code)", "<code>/graphsnip</code> pinned only if <code>routing.models.copilot.light</code> is set; hard tasks need <code>/graphsnip-deep</code>", "not available"),
|
|
384
|
+
("Codex", "<code>graphsnip codex \"task\"</code> picks the tier and runs <code>codex exec -m <model></code>; the prompt file alone is advisory", "launcher knows the model it passed")])
|
|
385
|
+
tier_rows = "".join(f"<tr><td>{t}</td><td>{e(mod('claude', t))}</td><td>{e(mod('codex', t))}</td><td class='r'>${cfg['prices'][t][0]:g} / ${cfg['prices'][t][1]:g}</td></tr>" for t in router.TIERS)
|
|
386
|
+
explain = _fold_inner("How routing works, statuses and client support",
|
|
387
|
+
flow + '<h2 style="font-size:15px;margin-top:12px">Statuses</h2><table><tbody>' + status_rows + '</tbody></table>'
|
|
388
|
+
'<h2 style="font-size:15px;margin-top:14px">Per client</h2><table><thead><tr><th>Client</th><th>How the model is switched</th><th>Verified by</th></tr></thead><tbody>' + client_rows + '</tbody></table>'
|
|
389
|
+
'<h2 style="font-size:15px;margin-top:14px">Tiers, models and prices used for estimates</h2><table><thead><tr><th>Tier</th><th>Claude model</th><th>Codex model</th><th class="r">$ per M tokens (in / out)</th></tr></thead><tbody>'
|
|
390
|
+
+ tier_rows + '</tbody></table><p class="sub">Prices are editable placeholders (<code>routing.prices</code> in <code>.graphsnip/config.json</code>). '
|
|
391
|
+
'Routing saves dollars per token, not tokens; the token savings above come from the graph alone.</p>')
|
|
392
|
+
|
|
393
|
+
if not rs["decisions"]:
|
|
394
|
+
return ('<section class="card" id="routing"><h2>Model routing</h2><p class="sub">No routing decisions yet. Use <code>/graphsnip</code> in your agent '
|
|
395
|
+
'(or <code>graphsnip route "your task"</code>) and this section fills in.</p>' + explain + '</section>')
|
|
396
|
+
|
|
397
|
+
kp = "".join([
|
|
398
|
+
_kpi("Routing decisions", n(rs["decisions"]), " · ".join(f"{k} {v}" for k, v in rs["by_tier"].items() if v) or "-"),
|
|
399
|
+
_kpi("Ran on a cheaper model", n(rs["routed_cheaper"]), f"{n(rs['tokens_on_cheaper'])} tokens handled by the light tier"),
|
|
400
|
+
_kpi("Est. dollars saved by routing", f"${rs['usd_saved']:.4f}", f"vs running everything on the {cfg['baseline_tier']} tier", accent=True),
|
|
401
|
+
_kpi("Escalations", n(rs["escalations"]), f"{rs['handoffs']} handed to a stronger model automatically"),
|
|
402
|
+
])
|
|
403
|
+
ev = router.events(recs, cfg, 8)
|
|
404
|
+
erows = "".join(
|
|
405
|
+
f"<tr><td class='muted'>{e(x['ts'][5:16].replace('T', ' '))}</td><td>{e(x['client'])}</td><td>{e(str(x['query'])[:55])}</td>"
|
|
406
|
+
f"<td><span class='chip'>{e(x['tier'])}</span></td><td>{e(x['path'])}</td><td class='r'>{_usd(x['saved'])}</td></tr>" for x in ev)
|
|
407
|
+
events = ('<h2 style="font-size:15px;margin-top:4px">What happened, task by task</h2><div style="overflow:auto"><table><thead><tr><th>Time</th><th>Client</th><th>Task</th>'
|
|
408
|
+
f'<th>Router said</th><th>What actually happened</th><th class="r">Est. saved</th></tr></thead><tbody>{erows}</tbody></table></div>'
|
|
409
|
+
f'<p class="sub">Not yet counted as saved: ${rs["usd_potential"]:.4f} from decisions nobody verified or that ran on the session model.</p>')
|
|
410
|
+
meas = ""
|
|
411
|
+
if u:
|
|
412
|
+
mrows = "".join(f"<tr><td>{e('other (synthetic/unknown)' if k == 'other' else k)}</td><td class='r'>{n(v['messages'])}</td><td class='r'>{n(v['input'])}</td>"
|
|
413
|
+
f"<td class='r'>{n(v['output'])}</td><td class='r'>{n(v['cache_read'])}</td><td class='r'>${v['usd']:.2f}</td></tr>"
|
|
414
|
+
for k, v in sorted(u["families"].items(), key=lambda kv: -kv[1]["usd"]))
|
|
415
|
+
span = f"since {e(str(u['since'])[:10])} (first graphsnip call)" if u.get("since") else "all history in this project"
|
|
416
|
+
meas = _fold_inner("Measured: which model actually answered (Claude Code transcripts)",
|
|
417
|
+
f'<p class="sub">{span}. Cost = list-price equivalent for these tokens, <b>not your bill</b> (plans and caching change what you pay). '
|
|
418
|
+
f'Cache-read tokens are billed at 10% of the input price in this estimate.</p>'
|
|
419
|
+
f'<table><thead><tr><th>Model</th><th class="r">Replies</th><th class="r">Input</th><th class="r">Output</th><th class="r">Cache read</th>'
|
|
420
|
+
f'<th class="r">≈ List-price cost</th></tr></thead><tbody>{mrows}</tbody></table>')
|
|
421
|
+
return (f'<section class="card" id="routing"><h2>Model routing</h2><div class="sub">graphsnip scores each task and steers it to the cheapest model tier that can do it. '
|
|
422
|
+
f'Dollars are estimates; savings are counted only when the running model matched the decision.</div>'
|
|
423
|
+
f'<div class="grid4" style="margin-top:12px">{kp}</div>{events}{explain}{meas}</section>')
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _fold_inner(title: str, body: str) -> str:
|
|
427
|
+
return f'<details style="margin-top:12px"><summary>{e(title)}</summary><div style="margin-top:8px">{body}</div></details>'
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _memory_library(project, cfg, include_details):
|
|
432
|
+
if not isinstance(cfg, dict) or cfg.get("enabled") is not True:
|
|
433
|
+
return "<p>Memory disabled.</p>", "<p>Enable memory to inspect skills.</p>"
|
|
434
|
+
if not include_details:
|
|
435
|
+
return "<p>Private records omitted from bundle.</p>", "<p>Private skills omitted from bundle.</p>"
|
|
436
|
+
if not (project.root / ".memory-engine" / "memory" / "memory.db").is_file():
|
|
437
|
+
return "<p>No local memory database yet.</p>", "<p>No local skills yet.</p>"
|
|
438
|
+
from graphsnip.memory_client import MemoryClient, MemoryUnavailable, MemoryRequestError
|
|
439
|
+
client = MemoryClient(project.root)
|
|
440
|
+
try:
|
|
441
|
+
stats = client.request("stats")
|
|
442
|
+
records = client.request("list", limit=100)
|
|
443
|
+
proposals = client.request("proposals")
|
|
444
|
+
eligible = {p["id"] for p in client.request("approvedSkills", context=cfg.get("context", "project"))}
|
|
445
|
+
def detail(title, record):
|
|
446
|
+
return '<details><summary>' + e(title) + '</summary><pre class="record">' + e(json.dumps(record, ensure_ascii=False, indent=2)) + '</pre></details>'
|
|
447
|
+
counts = '<div class="grid4">' + ''.join(_kpi(k.title(), n(stats.get(k, 0))) for k in ("candidate", "verified", "archived")) + '</div>'
|
|
448
|
+
memory = counts + '<p class="sub">Latest 100 records at most; historical data is untrusted.</p>' + ''.join(detail(str(r.get("title", "")) + " · " + str(r.get("status", "")), r) for r in records)
|
|
449
|
+
skills = '<div class="grid4">' + _kpi("Listed proposals", n(len(proposals))) + _kpi("Eligible in current context", n(len(eligible))) + '</div>'
|
|
450
|
+
skills += '<p class="sub">Latest 100 proposals at most. Expand for Markdown, sources and approval evidence.</p>'
|
|
451
|
+
for p in proposals:
|
|
452
|
+
status = p.get("status", "")
|
|
453
|
+
if status == "approved":
|
|
454
|
+
status = "Eligible" if p.get("id") in eligible else "Not eligible in current context / snapshot"
|
|
455
|
+
skills += detail(str(p.get("title", "")) + " · " + str(status), p)
|
|
456
|
+
return memory, skills
|
|
457
|
+
except (MemoryUnavailable, MemoryRequestError, TypeError, KeyError, ValueError, AttributeError):
|
|
458
|
+
return "<p>Memory inventory unavailable.</p>", "<p>Skill inventory unavailable.</p>"
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _memory_evaluation(project):
|
|
462
|
+
path = project.gs_dir / "memory-eval.jsonl"
|
|
463
|
+
if not path.is_file():
|
|
464
|
+
return '<p class="sub">No four-arm results yet. Place externally measured trials in <code>.graphsnip/memory-eval.jsonl</code>. See docs/memory-evaluation.md.</p>'
|
|
465
|
+
try:
|
|
466
|
+
from graphsnip.memory_eval import evaluate
|
|
467
|
+
if path.stat().st_size > 10_000_000:
|
|
468
|
+
raise ValueError("too large")
|
|
469
|
+
report = evaluate([json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()])
|
|
470
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
471
|
+
return '<p>Invalid or incomplete matched evaluation results.</p>'
|
|
472
|
+
arms = report["arms"]
|
|
473
|
+
rows = ''.join(f'<tr><td>{e(k)}</td><td>{n(v["input_tokens"])}</td><td>{n(v["output_tokens"])}</td><td>{v["pass_rate"]:.1%}</td><td>{n(v["latency_ms"])}</td><td>{_usd(v["cost_usd"])}</td></tr>' for k,v in arms.items())
|
|
474
|
+
delta = sum(arms["graph"][k] - arms["combined"][k] for k in ("input_tokens", "output_tokens"))
|
|
475
|
+
return (f'<p class="sub">{n(report["matched_trials"])} matched trials · mean per run · externally supplied measurements</p>'
|
|
476
|
+
+ _kpi("Incremental memory token difference", n(delta), "Graph-only minus combined; negative means more tokens")
|
|
477
|
+
+ '<div style="overflow:auto"><table><thead><tr><th>Arm</th><th>Input</th><th>Output</th><th>Pass rate</th><th>Latency ms</th><th>Cost USD</th></tr></thead><tbody>'
|
|
478
|
+
+ rows + '</tbody></table></div><p class="sub">' + e(report["note"]) + '</p>')
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _memory_curve(recs):
|
|
482
|
+
days = {}
|
|
483
|
+
for row in recs:
|
|
484
|
+
if row.get("kind") != "memory" or row.get("source") not in {"agent", "cli", "shell"}:
|
|
485
|
+
continue
|
|
486
|
+
day = str(row.get("ts", ""))[:10]
|
|
487
|
+
if len(day) == 10:
|
|
488
|
+
days[day] = days.get(day, 0) + int(row.get("included", 0))
|
|
489
|
+
points = sorted(days.items())[-30:]
|
|
490
|
+
if not points:
|
|
491
|
+
return '<p class="sub">No memory usage recorded yet.</p>'
|
|
492
|
+
peak = max(1, max(v for _, v in points))
|
|
493
|
+
coords = [(45 + 650*i/max(1,len(points)-1), 180-150*v/peak) for i,(_,v) in enumerate(points)]
|
|
494
|
+
line = " ".join(f"{x:.1f},{y:.1f}" for x,y in coords)
|
|
495
|
+
grid = "".join(f'<line x1="45" x2="695" y1="{y}" y2="{y}" class="grid"/>' for y in (30,80,130,180))
|
|
496
|
+
dots = "".join(f'<circle cx="{x}" cy="{y}" r="4" fill="var(--brand)"><title>{e(day)}: {v} inclusions</title></circle>' for (x,y),(day,v) in zip(coords,points))
|
|
497
|
+
return ('<div class="card"><h2>Memory utilization over time</h2><p class="sub">Daily memory inclusions · latest 30 recorded days</p>'
|
|
498
|
+
f'<svg class="chart" viewBox="0 0 740 215" role="img" aria-label="Daily memory inclusions">{grid}'
|
|
499
|
+
f'<text x="4" y="34" class="axis">{peak}</text><text x="4" y="184" class="axis">0</text>'
|
|
500
|
+
f'<polygon points="45,180 {line} {coords[-1][0]},180" class="area"/><polyline points="{line}" class="l-ret" fill="none"/>{dots}'
|
|
501
|
+
f'<text x="45" y="205" class="axis">{e(points[0][0])}</text><text x="695" y="205" text-anchor="end" class="axis">{e(points[-1][0])}</text></svg></div>')
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
APP_JS = """<script>
|
|
505
|
+
(function(){
|
|
506
|
+
const nav=document.querySelector('.nav'), main=document.querySelector('.views');
|
|
507
|
+
if(!nav||!main)return;
|
|
508
|
+
const groups={top:['top','method'],graph:['graph','retrieval'],tokens:['tokens','recent'],routing:['routing'],memory:['memory'],skills:['skills'],evaluations:['evaluations','ab','benchmark']};
|
|
509
|
+
const links=Array.from(nav.querySelectorAll('a'));
|
|
510
|
+
function show(){
|
|
511
|
+
const hash=location.hash.slice(1)||'top';
|
|
512
|
+
const key=Object.keys(groups).find(k=>groups[k].includes(hash))||'top';
|
|
513
|
+
Array.from(main.children).forEach(el=>{el.hidden=!groups[key].includes(el.id);});
|
|
514
|
+
links.forEach(a=>{if(a.hash==='#'+key)a.setAttribute('aria-current','page');else a.removeAttribute('aria-current');});
|
|
515
|
+
window.scrollTo(0,0);
|
|
516
|
+
}
|
|
517
|
+
window.addEventListener('hashchange',show);show();
|
|
518
|
+
['memory','skills'].forEach(id=>{
|
|
519
|
+
const panel=document.getElementById(id);if(!panel)return;
|
|
520
|
+
const records=Array.from(panel.querySelectorAll('details')).filter(d=>d.querySelector('.record'));
|
|
521
|
+
if(!records.length)return;
|
|
522
|
+
const input=document.createElement('input');input.type='search';input.placeholder='Search '+(id==='memory'?'memories':'skills');input.setAttribute('aria-label',input.placeholder);input.className='record-search';
|
|
523
|
+
records[0].before(input);
|
|
524
|
+
input.addEventListener('input',()=>{const q=input.value.toLowerCase();records.forEach(d=>{d.hidden=!d.textContent.toLowerCase().includes(q);});});
|
|
525
|
+
});
|
|
526
|
+
})();
|
|
527
|
+
</script>"""
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def build_html(project: Project, graph_href: str, include_details: bool = True) -> str:
|
|
531
|
+
cfg = project.config()
|
|
532
|
+
price = float(cfg.get("price_per_mtok", 3.0))
|
|
533
|
+
recs = _ledger.Ledger(project.gs_dir).read()
|
|
534
|
+
live = _ledger.summarize(recs, price, sources={"agent", "cli", "shell"})
|
|
535
|
+
mem = _ledger.summarize_memory(recs, sources={"agent", "cli", "shell"})
|
|
536
|
+
inventory, skills = _memory_library(project, cfg.get("memory"), include_details)
|
|
537
|
+
memory_card = (
|
|
538
|
+
'<section class="card" id="memory"><h2>Memory Engine</h2>'
|
|
539
|
+
'<p class="sub">Observed retrieval and context overhead, not causal token savings.</p>'
|
|
540
|
+
'<div class="grid4">'
|
|
541
|
+
+ _kpi("Retrieval attempts", n(mem["attempts"]), f'{mem["successful"]} successful')
|
|
542
|
+
+ _kpi("Packs with memory", n(mem["packs_with_memory"]))
|
|
543
|
+
+ _kpi("Memory inclusions", n(mem["included"]), f'{mem["retrieved"]} retrieved')
|
|
544
|
+
+ _kpi("Approved skill inclusions", n(mem["skills_included"]), f'{mem["packs_with_skills"]} packs')
|
|
545
|
+
+ _kpi("Context overhead", n(mem["tokens"]), "Additional estimated tokens")
|
|
546
|
+
+ '</div><p class="sub">'
|
|
547
|
+
+ f'Unavailable: {mem["unavailable"]} · Rejected: {mem["rejected"]}</p>' + _memory_curve(recs) + inventory + '</section>'
|
|
548
|
+
)
|
|
549
|
+
bench_s = _ledger.summarize(recs, price, sources={"bench"})
|
|
550
|
+
bench = None
|
|
551
|
+
bp = project.gs_dir / "bench.json"
|
|
552
|
+
if bp.exists():
|
|
553
|
+
try:
|
|
554
|
+
bench = json.loads(bp.read_text(encoding="utf-8"))
|
|
555
|
+
except Exception:
|
|
556
|
+
bench = None
|
|
557
|
+
stats = project.graph_stats() if project.has_graph() else {}
|
|
558
|
+
top = project.top_symbols(8) if project.has_graph() else []
|
|
559
|
+
|
|
560
|
+
# headline: live usage if there is any, else the benchmark
|
|
561
|
+
if live["calls"]:
|
|
562
|
+
head, head_label, head_cls = live, "Live usage (agents + CLI)", ""
|
|
563
|
+
else:
|
|
564
|
+
head, head_label, head_cls = bench_s, "Benchmark run (no live agent usage recorded yet)", " warn"
|
|
565
|
+
|
|
566
|
+
kpis = [
|
|
567
|
+
_kpi("Tokens saved", n(head["saved"]), f"{n(head['returned'])} returned vs {n(head['baseline'])} baseline", accent=True),
|
|
568
|
+
_kpi("Reduction", f"{head['pct']}%", f"{head['ratio']}× fewer tokens" if head["ratio"] else ""),
|
|
569
|
+
_kpi("Est. input cost saved", f"${head['usd_saved']:.2f}", f"list-price estimate at ${price:g}/M, one-off, input only"),
|
|
570
|
+
_kpi("Tool calls", n(head["calls"]), f"{head['deduped']} duplicate reads suppressed" if head["deduped"] else "priced individually"),
|
|
571
|
+
]
|
|
572
|
+
ab = _load_ab(project)
|
|
573
|
+
if ab:
|
|
574
|
+
at = ab["totals"]
|
|
575
|
+
pos = at["cost_saved"] >= 0
|
|
576
|
+
kpis.append(_kpi("Measured cost saved (A/B)" if pos else "Measured cost INCREASE (A/B)", _signed(abs(at["cost_saved"]), 2),
|
|
577
|
+
f"{abs(at['cost_saved_pct'])}% {'less' if pos else 'more'} · real runs, {ab['paired_tasks']} tasks × {ab['repeats']}", accent=pos))
|
|
578
|
+
if bench:
|
|
579
|
+
t = bench["totals"]
|
|
580
|
+
kpis.append(_kpi("Answered correctly", f"{t['answered']}/{t['tasks']}", "benchmark tasks with expected symbol + source"))
|
|
581
|
+
|
|
582
|
+
chips = []
|
|
583
|
+
if stats:
|
|
584
|
+
chips += [f'<span class="chip"><b>{n(stats["nodes"])}</b> nodes</span>', f'<span class="chip"><b>{n(stats["edges"])}</b> edges</span>',
|
|
585
|
+
f'<span class="chip"><b>{n(stats["communities"])}</b> communities</span>',
|
|
586
|
+
f'<span class="chip"><b>{n(stats["symbols"])}</b> code symbols</span>']
|
|
587
|
+
if stats.get("built_at_commit"):
|
|
588
|
+
chips.append(f'<span class="chip">commit <b>{e(str(stats["built_at_commit"])[:8])}</b></span>')
|
|
589
|
+
|
|
590
|
+
sections = []
|
|
591
|
+
bench_parts: list[str] = []
|
|
592
|
+
|
|
593
|
+
# --- approach comparison (benchmark)
|
|
594
|
+
if bench:
|
|
595
|
+
t = bench["totals"]
|
|
596
|
+
items = [
|
|
597
|
+
("grep + read files", t["naive_tokens"], "b-grep", "no graph"),
|
|
598
|
+
("Graphify + read files", t["graphify_read_tokens"], "b-gfyread", "map, then read whole files"),
|
|
599
|
+
("Graphify query alone", t["graphify_tokens"], "b-gfy", "map only, no source code"),
|
|
600
|
+
("graphsnip", t["graphsnip_tokens"], "b-cg", f"{t['answered']}/{t['tasks']} answered with code"),
|
|
601
|
+
]
|
|
602
|
+
bench_parts.append(
|
|
603
|
+
f'<h2>Same questions, four approaches</h2>'
|
|
604
|
+
f'<div class="sub">{t["tasks"]} tasks on this repo · tokens an agent would put in context · baseline: {e(bench["baseline_definition"])}</div>'
|
|
605
|
+
f'<div style="margin-top:12px">{_bars(items)}</div>'
|
|
606
|
+
f'<div class="callout" style="margin-top:12px"><b>{t["saved_pct"]}% fewer tokens</b> than grep + read, and '
|
|
607
|
+
f'<b>{t["saved_vs_graphify_read_pct"]}% fewer</b> than using Graphify alone and then reading the files it points to. '
|
|
608
|
+
f'Graphify\'s query is cheaper still, but it returns a map without source code, so the agent has to read files afterwards. '
|
|
609
|
+
f'graphsnip returns the exact code in the same step.</div>')
|
|
610
|
+
|
|
611
|
+
# --- timeline + by tool
|
|
612
|
+
tl_src = head["timeline"]
|
|
613
|
+
by_tool = head["by_tool"]
|
|
614
|
+
rows = "".join(
|
|
615
|
+
f'<tr><td><code>{e(tool)}</code></td><td class="r">{n(v["calls"])}</td><td class="r">{n(v["returned"])}</td>'
|
|
616
|
+
f'<td class="r">{n(v["baseline"])}</td><td class="r">{(100 * (v["baseline"] - v["returned"]) / v["baseline"]) if v["baseline"] else 0:.0f}%</td></tr>'
|
|
617
|
+
for tool, v in sorted(by_tool.items(), key=lambda kv: -(kv[1]["baseline"] - kv[1]["returned"])))
|
|
618
|
+
sections.append(
|
|
619
|
+
f'<div id="tokens" class="two" style="grid-template-columns:1.5fr 1fr">{_chart_card(head, head_label, bench)}'
|
|
620
|
+
f'<section class="card"><h2>By tool</h2><div class="sub">where the savings come from</div>'
|
|
621
|
+
f'<table style="margin-top:8px"><thead><tr><th>Tool</th><th class="r">Calls</th><th class="r">Returned</th><th class="r">Baseline</th><th class="r">Saved</th></tr></thead>'
|
|
622
|
+
f'<tbody>{rows or "<tr><td colspan=5 class=muted>No calls recorded yet.</td></tr>"}</tbody></table>'
|
|
623
|
+
f'<p class="sub" style="margin-top:10px">Hook activity: {e(", ".join(f"{k} ×{v}" for k, v in head["hooks"].items()) or "none yet")}</p></section></div>')
|
|
624
|
+
|
|
625
|
+
# --- per task table
|
|
626
|
+
if bench:
|
|
627
|
+
trs = ""
|
|
628
|
+
for r in bench["tasks"]:
|
|
629
|
+
saved = f"{100 * (1 - r['graphsnip_tokens'] / r['naive_tokens']):.0f}%" if r["naive_tokens"] and r["graphsnip_tokens"] else "-"
|
|
630
|
+
trs += (f'<tr><td>{e(r["question"])}</td><td><span class="chip">{e(r["type"])}</span></td><td class="r">{n(r["naive_tokens"])}</td>'
|
|
631
|
+
f'<td class="r">{n(r["graphify_read_tokens"])}</td><td class="r">{n(r["graphsnip_tokens"])}</td><td class="r">{saved}</td>'
|
|
632
|
+
f'<td class="{"ok" if r["graphsnip_hit"] else "no"}">{"✓" if r["graphsnip_hit"] else "✗"}</td></tr>')
|
|
633
|
+
bench_parts.append(
|
|
634
|
+
f'<h2 style="margin-top:18px">Benchmark tasks</h2><div class="sub">edit <code>.graphsnip/tasks.json</code> to use your own questions · '
|
|
635
|
+
f're-run <code>graphsnip bench</code></div>'
|
|
636
|
+
f'<div style="overflow:auto"><table style="margin-top:8px"><thead><tr><th>Question</th><th>Type</th><th class="r">grep + read</th>'
|
|
637
|
+
f'<th class="r">Graphify + read</th><th class="r">graphsnip</th><th class="r">Saved</th><th>OK</th></tr></thead><tbody>{trs}</tbody></table></div>')
|
|
638
|
+
|
|
639
|
+
# --- recent calls
|
|
640
|
+
if live["recent"]:
|
|
641
|
+
trs = "".join(
|
|
642
|
+
f'<tr><td><code>{e(r.get("tool", ""))}</code></td><td>{e(str(r.get("query", ""))[:90])}</td><td class="r">{n(r.get("returned"))}</td>'
|
|
643
|
+
f'<td class="r">{n(r.get("baseline"))}</td><td class="r">{(100 * (1 - r.get("returned", 0) / r["baseline"])) if r.get("baseline") else 0:.0f}%</td></tr>'
|
|
644
|
+
for r in live["recent"])
|
|
645
|
+
sections.append(_fold("recent", "Recent live calls", f"last {len(live['recent'])} tool calls",
|
|
646
|
+
f'<div style="overflow:auto"><table style="margin-top:8px"><thead><tr><th>Tool</th><th>Query</th>'
|
|
647
|
+
f'<th class="r">Returned</th><th class="r">Baseline</th><th class="r">Saved</th></tr></thead><tbody>{trs}</tbody></table></div>'))
|
|
648
|
+
|
|
649
|
+
# --- graph
|
|
650
|
+
hub_rows = "".join(
|
|
651
|
+
f'<tr><td><code>{e(str(t["label"]))}</code></td><td class="muted">{e(str(t["file"]))}:{t["line"]}</td><td class="r">{t["degree"]}</td></tr>' for t in top)
|
|
652
|
+
langs = ", ".join(f"{e(k)} ×{n(v)}" for k, v in (stats.get("languages") or {}).items())
|
|
653
|
+
graph_card = (
|
|
654
|
+
f'<section class="card" id="graph"><div style="display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;align-items:center">'
|
|
655
|
+
f'<div><h2>Knowledge graph (Graphify)</h2><div class="sub">every node is a symbol; colours are detected communities; click and drag to explore</div></div>'
|
|
656
|
+
f'<a class="btn" href="{e(graph_href)}" target="_blank" rel="noopener">Open full screen ↗</a></div>'
|
|
657
|
+
f'<div style="margin-top:12px"><iframe src="{e(graph_href)}" title="Graphify knowledge graph" loading="lazy"></iframe></div>'
|
|
658
|
+
f'<p class="sub">If the frame is blank, open it full screen. The graph file is <code>graphify-out/graph.html</code>.</p>'
|
|
659
|
+
f'<div class="two" style="margin-top:8px"><div><h2 style="font-size:15px">Most connected symbols</h2><table><thead><tr><th>Symbol</th><th>Where</th><th class="r">Links</th></tr></thead>'
|
|
660
|
+
f'<tbody>{hub_rows}</tbody></table></div>'
|
|
661
|
+
f'<div><h2 style="font-size:15px">Index</h2><p class="sub">Languages: {langs or "-"}</p>'
|
|
662
|
+
f'<p class="sub">Built by Graphify (tree-sitter AST, no LLM, nothing left this machine). Report: <code>graphify-out/GRAPH_REPORT.md</code></p></div></div></section>')
|
|
663
|
+
if bench_parts:
|
|
664
|
+
bt = bench["totals"]
|
|
665
|
+
sections.append(_fold("benchmark", "Benchmark (offline, same questions on this repo)",
|
|
666
|
+
f"{bt['tasks']} tasks · {bt['saved_pct']}% fewer tokens than grep + read · {bt['answered']}/{bt['tasks']} answered with code",
|
|
667
|
+
"".join(bench_parts)))
|
|
668
|
+
sections.insert(1, _routing_card(project, recs, price)) # right after the tokens/by-tool row
|
|
669
|
+
sections.insert(2, _ab_card(project))
|
|
670
|
+
rc = _retrieval_card(project)
|
|
671
|
+
nav_sem = '<a href="#retrieval">Semantic</a>' if rc else ""
|
|
672
|
+
if rc:
|
|
673
|
+
sections.insert(3, rc)
|
|
674
|
+
sections.append(graph_card)
|
|
675
|
+
sections.append(memory_card)
|
|
676
|
+
sections.append('<section class="card" id="skills"><h2>Skills Library</h2>' + skills + '</section>')
|
|
677
|
+
sections.append('<section class="card" id="evaluations"><h2>Memory effectiveness evaluation</h2>' + _memory_evaluation(project) + '</section>')
|
|
678
|
+
|
|
679
|
+
sections.append(
|
|
680
|
+
'<section class="card fold" id="method"><details><summary>How these numbers are measured</summary>'
|
|
681
|
+
'<p><b>Baseline.</b> For each call, graphsnip prices what an agent without the graph would realistically do: grep the question\'s terms and read the '
|
|
682
|
+
'top 8 matching files in full (symbol reads are priced against reading the whole file). This is deliberately conservative: it is far less than '
|
|
683
|
+
'"read the whole repo", the number Graphify\'s own benchmark compares against.</p>'
|
|
684
|
+
f'<p><b>Tokens.</b> {e(method())}. Install <code>graphsnip[accurate]</code> for exact cl100k counts; absolute numbers shift a little, ratios barely move.</p>'
|
|
685
|
+
'<p><b>Not counted.</b> Savings are counted once per call. In a real session, tokens that stay in context are re-sent on every later turn, so the real saving compounds; '
|
|
686
|
+
'this dashboard does not claim that. Shell-output savings (<code>graphsnip run</code>) are exact: raw vs compressed.</p>'
|
|
687
|
+
'<p><b>Quality.</b> A benchmark task counts as answered only if the expected symbol appears with its source code in the output.</p>'
|
|
688
|
+
'</details></section>')
|
|
689
|
+
|
|
690
|
+
now = datetime.now().strftime("%Y-%m-%d %H:%M")
|
|
691
|
+
return (f'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
|
692
|
+
f'<title>graphsnip dashboard</title><style>{CSS}</style></head><body><div class="wrap">'
|
|
693
|
+
f'<header><div class="brand"><div class="logo">cg</div><div><h1>graphsnip <span class="badge{head_cls}">{e(head_label)}</span></h1>'
|
|
694
|
+
f'<div class="sub">{e(project.root.name)} · generated {now} · v{__version__}</div></div></div><div class="chips">{"".join(chips)}</div></header>'
|
|
695
|
+
f'<nav class="nav" aria-label="Dashboard sections"><a href="#top"><span class="nav-icon" aria-hidden="true">▦</span>Overview</a><a href="#graph"><span class="nav-icon" aria-hidden="true">◇</span>Knowledge Graph</a><a href="#tokens"><span class="nav-icon" aria-hidden="true">▥</span>Token Analytics</a><a href="#routing"><span class="nav-icon" aria-hidden="true">⇄</span>Model Routing</a><a href="#memory"><span class="nav-icon" aria-hidden="true">◎</span>Memory Engine</a><a href="#skills"><span class="nav-icon" aria-hidden="true">▤</span>Skills Library</a><a href="#evaluations"><span class="nav-icon" aria-hidden="true">⚗</span>Evaluations</a></nav>'
|
|
696
|
+
f'<main class="views"><div class="grid4" id="top">{"".join(kpis)}</div>{"".join(sections)}</main>'
|
|
697
|
+
f'<footer>graphsnip is a companion layer on top of Graphify. Graph, communities and AST extraction are Graphify\'s; graphsnip adds symbol-level retrieval, '
|
|
698
|
+
f'context packs, hooks, MCP, and this honest accounting.</footer></div>{TAB_JS}{APP_JS}</body></html>')
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
_VIS_VERSION = "9.1.6"
|
|
702
|
+
_VIS_URLS = [f"https://unpkg.com/vis-network@{_VIS_VERSION}/standalone/umd/vis-network.min.js"]
|
|
703
|
+
_VIS_TGZ = f"https://registry.npmjs.org/vis-network/-/vis-network-{_VIS_VERSION}.tgz"
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def ensure_vis(project: Project) -> Path | None:
|
|
707
|
+
"""Cache vis-network locally so graph.html works offline (Graphify's graph.html loads it from a CDN)."""
|
|
708
|
+
import io
|
|
709
|
+
import tarfile
|
|
710
|
+
import urllib.request
|
|
711
|
+
|
|
712
|
+
dest = project.gs_dir / "vendor" / "vis-network.min.js"
|
|
713
|
+
if dest.exists() and dest.stat().st_size > 100_000:
|
|
714
|
+
return dest
|
|
715
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
716
|
+
for url in _VIS_URLS:
|
|
717
|
+
try:
|
|
718
|
+
data = urllib.request.urlopen(url, timeout=20).read()
|
|
719
|
+
if len(data) > 100_000:
|
|
720
|
+
dest.write_bytes(data)
|
|
721
|
+
return dest
|
|
722
|
+
except Exception:
|
|
723
|
+
continue
|
|
724
|
+
try: # npm registry tarball (same file, different host)
|
|
725
|
+
raw = urllib.request.urlopen(_VIS_TGZ, timeout=40).read()
|
|
726
|
+
with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as tf:
|
|
727
|
+
m = tf.extractfile("package/standalone/umd/vis-network.min.js")
|
|
728
|
+
if m:
|
|
729
|
+
dest.write_bytes(m.read())
|
|
730
|
+
return dest
|
|
731
|
+
except Exception:
|
|
732
|
+
pass
|
|
733
|
+
return None
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def _offline_graph(project: Project, out_dir: Path) -> bool:
|
|
737
|
+
"""Write graph.html next to the dashboard with vis-network loaded locally. False if it had to keep the CDN."""
|
|
738
|
+
import re
|
|
739
|
+
|
|
740
|
+
if not project.graph_html.exists():
|
|
741
|
+
return False
|
|
742
|
+
src = project.graph_html.read_text(encoding="utf-8", errors="replace")
|
|
743
|
+
vis = ensure_vis(project)
|
|
744
|
+
if vis is None:
|
|
745
|
+
(out_dir / "graph.html").write_text(src, encoding="utf-8")
|
|
746
|
+
return False
|
|
747
|
+
shutil.copy2(vis, out_dir / "vis-network.min.js")
|
|
748
|
+
src = re.sub(r'<script src="https://unpkg\.com/vis-network[^>]*>\s*</script>',
|
|
749
|
+
'<script src="vis-network.min.js"></script>', src, count=1, flags=re.S)
|
|
750
|
+
(out_dir / "graph.html").write_text(src, encoding="utf-8")
|
|
751
|
+
return True
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def write_dashboard(project: Project, bundle: str | None = None) -> Path:
|
|
755
|
+
project.gs_dir.mkdir(parents=True, exist_ok=True)
|
|
756
|
+
out_dir = Path(bundle).resolve() if bundle else project.gs_dir
|
|
757
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
758
|
+
offline = _offline_graph(project, out_dir)
|
|
759
|
+
if project.graph_html.exists() and not offline:
|
|
760
|
+
import sys
|
|
761
|
+
|
|
762
|
+
sys.stderr.write("[graphsnip] note: could not cache vis-network; graph.html will need internet to render.\n")
|
|
763
|
+
out = out_dir / "dashboard.html"
|
|
764
|
+
out.write_text(build_html(project, "graph.html", include_details=bundle is None), encoding="utf-8")
|
|
765
|
+
return out
|