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/hooks.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Claude Code PreToolUse hook.
|
|
2
|
+
|
|
3
|
+
Principles
|
|
4
|
+
- Fail open: any error means "do nothing".
|
|
5
|
+
- Only redirect when the graph can actually answer (a big file it has an outline
|
|
6
|
+
for, an identifier it knows). Never block a literal-string grep.
|
|
7
|
+
- Default mode is "nudge" (extra context, nothing blocked). "strict" denies the
|
|
8
|
+
redirectable calls with a reason that tells the agent exactly what to call.
|
|
9
|
+
- Rewriting shell commands is opt-in (config shell_filter) and limited to an
|
|
10
|
+
allow-list, because an `allow` decision skips the permission prompt.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
import shlex
|
|
17
|
+
import shutil
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from graphsnip import ledger as _ledger
|
|
22
|
+
from graphsnip.project import CODE_EXTS, Project, bare
|
|
23
|
+
from graphsnip.tokens import count_tokens
|
|
24
|
+
|
|
25
|
+
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_.]*$")
|
|
26
|
+
_GREPS = {"grep", "egrep", "fgrep", "rg", "ag", "ack"}
|
|
27
|
+
_NOISY = re.compile(
|
|
28
|
+
r"^\s*(pytest|python3? -m pytest|npm (run )?test|npm run (build|lint)|yarn (test|build|lint)|pnpm (test|build|lint)|"
|
|
29
|
+
r"npx (jest|vitest|tsc|eslint)|jest|vitest|tsc|eslint|ruff|mypy|go (test|build|vet)|cargo (test|build|check|clippy)|"
|
|
30
|
+
r"mvn|gradle|\./gradlew|make( \w+)?|dotnet (test|build)|git log)\b")
|
|
31
|
+
_UNSAFE_SHELL = re.compile(r"[|;&<>`$()]|\n")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _out(kind: str, text: str, deny: bool) -> dict:
|
|
35
|
+
if deny:
|
|
36
|
+
return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
|
|
37
|
+
"permissionDecisionReason": text}}
|
|
38
|
+
return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": text}}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _log(project: Project, tool: str, action: str, detail: str) -> None:
|
|
42
|
+
_ledger.Ledger(project.gs_dir).record(kind="hook", tool=tool, action=action, detail=detail[:160], source="hook")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _symbol_hint(project: Project, pattern: str) -> str | None:
|
|
46
|
+
pat = pattern.strip().strip("'\"")
|
|
47
|
+
if not _IDENT.match(pat) or len(pat) < 3:
|
|
48
|
+
return None
|
|
49
|
+
ids = project.label_index().get(bare(pat))
|
|
50
|
+
if not ids or len(ids) > 3:
|
|
51
|
+
return None
|
|
52
|
+
G = project.graph()
|
|
53
|
+
parts = []
|
|
54
|
+
for nid in ids:
|
|
55
|
+
d = G.nodes[nid]
|
|
56
|
+
parts.append(f'{project.display(nid)} ({d.get("source_file")}:{d.get("source_location")})')
|
|
57
|
+
first = project.display(ids[0]).replace("()", "")
|
|
58
|
+
return (f'"{pat}" is a symbol in the code graph: ' + "; ".join(parts) +
|
|
59
|
+
f'. Use gs_symbol("{first}") for its code and callers, or gs_impact("{first}") for usages, instead of grep.')
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _read_hint(project: Project, ti: dict, strict: bool) -> tuple[str, str] | None:
|
|
63
|
+
if ti.get("offset") or ti.get("limit"):
|
|
64
|
+
return None
|
|
65
|
+
fp = ti.get("file_path") or ti.get("path")
|
|
66
|
+
if not fp:
|
|
67
|
+
return None
|
|
68
|
+
p = Path(fp)
|
|
69
|
+
if p.suffix.lower() not in CODE_EXTS:
|
|
70
|
+
return None
|
|
71
|
+
try:
|
|
72
|
+
p = p.resolve()
|
|
73
|
+
rel = p.relative_to(project.root).as_posix()
|
|
74
|
+
size = p.stat().st_size
|
|
75
|
+
except Exception:
|
|
76
|
+
return None
|
|
77
|
+
threshold = int(project.config().get("read_threshold_tokens", 1500))
|
|
78
|
+
if size / 4 < threshold * 0.6:
|
|
79
|
+
return None
|
|
80
|
+
toks = count_tokens(p.read_text(encoding="utf-8", errors="replace"))
|
|
81
|
+
if toks <= threshold:
|
|
82
|
+
return None
|
|
83
|
+
rows = project.outline_rows(rel)
|
|
84
|
+
if not rows:
|
|
85
|
+
return None
|
|
86
|
+
cap = 40 if strict else 18
|
|
87
|
+
lines = [f"L{ln} {lab}{' [class]' if c else ''}" for ln, lab, c in rows[:cap]]
|
|
88
|
+
if len(rows) > cap:
|
|
89
|
+
lines.append(f"… +{len(rows) - cap} more (gs_outline('{rel}') lists all)")
|
|
90
|
+
msg = (f"{rel} is ~{toks:,} tokens. Its symbols per the code graph:\n" + "\n".join(lines) +
|
|
91
|
+
f"\nRead only what you need: gs_symbol(name) for one definition, or Read with offset/limit around a line.")
|
|
92
|
+
return msg, rel
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _bash_pattern(cmd: str) -> str | None:
|
|
96
|
+
"""Pattern of a plain `grep|rg|ag|ack PATTERN ...` command; None for pipelines and anything else."""
|
|
97
|
+
try:
|
|
98
|
+
lex = shlex.shlex(cmd, posix=True, punctuation_chars=True)
|
|
99
|
+
lex.whitespace_split = True
|
|
100
|
+
parts = list(lex)
|
|
101
|
+
except ValueError:
|
|
102
|
+
return None
|
|
103
|
+
if any(p and all(c in "|;&<>()" for c in p) for p in parts):
|
|
104
|
+
return None
|
|
105
|
+
if not parts or Path(parts[0]).name not in _GREPS:
|
|
106
|
+
return None
|
|
107
|
+
for a in parts[1:]:
|
|
108
|
+
if not a.startswith("-"):
|
|
109
|
+
return a
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _wrap_command(cmd: str) -> str:
|
|
114
|
+
exe = shutil.which("graphsnip")
|
|
115
|
+
base = shlex.quote(exe) if exe else f"{shlex.quote(sys.executable)} -m graphsnip"
|
|
116
|
+
return f"{base} run -- bash -c {shlex.quote(cmd)}"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def handle(payload: dict, project: Project) -> dict | None:
|
|
120
|
+
cfg = project.config()
|
|
121
|
+
mode = str(cfg.get("mode", "nudge")).lower()
|
|
122
|
+
if mode == "off" or not project.has_graph():
|
|
123
|
+
return None
|
|
124
|
+
strict = mode == "strict"
|
|
125
|
+
tool = payload.get("tool_name")
|
|
126
|
+
ti = payload.get("tool_input") or {}
|
|
127
|
+
|
|
128
|
+
if tool == "Read":
|
|
129
|
+
hit = _read_hint(project, ti, strict)
|
|
130
|
+
if hit:
|
|
131
|
+
msg, rel = hit
|
|
132
|
+
_log(project, "Read", "deny" if strict else "nudge", rel)
|
|
133
|
+
return _out("read", msg, deny=strict)
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
if tool == "Grep":
|
|
137
|
+
hint = _symbol_hint(project, str(ti.get("pattern", "")))
|
|
138
|
+
if hint:
|
|
139
|
+
_log(project, "Grep", "deny" if strict else "nudge", str(ti.get("pattern")))
|
|
140
|
+
return _out("grep", hint, deny=strict)
|
|
141
|
+
return None
|
|
142
|
+
|
|
143
|
+
if tool == "Bash":
|
|
144
|
+
cmd = str(ti.get("command", ""))
|
|
145
|
+
pat = _bash_pattern(cmd)
|
|
146
|
+
if pat:
|
|
147
|
+
hint = _symbol_hint(project, pat)
|
|
148
|
+
if hint:
|
|
149
|
+
_log(project, "Bash", "deny" if strict else "nudge", cmd)
|
|
150
|
+
return _out("grep", hint, deny=strict)
|
|
151
|
+
if cfg.get("shell_filter") and _NOISY.match(cmd) and not _UNSAFE_SHELL.search(cmd) and "graphsnip" not in cmd:
|
|
152
|
+
_log(project, "Bash", "compress", cmd)
|
|
153
|
+
new = dict(ti)
|
|
154
|
+
new["command"] = _wrap_command(cmd)
|
|
155
|
+
return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "allow",
|
|
156
|
+
"permissionDecisionReason": "graphsnip: compressing noisy command output",
|
|
157
|
+
"updatedInput": new}}
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def main_stdin(root: str = ".") -> int:
|
|
162
|
+
try:
|
|
163
|
+
raw = sys.stdin.read()
|
|
164
|
+
payload = json.loads(raw) if raw.strip() else {}
|
|
165
|
+
cwd = payload.get("cwd") or root
|
|
166
|
+
project = Project(cwd)
|
|
167
|
+
# walk up to find the project that owns a graph
|
|
168
|
+
p = project.root
|
|
169
|
+
for cand in [p, *p.parents]:
|
|
170
|
+
if (cand / "graphify-out" / "graph.json").exists():
|
|
171
|
+
project = Project(cand)
|
|
172
|
+
break
|
|
173
|
+
res = handle(payload, project)
|
|
174
|
+
if res:
|
|
175
|
+
sys.stdout.write(json.dumps(res))
|
|
176
|
+
except Exception as e: # fail open
|
|
177
|
+
sys.stderr.write(f"[graphsnip hook] ignored error: {type(e).__name__}: {e}\n")
|
|
178
|
+
return 0
|
graphsnip/installer.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
"""Client installers: Claude Code, GitHub Copilot (VS Code / CLI), Codex.
|
|
2
|
+
|
|
3
|
+
Everything is idempotent and reversible:
|
|
4
|
+
- text files get a marked, replaceable block (<!-- graphsnip:begin --> ... <!-- graphsnip:end -->)
|
|
5
|
+
- JSON files are merged, touching only the `graphsnip` entry / our own hook
|
|
6
|
+
- `--dry-run` prints what would change and writes nothing
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import sys
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from graphsnip.project import Project
|
|
18
|
+
|
|
19
|
+
BEGIN = "<!-- graphsnip:begin -->"
|
|
20
|
+
END = "<!-- graphsnip:end -->"
|
|
21
|
+
TOML_BEGIN = "# graphsnip:begin"
|
|
22
|
+
TOML_END = "# graphsnip:end"
|
|
23
|
+
HOOK_MARK = "graphsnip hook"
|
|
24
|
+
SERVER = "graphsnip"
|
|
25
|
+
CLIENTS = ("claude", "copilot", "codex")
|
|
26
|
+
|
|
27
|
+
GUIDE = f"""{BEGIN}
|
|
28
|
+
## Code navigation (graphsnip)
|
|
29
|
+
|
|
30
|
+
This repo is indexed as a code knowledge graph (Graphify). Use the `graphsnip` MCP tools before grep or whole-file reads:
|
|
31
|
+
|
|
32
|
+
1. `gs_pack(task)` first for "how does X work" or before a change. It returns the exact relevant code, ranked and token-budgeted.
|
|
33
|
+
2. `gs_find(question)` to locate things; `gs_outline(path)` before opening a big file.
|
|
34
|
+
3. `gs_symbol(name)` to read one function/class instead of the whole file.
|
|
35
|
+
4. `gs_impact(name)` before changing a signature or behaviour.
|
|
36
|
+
5. Fall back to grep/Read for literal strings, config, docs, or when the graph has no match.
|
|
37
|
+
|
|
38
|
+
Prefer `Read` with `offset`/`limit` over whole-file reads. If you need long test/build output, run it through `graphsnip run -- <command>` to compress it.
|
|
39
|
+
Interactive map: `graphify-out/graph.html`. Savings dashboard: `.graphsnip/dashboard.html` (`graphsnip report`).
|
|
40
|
+
{END}
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
EXPLORER_AGENT = """---
|
|
44
|
+
name: graphsnip-explorer
|
|
45
|
+
description: Read-only code exploration over the graphsnip knowledge graph. Use for "where is X", "how does Y work", or "what depends on Z" so the main context only receives a short answer.
|
|
46
|
+
tools: mcp__graphsnip__gs_pack, mcp__graphsnip__gs_find, mcp__graphsnip__gs_symbol, mcp__graphsnip__gs_impact, mcp__graphsnip__gs_outline, Read
|
|
47
|
+
model: haiku
|
|
48
|
+
---
|
|
49
|
+
You explore a codebase through the graphsnip tools and report back briefly.
|
|
50
|
+
|
|
51
|
+
1. Start with `gs_pack` (understanding) or `gs_find` (locating). Use `gs_symbol` for single definitions and `gs_impact` for dependents.
|
|
52
|
+
2. Use Read only with offset/limit, and only when the graph tools cannot answer.
|
|
53
|
+
3. Answer in at most 250 words: the direct answer first, then the key `file:line` references. Do not paste code unless asked; point to it.
|
|
54
|
+
4. If the graph has no match, say so and suggest the grep pattern to try.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# ---------------------------------------------------------------- slash command (/graphsnip)
|
|
59
|
+
_ACTIONS = """Pick the first row that fits the request:
|
|
60
|
+
|
|
61
|
+
| Request looks like | Do this |
|
|
62
|
+
|---|---|
|
|
63
|
+
| empty, or "savings" / "stats" | call `gs_savings` and report tokens saved, % saved and the call count |
|
|
64
|
+
| "symbol NAME" | call `gs_symbol` with NAME |
|
|
65
|
+
| "impact NAME" or "what breaks if I change NAME" | call `gs_impact` with NAME, then `gs_symbol` on the top dependents if needed |
|
|
66
|
+
| "outline PATH" | call `gs_outline` with PATH |
|
|
67
|
+
| "find ..." or "where is ..." | call `gs_find` with the question |
|
|
68
|
+
| anything else (a question or a task) | call `gs_pack` with the request as the task, then answer from the returned code |
|
|
69
|
+
|
|
70
|
+
Rules:
|
|
71
|
+
- Start from the graph: call `gs_pack` (or the matching graphsnip tool) before any built-in search, grep or file read, even when the request is vague. Use your own words to rephrase the request if the first result is thin, and try `gs_find` before falling back.
|
|
72
|
+
- Answer from the returned code and `file:line` references. Read a file directly only if the graph has no match or you need a literal string, config or docs.
|
|
73
|
+
- If the graphsnip tools are missing or fail, say once: run `graphsnip doctor` in the repo. Then carry on with your normal tools (search, read files, run commands) and still complete the request; never stop because graphsnip is unavailable.
|
|
74
|
+
- If the request is an action rather than a code question (run tests, coverage, builds, git), just do it with your normal tools; use the graph only to find the relevant code.
|
|
75
|
+
- Keep the answer short. If a graphsnip tool reported token numbers, finish with one line `graphsnip: ~N tokens returned vs ~M for grep+read` using exactly those numbers; if no tool ran or none reported numbers, omit that line.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _command_body(args_token: str, running: str | None, client: str, deep: bool = False) -> str:
|
|
80
|
+
"""Instructions behind /graphsnip. `args_token` is the client's placeholder for what the user typed after the command."""
|
|
81
|
+
route_args = f'task = the request, client = "{client}"' + (f', running_tier = "{running}"' if running else "")
|
|
82
|
+
if deep:
|
|
83
|
+
esc = ""
|
|
84
|
+
elif client == "claude":
|
|
85
|
+
esc = (" - If the result says ESCALATE to <tier>, print exactly one line: `Escalating to <model> (<tier> tier) and continuing...`, "
|
|
86
|
+
"then call the Agent tool (also called Task) with subagent_type `graphsnip-<tier>` and, as its prompt, the user's full original request. "
|
|
87
|
+
"Return the subagent's answer as your answer. Call no other tool yourself.\n")
|
|
88
|
+
else:
|
|
89
|
+
esc = " - If the result says ESCALATE, stop and tell the user to re-run the request with `/graphsnip-deep`. Do nothing else.\n"
|
|
90
|
+
return f"""Use the graphsnip code graph (Graphify under the hood) to answer from exact code instead of reading whole files.
|
|
91
|
+
|
|
92
|
+
Request: {args_token}
|
|
93
|
+
|
|
94
|
+
Step 1. Your first tool call must be `gs_route` ({route_args}), once, for the request as a whole. Do not search, grep or read any file before it.
|
|
95
|
+
{esc} - Otherwise continue.
|
|
96
|
+
|
|
97
|
+
Step 2. {_ACTIONS}"""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def handoff_agent(tier: str, model: str) -> str:
|
|
101
|
+
"""Subagent that /graphsnip hands a task to when the router says the light model is not enough."""
|
|
102
|
+
return (f"---\nname: graphsnip-{tier}\n"
|
|
103
|
+
f"description: Stronger-model worker that /graphsnip hands {tier}-tier requests to. Not for direct use.\n"
|
|
104
|
+
f"model: {model}\n---\n"
|
|
105
|
+
"Use the graphsnip code graph (Graphify under the hood) to answer from exact code instead of reading whole files.\n\n"
|
|
106
|
+
"You were handed this request because the router judged it needs a stronger model than the light one. "
|
|
107
|
+
f'Call `gs_route` once with task = the request, client = "claude", running_tier = "{tier}", handoff = true (this only logs the handoff). '
|
|
108
|
+
"Then do the work.\n\n" + _ACTIONS)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
_DESC = "Answer a code question or task from the graphsnip code graph (exact code, token-budgeted)"
|
|
112
|
+
_DESC_DEEP = "Same as /graphsnip but on your session's own model, for harder tasks (refactors, debugging, multi-file changes)"
|
|
113
|
+
_TOOLS = ", ".join(f"mcp__graphsnip__gs_{t}" for t in ("route", "pack", "find", "symbol", "impact", "outline", "savings"))
|
|
114
|
+
_DELEGATE = "Task, Agent"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def claude_command(light_model: str | None, deep: bool = False) -> str:
|
|
118
|
+
model = "" if deep or not light_model else f"model: {light_model}\n"
|
|
119
|
+
return (f"---\ndescription: {_DESC_DEEP if deep else _DESC}\nargument-hint: <question or task> | symbol NAME | impact NAME | outline PATH | savings\n"
|
|
120
|
+
f"allowed-tools: {_TOOLS}, Read" + ("" if deep else f", {_DELEGATE}") + f"\n{model}---\n"
|
|
121
|
+
+ _command_body("$ARGUMENTS", "session" if deep else ("light" if light_model else None), "claude", deep))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def copilot_prompt(light_model: str | None, deep: bool = False) -> str:
|
|
125
|
+
name = "graphsnip-deep" if deep else "graphsnip"
|
|
126
|
+
model = "" if deep or not light_model else f"model: {light_model}\n"
|
|
127
|
+
return (f"---\nname: {name}\ndescription: {_DESC_DEEP if deep else _DESC}\nargument-hint: <question or task> | symbol NAME | impact NAME | outline PATH | savings\n"
|
|
128
|
+
f"agent: agent\n{model}---\n"
|
|
129
|
+
+ _command_body("the text the user typed after the command (if none, treat it as empty)",
|
|
130
|
+
"session" if deep else ("light" if light_model else None), "copilot", deep))
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def codex_prompt() -> str:
|
|
134
|
+
# Codex prompts cannot pin a model, so routing there is advisory only.
|
|
135
|
+
return f"---\ndescription: {_DESC}\nargument-hint: <question or task>\n---\n" + _command_body("$ARGUMENTS", None, "codex")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
CMD_MARK = "Use the graphsnip code graph (Graphify under the hood)"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass
|
|
142
|
+
class Plan:
|
|
143
|
+
actions: list = field(default_factory=list) # (path, description, callable)
|
|
144
|
+
|
|
145
|
+
def add(self, path: Path, desc: str, fn):
|
|
146
|
+
self.actions.append((path, desc, fn))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
_PORTABLE = False # True: write bare `graphsnip` (commit-friendly) instead of this machine's absolute path
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _command(project_root: Path | None, gui: bool = False) -> tuple[str, list[str]]:
|
|
153
|
+
"""`gui=True`: the client is a GUI app (VS Code) that often has no pipx dir on its PATH, so always prefer the absolute path."""
|
|
154
|
+
exe = shutil.which("graphsnip")
|
|
155
|
+
if _PORTABLE and not (gui and exe):
|
|
156
|
+
return "graphsnip", ["serve", "--root", "."]
|
|
157
|
+
if exe:
|
|
158
|
+
return exe, ["serve", "--root", "."]
|
|
159
|
+
return sys.executable, ["-m", "graphsnip", "serve", "--root", "."]
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _hook_command() -> str:
|
|
163
|
+
exe = shutil.which("graphsnip")
|
|
164
|
+
if _PORTABLE:
|
|
165
|
+
return "graphsnip hook pretooluse"
|
|
166
|
+
return f"{exe} hook pretooluse" if exe else f"{sys.executable} -m graphsnip hook pretooluse"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# ---------------------------------------------------------------- text helpers
|
|
170
|
+
def _upsert_block(path: Path, block: str, begin: str, end: str) -> None:
|
|
171
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
172
|
+
cur = path.read_text(encoding="utf-8") if path.exists() else ""
|
|
173
|
+
if begin in cur and end in cur:
|
|
174
|
+
a = cur.index(begin)
|
|
175
|
+
b = cur.index(end, a) + len(end)
|
|
176
|
+
new = cur[:a] + block.strip("\n") + cur[b:]
|
|
177
|
+
else:
|
|
178
|
+
new = (cur.rstrip("\n") + "\n\n" if cur.strip() else "") + block
|
|
179
|
+
if not new.endswith("\n"):
|
|
180
|
+
new += "\n"
|
|
181
|
+
path.write_text(new, encoding="utf-8")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _remove_block(path: Path, begin: str, end: str) -> bool:
|
|
185
|
+
if not path.exists():
|
|
186
|
+
return False
|
|
187
|
+
cur = path.read_text(encoding="utf-8")
|
|
188
|
+
if begin not in cur or end not in cur:
|
|
189
|
+
return False
|
|
190
|
+
a = cur.index(begin)
|
|
191
|
+
b = cur.index(end, a) + len(end)
|
|
192
|
+
new = (cur[:a].rstrip("\n") + "\n" + cur[b:].lstrip("\n")).strip("\n")
|
|
193
|
+
if new.strip():
|
|
194
|
+
path.write_text(new + "\n", encoding="utf-8")
|
|
195
|
+
else:
|
|
196
|
+
path.unlink()
|
|
197
|
+
return True
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _load_json(path: Path) -> dict:
|
|
201
|
+
if not path.exists():
|
|
202
|
+
return {}
|
|
203
|
+
try:
|
|
204
|
+
return json.loads(path.read_text(encoding="utf-8") or "{}")
|
|
205
|
+
except Exception as e:
|
|
206
|
+
raise RuntimeError(f"{path} is not valid JSON ({e}); fix it or move it aside, then re-run") from e
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _save_json(path: Path, data: dict) -> None:
|
|
210
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
211
|
+
path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _write_owned(path: Path, text: str) -> None:
|
|
215
|
+
"""Write a file graphsnip owns. Never clobbers a same-named file that someone else wrote."""
|
|
216
|
+
if path.exists() and CMD_MARK not in path.read_text(encoding="utf-8", errors="replace"):
|
|
217
|
+
raise RuntimeError(f"{path} exists and was not created by graphsnip; move it aside and re-run")
|
|
218
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
219
|
+
path.write_text(text, encoding="utf-8")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _remove_owned(path: Path) -> bool:
|
|
223
|
+
if path.exists() and CMD_MARK in path.read_text(encoding="utf-8", errors="replace"):
|
|
224
|
+
path.unlink()
|
|
225
|
+
return True
|
|
226
|
+
return False
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _light_model(root: Path, client: str) -> str | None:
|
|
230
|
+
from graphsnip import router
|
|
231
|
+
|
|
232
|
+
return (router.config(Project(root))["models"].get(client) or {}).get("light") or None
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _codex_models(root: Path) -> dict:
|
|
236
|
+
from graphsnip import router
|
|
237
|
+
|
|
238
|
+
return router.config(Project(root))["models"].get("codex") or {}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _codex_prompt_path() -> Path:
|
|
242
|
+
home = Path(os.environ.get("CODEX_HOME") or (Path.home() / ".codex"))
|
|
243
|
+
return home / "prompts" / "graphsnip.md"
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
# ---------------------------------------------------------------- per client
|
|
247
|
+
def _claude(root: Path, plan: Plan, allow_tools: bool, strict: bool) -> None:
|
|
248
|
+
cmd, args = _command(root)
|
|
249
|
+
|
|
250
|
+
def mcp():
|
|
251
|
+
p = root / ".mcp.json"
|
|
252
|
+
d = _load_json(p)
|
|
253
|
+
d.setdefault("mcpServers", {})[SERVER] = {"command": cmd, "args": args}
|
|
254
|
+
_save_json(p, d)
|
|
255
|
+
|
|
256
|
+
def settings():
|
|
257
|
+
p = root / ".claude" / "settings.json"
|
|
258
|
+
d = _load_json(p)
|
|
259
|
+
pre = d.setdefault("hooks", {}).setdefault("PreToolUse", [])
|
|
260
|
+
pre[:] = [g for g in pre if not any(HOOK_MARK in (h.get("command", "")) for h in g.get("hooks", []))]
|
|
261
|
+
pre.append({"matcher": "Read|Grep|Bash", "hooks": [{"type": "command", "command": _hook_command()}]})
|
|
262
|
+
if allow_tools:
|
|
263
|
+
allow = d.setdefault("permissions", {}).setdefault("allow", [])
|
|
264
|
+
if f"mcp__{SERVER}" not in allow:
|
|
265
|
+
allow.append(f"mcp__{SERVER}")
|
|
266
|
+
_save_json(p, d)
|
|
267
|
+
|
|
268
|
+
plan.add(root / ".mcp.json", f"register MCP server '{SERVER}'", mcp)
|
|
269
|
+
plan.add(root / ".claude" / "settings.json",
|
|
270
|
+
"add PreToolUse hook (Read|Grep|Bash)" + (" + allow graphsnip tools" if allow_tools else ""), settings)
|
|
271
|
+
plan.add(root / "CLAUDE.md", "add graphsnip guidance block", lambda: _upsert_block(root / "CLAUDE.md", GUIDE, BEGIN, END))
|
|
272
|
+
cpath = root / ".claude" / "commands" / "graphsnip.md"
|
|
273
|
+
lm = _light_model(root, "claude")
|
|
274
|
+
dpath = root / ".claude" / "commands" / "graphsnip-deep.md"
|
|
275
|
+
plan.add(cpath, f"add /graphsnip slash command (pinned to model '{lm}')" if lm else "add /graphsnip slash command",
|
|
276
|
+
lambda: _write_owned(cpath, claude_command(lm)))
|
|
277
|
+
plan.add(dpath, "add /graphsnip-deep (session model, for hard tasks)", lambda: _write_owned(dpath, claude_command(lm, deep=True)))
|
|
278
|
+
from graphsnip import router
|
|
279
|
+
|
|
280
|
+
cmodels = router.config(Project(root))["models"].get("claude") or {}
|
|
281
|
+
for tier in ("standard", "heavy"):
|
|
282
|
+
m = cmodels.get(tier)
|
|
283
|
+
if m:
|
|
284
|
+
ap = root / ".claude" / "agents" / f"graphsnip-{tier}.md"
|
|
285
|
+
plan.add(ap, f"add auto-escalation subagent graphsnip-{tier} (model '{m}')",
|
|
286
|
+
lambda ap=ap, tier=tier, m=m: _write_owned(ap, handoff_agent(tier, m)))
|
|
287
|
+
plan.add(root / ".claude" / "agents" / "graphsnip-explorer.md", "add cheap read-only explorer subagent (Haiku)",
|
|
288
|
+
lambda: (root / ".claude" / "agents").mkdir(parents=True, exist_ok=True) or
|
|
289
|
+
(root / ".claude" / "agents" / "graphsnip-explorer.md").write_text(EXPLORER_AGENT, encoding="utf-8"))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _copilot(root: Path, plan: Plan) -> None:
|
|
293
|
+
cmd, args = _command(root, gui=True)
|
|
294
|
+
|
|
295
|
+
def mcp():
|
|
296
|
+
p = root / ".vscode" / "mcp.json"
|
|
297
|
+
d = _load_json(p)
|
|
298
|
+
d.setdefault("servers", {})[SERVER] = {"type": "stdio", "command": cmd, "args": args}
|
|
299
|
+
_save_json(p, d)
|
|
300
|
+
|
|
301
|
+
plan.add(root / ".vscode" / "mcp.json", f"register MCP server '{SERVER}' for VS Code Copilot", mcp)
|
|
302
|
+
plan.add(root / ".github" / "copilot-instructions.md", "add graphsnip guidance block",
|
|
303
|
+
lambda: _upsert_block(root / ".github" / "copilot-instructions.md", GUIDE, BEGIN, END))
|
|
304
|
+
ppath = root / ".github" / "prompts" / "graphsnip.prompt.md"
|
|
305
|
+
lm = _light_model(root, "copilot")
|
|
306
|
+
dpath = root / ".github" / "prompts" / "graphsnip-deep.prompt.md"
|
|
307
|
+
plan.add(ppath, "add /graphsnip prompt file (VS Code Copilot chat)" + (f", pinned to model '{lm}'" if lm else " (set routing.models.copilot.light to pin a model)"),
|
|
308
|
+
lambda: _write_owned(ppath, copilot_prompt(lm)))
|
|
309
|
+
plan.add(dpath, "add /graphsnip-deep prompt file", lambda: _write_owned(dpath, copilot_prompt(lm, deep=True)))
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _toml_block(cmd: str, args: list[str], models: dict | None = None) -> str:
|
|
313
|
+
a = ", ".join(json.dumps(x) for x in args)
|
|
314
|
+
prof = "".join(f'\n[profiles.graphsnip-{t}]\nmodel = {json.dumps(m)}\n' for t, m in (models or {}).items() if m)
|
|
315
|
+
return f'{TOML_BEGIN}\n[mcp_servers.{SERVER}]\ncommand = {json.dumps(cmd)}\nargs = [{a}]\n{prof}{TOML_END}\n'
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _codex(root: Path, plan: Plan, scope: str) -> None:
|
|
319
|
+
cmd, args = _command(root)
|
|
320
|
+
if scope == "user":
|
|
321
|
+
cfg = Path.home() / ".codex" / "config.toml"
|
|
322
|
+
args = ["serve", "--root", str(root)] if cmd.endswith("graphsnip") else ["-m", "graphsnip", "serve", "--root", str(root)]
|
|
323
|
+
else:
|
|
324
|
+
cfg = root / ".codex" / "config.toml"
|
|
325
|
+
plan.add(cfg, f"register MCP server '{SERVER}' ({scope} config)",
|
|
326
|
+
lambda: _upsert_block(cfg, _toml_block(cmd, args, _codex_models(root)), TOML_BEGIN, TOML_END))
|
|
327
|
+
plan.add(root / "AGENTS.md", "add graphsnip guidance block",
|
|
328
|
+
lambda: _upsert_block(root / "AGENTS.md", GUIDE, BEGIN, END))
|
|
329
|
+
# Codex only loads custom prompts from $CODEX_HOME/prompts (default ~/.codex/prompts), never from the repo.
|
|
330
|
+
xpath = _codex_prompt_path()
|
|
331
|
+
plan.add(xpath, "add /prompts:graphsnip custom prompt (Codex reads prompts from your home dir; restart Codex)",
|
|
332
|
+
lambda: _write_owned(xpath, codex_prompt()))
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _gitignore(root: Path, plan: Plan) -> None:
|
|
336
|
+
def fn():
|
|
337
|
+
p = root / ".gitignore"
|
|
338
|
+
cur = p.read_text(encoding="utf-8") if p.exists() else ""
|
|
339
|
+
if ".graphsnip/" not in cur.split():
|
|
340
|
+
p.write_text(cur.rstrip("\n") + ("\n" if cur else "") + "# graphsnip local data (ledger, dashboard)\n.graphsnip/\n", encoding="utf-8")
|
|
341
|
+
|
|
342
|
+
plan.add(root / ".gitignore", "ignore .graphsnip/ (ledger + dashboard are local)", fn)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def install(root: str, clients: list[str], dry_run: bool = False, allow_tools: bool = False,
|
|
346
|
+
codex_scope: str = "project", strict: bool = False, portable: bool = False) -> list[str]:
|
|
347
|
+
global _PORTABLE
|
|
348
|
+
_PORTABLE = portable
|
|
349
|
+
project = Project(root)
|
|
350
|
+
r = project.root
|
|
351
|
+
plan = Plan()
|
|
352
|
+
chosen = list(CLIENTS) if "all" in clients else [c for c in clients if c in CLIENTS]
|
|
353
|
+
unknown = [c for c in clients if c != "all" and c not in CLIENTS]
|
|
354
|
+
if unknown:
|
|
355
|
+
raise ValueError(f"unknown client(s): {', '.join(unknown)} (choose from {', '.join(CLIENTS)} or all)")
|
|
356
|
+
if "claude" in chosen:
|
|
357
|
+
_claude(r, plan, allow_tools, strict)
|
|
358
|
+
if "copilot" in chosen:
|
|
359
|
+
_copilot(r, plan)
|
|
360
|
+
if "codex" in chosen:
|
|
361
|
+
_codex(r, plan, codex_scope)
|
|
362
|
+
_gitignore(r, plan)
|
|
363
|
+
lines = []
|
|
364
|
+
for path, desc, fn in plan.actions:
|
|
365
|
+
try:
|
|
366
|
+
shown = path.relative_to(r)
|
|
367
|
+
except ValueError:
|
|
368
|
+
shown = path
|
|
369
|
+
if dry_run:
|
|
370
|
+
lines.append(f"[dry-run] would update {shown}: {desc}")
|
|
371
|
+
else:
|
|
372
|
+
fn()
|
|
373
|
+
lines.append(f"updated {shown}: {desc}")
|
|
374
|
+
if strict and not dry_run:
|
|
375
|
+
cfgp = project.write_default_config()
|
|
376
|
+
d = json.loads(cfgp.read_text(encoding="utf-8"))
|
|
377
|
+
d["mode"] = "strict"
|
|
378
|
+
cfgp.write_text(json.dumps(d, indent=2) + "\n", encoding="utf-8")
|
|
379
|
+
lines.append("set hook mode to strict in .graphsnip/config.json")
|
|
380
|
+
elif not dry_run:
|
|
381
|
+
project.write_default_config()
|
|
382
|
+
return lines
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def uninstall(root: str, clients: list[str], codex_scope: str = "project") -> list[str]:
|
|
386
|
+
r = Project(root).root
|
|
387
|
+
chosen = list(CLIENTS) if "all" in clients else [c for c in clients if c in CLIENTS]
|
|
388
|
+
out = []
|
|
389
|
+
if "claude" in chosen:
|
|
390
|
+
p = r / ".mcp.json"
|
|
391
|
+
if p.exists():
|
|
392
|
+
d = _load_json(p)
|
|
393
|
+
if d.get("mcpServers", {}).pop(SERVER, None) is not None:
|
|
394
|
+
_save_json(p, d)
|
|
395
|
+
out.append("removed MCP server from .mcp.json")
|
|
396
|
+
p = r / ".claude" / "settings.json"
|
|
397
|
+
if p.exists():
|
|
398
|
+
d = _load_json(p)
|
|
399
|
+
pre = d.get("hooks", {}).get("PreToolUse", [])
|
|
400
|
+
keep = [g for g in pre if not any(HOOK_MARK in h.get("command", "") for h in g.get("hooks", []))]
|
|
401
|
+
if len(keep) != len(pre):
|
|
402
|
+
d["hooks"]["PreToolUse"] = keep
|
|
403
|
+
if not keep:
|
|
404
|
+
d["hooks"].pop("PreToolUse")
|
|
405
|
+
if not d["hooks"]:
|
|
406
|
+
d.pop("hooks")
|
|
407
|
+
out.append("removed PreToolUse hook from .claude/settings.json")
|
|
408
|
+
al = d.get("permissions", {}).get("allow", [])
|
|
409
|
+
if f"mcp__{SERVER}" in al:
|
|
410
|
+
al.remove(f"mcp__{SERVER}")
|
|
411
|
+
out.append("removed tool allow-rule")
|
|
412
|
+
_save_json(p, d)
|
|
413
|
+
if _remove_block(r / "CLAUDE.md", BEGIN, END):
|
|
414
|
+
out.append("removed block from CLAUDE.md")
|
|
415
|
+
for nm in ("graphsnip", "graphsnip-deep"):
|
|
416
|
+
if _remove_owned(r / ".claude" / "commands" / f"{nm}.md"):
|
|
417
|
+
out.append(f"removed /{nm} slash command")
|
|
418
|
+
for tier in ("standard", "heavy"):
|
|
419
|
+
if _remove_owned(r / ".claude" / "agents" / f"graphsnip-{tier}.md"):
|
|
420
|
+
out.append(f"removed graphsnip-{tier} subagent")
|
|
421
|
+
a = r / ".claude" / "agents" / "graphsnip-explorer.md"
|
|
422
|
+
if a.exists():
|
|
423
|
+
a.unlink()
|
|
424
|
+
out.append("removed explorer subagent")
|
|
425
|
+
if "copilot" in chosen:
|
|
426
|
+
p = r / ".vscode" / "mcp.json"
|
|
427
|
+
if p.exists():
|
|
428
|
+
d = _load_json(p)
|
|
429
|
+
if d.get("servers", {}).pop(SERVER, None) is not None:
|
|
430
|
+
_save_json(p, d)
|
|
431
|
+
out.append("removed MCP server from .vscode/mcp.json")
|
|
432
|
+
if _remove_block(r / ".github" / "copilot-instructions.md", BEGIN, END):
|
|
433
|
+
out.append("removed block from .github/copilot-instructions.md")
|
|
434
|
+
for nm in ("graphsnip", "graphsnip-deep"):
|
|
435
|
+
if _remove_owned(r / ".github" / "prompts" / f"{nm}.prompt.md"):
|
|
436
|
+
out.append(f"removed /{nm} prompt file")
|
|
437
|
+
if "codex" in chosen:
|
|
438
|
+
cfg = (Path.home() / ".codex" / "config.toml") if codex_scope == "user" else (r / ".codex" / "config.toml")
|
|
439
|
+
if _remove_block(cfg, TOML_BEGIN, TOML_END):
|
|
440
|
+
out.append(f"removed MCP block from {cfg}")
|
|
441
|
+
if _remove_block(r / "AGENTS.md", BEGIN, END):
|
|
442
|
+
out.append("removed block from AGENTS.md")
|
|
443
|
+
if _remove_owned(_codex_prompt_path()):
|
|
444
|
+
out.append("removed Codex custom prompt graphsnip")
|
|
445
|
+
return out or ["nothing to remove"]
|