hermes-mindgraph-plugin 0.1.0__tar.gz

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,29 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ id-token: write
9
+
10
+ jobs:
11
+ publish:
12
+ name: Build and publish to PyPI
13
+ runs-on: ubuntu-latest
14
+
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: "3.12"
21
+
22
+ - name: Install build tools
23
+ run: pip install build
24
+
25
+ - name: Build package
26
+ run: python -m build
27
+
28
+ - name: Publish to PyPI
29
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .eggs/
8
+ *.egg
9
+ .env
10
+ .venv/
11
+ venv/
12
+ .pytest_cache/
13
+ .mypy_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MindGraph
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: hermes-mindgraph-plugin
3
+ Version: 0.1.0
4
+ Summary: MindGraph semantic graph memory plugin for Hermes Agent
5
+ Project-URL: Homepage, https://mindgraph.cloud
6
+ Project-URL: Repository, https://github.com/shuruheel/hermes-mindgraph-plugin
7
+ Project-URL: Issues, https://github.com/shuruheel/hermes-mindgraph-plugin/issues
8
+ Author-email: Shan Rizvi <shan@rizvi.nu>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: agent,hermes,memory,mindgraph,plugin,semantic-graph
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: mindgraph-sdk>=0.1.4
22
+ Description-Content-Type: text/markdown
23
+
24
+ # hermes-mindgraph-plugin
25
+
26
+ Semantic graph memory plugin for [Hermes Agent](https://github.com/NousResearch/hermes-agent). Gives any Hermes-powered agent persistent memory across sessions using [MindGraph](https://mindgraph.cloud).
27
+
28
+ ## What it does
29
+
30
+ This plugin hooks into Hermes Agent's lifecycle to provide:
31
+
32
+ - **Session context** — Active goals, open decisions, governance policies, weak claims, and user profile are injected into the agent's context at the start of each conversation.
33
+ - **Per-turn retrieval** — Score-gated semantic search finds topic-relevant knowledge from the graph and injects it ephemerally (never persisted to conversation history, no prompt cache breakage).
34
+ - **Session lifecycle** — Automatically opens and closes MindGraph sessions aligned with Hermes conversations.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install hermes-mindgraph-plugin
40
+ ```
41
+
42
+ The plugin is auto-discovered via the `hermes_agent.plugins` entry point. No configuration beyond the API key is needed.
43
+
44
+ ## Setup
45
+
46
+ 1. Get a MindGraph API key at [mindgraph.cloud](https://mindgraph.cloud)
47
+ 2. Add it to your Hermes environment:
48
+
49
+ ```bash
50
+ echo "MINDGRAPH_API_KEY=mg_your_key_here" >> ~/.hermes/.env
51
+ ```
52
+
53
+ 3. Verify the plugin is loaded:
54
+
55
+ ```bash
56
+ hermes plugins list
57
+ ```
58
+
59
+ ## How it works
60
+
61
+ The plugin registers three [lifecycle hooks](https://hermes.nousresearch.com/docs/user-guide/features/plugins):
62
+
63
+ | Hook | When | What |
64
+ |------|------|------|
65
+ | `on_session_start` | New conversation begins | Opens a MindGraph session, pre-fetches goals/decisions/policies |
66
+ | `pre_llm_call` | Before each agent turn | Returns session context (first turn) + semantic retrieval (every turn) |
67
+ | `on_session_end` | Conversation ends | Closes the MindGraph session |
68
+
69
+ Context is injected **ephemerally** into the system prompt — it's never persisted to the session database and doesn't break Anthropic's prompt cache prefix.
70
+
71
+ All MindGraph API calls are wrapped in try/except. A MindGraph failure never breaks the conversation.
72
+
73
+ ## Manual install (alternative)
74
+
75
+ If you prefer not to use pip, copy the plugin directly:
76
+
77
+ ```bash
78
+ mkdir -p ~/.hermes/plugins/mindgraph
79
+ # Copy plugin.yaml and __init__.py into that directory
80
+ ```
81
+
82
+ See the `plugin.yaml` in this repo for the manifest format.
83
+
84
+ ## Development
85
+
86
+ ```bash
87
+ git clone https://github.com/shuruheel/hermes-mindgraph-plugin
88
+ cd hermes-mindgraph-plugin
89
+ pip install -e ".[dev]"
90
+ pytest
91
+ ```
92
+
93
+ ## Requirements
94
+
95
+ - Hermes Agent ≥ v0.5.0 (plugin lifecycle hooks)
96
+ - Python ≥ 3.10
97
+ - `mindgraph-sdk` ≥ 0.1.4
98
+ - `MINDGRAPH_API_KEY` environment variable
99
+
100
+ ## License
101
+
102
+ MIT
@@ -0,0 +1,79 @@
1
+ # hermes-mindgraph-plugin
2
+
3
+ Semantic graph memory plugin for [Hermes Agent](https://github.com/NousResearch/hermes-agent). Gives any Hermes-powered agent persistent memory across sessions using [MindGraph](https://mindgraph.cloud).
4
+
5
+ ## What it does
6
+
7
+ This plugin hooks into Hermes Agent's lifecycle to provide:
8
+
9
+ - **Session context** — Active goals, open decisions, governance policies, weak claims, and user profile are injected into the agent's context at the start of each conversation.
10
+ - **Per-turn retrieval** — Score-gated semantic search finds topic-relevant knowledge from the graph and injects it ephemerally (never persisted to conversation history, no prompt cache breakage).
11
+ - **Session lifecycle** — Automatically opens and closes MindGraph sessions aligned with Hermes conversations.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pip install hermes-mindgraph-plugin
17
+ ```
18
+
19
+ The plugin is auto-discovered via the `hermes_agent.plugins` entry point. No configuration beyond the API key is needed.
20
+
21
+ ## Setup
22
+
23
+ 1. Get a MindGraph API key at [mindgraph.cloud](https://mindgraph.cloud)
24
+ 2. Add it to your Hermes environment:
25
+
26
+ ```bash
27
+ echo "MINDGRAPH_API_KEY=mg_your_key_here" >> ~/.hermes/.env
28
+ ```
29
+
30
+ 3. Verify the plugin is loaded:
31
+
32
+ ```bash
33
+ hermes plugins list
34
+ ```
35
+
36
+ ## How it works
37
+
38
+ The plugin registers three [lifecycle hooks](https://hermes.nousresearch.com/docs/user-guide/features/plugins):
39
+
40
+ | Hook | When | What |
41
+ |------|------|------|
42
+ | `on_session_start` | New conversation begins | Opens a MindGraph session, pre-fetches goals/decisions/policies |
43
+ | `pre_llm_call` | Before each agent turn | Returns session context (first turn) + semantic retrieval (every turn) |
44
+ | `on_session_end` | Conversation ends | Closes the MindGraph session |
45
+
46
+ Context is injected **ephemerally** into the system prompt — it's never persisted to the session database and doesn't break Anthropic's prompt cache prefix.
47
+
48
+ All MindGraph API calls are wrapped in try/except. A MindGraph failure never breaks the conversation.
49
+
50
+ ## Manual install (alternative)
51
+
52
+ If you prefer not to use pip, copy the plugin directly:
53
+
54
+ ```bash
55
+ mkdir -p ~/.hermes/plugins/mindgraph
56
+ # Copy plugin.yaml and __init__.py into that directory
57
+ ```
58
+
59
+ See the `plugin.yaml` in this repo for the manifest format.
60
+
61
+ ## Development
62
+
63
+ ```bash
64
+ git clone https://github.com/shuruheel/hermes-mindgraph-plugin
65
+ cd hermes-mindgraph-plugin
66
+ pip install -e ".[dev]"
67
+ pytest
68
+ ```
69
+
70
+ ## Requirements
71
+
72
+ - Hermes Agent ≥ v0.5.0 (plugin lifecycle hooks)
73
+ - Python ≥ 3.10
74
+ - `mindgraph-sdk` ≥ 0.1.4
75
+ - `MINDGRAPH_API_KEY` environment variable
76
+
77
+ ## License
78
+
79
+ MIT
@@ -0,0 +1,19 @@
1
+ # For manual installation: copy this file + __init__.py to
2
+ # ~/.hermes/plugins/mindgraph/
3
+ #
4
+ # For pip installation, use: pip install hermes-mindgraph-plugin
5
+ # (auto-discovered via entry points, no manual copy needed)
6
+
7
+ name: mindgraph
8
+ version: 0.1.0
9
+ description: >
10
+ Semantic graph memory provider — injects session context (goals, decisions,
11
+ policies) and per-turn topic-relevant knowledge from MindGraph into the
12
+ agent's context via plugin lifecycle hooks.
13
+ author: Shan Rizvi
14
+ requires_env:
15
+ - MINDGRAPH_API_KEY
16
+ provides_hooks:
17
+ - on_session_start
18
+ - pre_llm_call
19
+ - on_session_end
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "hermes-mindgraph-plugin"
7
+ version = "0.1.0"
8
+ description = "MindGraph semantic graph memory plugin for Hermes Agent"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ { name = "Shan Rizvi", email = "shan@rizvi.nu" },
14
+ ]
15
+ keywords = ["hermes", "agent", "mindgraph", "memory", "semantic-graph", "plugin"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
25
+ ]
26
+ dependencies = [
27
+ "mindgraph-sdk>=0.1.4",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://mindgraph.cloud"
32
+ Repository = "https://github.com/shuruheel/hermes-mindgraph-plugin"
33
+ Issues = "https://github.com/shuruheel/hermes-mindgraph-plugin/issues"
34
+
35
+ [project.entry-points."hermes_agent.plugins"]
36
+ mindgraph = "hermes_mindgraph_plugin"
@@ -0,0 +1,170 @@
1
+ """MindGraph semantic graph memory plugin for Hermes Agent.
2
+
3
+ Bridges MindGraph (https://mindgraph.cloud) into Hermes Agent's plugin
4
+ lifecycle hooks, giving any Hermes-powered agent persistent semantic memory
5
+ across sessions.
6
+
7
+ Install:
8
+ pip install hermes-mindgraph-plugin
9
+
10
+ Configure:
11
+ Set MINDGRAPH_API_KEY in ~/.hermes/.env (get one at https://mindgraph.cloud)
12
+
13
+ The plugin is auto-discovered via the ``hermes_agent.plugins`` entry point.
14
+ It can also be installed manually by copying this package to
15
+ ``~/.hermes/plugins/mindgraph/`` with an accompanying ``plugin.yaml``.
16
+
17
+ Hooks registered:
18
+ on_session_start — Opens a MindGraph session, pre-fetches context.
19
+ pre_llm_call — Injects session context (goals, decisions, policies)
20
+ on first turn; score-gated semantic retrieval every turn.
21
+ on_session_end — Closes the MindGraph session.
22
+ """
23
+
24
+ __version__ = "0.1.0"
25
+
26
+ import logging
27
+ from typing import Optional
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # State — per-process, reset on session_start
33
+ # ---------------------------------------------------------------------------
34
+
35
+ _session_context_cache: Optional[str] = None
36
+ _session_started: bool = False
37
+
38
+
39
+ def _is_available() -> bool:
40
+ """Check if MindGraph is configured and ready."""
41
+ try:
42
+ from tools.mindgraph_tool import check_requirements
43
+ return check_requirements()
44
+ except ImportError:
45
+ return False
46
+
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Hook callbacks
50
+ # ---------------------------------------------------------------------------
51
+
52
+ def _on_session_start(
53
+ *, session_id: str = "", model: str = "", platform: str = "", **kw
54
+ ):
55
+ """Open a MindGraph session and pre-fetch session context."""
56
+ global _session_context_cache, _session_started
57
+ _session_context_cache = None
58
+ _session_started = False
59
+
60
+ if not _is_available():
61
+ return
62
+
63
+ # Open session
64
+ try:
65
+ from tools.mindgraph_tool import auto_open_session
66
+
67
+ label = f"hermes-{session_id[:8]}" if session_id else "hermes-session"
68
+ sid = auto_open_session(label=label)
69
+ if sid:
70
+ logger.info("MindGraph session opened: %s", sid)
71
+ _session_started = True
72
+ except Exception as exc:
73
+ logger.debug("MindGraph session open failed (non-fatal): %s", exc)
74
+
75
+ # Pre-fetch session context (goals, decisions, policies, weak claims)
76
+ # so it's ready for the first pre_llm_call without blocking.
77
+ try:
78
+ from tools.mindgraph_tool import retrieve_session_context
79
+
80
+ _session_context_cache = retrieve_session_context()
81
+ except Exception as exc:
82
+ logger.debug("MindGraph session context prefetch failed: %s", exc)
83
+
84
+
85
+ def _pre_llm_call(
86
+ *,
87
+ session_id: str = "",
88
+ user_message: str = "",
89
+ conversation_history: list = None,
90
+ is_first_turn: bool = False,
91
+ model: str = "",
92
+ platform: str = "",
93
+ **kw,
94
+ ) -> dict | None:
95
+ """Return context to inject into the agent's ephemeral system prompt.
96
+
97
+ First turn: cached session context (goals, decisions, policies, weak claims).
98
+ Every turn: score-gated semantic retrieval for topic relevance.
99
+
100
+ Returns ``{"context": "..."}`` or ``None``.
101
+ """
102
+ if not _is_available():
103
+ return None
104
+
105
+ parts: list[str] = []
106
+
107
+ # --- Session context (first turn only) ---
108
+ if is_first_turn and _session_context_cache:
109
+ parts.append(_session_context_cache)
110
+ # Don't clear the cache — the gateway creates a fresh AIAgent per
111
+ # message, so is_first_turn may be True on every gateway turn for
112
+ # continuing sessions. The cache stays valid for the process
113
+ # lifetime and is reset on the next on_session_start.
114
+
115
+ # --- Per-turn semantic retrieval ---
116
+ if user_message:
117
+ try:
118
+ from tools.mindgraph_tool import proactive_graph_retrieve
119
+
120
+ turn_ctx = proactive_graph_retrieve(user_message)
121
+ if turn_ctx:
122
+ parts.append(turn_ctx)
123
+ except Exception as exc:
124
+ logger.debug("MindGraph turn retrieval failed (non-fatal): %s", exc)
125
+
126
+ if parts:
127
+ return {"context": "\n\n".join(parts)}
128
+ return None
129
+
130
+
131
+ def _on_session_end(
132
+ *,
133
+ session_id: str = "",
134
+ completed: bool = True,
135
+ interrupted: bool = False,
136
+ model: str = "",
137
+ platform: str = "",
138
+ **kw,
139
+ ):
140
+ """Close the MindGraph session."""
141
+ global _session_context_cache, _session_started
142
+
143
+ if not _session_started:
144
+ return
145
+
146
+ try:
147
+ from tools.mindgraph_tool import auto_close_session
148
+
149
+ auto_close_session(
150
+ summary=(
151
+ f"Session {session_id[:8] if session_id else 'unknown'} "
152
+ f"({'completed' if completed else 'interrupted' if interrupted else 'ended'})"
153
+ ),
154
+ )
155
+ _session_started = False
156
+ _session_context_cache = None
157
+ except Exception as exc:
158
+ logger.debug("MindGraph session close failed (non-fatal): %s", exc)
159
+
160
+
161
+ # ---------------------------------------------------------------------------
162
+ # Plugin entry point — called by Hermes plugin discovery
163
+ # ---------------------------------------------------------------------------
164
+
165
+ def register(ctx):
166
+ """Register MindGraph memory hooks with the Hermes plugin system."""
167
+ ctx.register_hook("on_session_start", _on_session_start)
168
+ ctx.register_hook("pre_llm_call", _pre_llm_call)
169
+ ctx.register_hook("on_session_end", _on_session_end)
170
+ logger.info("MindGraph memory plugin registered (3 lifecycle hooks)")
@@ -0,0 +1,231 @@
1
+ """Tests for hermes-mindgraph-plugin."""
2
+
3
+ import sys
4
+ from unittest.mock import MagicMock, patch
5
+
6
+ import pytest
7
+
8
+ import hermes_mindgraph_plugin as plugin
9
+
10
+
11
+ # ---------------------------------------------------------------------------
12
+ # Fixtures
13
+ # ---------------------------------------------------------------------------
14
+
15
+ @pytest.fixture(autouse=True)
16
+ def _reset_plugin_state():
17
+ """Reset module-level state between tests."""
18
+ plugin._session_context_cache = None
19
+ plugin._session_started = False
20
+ yield
21
+ plugin._session_context_cache = None
22
+ plugin._session_started = False
23
+
24
+
25
+ # ---------------------------------------------------------------------------
26
+ # register()
27
+ # ---------------------------------------------------------------------------
28
+
29
+ class TestRegister:
30
+
31
+ def test_registers_three_hooks(self):
32
+ ctx = MagicMock()
33
+ plugin.register(ctx)
34
+ assert ctx.register_hook.call_count == 3
35
+ hook_names = {call.args[0] for call in ctx.register_hook.call_args_list}
36
+ assert hook_names == {"on_session_start", "pre_llm_call", "on_session_end"}
37
+
38
+ def test_callbacks_are_callable(self):
39
+ ctx = MagicMock()
40
+ plugin.register(ctx)
41
+ for call in ctx.register_hook.call_args_list:
42
+ assert callable(call.args[1])
43
+
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # on_session_start
47
+ # ---------------------------------------------------------------------------
48
+
49
+ class TestOnSessionStart:
50
+
51
+ @patch("hermes_mindgraph_plugin._is_available", return_value=False)
52
+ def test_noop_when_unavailable(self, _mock):
53
+ plugin._on_session_start(session_id="abc123")
54
+ assert not plugin._session_started
55
+ assert plugin._session_context_cache is None
56
+
57
+ @patch("hermes_mindgraph_plugin._is_available", return_value=True)
58
+ def test_opens_session_and_prefetches(self, _avail):
59
+ mock_open = MagicMock(return_value="sess-uid-123")
60
+ mock_ctx = MagicMock(return_value="## Goals\n- Ship it")
61
+
62
+ with patch.dict(sys.modules, {
63
+ "tools.mindgraph_tool": MagicMock(
64
+ auto_open_session=mock_open,
65
+ retrieve_session_context=mock_ctx,
66
+ ),
67
+ }):
68
+ plugin._on_session_start(session_id="abcdef99", model="test", platform="cli")
69
+
70
+ assert plugin._session_started is True
71
+ assert plugin._session_context_cache == "## Goals\n- Ship it"
72
+ mock_open.assert_called_once_with(label="hermes-abcdef99")
73
+
74
+ @patch("hermes_mindgraph_plugin._is_available", return_value=True)
75
+ def test_session_start_failure_is_nonfatal(self, _avail):
76
+ mock_open = MagicMock(side_effect=RuntimeError("connection refused"))
77
+
78
+ with patch.dict(sys.modules, {
79
+ "tools.mindgraph_tool": MagicMock(
80
+ auto_open_session=mock_open,
81
+ retrieve_session_context=MagicMock(return_value=None),
82
+ ),
83
+ }):
84
+ # Should not raise
85
+ plugin._on_session_start(session_id="test")
86
+
87
+ assert not plugin._session_started
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # pre_llm_call
92
+ # ---------------------------------------------------------------------------
93
+
94
+ class TestPreLlmCall:
95
+
96
+ @patch("hermes_mindgraph_plugin._is_available", return_value=False)
97
+ def test_returns_none_when_unavailable(self, _mock):
98
+ result = plugin._pre_llm_call(
99
+ session_id="x", user_message="hello", is_first_turn=True,
100
+ )
101
+ assert result is None
102
+
103
+ @patch("hermes_mindgraph_plugin._is_available", return_value=True)
104
+ def test_returns_session_context_on_first_turn(self, _avail):
105
+ plugin._session_context_cache = "## Active Goals\n- Goal 1"
106
+ result = plugin._pre_llm_call(
107
+ session_id="x", user_message="hi",
108
+ conversation_history=[], is_first_turn=True,
109
+ )
110
+ assert result is not None
111
+ assert "Active Goals" in result["context"]
112
+
113
+ @patch("hermes_mindgraph_plugin._is_available", return_value=True)
114
+ def test_no_session_context_on_subsequent_turn(self, _avail):
115
+ plugin._session_context_cache = "## Active Goals\n- Goal 1"
116
+ result = plugin._pre_llm_call(
117
+ session_id="x", user_message="ok",
118
+ conversation_history=[{"role": "user"}], is_first_turn=False,
119
+ )
120
+ # Short message + not first turn = no retrieval, no session context
121
+ assert result is None
122
+
123
+ @patch("hermes_mindgraph_plugin._is_available", return_value=True)
124
+ def test_returns_turn_context_from_retrieval(self, _avail):
125
+ mock_retrieve = MagicMock(return_value="## Relevant: plugin hooks")
126
+
127
+ with patch.dict(sys.modules, {
128
+ "tools.mindgraph_tool": MagicMock(
129
+ proactive_graph_retrieve=mock_retrieve,
130
+ ),
131
+ }):
132
+ result = plugin._pre_llm_call(
133
+ session_id="x",
134
+ user_message="Tell me about the plugin lifecycle hooks",
135
+ conversation_history=[{"role": "user"}],
136
+ is_first_turn=False,
137
+ )
138
+
139
+ assert result is not None
140
+ assert "plugin hooks" in result["context"]
141
+ mock_retrieve.assert_called_once()
142
+
143
+ @patch("hermes_mindgraph_plugin._is_available", return_value=True)
144
+ def test_combines_session_and_turn_context(self, _avail):
145
+ plugin._session_context_cache = "## Goals\n- Ship plugin"
146
+ mock_retrieve = MagicMock(return_value="## Related: memory systems")
147
+
148
+ with patch.dict(sys.modules, {
149
+ "tools.mindgraph_tool": MagicMock(
150
+ proactive_graph_retrieve=mock_retrieve,
151
+ ),
152
+ }):
153
+ result = plugin._pre_llm_call(
154
+ session_id="x",
155
+ user_message="How does memory work in Hermes?",
156
+ conversation_history=[],
157
+ is_first_turn=True,
158
+ )
159
+
160
+ assert result is not None
161
+ ctx = result["context"]
162
+ assert "## Goals" in ctx
163
+ assert "## Related" in ctx
164
+
165
+ @patch("hermes_mindgraph_plugin._is_available", return_value=True)
166
+ def test_retrieval_failure_is_nonfatal(self, _avail):
167
+ with patch.dict(sys.modules, {
168
+ "tools.mindgraph_tool": MagicMock(
169
+ proactive_graph_retrieve=MagicMock(side_effect=Exception("timeout")),
170
+ ),
171
+ }):
172
+ result = plugin._pre_llm_call(
173
+ session_id="x",
174
+ user_message="Tell me about something complex",
175
+ is_first_turn=False,
176
+ )
177
+ # Should not raise, returns None
178
+ assert result is None
179
+
180
+ @patch("hermes_mindgraph_plugin._is_available", return_value=True)
181
+ def test_preserves_cache_across_calls(self, _avail):
182
+ """Session context cache is not cleared after first use."""
183
+ plugin._session_context_cache = "## Goals\n- Persist"
184
+
185
+ plugin._pre_llm_call(
186
+ session_id="x", user_message="hi",
187
+ conversation_history=[], is_first_turn=True,
188
+ )
189
+ # Cache should still be there
190
+ assert plugin._session_context_cache == "## Goals\n- Persist"
191
+
192
+
193
+ # ---------------------------------------------------------------------------
194
+ # on_session_end
195
+ # ---------------------------------------------------------------------------
196
+
197
+ class TestOnSessionEnd:
198
+
199
+ def test_noop_when_not_started(self):
200
+ plugin._session_started = False
201
+ # Should not raise or call anything
202
+ plugin._on_session_end(session_id="test", completed=True)
203
+ assert not plugin._session_started
204
+
205
+ @patch("hermes_mindgraph_plugin._is_available", return_value=True)
206
+ def test_closes_session(self, _avail):
207
+ plugin._session_started = True
208
+ plugin._session_context_cache = "some cached context"
209
+ mock_close = MagicMock()
210
+
211
+ with patch.dict(sys.modules, {
212
+ "tools.mindgraph_tool": MagicMock(auto_close_session=mock_close),
213
+ }):
214
+ plugin._on_session_end(
215
+ session_id="abcdef99", completed=True, interrupted=False,
216
+ )
217
+
218
+ assert not plugin._session_started
219
+ assert plugin._session_context_cache is None
220
+ mock_close.assert_called_once()
221
+
222
+ @patch("hermes_mindgraph_plugin._is_available", return_value=True)
223
+ def test_close_failure_is_nonfatal(self, _avail):
224
+ plugin._session_started = True
225
+ mock_close = MagicMock(side_effect=RuntimeError("api down"))
226
+
227
+ with patch.dict(sys.modules, {
228
+ "tools.mindgraph_tool": MagicMock(auto_close_session=mock_close),
229
+ }):
230
+ # Should not raise
231
+ plugin._on_session_end(session_id="test", completed=True)