-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathentity.py
More file actions
70 lines (63 loc) · 2.71 KB
/
Copy pathentity.py
File metadata and controls
70 lines (63 loc) · 2.71 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
"""Entity memory operations."""
import json, re
from pathlib import Path
from scripts.paths import get_memory_dir
from scripts.schema import is_legacy_schema, migrate_v1, SCHEMA_URL
from scripts.merge import merge_entity
_VALID_NAME = re.compile(r'^[a-zA-Z0-9_-]+$')
def validate_entity_name(name: str) -> str:
if not name or not _VALID_NAME.match(name):
raise ValueError(f"invalid_entity_name: {name}")
return name
def _new_entity(name: str) -> dict:
return {"$schema": SCHEMA_URL, "entity": name,
"permanent_facts": {"metadata": {}, "items": []},
"decisions": [], "current_status": {}, "last_session": {}, "technical_notes": []}
def load_entity(name: str, project_root: Path) -> dict | None:
validate_entity_name(name)
file = get_memory_dir(project_root) / f"{name}.json"
if not file.exists():
return None
try:
data = json.loads(file.read_text(encoding="utf-8"))
except json.JSONDecodeError:
raise ValueError(f"invalid_json:{file}")
if is_legacy_schema(data):
data = migrate_v1(data)
return data
def diff_entity(name: str, updates: dict, project_root: Path) -> dict:
validate_entity_name(name)
existing = load_entity(name, project_root)
is_new = existing is None
if is_new:
existing = _new_entity(name)
preview, diff = merge_entity(existing, updates)
return {"is_new": is_new, "entity": name, "diff": diff, "preview": preview}
def save_entity(name: str, updates: dict, project_root: Path) -> dict:
validate_entity_name(name)
existing = load_entity(name, project_root)
is_new = existing is None
if is_new:
existing = _new_entity(name)
merged, diff = merge_entity(existing, updates)
merged["$schema"] = SCHEMA_URL
merged["entity"] = name
file = get_memory_dir(project_root) / f"{name}.json"
file.write_text(json.dumps(merged, ensure_ascii=False, indent=2), encoding="utf-8")
return {"entity": name, "is_new": is_new, "file": str(file), "diff": diff}
def list_entities(project_root: Path) -> list[dict]:
results = []
for file in sorted(get_memory_dir(project_root).glob("*.json")):
try:
data = json.loads(file.read_text(encoding="utf-8"))
if is_legacy_schema(data):
data = migrate_v1(data)
results.append({
"entity": data.get("entity", file.stem),
"updated_at": data.get("updated_at", ""),
"phase": data.get("current_status", {}).get("phase", ""),
"tracker_ids": data.get("current_status", {}).get("tracker_ids", []),
})
except Exception:
results.append({"entity": file.stem, "error": "invalid_json"})
return results