graphlore 0.7.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.
- graphlore/__init__.py +7 -0
- graphlore/__main__.py +12 -0
- graphlore/agents_md.py +96 -0
- graphlore/algorithms.py +311 -0
- graphlore/apis.py +617 -0
- graphlore/cli.py +133 -0
- graphlore/clients.py +260 -0
- graphlore/config.py +68 -0
- graphlore/embed.py +233 -0
- graphlore/engine.py +379 -0
- graphlore/graph.py +1643 -0
- graphlore/history.py +198 -0
- graphlore/imports.py +581 -0
- graphlore/oauth.py +169 -0
- graphlore/resolve.py +332 -0
- graphlore/review.py +1121 -0
- graphlore/routes.py +1417 -0
- graphlore/scope.py +362 -0
- graphlore/search.py +1070 -0
- graphlore/server.py +8152 -0
- graphlore/spans.py +1254 -0
- graphlore/viewer.html +1649 -0
- graphlore/viz.py +381 -0
- graphlore-0.7.0.dist-info/METADATA +379 -0
- graphlore-0.7.0.dist-info/RECORD +28 -0
- graphlore-0.7.0.dist-info/WHEEL +4 -0
- graphlore-0.7.0.dist-info/entry_points.txt +2 -0
- graphlore-0.7.0.dist-info/licenses/LICENSE +21 -0
graphlore/cli.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""The ``graphlore`` command.
|
|
2
|
+
|
|
3
|
+
With no arguments it runs the MCP server (stdio by default), exactly as before:
|
|
4
|
+
every client config, the Claude Code plugin and the MCP Registry entry start it
|
|
5
|
+
so. The subcommands are for setting a client up:
|
|
6
|
+
|
|
7
|
+
- ``graphlore setup <client>`` prints, or with ``--write`` merges, the block a
|
|
8
|
+
client's MCP config needs (``clients.py``);
|
|
9
|
+
- ``graphlore clients`` lists the clients it knows;
|
|
10
|
+
- ``graphlore agents-md`` prints, or merges into a file, the usage guide for
|
|
11
|
+
agents that read AGENTS.md / GEMINI.md and the like (``agents_md.py``).
|
|
12
|
+
|
|
13
|
+
The server module is imported only to run the server or to name its tools.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from . import agents_md, clients
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _tools_of(toolset: str) -> list[str]:
|
|
25
|
+
"""The tools the server registers with ``toolset``, by name."""
|
|
26
|
+
from . import server # registers every tool; only here
|
|
27
|
+
|
|
28
|
+
names = server._registered_tool_names()
|
|
29
|
+
keep = server.TOOLSETS.get(toolset)
|
|
30
|
+
return sorted(names if keep is None else names & keep)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _write_guide(path: Path, block: str) -> str:
|
|
34
|
+
old = path.read_text(encoding="utf-8") if path.is_file() else ""
|
|
35
|
+
new = agents_md.merge(old, block)
|
|
36
|
+
if new == old:
|
|
37
|
+
return f"{path}: already up to date"
|
|
38
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
path.write_text(new, encoding="utf-8")
|
|
40
|
+
return f"{path}: {'updated' if old else 'written'}"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _cmd_clients(_args: argparse.Namespace) -> int:
|
|
44
|
+
for c in clients.CLIENTS.values():
|
|
45
|
+
where = ", ".join(str(p) for p in (c.project_file, c.user_file) if p) or "(printed only)"
|
|
46
|
+
print(f"{c.name:15} {c.title:28} {where}")
|
|
47
|
+
return 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _cmd_setup(args: argparse.Namespace) -> int:
|
|
51
|
+
client = clients.CLIENTS.get(args.client)
|
|
52
|
+
if client is None:
|
|
53
|
+
print(f"unknown client {args.client!r}; `graphlore clients` lists them",
|
|
54
|
+
file=sys.stderr)
|
|
55
|
+
return 2
|
|
56
|
+
project = Path(args.project).expanduser().resolve()
|
|
57
|
+
server_cfg = clients.server_config(project, args.toolset, args.command,
|
|
58
|
+
absolute=client.absolute_command)
|
|
59
|
+
target = clients.target(client, project, user=args.user)
|
|
60
|
+
if not args.write or target is None:
|
|
61
|
+
print(clients.render(client, server_cfg, project, user=args.user))
|
|
62
|
+
if args.write and target is None:
|
|
63
|
+
print(f"\n({client.title} keeps no config file graphlore writes: add the "
|
|
64
|
+
"block above by hand.)", file=sys.stderr)
|
|
65
|
+
return 1
|
|
66
|
+
else:
|
|
67
|
+
try:
|
|
68
|
+
note = clients.write(client, target, server_cfg)
|
|
69
|
+
except clients.SetupError as e:
|
|
70
|
+
print(f"ERROR: {e}", file=sys.stderr)
|
|
71
|
+
return 1
|
|
72
|
+
print(note)
|
|
73
|
+
if args.with_agents_md:
|
|
74
|
+
guide = project / client.guide_file
|
|
75
|
+
print(_write_guide(guide, agents_md.render(_tools_of(args.toolset))))
|
|
76
|
+
return 0
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _cmd_agents_md(args: argparse.Namespace) -> int:
|
|
80
|
+
block = agents_md.render(_tools_of(args.toolset))
|
|
81
|
+
if args.write:
|
|
82
|
+
print(_write_guide(Path(args.write), block))
|
|
83
|
+
else:
|
|
84
|
+
sys.stdout.write(block)
|
|
85
|
+
return 0
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _parser() -> argparse.ArgumentParser:
|
|
89
|
+
p = argparse.ArgumentParser(
|
|
90
|
+
prog="graphlore",
|
|
91
|
+
description="With no arguments: run the graphlore MCP server (stdio). "
|
|
92
|
+
"The subcommands set an MCP client up for it.")
|
|
93
|
+
sub = p.add_subparsers(dest="cmd")
|
|
94
|
+
s = sub.add_parser("setup", help="the MCP config block for a client, printed or merged")
|
|
95
|
+
s.add_argument("client", help="see `graphlore clients`")
|
|
96
|
+
s.add_argument("--project", default=".", help="the repository graphlore reads")
|
|
97
|
+
s.add_argument("--toolset", default="lean", choices=("lean", "full", "locate"))
|
|
98
|
+
s.add_argument("--command", default="graphlore",
|
|
99
|
+
help="how the client starts graphlore: graphlore (default, the "
|
|
100
|
+
"command on PATH), uvx (from PyPI) or a path")
|
|
101
|
+
s.add_argument("--user", action="store_true",
|
|
102
|
+
help="the client's user-level config instead of the project's")
|
|
103
|
+
s.add_argument("--write", action="store_true",
|
|
104
|
+
help="merge it into the config file (a backup is kept)")
|
|
105
|
+
s.add_argument("--with-agents-md", action="store_true",
|
|
106
|
+
help="also write the usage guide into the file this client reads")
|
|
107
|
+
s.set_defaults(fn=_cmd_setup)
|
|
108
|
+
c = sub.add_parser("clients", help="the clients `setup` knows")
|
|
109
|
+
c.set_defaults(fn=_cmd_clients)
|
|
110
|
+
a = sub.add_parser("agents-md", help="the usage guide for AGENTS.md and the like")
|
|
111
|
+
a.add_argument("--toolset", default="lean", choices=("lean", "full", "locate"))
|
|
112
|
+
a.add_argument("--write", metavar="PATH",
|
|
113
|
+
help="merge it into this file (between its graphlore markers)")
|
|
114
|
+
a.set_defaults(fn=_cmd_agents_md)
|
|
115
|
+
return p
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def main(argv: list[str] | None = None) -> int | None:
|
|
119
|
+
args_in = sys.argv[1:] if argv is None else argv
|
|
120
|
+
if not args_in:
|
|
121
|
+
from . import server
|
|
122
|
+
|
|
123
|
+
server.main()
|
|
124
|
+
return None
|
|
125
|
+
args = _parser().parse_args(args_in)
|
|
126
|
+
if not getattr(args, "fn", None):
|
|
127
|
+
_parser().print_help()
|
|
128
|
+
return 2
|
|
129
|
+
return int(args.fn(args))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
if __name__ == "__main__": # pragma: no cover
|
|
133
|
+
sys.exit(main())
|
graphlore/clients.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""MCP clients ``graphlore setup`` knows: where each keeps its servers, in what
|
|
2
|
+
shape, and the block that starts graphlore there.
|
|
3
|
+
|
|
4
|
+
A client is a row of `CLIENTS`: its config files (project-level and user-level,
|
|
5
|
+
either may be absent), the format (JSON under a key, or Codex's TOML), and the
|
|
6
|
+
file its agent reads project instructions from (for ``--with-agents-md``).
|
|
7
|
+
`render` gives the text to paste; `write` merges the server into the file,
|
|
8
|
+
keeping every other server, after a backup, and refuses a file it cannot parse
|
|
9
|
+
rather than rewrite it. The formats are from each client's own documentation
|
|
10
|
+
(`docs/clients.md` cites the pages).
|
|
11
|
+
|
|
12
|
+
Imports nothing from graphlore: ``graphlore setup`` never loads the server.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import shlex
|
|
20
|
+
import shutil
|
|
21
|
+
import sys
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
SERVER_NAME = "graphlore"
|
|
27
|
+
# What the client installs and runs, through uv (the same extras as server.json).
|
|
28
|
+
UVX_PACKAGE = "graphlore[engine,treesitter]"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SetupError(Exception):
|
|
32
|
+
"""A config file graphlore will not touch (unparseable, or not an object)."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Client:
|
|
37
|
+
name: str
|
|
38
|
+
title: str
|
|
39
|
+
fmt: str # "json" | "toml"
|
|
40
|
+
key: str # the object servers sit under ("mcpServers", …)
|
|
41
|
+
project_file: str | None # relative to the project
|
|
42
|
+
user_file: str | None # "~"-relative; an OS-dependent one is resolved below
|
|
43
|
+
guide_file: str = "AGENTS.md" # where its agent reads project instructions
|
|
44
|
+
add_command: str = "" # the client's own command, when it has one
|
|
45
|
+
project_dir_value: str = "" # what GRAPHLORE_PROJECT_DIR is in the project file
|
|
46
|
+
stdio_type: bool = False # entries carry "type": "stdio"
|
|
47
|
+
note: str = ""
|
|
48
|
+
absolute_command: bool = False # name the launcher by its full path
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _zed_settings() -> str:
|
|
52
|
+
if os.name == "nt":
|
|
53
|
+
return os.path.join(os.environ.get("APPDATA", "~"), "Zed", "settings.json")
|
|
54
|
+
return os.path.join(os.environ.get("XDG_CONFIG_HOME", "~/.config"), "zed", "settings.json")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _desktop_config() -> str:
|
|
58
|
+
if sys.platform == "darwin":
|
|
59
|
+
return "~/Library/Application Support/Claude/claude_desktop_config.json"
|
|
60
|
+
if os.name == "nt":
|
|
61
|
+
return os.path.join(os.environ.get("APPDATA", "~"), "Claude",
|
|
62
|
+
"claude_desktop_config.json")
|
|
63
|
+
return "~/.config/Claude/claude_desktop_config.json"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
CLIENTS: dict[str, Client] = {c.name: c for c in (
|
|
67
|
+
Client("claude-code", "Claude Code", "json", "mcpServers", ".mcp.json", None,
|
|
68
|
+
guide_file="CLAUDE.md",
|
|
69
|
+
# an option must stand between --env and the name, or the name is
|
|
70
|
+
# read as one more KEY=value
|
|
71
|
+
add_command="claude mcp add --env 'GRAPHLORE_PROJECT_DIR=${{CLAUDE_PROJECT_DIR:-.}}' "
|
|
72
|
+
"--transport stdio --scope project graphlore -- {command}",
|
|
73
|
+
project_dir_value="${CLAUDE_PROJECT_DIR:-.}", stdio_type=True,
|
|
74
|
+
note="The plugin (/plugin install graphlore@graphlore) sets all of this up."),
|
|
75
|
+
Client("claude-desktop", "Claude Desktop", "json", "mcpServers", None, _desktop_config(),
|
|
76
|
+
absolute_command=True,
|
|
77
|
+
note="Restart Claude Desktop after editing. It needs absolute paths."),
|
|
78
|
+
Client("codex", "OpenAI Codex CLI", "toml", "mcp_servers", ".codex/config.toml",
|
|
79
|
+
"~/.codex/config.toml",
|
|
80
|
+
add_command="codex mcp add graphlore --env GRAPHLORE_PROJECT_DIR={project} "
|
|
81
|
+
"-- {command}",
|
|
82
|
+
note="Codex reads a project's .codex/config.toml only in a trusted project."),
|
|
83
|
+
Client("gemini", "Google Gemini CLI", "json", "mcpServers", ".gemini/settings.json",
|
|
84
|
+
"~/.gemini/settings.json", guide_file="GEMINI.md",
|
|
85
|
+
note="Gemini starts a project's stdio servers only in a trusted folder "
|
|
86
|
+
"(GEMINI_CLI_TRUST_WORKSPACE=true for a headless run)."),
|
|
87
|
+
Client("cursor", "Cursor", "json", "mcpServers", ".cursor/mcp.json",
|
|
88
|
+
"~/.cursor/mcp.json", project_dir_value="${workspaceFolder}", stdio_type=True),
|
|
89
|
+
Client("vscode", "VS Code (GitHub Copilot)", "json", "mcpServers", ".mcp.json",
|
|
90
|
+
"~/.copilot/mcp-config.json", guide_file=".github/copilot-instructions.md",
|
|
91
|
+
stdio_type=True,
|
|
92
|
+
note="Copilot shows no MCP prompts: the guide from --with-agents-md is what "
|
|
93
|
+
"tells it the flow. (.vscode/mcp.json is the deprecated format.)"),
|
|
94
|
+
Client("kimi", "Kimi Code CLI", "json", "mcpServers", ".kimi-code/mcp.json",
|
|
95
|
+
"~/.kimi-code/mcp.json",
|
|
96
|
+
note="A headless run (kimi -p) starts a project's servers only in a trusted "
|
|
97
|
+
"workspace (KIMI_CODE_TRUST_WORKSPACE=1). The older kimi-cli read "
|
|
98
|
+
"~/.kimi/mcp.json."),
|
|
99
|
+
Client("zed", "Zed", "json", "context_servers", None, _zed_settings(),
|
|
100
|
+
note="Zed's settings may hold comments: --write refuses such a file; paste "
|
|
101
|
+
"the block in Settings > AI > MCP Servers instead."),
|
|
102
|
+
Client("windsurf", "Windsurf", "json", "mcpServers", None,
|
|
103
|
+
"~/.codeium/windsurf/mcp_config.json",
|
|
104
|
+
note="Cascade sees at most 100 tools at a time: lean (12) fits."),
|
|
105
|
+
Client("cline", "Cline", "json", "mcpServers", None,
|
|
106
|
+
"~/.cline/data/settings/cline_mcp_settings.json",
|
|
107
|
+
add_command="cline mcp add graphlore --yes -- {command}",
|
|
108
|
+
note="That is the Cline CLI's file; the extension's opens from its MCP panel "
|
|
109
|
+
"(Configure MCP Servers). cline mcp add sets no environment: add "
|
|
110
|
+
"GRAPHLORE_PROJECT_DIR to the entry."),
|
|
111
|
+
)}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def server_config(
|
|
115
|
+
project: Path, toolset: str, command: str = "graphlore", absolute: bool = False,
|
|
116
|
+
) -> dict[str, Any]:
|
|
117
|
+
"""``{command, args, env}`` that start graphlore on ``project``: the
|
|
118
|
+
``graphlore`` command on PATH (default: the README's install), through
|
|
119
|
+
``uvx`` from PyPI, or a path. ``absolute`` names the command by its full
|
|
120
|
+
path, for a client that does not start servers with the user's shell PATH
|
|
121
|
+
(Claude Desktop)."""
|
|
122
|
+
if command == "uvx":
|
|
123
|
+
cmd = (shutil.which("uvx") or "uvx") if absolute else "uvx"
|
|
124
|
+
args = ["--from", UVX_PACKAGE, "graphlore"]
|
|
125
|
+
elif command in ("graphlore", "installed"):
|
|
126
|
+
cmd = (shutil.which("graphlore") or "graphlore") if absolute else "graphlore"
|
|
127
|
+
args = []
|
|
128
|
+
else:
|
|
129
|
+
cmd, args = command, []
|
|
130
|
+
env = {"GRAPHLORE_PROJECT_DIR": str(project)}
|
|
131
|
+
if toolset != "lean":
|
|
132
|
+
env["GRAPHLORE_TOOLSET"] = toolset
|
|
133
|
+
return {"command": cmd, "args": args, "env": env}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _entry(client: Client, cfg: dict[str, Any], user: bool) -> dict[str, Any]:
|
|
137
|
+
entry: dict[str, Any] = {}
|
|
138
|
+
if client.stdio_type:
|
|
139
|
+
entry["type"] = "stdio"
|
|
140
|
+
entry.update(cfg)
|
|
141
|
+
entry["env"] = dict(cfg["env"])
|
|
142
|
+
if not user and client.project_file and client.project_dir_value:
|
|
143
|
+
# a project file travels with the repository: no absolute path in it
|
|
144
|
+
entry["env"]["GRAPHLORE_PROJECT_DIR"] = client.project_dir_value
|
|
145
|
+
return entry
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def target(client: Client, project: Path, user: bool = False) -> Path | None:
|
|
149
|
+
"""The file ``--write`` merges into: the project's, else (or with ``user``)
|
|
150
|
+
the user's; None when the client keeps neither."""
|
|
151
|
+
if not user and client.project_file:
|
|
152
|
+
return project / client.project_file
|
|
153
|
+
if client.user_file:
|
|
154
|
+
return Path(os.path.expanduser(client.user_file))
|
|
155
|
+
return None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _toml_str(s: str) -> str:
|
|
159
|
+
return json.dumps(s, ensure_ascii=False) # a JSON string is a TOML basic string
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _toml_block(entry: dict[str, Any]) -> str:
|
|
163
|
+
lines = [f"[mcp_servers.{SERVER_NAME}]",
|
|
164
|
+
f"command = {_toml_str(entry['command'])}",
|
|
165
|
+
"args = [" + ", ".join(_toml_str(a) for a in entry["args"]) + "]",
|
|
166
|
+
f"[mcp_servers.{SERVER_NAME}.env]"]
|
|
167
|
+
lines += [f"{k} = {_toml_str(v)}" for k, v in entry["env"].items()]
|
|
168
|
+
return "\n".join(lines) + "\n"
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def render(client: Client, cfg: dict[str, Any], project: Path, user: bool = False) -> str:
|
|
172
|
+
"""The block to paste, where it goes, and the client's own add command."""
|
|
173
|
+
entry = _entry(client, cfg, user)
|
|
174
|
+
where = target(client, project, user)
|
|
175
|
+
if client.fmt == "toml":
|
|
176
|
+
body = _toml_block(entry)
|
|
177
|
+
else:
|
|
178
|
+
body = json.dumps({client.key: {SERVER_NAME: entry}}, indent=2, ensure_ascii=False)
|
|
179
|
+
place = f"put this in {where}" if where else "add this to its MCP config"
|
|
180
|
+
out = [f"# {client.title}: {place}", body.rstrip("\n")]
|
|
181
|
+
if client.add_command:
|
|
182
|
+
command = shlex.join([cfg["command"], *cfg["args"]])
|
|
183
|
+
out.append("\n# or with its own command:\n" + client.add_command.format(
|
|
184
|
+
command=command, project=shlex.quote(cfg["env"]["GRAPHLORE_PROJECT_DIR"])))
|
|
185
|
+
if client.note:
|
|
186
|
+
out.append(f"\n# {client.note}")
|
|
187
|
+
return "\n".join(out) + "\n"
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _backup(path: Path) -> None:
|
|
191
|
+
if path.exists():
|
|
192
|
+
shutil.copy2(path, path.with_name(path.name + ".graphlore.bak"))
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
_TOML_TABLE = re.compile(r"^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*$")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _merge_toml(text: str, block: str) -> str:
|
|
199
|
+
"""``text`` with graphlore's ``[mcp_servers.graphlore]`` tables (and their
|
|
200
|
+
subtables) replaced by ``block``, or the block appended."""
|
|
201
|
+
own = f"mcp_servers.{SERVER_NAME}"
|
|
202
|
+
out: list[str] = []
|
|
203
|
+
skipping = placed = False
|
|
204
|
+
for line in text.splitlines():
|
|
205
|
+
m = _TOML_TABLE.match(line)
|
|
206
|
+
if m:
|
|
207
|
+
name = m.group(1).replace('"', "")
|
|
208
|
+
mine = name == own or name.startswith(own + ".")
|
|
209
|
+
if mine and not placed:
|
|
210
|
+
out.append(block.rstrip("\n"))
|
|
211
|
+
placed = True
|
|
212
|
+
skipping = mine
|
|
213
|
+
if mine:
|
|
214
|
+
continue
|
|
215
|
+
if not skipping:
|
|
216
|
+
out.append(line)
|
|
217
|
+
if not placed:
|
|
218
|
+
if out and out[-1].strip():
|
|
219
|
+
out.append("")
|
|
220
|
+
out.append(block.rstrip("\n"))
|
|
221
|
+
return "\n".join(out) + "\n"
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def write(client: Client, path: Path, cfg: dict[str, Any], user: bool = False) -> str:
|
|
225
|
+
"""Merge graphlore into ``path``; a sentence saying what was done."""
|
|
226
|
+
entry = _entry(client, cfg, user)
|
|
227
|
+
old = path.read_text(encoding="utf-8") if path.is_file() else ""
|
|
228
|
+
if client.fmt == "toml":
|
|
229
|
+
new = _merge_toml(old, _toml_block(entry))
|
|
230
|
+
try:
|
|
231
|
+
import tomllib # Python 3.11+: check the result parses
|
|
232
|
+
except ImportError: # pragma: no cover - 3.10
|
|
233
|
+
tomllib = None # type: ignore[assignment]
|
|
234
|
+
if tomllib is not None:
|
|
235
|
+
try:
|
|
236
|
+
tomllib.loads(old)
|
|
237
|
+
tomllib.loads(new)
|
|
238
|
+
except tomllib.TOMLDecodeError as e:
|
|
239
|
+
raise SetupError(f"{path} is not TOML graphlore can merge into: {e}") from e
|
|
240
|
+
else:
|
|
241
|
+
try:
|
|
242
|
+
data = json.loads(old) if old.strip() else {}
|
|
243
|
+
except json.JSONDecodeError as e:
|
|
244
|
+
raise SetupError(
|
|
245
|
+
f"{path} is not plain JSON ({e}); add the block from "
|
|
246
|
+
f"`graphlore setup {client.name}` by hand") from e
|
|
247
|
+
if not isinstance(data, dict):
|
|
248
|
+
raise SetupError(f"{path} does not hold a JSON object")
|
|
249
|
+
servers = data.setdefault(client.key, {})
|
|
250
|
+
if not isinstance(servers, dict):
|
|
251
|
+
raise SetupError(f"{path}: {client.key!r} is not an object")
|
|
252
|
+
servers[SERVER_NAME] = entry
|
|
253
|
+
new = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
|
|
254
|
+
if new == old:
|
|
255
|
+
return f"{path}: graphlore is already set up"
|
|
256
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
257
|
+
_backup(path)
|
|
258
|
+
path.write_text(new, encoding="utf-8")
|
|
259
|
+
kept = " (the previous file is kept as " + path.name + ".graphlore.bak)" if old else ""
|
|
260
|
+
return f"{path}: graphlore {'updated' if old else 'added'}{kept}"
|
graphlore/config.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Shared runtime configuration.
|
|
2
|
+
|
|
3
|
+
Lives in its own module so the analysis layers (``graph``, ``spans``) and the MCP
|
|
4
|
+
surface (``server``) all read the SAME ``PROJECT_DIR`` by attribute access — and so
|
|
5
|
+
tests can repoint it with ``monkeypatch.setattr(config, "PROJECT_DIR", tmp_path)``.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import overload
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@overload
|
|
15
|
+
def env(name: str) -> str | None: ...
|
|
16
|
+
@overload
|
|
17
|
+
def env(name: str, default: str) -> str: ...
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def env(name: str, default: str | None = None) -> str | None:
|
|
21
|
+
"""Read a server setting: ``GRAPHLORE_<name>`` first, ``GRAPHIFY_<name>`` as
|
|
22
|
+
the legacy fallback.
|
|
23
|
+
|
|
24
|
+
The ``GRAPHIFY_*`` spellings predate the graphlore rename and are still
|
|
25
|
+
honored so existing configs keep working; new configs should use
|
|
26
|
+
``GRAPHLORE_*``. (Artifacts of the wrapped Graphify CLI — the ``graphify``
|
|
27
|
+
binary, ``graphify-out/``, ``.graphify_labels.json`` — keep their own names
|
|
28
|
+
regardless.)
|
|
29
|
+
"""
|
|
30
|
+
value = os.environ.get(f"GRAPHLORE_{name}")
|
|
31
|
+
if value is None:
|
|
32
|
+
value = os.environ.get(f"GRAPHIFY_{name}")
|
|
33
|
+
return default if value is None else value
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _truthy(value: str | None) -> bool:
|
|
37
|
+
return (value or "").strip().lower() in ("1", "true", "yes", "on")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def offline() -> bool:
|
|
41
|
+
"""``GRAPHLORE_OFFLINE=1``: refuse every path graphlore knows reaches the network
|
|
42
|
+
(read per call, so tests and a restarted watcher see the current value)."""
|
|
43
|
+
return _truthy(env("OFFLINE", ""))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# The Hugging Face libraries behind the embedding models (semble's, and the
|
|
47
|
+
# built-in search's dense tier) read these before any download.
|
|
48
|
+
HF_OFFLINE_ENV = {"HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1"}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def export_offline_env() -> None:
|
|
52
|
+
"""Offline: tell the Hugging Face libraries not to download, for this process
|
|
53
|
+
and every child. Unset values only, so an explicit setting wins. Takes effect
|
|
54
|
+
only for libraries not yet imported."""
|
|
55
|
+
if offline():
|
|
56
|
+
for k, v in HF_OFFLINE_ENV.items():
|
|
57
|
+
os.environ.setdefault(k, v)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
PROJECT_DIR = Path(env("PROJECT_DIR", ".")).resolve()
|
|
61
|
+
# A plugin client (Agent Plugins 1.0: Codex, Copilot CLI) starts the server in the
|
|
62
|
+
# plugin's own directory and names no project. With GRAPHLORE_PROJECT_FROM_CLIENT=1
|
|
63
|
+
# and no GRAPHLORE_PROJECT_DIR, the project is the client's first root (MCP
|
|
64
|
+
# `roots/list`, asked on the first tool call) or the directory `graphlore_project`
|
|
65
|
+
# is given; until then `project_pending` is True and the tools say so.
|
|
66
|
+
PROJECT_FROM_CLIENT = _truthy(env("PROJECT_FROM_CLIENT")) and env("PROJECT_DIR") is None
|
|
67
|
+
project_pending = PROJECT_FROM_CLIENT
|
|
68
|
+
OUT_DIR_NAME = env("OUT_DIR", "graphify-out")
|