File size: 13,992 Bytes
3ccdcc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import json
import pathlib
import shutil
import subprocess
from types import SimpleNamespace
from urllib.parse import urlencode

import api.profiles
import api.routes as routes
import pytest


REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
NODE = shutil.which("node")


def project_context_for(workspace):
    return routes._read_active_project_context(pathlib.Path(workspace))


def test_project_context_reads_agents_md_from_active_workspace(tmp_path):
    workspace = tmp_path / "agents-only"
    workspace.mkdir()
    (workspace / "AGENTS.md").write_text("# Agent Rules\n\nUse pytest here.", encoding="utf-8")

    data = project_context_for(workspace)

    assert "Use pytest here." in data["content"]
    assert data["path"].endswith("AGENTS.md")
    assert data["name"] == "AGENTS.md"
    assert data["shadowed"] == []


def test_project_context_prefers_hermes_md_and_reports_shadowed_agents(tmp_path):
    workspace = tmp_path / "priority"
    workspace.mkdir()
    (workspace / "HERMES.md").write_text("# Hermes Rules\n\nHermes wins.", encoding="utf-8")
    (workspace / "AGENTS.md").write_text("# Agent Rules\n\nAgents lose.", encoding="utf-8")

    data = project_context_for(workspace)

    assert "Hermes wins." in data["content"]
    assert "Agents lose." not in data["content"]
    assert data["path"].endswith("HERMES.md")
    assert [item["name"] for item in data["shadowed"]] == ["AGENTS.md"]
    assert data["shadowed"][0]["shadowed_by"] == "HERMES.md"


def test_project_context_walks_hermes_md_to_git_root_but_not_agents_md(tmp_path):
    root = tmp_path / "repo"
    child = root / "src" / "pkg"
    child.mkdir(parents=True)
    (root / ".git").mkdir()
    (root / ".hermes.md").write_text("# Root Hermes\n\nRoot project rules.", encoding="utf-8")
    (root / "AGENTS.md").write_text("# Root Agents\n\nRoot AGENTS should not be cwd-loaded.", encoding="utf-8")

    data = project_context_for(child)

    assert "Root project rules." in data["content"]
    assert data["path"].endswith(".hermes.md")
    assert data["path"].startswith(str(root))
    assert data["shadowed"] == []


def test_project_context_workspace_switch_re_resolves_same_session(tmp_path, monkeypatch):
    first = tmp_path / "first"
    second = tmp_path / "second"
    first.mkdir()
    second.mkdir()
    (first / "AGENTS.md").write_text("First workspace rules.", encoding="utf-8")
    (second / "AGENTS.md").write_text("Second workspace rules.", encoding="utf-8")

    current = {"workspace": str(first)}

    def fake_get_session(_sid):
        return SimpleNamespace(workspace=current["workspace"])

    monkeypatch.setattr(routes, "get_session", fake_get_session)
    parsed = SimpleNamespace(query=urlencode({"session_id": "sid"}))

    before = routes._read_active_project_context(routes._memory_project_context_workspace(parsed))
    assert "First workspace rules." in before["content"]

    current["workspace"] = str(second)
    after = routes._read_active_project_context(routes._memory_project_context_workspace(parsed))
    assert "Second workspace rules." in after["content"]
    assert "First workspace rules." not in after["content"]
    assert after["workspace"] == str(second.resolve())


def test_project_context_absent_returns_empty_fields(tmp_path):
    workspace = tmp_path / "empty"
    workspace.mkdir()
    (workspace / ".git").mkdir()

    data = project_context_for(workspace)

    assert data["content"] == ""
    assert data["path"] == ""
    assert data["mtime"] is None
    assert data["shadowed"] == []


def test_project_context_content_is_redacted_in_memory_response(tmp_path, monkeypatch):
    home = tmp_path / "home"
    workspace = tmp_path / "redacted"
    (home / "memories").mkdir(parents=True)
    workspace.mkdir()
    secret = "ghp_TestFakeCredential1234567890ab"
    (workspace / "AGENTS.md").write_text(
        f"# Agent Rules\n\nGitHub PAT: {secret}\nNormal note: keep me.",
        encoding="utf-8",
    )

    monkeypatch.setattr(api.profiles, "get_active_hermes_home", lambda: home)
    monkeypatch.setattr(routes, "_memory_project_context_workspace", lambda _parsed: workspace)
    monkeypatch.setattr(routes, "_external_notes_sources_enabled", lambda: False)
    monkeypatch.setattr(routes, "j", lambda _handler, payload, **_kwargs: payload)

    payload = routes._handle_memory_read(object(), SimpleNamespace(query=""))
    dumped = json.dumps(payload)

    assert secret not in dumped
    assert "Normal note: keep me." in payload["project_context"]


def test_memory_panel_defines_read_only_project_context_section():
    panels = (REPO_ROOT / "static" / "panels.js").read_text(encoding="utf-8")

    assert "key: 'project_context'" in panels
    assert "readOnly: true" in panels
    assert "project_context_shadowed" in panels
    assert "/api/memory?session_id=" in panels


def test_memory_panel_references_all_memory_path_fields():
    panels = (REPO_ROOT / "static" / "panels.js").read_text(encoding="utf-8")

    assert "function _memorySectionPath(key)" in panels
    assert "_memoryData.memory_path" in panels
    assert "_memoryData.user_path" in panels
    assert "_memoryData.soul_path" in panels
    assert "_memoryData.project_context_path" in panels
    assert "const sectionPath = _memorySectionPath(s.key)" in panels
    assert "if (sectionPath) el.title = sectionPath" in panels


def _memory_render_blocks():
    panels = (REPO_ROOT / "static" / "panels.js").read_text(encoding="utf-8")
    helper_start = panels.index("function _memorySectionContent(key)")
    helper_end = panels.index("function _setMemoryHeaderButtons", helper_start)
    render_start = panels.index("function _renderMemoryDetail(section)")
    render_end = panels.index("function _renderMemoryEdit", render_start)
    return panels[helper_start:helper_end], panels[render_start:render_end]


def _run_memory_render_harness():
    helper_block, render_block = _memory_render_blocks()
    script = (
        "const helperBlock = "
        + json.dumps(helper_block)
        + ";\nconst renderBlock = "
        + json.dumps(render_block)
        + ";\n"
        + r"""
let _memoryData = {
  memory: 'Primary memory body',
  memory_path: 'C:/Users/Rod/.hermes/memories/MEMORY.md',
  memory_mtime: 1712345678,
  user: 'User memory body',
  user_path: 'C:/Users/Rod/.hermes/memories/USER.md',
  user_mtime: 1712345678,
  soul: 'Soul memory body',
  soul_path: 'C:/Users/Rod/.hermes/SOUL.md',
  soul_mtime: 1712345678,
  project_context: 'Project context body',
  project_context_path: 'D:/Repos/hermes-webui/AGENTS.md',
  project_context_name: 'AGENTS.md',
  project_context_mtime: 1712345678,
  project_context_shadowed: [{name: 'CLAUDE.md', shadowed_by: 'AGENTS.md'}],
};
let _memoryMode = '';
const nodes = {
  memoryDetailTitle: {textContent: '', style: {}},
  memoryDetailBody: {innerHTML: '', style: {}},
  memoryDetailEmpty: {style: {}},
};
function $(id) { return nodes[id] || null; }
function _memorySectionMeta(section) {
  return {key: section, label: section, emptyKey: section + '_empty'};
}
function _memorySectionLabel(meta) { return meta.label; }
function _memorySectionEmpty(meta) { return meta.emptyKey; }
function _setMemoryHeaderButtons() {}
function renderMd(content) { return 'rendered:' + content; }
function esc(value) {
  return String(value)
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
eval(helperBlock + "\n" + renderBlock);
_renderMemoryDetail('memory');
const memoryHtml = nodes.memoryDetailBody.innerHTML;
_renderMemoryDetail('user');
const userHtml = nodes.memoryDetailBody.innerHTML;
_renderMemoryDetail('soul');
const soulHtml = nodes.memoryDetailBody.innerHTML;
_renderMemoryDetail('project_context');
const projectHtml = nodes.memoryDetailBody.innerHTML;
console.log(JSON.stringify({memoryHtml, userHtml, soulHtml, projectHtml, memoryMode: _memoryMode}));
"""
    )
    completed = subprocess.run(
        [NODE, "-e", script],
        capture_output=True,
        text=True,
        encoding="utf-8",
        timeout=30,
        check=True,
    )
    return json.loads(completed.stdout)


def _memory_button_render_blocks():
    panels = (REPO_ROOT / "static" / "panels.js").read_text(encoding="utf-8")
    sections_start = panels.index("const MEMORY_SECTIONS = [")
    sections_end = panels.index("];", sections_start) + 2
    helper_start = panels.index("function _memorySectionPath(key)")
    helper_end = panels.index("function _setMemoryHeaderButtons", helper_start)
    loop_start = panels.index("for (const s of MEMORY_SECTIONS) {")
    loop_end = panels.index("    if (_currentMemorySection && _memoryMode !== 'edit') {", loop_start)
    return (
        panels[sections_start:sections_end],
        panels[helper_start:helper_end],
        panels[loop_start:loop_end].rsplit("    }", 1)[0],
    )


def _run_memory_button_harness():
    sections_block, helper_block, loop_block = _memory_button_render_blocks()
    script = (
        "const sectionsBlock = "
        + json.dumps(sections_block)
        + ";\nconst helperBlock = "
        + json.dumps(helper_block)
        + ";\nconst loopBlock = "
        + json.dumps(loop_block)
        + ";\n"
        + r"""
let _memoryData = {
  memory_path: 'C:/Users/Rod/.hermes/memories/MEMORY.md',
  user_path: 'C:/Users/Rod/.hermes/memories/USER.md',
  soul_path: 'C:/Users/Rod/.hermes/SOUL.md',
  project_context_path: 'D:/Repos/hermes-webui/AGENTS.md',
  external_notes_enabled: true,
};
let _currentMemorySection = 'memory';
const nodes = {
  memoryPanel: {
    innerHTML: '',
    appended: [],
    appendChild(node) { this.appended.push(node); },
  },
};
const document = {
  createElement() {
    return {
      title: '',
      type: '',
      className: '',
      innerHTML: '',
      onclick: null,
      classList: { add() {} },
      setAttribute(name, value) { this[name] = value; },
    };
  },
};
function _memorySectionLabel(meta) { return meta.key; }
function li() { return ''; }
function esc(value) { return String(value); }
function openMemorySection() {}
eval(
  sectionsBlock +
  "\n" +
  helperBlock +
  "\nfunction renderButtons() {\nconst panel = nodes.memoryPanel;\n" +
  loopBlock +
  "\n}\nrenderButtons();"
);
const buttons = nodes.memoryPanel.appended.map(btn => ({
  label: btn.innerHTML.replace(/<[^>]+>/g, ''),
  title: btn.title || '',
}));
console.log(JSON.stringify(buttons));
"""
    )
    completed = subprocess.run(
        [NODE, "-e", script],
        capture_output=True,
        text=True,
        encoding="utf-8",
        timeout=30,
        check=True,
    )
    return json.loads(completed.stdout)


def test_memory_detail_renders_path_for_non_project_sections():
    """Base-fails/head-passes regression for issue #4999.

    On base, `_renderMemoryDetail('memory')` ignores `memory_path`, so the
    rendered header omits the path row entirely. On head, the same render must
    show `MEMORY.md · <path>` using the existing pinned header row pattern.
    """
    if NODE is None:
        pytest.skip("node not on PATH")

    rendered = _run_memory_render_harness()

    assert "MEMORY.md" in rendered["memoryHtml"]
    assert "C:/Users/Rod/.hermes/memories/MEMORY.md" in rendered["memoryHtml"]
    assert "USER.md" in rendered["userHtml"]
    assert "C:/Users/Rod/.hermes/memories/USER.md" in rendered["userHtml"]
    assert "SOUL.md" in rendered["soulHtml"]
    assert "C:/Users/Rod/.hermes/SOUL.md" in rendered["soulHtml"]
    assert "AGENTS.md · D:/Repos/hermes-webui/AGENTS.md" in rendered["projectHtml"]
    assert "CLAUDE.md present, shadowed by AGENTS.md" in rendered["projectHtml"]


def test_memory_section_list_renders_hover_path_titles():
    """Base-fails/head-passes regression for issue #5045."""
    if NODE is None:
        pytest.skip("node not on PATH")

    rendered = {item["label"]: item["title"] for item in _run_memory_button_harness()}

    assert rendered["memory"] == "C:/Users/Rod/.hermes/memories/MEMORY.md"
    assert rendered["user"] == "C:/Users/Rod/.hermes/memories/USER.md"
    assert rendered["soul"] == "C:/Users/Rod/.hermes/SOUL.md"
    assert rendered["project_context"] == "D:/Repos/hermes-webui/AGENTS.md"
    assert rendered["external_notes"] == ""


def test_blank_session_workspace_does_not_resolve_to_server_cwd(monkeypatch):
    # Regression for the empty-workspace guard: a session with a blank workspace
    # (freshly-created/draft sessions) must return None rather than letting
    # Path("").resolve() surface the server's own CWD as project context.
    monkeypatch.setattr(routes, "get_session", lambda _sid: SimpleNamespace(workspace=""))
    parsed = SimpleNamespace(query="session_id=draft-session")

    assert routes._memory_project_context_workspace(parsed) is None


def test_project_context_reads_lowercase_agents_md(tmp_path):
    # Parity with the agent, which matches lowercase filename variants.
    workspace = tmp_path / "lowercase"
    workspace.mkdir()
    (workspace / "agents.md").write_text("# lower agents\n\nlowercase loads.", encoding="utf-8")

    data = project_context_for(workspace)

    # On case-insensitive filesystems the resolved name may normalize to the
    # uppercase candidate; the point of the fix is that the content loads at all
    # (on case-sensitive Linux CI, only the lowercase candidate matches).
    assert "lowercase loads." in data["content"]
    assert data["path"].lower().endswith("agents.md")


def test_project_context_strips_yaml_frontmatter(tmp_path):
    # Parity with the agent, which strips frontmatter before injecting context.
    workspace = tmp_path / "frontmatter"
    workspace.mkdir()
    (workspace / "AGENTS.md").write_text(
        "---\ntitle: Rules\nowner: me\n---\n\nActual body the agent injects.",
        encoding="utf-8",
    )

    data = project_context_for(workspace)

    assert "Actual body the agent injects." in data["content"]
    assert "title: Rules" not in data["content"]