claudecode-memanto 0.1.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.
@@ -0,0 +1,28 @@
1
+ """Cross-session engineering memory for Claude Code + mattpocock/skills.
2
+
3
+ Memanto becomes a global, active memory companion across skill executions.
4
+ Three real Claude Code lifecycle hooks make it work without manual effort:
5
+
6
+ * ``SessionStart`` -> inject the accumulated Engineering Profile once.
7
+ * ``UserPromptExpansion`` -> recall memories relevant to the skill being invoked
8
+ and inject them before Claude reads the prompt.
9
+ * ``Stop`` -> distill the just-finished session into typed memories
10
+ using Memanto's backend LLM, then persist them.
11
+
12
+ The public surface is intentionally tiny:
13
+
14
+ from claudecode_memanto import SkillMemory
15
+
16
+ mem = SkillMemory() # reads MOORCHEH_API_KEY + MEMANTO_AGENT_ID
17
+ block = mem.recall_for_skill("tdd", task_hint="auth module")
18
+ mem.distill_and_store("tdd", transcript)
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from .client import SkillMemory
24
+ from .config import SkillsConfig
25
+ from .profile import MemoryProfile
26
+
27
+ __all__ = ["SkillMemory", "SkillsConfig", "MemoryProfile"]
28
+ __version__ = "0.1.0"
@@ -0,0 +1,156 @@
1
+ """``claudecode-memanto`` CLI — manual control over the skill memory layer.
2
+
3
+ The lifecycle hooks make memory automatic; this CLI is the manual escape hatch
4
+ (and what the /memanto-companion skill shells out to):
5
+
6
+ claudecode-memanto recall <skill> [--hint TEXT] # print injectable context
7
+ claudecode-memanto store <skill> "summary..." # distill + persist
8
+ claudecode-memanto profile # show accumulated profile
9
+ claudecode-memanto install [--global] # register lifecycle hooks
10
+ claudecode-memanto doctor # check config + connectivity
11
+
12
+ Uses only the standard library (argparse) to stay dependency-light.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import sys
19
+
20
+ from .client import SkillMemory
21
+ from .config import ConfigError, SkillsConfig
22
+ from .skill_map import known_skills
23
+
24
+
25
+ def main(argv: list[str] | None = None) -> int:
26
+ """Dispatch the ``claudecode-memanto`` CLI.
27
+
28
+ Parses ``argv`` (defaulting to ``sys.argv``), runs the matching subcommand,
29
+ and returns its exit code. Network/API failures are surfaced as a single
30
+ clean error line, not a traceback.
31
+ """
32
+ parser = argparse.ArgumentParser(
33
+ prog="claudecode-memanto",
34
+ description="Cross-session engineering memory for Claude Code skills.",
35
+ )
36
+ sub = parser.add_subparsers(dest="command", required=True)
37
+
38
+ p_recall = sub.add_parser("recall", help="Print injectable context for a skill.")
39
+ p_recall.add_argument("skill", help="Skill name, e.g. tdd, grill-with-docs.")
40
+ p_recall.add_argument("--hint", default=None, help="Current task hint.")
41
+
42
+ p_store = sub.add_parser("store", help="Distill a session summary into memory.")
43
+ p_store.add_argument("skill", help="Skill name the summary came from.")
44
+ p_store.add_argument("summary", help="Free-text session summary.")
45
+
46
+ sub.add_parser("profile", help="Show the accumulated engineering profile.")
47
+ sub.add_parser("doctor", help="Check configuration and connectivity.")
48
+
49
+ p_install = sub.add_parser(
50
+ "install", help="Install the Memanto integration (hooks or prompt)."
51
+ )
52
+ p_install.add_argument(
53
+ "--method",
54
+ choices=["hooks", "prompt"],
55
+ default="hooks",
56
+ help="Installation method to use.",
57
+ )
58
+ p_install.add_argument(
59
+ "--global",
60
+ dest="global_scope",
61
+ action="store_true",
62
+ help="Install into ~/.claude/settings.json instead of ./.claude/settings.json.",
63
+ )
64
+
65
+ p_uninstall = sub.add_parser("uninstall", help="Remove the lifecycle hooks.")
66
+ p_uninstall.add_argument(
67
+ "--global",
68
+ dest="global_scope",
69
+ action="store_true",
70
+ help="Uninstall from ~/.claude/settings.json instead of ./.claude/settings.json.",
71
+ )
72
+
73
+ args = parser.parse_args(argv)
74
+
75
+ if args.command == "install":
76
+ if args.method == "prompt":
77
+ from .installer import install_prompt
78
+
79
+ return install_prompt(global_scope=args.global_scope)
80
+
81
+ from .installer import install_hooks
82
+
83
+ return install_hooks(global_scope=args.global_scope)
84
+
85
+ if args.command == "uninstall":
86
+ from .installer import uninstall_hooks
87
+
88
+ return uninstall_hooks(global_scope=args.global_scope)
89
+
90
+ if args.command == "doctor":
91
+ return _doctor()
92
+
93
+ try:
94
+ mem = SkillMemory()
95
+ except ConfigError as exc:
96
+ print(f"error: {exc}", file=sys.stderr)
97
+ return 2
98
+
99
+ try:
100
+ return _run_memory_command(mem, args)
101
+ except Exception as exc: # network/API failures — show cleanly, not as a traceback
102
+ print(f"error: {exc}", file=sys.stderr)
103
+ return 1
104
+
105
+
106
+ def _run_memory_command(mem: SkillMemory, args: argparse.Namespace) -> int:
107
+ if args.command == "recall":
108
+ profile = mem.recall_for_skill(args.skill, task_hint=args.hint)
109
+ block = profile.format_context_block(skill_name=args.skill)
110
+ if block:
111
+ print(block)
112
+ else:
113
+ print("(no relevant memories yet)", file=sys.stderr)
114
+ return 0
115
+
116
+ if args.command == "store":
117
+ stored = mem.distill_and_store(args.skill, args.summary)
118
+ print(f"stored {len(stored)} memory(ies) from /{args.skill}")
119
+ for m in stored:
120
+ mtype = m.get("type") or "memory"
121
+ title = m.get("title") or (m.get("content") or "")[:80] or "(no title)"
122
+ print(f" - [{mtype}] {title}")
123
+ return 0
124
+
125
+ if args.command == "profile":
126
+ block = mem.profile_block()
127
+ print(block or "(profile is empty)")
128
+ return 0
129
+
130
+ return 1
131
+
132
+
133
+ def _doctor() -> int:
134
+ try:
135
+ cfg = SkillsConfig.from_env()
136
+ except ConfigError as exc:
137
+ print(f"✗ config: {exc}", file=sys.stderr)
138
+ return 2
139
+ print(f"✓ MOORCHEH_API_KEY set (…{cfg.api_key[-4:]})")
140
+ print(f"✓ agent_id: {cfg.agent_id}")
141
+ print(f"✓ recall_limit: {cfg.recall_limit}, min_similarity: {cfg.min_similarity}")
142
+ print(
143
+ f"✓ curated skill routes: {', '.join(known_skills())} (others use a generic route)"
144
+ )
145
+ try:
146
+ mem = SkillMemory(cfg)
147
+ mem.setup()
148
+ print("✓ connected to Memanto and session active")
149
+ except Exception as exc:
150
+ print(f"✗ connectivity: {exc}", file=sys.stderr)
151
+ return 1
152
+ return 0
153
+
154
+
155
+ if __name__ == "__main__":
156
+ raise SystemExit(main())
@@ -0,0 +1,229 @@
1
+ """SkillMemory — the single integration point between Claude Code skills and Memanto.
2
+
3
+ Wraps Memanto's ``SdkClient`` with the three operations the bounty calls for:
4
+
5
+ * ``recall_for_skill`` — dynamic injection: pull memories relevant to the skill
6
+ being invoked and render an injectable context block.
7
+ * ``distill_and_store`` — active extraction: use the backend LLM to distill a
8
+ finished session into typed memories, then persist them.
9
+ * ``profile_block`` — the accumulated Engineering Profile (for SessionStart).
10
+
11
+ Agent + session lifecycle is idempotent and lazy: ``setup`` is safe to call on
12
+ every hook invocation, mirroring the pattern used by the official MCP and
13
+ LangGraph integrations in this repo.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ from typing import Any
20
+
21
+ from memanto.app.utils.errors import AgentAlreadyExistsError, AgentNotFoundError
22
+ from memanto.cli.client.sdk_client import SdkClient
23
+
24
+ from . import extractor
25
+ from .config import SkillsConfig
26
+ from .profile import MemoryProfile
27
+ from .skill_map import normalize_skill, route_for
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ # Stamped onto every memory this layer writes, so skill memories are filterable
32
+ # and separable from memories written by other Memanto integrations.
33
+ SOURCE_TAG = "claudecode-skills-memanto"
34
+
35
+ # Memanto session lifetime requested on activation. Sessions are JWT-backed and
36
+ # auto-renewed by the SDK when nearing expiry, so the exact value is not load-bearing.
37
+ _SESSION_HOURS = 6
38
+
39
+
40
+ class SkillMemory:
41
+ """Drop-in cross-session memory companion for Claude Code skills."""
42
+
43
+ def __init__(
44
+ self,
45
+ config: SkillsConfig | None = None,
46
+ client: SdkClient | None = None,
47
+ ) -> None:
48
+ self.config = config or SkillsConfig.from_env()
49
+ # ``client`` injection keeps this unit-testable without a network.
50
+ self._sdk = client or SdkClient(api_key=self.config.api_key)
51
+ self._ready = False
52
+
53
+ # ------------------------------------------------------------------ #
54
+ # Lifecycle (idempotent, lazy)
55
+ # ------------------------------------------------------------------ #
56
+
57
+ def setup(self) -> None:
58
+ """Ensure the agent exists and a session is active. Safe to repeat.
59
+
60
+ Activation is attempted first: each hook runs in a fresh process, and
61
+ for the common case (the agent already exists) this costs one network
62
+ call instead of two. Creation only happens on AgentNotFoundError.
63
+
64
+ Exceptions propagate to the caller. Hook entry points are wrapped in
65
+ ``_common.run()``, which catches all exceptions and exits 0, so a
66
+ failed setup never blocks Claude Code. Demo scripts and the CLI surface
67
+ the real error directly.
68
+ """
69
+ if self._ready:
70
+ return
71
+ agent_id = self.config.agent_id
72
+ try:
73
+ self._sdk.activate_agent(agent_id, duration_hours=_SESSION_HOURS)
74
+ except AgentNotFoundError:
75
+ self._create_and_activate(agent_id)
76
+ self._ready = True
77
+
78
+ def _create_and_activate(self, agent_id: str) -> None:
79
+ """First-run path: create the agent, then activate a session for it."""
80
+ try:
81
+ self._sdk.create_agent(agent_id=agent_id, pattern="tool")
82
+ except AgentAlreadyExistsError:
83
+ pass # concurrent hook created it between our activate and create
84
+ self._sdk.activate_agent(agent_id, duration_hours=_SESSION_HOURS)
85
+
86
+ # ------------------------------------------------------------------ #
87
+ # Dynamic injection (UserPromptExpansion / skill start)
88
+ # ------------------------------------------------------------------ #
89
+
90
+ def recall_for_skill(
91
+ self,
92
+ skill_name: str | None,
93
+ task_hint: str | None = None,
94
+ ) -> MemoryProfile:
95
+ """Recall memories relevant to ``skill_name`` (+ optional task hint)."""
96
+ self.setup()
97
+ route = route_for(skill_name)
98
+ query = route.query
99
+ if task_hint:
100
+ query = f"{query}; current task: {task_hint.strip()}"
101
+
102
+ # We deliberately do NOT pass a hard ``type`` filter here. Live testing
103
+ # showed that combining a type filter with Memanto's semantic threshold
104
+ # over-constrains and can return nothing even when matching-typed
105
+ # memories exist. The skill-specific ``query`` already biases retrieval
106
+ # toward the right memories, and Memanto returns relevant results only.
107
+ result = self._sdk.recall(
108
+ agent_id=self.config.agent_id,
109
+ query=query,
110
+ limit=self.config.recall_limit,
111
+ )
112
+ return MemoryProfile.from_recall(result, self.config.min_similarity)
113
+
114
+ def profile_block(self, limit: int | None = None) -> str:
115
+ """Render the most recent slice of the Engineering Profile.
116
+
117
+ Used by the SessionStart hook to brief Claude once per session.
118
+ """
119
+ self.setup()
120
+ result = self._sdk.recall_recent(
121
+ agent_id=self.config.agent_id,
122
+ limit=limit or self.config.recall_limit,
123
+ )
124
+ return MemoryProfile.from_recall(result).format_context_block()
125
+
126
+ # ------------------------------------------------------------------ #
127
+ # Active extraction (Stop / skill complete)
128
+ # ------------------------------------------------------------------ #
129
+
130
+ def distill_and_store(
131
+ self,
132
+ skill_name: str | None,
133
+ summary: str,
134
+ ) -> list[dict[str, Any]]:
135
+ """Distill a finished session into memories and persist them.
136
+
137
+ Leads with the backend LLM (``answer``); falls back to a conservative
138
+ heuristic only if the LLM yields nothing parseable. Returns only the
139
+ memories that were actually persisted — items that failed to write are
140
+ omitted so the return value matches reality.
141
+ """
142
+ summary = (summary or "").strip()
143
+ if not summary:
144
+ return []
145
+ self.setup()
146
+
147
+ memories = self._llm_extract(skill_name, summary)
148
+ if not memories:
149
+ logger.debug(
150
+ "LLM extraction yielded nothing for skill=%s; using heuristic fallback",
151
+ skill_name,
152
+ )
153
+ memories = extractor.heuristic_memories(summary)
154
+ if not memories:
155
+ return []
156
+
157
+ normalized = normalize_skill(skill_name)
158
+ route = route_for(skill_name)
159
+ skill_tag = f"skill:{normalized}" if normalized else "skill:unknown"
160
+ for mem in memories:
161
+ mem["tags"] = sorted({*route.tags, skill_tag, SOURCE_TAG})
162
+
163
+ return self._persist(memories)
164
+
165
+ # ------------------------------------------------------------------ #
166
+ # Internals
167
+ # ------------------------------------------------------------------ #
168
+
169
+ def _llm_extract(
170
+ self, skill_name: str | None, summary: str
171
+ ) -> list[dict[str, Any]]:
172
+ """Run backend-LLM distillation. Returns [] on any failure."""
173
+ question = extractor.build_extraction_question(skill_name, summary)
174
+ try:
175
+ result = self._sdk.answer(
176
+ agent_id=self.config.agent_id,
177
+ question=question,
178
+ header_prompt=extractor.EXTRACTION_HEADER,
179
+ footer_prompt=extractor.EXTRACTION_FOOTER,
180
+ temperature=0.0,
181
+ )
182
+ except Exception as exc:
183
+ logger.debug("LLM extraction call failed: %s", exc)
184
+ return []
185
+ return extractor.parse_llm_memories(result.get("answer", ""))
186
+
187
+ def _persist(self, memories: list[dict[str, Any]]) -> list[dict[str, Any]]:
188
+ """Store memories and return only those that were actually persisted.
189
+
190
+ Tries ``batch_remember`` first; on failure (or partial success), falls
191
+ back to per-memory ``remember`` calls. Any item whose write raised is
192
+ excluded from the returned list so callers can trust the count and the
193
+ ``stored 0 memory(ies)`` output is honest rather than optimistic.
194
+ """
195
+ payload = [
196
+ {
197
+ "type": m["type"],
198
+ "title": m["title"],
199
+ "content": m["content"],
200
+ "confidence": m.get("confidence", 0.85),
201
+ "tags": m.get("tags", []),
202
+ "source": SOURCE_TAG,
203
+ "provenance": "inferred",
204
+ }
205
+ for m in memories
206
+ ]
207
+ try:
208
+ self._sdk.batch_remember(agent_id=self.config.agent_id, memories=payload)
209
+ return list(memories)
210
+ except Exception as exc:
211
+ logger.debug("batch_remember failed, falling back to remember: %s", exc)
212
+
213
+ persisted: list[dict[str, Any]] = []
214
+ for original, m in zip(memories, payload, strict=True):
215
+ try:
216
+ self._sdk.remember(
217
+ agent_id=self.config.agent_id,
218
+ memory_type=m["type"],
219
+ title=m["title"],
220
+ content=m["content"],
221
+ confidence=m["confidence"],
222
+ tags=m["tags"],
223
+ source=m["source"],
224
+ provenance=m["provenance"],
225
+ )
226
+ persisted.append(original)
227
+ except Exception as exc:
228
+ logger.debug("remember failed for %r: %s", m["title"], exc)
229
+ return persisted
@@ -0,0 +1,95 @@
1
+ """Environment-driven configuration for the Claude Code skills memory layer.
2
+
3
+ Kept dependency-light on purpose: the hooks run on *every* prompt and must
4
+ start fast, so we avoid pulling pydantic into the hot path and read plain
5
+ environment variables (optionally seeded from a local ``.env``).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from dataclasses import dataclass
12
+
13
+ try: # .env support is convenient but never required.
14
+ from dotenv import load_dotenv
15
+
16
+ load_dotenv()
17
+ except Exception: # pragma: no cover - dotenv is an optional convenience
18
+ pass
19
+
20
+
21
+ DEFAULT_AGENT_ID = "skills-dev-profile"
22
+ DEFAULT_RECALL_LIMIT = 8
23
+ # No floor by default: Memanto's information-theoretic retrieval already returns
24
+ # only relevant results, and its ITS scores live on a small, non-cosine scale
25
+ # (top hits are often ~0.1-0.2), so a naive 0-1 floor would discard everything.
26
+ # Advanced users can opt in via MEMANTO_MIN_SIMILARITY once they know the scale.
27
+ DEFAULT_MIN_SIMILARITY: float | None = None
28
+
29
+
30
+ class ConfigError(RuntimeError):
31
+ """Raised when required configuration (the API key) is missing."""
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class SkillsConfig:
36
+ """Resolved configuration for a memory-backed skill session."""
37
+
38
+ api_key: str
39
+ agent_id: str = DEFAULT_AGENT_ID
40
+ recall_limit: int = DEFAULT_RECALL_LIMIT
41
+ min_similarity: float | None = DEFAULT_MIN_SIMILARITY
42
+
43
+ @classmethod
44
+ def from_env(cls) -> SkillsConfig:
45
+ """Build config from the environment.
46
+
47
+ Raises:
48
+ ConfigError: if ``MOORCHEH_API_KEY`` is absent. We fail loud here
49
+ because a silent no-op would make the memory layer look broken.
50
+ """
51
+ api_key = (os.environ.get("MOORCHEH_API_KEY") or "").strip()
52
+ if not api_key:
53
+ raise ConfigError(
54
+ "MOORCHEH_API_KEY is not set. Create a key at "
55
+ "https://console.moorcheh.ai/api-keys and export it "
56
+ "(or add it to a .env file in this directory)."
57
+ )
58
+
59
+ agent_id = (
60
+ os.environ.get("MEMANTO_AGENT_ID") or DEFAULT_AGENT_ID
61
+ ).strip() or DEFAULT_AGENT_ID
62
+
63
+ recall_limit = _int_env("MEMANTO_RECALL_LIMIT", DEFAULT_RECALL_LIMIT)
64
+ min_similarity = _float_env("MEMANTO_MIN_SIMILARITY", DEFAULT_MIN_SIMILARITY)
65
+
66
+ return cls(
67
+ api_key=api_key,
68
+ agent_id=agent_id,
69
+ recall_limit=recall_limit,
70
+ min_similarity=min_similarity,
71
+ )
72
+
73
+
74
+ def _int_env(name: str, default: int) -> int:
75
+ raw = os.environ.get(name)
76
+ if raw is None or not raw.strip():
77
+ return default
78
+ try:
79
+ return max(1, int(raw))
80
+ except ValueError:
81
+ return default
82
+
83
+
84
+ def _float_env(name: str, default: float | None) -> float | None:
85
+ raw = os.environ.get(name)
86
+ if raw is None or not raw.strip():
87
+ return default
88
+ try:
89
+ value = float(raw)
90
+ except ValueError:
91
+ return default
92
+ # Clamp into the valid similarity range; treat <=0 as "no floor".
93
+ if value <= 0:
94
+ return None
95
+ return min(value, 1.0)