-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.py
More file actions
76 lines (57 loc) · 2.32 KB
/
Copy pathmemory.py
File metadata and controls
76 lines (57 loc) · 2.32 KB
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
"""Chapter 8 reference: small filesystem-backed memory index."""
from __future__ import annotations
from pathlib import Path
MEMORY_DIR = Path.cwd() / "memory"
MEMORY_INDEX_NAME = "MEMORY.md"
def parse_frontmatter(text: str) -> tuple[dict[str, str], str]:
"""Parse a tiny YAML-like frontmatter block from a memory file."""
if not text.startswith("---\n"):
return {}, text
end = text.find("\n---", 4)
if end == -1:
return {}, text
raw = text[4:end]
body = text[end + 4 :].lstrip("\n")
metadata: dict[str, str] = {}
for line in raw.splitlines():
if ":" not in line:
continue
key, value = line.split(":", 1)
metadata[key.strip()] = value.strip().strip("\"'")
return metadata, body
def refresh_memory_index() -> str:
"""Rebuild MEMORY.md from individual memory files."""
MEMORY_DIR.mkdir(parents=True, exist_ok=True)
lines = ["# Memory Index", ""]
for path in sorted(MEMORY_DIR.glob("*.md")):
if path.name == MEMORY_INDEX_NAME:
continue
try:
metadata, _ = parse_frontmatter(path.read_text(encoding="utf-8"))
except OSError:
continue
memory_type = metadata.get("type", "note")
summary = metadata.get("summary", path.stem)
updated = metadata.get("updated")
suffix = f" - updated {updated}" if updated else ""
lines.append(f"- {memory_type}: {summary} (`{path.name}`){suffix}")
index = "\n".join(lines).rstrip() + "\n"
(MEMORY_DIR / MEMORY_INDEX_NAME).write_text(index, encoding="utf-8")
return index
def load_memory_index() -> str:
"""Load the current memory index, creating it when needed."""
index_path = MEMORY_DIR / MEMORY_INDEX_NAME
if not index_path.exists():
return refresh_memory_index()
return index_path.read_text(encoding="utf-8")
def build_memory_prompt_section() -> str:
"""Return the memory rules and current index for the system prompt."""
index = load_memory_index()
return (
"# Memory System\n"
"Use memory files only when they are relevant to the current task.\n"
"To save durable preferences or project facts, write Markdown files "
f"under `{MEMORY_DIR}` with frontmatter fields `type`, `summary`, "
"and `updated`.\n\n"
f"{index}"
)