claude-code-router 0.1.1__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.
- ccr/__init__.py +0 -0
- ccr/__main__.py +4 -0
- ccr/cli.py +595 -0
- ccr/config.py +518 -0
- ccr/detect/__init__.py +123 -0
- ccr/doctor.py +208 -0
- ccr/entry.py +23 -0
- ccr/evaluate/__init__.py +13 -0
- ccr/evaluate/classify.py +335 -0
- ccr/evaluate/llm.py +182 -0
- ccr/evaluate/locate.py +359 -0
- ccr/evaluate/risk.py +285 -0
- ccr/evaluate/text.py +190 -0
- ccr/graph/__init__.py +15 -0
- ccr/graph/build.py +475 -0
- ccr/graph/db.py +88 -0
- ccr/graph/files.py +169 -0
- ccr/graph/git.py +90 -0
- ccr/graph/parse.py +510 -0
- ccr/graph/query.py +359 -0
- ccr/graph/resolve.py +256 -0
- ccr/headless.py +363 -0
- ccr/history/__init__.py +172 -0
- ccr/history/calibrate.py +161 -0
- ccr/history/dashboard.py +374 -0
- ccr/history/feedback.py +91 -0
- ccr/history/learn.py +184 -0
- ccr/history/prompts.py +120 -0
- ccr/history/redact.py +45 -0
- ccr/history/savings.py +187 -0
- ccr/history/shadow.py +114 -0
- ccr/history/stats.py +172 -0
- ccr/history/tune.py +80 -0
- ccr/history/why.py +186 -0
- ccr/hooks/__init__.py +134 -0
- ccr/hooks/bg.py +68 -0
- ccr/hooks/common.py +159 -0
- ccr/hooks/prompt.py +322 -0
- ccr/hooks/session_start.py +91 -0
- ccr/hooks/stop.py +52 -0
- ccr/hooks/tasks.py +170 -0
- ccr/install/__init__.py +388 -0
- ccr/install/agents.py +200 -0
- ccr/install/command.py +159 -0
- ccr/install/settings.py +175 -0
- ccr/memory/__init__.py +87 -0
- ccr/memory/signals.py +210 -0
- ccr/memory/sources.py +422 -0
- ccr/report.py +40 -0
- ccr/route/__init__.py +527 -0
- ccr/route/budget.py +166 -0
- ccr/statusline.py +143 -0
- ccr/transcript.py +98 -0
- claude_code_router-0.1.1.dist-info/METADATA +291 -0
- claude_code_router-0.1.1.dist-info/RECORD +58 -0
- claude_code_router-0.1.1.dist-info/WHEEL +4 -0
- claude_code_router-0.1.1.dist-info/entry_points.txt +2 -0
- claude_code_router-0.1.1.dist-info/licenses/LICENSE +21 -0
ccr/install/command.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""How Claude Code should invoke ccr from hooks and the status line.
|
|
2
|
+
|
|
3
|
+
Preference order:
|
|
4
|
+
1. a `ccr` on PATH that is *this* tool (not e.g. the npm "claude-code-router", which also
|
|
5
|
+
installs a `ccr`) and is not only on PATH because a virtualenv is active -> bare `ccr`,
|
|
6
|
+
portable across machines;
|
|
7
|
+
2. otherwise `<absolute interpreter> -m ccr` (machine-specific; init warns).
|
|
8
|
+
|
|
9
|
+
Quoting: Claude Code runs commands with `sh -c` on macOS/Linux and with Git Bash on Windows
|
|
10
|
+
(PowerShell when Git Bash is missing; hooks accept an explicit `"shell": "powershell"`).
|
|
11
|
+
Arguments made only of safe characters are left bare, which reads the same in all three
|
|
12
|
+
shells; anything else is single-quoted in the target shell's syntax.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import shutil
|
|
19
|
+
import sys
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
_SAFE = re.compile(r"^[A-Za-z0-9_@%+=:,./-]+$")
|
|
24
|
+
# Our hook / status line commands: `ccr hook x`, `/p/ccr hook x`, `py -m ccr hook x`,
|
|
25
|
+
# `'C:/p/ccr.exe' statusline ...`, `& 'p/ccr' statusline`.
|
|
26
|
+
_OURS = re.compile(r"""(?:^|[\s/\\'"&])ccr(?:\.exe)?['"]?\s+(hook|statusline)(?:\s|$)""")
|
|
27
|
+
IS_WINDOWS = os.name == "nt"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class HookCommand:
|
|
32
|
+
prefix: list[str] # argv prefix, e.g. ["ccr"] or [python, "-m", "ccr"]
|
|
33
|
+
flavor: str = "posix" # posix (sh / Git Bash) | powershell
|
|
34
|
+
portable: bool = True # False when the command embeds a machine-specific path
|
|
35
|
+
source: str = "path" # path | interpreter | override
|
|
36
|
+
|
|
37
|
+
def render(self, *args: str) -> str:
|
|
38
|
+
return render([*self.prefix, *args], self.flavor)
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def shell_field(self) -> str | None:
|
|
42
|
+
"""Value for a hook entry's `shell` field (only needed for PowerShell)."""
|
|
43
|
+
return "powershell" if self.flavor == "powershell" else None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def quote(arg: str, flavor: str = "posix") -> str:
|
|
47
|
+
if arg and _SAFE.match(arg):
|
|
48
|
+
return arg
|
|
49
|
+
if flavor == "powershell":
|
|
50
|
+
return "'" + arg.replace("'", "''") + "'"
|
|
51
|
+
return "'" + arg.replace("'", "'\"'\"'") + "'"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def render(parts: list[str], flavor: str = "posix") -> str:
|
|
55
|
+
q = [quote(p, flavor) for p in parts]
|
|
56
|
+
if flavor == "powershell" and q and q[0][:1] == "'":
|
|
57
|
+
return "& " + " ".join(q) # PowerShell needs the call operator for a quoted path
|
|
58
|
+
return " ".join(q)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def split(cmd: str, flavor: str = "posix") -> list[str]:
|
|
62
|
+
"""Inverse of `render` (enough for commands ccr wrote itself)."""
|
|
63
|
+
if flavor == "powershell":
|
|
64
|
+
s = cmd.strip()
|
|
65
|
+
if s.startswith("& "):
|
|
66
|
+
s = s[2:]
|
|
67
|
+
out = []
|
|
68
|
+
for m in re.finditer(r"'((?:[^']|'')*)'|(\S+)", s):
|
|
69
|
+
out.append(m.group(1).replace("''", "'") if m.group(1) is not None else m.group(2))
|
|
70
|
+
return out
|
|
71
|
+
import shlex
|
|
72
|
+
return shlex.split(cmd, posix=True)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def is_ours(cmd: object) -> bool:
|
|
76
|
+
return isinstance(cmd, str) and bool(_OURS.search(cmd))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def our_subcommand(cmd: str) -> str | None:
|
|
80
|
+
m = _OURS.search(cmd)
|
|
81
|
+
return m.group(1) if m else None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _norm(p: str) -> str:
|
|
85
|
+
return p.replace("\\", "/") if IS_WINDOWS else p
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def git_bash() -> str | None:
|
|
89
|
+
if not IS_WINDOWS:
|
|
90
|
+
return None
|
|
91
|
+
found = shutil.which("bash")
|
|
92
|
+
if found:
|
|
93
|
+
return found
|
|
94
|
+
for base in (os.environ.get("ProgramFiles", r"C:\Program Files"),
|
|
95
|
+
os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")):
|
|
96
|
+
cand = Path(base) / "Git" / "bin" / "bash.exe"
|
|
97
|
+
if cand.exists():
|
|
98
|
+
return str(cand)
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def detect_flavor() -> str:
|
|
103
|
+
if not IS_WINDOWS:
|
|
104
|
+
return "posix"
|
|
105
|
+
return "posix" if git_bash() else "powershell"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _venv_scripts_dir() -> Path | None:
|
|
109
|
+
if sys.prefix == getattr(sys, "base_prefix", sys.prefix):
|
|
110
|
+
return None
|
|
111
|
+
return Path(sys.prefix) / ("Scripts" if IS_WINDOWS else "bin")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _is_this_tool(exe: str) -> bool:
|
|
115
|
+
try:
|
|
116
|
+
real = Path(os.path.realpath(exe))
|
|
117
|
+
prefix = Path(os.path.realpath(sys.prefix))
|
|
118
|
+
if prefix in real.parents:
|
|
119
|
+
return True
|
|
120
|
+
with open(real, "rb") as f:
|
|
121
|
+
head = f.read(256 * 1024)
|
|
122
|
+
return b"ccr.entry" in head or b"ccr.cli" in head
|
|
123
|
+
except OSError:
|
|
124
|
+
return False
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def find_on_path(environ: dict | None = None) -> str | None:
|
|
128
|
+
"""A `ccr` on PATH that is this tool, ignoring the active virtualenv's scripts dir."""
|
|
129
|
+
env = os.environ if environ is None else environ
|
|
130
|
+
skip = _venv_scripts_dir()
|
|
131
|
+
dirs = []
|
|
132
|
+
for d in env.get("PATH", "").split(os.pathsep):
|
|
133
|
+
if not d:
|
|
134
|
+
continue
|
|
135
|
+
try:
|
|
136
|
+
if skip is not None and Path(d).resolve() == skip.resolve():
|
|
137
|
+
continue
|
|
138
|
+
except OSError:
|
|
139
|
+
pass
|
|
140
|
+
dirs.append(d)
|
|
141
|
+
for d in dirs: # the first `ccr` on PATH wins in a shell, so only accept it if ours
|
|
142
|
+
found = shutil.which("ccr", path=d)
|
|
143
|
+
if found:
|
|
144
|
+
return found if _is_this_tool(found) else None
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def detect_command(override: str | None = None, environ: dict | None = None,
|
|
149
|
+
flavor: str | None = None) -> HookCommand:
|
|
150
|
+
flavor = flavor or detect_flavor()
|
|
151
|
+
if override:
|
|
152
|
+
return HookCommand(split(override, "posix") if flavor == "posix" else
|
|
153
|
+
split(override, "powershell"), flavor, portable=True,
|
|
154
|
+
source="override")
|
|
155
|
+
if find_on_path(environ):
|
|
156
|
+
return HookCommand(["ccr"], flavor, portable=True, source="path")
|
|
157
|
+
# Keep sys.executable unresolved: resolving a venv's python symlink loses the venv.
|
|
158
|
+
return HookCommand([_norm(sys.executable), "-m", "ccr"], flavor, portable=False,
|
|
159
|
+
source="interpreter")
|
ccr/install/settings.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Merge-safe edits of Claude Code settings files.
|
|
2
|
+
|
|
3
|
+
Only ccr's own pieces are touched:
|
|
4
|
+
* hook entries whose command runs `ccr hook ...` (any path / interpreter prefix) are
|
|
5
|
+
replaced in place, so re-init never duplicates them and user hooks survive untouched;
|
|
6
|
+
* `statusLine`: ours is refreshed; someone else's is wrapped (`ccr statusline --wrap
|
|
7
|
+
"<their command>"`) instead of being replaced;
|
|
8
|
+
* `model` / `effortLevel` are only added when absent (or with force).
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import copy
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from ccr.install.command import HookCommand, is_ours, our_subcommand, split
|
|
19
|
+
|
|
20
|
+
# event -> (ccr hook name, timeout seconds). Claude Code timeouts are in seconds.
|
|
21
|
+
HOOKS = {
|
|
22
|
+
"SessionStart": ("session-start", 5),
|
|
23
|
+
"UserPromptSubmit": ("prompt", 5),
|
|
24
|
+
"SubagentStop": ("stop", 5),
|
|
25
|
+
"Stop": ("stop", 5),
|
|
26
|
+
}
|
|
27
|
+
STATUSLINE_KEYS_KEPT = ("padding", "refreshInterval")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SettingsError(ValueError):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def load(path: Path) -> tuple[dict | None, str | None]:
|
|
35
|
+
"""(parsed object or None when missing, raw text). Raises SettingsError when invalid."""
|
|
36
|
+
try:
|
|
37
|
+
text = path.read_text(encoding="utf-8")
|
|
38
|
+
except FileNotFoundError:
|
|
39
|
+
return None, None
|
|
40
|
+
except OSError as e:
|
|
41
|
+
raise SettingsError(f"{path}: cannot read ({e})") from e
|
|
42
|
+
if not text.strip():
|
|
43
|
+
return {}, text
|
|
44
|
+
try:
|
|
45
|
+
data = json.loads(text)
|
|
46
|
+
except ValueError as e:
|
|
47
|
+
raise SettingsError(f"{path}: not valid JSON ({e}); fix or move it aside, then rerun"
|
|
48
|
+
) from e
|
|
49
|
+
if not isinstance(data, dict):
|
|
50
|
+
raise SettingsError(f"{path}: top level must be a JSON object")
|
|
51
|
+
return data, text
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def indent_of(text: str | None) -> int | str:
|
|
55
|
+
if text:
|
|
56
|
+
m = re.search(r"^([ \t]+)\"", text, re.M)
|
|
57
|
+
if m:
|
|
58
|
+
ws = m.group(1)
|
|
59
|
+
return "\t" if ws.startswith("\t") else len(ws)
|
|
60
|
+
return 2
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def dumps(data: dict, indent: int | str = 2) -> str:
|
|
64
|
+
return json.dumps(data, indent=indent, ensure_ascii=False) + "\n"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def user_settings_path(environ: dict | None = None) -> Path:
|
|
68
|
+
env = os.environ if environ is None else environ
|
|
69
|
+
base = env.get("CLAUDE_CONFIG_DIR") or str(Path(env.get("HOME") or Path.home()) / ".claude")
|
|
70
|
+
return Path(base) / "settings.json"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# --------------------------------------------------------------------------- hooks
|
|
74
|
+
def hook_entry(cmd: HookCommand, name: str, timeout: int) -> dict:
|
|
75
|
+
e = {"type": "command", "command": cmd.render("hook", name), "timeout": timeout}
|
|
76
|
+
if cmd.shell_field:
|
|
77
|
+
e["shell"] = cmd.shell_field
|
|
78
|
+
return e
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _check_hooks(hooks: object, where: str) -> dict:
|
|
82
|
+
if hooks is None:
|
|
83
|
+
return {}
|
|
84
|
+
if not isinstance(hooks, dict):
|
|
85
|
+
raise SettingsError(f"{where}: `hooks` must be an object")
|
|
86
|
+
for ev, groups in hooks.items():
|
|
87
|
+
if not isinstance(groups, list):
|
|
88
|
+
raise SettingsError(f"{where}: hooks.{ev} must be a list")
|
|
89
|
+
return hooks
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _is_our_hook(h: object) -> bool:
|
|
93
|
+
return isinstance(h, dict) and our_subcommand(str(h.get("command", ""))) == "hook"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _strip_group(g: object):
|
|
97
|
+
"""Group without ccr entries; None when only ccr entries were in it."""
|
|
98
|
+
if not isinstance(g, dict) or not isinstance(g.get("hooks"), list):
|
|
99
|
+
return g
|
|
100
|
+
kept = [h for h in g["hooks"] if not _is_our_hook(h)]
|
|
101
|
+
if not kept and g["hooks"]:
|
|
102
|
+
return None
|
|
103
|
+
return {**g, "hooks": kept} if len(kept) != len(g["hooks"]) else g
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def strip_ours(hooks: dict) -> dict:
|
|
107
|
+
"""Copy of `hooks` without ccr hook entries (emptied groups / events removed)."""
|
|
108
|
+
out = {}
|
|
109
|
+
for ev, groups in hooks.items():
|
|
110
|
+
kept = [s for s in (_strip_group(g) for g in groups) if s is not None]
|
|
111
|
+
if kept or not groups:
|
|
112
|
+
out[ev] = kept
|
|
113
|
+
return copy.deepcopy(out)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def has_ours(hooks: dict) -> bool:
|
|
117
|
+
return strip_ours(hooks) != hooks
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def merge_hooks(hooks: dict, cmd: HookCommand) -> dict:
|
|
121
|
+
"""Install ccr's hooks. The first matcher-less group holding only a ccr hook is updated
|
|
122
|
+
in place (stable order, so re-init is a no-op); other ccr entries are removed; user
|
|
123
|
+
groups and entries are kept as they are."""
|
|
124
|
+
out = copy.deepcopy(hooks)
|
|
125
|
+
for ev, (name, timeout) in HOOKS.items():
|
|
126
|
+
want = hook_entry(cmd, name, timeout)
|
|
127
|
+
new_groups, placed = [], False
|
|
128
|
+
for g in out.get(ev, []):
|
|
129
|
+
pure = (isinstance(g, dict) and isinstance(g.get("hooks"), list)
|
|
130
|
+
and len(g["hooks"]) == 1 and _is_our_hook(g["hooks"][0])
|
|
131
|
+
and not g.get("matcher"))
|
|
132
|
+
if pure and not placed:
|
|
133
|
+
new_groups.append({**g, "hooks": [want]})
|
|
134
|
+
placed = True
|
|
135
|
+
continue
|
|
136
|
+
s = _strip_group(g)
|
|
137
|
+
if s is not None:
|
|
138
|
+
new_groups.append(s)
|
|
139
|
+
if not placed:
|
|
140
|
+
new_groups.append({"hooks": [want]})
|
|
141
|
+
out[ev] = new_groups
|
|
142
|
+
return out
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# --------------------------------------------------------------------------- statusLine
|
|
146
|
+
def wrapped_command(sl: dict, flavor: str) -> str | None:
|
|
147
|
+
"""The user command inside our `ccr statusline --wrap <cmd>`, if any."""
|
|
148
|
+
try:
|
|
149
|
+
parts = split(str(sl.get("command", "")), flavor)
|
|
150
|
+
except ValueError:
|
|
151
|
+
return None
|
|
152
|
+
if "--wrap" in parts:
|
|
153
|
+
i = parts.index("--wrap")
|
|
154
|
+
if i + 1 < len(parts):
|
|
155
|
+
return parts[i + 1]
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def statusline_for(existing: object, cmd: HookCommand) -> tuple[dict | None, str]:
|
|
160
|
+
"""(new statusLine value or None to leave as is, note)."""
|
|
161
|
+
if existing is None:
|
|
162
|
+
return {"type": "command", "command": cmd.render("statusline")}, "status line relay"
|
|
163
|
+
if not isinstance(existing, dict) or not isinstance(existing.get("command"), str) or \
|
|
164
|
+
not existing["command"].strip():
|
|
165
|
+
return None, "statusLine left unchanged (not a command status line)"
|
|
166
|
+
keep = {k: existing[k] for k in STATUSLINE_KEYS_KEPT if k in existing}
|
|
167
|
+
if is_ours(existing["command"]) and our_subcommand(existing["command"]) == "statusline":
|
|
168
|
+
inner = wrapped_command(existing, cmd.flavor)
|
|
169
|
+
args = ["statusline"] + (["--wrap", inner] if inner else [])
|
|
170
|
+
new = {**existing, "type": "command", "command": cmd.render(*args)}
|
|
171
|
+
return new, ("status line relay (still wrapping your command)" if inner
|
|
172
|
+
else "status line relay")
|
|
173
|
+
new = {"type": "command", "command": cmd.render("statusline", "--wrap", existing["command"]),
|
|
174
|
+
**keep}
|
|
175
|
+
return new, "wrapped your existing status line (its output is shown unchanged)"
|
ccr/memory/__init__.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Read-only memory readers (CLAUDE.md, auto memory, agent memory, MCP knowledge graph) and
|
|
2
|
+
keyword-based risk signals extracted from them. Missing sources are silently skipped."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Mapping
|
|
9
|
+
|
|
10
|
+
from ccr.memory.signals import MemorySignal, dedupe, matches, signals_from_kg, signals_from_text
|
|
11
|
+
from ccr.memory import sources as S
|
|
12
|
+
|
|
13
|
+
log = logging.getLogger("ccr.memory")
|
|
14
|
+
|
|
15
|
+
__all__ = ["MemorySignal", "MemorySource", "MemoryReport", "collect", "matches"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class MemorySource:
|
|
20
|
+
kind: str # claude_md | claude_local | rules | import | auto_memory | agent_memory | mcp_memory
|
|
21
|
+
scope: str # managed | user | ancestor | project | local | nested
|
|
22
|
+
path: str
|
|
23
|
+
entries: int = 0 # non-empty lines, or entities + relations for MCP memory
|
|
24
|
+
agent: str | None = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class MemoryReport:
|
|
29
|
+
sources: list[MemorySource] = field(default_factory=list)
|
|
30
|
+
signals: list[MemorySignal] = field(default_factory=list)
|
|
31
|
+
notes: list[str] = field(default_factory=list)
|
|
32
|
+
|
|
33
|
+
def signals_for(self, rel_path: str) -> list[MemorySignal]:
|
|
34
|
+
return [s for s in self.signals if matches(s, rel_path)]
|
|
35
|
+
|
|
36
|
+
def by_kind(self) -> dict[str, int]:
|
|
37
|
+
out: dict[str, int] = {}
|
|
38
|
+
for s in self.signals:
|
|
39
|
+
out[s.kind] = out.get(s.kind, 0) + 1
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _lines(text: str) -> int:
|
|
44
|
+
return sum(1 for ln in text.splitlines() if ln.strip())
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def collect(root: str | Path, home: str | Path | None = None,
|
|
48
|
+
environ: Mapping[str, str] | None = None, nested: bool = True) -> MemoryReport:
|
|
49
|
+
"""Read every memory source for a project. Never raises."""
|
|
50
|
+
rep = MemoryReport()
|
|
51
|
+
try:
|
|
52
|
+
ctx = S.make_context(root, home, environ)
|
|
53
|
+
except Exception as e: # pragma: no cover - unusable root
|
|
54
|
+
rep.notes.append(f"memory: cannot resolve project root: {e}")
|
|
55
|
+
return rep
|
|
56
|
+
try:
|
|
57
|
+
amd = S.auto_memory_dir(ctx)
|
|
58
|
+
if amd is not None and not S._md_dir(amd):
|
|
59
|
+
rep.notes.append(f"auto memory directory is empty: {amd}")
|
|
60
|
+
except Exception:
|
|
61
|
+
pass
|
|
62
|
+
readers = [("CLAUDE.md", lambda: S.claude_md_docs(ctx, nested=nested)),
|
|
63
|
+
("auto memory", lambda: S.auto_memory_docs(ctx)),
|
|
64
|
+
("agent memory", lambda: S.agent_memory_docs(ctx))]
|
|
65
|
+
for label, fn in readers:
|
|
66
|
+
try:
|
|
67
|
+
docs = fn()
|
|
68
|
+
except Exception as e:
|
|
69
|
+
log.debug("memory reader %s failed: %s", label, e)
|
|
70
|
+
continue
|
|
71
|
+
for d in docs:
|
|
72
|
+
rep.sources.append(MemorySource(d.kind, d.scope, str(d.path), _lines(d.text), d.agent))
|
|
73
|
+
try:
|
|
74
|
+
rep.signals += signals_from_text(d.text, str(d.path))
|
|
75
|
+
except Exception as e:
|
|
76
|
+
log.debug("signal extraction failed for %s: %s", d.path, e)
|
|
77
|
+
try:
|
|
78
|
+
graphs, notes = S.mcp_memory(ctx)
|
|
79
|
+
rep.notes += notes
|
|
80
|
+
for g in graphs:
|
|
81
|
+
rep.sources.append(MemorySource("mcp_memory", "project", str(g.path),
|
|
82
|
+
len(g.entities) + len(g.relations)))
|
|
83
|
+
rep.signals += signals_from_kg(g.entities, g.relations, f"mcp:{g.server}")
|
|
84
|
+
except Exception as e:
|
|
85
|
+
log.debug("MCP memory reader failed: %s", e)
|
|
86
|
+
rep.signals = dedupe(rep.signals)
|
|
87
|
+
return rep
|
ccr/memory/signals.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Keyword heuristics that turn memory text into risk/ownership signals."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import fnmatch
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class MemorySignal:
|
|
11
|
+
path_or_term: str
|
|
12
|
+
kind: str # fragile | critical | protected | hard | ownership
|
|
13
|
+
text: str
|
|
14
|
+
source: str # file the signal came from (path), or "mcp:<server>"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
KIND_RX: dict[str, re.Pattern] = {
|
|
18
|
+
"protected": re.compile(
|
|
19
|
+
r"\b(?:do\s+not|don'?t|never|must\s+not|should\s+not)\s+(?:ever\s+)?(?:edit|modify|touch|"
|
|
20
|
+
r"change|delete|rename|regenerate|hand[- ]edit)\b|\bauto-?generated\b|\bread[- ]only\b|"
|
|
21
|
+
r"\bfrozen\b", re.I),
|
|
22
|
+
"fragile": re.compile(
|
|
23
|
+
r"\b(?:fragile|brittle|flaky|delicate|finicky|tricky|subtle|easy\s+to\s+break|"
|
|
24
|
+
r"breaks\s+easily|be\s+careful|careful\s+(?:with|when|around|about)|handle\s+with\s+care|"
|
|
25
|
+
r"gotchas?|footguns?|pitfalls?|race\s+conditions?|regress(?:ion|ions|es)?|"
|
|
26
|
+
r"watch\s+out)\b", re.I),
|
|
27
|
+
"critical": re.compile(
|
|
28
|
+
r"\b(?:critical|mission[- ]critical|load[- ]bearing|high[- ]risk|risky|dangerous|"
|
|
29
|
+
r"security[- ](?:sensitive|critical)|sensitive|hot\s+path|blast\s+radius|"
|
|
30
|
+
r"production[- ]critical)\b", re.I),
|
|
31
|
+
"hard": re.compile(
|
|
32
|
+
r"\b(?:complex|complicated|hard\s+to|difficult|confusing|convoluted|legacy|spaghetti|"
|
|
33
|
+
r"gnarly|hairy|messy|tech(?:nical)?\s+debt|poorly\s+understood|nobody\s+understands|"
|
|
34
|
+
r"known[- ]hard|hardest)\b", re.I),
|
|
35
|
+
"ownership": re.compile(
|
|
36
|
+
r"\b(?:owned\s+by|owners?\s*[:=]|owns\b|maintained\s+by|maintainers?\s*[:=]|"
|
|
37
|
+
r"ask\s+@?[\w.-]+\s+before|ping\s+@[\w.-]+|code\s*owners?|point\s+of\s+contact|"
|
|
38
|
+
r"(?:is|are)\s+responsible\s+for|reviewed\s+by\s+@)", re.I),
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
_CODE_EXT = (r"py|pyi|ts|tsx|js|jsx|mjs|go|rs|java|kt|scala|rb|php|cs|c|h|cc|cpp|hpp|swift|"
|
|
42
|
+
r"sql|ya?ml|json|toml|ini|cfg|md|sh|zig|ex|exs|lua|dart|vue|svelte|proto|tf")
|
|
43
|
+
_PATH_RX = re.compile(
|
|
44
|
+
r"(?<![\w@/.-])((?:\.{0,2}/)?(?:[\w.*-]+/)+[\w.*-]*|[\w*-]+(?:\.[\w-]+)*\.(?:" + _CODE_EXT +
|
|
45
|
+
r"))(?![\w/])")
|
|
46
|
+
_TICK_RX = re.compile(r"`([^`\n]{1,120})`")
|
|
47
|
+
_PHRASE_RX = re.compile(
|
|
48
|
+
r"\b(?:careful\s+(?:with|when\s+(?:touching|changing|editing|modifying)|around|about)|"
|
|
49
|
+
r"(?:don'?t|do\s+not|never)\s+(?:touch|edit|modify|change)|"
|
|
50
|
+
r"owned\s+by\s+[\w@ .-]+?\s+(?:for|of)|(?:owns|maintains))\s+(?:the\s+)?"
|
|
51
|
+
r"([A-Za-z_][\w./-]*(?:\s+[A-Za-z_][\w-]*){0,2})", re.I)
|
|
52
|
+
_STOP = {"it", "this", "that", "these", "those", "them", "anything", "everything", "here",
|
|
53
|
+
"there", "code", "files", "file", "the", "a", "an", "any", "all", "when", "with"}
|
|
54
|
+
_SLASH_WORDS = {"and/or", "either/or", "i/o", "n/a", "w/o", "yes/no", "on/off", "read/write",
|
|
55
|
+
"input/output", "client/server", "true/false", "he/she", "s/he", "ci/cd"}
|
|
56
|
+
_HEADING_RX = re.compile(r"^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$")
|
|
57
|
+
_BULLET_RX = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?")
|
|
58
|
+
_GENERIC_HEADINGS = {"notes", "memory", "overview", "general", "misc", "todo", "context",
|
|
59
|
+
"guidelines", "rules", "instructions", "conventions", "summary"}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _clean_term(t: str) -> str:
|
|
63
|
+
t = t.strip().strip("`'\"()[]{}<>,;:!?")
|
|
64
|
+
t = re.sub(r"\.$", "", t)
|
|
65
|
+
if t.startswith("./"):
|
|
66
|
+
t = t[2:]
|
|
67
|
+
return t
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _looks_like_term(t: str) -> bool:
|
|
71
|
+
if not t or len(t) > 120 or t.lower() in _STOP:
|
|
72
|
+
return False
|
|
73
|
+
if " " in t:
|
|
74
|
+
return len(t.split()) <= 3
|
|
75
|
+
return bool(re.search(r"[A-Za-z]", t))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def extract_terms(unit: str) -> list[str]:
|
|
79
|
+
"""Paths / identifiers a sentence is about, most specific first."""
|
|
80
|
+
terms: list[str] = []
|
|
81
|
+
for m in _TICK_RX.finditer(unit):
|
|
82
|
+
inner = m.group(1).strip()
|
|
83
|
+
if " " not in inner or len(inner.split()) <= 3:
|
|
84
|
+
terms.append(inner)
|
|
85
|
+
stripped = _TICK_RX.sub(" ", unit)
|
|
86
|
+
for m in _PATH_RX.finditer(stripped):
|
|
87
|
+
val = m.group(1)
|
|
88
|
+
if "/" in val and (not re.search(r"[A-Za-z]", val) or val.lower() in _SLASH_WORDS):
|
|
89
|
+
continue
|
|
90
|
+
if re.match(r"^(?:https?:|www\.)", val) or val.count("/") == 1 and val.endswith("/") \
|
|
91
|
+
and len(val) <= 2:
|
|
92
|
+
continue
|
|
93
|
+
terms.append(val)
|
|
94
|
+
if not terms:
|
|
95
|
+
for m in _PHRASE_RX.finditer(stripped):
|
|
96
|
+
terms.append(m.group(1))
|
|
97
|
+
out: list[str] = []
|
|
98
|
+
for t in terms:
|
|
99
|
+
t = _clean_term(t)
|
|
100
|
+
if _looks_like_term(t) and t not in out and not t.startswith(("http:", "https:")):
|
|
101
|
+
out.append(t)
|
|
102
|
+
return out
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _units(text: str):
|
|
106
|
+
"""Yield (heading, unit) for each bullet / line / sentence outside code fences."""
|
|
107
|
+
heading = ""
|
|
108
|
+
in_fence = False
|
|
109
|
+
for raw in text.splitlines():
|
|
110
|
+
if raw.lstrip().startswith(("```", "~~~")):
|
|
111
|
+
in_fence = not in_fence
|
|
112
|
+
continue
|
|
113
|
+
if in_fence or not raw.strip():
|
|
114
|
+
continue
|
|
115
|
+
h = _HEADING_RX.match(raw)
|
|
116
|
+
if h:
|
|
117
|
+
heading = h.group(2).strip()
|
|
118
|
+
continue
|
|
119
|
+
line = _BULLET_RX.sub("", raw).strip()
|
|
120
|
+
if line.startswith(("---", "|---")):
|
|
121
|
+
continue
|
|
122
|
+
parts = re.split(r"(?<=[.!?])\s+(?=[A-Z`])", line) if len(line) > 160 else [line]
|
|
123
|
+
for p in parts:
|
|
124
|
+
if p.strip():
|
|
125
|
+
yield heading, p.strip()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def signals_from_text(text: str, source: str) -> list[MemorySignal]:
|
|
129
|
+
out: list[MemorySignal] = []
|
|
130
|
+
for heading, unit in _units(text):
|
|
131
|
+
kinds = [k for k, rx in KIND_RX.items() if rx.search(unit)]
|
|
132
|
+
if not kinds:
|
|
133
|
+
continue
|
|
134
|
+
terms = extract_terms(unit)
|
|
135
|
+
if not terms and heading:
|
|
136
|
+
h = _clean_term(heading)
|
|
137
|
+
ht = extract_terms(heading)
|
|
138
|
+
if ht:
|
|
139
|
+
terms = ht
|
|
140
|
+
elif h.lower() not in _GENERIC_HEADINGS and _looks_like_term(h):
|
|
141
|
+
terms = [h]
|
|
142
|
+
snippet = unit if len(unit) <= 300 else unit[:297] + "..."
|
|
143
|
+
for k in kinds:
|
|
144
|
+
for t in terms:
|
|
145
|
+
out.append(MemorySignal(t, k, snippet, source))
|
|
146
|
+
return out
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
_OWN_REL = re.compile(r"own|maintain|responsible|steward", re.I)
|
|
150
|
+
_OWNED_BY = re.compile(r"(?:owned|maintained)_?by|has_?owner|owner$", re.I)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def signals_from_kg(entities: list[dict], relations: list[dict], source: str) -> list[MemorySignal]:
|
|
154
|
+
out: list[MemorySignal] = []
|
|
155
|
+
for e in entities:
|
|
156
|
+
name = str(e.get("name") or "").strip()
|
|
157
|
+
if not name:
|
|
158
|
+
continue
|
|
159
|
+
etype = str(e.get("entityType") or "")
|
|
160
|
+
for obs in e.get("observations") or []:
|
|
161
|
+
obs = str(obs)
|
|
162
|
+
for k, rx in KIND_RX.items():
|
|
163
|
+
if rx.search(obs) or (k != "ownership" and rx.search(etype)):
|
|
164
|
+
out.append(MemorySignal(name, k, obs[:300], source))
|
|
165
|
+
for r in relations:
|
|
166
|
+
frm, to, rel = (str(r.get(x) or "").strip() for x in ("from", "to", "relationType"))
|
|
167
|
+
if not (frm and to and rel):
|
|
168
|
+
continue
|
|
169
|
+
if _OWNED_BY.search(rel):
|
|
170
|
+
out.append(MemorySignal(frm, "ownership", f"{frm} {rel} {to}", source))
|
|
171
|
+
elif _OWN_REL.search(rel):
|
|
172
|
+
out.append(MemorySignal(to, "ownership", f"{frm} {rel} {to}", source))
|
|
173
|
+
return out
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def dedupe(signals: list[MemorySignal]) -> list[MemorySignal]:
|
|
177
|
+
seen, out = set(), []
|
|
178
|
+
for s in signals:
|
|
179
|
+
key = (s.path_or_term.lower(), s.kind, s.text)
|
|
180
|
+
if key not in seen:
|
|
181
|
+
seen.add(key)
|
|
182
|
+
out.append(s)
|
|
183
|
+
return out
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
_GENERIC_WORDS = {"module", "modules", "code", "logic", "area", "layer", "component", "components",
|
|
187
|
+
"package", "folder", "directory", "dir", "file", "files", "the", "system",
|
|
188
|
+
"subsystem", "part", "stuff", "service", "library", "lib"}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def matches(signal: MemorySignal, rel_path: str) -> bool:
|
|
192
|
+
"""Does a signal's path/term apply to a project-relative file path?"""
|
|
193
|
+
term = signal.path_or_term.strip().strip("/")
|
|
194
|
+
rel = rel_path.strip("/")
|
|
195
|
+
if not term:
|
|
196
|
+
return False
|
|
197
|
+
if any(c in term for c in "*?["):
|
|
198
|
+
return fnmatch.fnmatch(rel, term) or fnmatch.fnmatch(rel, "*/" + term)
|
|
199
|
+
if "/" in term or "." in term.rsplit("/", 1)[-1]:
|
|
200
|
+
return rel == term or rel.startswith(term + "/") or rel.endswith("/" + term) \
|
|
201
|
+
or ("/" + term + "/") in ("/" + rel + "/")
|
|
202
|
+
words = [w for w in re.split(r"[\s_.-]+", term.lower()) if w and w not in _GENERIC_WORDS]
|
|
203
|
+
if not words:
|
|
204
|
+
return False
|
|
205
|
+
comps = [c for c in re.split(r"[/_.-]+", rel.lower()) if c]
|
|
206
|
+
if len(words) == 1:
|
|
207
|
+
return words[0] in comps or any(c.startswith(words[0]) and len(words[0]) >= 4
|
|
208
|
+
for c in comps)
|
|
209
|
+
joined = "".join(words)
|
|
210
|
+
return joined in "".join(comps) or all(w in comps for w in words)
|