omp-memory 0.2.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.
omp_memory/web.py ADDED
@@ -0,0 +1,879 @@
1
+ """Interactive graph view server for the memory store.
2
+
3
+ Serves the built single-page app in web/dist/ and a small JSON API over the
4
+ records graph. Pure standard library: http.server plus a hand-rolled
5
+ Server-Sent Events fan-out. Graph cosmetics (positions, labels, images) live
6
+ in web/data/graph.json via PUT /api/graph. Record content edits write back to
7
+ SQLite through POST /api/record; images are copied into web/data/media/ via
8
+ POST /api/image so both the operator and agents can attach them.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import hmac
15
+ import json
16
+ import secrets
17
+ import sqlite3
18
+ import math
19
+ import mimetypes
20
+ import os
21
+ import re
22
+ import threading
23
+ import webbrowser
24
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
25
+ from pathlib import Path
26
+
27
+ from . import db
28
+
29
+ # In a source checkout web/ sits next to src/; in a venv install it does not.
30
+ # An explicit OMP_MEMORY_WEB_DIR wins unconditionally: falling through to the
31
+ # checkout would point GRAPH_FILE/MEDIA_DIR at tracked repo files, so a demo
32
+ # run could pollute the repo. Missing dist there is main()'s error to report.
33
+ _ENV_WEB = os.environ.get("OMP_MEMORY_WEB_DIR")
34
+ if _ENV_WEB:
35
+ WEB_DIR = Path(_ENV_WEB)
36
+ else:
37
+ _WEB_CANDIDATES = [
38
+ Path(__file__).resolve().parent / "web", # packaged wheel
39
+ Path(__file__).resolve().parent.parent.parent / "web", # repo checkout
40
+ Path.home() / ".omp/memory/web",
41
+ ]
42
+ WEB_DIR = next((p for p in _WEB_CANDIDATES if (p / "dist" / "index.html").is_file()),
43
+ _WEB_CANDIDATES[0])
44
+ DIST_DIR = WEB_DIR / "dist"
45
+ GRAPH_FILE = WEB_DIR / "data" / "graph.json"
46
+ MEDIA_DIR = WEB_DIR / "data" / "media"
47
+
48
+ # Images: raster formats only, no SVG (script vector), 8 MB cap.
49
+ _IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".gif"}
50
+ _IMAGE_MAX_BYTES = 8 * 1024 * 1024
51
+
52
+ # Loopback is not a trust boundary: any page the user visits can POST at
53
+ # 127.0.0.1, and DNS rebinding makes the attacker's origin look same-origin.
54
+ # Three independent checks close that: Host must name this machine, Origin
55
+ # must be this server's own, and every write needs a per-process token that a
56
+ # cross-site page cannot read. Comparing Origin against Host was the bug: the
57
+ # attacker controls Host during rebinding, and "null" (sandboxed iframe,
58
+ # file://) was explicitly allowed.
59
+ _ALLOWED_HOSTS = {"127.0.0.1", "localhost", "::1"}
60
+ CSRF_HEADER = "X-OMP-Token"
61
+ CSRF_TOKEN = secrets.token_urlsafe(32)
62
+ MAX_BODY_BYTES = _IMAGE_MAX_BYTES + 4 * 1024 * 1024
63
+
64
+ sse_clients: list = []
65
+ sse_lock = threading.Lock()
66
+
67
+ # Layout: records ring inward, skills ring outward.
68
+ RING_RECORD = 420
69
+ RING_SKILL = 780
70
+
71
+
72
+ def build_graph() -> dict:
73
+ """Read the store and rebuild the default graph (records + skills)."""
74
+ conn = db.connect()
75
+ try:
76
+ # init_db on a fresh machine: `pip install` then `overview` used to
77
+ # crash here with "no such table: records", and the handler died
78
+ # mid-response so the browser saw a dropped connection instead of an
79
+ # error it could report. The CLI and the MCP server both migrate on
80
+ # open; the web surface was the only one that skipped it.
81
+ db.init_db(conn)
82
+ rows = db.list_records(conn, limit=1000)
83
+ finally:
84
+ conn.close()
85
+
86
+ nodes = []
87
+ for r in rows:
88
+ first = next((l for l in r["content"].splitlines() if l.strip()), "")
89
+ nodes.append(
90
+ {
91
+ "id": f"mem-{r['id']}",
92
+ "type": "graphNode",
93
+ "position": {"x": 0, "y": 0},
94
+ "data": {
95
+ "label": first[:90],
96
+ "type": r["type"],
97
+ "meta": f"memory · conf {float(r['confidence']):.2f}"
98
+ + (" · verified" if r["verified"] else ""),
99
+ "color": _TYPE_COLORS.get(r["type"], "#64748b"),
100
+ },
101
+ }
102
+ )
103
+
104
+ skill_nodes = _skill_nodes()
105
+ nodes.extend(skill_nodes)
106
+
107
+ edges = _similarity_edges(rows)
108
+ edges.extend(_skill_edges(rows, skill_nodes))
109
+
110
+ _ring_layout(nodes)
111
+ return {"nodes": nodes, "edges": edges}
112
+
113
+
114
+ _TYPE_COLORS = {
115
+ "RULE": "#7c3aed",
116
+ "FACT": "#10b981",
117
+ "CORRECTION": "#f59e0b",
118
+ "DECISION": "#06b6d4",
119
+ "INFERENCE": "#94a3b8",
120
+ "skill": "#ec4899",
121
+ }
122
+
123
+
124
+ def _skill_nodes() -> list:
125
+ home = Path.home()
126
+ dirs = [
127
+ home / ".omp/agent/managed-skills",
128
+ home / ".omp/agent/skills",
129
+ ]
130
+ nodes = []
131
+ for root in dirs:
132
+ if not root.is_dir():
133
+ continue
134
+ source = "managed" if "managed" in str(root) else "user"
135
+ for child in sorted(root.iterdir()):
136
+ skill_md = child / "SKILL.md"
137
+ if not skill_md.is_file():
138
+ continue
139
+ try:
140
+ body = skill_md.read_text(encoding="utf-8", errors="replace")
141
+ except OSError:
142
+ continue
143
+ desc = ""
144
+ m = re.search(r"^description:\s*(.+)$", body, re.M)
145
+ if m:
146
+ desc = m.group(1).strip()
147
+ nodes.append(
148
+ {
149
+ "id": f"skill-{source}-{child.name}",
150
+ "type": "graphNode",
151
+ "position": {"x": 0, "y": 0},
152
+ "data": {
153
+ "label": child.name,
154
+ "type": "skill",
155
+ "meta": f"{source} skill" + (f" · {desc[:60]}" if desc else ""),
156
+ "color": _TYPE_COLORS["skill"],
157
+ },
158
+ }
159
+ )
160
+ return nodes
161
+
162
+
163
+ def _tokens(text: str) -> set:
164
+ return {w for w in re.split(r"[^a-z0-9]+", text.lower()) if len(w) > 4}
165
+
166
+
167
+ def _tokens(text: str) -> set:
168
+ return {w for w in re.split(r"[^a-z0-9]+", text.lower()) if len(w) > 4}
169
+
170
+
171
+ def _jaccard(a: set, b: set) -> float:
172
+ if not a or not b:
173
+ return 0.0
174
+ inter = len(a & b)
175
+ return inter / (len(a) + len(b) - inter)
176
+
177
+
178
+ def _tfidf_vectors(docs: list[str]) -> list[dict]:
179
+ """TF-IDF weight vectors, one dict per doc. Term weight = tf * idf."""
180
+ n = len(docs)
181
+ df: dict[str, int] = {}
182
+ tokenized = []
183
+ for doc in docs:
184
+ toks = [w for w in re.split(r"[^a-z0-9]+", doc.lower()) if len(w) > 4]
185
+ tokenized.append(toks)
186
+ for w in set(toks):
187
+ df[w] = df.get(w, 0) + 1
188
+ vecs = []
189
+ for toks in tokenized:
190
+ tf: dict[str, int] = {}
191
+ for w in toks:
192
+ tf[w] = tf.get(w, 0) + 1
193
+ vecs.append(
194
+ {
195
+ w: (1 + math.log(c)) * math.log((n + 1) / (df[w] + 1)) + 1e-9
196
+ for w, c in tf.items()
197
+ }
198
+ )
199
+ return vecs
200
+
201
+
202
+ def _cosine(a: dict, b: dict) -> float:
203
+ if not a or not b:
204
+ return 0.0
205
+ common = set(a) & set(b)
206
+ dot = sum(a[w] * b[w] for w in common)
207
+ na = math.sqrt(sum(v * v for v in a.values()))
208
+ nb = math.sqrt(sum(v * v for v in b.values()))
209
+ if na == 0 or nb == 0:
210
+ return 0.0
211
+ return dot / (na * nb)
212
+
213
+
214
+ def _similarity_edges(rows: list) -> list:
215
+ vecs = _tfidf_vectors([r["content"] for r in rows])
216
+ norms = [math.sqrt(sum(v * v for v in vec.values())) for vec in vecs]
217
+ # Inverted index: cosine is zero unless two docs share a term, so score
218
+ # only candidate pairs instead of all n^2. Same edges, ~100x faster at
219
+ # 600 records (13s -> ~0.1s rebuild).
220
+ postings: dict = {}
221
+ for i, vec in enumerate(vecs):
222
+ for w in vec:
223
+ postings.setdefault(w, []).append(i)
224
+ edges = []
225
+ seen = set()
226
+ for i, vec in enumerate(vecs):
227
+ if norms[i] == 0:
228
+ continue
229
+ dots: dict = {}
230
+ for w, weight in vec.items():
231
+ for j in postings[w]:
232
+ if j != i:
233
+ dots[j] = dots.get(j, 0.0) + weight * vecs[j][w]
234
+ scored = [(j, dot / (norms[i] * norms[j]))
235
+ for j, dot in dots.items() if norms[j] > 0]
236
+ scored = [(j, sim) for j, sim in scored if sim >= 0.22]
237
+ scored.sort(key=lambda p: -p[1])
238
+ for j, _ in scored[:3]:
239
+ key = (min(i, j), max(i, j))
240
+ if key in seen:
241
+ continue
242
+ seen.add(key)
243
+ edges.append(
244
+ {
245
+ "id": f"e-sim-{key[0]}-{key[1]}",
246
+ "source": f"mem-{rows[i]['id']}",
247
+ "target": f"mem-{rows[j]['id']}",
248
+ "label": "similar",
249
+ }
250
+ )
251
+ return edges
252
+
253
+
254
+ def _skill_edges(rows: list, skill_nodes: list) -> list:
255
+ edges = []
256
+ skill_tokens = [
257
+ (s, _tokens(s["data"]["label"] + " " + s["data"].get("meta", "")))
258
+ for s in skill_nodes
259
+ ]
260
+ for r in rows:
261
+ r_tokens = _tokens(r["content"][:200])
262
+ if not r_tokens:
263
+ continue
264
+ for s, s_tokens in skill_tokens:
265
+ if _jaccard(r_tokens, s_tokens) >= 0.12:
266
+ edges.append(
267
+ {
268
+ "id": f"e-memsim-{r['id']}-{s['id']}",
269
+ "source": f"mem-{r['id']}",
270
+ "target": s["id"],
271
+ "label": "related",
272
+ }
273
+ )
274
+ return edges
275
+
276
+
277
+ def _ring_layout(nodes: list) -> None:
278
+ records = [n for n in nodes if n["id"].startswith("mem-")]
279
+ skills = [n for n in nodes if n["id"].startswith("skill-")]
280
+ for i, n in enumerate(records):
281
+ a = 2 * math.pi * i / max(1, len(records))
282
+ n["position"] = {
283
+ "x": RING_RECORD * math.cos(a) * 1.6,
284
+ "y": RING_RECORD * math.sin(a) * 1.1,
285
+ }
286
+ for i, n in enumerate(skills):
287
+ a = 2 * math.pi * i / max(1, len(skills))
288
+ n["position"] = {"x": RING_SKILL * math.cos(a), "y": RING_SKILL * math.sin(a)}
289
+
290
+
291
+ _graph_version = None
292
+
293
+
294
+ def _load_graph() -> dict:
295
+ """Serve the cached graph, rebuilding when another process wrote.
296
+
297
+ PRAGMA data_version (remembrane pattern) bumps on commits from other
298
+ connections, so timer captures and MCP writes surface on the next GET
299
+ without waiting for a UI edit. Own writes already call _refresh_graph.
300
+ """
301
+ global _graph_version
302
+ try:
303
+ conn = db.connect()
304
+ try:
305
+ version = db.store_version(conn)
306
+ finally:
307
+ conn.close()
308
+ except Exception:
309
+ version = None
310
+ if version is not None and _graph_version is not None and version != _graph_version:
311
+ graph = _refresh_graph()
312
+ # Re-read after the rebuild: our own merge writes bump the counter,
313
+ # and caching the pre-write value would loop-refresh on every GET.
314
+ try:
315
+ conn = db.connect()
316
+ try:
317
+ _graph_version = db.store_version(conn)
318
+ finally:
319
+ conn.close()
320
+ except Exception:
321
+ _graph_version = version
322
+ return graph
323
+ if GRAPH_FILE.is_file():
324
+ try:
325
+ graph = json.loads(GRAPH_FILE.read_text(encoding="utf-8"))
326
+ if version is not None:
327
+ _graph_version = version
328
+ return graph
329
+ except (OSError, json.JSONDecodeError):
330
+ pass
331
+ graph = build_graph()
332
+ if version is not None:
333
+ _graph_version = version
334
+ return graph
335
+
336
+
337
+ def _refresh_graph() -> dict:
338
+ """Rebuild from the store keeping cosmetics, persist, return. Called after
339
+ a record write so every tab sees fresh content without losing layout."""
340
+ graph = _merge_fresh(_load_graph())
341
+ _save_graph(graph)
342
+ return graph
343
+
344
+
345
+ def _merge_fresh(saved: dict) -> dict:
346
+ """Rebuild from the store, keep operator cosmetics (position/label/image).
347
+
348
+ The store owns record truth; graph.json owns presentation. Without this
349
+ merge a content edit in the UI would be reverted by the next rebuild.
350
+ """
351
+ fresh = build_graph()
352
+ old = {n["id"]: n for n in saved.get("nodes", [])}
353
+ for n in fresh["nodes"]:
354
+ prev = old.get(n["id"])
355
+ if not prev:
356
+ continue
357
+ if prev.get("position"):
358
+ n["position"] = prev["position"]
359
+ for key in ("image", "color"):
360
+ if key in prev.get("data", {}):
361
+ n["data"][key] = prev["data"][key]
362
+ if not n["id"].startswith("mem-") and "meta" in prev.get("data", {}):
363
+ n["data"]["meta"] = prev["data"]["meta"]
364
+ # Label override only when the operator explicitly renamed the node
365
+ # (customLabel flag set by the UI); otherwise fresh content wins.
366
+ if prev.get("data", {}).get("customLabel") and prev["data"].get("label"):
367
+ n["data"]["label"] = prev["data"]["label"]
368
+ n["data"]["customLabel"] = True
369
+ # Operator-added nodes (notes) have no store record; keep them as-is.
370
+ # A mem- id absent from the fresh build is a foreign/deleted record
371
+ # (e.g. a cache seeded from another machine), not a note: drop it, or
372
+ # its detail panel would 404 forever.
373
+ fresh_ids = {n["id"] for n in fresh["nodes"]}
374
+ for n in saved.get("nodes", []):
375
+ if n["id"] not in fresh_ids and not n["id"].startswith("mem-"):
376
+ fresh["nodes"].append(n)
377
+ fresh_edge_ids = {e["id"] for e in fresh["edges"]}
378
+ all_ids = {n["id"] for n in fresh["nodes"]}
379
+ for e in saved.get("edges", []):
380
+ if e["id"] not in fresh_edge_ids \
381
+ and e.get("source") in all_ids and e.get("target") in all_ids:
382
+ fresh["edges"].append(e)
383
+ return fresh
384
+
385
+
386
+ def _record_payload(r: dict) -> dict:
387
+ return {
388
+ "id": r["id"],
389
+ "type": r["type"],
390
+ "content": r["content"],
391
+ "evidence": r["evidence"],
392
+ "confidence": r["confidence"],
393
+ "verified": bool(r["verified"]),
394
+ "tags": r["tags"],
395
+ "source": r["source"],
396
+ "project_id": r["project_id"],
397
+ "created_at": r["created_at"],
398
+ "updated_at": r["updated_at"],
399
+ }
400
+
401
+
402
+ def _update_record(record_id: str, patch: dict) -> dict:
403
+ """Edit one record in place. A content change goes through the store's
404
+ correction primitive (db.reinforce): same id, FTS trigger sync, evidence
405
+ or verified required, length capped, confidence surprise + supersede
406
+ history applied. A raw UPDATE here would bypass those invariants."""
407
+ conn = db.connect()
408
+ try:
409
+ r = db.get_record(conn, record_id)
410
+ if not r:
411
+ raise db.NotFound(f"record {record_id} not found")
412
+ content = patch.get("content", r["content"])
413
+ if not isinstance(content, str) or not content.strip():
414
+ raise ValueError("content must not be empty")
415
+ evidence = patch.get("evidence", r["evidence"])
416
+ verified = 1 if patch.get("verified", r["verified"]) else 0
417
+ # Verified without evidence is an assertion, not a check. The store
418
+ # enforces this too; failing here names the field the editor sent.
419
+ if verified and not str(evidence or "").strip():
420
+ raise ValueError("verified requires evidence")
421
+ # Same secret guard as MCP remember and CLI capture: the web editor
422
+ # must not become the one door that stores credentials.
423
+ from . import capture
424
+ for text in (content, str(evidence)):
425
+ hits = capture.scan_text(text)
426
+ if hits:
427
+ raise ValueError(f"secret-looking content refused ({hits[0][0]})")
428
+ if content.strip() != r["content"].strip():
429
+ try:
430
+ db.reinforce(conn, record_id, "correction",
431
+ content=content, evidence=str(evidence),
432
+ verified=verified, source="web-ui")
433
+ except ValueError as e:
434
+ # reinforce words it as "correction rewrite..."; the UI
435
+ # caller just edited content, so translate the wording.
436
+ raise ValueError(str(e).replace("correction rewrite", "content edit"))
437
+ # New text is unattested text: the operator checked the old
438
+ # wording, not this one. Re-attest to restore trust.
439
+ conn.execute("UPDATE records SET trust=? WHERE id=?",
440
+ (db.TRUST_CLAIMED, record_id))
441
+ conn.commit()
442
+ else:
443
+ conn.execute(
444
+ "UPDATE records SET evidence=?, verified=?, updated_at=?, trust=?"
445
+ " WHERE id=?",
446
+ (str(evidence), verified, db.now_iso(), db.TRUST_CLAIMED,
447
+ record_id),
448
+ )
449
+ conn.commit()
450
+ return _record_payload(db.get_record(conn, record_id))
451
+ finally:
452
+ conn.close()
453
+
454
+
455
+ def _store_image(payload: dict) -> dict:
456
+ """Copy a local file or decode a data URL into MEDIA_DIR. Agents call this
457
+ with {"path": "/abs/file.png"}; the browser sends {"dataUrl": "data:..."}.
458
+ Returns the served URL. Raster only, size-capped, content sniffed."""
459
+ import base64
460
+ import hashlib
461
+
462
+ if payload.get("path"):
463
+ src = Path(payload["path"]).expanduser()
464
+ if not src.is_file():
465
+ raise FileNotFoundError(str(src))
466
+ ext = src.suffix.lower()
467
+ if ext not in _IMAGE_EXTS:
468
+ raise ValueError(f"unsupported image type: {ext}")
469
+ data = src.read_bytes()
470
+ elif payload.get("dataUrl"):
471
+ m = re.match(r"data:image/(png|jpeg|webp|gif);base64,(.+)$",
472
+ payload["dataUrl"], re.S)
473
+ if not m:
474
+ raise ValueError("dataUrl must be a base64 raster image")
475
+ ext = ".jpg" if m.group(1) == "jpeg" else f".{m.group(1)}"
476
+ data = base64.b64decode(m.group(2))
477
+ else:
478
+ raise ValueError("provide path or dataUrl")
479
+ if len(data) > _IMAGE_MAX_BYTES:
480
+ raise ValueError("image exceeds 8 MB")
481
+ if not _sniff_image(data, ext):
482
+ raise ValueError("file content does not match an image signature")
483
+ MEDIA_DIR.mkdir(parents=True, exist_ok=True)
484
+ name = hashlib.sha256(data).hexdigest()[:16] + ext
485
+ (MEDIA_DIR / name).write_bytes(data)
486
+ return {"url": f"/media/{name}"}
487
+
488
+
489
+ def _sniff_image(data: bytes, ext: str) -> bool:
490
+ if ext == ".png":
491
+ return data.startswith(b"\x89PNG\r\n\x1a\n")
492
+ if ext in (".jpg", ".jpeg"):
493
+ return data.startswith(b"\xff\xd8\xff")
494
+ if ext == ".gif":
495
+ return data.startswith((b"GIF87a", b"GIF89a"))
496
+ if ext == ".webp":
497
+ return data[:4] == b"RIFF" and data[8:12] == b"WEBP"
498
+ return False
499
+
500
+
501
+ def _dashboard_stats() -> dict:
502
+ """Real numbers for the dashboard: store stats + graph health + activity."""
503
+ conn = db.connect()
504
+ try:
505
+ s = db.stats(conn)
506
+ rows = conn.execute(
507
+ "SELECT confidence, created_at, source FROM records"
508
+ ).fetchall()
509
+ finally:
510
+ conn.close()
511
+ buckets = {"low": 0, "mid": 0, "high": 0}
512
+ per_day: dict = {}
513
+ auto = 0
514
+ for r in rows:
515
+ c = float(r["confidence"])
516
+ buckets["low" if c < 0.4 else "mid" if c < 0.7 else "high"] += 1
517
+ day = (r["created_at"] or "")[:10]
518
+ if day:
519
+ per_day[day] = per_day.get(day, 0) + 1
520
+ if "auto-capture" in (r["source"] or ""):
521
+ auto += 1
522
+ graph = _load_graph()
523
+ degree: dict = {}
524
+ for e in graph["edges"]:
525
+ degree[e["source"]] = degree.get(e["source"], 0) + 1
526
+ degree[e["target"]] = degree.get(e["target"], 0) + 1
527
+ nodes = graph["nodes"]
528
+ orphans = sum(1 for n in nodes if n["id"] not in degree)
529
+ top = sorted(nodes, key=lambda n: -degree.get(n["id"], 0))[:8]
530
+ days = sorted(per_day)[-14:]
531
+ return {
532
+ "store": s,
533
+ "confidence": buckets,
534
+ "auto_captured": auto,
535
+ "graph": {
536
+ "nodes": len(nodes),
537
+ "edges": len(graph["edges"]),
538
+ "orphans": orphans,
539
+ "top_connected": [
540
+ {"id": n["id"], "label": n["data"].get("label", n["id"]),
541
+ "type": n["data"].get("type", ""), "degree": degree.get(n["id"], 0)}
542
+ for n in top
543
+ ],
544
+ },
545
+ "activity": [{"day": d, "count": per_day[d]} for d in days],
546
+ }
547
+
548
+
549
+ def _save_graph(graph: dict) -> None:
550
+ GRAPH_FILE.parent.mkdir(parents=True, exist_ok=True)
551
+ GRAPH_FILE.write_text(json.dumps(graph, indent=2), encoding="utf-8")
552
+
553
+
554
+ def _broadcast(event: str, data) -> None:
555
+ payload = f"event: {event}\ndata: {json.dumps(data)}\n\n".encode()
556
+ with sse_lock:
557
+ dead = []
558
+ for res in sse_clients:
559
+ try:
560
+ res.write(payload)
561
+ except OSError:
562
+ dead.append(res)
563
+ for res in dead:
564
+ sse_clients.remove(res)
565
+
566
+
567
+ class Handler(BaseHTTPRequestHandler):
568
+ server_version = "omp-memory-overview/1.0"
569
+
570
+ def log_message(self, fmt, *args): # quiet
571
+ pass
572
+
573
+ def _json(self, obj, status=200):
574
+ body = json.dumps(obj).encode()
575
+ self.send_response(status)
576
+ self.send_header("Content-Type", "application/json")
577
+ self.send_header("Content-Length", str(len(body)))
578
+ self.send_header("Cache-Control", "no-store")
579
+ self._security_headers()
580
+ self.end_headers()
581
+ self.wfile.write(body)
582
+
583
+ def do_GET(self):
584
+ if not self._guard():
585
+ return
586
+ path = self.path.split("?", 1)[0]
587
+ if path == "/api/graph":
588
+ self._json(_load_graph())
589
+ return
590
+ if path == "/api/stats":
591
+ self._json(_dashboard_stats())
592
+ return
593
+ if path.startswith("/api/record/"):
594
+ conn = db.connect()
595
+ try:
596
+ r = db.get_record(conn, path[len("/api/record/"):])
597
+ finally:
598
+ conn.close()
599
+ if not r:
600
+ self._json({"error": "not found"}, 404)
601
+ return
602
+ self._json(_record_payload(r))
603
+ return
604
+ if path.startswith("/media/"):
605
+ self._media(path[len("/media/"):])
606
+ return
607
+ if path == "/events":
608
+ self._sse()
609
+ return
610
+ self._static(path)
611
+
612
+ def _media(self, name):
613
+ # Content-addressed filenames only; no traversal, no dotfiles.
614
+ if not re.fullmatch(r"[0-9a-f]{16}\.(png|jpg|jpeg|webp|gif)", name):
615
+ self.send_error(404)
616
+ return
617
+ target = MEDIA_DIR / name
618
+ if not target.is_file():
619
+ self.send_error(404)
620
+ return
621
+ ctype = mimetypes.guess_type(name)[0] or "application/octet-stream"
622
+ body = target.read_bytes()
623
+ self.send_response(200)
624
+ self.send_header("Content-Type", ctype)
625
+ self.send_header("Content-Length", str(len(body)))
626
+ self.send_header("Cache-Control", "public, max-age=31536000, immutable")
627
+ self._security_headers()
628
+ self.end_headers()
629
+ self.wfile.write(body)
630
+
631
+ def _sse(self):
632
+ self.send_response(200)
633
+ self.send_header("Content-Type", "text/event-stream")
634
+ self.send_header("Cache-Control", "no-cache")
635
+ self.send_header("Connection", "keep-alive")
636
+ self._security_headers()
637
+ self.end_headers()
638
+ self.wfile.write(b": connected\n\n")
639
+ with sse_lock:
640
+ sse_clients.append(self.wfile)
641
+ try:
642
+ while True:
643
+ # Blocked writes are fine; a dropped client raises and cleans up.
644
+ threading.Event().wait(3600)
645
+ except (OSError, ConnectionError):
646
+ pass
647
+ finally:
648
+ with sse_lock:
649
+ if self.wfile in sse_clients:
650
+ sse_clients.remove(self.wfile)
651
+
652
+ def _static(self, path):
653
+ if path == "/":
654
+ path = "/index.html"
655
+ dist_root = DIST_DIR.resolve()
656
+ target = (dist_root / path.lstrip("/")).resolve()
657
+ # is_relative_to is the correct containment test; a prefix match would
658
+ # accept /srv/web-evil as inside /srv/web.
659
+ if not target.is_file() or not target.is_relative_to(dist_root):
660
+ target = dist_root / "index.html" # SPA fallback
661
+ if not target.is_file():
662
+ self.send_error(404, "run npm run build in web/")
663
+ return
664
+ ctype = mimetypes.guess_type(str(target))[0] or "application/octet-stream"
665
+ body = target.read_bytes()
666
+ if target.name == "index.html" and ctype.startswith("text/html"):
667
+ # The UI reads this token and sends it on every write. A cross-site
668
+ # page cannot read the HTML (same-origin policy), and DNS rebinding
669
+ # is already dead at the Host check, so the token never reaches an
670
+ # attacker.
671
+ meta = ('<meta name="omp-token" content="%s">' % CSRF_TOKEN).encode()
672
+ if b"<head>" in body:
673
+ body = body.replace(b"<head>", b"<head>" + meta, 1)
674
+ else:
675
+ # No <head> to anchor to: prefix it. A token that silently
676
+ # fails to appear would lock the UI out of every write.
677
+ body = meta + body
678
+ self.send_response(200)
679
+ self.send_header("Content-Type", ctype)
680
+ self.send_header("Content-Length", str(len(body)))
681
+ self.send_header("Cache-Control", "no-store")
682
+ self._security_headers()
683
+ self.end_headers()
684
+ self.wfile.write(body)
685
+
686
+ def _port(self) -> int:
687
+ try:
688
+ return int(self.server.server_address[1])
689
+ except (AttributeError, IndexError, TypeError, ValueError):
690
+ return 0
691
+
692
+ def _host_ok(self) -> bool:
693
+ host = (self.headers.get("Host") or "").strip().lower()
694
+ if not host:
695
+ return False
696
+ if host.startswith("["): # [::1]:4173
697
+ name, _, rest = host.partition("]")
698
+ name, port = name[1:], rest.lstrip(":")
699
+ else:
700
+ name, _, port = host.partition(":")
701
+ if name not in _ALLOWED_HOSTS:
702
+ return False
703
+ return port in ("", str(self._port()))
704
+
705
+ def _origin_ok(self) -> bool:
706
+ origin = self.headers.get("Origin")
707
+ if origin is None:
708
+ return True # non-browser client; Host still had to pass
709
+ if origin == "null":
710
+ return False # sandboxed iframe or file://
711
+ port = self._port()
712
+ return origin in {
713
+ f"http://127.0.0.1:{port}",
714
+ f"http://localhost:{port}",
715
+ f"http://[::1]:{port}",
716
+ }
717
+
718
+ def _guard(self) -> bool:
719
+ """Host and Origin check for every request, reads included."""
720
+ if self._host_ok() and self._origin_ok():
721
+ return True
722
+ self._json({"error": "forbidden host or origin"}, 403)
723
+ return False
724
+
725
+ def _guard_write(self) -> bool:
726
+ """Host, Origin, CSRF token and JSON content type for writes."""
727
+ if not self._guard():
728
+ return False
729
+ token = self.headers.get(CSRF_HEADER) or ""
730
+ if not token or not hmac.compare_digest(token, CSRF_TOKEN):
731
+ self._json({"error": "missing or invalid CSRF token"}, 403)
732
+ return False
733
+ ctype = (self.headers.get("Content-Type") or "").split(";")[0].strip().lower()
734
+ if ctype != "application/json":
735
+ # Forces a preflight for any cross-site request: a plain HTML form
736
+ # cannot set application/json.
737
+ self._json({"error": "Content-Type must be application/json"}, 415)
738
+ return False
739
+ return True
740
+
741
+ def _body_length(self) -> int:
742
+ raw = self.headers.get("Content-Length")
743
+ if raw is None:
744
+ return 0
745
+ try:
746
+ n = int(raw)
747
+ except (TypeError, ValueError):
748
+ raise ValueError("invalid Content-Length") from None
749
+ if n < 0:
750
+ raise ValueError("invalid Content-Length")
751
+ if n > MAX_BODY_BYTES:
752
+ raise ValueError("payload too large")
753
+ return n
754
+
755
+ def _security_headers(self) -> None:
756
+ self.send_header("X-Content-Type-Options", "nosniff")
757
+ self.send_header("Referrer-Policy", "no-referrer")
758
+ self.send_header("X-Frame-Options", "DENY")
759
+ self.send_header(
760
+ "Content-Security-Policy",
761
+ "default-src 'self'; img-src 'self' data: blob:; "
762
+ "style-src 'self' 'unsafe-inline'; script-src 'self'; "
763
+ "connect-src 'self'; object-src 'none'; base-uri 'none'; "
764
+ "frame-ancestors 'none'",
765
+ )
766
+
767
+ def do_PUT(self):
768
+ path = self.path.split("?", 1)[0]
769
+ if path != "/api/graph":
770
+ self.send_error(404)
771
+ return
772
+ if not self._guard_write():
773
+ return
774
+ try:
775
+ length = self._body_length()
776
+ except ValueError as e:
777
+ self._json({"error": str(e)}, 400)
778
+ return
779
+ raw = self.rfile.read(length)
780
+ try:
781
+ graph = json.loads(raw)
782
+ except json.JSONDecodeError:
783
+ self._json({"error": "invalid json"}, 400)
784
+ return
785
+ if not isinstance(graph, dict) \
786
+ or not isinstance(graph.get("nodes"), list) \
787
+ or not isinstance(graph.get("edges"), list):
788
+ self._json({"error": "graph must be {nodes: [], edges: []}"}, 400)
789
+ return
790
+ _save_graph(graph)
791
+ _broadcast("graph:updated", graph)
792
+ self._json({"ok": True})
793
+
794
+ def _read_json(self):
795
+ length = self._body_length()
796
+ return json.loads(self.rfile.read(length))
797
+
798
+ def do_POST(self):
799
+ path = self.path.split("?", 1)[0]
800
+ if not self._guard_write():
801
+ return
802
+ if path not in ("/api/record", "/api/image"):
803
+ self.send_error(404)
804
+ return
805
+ try:
806
+ payload = self._read_json()
807
+ except (json.JSONDecodeError, ValueError) as e:
808
+ self._json({"error": str(e)}, 400)
809
+ return
810
+ if path == "/api/image":
811
+ try:
812
+ self._json(_store_image(payload))
813
+ except (OSError, ValueError) as e:
814
+ self._json({"error": str(e)}, 400)
815
+ return
816
+ record_id = payload.get("id", "")
817
+ if not record_id:
818
+ self._json({"error": "id required"}, 400)
819
+ return
820
+ try:
821
+ updated = _update_record(record_id, payload)
822
+ except (KeyError, db.NotFound) as e:
823
+ self._json({"error": str(e) or "not found"}, 404)
824
+ return
825
+ except ValueError as e:
826
+ self._json({"error": str(e)}, 400)
827
+ return
828
+ # Refresh so every open tab sees the new content; cosmetics survive.
829
+ graph = _refresh_graph()
830
+ _broadcast("graph:updated", graph)
831
+ self._json(updated)
832
+
833
+
834
+ def main(argv=None):
835
+ ap = argparse.ArgumentParser(prog="omp-memory overview")
836
+ ap.add_argument("--port", type=int, default=4173)
837
+ ap.add_argument("--no-open", action="store_true")
838
+ args = ap.parse_args(argv)
839
+
840
+ if not (DIST_DIR / "index.html").exists():
841
+ import sys
842
+ print(f"[overview] dist missing: {DIST_DIR}", file=sys.stderr)
843
+ checkout = Path(__file__).resolve().parent.parent.parent
844
+ if (checkout / "web").is_dir():
845
+ print("[overview] run: bash bin/web-deploy.sh", file=sys.stderr)
846
+ else:
847
+ print("[overview] run bin/web-deploy.sh from a repo checkout "
848
+ "(or set OMP_MEMORY_WEB_DIR)", file=sys.stderr)
849
+ return 1
850
+
851
+ server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler)
852
+ url = f"http://127.0.0.1:{args.port}"
853
+ print(f"[overview] {url}")
854
+ # The seeded cache may hold ids from another machine's store. Paint
855
+ # instantly from it, then reconcile against the local store in the
856
+ # background so foreign nodes self-heal without waiting for an edit.
857
+ def _self_heal():
858
+ try:
859
+ graph = _refresh_graph()
860
+ _broadcast("graph:updated", graph)
861
+ except sqlite3.OperationalError as e:
862
+ # A brand-new store has no schema until something writes to it;
863
+ # that is an empty universe, not a failure worth a warning.
864
+ if "no such table" not in str(e):
865
+ print(f"[overview] graph refresh failed: {e}", file=__import__("sys").stderr)
866
+ except Exception as e: # a broken store must not kill the viewer
867
+ print(f"[overview] graph refresh failed: {e}", file=__import__("sys").stderr)
868
+ threading.Thread(target=_self_heal, daemon=True).start()
869
+ if not args.no_open:
870
+ threading.Timer(0.5, lambda: webbrowser.open(url)).start()
871
+ try:
872
+ server.serve_forever()
873
+ except KeyboardInterrupt:
874
+ pass
875
+ return 0
876
+
877
+
878
+ if __name__ == "__main__":
879
+ raise SystemExit(main())