cotrail 0.7.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.
- cotrail/__init__.py +64 -0
- cotrail/aliases.py +132 -0
- cotrail/assistant_setup.py +280 -0
- cotrail/beads.py +41 -0
- cotrail/calls.py +100 -0
- cotrail/cc_transcripts.py +323 -0
- cotrail/claude_ai_export.py +116 -0
- cotrail/cli.py +643 -0
- cotrail/clients.py +423 -0
- cotrail/e1/__init__.py +1 -0
- cotrail/e1/budget.py +71 -0
- cotrail/e1/judge.py +131 -0
- cotrail/e1/llm.py +109 -0
- cotrail/e1/tasks.py +82 -0
- cotrail/e1/variants.py +275 -0
- cotrail/e1b/__init__.py +1 -0
- cotrail/e1b/backends.py +281 -0
- cotrail/e1b/chat.py +95 -0
- cotrail/e1b/coverage.py +169 -0
- cotrail/e1b/decisions.py +114 -0
- cotrail/e1b/judge.py +252 -0
- cotrail/e1b/memory.py +383 -0
- cotrail/e1b/replaces.py +110 -0
- cotrail/e1b/runner.py +264 -0
- cotrail/e1b/selection.py +162 -0
- cotrail/e1b/sleeves.py +305 -0
- cotrail/e1b/steps.py +164 -0
- cotrail/e1b/thinking.py +245 -0
- cotrail/e1b/v9.py +412 -0
- cotrail/e3/__init__.py +1 -0
- cotrail/e3/data.py +135 -0
- cotrail/embed.py +77 -0
- cotrail/episodes.py +143 -0
- cotrail/flow.py +203 -0
- cotrail/graph.py +562 -0
- cotrail/graphify.py +256 -0
- cotrail/ingest.py +264 -0
- cotrail/legacy.py +140 -0
- cotrail/lexical.py +72 -0
- cotrail/mcp_server.py +69 -0
- cotrail/memory.py +2645 -0
- cotrail/memory_mcp.py +517 -0
- cotrail/menu.py +176 -0
- cotrail/model.py +131 -0
- cotrail/overview.py +578 -0
- cotrail/pasted.py +173 -0
- cotrail/privacy.py +75 -0
- cotrail/setup.py +544 -0
- cotrail/sources/__init__.py +16 -0
- cotrail/sources/base.py +40 -0
- cotrail/sources/conceptnet.py +94 -0
- cotrail/sources/experience.py +96 -0
- cotrail/sources/wikidata.py +312 -0
- cotrail/sources/wordnet.py +210 -0
- cotrail/store.py +352 -0
- cotrail/text.py +598 -0
- cotrail/topics.py +56 -0
- cotrail/v2/__init__.py +5 -0
- cotrail/v2/english.py +78 -0
- cotrail/v2/extract.py +155 -0
- cotrail/v2/gate.py +190 -0
- cotrail/v2/graph.py +478 -0
- cotrail/v2/planner.py +59 -0
- cotrail/v2/sleeves.py +212 -0
- cotrail/v2/store.py +193 -0
- cotrail/vendor/3d-force-graph.LICENSE +27 -0
- cotrail/vendor/3d-force-graph.min.js +5 -0
- cotrail/vendor/force-graph.LICENSE +21 -0
- cotrail/vendor/force-graph.min.js +5 -0
- cotrail/vendor/three.LICENSE +21 -0
- cotrail/vendor/three.min.js +6 -0
- cotrail/viewer.py +223 -0
- cotrail/viewer_cosmos.js +514 -0
- cotrail/viewer_flow.js +502 -0
- cotrail/viewer_i18n.js +110 -0
- cotrail/viewer_template.html +393 -0
- cotrail-0.7.1.dist-info/METADATA +471 -0
- cotrail-0.7.1.dist-info/RECORD +82 -0
- cotrail-0.7.1.dist-info/WHEEL +5 -0
- cotrail-0.7.1.dist-info/entry_points.txt +9 -0
- cotrail-0.7.1.dist-info/licenses/LICENSE +202 -0
- cotrail-0.7.1.dist-info/top_level.txt +1 -0
cotrail/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""cotrail — контекстный граф: меню извлечённых подсказок для LLM."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from cotrail import legacy as _legacy
|
|
6
|
+
|
|
7
|
+
_legacy.mirror_env() # CTXGRAPH_* (the old name) fills COTRAIL_* before any module reads it
|
|
8
|
+
|
|
9
|
+
from dataclasses import replace
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from cotrail.embed import Encoder, HashingEncoder, Model2VecEncoder
|
|
13
|
+
from cotrail.graph import Engine
|
|
14
|
+
from cotrail.menu import Menu, MenuConfig
|
|
15
|
+
from cotrail.store import Store
|
|
16
|
+
|
|
17
|
+
__all__ = ["E1_CONFIG", "Engine", "Menu", "MenuConfig", "Store", "build_engine"]
|
|
18
|
+
|
|
19
|
+
#: Конфигурация меню для E1 (reports/prereg_e1.md): слоты как в задании, без «опыта».
|
|
20
|
+
E1_CONFIG = MenuConfig(
|
|
21
|
+
slot_limits=(("deeper", 3), ("side", 2), ("assoc", 2), ("experience", 0)),
|
|
22
|
+
auto_depth=0,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
DEFAULT_DB = Path(__file__).resolve().parent.parent / ".cache" / "graph.sqlite"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def build_engine(
|
|
29
|
+
db: str | Path = DEFAULT_DB,
|
|
30
|
+
*,
|
|
31
|
+
encoder: str | Encoder = "model2vec",
|
|
32
|
+
offline: bool = False,
|
|
33
|
+
conceptnet: bool = False, # api.conceptnet.io отвечает 502; без дампа источник выключен
|
|
34
|
+
experience: bool = True, # слот «опыт»; в E1 выключен (reports/01b_edge_fixes.md §8)
|
|
35
|
+
config: MenuConfig | None = None,
|
|
36
|
+
session: str | None = None,
|
|
37
|
+
seed: int = 0,
|
|
38
|
+
) -> Engine:
|
|
39
|
+
from cotrail.sources import (
|
|
40
|
+
ConceptNetSource,
|
|
41
|
+
ExperienceSource,
|
|
42
|
+
RuWordNetSource,
|
|
43
|
+
WikidataSource,
|
|
44
|
+
WordNetSource,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
store = Store(db)
|
|
48
|
+
if isinstance(encoder, str):
|
|
49
|
+
encoder = HashingEncoder() if encoder == "hashing" else Model2VecEncoder()
|
|
50
|
+
sources = [
|
|
51
|
+
WordNetSource(),
|
|
52
|
+
RuWordNetSource(),
|
|
53
|
+
WikidataSource(store, offline=offline),
|
|
54
|
+
]
|
|
55
|
+
if experience:
|
|
56
|
+
sources += [ExperienceSource(store)]
|
|
57
|
+
else:
|
|
58
|
+
# Без опыта нет и сокращений в слоте «опыт»: лимит слота 0.
|
|
59
|
+
base = config or MenuConfig()
|
|
60
|
+
limits = tuple((k, 0 if k == "experience" else v) for k, v in base.slot_limits)
|
|
61
|
+
config = replace(base, slot_limits=limits)
|
|
62
|
+
if conceptnet:
|
|
63
|
+
sources.insert(3, ConceptNetSource(store, offline=offline))
|
|
64
|
+
return Engine(store, sources, encoder, config=config, session=session, seed=seed)
|
cotrail/aliases.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Name variants of one concept ("Postgres" / "PostgreSQL", "ctx-graph" / "cotrail", "постгрес" / "postgres").
|
|
2
|
+
|
|
3
|
+
Rule: the aliases rule (written before the code). The idea - entity resolution by trigram
|
|
4
|
+
similarity with pg_trgm-style thresholds - is taken from Hindsight (github.com/vectorize-io/hindsight, MIT,
|
|
5
|
+
Copyright (c) Vectorize); this is our own re-implementation, no code copied. No model, no LLM.
|
|
6
|
+
|
|
7
|
+
The originals are never changed: the pairs live in a separate table and recall maps a concept to the canonical
|
|
8
|
+
one of its group only where it compares concepts across turns. `COTRAIL_ALIASES=off` turns it off.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
|
|
17
|
+
SIM = 0.5 # Hindsight's in-batch merge threshold (pg_trgm similarity)
|
|
18
|
+
MIN_CHARS = 4
|
|
19
|
+
SKIP_KINDS = {"ent:DATE", "ent:TIME", "path", "code"}
|
|
20
|
+
_TR = dict(zip("абвгдежзийклмнопрстуфхцчшщъыьэюяё",
|
|
21
|
+
["a", "b", "v", "g", "d", "e", "zh", "z", "i", "i", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u",
|
|
22
|
+
"f", "h", "c", "ch", "sh", "sh", "", "y", "", "e", "yu", "ya", "e"])) # fmt: skip
|
|
23
|
+
_NON = re.compile(r"[^0-9a-z]+")
|
|
24
|
+
_HASH = re.compile(r"[0-9a-f]{7,40}")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def enabled() -> bool:
|
|
28
|
+
return os.environ.get("COTRAIL_ALIASES", "on").lower() not in ("off", "0", "no", "false")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def key(label: str) -> str:
|
|
32
|
+
"""Lower case, Cyrillic -> Latin, every non-alphanumeric run -> one space."""
|
|
33
|
+
s = label.lower()
|
|
34
|
+
if s.startswith("c:"):
|
|
35
|
+
s = s[2:]
|
|
36
|
+
s = "".join(_TR.get(ch, ch) for ch in s)
|
|
37
|
+
return _NON.sub(" ", s).strip()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def trigrams(k: str) -> set[str]:
|
|
41
|
+
"""pg_trgm: each word padded with two spaces in front and one behind."""
|
|
42
|
+
out = set()
|
|
43
|
+
for w in k.split():
|
|
44
|
+
p = " " + w + " "
|
|
45
|
+
out.update(p[i:i + 3] for i in range(len(p) - 2))
|
|
46
|
+
return out
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def similarity(a: str, b: str) -> float:
|
|
50
|
+
ta, tb = trigrams(a), trigrams(b)
|
|
51
|
+
return len(ta & tb) / len(ta | tb) if ta and tb else 0.0
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _digits(k: str) -> str:
|
|
55
|
+
return "".join(ch for ch in k if ch.isdigit())
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def eligible(k: str, kind: str = "") -> bool:
|
|
59
|
+
flat = k.replace(" ", "")
|
|
60
|
+
return kind not in SKIP_KINDS and len(flat) >= MIN_CHARS and not _HASH.fullmatch(flat)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def same(a: str, b: str) -> tuple[bool, float, str]:
|
|
64
|
+
"""(alias?, similarity, method) for two keys by the rule (both assumed eligible)."""
|
|
65
|
+
if a == b:
|
|
66
|
+
return True, 1.0, "equal"
|
|
67
|
+
if a.replace(" ", "") == b.replace(" ", ""):
|
|
68
|
+
return True, 1.0, "spaces"
|
|
69
|
+
if len(a.split()) != len(b.split()) or _digits(a) != _digits(b):
|
|
70
|
+
return False, 0.0, ""
|
|
71
|
+
s = similarity(a, b)
|
|
72
|
+
return s >= SIM, s, "trigram"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def pairs(concepts: list[tuple[str, str, str, int]]) -> list[tuple[str, str, float, str]]:
|
|
76
|
+
"""Alias pairs among (id, label, kind, first_seq) rows: (alias, canonical, sim, method), one row per
|
|
77
|
+
non-canonical member of a group (canonical = smallest first_seq, then id)."""
|
|
78
|
+
items = []
|
|
79
|
+
for cid, label, kind, seq in concepts:
|
|
80
|
+
k = key(cid)
|
|
81
|
+
if eligible(k, kind or ""):
|
|
82
|
+
items.append((cid, k, seq))
|
|
83
|
+
tri = [trigrams(k) for _, k, _ in items]
|
|
84
|
+
freq: dict[str, int] = {}
|
|
85
|
+
for t in tri:
|
|
86
|
+
for g in t:
|
|
87
|
+
freq[g] = freq.get(g, 0) + 1
|
|
88
|
+
# prefix filter for Jaccard >= SIM: a pair shares at least one of the first n - ceil(SIM*n) + 1 rarest trigrams
|
|
89
|
+
post: dict[str, list[int]] = {}
|
|
90
|
+
pref = []
|
|
91
|
+
for i, t in enumerate(tri):
|
|
92
|
+
order = sorted(t, key=lambda g: (freq[g], g))
|
|
93
|
+
p = order[: len(order) - math.ceil(SIM * len(order)) + 1]
|
|
94
|
+
pref.append(p)
|
|
95
|
+
for g in p:
|
|
96
|
+
post.setdefault(g, []).append(i)
|
|
97
|
+
flat: dict[str, list[int]] = {}
|
|
98
|
+
for i, (_, k, _) in enumerate(items):
|
|
99
|
+
flat.setdefault(k.replace(" ", ""), []).append(i)
|
|
100
|
+
parent = list(range(len(items)))
|
|
101
|
+
|
|
102
|
+
def find(i: int) -> int:
|
|
103
|
+
while parent[i] != i:
|
|
104
|
+
parent[i] = parent[parent[i]]
|
|
105
|
+
i = parent[i]
|
|
106
|
+
return i
|
|
107
|
+
|
|
108
|
+
best: dict[tuple[int, int], tuple[float, str]] = {}
|
|
109
|
+
cand: set[tuple[int, int]] = set()
|
|
110
|
+
for i, p in enumerate(pref):
|
|
111
|
+
for g in p:
|
|
112
|
+
cand.update((min(i, j), max(i, j)) for j in post[g] if j != i)
|
|
113
|
+
for group in flat.values():
|
|
114
|
+
cand.update((a, b) for a in group for b in group if a < b)
|
|
115
|
+
for i, j in cand:
|
|
116
|
+
ok, s, how = same(items[i][1], items[j][1])
|
|
117
|
+
if ok:
|
|
118
|
+
best[(i, j)] = (s, how)
|
|
119
|
+
parent[find(i)] = find(j)
|
|
120
|
+
groups: dict[int, list[int]] = {}
|
|
121
|
+
for i in range(len(items)):
|
|
122
|
+
groups.setdefault(find(i), []).append(i)
|
|
123
|
+
out = []
|
|
124
|
+
for members in groups.values():
|
|
125
|
+
if len(members) < 2:
|
|
126
|
+
continue
|
|
127
|
+
canon = min(members, key=lambda i: (items[i][2], items[i][0]))
|
|
128
|
+
for i in members:
|
|
129
|
+
if i != canon:
|
|
130
|
+
s, how = best.get((min(i, canon), max(i, canon)), (0.0, "group"))
|
|
131
|
+
out.append((items[i][0], items[canon][0], s, how))
|
|
132
|
+
return out
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""Setup through the assistant (the MCP setup tools): list memories, connect a folder, join a team, find and import
|
|
2
|
+
chats. "Show before write": every call that changes something is a dry run unless `confirm=True`; the dry run says
|
|
3
|
+
exactly what would be written, and the assistant asks the user before calling again with confirm=True.
|
|
4
|
+
|
|
5
|
+
Nothing here leaves the machine except `join_team(confirm=True)`, which pushes to the user's private memory repo
|
|
6
|
+
after the repo check (lines the check flags are held back locally and listed).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from cotrail import memory as M
|
|
17
|
+
|
|
18
|
+
ASK = "Nothing written yet. Show this to the user; call again with confirm=true only after the user says yes."
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _home(home) -> Path:
|
|
22
|
+
return Path(home or M.HOME)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _identity(store: Path) -> str:
|
|
26
|
+
import sqlite3
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
con = sqlite3.connect(str(store / "graph.sqlite"))
|
|
30
|
+
try:
|
|
31
|
+
row = con.execute("SELECT value FROM memory_meta WHERE key='identity'").fetchone()
|
|
32
|
+
finally:
|
|
33
|
+
con.close()
|
|
34
|
+
return row[0] if row else ""
|
|
35
|
+
except sqlite3.Error:
|
|
36
|
+
return ""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def list_memories(home=None) -> list[dict]:
|
|
40
|
+
"""Every memory with a short friendly name (the repo name of its git remote, else its folder's name)."""
|
|
41
|
+
out = []
|
|
42
|
+
for k in M.known_projects(_home(home)):
|
|
43
|
+
d = Path(k["store"]).parent
|
|
44
|
+
try:
|
|
45
|
+
cfg = json.loads((d / "sync.json").read_text("utf-8"))
|
|
46
|
+
except (OSError, ValueError):
|
|
47
|
+
cfg = {}
|
|
48
|
+
ident = _identity(d)
|
|
49
|
+
name = (ident.rsplit("/", 1)[-1] if ident else Path(k["path"]).name or k["slug"]).lower()
|
|
50
|
+
out.append({"name": name, "memory": k["slug"], "folder": k["path"], "records": k["records"], "last": k["last"],
|
|
51
|
+
"kind": "team" if cfg.get("remote") else "local",
|
|
52
|
+
"team": re.sub(r"//[^/@]+@", "//", cfg.get("remote", "")), "author": cfg.get("author", "")}) # fmt: skip
|
|
53
|
+
return sorted(out, key=lambda r: r["last"], reverse=True)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def format_memories(rows: list[dict]) -> str:
|
|
57
|
+
if not rows:
|
|
58
|
+
return "No memories yet on this computer."
|
|
59
|
+
dup = {r["name"] for r in rows if sum(x["name"] == r["name"] for x in rows) > 1}
|
|
60
|
+
return "\n".join(f"- {r['memory'] if r['name'] in dup else r['name']} ({r['kind']}, {r['records']} records, "
|
|
61
|
+
f"last {r['last'] or '-'}) · {r['folder']}" for r in rows) # fmt: skip
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def workspace_problem(folder: str | Path, home=None) -> str:
|
|
65
|
+
"""The server's folder is a workspace (home, drive root, or a folder holding several projects) with no memory of
|
|
66
|
+
its own: no default memory - the chat must pick one. "" when the folder is a project (or has its own memory)."""
|
|
67
|
+
home = _home(home)
|
|
68
|
+
folder = Path(folder).resolve()
|
|
69
|
+
if (M.store_dir(folder, home) / "graph.sqlite").exists() or M.git_remote(folder):
|
|
70
|
+
return ""
|
|
71
|
+
inside = [r for r in list_memories(home) if r["folder"] and Path(r["folder"]).is_absolute()
|
|
72
|
+
and folder in Path(r["folder"]).resolve().parents] # fmt: skip
|
|
73
|
+
kids = any((c / ".git").exists() for c in folder.iterdir() if c.is_dir()) if folder.is_dir() else False
|
|
74
|
+
if not (folder == Path.home().resolve() or folder.parent == folder or inside or kids):
|
|
75
|
+
return ""
|
|
76
|
+
return ("No memory chosen for this chat (the server's folder " + str(folder) + " holds several projects). "
|
|
77
|
+
"Memories:\n" + format_memories(list_memories(home)) + "\nAsk the user once which one for this chat (or "
|
|
78
|
+
"take it from their words), then pass memory=<name> on every call.") # fmt: skip
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class UnknownMemory(ValueError):
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def resolve_memory(memory: str, home=None) -> tuple[Path, Path]:
|
|
86
|
+
"""(store folder, project folder) of an EXISTING memory: a name from list_memories, a project folder that has a
|
|
87
|
+
memory, or a git remote URL. Never creates anything; unknown -> UnknownMemory listing the memories."""
|
|
88
|
+
home = _home(home)
|
|
89
|
+
v = (memory or "").strip()
|
|
90
|
+
cand: Path | None = None
|
|
91
|
+
if v and (home / v / "graph.sqlite").exists():
|
|
92
|
+
cand = home / v
|
|
93
|
+
elif v and ("://" in v or re.match(r"^[\w.-]+@[\w.-]+:", v)):
|
|
94
|
+
rid = M.remote_slug(v)
|
|
95
|
+
al = M._aliases(home).get(rid)
|
|
96
|
+
for d in (home / rid, home / al if al else None):
|
|
97
|
+
if d is not None and (d / "graph.sqlite").exists():
|
|
98
|
+
cand = d
|
|
99
|
+
break
|
|
100
|
+
elif v and Path(v).expanduser().is_dir():
|
|
101
|
+
d = M.store_dir(Path(v).expanduser(), home)
|
|
102
|
+
cand = d if (d / "graph.sqlite").exists() else None
|
|
103
|
+
if cand is None and v:
|
|
104
|
+
hits = [r for r in list_memories(home) if r["name"] == v.lower()]
|
|
105
|
+
if len(hits) > 1:
|
|
106
|
+
raise UnknownMemory(f"{memory!r} is ambiguous: " + ", ".join(f"{r['memory']} ({r['folder']})" for r in hits)
|
|
107
|
+
+ ". Ask the user which one and pass its id as memory=.") # fmt: skip
|
|
108
|
+
if hits:
|
|
109
|
+
cand = home / hits[0]["memory"]
|
|
110
|
+
if cand is None:
|
|
111
|
+
names = ", ".join(r["name"] for r in list_memories(home)) or "none yet"
|
|
112
|
+
raise UnknownMemory(f"No memory {memory!r}. Available memories: {names}. Call list_memories and pass one "
|
|
113
|
+
"of these names as memory=.") # fmt: skip
|
|
114
|
+
rows = [k for k in M.known_projects(home) if Path(k["store"]).parent == cand]
|
|
115
|
+
folder = Path(rows[0]["path"]) if rows and rows[0]["exact"] else cand
|
|
116
|
+
return cand, folder
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _target(memory: str | None, home: Path) -> Path | None:
|
|
120
|
+
"""An existing memory by its name (store folder) or by a folder that has one; None = the folder's own."""
|
|
121
|
+
if not memory or memory.lower() in ("auto", "new", "own"):
|
|
122
|
+
return None
|
|
123
|
+
if (home / memory / "graph.sqlite").exists():
|
|
124
|
+
return home / memory
|
|
125
|
+
p = Path(memory).expanduser()
|
|
126
|
+
if p.is_dir() and (M.store_dir(p, home) / "graph.sqlite").exists():
|
|
127
|
+
return M.store_dir(p, home)
|
|
128
|
+
raise ValueError(f"no memory named {memory!r}: call list_memories")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _sessions(folder: Path) -> int:
|
|
132
|
+
d = M.claude_project_dir(folder)
|
|
133
|
+
return len(list(d.glob("*.jsonl"))) if d.is_dir() else 0
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def connect_folder(path: str, memory: str | None = None, home=None, confirm: bool = False) -> str:
|
|
137
|
+
"""Point a folder at a memory (its own, or an existing one) and import its Claude Code chats."""
|
|
138
|
+
home = _home(home)
|
|
139
|
+
folder = Path(path).expanduser().resolve()
|
|
140
|
+
if not folder.is_dir():
|
|
141
|
+
return f"No such folder: {folder}"
|
|
142
|
+
own = M.store_dir(folder, home)
|
|
143
|
+
target = _target(memory, home) or own
|
|
144
|
+
remote = M.git_remote(folder)
|
|
145
|
+
key = M.remote_slug(remote) if remote else M.project_slug(folder)
|
|
146
|
+
n = _sessions(folder)
|
|
147
|
+
if target != own and (own / "graph.sqlite").exists():
|
|
148
|
+
return (f"{folder} already has its own memory ({own.name}); joining two memories is not supported. "
|
|
149
|
+
"Use its own memory, or pick another folder.")
|
|
150
|
+
plan = [f"Folder: {folder}" + (f" (git remote {M.normalize_remote(remote)}: every clone shares it)" if remote else ""),
|
|
151
|
+
f"Memory: {target.name}" + (" (exists)" if (target / "graph.sqlite").exists() else " (new)"),
|
|
152
|
+
f"Import: {n} Claude Code chat file(s) of this folder (read locally, nothing leaves the computer)"] # fmt: skip
|
|
153
|
+
if not confirm:
|
|
154
|
+
return "\n".join(["Would connect:", *plan, ASK])
|
|
155
|
+
if target != own:
|
|
156
|
+
al = M._aliases(home) | {key: target.name}
|
|
157
|
+
home.mkdir(parents=True, exist_ok=True)
|
|
158
|
+
M._aliases_path(home).write_text(json.dumps(al, indent=1), "utf-8")
|
|
159
|
+
m = M.ProjectMemory(folder, home=home)
|
|
160
|
+
r = m.import_claude_code() if n else {"new": 0}
|
|
161
|
+
return f"Connected {folder} to memory {m.dir.name}; imported {r['new']} new turn(s)."
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def join_team(sync_repo: str, project: str | None = None, name: str | None = None, home=None, confirm: bool = False,
|
|
165
|
+
check=None) -> str: # fmt: skip
|
|
166
|
+
from cotrail import repo_check as RC
|
|
167
|
+
from cotrail import sync as S
|
|
168
|
+
from cotrail import team as T
|
|
169
|
+
|
|
170
|
+
home = _home(home)
|
|
171
|
+
project = Path(project or os.environ.get("COTRAIL_PROJECT") or Path.cwd()).resolve()
|
|
172
|
+
bad = T.folder_problem(project, home)
|
|
173
|
+
if bad: # the assistant passes memory= (a project with a git remote) instead
|
|
174
|
+
return "Not joined: " + bad.replace("`--force` joins this folder anyway.", "Pass memory=<a project memory>.")
|
|
175
|
+
vis = (check or T.visibility)(sync_repo)
|
|
176
|
+
if vis == "PUBLIC":
|
|
177
|
+
return f"Refused: {sync_repo} is PUBLIC. The memory repo must be private."
|
|
178
|
+
who = (name or "").strip() or S.load_config(project, home).get("author") or M.default_author(project)
|
|
179
|
+
db = M.store_dir(project, home) / "graph.sqlite"
|
|
180
|
+
rows = [S._scrubbed(r) for r in S.local_episodes(db, who)]
|
|
181
|
+
held = RC.check_rows(rows)
|
|
182
|
+
plan = [T.WARNING, "", f"Repository: {sync_repo} (visibility: {vis.lower() or 'could not check - make sure it is PRIVATE'})",
|
|
183
|
+
f"Project: {M.project_identity(project) or project}", f"Your name on the records: {who or '(none: give name)'}",
|
|
184
|
+
f"Would push: {len(rows) - len({b['id'] for b in held})} record(s) already in this memory, plus this "
|
|
185
|
+
"folder's Claude Code chats (imported first)",
|
|
186
|
+
f"Held back by the secret check (stay local, never pushed): {len({b['id'] for b in held})}"
|
|
187
|
+
+ (": " + ", ".join(f"{b['id']} {b['field']}:{b['kind']}" for b in held[:10]) if held else "")] # fmt: skip
|
|
188
|
+
if not confirm:
|
|
189
|
+
return "\n".join(["Would join the team memory:", *plan, ASK])
|
|
190
|
+
if not who:
|
|
191
|
+
return "No name: ask the user for the name to put on the records, then call again with name=..."
|
|
192
|
+
logs: list[str] = []
|
|
193
|
+
try:
|
|
194
|
+
r = T.join(project, sync_repo, home, name=who, check=lambda _u: vis, log=logs.append, force=True)
|
|
195
|
+
except (T.TeamError, S.SyncError) as e:
|
|
196
|
+
return f"Not joined: {e}"
|
|
197
|
+
tail = f" Held back by the secret check (not pushed): {r['held']}." if r.get("held") else ""
|
|
198
|
+
joined = next((x for x in logs if x.startswith("Joined as")), "Joined.")
|
|
199
|
+
return joined + tail + " " + logs[-1]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _first_prompt(f: Path) -> tuple[str, str, str]:
|
|
203
|
+
"""cwd, first user text, first timestamp of a Claude Code transcript (first ~80 lines)."""
|
|
204
|
+
from cotrail import cc_transcripts as CC
|
|
205
|
+
|
|
206
|
+
cwd = text = ts = ""
|
|
207
|
+
try:
|
|
208
|
+
with f.open(encoding="utf-8", errors="replace") as fh:
|
|
209
|
+
for _, ln in zip(range(80), fh):
|
|
210
|
+
try:
|
|
211
|
+
r = json.loads(ln)
|
|
212
|
+
except ValueError:
|
|
213
|
+
continue
|
|
214
|
+
cwd = cwd or r.get("cwd") or ""
|
|
215
|
+
ts = ts or r.get("timestamp") or ""
|
|
216
|
+
if not text and r.get("type") == "user" and not r.get("isMeta"):
|
|
217
|
+
t = CC.clean(CC._text((r.get("message") or {}).get("content")))
|
|
218
|
+
if t and not t.startswith("<"):
|
|
219
|
+
text = t
|
|
220
|
+
if cwd and text:
|
|
221
|
+
break
|
|
222
|
+
except OSError:
|
|
223
|
+
pass
|
|
224
|
+
return cwd, text, ts
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def find_chats(query: str = "", export: str | None = None, limit: int = 30) -> list[dict]:
|
|
228
|
+
"""Claude Code chats on this computer (folder or first prompt contains `query`), and with `export` the claude.ai
|
|
229
|
+
conversations whose title contains it. Read only."""
|
|
230
|
+
q = (query or "").lower()
|
|
231
|
+
out = []
|
|
232
|
+
root = Path.home() / ".claude" / "projects"
|
|
233
|
+
for f in sorted(root.glob("*/*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True) if root.is_dir() else []:
|
|
234
|
+
cwd, text, ts = _first_prompt(f)
|
|
235
|
+
if q and q not in cwd.lower() and q not in text.lower():
|
|
236
|
+
continue
|
|
237
|
+
out.append({"id": "cc:" + f.stem[:8], "date": ts[:10], "where": cwd or f.parent.name, "title": text[:90]})
|
|
238
|
+
if len(out) >= limit:
|
|
239
|
+
break
|
|
240
|
+
if export:
|
|
241
|
+
from cotrail import claude_ai_export as CA
|
|
242
|
+
|
|
243
|
+
conv, projects = CA.load(export)
|
|
244
|
+
rows = [r for r in CA.summary(conv, projects) if not q or q in r["title"].lower() or q in r["project"].lower()]
|
|
245
|
+
out += [{"id": "ai:" + r["id"][:8], "date": r["date"], "where": "claude.ai" + (f" [{r['project']}]" if r["project"]
|
|
246
|
+
else ""), "title": r["title"][:90]} for r in sorted(rows, key=lambda r: r["date"], reverse=True)[:limit]] # fmt: skip
|
|
247
|
+
return out
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def format_chats(rows: list[dict]) -> str:
|
|
251
|
+
if not rows:
|
|
252
|
+
return "No chats found."
|
|
253
|
+
return "\n".join(f"- {r['id']} · {r['date']} · {r['where']} · {r['title']}" for r in rows)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def import_chats(ids: list[str], memory: str | None = None, export: str | None = None, project: str | None = None,
|
|
257
|
+
home=None, confirm: bool = False) -> str: # fmt: skip
|
|
258
|
+
home = _home(home)
|
|
259
|
+
cc = [i[3:] for i in ids if i.startswith("cc:")]
|
|
260
|
+
ai = [i[3:] for i in ids if i.startswith("ai:")]
|
|
261
|
+
if ai and not export:
|
|
262
|
+
return "claude.ai chats need the export: give export=<path to the .zip>."
|
|
263
|
+
root = Path.home() / ".claude" / "projects"
|
|
264
|
+
files = [f for f in root.glob("*/*.jsonl") if any(f.stem.startswith(c) for c in cc)] if cc else []
|
|
265
|
+
tgt = _target(memory, home)
|
|
266
|
+
folder = Path(project or os.environ.get("COTRAIL_PROJECT") or Path.cwd()).resolve()
|
|
267
|
+
if tgt is not None:
|
|
268
|
+
rows = [k for k in M.known_projects(home) if Path(k["store"]).parent == tgt]
|
|
269
|
+
folder = Path(rows[0]["path"]) if rows and Path(rows[0]["path"]).is_dir() else folder
|
|
270
|
+
dest = tgt or M.store_dir(folder, home)
|
|
271
|
+
plan = [f"Into memory: {dest.name}", f"Claude Code chats: {len(files)} of {len(cc)} asked",
|
|
272
|
+
f"claude.ai chats: {len(ai)}" + (f" from {export}" if ai else "")] # fmt: skip
|
|
273
|
+
if not confirm:
|
|
274
|
+
return "\n".join(["Would import:", *plan, ASK])
|
|
275
|
+
if tgt is not None and M.store_dir(folder, home) != tgt:
|
|
276
|
+
return f"Memory {tgt.name}: its folder is not on this computer; connect a folder to it first."
|
|
277
|
+
m = M.ProjectMemory(folder, home=home)
|
|
278
|
+
n = m.import_claude_code(files=files)["new"] if files else 0
|
|
279
|
+
k = m.import_claude_ai(export, ids=ai)["new"] if ai else 0
|
|
280
|
+
return f"Imported into {m.dir.name}: {n} turn(s) from Claude Code, {k} from claude.ai (each with your name)."
|
cotrail/beads.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Read-only source of deferred items: Beads issues (github.com/gastownhall/beads, MIT) in `<project>/.beads/*.jsonl`.
|
|
2
|
+
|
|
3
|
+
Beads keeps its truth in Dolt; `.beads/issues.jsonl` is an export, rewritten whole. We only read it, never write, and
|
|
4
|
+
use none of Beads' code. An issue counts as deferred ("later") when its status is `deferred`, or it has a non-empty
|
|
5
|
+
`defer_until`, or a `later` label; `closed` issues never count. Lines of other types (`_type` other than "issue"),
|
|
6
|
+
unknown fields and broken lines are skipped (rules written before the code).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def deferred(project: str | Path) -> list[dict]:
|
|
16
|
+
"""[{"id", "date", "text", "status"}] of deferred Beads issues, newest first; [] without a `.beads` folder."""
|
|
17
|
+
d = Path(project) / ".beads"
|
|
18
|
+
if not d.is_dir():
|
|
19
|
+
return []
|
|
20
|
+
seen, out = set(), []
|
|
21
|
+
for f in sorted(d.glob("*.jsonl")):
|
|
22
|
+
try:
|
|
23
|
+
lines = f.read_text("utf-8", errors="replace").splitlines()
|
|
24
|
+
except OSError:
|
|
25
|
+
continue
|
|
26
|
+
for ln in lines:
|
|
27
|
+
try:
|
|
28
|
+
r = json.loads(ln)
|
|
29
|
+
except json.JSONDecodeError:
|
|
30
|
+
continue
|
|
31
|
+
if not isinstance(r, dict) or r.get("_type", "issue") != "issue" or not r.get("id") or not r.get("title"):
|
|
32
|
+
continue
|
|
33
|
+
status = str(r.get("status") or "")
|
|
34
|
+
labels = r.get("labels") or []
|
|
35
|
+
later = status == "deferred" or bool(r.get("defer_until")) or "later" in labels
|
|
36
|
+
if status == "closed" or not later or r["id"] in seen:
|
|
37
|
+
continue
|
|
38
|
+
seen.add(r["id"])
|
|
39
|
+
date = str(r.get("updated_at") or r.get("created_at") or "")[:10]
|
|
40
|
+
out.append({"id": str(r["id"]), "date": date, "text": str(r["title"]).strip(), "status": status})
|
|
41
|
+
return sorted(out, key=lambda x: x["date"], reverse=True)
|
cotrail/calls.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Local log of the memory's MCP tool calls: `~/.cotrail/<project>/calls.jsonl`, for the «Живая память» view.
|
|
2
|
+
|
|
3
|
+
One JSON line per tool call: {"t": UTC ISO time, "tool": tool name, "ids": record ids (#...) in the result, "ms":
|
|
4
|
+
duration}. NEVER the query text or any record text: only ids, which are already local labels of the store.
|
|
5
|
+
Bounded (rule fixed before the code): when calls.jsonl reaches MAX_BYTES it is renamed to calls.1.jsonl (the older
|
|
6
|
+
part is dropped) and a new file starts - at most ~2 x MAX_BYTES on disk. A failure to log never fails a tool call.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import datetime as dt
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
NAME, OLD = "calls.jsonl", "calls.1.jsonl"
|
|
17
|
+
MAX_BYTES = 1_000_000 # ~8-10 thousand calls per file
|
|
18
|
+
MAX_IDS = 40
|
|
19
|
+
# record ids as recall / expand / decisions print them: "#" + 4-8 hex characters of the episode id
|
|
20
|
+
ID = re.compile(r"#([0-9a-f]{4,8})\b")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def ids_of(text) -> list[str]:
|
|
24
|
+
"""Record ids in a tool result, in order, without repeats."""
|
|
25
|
+
out: list[str] = []
|
|
26
|
+
for x in ID.findall(text if isinstance(text, str) else ""):
|
|
27
|
+
if x not in out:
|
|
28
|
+
out.append(x)
|
|
29
|
+
return out[:MAX_IDS]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def log_call(folder: Path, tool: str, result, ms: float, now: dt.datetime | None = None) -> None:
|
|
33
|
+
"""Append one line; any error (read-only disk, a locked file) is swallowed."""
|
|
34
|
+
try:
|
|
35
|
+
folder = Path(folder)
|
|
36
|
+
p = folder / NAME
|
|
37
|
+
if p.exists() and p.stat().st_size >= MAX_BYTES:
|
|
38
|
+
p.replace(folder / OLD)
|
|
39
|
+
t = (now or dt.datetime.now(dt.UTC)).astimezone(dt.UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
40
|
+
line = json.dumps({"t": t, "tool": str(tool), "ids": ids_of(result), "ms": int(round(ms))}, ensure_ascii=False)
|
|
41
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
with p.open("a", encoding="utf-8") as f:
|
|
43
|
+
f.write(line + "\n")
|
|
44
|
+
except Exception: # noqa: BLE001 - logging must never fail a tool call
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _lines(p: Path) -> list[dict]:
|
|
49
|
+
out = []
|
|
50
|
+
try:
|
|
51
|
+
raw = p.read_text("utf-8", errors="replace")
|
|
52
|
+
except OSError:
|
|
53
|
+
return out
|
|
54
|
+
for ln in raw.splitlines():
|
|
55
|
+
try:
|
|
56
|
+
c = json.loads(ln)
|
|
57
|
+
except ValueError:
|
|
58
|
+
continue # a line cut by a crash
|
|
59
|
+
if isinstance(c, dict) and isinstance(c.get("t"), str) and isinstance(c.get("tool"), str):
|
|
60
|
+
out.append({"t": c["t"], "tool": c["tool"], "ids": [str(x) for x in c.get("ids") or []][:MAX_IDS],
|
|
61
|
+
"ms": int(c.get("ms") or 0)}) # fmt: skip
|
|
62
|
+
return out
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def read_calls(folder: Path, limit: int = 3000) -> list[dict]:
|
|
66
|
+
"""The latest `limit` calls, oldest first (the rotated part, then the current file)."""
|
|
67
|
+
folder = Path(folder)
|
|
68
|
+
return (_lines(folder / OLD) + _lines(folder / NAME))[-limit:]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def size(folder: Path) -> int:
|
|
72
|
+
"""The current file's size: the offset from which a live page polls."""
|
|
73
|
+
try:
|
|
74
|
+
return (Path(folder) / NAME).stat().st_size
|
|
75
|
+
except OSError:
|
|
76
|
+
return 0
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def read_from(folder: Path, offset: int) -> tuple[int, list[dict]]:
|
|
80
|
+
"""Calls appended after byte `offset` of the current file -> (new offset, calls). A file shorter than the offset
|
|
81
|
+
was rotated: read it from the start."""
|
|
82
|
+
p = Path(folder) / NAME
|
|
83
|
+
try:
|
|
84
|
+
size = p.stat().st_size
|
|
85
|
+
except OSError:
|
|
86
|
+
return 0, []
|
|
87
|
+
if offset > size or offset < 0:
|
|
88
|
+
offset = 0
|
|
89
|
+
with p.open("rb") as f:
|
|
90
|
+
f.seek(offset)
|
|
91
|
+
raw = f.read()
|
|
92
|
+
cut = raw.rfind(b"\n") + 1 # a half-written last line waits for the next poll
|
|
93
|
+
out = []
|
|
94
|
+
for ln in raw[:cut].decode("utf-8", errors="replace").splitlines():
|
|
95
|
+
try:
|
|
96
|
+
c = json.loads(ln)
|
|
97
|
+
out.append({"t": c["t"], "tool": c["tool"], "ids": list(c.get("ids") or [])[:MAX_IDS], "ms": int(c.get("ms") or 0)})
|
|
98
|
+
except (ValueError, KeyError, TypeError):
|
|
99
|
+
continue
|
|
100
|
+
return offset + cut, out
|