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/cli.py ADDED
@@ -0,0 +1,591 @@
1
+ """graphsnip command line."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import importlib.metadata as md
6
+ import json
7
+ import shutil
8
+ import os
9
+ import sys
10
+ import webbrowser
11
+
12
+ from graphsnip import __version__
13
+ from graphsnip import ledger as _ledger
14
+ from graphsnip.engine import Engine, Result
15
+ from graphsnip.project import GraphError, Project
16
+
17
+
18
+ def _common() -> argparse.ArgumentParser:
19
+ c = argparse.ArgumentParser(add_help=False)
20
+ c.add_argument("--root", default=".", help="project root (default: current directory)")
21
+ return c
22
+
23
+
24
+ def _emit(r: Result, quiet: bool = False) -> int:
25
+ print(r.text)
26
+ if r.ok and not quiet:
27
+ pct = f"{100 * (1 - r.returned / r.baseline):.0f}%" if r.baseline else "n/a"
28
+ note = " (duplicate, suppressed)" if r.deduped else ""
29
+ sys.stderr.write(f"\n[graphsnip] ~{r.returned:,} tokens returned vs ~{r.baseline:,} for grep+read → saved {pct}{note}\n")
30
+ return 0 if r.ok else 1
31
+
32
+
33
+ def cmd_build(a) -> int:
34
+ p = Project(a.root)
35
+ if not p.try_lock():
36
+ print("Another graphsnip refresh is running; waiting for it to finish...")
37
+ p.wait_unlocked(900.0)
38
+ if p.has_graph() and not a.force:
39
+ s = p.graph_stats()
40
+ print(f"Graph is up to date: {s['nodes']:,} nodes, {s['edges']:,} edges, {s['symbols']:,} code symbols.")
41
+ return 0
42
+ if not p.try_lock():
43
+ print("Could not take the refresh lock; try again.")
44
+ return 1
45
+ try:
46
+ s = p.build(force=a.force)
47
+ finally:
48
+ p.unlock()
49
+ print(f"Graph ready ({s['mode']}, {s['seconds']}s): {s['nodes']:,} nodes, {s['edges']:,} edges, "
50
+ f"{s['communities']:,} communities, {s['symbols']:,} code symbols.")
51
+ print(f" map: {p.graph_html}")
52
+ print(f" report: {p.report_md}")
53
+ return 0
54
+
55
+
56
+ def cmd_embed(a) -> int:
57
+ from graphsnip import semantic
58
+
59
+ p = Project(a.root)
60
+ if a.status:
61
+ st = semantic.status(p)
62
+ if not st["present"]:
63
+ print("No semantic index yet. Build one with `graphsnip embed` (needs: pip install 'graphsnip[semantic]').")
64
+ return 0
65
+ pend = "unknown" if st["pending"] is None else f"{st['pending']:,}"
66
+ print(f"Semantic index: {st['count']:,} symbols, model {st['model']} ({st['dim']} dims), {pend} symbols waiting to be re-embedded.")
67
+ return 0
68
+ if not p.try_lock():
69
+ print("Another graphsnip refresh is running; waiting for it to finish...")
70
+ p.wait_unlocked(900.0)
71
+ else:
72
+ p.unlock()
73
+ p.ensure_graph(True)
74
+ try:
75
+ emb = semantic.get_embedder(p)
76
+ except semantic.SemanticUnavailable as e:
77
+ print(str(e))
78
+ return 1
79
+
80
+ def prog(done, total):
81
+ if total:
82
+ print(f"\r embedding {done:,}/{total:,}", end="", flush=True)
83
+
84
+ r = semantic.refresh(p, emb, force=a.force, progress=prog)
85
+ if r["embedded"]:
86
+ print()
87
+ print(f"Semantic index ready: {r['total']:,} symbols ({r['embedded']:,} embedded, {r['reused']:,} reused, "
88
+ f"{r['removed']:,} removed) with {r['model']} in {r['seconds']}s.")
89
+ print(f" stored in {semantic.sem_dir(p)} (derived data; safe to delete)")
90
+ return 0
91
+
92
+
93
+ def cmd_eval(a) -> int:
94
+ from graphsnip import retrieval, semantic
95
+
96
+ try:
97
+ res = retrieval.run_eval(a.root, a.tasks)
98
+ except semantic.SemanticUnavailable as e:
99
+ print(str(e))
100
+ return 1
101
+ print(retrieval.format_table(res))
102
+ print(" saved: .graphsnip/retrieval.json (the dashboard shows it)")
103
+ return 0
104
+
105
+
106
+ def cmd_status(a) -> int:
107
+ p = Project(a.root)
108
+ if not p.has_graph():
109
+ print("No graph yet. Run `graphsnip build` or `graphsnip init`.")
110
+ return 1
111
+ s = p.graph_stats()
112
+ print(f"Project: {p.root}")
113
+ print(f"Graph: {s['nodes']:,} nodes · {s['edges']:,} edges · {s['communities']:,} communities · {s['symbols']:,} code symbols")
114
+ ch = p.changes()
115
+ if ch and (ch["added"] or ch["modified"] or ch["deleted"]):
116
+ print(f"Stale: yes, {len(ch['modified'])} modified, {len(ch['added'])} added, {len(ch['deleted'])} deleted "
117
+ f"(run `graphsnip build`; the server refreshes automatically)")
118
+ else:
119
+ print(f"Stale: {'yes, run `graphsnip build` (the server refreshes automatically)' if p.is_stale(0) else 'no'}")
120
+ if p.refreshing():
121
+ print("Refresh: running now")
122
+ print(f"Mode: {p.config()['mode']}")
123
+ return 0
124
+
125
+
126
+ def cmd_find(a) -> int:
127
+ return _emit(Engine(a.root, source="cli").find(a.question, budget=a.budget, depth=a.depth), a.quiet)
128
+
129
+
130
+ def cmd_symbol(a) -> int:
131
+ return _emit(Engine(a.root, source="cli").symbol(a.name, max_lines=a.max_lines, docs="full" if a.full_docs else "short"), a.quiet)
132
+
133
+
134
+ def cmd_pack(a) -> int:
135
+ return _emit(Engine(a.root, source="cli").pack(a.task, budget=a.budget), a.quiet)
136
+
137
+
138
+ def cmd_impact(a) -> int:
139
+ return _emit(Engine(a.root, source="cli").impact(a.name, depth=a.depth), a.quiet)
140
+
141
+
142
+ def cmd_outline(a) -> int:
143
+ return _emit(Engine(a.root, source="cli").outline(a.path), a.quiet)
144
+
145
+
146
+ def cmd_stats(a) -> int:
147
+ p = Project(a.root)
148
+ recs = _ledger.Ledger(p.gs_dir).read()
149
+ price = float(p.config().get("price_per_mtok", 3.0))
150
+ if a.json:
151
+ print(json.dumps({"live": _ledger.summarize(recs, price, {"agent", "cli", "shell"}),
152
+ "bench": _ledger.summarize(recs, price, {"bench"})}, indent=2, default=str))
153
+ return 0
154
+ for title, src in (("Live usage (agents + CLI + shell)", {"agent", "cli", "shell"}), ("Benchmark", {"bench"})):
155
+ s = _ledger.summarize(recs, price, src)
156
+ print(f"\n{title}")
157
+ if not s["calls"]:
158
+ print(" nothing recorded yet")
159
+ continue
160
+ print(f" {s['calls']} calls · {s['returned']:,} tokens returned vs {s['baseline']:,} baseline")
161
+ print(f" saved {s['saved']:,} tokens ({s['pct']}%, {s['ratio']}x) ≈ ${s['usd_saved']} at ${price:g}/M input tokens")
162
+ for tool, t in sorted(s["by_tool"].items(), key=lambda kv: -(kv[1]["baseline"] - kv[1]["returned"])):
163
+ print(f" {tool:<8} {t['calls']:>4} calls {t['returned']:>9,} vs {t['baseline']:>10,}")
164
+ if s["hooks"]:
165
+ print(" hooks: " + ", ".join(f"{k} ×{v}" for k, v in s["hooks"].items()))
166
+ from graphsnip import router
167
+
168
+ rs = router.summarize(recs, router.config(p))
169
+ if rs["decisions"]:
170
+ print(f"\nRouting\n {rs['decisions']} decisions · tiers {rs['by_tier']} · status {rs['by_status']}")
171
+ print(f" routed (verified match): {rs['routed']} · on a cheaper tier: {rs['routed_cheaper']} ({rs['tokens_on_cheaper']:,} tokens)")
172
+ print(f" est. dollars saved by routing: ${rs['usd_saved']} (+ ${rs['usd_potential']} potential from advisory-only decisions)")
173
+ return 0
174
+
175
+
176
+ def cmd_route(a) -> int:
177
+ r = Engine(a.root, source="cli").route(a.task, client=a.client, running_tier=a.running)
178
+ print(r.text)
179
+ return 0
180
+
181
+
182
+ def cmd_codex(a) -> int:
183
+ """Route a task, then launch `codex exec -m <model>` on the chosen tier. Unlike a prompt file this really switches the model."""
184
+ import subprocess
185
+
186
+ from graphsnip import router
187
+
188
+ p = Project(a.root)
189
+ cfg = router.config(p)
190
+ eng = Engine(a.root, source="cli")
191
+ task = " ".join(a.task)
192
+ r = router.decide(task, cfg=cfg) # quick wording-only decision; the full graph-aware route is logged below
193
+ models = cfg["models"].get("codex") or {}
194
+ tier = a.tier or r.tier
195
+ model = models.get(tier)
196
+ res = eng.route(task, client="codex", running_tier="auto" if model else "session")
197
+ print(res.text, file=sys.stderr)
198
+ if not model:
199
+ print(f"[graphsnip] no Codex model configured for tier '{tier}'. Set routing.models.codex.{tier} in .graphsnip/config.json "
200
+ f"(any model name your Codex accepts). Running on Codex's default model instead.", file=sys.stderr)
201
+ cmd = ["codex", "exec"] + (["-m", model] if model else []) + a.extra + [task]
202
+ if a.dry_run:
203
+ print(" ".join(cmd))
204
+ return 0
205
+ if not shutil.which("codex"):
206
+ print("[graphsnip] `codex` was not found on PATH.", file=sys.stderr)
207
+ return 127
208
+ return subprocess.call(cmd, cwd=str(p.root))
209
+
210
+
211
+ def cmd_usage(a) -> int:
212
+ from graphsnip import router, usage
213
+
214
+ p = Project(a.root)
215
+ u = usage.scan(p.root, router.config(p), since=None if a.all else a.since)
216
+ if not u:
217
+ print(f"No Claude Code transcripts found for this project ({usage.transcripts_dir(p.root)}).")
218
+ return 1
219
+ print(f"Measured model mix from Claude Code transcripts ({u['dir']})")
220
+ for name, row in sorted(u["families"].items(), key=lambda kv: -kv[1]["usd"]):
221
+ print(f" {name:<7} {row['messages']:>5} replies in {row['input']:>10,} out {row['output']:>9,} cache-read {row['cache_read']:>11,} ≈ ${row['usd']}")
222
+ print(f" window: {u['first']} .. {u['last']}")
223
+ print(f" total ≈ ${u['usd_total']} list-price equivalent (not your bill; from routing.prices in .graphsnip/config.json)")
224
+ return 0
225
+
226
+
227
+ def cmd_report(a) -> int:
228
+ from graphsnip.dashboard import write_dashboard
229
+
230
+ p = Project(a.root)
231
+ if not p.has_graph():
232
+ print("No graph yet. Run `graphsnip build` first.")
233
+ return 1
234
+ out = write_dashboard(p, bundle=a.bundle)
235
+ print(f"Dashboard written: {out}")
236
+ if a.bundle:
237
+ print("The folder is self-contained (dashboard.html + graph.html): zip or share it as is.")
238
+ if a.open:
239
+ webbrowser.open(out.as_uri())
240
+ return 0
241
+
242
+
243
+ def cmd_ab(a) -> int:
244
+ from graphsnip import ab
245
+
246
+ if not a.dry_run and not a.yes:
247
+ print(f"graphsnip ab runs each benchmark question (repeats x 2 arms) as headless Claude Code sessions, with and without graphsnip, and spends real usage\n"
248
+ f"(capped at ${a.max_cost:g} total, ${a.run_budget:g} per run). Re-run with --yes to start, or --dry-run to preview.", file=sys.stderr)
249
+ return 2
250
+ try:
251
+ res = ab.run_ab(a.root, a.tasks, repeats=a.repeats, limit=a.limit, model=a.model, max_cost=a.max_cost, run_budget=a.run_budget,
252
+ dry_run=a.dry_run, keep=a.keep, claude_bin=a.claude_bin)
253
+ except RuntimeError as e:
254
+ print(f"[graphsnip ab] {e}", file=sys.stderr)
255
+ return 1
256
+ if a.dry_run:
257
+ print(f"Would run {res['runs']} sessions ({res['tasks']} tasks x {res['repeats']} repeats x 2 arms), cap ${res['max_cost']:g}.")
258
+ print("Example command (treatment arm):\n " + " ".join(res["example"]))
259
+ return 0
260
+ print(ab.format_table(res))
261
+ return 0
262
+
263
+
264
+ def cmd_bench(a) -> int:
265
+ from graphsnip.bench import format_table, run_bench, save_default_tasks
266
+
267
+ p = Project(a.root)
268
+ p.ensure_graph(True)
269
+ if a.init_tasks or (not (p.gs_dir / "tasks.json").exists() and not a.tasks):
270
+ path = save_default_tasks(p)
271
+ print(f"Wrote starter tasks to {path} (edit them to use your own questions).\n")
272
+ res = run_bench(a.root, a.tasks)
273
+ if a.json:
274
+ print(json.dumps(res, indent=2))
275
+ else:
276
+ print(format_table(res))
277
+ return 0
278
+
279
+
280
+ def cmd_demo(a) -> int:
281
+ from graphsnip.bench import format_table, run_bench, save_default_tasks
282
+ from graphsnip.dashboard import write_dashboard
283
+
284
+ p = Project(a.root)
285
+ if not p.has_graph():
286
+ print("Building the Graphify graph (code only, local, no LLM)…")
287
+ s = p.build()
288
+ print(f" {s['nodes']:,} nodes, {s['edges']:,} edges in {s['seconds']}s\n")
289
+ if not (p.gs_dir / "tasks.json").exists():
290
+ save_default_tasks(p)
291
+ print("Running benchmark…\n")
292
+ res = run_bench(a.root)
293
+ print(format_table(res))
294
+ out = write_dashboard(p, bundle=a.bundle)
295
+ print(f"\nDashboard: {out}")
296
+ if a.open:
297
+ webbrowser.open(out.as_uri())
298
+ return 0
299
+
300
+
301
+ def cmd_serve(a) -> int:
302
+ from graphsnip.mcp_server import serve
303
+
304
+ serve(a.root)
305
+ return 0
306
+
307
+
308
+ def cmd_hook(a) -> int:
309
+ from graphsnip.hooks import main_stdin
310
+
311
+ return main_stdin(a.root)
312
+
313
+
314
+ def cmd_run(a) -> int:
315
+ from graphsnip.shellfilter import run
316
+
317
+ argv = list(a.cmd)
318
+ if argv and argv[0] == "--":
319
+ argv = argv[1:]
320
+ return run(argv, a.root)
321
+
322
+
323
+ def _clients(s: str) -> list[str]:
324
+ return [x.strip().lower() for x in s.split(",") if x.strip()]
325
+
326
+
327
+ def cmd_install(a) -> int:
328
+ from graphsnip.installer import install
329
+
330
+ try:
331
+ for ln in install(a.root, _clients(a.clients), dry_run=a.dry_run, allow_tools=a.allow_tools,
332
+ codex_scope=a.codex_scope, strict=a.strict, portable=a.portable):
333
+ print(ln)
334
+ except (ValueError, RuntimeError) as e:
335
+ print(f"error: {e}", file=sys.stderr)
336
+ return 2
337
+ if not a.dry_run:
338
+ print("\nRestart your agent/IDE so it picks up the MCP server. `graphsnip doctor` checks the setup.")
339
+ return 0
340
+
341
+
342
+ def cmd_uninstall(a) -> int:
343
+ from graphsnip.installer import uninstall
344
+
345
+ for ln in uninstall(a.root, _clients(a.clients), a.codex_scope):
346
+ print(ln)
347
+ return 0
348
+
349
+
350
+ def cmd_init(a) -> int:
351
+ from graphsnip.bench import format_table, run_bench, save_default_tasks
352
+ from graphsnip.dashboard import write_dashboard
353
+ from graphsnip.installer import install
354
+
355
+ p = Project(a.root)
356
+ if a.dry_run:
357
+ print("1/4 [dry-run] skipping graph build")
358
+ elif not a.no_build:
359
+ print("1/4 Building the Graphify graph (code only, local, no LLM)…")
360
+ s = p.build()
361
+ print(f" {s['nodes']:,} nodes, {s['edges']:,} edges, {s['communities']:,} communities in {s['seconds']}s")
362
+ print("2/4 Installing agent integrations…")
363
+ try:
364
+ for ln in install(a.root, _clients(a.clients), dry_run=a.dry_run, allow_tools=a.allow_tools,
365
+ codex_scope=a.codex_scope, strict=a.strict, portable=a.portable):
366
+ print(" " + ln)
367
+ except (ValueError, RuntimeError) as e:
368
+ print(f"error: {e}", file=sys.stderr)
369
+ return 2
370
+ if a.dry_run or not p.has_graph():
371
+ return 0
372
+ if not a.no_bench:
373
+ print("3/4 Benchmarking on this repo…")
374
+ save_default_tasks(p) if not (p.gs_dir / "tasks.json").exists() else None
375
+ res = run_bench(a.root)
376
+ print("\n" + format_table(res) + "\n")
377
+ print("4/4 Writing the dashboard…")
378
+ out = write_dashboard(p)
379
+ print(f" {out}")
380
+ print("\nDone. Restart your agent/IDE, then ask it a code question. `graphsnip report --open` shows the savings.")
381
+ return 0
382
+
383
+
384
+ def cmd_doctor(a) -> int:
385
+ from graphsnip.installer import CLIENTS, HOOK_MARK
386
+
387
+ p = Project(a.root)
388
+ ok = True
389
+
390
+ def line(good: bool, msg: str, fix: str = ""):
391
+ nonlocal ok
392
+ ok &= good
393
+ print(f"{'✓' if good else '✗'} {msg}" + (f" → {fix}" if (fix and not good) else ""))
394
+
395
+ line(sys.version_info >= (3, 10), f"Python {sys.version.split()[0]}", "needs Python 3.10+")
396
+ try:
397
+ gv = md.version("graphifyy")
398
+ line(True, f"Graphify {gv}")
399
+ except Exception:
400
+ line(False, "Graphify not installed", "pip install graphifyy")
401
+ try:
402
+ import tree_sitter # noqa: F401
403
+ line(True, "tree-sitter available (exact symbol slicing)")
404
+ except Exception:
405
+ line(False, "tree-sitter missing; slicing falls back to heuristics", "pip install graphifyy")
406
+ exe = shutil.which("graphsnip")
407
+ line(bool(exe), f"`graphsnip` on PATH ({exe})" if exe else "`graphsnip` not on PATH (configs will use `python -m graphsnip`)", "pipx install graphsnip")
408
+ line(p.has_graph(), f"graph present ({p.graph_json})" if p.has_graph() else "no graph yet", "graphsnip build")
409
+ if p.has_graph():
410
+ line(not p.is_stale(0), "graph is up to date" if not p.is_stale(0) else "graph is older than some source files", "graphsnip build (the server also refreshes itself)")
411
+ s = p.graph_stats()
412
+ line(s["symbols"] > 0, f"{s['symbols']:,} code symbols indexed")
413
+ mcp_claude = (p.root / ".mcp.json")
414
+ st = p.root / ".claude" / "settings.json"
415
+ found = {
416
+ "claude": mcp_claude.exists() and "graphsnip" in mcp_claude.read_text(encoding="utf-8", errors="ignore"),
417
+ "copilot": (p.root / ".vscode" / "mcp.json").exists() and "graphsnip" in (p.root / ".vscode" / "mcp.json").read_text(encoding="utf-8", errors="ignore"),
418
+ "codex": (p.root / ".codex" / "config.toml").exists() and "graphsnip" in (p.root / ".codex" / "config.toml").read_text(encoding="utf-8", errors="ignore"),
419
+ }
420
+ from graphsnip import semantic as _sem
421
+
422
+ st_ = _sem.status(p) if p.has_graph() else {"present": False}
423
+ if st_["present"]:
424
+ pend = st_.get("pending")
425
+ line(not pend, f"semantic index: {st_['count']:,} symbols, {st_['model']}" + (f", {pend:,} to re-embed" if pend else ""),
426
+ "graphsnip embed")
427
+ else:
428
+ try:
429
+ import fastembed # noqa: F401
430
+ print("· semantic search: extra installed, no index yet (graphsnip embed)")
431
+ except Exception:
432
+ print("· semantic search: optional, not enabled (pip install 'graphsnip[semantic]' then graphsnip embed)")
433
+ for c in CLIENTS:
434
+ print(f"{'✓' if found[c] else '·'} {c}: {'MCP server registered' if found[c] else 'not installed here (graphsnip install --clients ' + c + ')'}")
435
+ for label, f, key in (("claude", mcp_claude, "mcpServers"), ("copilot", p.root / ".vscode" / "mcp.json", "servers")):
436
+ try:
437
+ ent = json.loads(f.read_text(encoding="utf-8")).get(key, {}).get("graphsnip")
438
+ except Exception:
439
+ ent = None
440
+ if ent:
441
+ c = str(ent.get("command", ""))
442
+ if not os.path.isabs(c):
443
+ print(f"! {label}: server command is the bare `{c}`; apps started from the Dock/Start menu may not find it. "
444
+ f"Re-run `graphsnip install` (without --portable) to write the full path.")
445
+ elif not os.path.exists(c):
446
+ print(f"! {label}: server command {c} does not exist; re-run `graphsnip install`.")
447
+ if not getattr(a, "no_probe", False):
448
+ from graphsnip.probe import probe_mcp
449
+
450
+ for label, f, key in (("claude", mcp_claude, "mcpServers"), ("copilot", p.root / ".vscode" / "mcp.json", "servers")):
451
+ try:
452
+ ent = json.loads(f.read_text(encoding="utf-8")).get(key, {}).get("graphsnip")
453
+ except Exception:
454
+ ent = None
455
+ if not ent:
456
+ continue
457
+ r = probe_mcp(str(ent.get("command", "")), [str(x) for x in ent.get("args", [])], str(p.root))
458
+ if r["ok"]:
459
+ line(True, f"{label}: the MCP server starts and lists {len(r['tools'])} tools ({r['seconds']}s)")
460
+ else:
461
+ line(False, f"{label}: the MCP server does NOT work: {r['error']}", "fix the command in the config, then reload the app")
462
+ if r["stderr"]:
463
+ print(" server said: " + r["stderr"].replace("\n", "\n "))
464
+ print(" If every server above starts but the assistant still has no graphsnip tools, the app has not started or trusted it:")
465
+ print(" Claude Code: run /mcp and approve it. VS Code: Command Palette > 'MCP: List Servers' > start/trust graphsnip, then 'Configure Tools'.")
466
+ hook_on = st.exists() and HOOK_MARK in st.read_text(encoding="utf-8", errors="ignore")
467
+ print(f"{'✓' if hook_on else '·'} claude hook: {'installed' if hook_on else 'not installed'} (mode: {p.config()['mode']})")
468
+ print("\nAll good." if ok else "\nSome checks failed; see arrows above.")
469
+ return 0 if ok else 1
470
+
471
+
472
+ def main(argv=None) -> int:
473
+ common = _common()
474
+ ap = argparse.ArgumentParser(prog="graphsnip", description="Token-saving layer on top of Graphify.")
475
+ ap.add_argument("--version", action="version", version=f"graphsnip {__version__}")
476
+ sub = ap.add_subparsers(dest="cmd")
477
+
478
+ def add(name, fn, help_, **kw):
479
+ sp = sub.add_parser(name, parents=[common], help=help_, **kw)
480
+ sp.set_defaults(fn=fn)
481
+ return sp
482
+
483
+ sp = add("init", cmd_init, "build graph + install integrations + benchmark + dashboard")
484
+ sp.add_argument("--clients", default="all", help="claude,copilot,codex or all (default: all)")
485
+ sp.add_argument("--dry-run", action="store_true")
486
+ sp.add_argument("--allow-tools", action="store_true", help="Claude Code: pre-approve the read-only graphsnip tools")
487
+ sp.add_argument("--strict", action="store_true", help="hooks deny redirectable calls instead of nudging")
488
+ sp.add_argument("--portable", action="store_true", help="write bare `graphsnip` into configs (safe to commit) instead of this machine's path")
489
+ sp.add_argument("--codex-scope", choices=["project", "user"], default="project")
490
+ sp.add_argument("--no-build", action="store_true")
491
+ sp.add_argument("--no-bench", action="store_true")
492
+
493
+ sp = add("build", cmd_build, "build or refresh the Graphify graph (code only, no LLM)")
494
+ sp.add_argument("--force", action="store_true")
495
+ sp = add("eval", cmd_eval, "compare keyword-only and hybrid retrieval on your own questions (needs the semantic index)")
496
+ sp.add_argument("--tasks", default=None, help="tasks.json with question + expect (default: .graphsnip/tasks.json)")
497
+ sp = add("embed", cmd_embed, "build or refresh the optional semantic index (only changed symbols are re-embedded)")
498
+ sp.add_argument("--force", action="store_true", help="re-embed everything")
499
+ sp.add_argument("--status", action="store_true", help="show the index state and exit")
500
+ add("status", cmd_status, "show graph status")
501
+ sp = add("find", cmd_find, "locate symbols and connections (budgeted map)")
502
+ sp.add_argument("question")
503
+ sp.add_argument("--budget", type=int, default=1500)
504
+ sp.add_argument("--depth", type=int, default=2)
505
+ sp.add_argument("--quiet", action="store_true")
506
+ sp = add("symbol", cmd_symbol, "read one function/class with callers and callees")
507
+ sp.add_argument("name")
508
+ sp.add_argument("--max-lines", type=int, default=120)
509
+ sp.add_argument("--full-docs", action="store_true")
510
+ sp.add_argument("--quiet", action="store_true")
511
+ sp = add("pack", cmd_pack, "token-budgeted context pack for a task")
512
+ sp.add_argument("task")
513
+ sp.add_argument("--budget", type=int, default=4000)
514
+ sp.add_argument("--quiet", action="store_true")
515
+ sp = add("impact", cmd_impact, "what depends on a symbol")
516
+ sp.add_argument("name")
517
+ sp.add_argument("--depth", type=int, default=2)
518
+ sp.add_argument("--quiet", action="store_true")
519
+ sp = add("outline", cmd_outline, "symbols in a file with line numbers")
520
+ sp.add_argument("path")
521
+ sp.add_argument("--quiet", action="store_true")
522
+ sp = add("stats", cmd_stats, "token savings so far")
523
+ sp.add_argument("--json", action="store_true")
524
+ sp = add("route", cmd_route, "which model tier does this task need? (logs the decision)")
525
+ sp.add_argument("task")
526
+ sp.add_argument("--client", default="claude", choices=["claude", "copilot", "codex"])
527
+ sp.add_argument("--running", choices=["light", "standard", "heavy", "session"], help="tier you are actually running on, if known")
528
+ sp = add("codex", cmd_codex, "route a task and run it with `codex exec -m <model for the chosen tier>`")
529
+ sp.add_argument("task", nargs="+")
530
+ sp.add_argument("--tier", choices=["light", "standard", "heavy"], help="force a tier instead of the router's pick")
531
+ sp.add_argument("--dry-run", action="store_true", help="print the codex command, do not run it")
532
+ sp.add_argument("--extra", nargs="*", default=[], help="extra args passed to codex exec")
533
+ sp = add("usage", cmd_usage, "measured model mix from Claude Code transcripts")
534
+ sp.add_argument("--since", help="ISO date, e.g. 2026-11-01 (default: all history)")
535
+ sp.add_argument("--all", action="store_true", help="all history (default)")
536
+ sp = add("report", cmd_report, "write the HTML dashboard")
537
+ sp.add_argument("--open", action="store_true")
538
+ sp.add_argument("--bundle", metavar="DIR", help="write a self-contained folder (dashboard + graph.html) for sharing")
539
+ sp = add("ab", cmd_ab, "MEASURED A/B: same questions with and without graphsnip in headless Claude Code (real tokens and cost)")
540
+ sp.add_argument("--tasks", help="tasks JSON (default .graphsnip/tasks.json)")
541
+ sp.add_argument("--repeats", type=int, default=2, help="runs per task per arm (default 2; more = less noise)")
542
+ sp.add_argument("--limit", type=int, help="only the first N tasks")
543
+ sp.add_argument("--model", help="same model for both arms (default: your Claude Code default)")
544
+ sp.add_argument("--max-cost", type=float, default=5.0, help="stop after this many USD in total (default 5)")
545
+ sp.add_argument("--run-budget", type=float, default=1.0, help="per-run USD cap passed to claude (default 1)")
546
+ sp.add_argument("--claude-bin", default="claude")
547
+ sp.add_argument("--keep", action="store_true", help="keep the temporary repo copies")
548
+ sp.add_argument("--dry-run", action="store_true")
549
+ sp.add_argument("--yes", action="store_true", help="confirm that this spends real usage")
550
+ sp = add("bench", cmd_bench, "offline benchmark: grep+read vs Graphify vs graphsnip")
551
+ sp.add_argument("--tasks", help="tasks JSON (default .graphsnip/tasks.json, auto-generated)")
552
+ sp.add_argument("--init-tasks", action="store_true", help="(re)write starter tasks")
553
+ sp.add_argument("--json", action="store_true")
554
+ sp = add("demo", cmd_demo, "one command for a live demo: graph + benchmark + dashboard")
555
+ sp.add_argument("--open", action="store_true")
556
+ sp.add_argument("--bundle", metavar="DIR")
557
+ add("serve", cmd_serve, "run the MCP server over stdio")
558
+ sp = add("hook", cmd_hook, "agent hook entry point (reads JSON on stdin)")
559
+ sp.add_argument("event", choices=["pretooluse"])
560
+ sp = add("run", cmd_run, "run a command and compress its output (exact token savings)")
561
+ sp.add_argument("cmd", nargs=argparse.REMAINDER)
562
+ sp = add("install", cmd_install, "write MCP + hooks + guidance for Claude Code / Copilot / Codex")
563
+ sp.add_argument("--clients", default="all")
564
+ sp.add_argument("--dry-run", action="store_true")
565
+ sp.add_argument("--allow-tools", action="store_true")
566
+ sp.add_argument("--strict", action="store_true")
567
+ sp.add_argument("--portable", action="store_true")
568
+ sp.add_argument("--codex-scope", choices=["project", "user"], default="project")
569
+ sp = add("uninstall", cmd_uninstall, "remove everything install added")
570
+ sp.add_argument("--clients", default="all")
571
+ sp.add_argument("--codex-scope", choices=["project", "user"], default="project")
572
+ sp = add("doctor", cmd_doctor, "check the setup (also starts the configured MCP servers to prove they work)")
573
+ sp.add_argument("--no-probe", action="store_true", help="skip starting the MCP servers")
574
+
575
+ args = ap.parse_args(argv)
576
+ if not getattr(args, "fn", None):
577
+ ap.print_help()
578
+ return 0
579
+ try:
580
+ return int(args.fn(args) or 0)
581
+ except GraphError as e:
582
+ print(f"error: {e}", file=sys.stderr)
583
+ return 1
584
+ except BrokenPipeError:
585
+ return 0
586
+ except KeyboardInterrupt:
587
+ return 130
588
+
589
+
590
+ if __name__ == "__main__":
591
+ raise SystemExit(main())