Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(memory): three-layer memory subsystem (L1/L2/L3) with workbench

Bingxi Zhao (Frank)2b7242081ff6
diff --git a/deeptutor/api/routers/memory.py b/deeptutor/api/routers/memory.py
index 34e9ad6d6..101143b51 100644
--- a/deeptutor/api/routers/memory.py
+++ b/deeptutor/api/routers/memory.py
@@ -1,87 +1,785 @@
-"""
-Two-file public memory API: SUMMARY and PROFILE.
+"""Memory v3 API — workbench backend.
+
+Three layers, three modes (update / audit / dedup). Long-running work
+is owned by the :mod:`runs` manager so a refresh / nav-away does not
+kill it; clients re-attach by polling ``/runs/{id}/events?since=N``.
+
+- ``GET /overview`` → all 11 docs' state + L1 backlog
+- ``GET /doc/{layer}/{key}`` → raw MD
+- ``GET /doc/{layer}/{key}/lines`` → line-numbered view
+- ``PUT /doc/{layer}/{key}`` → user-edited save
+- ``DELETE /doc/{layer}/{key}/entry/{id}`` → drop one entry
+- ``POST /runs/start`` → start update/audit/dedup; returns run_id
+- ``GET /runs/{id}`` → run state
+- ``GET /runs/{id}/events?since=N`` → SSE-replay events from cursor N
+- ``POST /runs/{id}/cancel`` → cooperative cancellation
+- ``POST /runs/{id}/undo`` → restore latest run write
+- ``GET /runs?layer=L2&key=chat`` → active+recent runs for one doc
+- ``GET /settings`` → memory: settings subtree
+- ``PUT /settings`` → save memory: settings subtree
+- ``GET /trace/{surface}`` → paginated L1 events
+- ``DELETE /trace/{surface}/day/{date}`` → drop one day of trace
+- ``DELETE /trace/{surface}`` → drop all trace for a surface
+- ``GET /backup`` → list v1-migration backup dirs (if any)
+
+The legacy per-mode endpoints (``POST /doc/{layer}/{key}/update`` etc.)
+are kept for the moment as thin wrappers that start a run and stream
+its events — older clients keep working.
"""
from __future__ import annotations
+from dataclasses import asdict
+from datetime import date as date_cls
+import json
+import logging
+import re
+from typing import Literal
+
from fastapi import APIRouter, HTTPException
+from fastapi.responses import StreamingResponse
from pydantic import BaseModel
-from deeptutor.services.memory import MemoryFile, get_memory_service
-from deeptutor.services.session import get_session_store
+from deeptutor.services.memory import (
+ L3_SLOTS,
+ SURFACES,
+ Surface,
+ get_memory_store,
+ paths,
+)
+_ENTRY_ID_RE = re.compile(r"^m_[0-9A-HJKMNP-TV-Z]{26}$")
+
+logger = logging.getLogger(__name__)
router = APIRouter()
-_VALID_FILES: set[MemoryFile] = {"summary", "profile"}
+Layer = Literal["L2", "L3"]
+
+
+# ── Helpers ──────────────────────────────────────────────────────────────
+
+
+def _validate_doc_key(layer: Layer, key: str) -> None:
+ if layer == "L2" and key not in SURFACES:
+ raise HTTPException(status_code=404, detail=f"unknown surface {key!r}")
+ if layer == "L3" and key not in L3_SLOTS:
+ raise HTTPException(status_code=404, detail=f"unknown L3 slot {key!r}")
+
+
+def _validate_layer(layer: str) -> Layer:
+ if layer not in {"L2", "L3"}:
+ raise HTTPException(status_code=400, detail="layer must be L2 or L3")
+ return layer # type: ignore[return-value]
+
+
+def _validate_surface(surface: str) -> Surface:
+ if surface not in SURFACES:
+ raise HTTPException(status_code=404, detail=f"unknown surface {surface!r}")
+ return surface # type: ignore[return-value]
+
+
+# ── Overview / list ──────────────────────────────────────────────────────
+
+
[email protected]("/overview")
+async def get_overview():
+ store = get_memory_store()
+ rows = [asdict(r) for r in store.overview()]
+ backup_dir = paths.backup_root()
+ backups: list[str] = []
+ if backup_dir.exists():
+ backups = sorted(p.name for p in backup_dir.iterdir() if p.is_dir())
+ return {"docs": rows, "backups": backups}
+
+
[email protected]("/resolve_entry/{entry_id}")
+async def resolve_entry(entry_id: str):
+ """Find which L2 doc owns this entry id.
+
+ L3 docs cite L2 entries by their ``m_<ULID>`` entry id; the workbench
+ UI uses this resolver to turn an L3 footnote click into a navigation
+ to the right L2 surface + scroll-to anchor.
+
+ Scans the seven L2 mds in order; first hit wins. 404 if no L2 doc
+ contains the id (e.g. the entry was deleted or the id is stale).
+ """
+ if not _ENTRY_ID_RE.match(entry_id):
+ raise HTTPException(status_code=400, detail="not a valid entry id")
+ from deeptutor.services.memory.document import parse
+
+ for surface in SURFACES:
+ path = paths.l2_file(surface)
+ if not path.exists():
+ continue
+ try:
+ doc = parse(path.read_text(encoding="utf-8"))
+ except Exception: # noqa: BLE001 — malformed L2 should not 500 the resolver
+ continue
+ for entry in doc.all_entries():
+ if entry.id == entry_id:
+ return {"layer": "L2", "key": surface, "entry_id": entry_id}
+ raise HTTPException(status_code=404, detail="entry not found in any L2 doc")
+
+
+async def list_backups():
+ backup_dir = paths.backup_root()
+ if not backup_dir.exists():
+ return {"backups": []}
+ out: list[dict] = []
+ for entry in sorted(backup_dir.iterdir()):
+ if entry.is_dir():
+ files = sorted(p.name for p in entry.iterdir())
+ out.append({"name": entry.name, "files": files})
+ return {"backups": out}
+
+
+# ── Doc read / write / delete ────────────────────────────────────────────
+
+
[email protected]("/doc/{layer}/{key}")
+async def get_doc(layer: str, key: str):
+ lyr = _validate_layer(layer)
+ _validate_doc_key(lyr, key)
+ return {"layer": lyr, "key": key, "content": get_memory_store().read_raw(lyr, key)}
+
+
+class DocWriteRequest(BaseModel):
+ content: str
+
+
[email protected]("/doc/{layer}/{key}")
+async def put_doc(layer: str, key: str, payload: DocWriteRequest):
+ lyr = _validate_layer(layer)
+ _validate_doc_key(lyr, key)
+ await get_memory_store().overwrite_doc(lyr, key, payload.content)
+ return {"layer": lyr, "key": key, "saved": True}
+
+
[email protected]("/doc/{layer}/{key}/entry/{entry_id}")
+async def delete_entry(layer: str, key: str, entry_id: str):
+ lyr = _validate_layer(layer)
+ _validate_doc_key(lyr, key)
+ ok = await get_memory_store().delete_entry(lyr, key, entry_id)
+ if not ok:
+ raise HTTPException(status_code=404, detail="entry not found")
+ return {"layer": lyr, "key": key, "deleted": entry_id}
+
+
[email protected]("/doc/{layer}/{key}/reset")
+async def reset_doc(layer: str, key: str):
+ """Wipe the doc + its meta sidecar so the next update starts fresh.
+
+ Destructive — the caller has confirmed. After this returns the .md
+ file is gone *and* the ``seen_entity_refs`` set is cleared, so a
+ subsequent ``run_update`` re-ingests every L1 entity instead of
+ treating them as already-seen.
+
+ Refuses while a consolidator run is active on this doc; the caller
+ can cancel first.
+ """
+ lyr = _validate_layer(layer)
+ _validate_doc_key(lyr, key)
+
+ from deeptutor.services.memory.consolidator.runs import get_run_manager
+
+ if get_run_manager().active_for(lyr, key) is not None:
+ raise HTTPException(
+ status_code=409,
+ detail="cancel the active run before resetting this doc",
+ )
+
+ from deeptutor.services.memory.consolidator import meta as meta_mod
+
+ doc_path = paths.l2_file(key) if lyr == "L2" else paths.l3_file(key) # type: ignore[arg-type]
+ meta_path = (
+ meta_mod.l2_meta_path(key) # type: ignore[arg-type]
+ if lyr == "L2"
+ else meta_mod.l3_meta_path(key) # type: ignore[arg-type]
+ )
+
+ removed_doc = False
+ removed_meta = False
+ try:
+ if doc_path.exists():
+ doc_path.unlink()
+ removed_doc = True
+ if meta_path.exists():
+ meta_path.unlink()
+ removed_meta = True
+ except OSError as exc:
+ raise HTTPException(status_code=500, detail=f"reset failed: {exc}") from exc
+
+ return {
+ "layer": lyr,
+ "key": key,
+ "reset": True,
+ "removed_doc": removed_doc,
+ "removed_meta": removed_meta,
+ }
+
+
+# ── Doc update (SSE-streamed consolidator) ───────────────────────────────
+
+
+class LLMSelectionPayload(BaseModel):
+ profile_id: str
+ model_id: str
+
+
+class RunStartRequest(BaseModel):
+ layer: str
+ key: str
+ mode: Literal["update", "audit", "dedup", "merge"]
+ language: str = "en"
+ budget: int | None = None
+ iterations: int | None = None
+ llm_selection: LLMSelectionPayload | None = None
+
+
+def _runner_for(req: RunStartRequest):
+ """Return an ``async on_event → None`` runner for the requested mode."""
+ from deeptutor.services.memory.consolidator import (
+ run_audit,
+ run_dedup,
+ run_merge,
+ run_update,
+ )
+
+ selection = (
+ {"profile_id": req.llm_selection.profile_id, "model_id": req.llm_selection.model_id}
+ if req.llm_selection
+ else None
+ )
+
+ if req.mode == "update":
+
+ async def go(on_event):
+ await run_update(
+ req.layer,
+ req.key,
+ language=req.language,
+ budget=req.budget,
+ llm_selection=selection,
+ on_event=on_event,
+ )
+
+ return go
+ if req.mode == "audit":
+
+ async def go(on_event):
+ await run_audit(
+ req.layer,
+ req.key,
+ language=req.language,
+ budget=req.budget,
+ llm_selection=selection,
+ on_event=on_event,
+ )
+
+ return go
+ if req.mode == "dedup":
+
+ async def go(on_event):
+ await run_dedup(
+ req.layer,
+ req.key,
+ language=req.language,
+ iterations=req.iterations,
+ llm_selection=selection,
+ on_event=on_event,
+ )
+
+ return go
+ if req.mode == "merge":
+
+ async def go(on_event):
+ await run_merge(
+ req.layer,
+ req.key,
+ language=req.language,
+ on_event=on_event,
+ )
+
+ return go
+ raise HTTPException(status_code=400, detail=f"unknown mode {req.mode!r}")
+
+
[email protected]("/runs/start")
+async def start_run(req: RunStartRequest):
+ """Start one consolidator mode and return a run handle.
+
+ The run survives client disconnects; reconnect via
+ ``GET /runs/{id}/events?since=N``.
+ """
+ lyr = _validate_layer(req.layer)
+ _validate_doc_key(lyr, req.key)
+ if lyr == "L3" and req.key == "preferences" and req.mode not in ("dedup", "merge"):
+ raise HTTPException(
+ status_code=405,
+ detail="preferences is written by the write_memory tool, not consolidated",
+ )
+ from deeptutor.services.memory.consolidator.runs import (
+ RunBusyError,
+ get_run_manager,
+ )
+
+ manager = get_run_manager()
+ runner = _runner_for(req)
+ selection = (
+ {"profile_id": req.llm_selection.profile_id, "model_id": req.llm_selection.model_id}
+ if req.llm_selection
+ else None
+ )
+ try:
+ run = await manager.start(
+ layer=lyr,
+ key=req.key,
+ mode=req.mode,
+ runner=runner,
+ params={
+ "budget": req.budget,
+ "iterations": req.iterations,
+ "language": req.language,
+ "llm_selection": selection,
+ },
+ language=req.language,
+ )
+ except RunBusyError as exc:
+ raise HTTPException(status_code=409, detail=str(exc))
+ return run.to_dict()
+
+
[email protected]("/runs/{run_id}")
+async def get_run(run_id: str):
+ from deeptutor.services.memory.consolidator.runs import get_run_manager
+
+ run = get_run_manager().get(run_id)
+ if run is None:
+ raise HTTPException(status_code=404, detail="unknown run_id")
+ return run.to_dict()
-def get_sqlite_session_store():
- """Backward-compatible hook for tests and legacy monkeypatches."""
- return get_session_store()
[email protected]("/runs/{run_id}/cancel")
+async def cancel_run(run_id: str):
+ from deeptutor.services.memory.consolidator.runs import get_run_manager
+ ok = await get_run_manager().cancel(run_id)
+ if not ok:
+ raise HTTPException(status_code=409, detail="not active")
+ return {"run_id": run_id, "cancelled": True}
-def _snap_dict(snap) -> dict:
+
[email protected]("/runs/{run_id}/undo")
+async def undo_run_edit(run_id: str):
+ from deeptutor.services.memory.consolidator.runs import (
+ RunBusyError,
+ get_run_manager,
+ )
+
+ manager = get_run_manager()
+ try:
+ event = await manager.undo_last(run_id)
+ except KeyError:
+ raise HTTPException(status_code=404, detail="unknown run_id")
+ except RunBusyError as exc:
+ raise HTTPException(status_code=409, detail=str(exc))
+ if event is None:
+ raise HTTPException(status_code=409, detail="nothing to undo")
+ run = manager.get(run_id)
return {
- "summary": snap.summary,
- "profile": snap.profile,
- "summary_updated_at": snap.summary_updated_at,
- "profile_updated_at": snap.profile_updated_at,
+ "run_id": run_id,
+ "undone": True,
+ "undo_count": len(run.undo_stack) if run else 0,
+ "event": {"seq": event.seq, "ts": event.ts, **event.payload},
}
-class FileUpdateRequest(BaseModel):
- file: MemoryFile
- content: str = ""
+async def list_runs(layer: str | None = None, key: str | None = None):
+ from deeptutor.services.memory.consolidator.runs import get_run_manager
+
+ lyr = _validate_layer(layer) if layer is not None else None
+ if lyr and key is not None:
+ _validate_doc_key(lyr, key)
+ runs = get_run_manager().list_for(layer=lyr, key=key)
+ return {"runs": [r.to_dict() for r in runs]}
+
+
[email protected]("/runs/{run_id}/events")
+async def stream_run_events(run_id: str, since: int = 0):
+ """SSE-replay events from ``since`` (exclusive) until the run ends.
+
+ Reconnecting after a refresh: pass the largest ``seq`` previously
+ observed. The manager replays the buffered tail, then blocks on
+ new events until the run reaches a terminal state.
+ """
+ from deeptutor.services.memory.consolidator.runs import get_run_manager
+
+ manager = get_run_manager()
+ run = manager.get(run_id)
+ if run is None:
+ raise HTTPException(status_code=404, detail="unknown run_id")
+
+ async def producer():
+ cursor = max(0, since)
+ # Initial backfill (if any) is delivered as a batch up front.
+ while True:
+ events = await manager.wait_for_events(run, since=cursor)
+ for ev in events:
+ yield (
+ "data: "
+ + json.dumps(
+ {"seq": ev.seq, "ts": ev.ts, **ev.payload},
+ ensure_ascii=False,
+ )
+ + "\n\n"
+ )
+ cursor = max(cursor, run.events[-1].seq + 1 if run.events else cursor)
+ if not run.active:
+ # Drain any final events that arrived between wait return and now.
+ final = run.events[cursor:]
+ for ev in final:
+ yield (
+ "data: "
+ + json.dumps(
+ {"seq": ev.seq, "ts": ev.ts, **ev.payload},
+ ensure_ascii=False,
+ )
+ + "\n\n"
+ )
+ break
+
+ return StreamingResponse(producer(), media_type="text/event-stream")
-class MemoryRefreshRequest(BaseModel):
- session_id: str | None = None
+# ── Legacy per-mode endpoints (kept as thin wrappers over /runs/start) ──
+
+
+def _legacy_run_stream(req: RunStartRequest) -> StreamingResponse:
+ """Old contract: POST /doc/{layer}/{key}/<mode> streams events inline."""
+ from deeptutor.services.memory.consolidator.runs import (
+ RunBusyError,
+ get_run_manager,
+ )
+
+ async def producer():
+ manager = get_run_manager()
+ runner = _runner_for(req)
+ selection = (
+ {"profile_id": req.llm_selection.profile_id, "model_id": req.llm_selection.model_id}
+ if req.llm_selection
+ else None
+ )
+ try:
+ run = await manager.start(
+ layer=req.layer,
+ key=req.key,
+ mode=req.mode,
+ runner=runner,
+ params={
+ "budget": req.budget,
+ "iterations": req.iterations,
+ "language": req.language,
+ "llm_selection": selection,
+ },
+ language=req.language,
+ )
+ except RunBusyError as exc:
+ yield (
+ "data: "
+ + json.dumps({"stage": "error", "message": str(exc)}, ensure_ascii=False)
+ + "\n\n"
+ )
+ return
+ cursor = 0
+ while True:
+ events = await manager.wait_for_events(run, since=cursor)
+ for ev in events:
+ yield (
+ "data: "
+ + json.dumps({**ev.payload, "seq": ev.seq}, ensure_ascii=False)
+ + "\n\n"
+ )
+ cursor = ev.seq + 1
+ if not run.active:
+ break
+
+ return StreamingResponse(producer(), media_type="text/event-stream")
+
+
+class UpdateRequest(BaseModel):
language: str = "en"
+ budget: int | None = None
+ llm_selection: LLMSelectionPayload | None = None
-class MemoryClearRequest(BaseModel):
- file: MemoryFile | None = None
+class AuditRequest(BaseModel):
+ language: str = "en"
+ budget: int | None = None
+ llm_selection: LLMSelectionPayload | None = None
-async def get_memory():
- return _snap_dict(get_memory_service().read_snapshot())
+class DedupRequest(BaseModel):
+ language: str = "en"
+ iterations: int | None = None
+ llm_selection: LLMSelectionPayload | None = None
-async def update_memory(payload: FileUpdateRequest):
- if payload.file not in _VALID_FILES:
- raise HTTPException(status_code=400, detail=f"Invalid file: {payload.file}")
- snap = get_memory_service().write_file(payload.file, payload.content)
- return {**_snap_dict(snap), "saved": True}
[email protected]("/doc/{layer}/{key}/update")
+async def update_doc(layer: str, key: str, payload: UpdateRequest | None = None):
+ lyr = _validate_layer(layer)
+ _validate_doc_key(lyr, key)
+ req = RunStartRequest(
+ layer=lyr,
+ key=key,
+ mode="update",
+ language=(payload.language if payload else "en") or "en",
+ budget=payload.budget if payload else None,
+ llm_selection=payload.llm_selection if payload else None,
+ )
+ return _legacy_run_stream(req)
[email protected]("/refresh")
-async def refresh_memory(payload: MemoryRefreshRequest):
- store = get_sqlite_session_store()
- session_id = str(payload.session_id or "").strip()
- if session_id:
- session = await store.get_session(session_id)
- if session is None:
- raise HTTPException(status_code=404, detail="Session not found")
[email protected]("/doc/{layer}/{key}/audit")
+async def audit_doc(layer: str, key: str, payload: AuditRequest | None = None):
+ lyr = _validate_layer(layer)
+ _validate_doc_key(lyr, key)
+ req = RunStartRequest(
+ layer=lyr,
+ key=key,
+ mode="audit",
+ language=(payload.language if payload else "en") or "en",
+ budget=payload.budget if payload else None,
+ llm_selection=payload.llm_selection if payload else None,
+ )
+ return _legacy_run_stream(req)
+
+
[email protected]("/doc/{layer}/{key}/dedup")
+async def dedup_doc(layer: str, key: str, payload: DedupRequest | None = None):
+ lyr = _validate_layer(layer)
+ _validate_doc_key(lyr, key)
+ req = RunStartRequest(
+ layer=lyr,
+ key=key,
+ mode="dedup",
+ language=(payload.language if payload else "en") or "en",
+ iterations=payload.iterations if payload else None,
+ llm_selection=payload.llm_selection if payload else None,
+ )
+ return _legacy_run_stream(req)
+
- result = await get_memory_service().refresh_from_session(
- session_id or None,
- language=payload.language,
[email protected]("/doc/{layer}/{key}/lines")
+async def get_doc_lines(layer: str, key: str):
+ """Return the line-numbered, footnote-stripped view of a doc.
+
+ Used by the workbench's "show line numbers" toggle so the same line
+ indices the audit/dedup LLMs see are visible to the user. Footnote
+ block is omitted because edit ops never reference it directly.
+ """
+ lyr = _validate_layer(layer)
+ _validate_doc_key(lyr, key)
+ from deeptutor.services.memory import paths
+ from deeptutor.services.memory.consolidator.line_doc import render_view
+ from deeptutor.services.memory.document import Document, parse
+
+ path = paths.l2_file(key) if lyr == "L2" else paths.l3_file(key) # type: ignore[arg-type]
+ doc = (
+ parse(path.read_text(encoding="utf-8"))
+ if path.exists()
+ else Document(title=_default_title(lyr, key))
)
- snap = get_memory_service().read_snapshot()
- return {**_snap_dict(snap), "changed": result.changed}
-
-
-async def clear_memory(payload: MemoryClearRequest | None = None):
- svc = get_memory_service()
- target = payload.file if payload else None
- if target and target not in _VALID_FILES:
- raise HTTPException(status_code=400, detail=f"Invalid file: {target}")
-
- if target:
- snap = svc.clear_file(target)
- else:
- snap = svc.clear_memory()
- return {**_snap_dict(snap), "cleared": True}
+ view = render_view(doc)
+ return {
+ "layer": lyr,
+ "key": key,
+ "lines": [
+ {
+ "number": line.number,
+ "kind": line.kind,
+ "text": line.text,
+ "entry_id": line.entry_id,
+ "section": line.section,
+ }
+ for line in view.lines
+ ],
+ }
+
+
+# ── Settings ────────────────────────────────────────────────────────────
+
+
[email protected]("/settings")
+async def get_memory_settings_endpoint():
+ """Return the current ``memory:`` subtree (defaults merged in)."""
+ from deeptutor.services.memory.settings import memory_settings_dict
+
+ return memory_settings_dict()
+
+
[email protected]("/settings")
+async def put_memory_settings(payload: dict):
+ """Merge the payload into the ``memory:`` subtree and persist."""
+ from deeptutor.services.memory.settings import (
+ memory_settings_dict,
+ save_memory_settings,
+ )
+
+ save_memory_settings(payload)
+ return memory_settings_dict()
+
+
+def _default_title(layer: str, key: str) -> str:
+ if layer == "L2":
+ return f"{key} memory"
+ return {
+ "recent": "Recent summary",
+ "profile": "User profile",
+ "scope": "Knowledge scope",
+ "preferences": "Preferences",
+ }.get(key, f"{key} memory")
+
+
+class ApplyOpsRequest(BaseModel):
+ ops: list[dict]
+
+
[email protected]("/doc/{layer}/{key}/apply")
+async def apply_doc_ops(layer: str, key: str, payload: ApplyOpsRequest):
+ """Commit a list of previously-previewed ops to a doc atomically."""
+ lyr = _validate_layer(layer)
+ _validate_doc_key(lyr, key)
+ if lyr == "L3" and key == "preferences":
+ raise HTTPException(
+ status_code=405,
+ detail="preferences is written by the write_memory tool, not consolidated",
+ )
+ if not payload.ops:
+ return {"accepted": True, "reason": "no ops to apply", "results": []}
+
+ report = await get_memory_store().apply_ops_payload(lyr, key, payload.ops)
+ return {
+ "accepted": report.accepted,
+ "reason": report.reason,
+ "results": [
+ {
+ "status": r.status,
+ "entry_id": r.entry_id,
+ "detail": r.detail,
+ }
+ for r in report.results
+ ],
+ }
+
+
+# ── Trace browser ────────────────────────────────────────────────────────
+
+
[email protected]("/trace/{surface}")
+async def get_trace(surface: str, limit: int = 200, offset: int = 0):
+ surf = _validate_surface(surface)
+ from deeptutor.services.memory.trace import iter_since
+
+ events = []
+ for i, event in enumerate(iter_since(surf)):
+ if i < offset:
+ continue
+ if len(events) >= max(1, min(limit, 1000)):
+ break
+ events.append(asdict(event))
+ return {"surface": surf, "events": events, "offset": offset, "limit": limit}
+
+
[email protected]("/trace/{surface}")
+async def clear_trace(surface: str):
+ surf = _validate_surface(surface)
+ removed = 0
+ for path in paths.trace_dir(surf).glob("*.jsonl"):
+ try:
+ path.unlink()
+ removed += 1
+ except OSError:
+ continue
+ return {"surface": surf, "removed_files": removed}
+
+
[email protected]("/trace/{surface}/day/{day}")
+async def clear_trace_day(surface: str, day: str):
+ surf = _validate_surface(surface)
+ try:
+ parsed = date_cls.fromisoformat(day)
+ except ValueError:
+ raise HTTPException(status_code=400, detail="day must be YYYY-MM-DD")
+ path = paths.trace_file(surf, parsed)
+ if not path.exists():
+ raise HTTPException(status_code=404, detail="no trace for that day")
+ try:
+ path.unlink()
+ except OSError as exc:
+ raise HTTPException(status_code=500, detail=str(exc))
+ return {"surface": surf, "day": day, "deleted": True}
+
+
+# ── Snapshot (L1 workspace mirror) ───────────────────────────────────────
+
+
[email protected]("/snapshot/{surface}")
+async def get_snapshot(surface: str):
+ """Return the current entity list for ``surface`` from workspace.
+
+ Snapshot is always derived live from workspace at call time. The response
+ also includes ``pending_changes`` — the diff vs the last persisted state.
+ Refresh commits these pending changes into ``changes.jsonl``.
+ """
+ surf = _validate_surface(surface)
+ from deeptutor.services.memory import snapshot as snap
+
+ entities = snap.read_snapshot(surf)
+ pending = snap.pending_changes(surf, entities)
+ state = snap.current_state(surf)
+ return {
+ "surface": surf,
+ "entities": [e.to_dict() for e in entities],
+ "last_refresh": state.get("last_refresh"),
+ "pending_changes": [c.to_dict() for c in pending],
+ }
+
+
[email protected]("/snapshot/{surface}/refresh")
+async def refresh_snapshot(surface: str):
+ """Reconcile persisted state with current workspace; record diffs."""
+ surf = _validate_surface(surface)
+ from deeptutor.services.memory import snapshot as snap
+
+ changes = snap.refresh_snapshot(surf)
+ state = snap.current_state(surf)
+ return {
+ "surface": surf,
+ "changes": [c.to_dict() for c in changes],
+ "last_refresh": state.get("last_refresh"),
+ }
+
+
[email protected]("/snapshot/{surface}/changes")
+async def get_changes(surface: str, limit: int = 200, offset: int = 0):
+ surf = _validate_surface(surface)
+ from deeptutor.services.memory import snapshot as snap
+
+ entries = snap.read_changes(surf, limit=limit, offset=offset)
+ return {
+ "surface": surf,
+ "changes": [c.to_dict() for c in entries],
+ "limit": limit,
+ "offset": offset,
+ }
+
+
[email protected]("/snapshot/{surface}/changes")
+async def clear_snapshot_changes(surface: str):
+ surf = _validate_surface(surface)
+ from deeptutor.services.memory import snapshot as snap
+
+ snap.clear_changes(surf)
+ return {"surface": surf, "cleared": True}
diff --git a/deeptutor/services/memory/__init__.py b/deeptutor/services/memory/__init__.py
index 1efea6dc0..f2e4dc1f4 100644
--- a/deeptutor/services/memory/__init__.py
+++ b/deeptutor/services/memory/__init__.py
@@ -1,15 +1,34 @@
-from .service import (
- MemoryFile,
- MemoryService,
- MemorySnapshot,
- MemoryUpdateResult,
- get_memory_service,
-)
+"""Three-layer memory subsystem.
+
+- ``trace`` : L1 raw event capture (append-only JSONL per surface per day)
+- ``document``: L2/L3 markdown + footnote-citation parser/serializer (pure)
+- ``ops`` : add/edit/delete batch applier (pure)
+- ``paths`` : per-user path resolution
+- ``ids`` : ULID-style trace and entry id generators
+- ``store`` : public facade — :class:`MemoryStore`
+- ``consolidator``: LLM-driven L1→L2 and L2→L3 ops
+
+The v1 two-file `MemoryService` is gone. All callers go through
+:func:`get_memory_store` and the :class:`MemoryStore` facade.
+"""
+
+from .ids import is_entry_id, is_trace_id, new_entry_id, new_trace_id
+from .paths import L3_SLOTS, SURFACES, L3Slot, Surface
+from .store import DocOverview, MemoryStore, get_memory_store, migrate_v1_if_needed
+from .trace import TraceEvent
__all__ = [
- "MemoryFile",
- "MemoryService",
- "MemorySnapshot",
- "MemoryUpdateResult",
- "get_memory_service",
+ "DocOverview",
+ "L3_SLOTS",
+ "L3Slot",
+ "MemoryStore",
+ "SURFACES",
+ "Surface",
+ "TraceEvent",
+ "get_memory_store",
+ "is_entry_id",
+ "is_trace_id",
+ "migrate_v1_if_needed",
+ "new_entry_id",
+ "new_trace_id",
]
diff --git a/deeptutor/services/memory/consolidator/__init__.py b/deeptutor/services/memory/consolidator/__init__.py
new file mode 100644
index 000000000..6e55707b3
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/__init__.py
@@ -0,0 +1,62 @@
+"""Memory consolidator — chunk-based update / audit / dedup.
+
+Public surface (call these from the API router / store / tests):
+
+* :class:`ConsolidateResult`, :data:`OnEvent` — legacy types preserved
+ for :mod:`deeptutor.services.memory.store`.
+* :func:`consolidate_l2`, :func:`consolidate_l3` — legacy shims that
+ delegate to :func:`run_update`.
+* :func:`run_update`, :func:`run_audit`, :func:`run_dedup` — the three
+ modes the workbench drives directly.
+* :func:`_parse_ops_response`, :func:`_filter_banned`,
+ :func:`_has_banned` — kept for :meth:`store.MemoryStore.apply_ops_payload`
+ and the existing test suite.
+
+Submodule layout:
+
+ chunker.py pure char-based chunker with boundary expansion
+ line_doc.py line-numbered view + replace/delete/insert edits
+ meta.py *.meta.json read/write for "seen ids" diffs
+ references.py ref pool validation + raw-trace annotation
+ guards.py banned-phrase filter (legacy + L3 enforcement)
+ parse.py legacy ops-array parser (apply_ops_payload)
+ modes/
+ _runtime.py shared prompt loading + LLM + atomic write
+ _shims.py legacy consolidate_l2/l3 → run_update
+ update.py chunk-based incremental fact extraction
+ audit.py chunk-based line edits vs raw evidence
+ dedup.py iterative line-level dedup over full doc
+ prompts/
+ {en,zh}/{update_l2,update_l3,audit_l2,audit_l3,dedup,_meta}.yaml
+"""
+
+from __future__ import annotations
+
+from deeptutor.services.memory.consolidator.guards import _filter_banned, _has_banned
+from deeptutor.services.memory.consolidator.modes import (
+ consolidate_l2,
+ consolidate_l3,
+ run_audit,
+ run_dedup,
+ run_merge,
+ run_update,
+)
+from deeptutor.services.memory.consolidator.modes._shims import (
+ ConsolidateResult,
+ OnEvent,
+)
+from deeptutor.services.memory.consolidator.parse import _parse_ops_response
+
+__all__ = [
+ "ConsolidateResult",
+ "OnEvent",
+ "_filter_banned",
+ "_has_banned",
+ "_parse_ops_response",
+ "consolidate_l2",
+ "consolidate_l3",
+ "run_audit",
+ "run_dedup",
+ "run_merge",
+ "run_update",
+]
diff --git a/deeptutor/services/memory/consolidator/chunker.py b/deeptutor/services/memory/consolidator/chunker.py
new file mode 100644
index 000000000..90f73cb68
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/chunker.py
@@ -0,0 +1,134 @@
+"""Character-based chunking with boundary expansion.
+
+The L2 / L3 update flow concatenates inputs into one string, then
+:func:`chunk_with_boundary` cuts it into ≤ budget pieces. Each piece's
+right edge is extended forward to the next paragraph or sentence
+boundary — content is **never truncated mid-statement**. Adjacent
+chunks overlap by a percentage of the target size so a fact straddling
+a cut still gets a fair read.
+
+Pure functions: no I/O, no LLM. Easy to unit-test.
+"""
+
+from __future__ import annotations
+
+import math
+import re
+from dataclasses import dataclass
+from typing import Literal
+
+
+Boundary = Literal["paragraph", "sentence"]
+
+# Paragraph boundary: one or more blank lines.
+_PARA_BOUNDARY = re.compile(r"\n\s*\n+")
+# Sentence boundary: terminal punctuation followed by space/newline.
+# Covers ASCII (.!?) and CJK (。!?).
+_SENT_BOUNDARY = re.compile(r"[.!?。!?](?:[\")»」』]+)?(?=\s|$)")
+
+
+@dataclass(frozen=True)
+class ChunkSpan:
+ """One chunk's coordinates inside the source text.
+
+ ``start`` is inclusive, ``end`` exclusive. ``index`` is the 0-based
+ position in the returned list (useful for events).
+ """
+
+ index: int
+ start: int
+ end: int
+ text: str
+
+
+def chunk_with_boundary(
+ text: str,
+ *,
+ budget: int,
+ overlap_ratio: float,
+ min_chunk_chars: int,
+ max_chunk_chars: int,
+ boundary: Boundary = "paragraph",
+) -> list[ChunkSpan]:
+ """Cut ``text`` into ≤ ``budget`` chunks aligned to natural boundaries.
+
+ * Target size = ``clamp(ceil(len(text) / budget), min, max)``.
+ * Right edge of each chunk is extended forward to the next
+ ``boundary`` so no sentence/paragraph is split.
+ * Adjacent chunks overlap by ``round(target * overlap_ratio)`` chars.
+ * If the input is short enough to fit in a single chunk, returns
+ one ``ChunkSpan`` covering everything.
+ """
+ if not text.strip():
+ return []
+ if budget < 1:
+ budget = 1
+
+ n = len(text)
+ target = math.ceil(n / budget)
+ target = max(min_chunk_chars, min(max_chunk_chars, target))
+ overlap = max(0, min(target - 1, round(target * overlap_ratio)))
+
+ # Short-circuit: input fits in one chunk.
+ if n <= target:
+ return [ChunkSpan(index=0, start=0, end=n, text=text)]
+
+ # Hard cap on how far the right edge can be pulled to find a
+ # boundary. Beyond this we accept a non-boundary cut so chunks
+ # never grow past ``max_chunk_chars`` even in degenerate input
+ # (e.g. a single long line with no paragraph/sentence breaks).
+ spans: list[ChunkSpan] = []
+ cursor = 0
+ while cursor < n:
+ target_end = min(n, cursor + target)
+ hard_cap = min(n, cursor + max_chunk_chars)
+ if target_end >= n:
+ end = n
+ else:
+ end = _expand_to_boundary(text, target_end, boundary, limit=hard_cap)
+ # Guarantee forward motion: the boundary expansion may pull us
+ # to len(text), or — degenerate input — to ``target_end`` itself.
+ if end <= cursor:
+ end = min(n, cursor + max(1, target))
+ spans.append(
+ ChunkSpan(
+ index=len(spans),
+ start=cursor,
+ end=end,
+ text=text[cursor:end],
+ )
+ )
+ if end >= n:
+ break
+ next_cursor = end - overlap
+ # No infinite loop: must advance by at least one char even with
+ # huge overlap.
+ if next_cursor <= cursor:
+ next_cursor = cursor + 1
+ cursor = next_cursor
+
+ return spans
+
+
+# ── Internals ───────────────────────────────────────────────────────────
+
+
+def _expand_to_boundary(
+ text: str, target_end: int, boundary: Boundary, *, limit: int
+) -> int:
+ """Push ``target_end`` forward to the next natural boundary.
+
+ The search is bounded by ``limit`` (exclusive). If no boundary is
+ found within that window the function returns ``limit`` — a non-
+ boundary cut, but a bounded one. Without this the chunker can
+ inflate a single chunk to the end of the input on pathological
+ text with no paragraph/sentence markers.
+ """
+ pattern = _PARA_BOUNDARY if boundary == "paragraph" else _SENT_BOUNDARY
+ match = pattern.search(text, target_end, limit)
+ if match is None:
+ return limit
+ return match.end()
+
+
+__all__ = ["Boundary", "ChunkSpan", "chunk_with_boundary"]
diff --git a/deeptutor/services/memory/consolidator/guards.py b/deeptutor/services/memory/consolidator/guards.py
new file mode 100644
index 000000000..7681efc73
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/guards.py
@@ -0,0 +1,103 @@
+"""Op-emit guards: banned-phrase filter + budgets.
+
+Run at op-emit time (during the loop) so the model gets an observation
+back when an op is rejected and can rewrite. Today's pre-redesign code
+filtered banned phrases after the LLM call returned all ops at once,
+which meant rejection was a silent drop.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+from dataclasses import dataclass
+from typing import Iterable
+
+from deeptutor.services.memory.ops import Op
+
+logger = logging.getLogger(__name__)
+
+# L3 objectivity guard: phrases the LLM is prompt-banned from emitting.
+# Runtime enforces by dropping any L3 op whose text contains one of these
+# (outside of quoted user verbatim 「」 / "…"). Logged as a warning so we
+# can tune the list against real prompt regressions.
+BANNED_PHRASES: tuple[str, ...] = (
+ # English absolutes
+ "deeply",
+ "truly",
+ "mastered",
+ "expert in",
+ "passionate",
+ "loves",
+ "hates",
+ "always",
+ "never",
+ "fully understands",
+ # Chinese absolutes
+ "深刻",
+ "彻底",
+ "完美掌握",
+ "完美理解",
+ "完全理解",
+ "完全掌握",
+ "专家",
+ "热爱",
+ "总是",
+ "从来不",
+)
+
+# Per-loop budgets. Beyond these the dispatcher emits a hint observation
+# instead of executing the action; the prompt nudges the model to finish.
+@dataclass(frozen=True)
+class ToolBudgets:
+ read_entity: int = 30
+ search: int = 20
+ list_pending: int = 50 # cheap nav, generous
+ list_sections: int = 50
+ recent_changes: int = 3
+ add_entry: int = 12
+ edit_entry: int = 12
+ delete_entry: int = 12
+ note: int = 8
+
+
+_QUOTED_RE = re.compile(r"「[^」]*」|\"[^\"]*\"")
+
+
+def _has_banned(text: str) -> bool:
+ """Return ``True`` iff a banned phrase appears outside every quote.
+
+ Quoted regions (CJK 「…」 or ASCII "…") are stripped first, because
+ the prompt allows verbatim user quotations to contain the otherwise-
+ banned absolutes.
+ """
+ stripped = _QUOTED_RE.sub("", text).lower()
+ for phrase in BANNED_PHRASES:
+ if phrase in stripped:
+ return True
+ return False
+
+
+def _op_text(op: Op) -> str:
+ text = getattr(op, "text", "") or getattr(op, "new_text", "")
+ return str(text)
+
+
+def _filter_banned(ops: Iterable[Op]) -> list[Op]:
+ """Drop ops whose text contains banned absolutist phrasing.
+
+ Used post-loop as a safety net even though the per-op emit path
+ already rejects them. Kept callable by name for legacy tests and
+ the apply_ops_payload preview/apply round-trip.
+ """
+ kept: list[Op] = []
+ for op in ops:
+ text = _op_text(op)
+ if text and _has_banned(text):
+ logger.warning(
+ "memory consolidate: dropped op with banned phrase: %s",
+ text[:80],
+ )
+ continue
+ kept.append(op)
+ return kept
diff --git a/deeptutor/services/memory/consolidator/line_doc.py b/deeptutor/services/memory/consolidator/line_doc.py
new file mode 100644
index 000000000..5549a6bcf
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/line_doc.py
@@ -0,0 +1,488 @@
+"""Line-numbered view of a memory document + line-level edit ops.
+
+The audit / dedup modes ask the LLM to operate on a memory document
+the same way an IDE assistant operates on source code: it sees
+numbered lines and emits structured edits referencing those numbers.
+
+To keep the document's invariants intact, the LLM only ever sees a
+**sanitized** view — section headers (``## name``) and entry bullets
+(``- text [^m_xxx]``). The footnote block is hidden and rebuilt by
+:func:`apply_edits` from the surviving entries' refs.
+
+Editing model
+-------------
+Three op types: ``ReplaceLineOp``, ``DeleteLinesOp``, ``InsertAfterOp``.
+Apply in **descending line order** so earlier lines never shift under
+later edits. Each op carries a free-form ``reason`` for observability;
+audit/dedup prompts require it. Refs are mandatory on replace / insert
+of an entry (validated by the runtime).
+
+Public API
+----------
+* :func:`render_view` — turn a :class:`Document` into a list of numbered
+ :class:`Line` rows + lookup tables.
+* :func:`apply_edits` — apply a batch of edits to a document; pure
+ function (returns a new document) so callers can preview without
+ mutating shared state.
+* :func:`parse_edits_payload` — tolerant JSON → typed edit list parser.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+from dataclasses import dataclass, field
+from typing import Iterable, Literal, Union
+
+from deeptutor.services.memory.document import Document, Entry
+from deeptutor.services.memory.ids import is_entry_id, new_entry_id
+
+logger = logging.getLogger(__name__)
+
+LineKind = Literal["title", "blank", "section", "bullet"]
+
+
+@dataclass(frozen=True)
+class Line:
+ number: int # 1-based, matches what the LLM sees
+ kind: LineKind
+ text: str # rendered text (no leading "n: ")
+ entry_id: str | None = None # for bullet lines, the m_xxx id
+ section: str | None = None # for bullet lines, owning section name
+
+
+@dataclass(frozen=True)
+class LineView:
+ """Snapshot of the sanitized document seen by audit / dedup LLMs."""
+
+ lines: list[Line]
+ entry_by_id: dict[str, Entry]
+ entries_in_order: list[Entry]
+
+ def render(self, *, with_numbers: bool = True) -> str:
+ if with_numbers:
+ width = max(2, len(str(len(self.lines))))
+ return "\n".join(
+ f"{l.number:>{width}}: {l.text}" for l in self.lines
+ )
+ return "\n".join(l.text for l in self.lines)
+
+ def line(self, number: int) -> Line | None:
+ return self.lines[number - 1] if 1 <= number <= len(self.lines) else None
+
+
+# ── Edit ops ────────────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class ReplaceLineOp:
+ line: int
+ new_text: str
+ refs: list[str]
+ reason: str = ""
+ op: Literal["replace"] = "replace"
+
+
+@dataclass(frozen=True)
+class DeleteLinesOp:
+ line_start: int
+ line_end: int # inclusive
+ reason: str = ""
+ op: Literal["delete"] = "delete"
+
+
+@dataclass(frozen=True)
+class InsertAfterOp:
+ after_line: int
+ text: str
+ refs: list[str]
+ # ``section`` is optional: when None, the engine uses the section
+ # containing ``after_line``. If after_line is 0 (top-of-doc) or
+ # points at a title/blank, section MUST be provided.
+ section: str | None = None
+ reason: str = ""
+ op: Literal["insert"] = "insert"
+
+
+Edit = Union[ReplaceLineOp, DeleteLinesOp, InsertAfterOp]
+
+
+@dataclass
+class EditResult:
+ op: Edit
+ status: Literal["applied", "rejected"]
+ detail: str = ""
+
+
+@dataclass
+class EditReport:
+ applied: list[EditResult] = field(default_factory=list)
+ rejected: list[EditResult] = field(default_factory=list)
+
+ @property
+ def all_results(self) -> list[EditResult]:
+ return self.applied + self.rejected
+
+
+# ── Render: Document → LineView ─────────────────────────────────────────
+
+
+def render_view(doc: Document) -> LineView:
+ """Produce the numbered view the LLM operates on."""
+ lines: list[Line] = []
+ entries_in_order: list[Entry] = []
+ entry_by_id: dict[str, Entry] = {}
+
+ if doc.title:
+ lines.append(Line(number=len(lines) + 1, kind="title", text=f"# {doc.title}"))
+ lines.append(Line(number=len(lines) + 1, kind="blank", text=""))
+
+ for section_name, entries in doc.sections:
+ if not entries:
+ continue
+ lines.append(
+ Line(number=len(lines) + 1, kind="section", text=f"## {section_name}")
+ )
+ for entry in entries:
+ lines.append(
+ Line(
+ number=len(lines) + 1,
+ kind="bullet",
+ text=f"- {entry.text} [^{entry.id}]",
+ entry_id=entry.id,
+ section=section_name,
+ )
+ )
+ entries_in_order.append(entry)
+ entry_by_id[entry.id] = entry
+ lines.append(Line(number=len(lines) + 1, kind="blank", text=""))
+
+ # Strip the trailing blank so the rendered view doesn't end with an
+ # empty line — keeps line counts predictable.
+ while lines and lines[-1].kind == "blank":
+ lines.pop()
+
+ return LineView(
+ lines=lines,
+ entry_by_id=entry_by_id,
+ entries_in_order=entries_in_order,
+ )
+
+
+# ── Apply edits ─────────────────────────────────────────────────────────
+
+
+def apply_edits(doc: Document, edits: Iterable[Edit]) -> tuple[Document, EditReport]:
+ """Apply a batch of edits, in reverse line order, to a fresh copy.
+
+ Returns ``(new_doc, report)``. ``new_doc`` is always returned; if
+ any edit was rejected, those are captured in ``report.rejected`` and
+ the rest are still applied. The caller decides what to do with a
+ partial-success batch (audit/dedup just write the partial result).
+
+ Reverse order avoids line-number drift: removing line 5 does not
+ affect the meaning of "line 3" since 3 < 5 and we process 5 first.
+ """
+ view = render_view(doc)
+ edit_list = _sort_reverse(list(edits))
+ report = EditReport()
+
+ # Work on a deep-ish copy: the entry list per section is fresh, but
+ # Entry instances themselves are reused (and possibly mutated in
+ # place by replace).
+ new_doc = Document(
+ title=doc.title,
+ sections=[(name, list(entries)) for name, entries in doc.sections],
+ )
+
+ for edit in edit_list:
+ try:
+ detail = _apply_one(edit, new_doc, view)
+ report.applied.append(EditResult(op=edit, status="applied", detail=detail))
+ except _Reject as exc:
+ logger.warning("line-edit rejected: %s — %s", _short(edit), exc)
+ report.rejected.append(
+ EditResult(op=edit, status="rejected", detail=str(exc))
+ )
+
+ _drop_empty_sections(new_doc)
+ return new_doc, report
+
+
+class _Reject(Exception):
+ """Internal sentinel — signals one edit is unsafe; siblings still apply."""
+
+
+def _apply_one(edit: Edit, doc: Document, view: LineView) -> str:
+ if isinstance(edit, ReplaceLineOp):
+ return _apply_replace(edit, doc, view)
+ if isinstance(edit, DeleteLinesOp):
+ return _apply_delete(edit, doc, view)
+ if isinstance(edit, InsertAfterOp):
+ return _apply_insert(edit, doc, view)
+ raise _Reject(f"unknown edit type {type(edit).__name__}")
+
+
+def _apply_replace(edit: ReplaceLineOp, doc: Document, view: LineView) -> str:
+ line = view.line(edit.line)
+ if line is None:
+ raise _Reject(f"line {edit.line} out of range")
+ if line.kind != "bullet" or not line.entry_id:
+ raise _Reject(f"line {edit.line} is not an editable entry")
+ if not edit.new_text.strip():
+ raise _Reject("new_text empty")
+ if not edit.refs:
+ raise _Reject("replace requires non-empty refs")
+
+ entry = _entry_in_doc(doc, line.entry_id)
+ if entry is None:
+ raise _Reject(f"entry {line.entry_id} not found in current doc")
+ entry.text = edit.new_text.strip()
+ entry.refs = list(edit.refs)
+ return f"replace {entry.id}"
+
+
+def _apply_delete(edit: DeleteLinesOp, doc: Document, view: LineView) -> str:
+ if edit.line_end < edit.line_start:
+ raise _Reject(f"line_end {edit.line_end} < line_start {edit.line_start}")
+ ids_to_drop: set[str] = set()
+ for n in range(edit.line_start, edit.line_end + 1):
+ line = view.line(n)
+ if line is None or line.kind != "bullet" or not line.entry_id:
+ continue # section/blank lines are removed only as a side-effect of empties
+ ids_to_drop.add(line.entry_id)
+ if not ids_to_drop:
+ raise _Reject("range covers no entries")
+ for _name, entries in doc.sections:
+ entries[:] = [e for e in entries if e.id not in ids_to_drop]
+ return f"deleted {len(ids_to_drop)} entries"
+
+
+def _apply_insert(edit: InsertAfterOp, doc: Document, view: LineView) -> str:
+ if not edit.text.strip():
+ raise _Reject("insert text empty")
+ if not edit.refs:
+ raise _Reject("insert requires non-empty refs")
+
+ section = edit.section
+ if section is None:
+ if edit.after_line < 1 or edit.after_line > len(view.lines):
+ raise _Reject(
+ "after_line out of range; for top-of-doc insert provide `section` explicitly"
+ )
+ anchor = view.line(edit.after_line)
+ section = anchor.section if anchor and anchor.section else None
+ if section is None and anchor and anchor.kind == "section":
+ section = anchor.text.lstrip("# ").strip()
+ if section is None:
+ raise _Reject("no section context for insert; supply `section`")
+
+ entry = Entry(
+ id=new_entry_id(),
+ section=section,
+ text=edit.text.strip(),
+ refs=list(edit.refs),
+ )
+ target = _section_entries(doc, section)
+ # When inserting after a bullet inside an existing section, honor
+ # the local position; otherwise append at end.
+ anchor = view.line(edit.after_line) if 1 <= edit.after_line <= len(view.lines) else None
+ if anchor and anchor.kind == "bullet" and anchor.section == section and anchor.entry_id:
+ for idx, existing in enumerate(target):
+ if existing.id == anchor.entry_id:
+ target.insert(idx + 1, entry)
+ break
+ else:
+ target.append(entry)
+ else:
+ target.append(entry)
+ return f"inserted {entry.id} into {section!r}"
+
+
+# ── Parse edits payload ─────────────────────────────────────────────────
+
+
+_REF_WRAPPER_CHARS = "`[](){}<>^ \t\n\r"
+_ENTRY_ID_REF_RE = re.compile(r"^m_[0-9A-HJKMNP-TV-Z]{26}$")
+
+
+def _clean_refs(raw_refs: object, *, layer: str | None) -> list[str]:
+ """Strip wrappers + drop garbage refs from one ``refs`` array.
+
+ Two cleanups, in order:
+
+ 1. **Wrapper strip**. The audit / dedup line-numbered view shows each
+ bullet as ``- text [^m_xxx]``. LLMs sometimes copy the marker
+ (``^m_xxx``) wholesale into the new refs array — caret and all.
+ Strip ``` ` [ ] ( ) { } < > ^ ``` plus whitespace from both sides.
+
+ 2. **Layer-shape filter**. After stripping, an L2 doc whose refs
+ still look like ``m_<ULID>`` (an entry id from the line view) is
+ almost certainly hallucinated — real L2 refs are ``surface:id``.
+ Drop them. L3 ref shape *is* ``m_<ULID>`` so the filter is a
+ no-op there.
+ """
+ if not isinstance(raw_refs, list):
+ return []
+ out: list[str] = []
+ for r in raw_refs:
+ if not r:
+ continue
+ s = str(r).strip(_REF_WRAPPER_CHARS).strip()
+ if not s:
+ continue
+ if layer == "L2" and _ENTRY_ID_REF_RE.match(s):
+ continue
+ out.append(s)
+ return out
+
+
+def parse_edits_payload(raw: str, *, layer: str | None = None) -> list[Edit]:
+ """Tolerant JSON parse → list[Edit].
+
+ Accepts ``{"edits": [...]}`` or a top-level ``[...]``. Each entry's
+ ``op`` field discriminates the type. Unknown ops are dropped.
+
+ ``layer`` (``"L2"`` / ``"L3"``) controls ref-shape filtering — see
+ :func:`_clean_refs`. Omit it (or pass ``None``) when the caller
+ can't or shouldn't filter by layer; refs are still stripped of
+ wrapper characters.
+ """
+ snippet = _extract_json(raw)
+ if snippet is None:
+ return []
+ try:
+ data = json.loads(snippet)
+ except json.JSONDecodeError:
+ logger.warning("line-edit parse: malformed JSON")
+ return []
+ items = data.get("edits") if isinstance(data, dict) else data
+ if not isinstance(items, list):
+ return []
+
+ edits: list[Edit] = []
+ for raw_op in items:
+ if not isinstance(raw_op, dict):
+ continue
+ kind = raw_op.get("op")
+ try:
+ if kind == "replace":
+ edits.append(
+ ReplaceLineOp(
+ line=int(raw_op.get("line", 0)),
+ new_text=str(raw_op.get("new_text", "")).strip(),
+ refs=_clean_refs(raw_op.get("refs", []), layer=layer),
+ reason=str(raw_op.get("reason", "")).strip(),
+ )
+ )
+ elif kind == "delete":
+ edits.append(
+ DeleteLinesOp(
+ line_start=int(raw_op.get("line_start", raw_op.get("line", 0))),
+ line_end=int(raw_op.get("line_end", raw_op.get("line", 0))),
+ reason=str(raw_op.get("reason", "")).strip(),
+ )
+ )
+ elif kind == "insert":
+ section = raw_op.get("section")
+ edits.append(
+ InsertAfterOp(
+ after_line=int(raw_op.get("after_line", 0)),
+ text=str(raw_op.get("text", "")).strip(),
+ refs=_clean_refs(raw_op.get("refs", []), layer=layer),
+ section=str(section).strip() if section else None,
+ reason=str(raw_op.get("reason", "")).strip(),
+ )
+ )
+ except (TypeError, ValueError):
+ continue
+ return edits
+
+
+# ── Helpers ─────────────────────────────────────────────────────────────
+
+
+def _sort_reverse(edits: list[Edit]) -> list[Edit]:
+ def key(e: Edit) -> tuple[int, int]:
+ if isinstance(e, ReplaceLineOp):
+ return (e.line, 0)
+ if isinstance(e, DeleteLinesOp):
+ return (e.line_end, 1) # delete sorts before insert at same line
+ if isinstance(e, InsertAfterOp):
+ return (e.after_line, 2)
+ return (0, 9)
+
+ return sorted(edits, key=key, reverse=True)
+
+
+def _entry_in_doc(doc: Document, entry_id: str) -> Entry | None:
+ if not is_entry_id(entry_id):
+ return None
+ for _section, entries in doc.sections:
+ for entry in entries:
+ if entry.id == entry_id:
+ return entry
+ return None
+
+
+def _section_entries(doc: Document, name: str) -> list[Entry]:
+ for section, entries in doc.sections:
+ if section == name:
+ return entries
+ entries: list[Entry] = []
+ doc.sections.append((name, entries))
+ return entries
+
+
+def _drop_empty_sections(doc: Document) -> None:
+ doc.sections[:] = [(name, entries) for name, entries in doc.sections if entries]
+
+
+def _short(edit: Edit) -> str:
+ if isinstance(edit, ReplaceLineOp):
+ return f"replace L{edit.line}"
+ if isinstance(edit, DeleteLinesOp):
+ return f"delete L{edit.line_start}-{edit.line_end}"
+ if isinstance(edit, InsertAfterOp):
+ return f"insert@L{edit.after_line}"
+ return repr(edit)
+
+
+_FENCE_RE = re.compile(r"^```[a-zA-Z]*\s*|\s*```$")
+
+
+def _extract_json(raw: str) -> str | None:
+ text = _FENCE_RE.sub("", raw.strip())
+ # Find the outermost {...} or [...].
+ obj_start = text.find("{")
+ arr_start = text.find("[")
+ if obj_start == -1 and arr_start == -1:
+ return None
+ if obj_start == -1:
+ start = arr_start
+ elif arr_start == -1:
+ start = obj_start
+ else:
+ start = min(obj_start, arr_start)
+ end_obj = text.rfind("}")
+ end_arr = text.rfind("]")
+ end = max(end_obj, end_arr)
+ if end <= start:
+ return None
+ return text[start : end + 1]
+
+
+__all__ = [
+ "DeleteLinesOp",
+ "Edit",
+ "EditReport",
+ "EditResult",
+ "InsertAfterOp",
+ "Line",
+ "LineView",
+ "ReplaceLineOp",
+ "apply_edits",
+ "parse_edits_payload",
+ "render_view",
+]
diff --git a/deeptutor/services/memory/consolidator/meta.py b/deeptutor/services/memory/consolidator/meta.py
new file mode 100644
index 000000000..e673df48d
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/meta.py
@@ -0,0 +1,198 @@
+"""Per-doc consolidator metadata (``*.meta.json`` files).
+
+For each L2/L3 markdown doc we keep a sidecar JSON capturing the set of
+upstream ids "seen" at the last update. ``run_update`` uses set diff
+against the live state to compute "what's new since last update" — a
+purely id-based diff is robust against mtime / time-zone / replays.
+
+Files
+-----
+* ``memory/L2/<surface>.meta.json``::
+
+ {
+ "version": 1,
+ "last_update_at": "<iso-utc>",
+ "seen_entity_refs": ["chat:01HZK4...", ...]
+ }
+
+* ``memory/L3/<slot>.meta.json``::
+
+ {
+ "version": 1,
+ "last_update_at": "<iso-utc>",
+ "seen_l2_entry_ids": {
+ "chat": ["m_xxx", ...],
+ "notebook": ["m_yyy"],
+ ...
+ }
+ }
+
+Atomic writes via temp + rename. Missing files behave as "first run".
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import tempfile
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+
+from deeptutor.services.memory import paths
+from deeptutor.services.memory.paths import L3Slot, Surface
+
+logger = logging.getLogger(__name__)
+
+_META_VERSION = 1
+
+
+# ── L2 meta ─────────────────────────────────────────────────────────────
+
+
+@dataclass
+class L2Meta:
+ last_update_at: str | None = None
+ seen_entity_refs: set[str] = field(default_factory=set)
+
+
+def l2_meta_path(surface: Surface) -> Path:
+ return paths.l2_dir() / f"{surface}.meta.json"
+
+
+def load_l2_meta(surface: Surface) -> L2Meta:
+ return _load_meta_l2(l2_meta_path(surface))
+
+
+def save_l2_meta(surface: Surface, *, seen_entity_refs: set[str]) -> L2Meta:
+ path = l2_meta_path(surface)
+ meta = L2Meta(
+ last_update_at=_now_iso(),
+ seen_entity_refs=set(seen_entity_refs),
+ )
+ _atomic_write_json(
+ path,
+ {
+ "version": _META_VERSION,
+ "last_update_at": meta.last_update_at,
+ "seen_entity_refs": sorted(meta.seen_entity_refs),
+ },
+ )
+ return meta
+
+
+# ── L3 meta ─────────────────────────────────────────────────────────────
+
+
+@dataclass
+class L3Meta:
+ last_update_at: str | None = None
+ seen_l2_entry_ids: dict[str, set[str]] = field(default_factory=dict)
+
+
+def l3_meta_path(slot: L3Slot) -> Path:
+ return paths.l3_dir() / f"{slot}.meta.json"
+
+
+def load_l3_meta(slot: L3Slot) -> L3Meta:
+ return _load_meta_l3(l3_meta_path(slot))
+
+
+def save_l3_meta(
+ slot: L3Slot,
+ *,
+ seen_l2_entry_ids: dict[str, set[str]],
+) -> L3Meta:
+ path = l3_meta_path(slot)
+ meta = L3Meta(
+ last_update_at=_now_iso(),
+ seen_l2_entry_ids={
+ surface: set(ids) for surface, ids in seen_l2_entry_ids.items()
+ },
+ )
+ _atomic_write_json(
+ path,
+ {
+ "version": _META_VERSION,
+ "last_update_at": meta.last_update_at,
+ "seen_l2_entry_ids": {
+ surface: sorted(ids)
+ for surface, ids in meta.seen_l2_entry_ids.items()
+ },
+ },
+ )
+ return meta
+
+
+# ── Internals ───────────────────────────────────────────────────────────
+
+
+def _load_meta_l2(path: Path) -> L2Meta:
+ data = _read_json(path)
+ if not data:
+ return L2Meta()
+ refs = data.get("seen_entity_refs") or []
+ return L2Meta(
+ last_update_at=data.get("last_update_at"),
+ seen_entity_refs=set(refs) if isinstance(refs, list) else set(),
+ )
+
+
+def _load_meta_l3(path: Path) -> L3Meta:
+ data = _read_json(path)
+ if not data:
+ return L3Meta()
+ raw = data.get("seen_l2_entry_ids") or {}
+ if not isinstance(raw, dict):
+ raw = {}
+ return L3Meta(
+ last_update_at=data.get("last_update_at"),
+ seen_l2_entry_ids={
+ surface: set(ids) if isinstance(ids, list) else set()
+ for surface, ids in raw.items()
+ },
+ )
+
+
+def _read_json(path: Path) -> dict | None:
+ if not path.exists():
+ return None
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ logger.warning("memory meta: failed to read %s: %s", path, exc)
+ return None
+
+
+def _atomic_write_json(path: Path, payload: dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp_str = tempfile.mkstemp(prefix=path.name + ".", dir=str(path.parent))
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ json.dump(payload, fh, ensure_ascii=False, indent=2, sort_keys=False)
+ fh.flush()
+ os.fsync(fh.fileno())
+ os.replace(tmp_str, path)
+ finally:
+ if os.path.exists(tmp_str):
+ try:
+ os.remove(tmp_str)
+ except OSError:
+ pass
+
+
+def _now_iso() -> str:
+ return datetime.now(tz=timezone.utc).isoformat()
+
+
+__all__ = [
+ "L2Meta",
+ "L3Meta",
+ "l2_meta_path",
+ "l3_meta_path",
+ "load_l2_meta",
+ "load_l3_meta",
+ "save_l2_meta",
+ "save_l3_meta",
+]
diff --git a/deeptutor/services/memory/consolidator/modes/__init__.py b/deeptutor/services/memory/consolidator/modes/__init__.py
new file mode 100644
index 000000000..444c473f3
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/modes/__init__.py
@@ -0,0 +1,31 @@
+"""Four user-visible consolidation modes.
+
+* :func:`run_update` — chunk-based incremental fact extraction.
+* :func:`run_audit` — chunk-based line-level edits against raw evidence.
+* :func:`run_dedup` — iterative line-level dedup over the full doc.
+* :func:`run_merge` — no-LLM footnote consolidation (collapse duplicate refs).
+
+Plus thin shims (:func:`consolidate_l2`, :func:`consolidate_l3`) kept
+for :mod:`deeptutor.services.memory.store` so the public API surface
+stays stable while the implementation switches under the hood.
+"""
+
+from __future__ import annotations
+
+from deeptutor.services.memory.consolidator.modes.audit import run_audit
+from deeptutor.services.memory.consolidator.modes.dedup import run_dedup
+from deeptutor.services.memory.consolidator.modes.merge import run_merge
+from deeptutor.services.memory.consolidator.modes.update import run_update
+from deeptutor.services.memory.consolidator.modes._shims import (
+ consolidate_l2,
+ consolidate_l3,
+)
+
+__all__ = [
+ "consolidate_l2",
+ "consolidate_l3",
+ "run_audit",
+ "run_dedup",
+ "run_merge",
+ "run_update",
+]
diff --git a/deeptutor/services/memory/consolidator/modes/_runtime.py b/deeptutor/services/memory/consolidator/modes/_runtime.py
new file mode 100644
index 000000000..dba368579
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/modes/_runtime.py
@@ -0,0 +1,337 @@
+"""Shared runtime helpers used by every mode.
+
+These keep the per-mode files focused on algorithm, not plumbing:
+
+* Prompt loading (en/zh, cached).
+* SSE event emission (``_emit``).
+* Document load + atomic write.
+* LLM call wrapper with retries + a one-line warning on failure.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime, timezone
+import logging
+import os
+from pathlib import Path
+import tempfile
+from typing import Any, Awaitable, Callable
+
+import yaml
+
+from deeptutor.services.llm import clean_thinking_tags
+from deeptutor.services.llm import complete as llm_complete
+from deeptutor.services.llm import stream as llm_stream
+from deeptutor.services.memory.document import Document, parse, serialize
+
+logger = logging.getLogger(__name__)
+
+OnEvent = Callable[[dict[str, Any]], Awaitable[None]]
+
+_PROMPTS_DIR = Path(__file__).parent.parent / "prompts"
+_PROMPT_CACHE: dict[tuple[str, str], dict[str, str]] = {}
+
+
+_META_CACHE: dict[str, dict[str, Any]] = {}
+
+
+def load_prompt(name: str, language: str) -> dict[str, str]:
+ """Load and cache one prompt YAML by name + language (en/zh)."""
+ lang = _lang_code(language)
+ key = (lang, name)
+ cached = _PROMPT_CACHE.get(key)
+ if cached is not None:
+ return cached
+ path = _PROMPTS_DIR / lang / f"{name}.yaml"
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
+ if not isinstance(data, dict) or "system" not in data or "user" not in data:
+ raise RuntimeError(f"prompt {path} missing 'system'/'user' keys")
+ _PROMPT_CACHE[key] = {"system": data["system"], "user": data["user"]}
+ return _PROMPT_CACHE[key]
+
+
+def load_focus_meta(language: str) -> dict[str, Any]:
+ """Load the per-surface / per-slot focus + sections map for a language."""
+ lang = _lang_code(language)
+ cached = _META_CACHE.get(lang)
+ if cached is not None:
+ return cached
+ path = _PROMPTS_DIR / lang / "_meta.yaml"
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
+ _META_CACHE[lang] = data
+ return data
+
+
+def surface_focus(language: str, surface: str) -> tuple[str, list[str]]:
+ meta = load_focus_meta(language).get("surfaces", {}).get(surface) or {}
+ return meta.get("focus", ""), list(meta.get("sections", []) or [])
+
+
+def slot_focus(language: str, slot: str) -> tuple[str, list[str]]:
+ meta = load_focus_meta(language).get("slots", {}).get(slot) or {}
+ return meta.get("focus", ""), list(meta.get("sections", []) or [])
+
+
+def _lang_code(language: str) -> str:
+ return "zh" if (language or "").lower().startswith("zh") else "en"
+
+
+async def emit(on_event: OnEvent | None, event: dict[str, Any]) -> None:
+ if on_event is None:
+ return
+ try:
+ await on_event(event)
+ except Exception:
+ logger.debug("consolidator: on_event consumer raised", exc_info=True)
+
+
+async def call_llm(
+ *,
+ system_prompt: str,
+ user_prompt: str,
+ temperature: float = 0.2,
+ max_tokens: int = 1500,
+ on_event: OnEvent | None = None,
+ turn: int | None = None,
+ chunk_index: int | None = None,
+ label: str | None = None,
+) -> str:
+ """Single LLM call. Returns the raw text body; "" on failure.
+
+ The model/provider is resolved from the *active* LLM config — the
+ mode is expected to have installed a scoped config via
+ :func:`activate_llm_selection` if the user picked a non-default
+ model. Emits ``llm_io_start`` / ``llm_io_end`` events for the
+ workbench trace.
+ """
+ from deeptutor.services.llm import get_llm_config
+
+ model_label = get_llm_config().model or None
+ if on_event is not None:
+ await on_event(
+ {
+ "stage": "llm_io_start",
+ "turn": turn,
+ "chunk_index": chunk_index,
+ "label": label,
+ "system_prompt": system_prompt,
+ "user_prompt": user_prompt,
+ "model": model_label,
+ }
+ )
+ response_parts: list[str] = []
+ in_think_block = False
+ try:
+ async for delta in llm_stream(
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ stream_coalesce_chars=64,
+ stream_coalesce_seconds=0.05,
+ ):
+ if not delta:
+ continue
+ response_parts.append(delta)
+ visible_delta, in_think_block = _strip_thinking_delta(delta, in_think_block)
+ if on_event is not None:
+ if visible_delta:
+ await on_event(
+ {
+ "stage": "llm_io_delta",
+ "turn": turn,
+ "chunk_index": chunk_index,
+ "label": label,
+ "delta": visible_delta,
+ "model": model_label,
+ }
+ )
+ response = clean_thinking_tags("".join(response_parts))
+ if on_event is not None:
+ await on_event(
+ {
+ "stage": "llm_io_end",
+ "turn": turn,
+ "chunk_index": chunk_index,
+ "label": label,
+ "response": response,
+ "error": None,
+ "model": model_label,
+ }
+ )
+ return response
+ except Exception as exc: # noqa: BLE001
+ # Some providers still do not implement streaming. Fall back to the
+ # non-streaming path so memory jobs remain usable.
+ logger.warning("consolidator streaming LLM call failed; falling back: %s", exc)
+ try:
+ response = await llm_complete(
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ )
+ response = clean_thinking_tags(response)
+ if on_event is not None:
+ await on_event(
+ {
+ "stage": "llm_io_delta",
+ "turn": turn,
+ "chunk_index": chunk_index,
+ "label": label,
+ "delta": response,
+ "model": model_label,
+ }
+ )
+ await on_event(
+ {
+ "stage": "llm_io_end",
+ "turn": turn,
+ "chunk_index": chunk_index,
+ "label": label,
+ "response": response,
+ "error": None,
+ "model": model_label,
+ }
+ )
+ return response
+ except Exception as fallback_exc: # noqa: BLE001
+ logger.warning("consolidator LLM call failed: %s", fallback_exc)
+ if on_event is not None:
+ await on_event(
+ {
+ "stage": "llm_io_end",
+ "turn": turn,
+ "chunk_index": chunk_index,
+ "label": label,
+ "response": "",
+ "error": str(fallback_exc),
+ "model": model_label,
+ }
+ )
+ return ""
+
+
+def load_doc(path: Path, *, default_title: str) -> Document:
+ if not path.exists():
+ return Document(title=default_title)
+ return parse(path.read_text(encoding="utf-8"))
+
+
+async def write_doc_atomic(path: Path, doc: Document) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ text = serialize(doc)
+ await asyncio.to_thread(_atomic_write, path, text)
+
+
+async def write_doc_checkpoint(
+ path: Path,
+ doc: Document,
+ *,
+ layer: str,
+ key: str,
+ on_event: OnEvent | None = None,
+ turn: int | None = None,
+ label: str | None = None,
+ action: str = "write",
+) -> int:
+ """Write a doc now and register one run-scoped undo checkpoint."""
+ existed = path.exists()
+ previous = path.read_text(encoding="utf-8") if existed else ""
+ await write_doc_atomic(path, doc)
+ from deeptutor.services.memory.consolidator.runs import push_undo_checkpoint
+
+ undo_depth = push_undo_checkpoint(
+ layer=layer,
+ key=key,
+ path=path,
+ existed=existed,
+ previous_content=previous,
+ action=action,
+ turn=turn,
+ label=label,
+ )
+ await emit(
+ on_event,
+ {
+ "stage": "doc_updated",
+ "layer": layer,
+ "key": key,
+ "turn": turn,
+ "label": label,
+ "action": action,
+ "undo_depth": undo_depth,
+ },
+ )
+ return undo_depth
+
+
+def _atomic_write(path: Path, content: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp_str = tempfile.mkstemp(prefix=path.name + ".", dir=str(path.parent))
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ fh.write(content)
+ fh.flush()
+ os.fsync(fh.fileno())
+ os.replace(tmp_str, path)
+ finally:
+ if os.path.exists(tmp_str):
+ try:
+ os.remove(tmp_str)
+ except OSError:
+ pass
+
+
+def _strip_thinking_delta(delta: str, in_block: bool) -> tuple[str, bool]:
+ """Remove streamed <think> blocks before they reach the workbench UI."""
+ out: list[str] = []
+ text = delta
+ while text:
+ lower = text.lower()
+ if in_block:
+ close_at = lower.find("</think>")
+ close_len = len("</think>")
+ alt_close = lower.find("</thinking>")
+ if alt_close != -1 and (close_at == -1 or alt_close < close_at):
+ close_at = alt_close
+ close_len = len("</thinking>")
+ if close_at == -1:
+ return "".join(out), True
+ text = text[close_at + close_len :]
+ in_block = False
+ continue
+
+ open_at = lower.find("<think>")
+ open_len = len("<think>")
+ alt_open = lower.find("<thinking>")
+ if alt_open != -1 and (open_at == -1 or alt_open < open_at):
+ open_at = alt_open
+ open_len = len("<thinking>")
+ if open_at == -1:
+ out.append(text)
+ break
+ out.append(text[:open_at])
+ text = text[open_at + open_len :]
+ in_block = True
+ return "".join(out), in_block
+
+
+def today_iso() -> str:
+ return datetime.now(tz=timezone.utc).date().isoformat()
+
+
+__all__ = [
+ "OnEvent",
+ "call_llm",
+ "emit",
+ "load_doc",
+ "load_focus_meta",
+ "load_prompt",
+ "slot_focus",
+ "surface_focus",
+ "today_iso",
+ "write_doc_atomic",
+ "write_doc_checkpoint",
+]
diff --git a/deeptutor/services/memory/consolidator/modes/_shims.py b/deeptutor/services/memory/consolidator/modes/_shims.py
new file mode 100644
index 000000000..136717f2a
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/modes/_shims.py
@@ -0,0 +1,129 @@
+"""Legacy public-API shims for :mod:`deeptutor.services.memory.store`.
+
+The pre-redesign module exposed ``consolidate_l2`` and ``consolidate_l3``
+returning a :class:`ConsolidateResult`. The store / API router still
+call these names. We keep them as thin wrappers around :func:`run_update`
+so the surface that the router and the test fixtures import doesn't
+change while the implementation switches to chunk-based update + dedup.
+
+``apply_ops`` semantics
+-----------------------
+The pre-redesign ``apply_ops=False`` was a "preview the ops, do not
+write" toggle for the workbench. The new chunk-based update writes
+incrementally and there's no clean way to roll it back atomically. So:
+
+* ``apply_ops=True`` (default) → :func:`run_update` runs end-to-end.
+* ``apply_ops=False`` → we still run the update so the workbench can
+ observe what would be added via the SSE event stream, but we capture
+ the new entry ids and immediately delete them post-write. This keeps
+ the preview semantic functionally close to the old behaviour without
+ introducing a parallel preview pipeline. Auto-dedup is suppressed
+ in preview mode to avoid touching pre-existing entries.
+
+Callers that want a true preview (no disk writes at all) should move
+to the new ``run_update`` API directly with a custom on_event consumer.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Awaitable, Callable
+
+from deeptutor.services.memory.consolidator.modes.update import (
+ UpdateResult,
+ run_update,
+)
+from deeptutor.services.memory.document import parse, serialize
+from deeptutor.services.memory.ops import ApplyReport, Op, OpResult
+from deeptutor.services.memory.paths import L3Slot, Surface
+from deeptutor.services.memory import paths
+
+OnEvent = Callable[[dict[str, Any]], Awaitable[None]]
+
+
+@dataclass
+class ConsolidateResult:
+ report: ApplyReport
+ backlog_count: int
+ proposed_ops: list[Op] = field(default_factory=list)
+
+
+async def consolidate_l2(
+ surface: Surface,
+ *,
+ language: str = "en",
+ user_label: str = "anonymous",
+ on_event: OnEvent | None = None,
+ apply_ops: bool = True,
+) -> ConsolidateResult:
+ result = await run_update(
+ "L2",
+ surface,
+ language=language,
+ user_label=user_label,
+ on_event=on_event,
+ )
+ if not apply_ops:
+ _rollback_new_entries("L2", surface, result.new_entry_ids)
+ return _to_consolidate_result(result)
+
+
+async def consolidate_l3(
+ slot: L3Slot,
+ *,
+ language: str = "en",
+ user_label: str = "anonymous",
+ on_event: OnEvent | None = None,
+ apply_ops: bool = True,
+) -> ConsolidateResult:
+ if slot == "preferences":
+ raise ValueError("preferences.md is not auto-consolidated")
+ result = await run_update(
+ "L3",
+ slot,
+ language=language,
+ user_label=user_label,
+ on_event=on_event,
+ )
+ if not apply_ops:
+ _rollback_new_entries("L3", slot, result.new_entry_ids)
+ return _to_consolidate_result(result)
+
+
+def _to_consolidate_result(result: UpdateResult) -> ConsolidateResult:
+ reason = (
+ "no new input"
+ if result.no_new_input
+ else f"applied via chunk-update ({result.facts_added} added)"
+ )
+ return ConsolidateResult(
+ report=ApplyReport(
+ accepted=True,
+ reason=reason,
+ results=[], # the new pipeline does not emit per-op OpResult objects
+ ),
+ backlog_count=result.chunks_processed,
+ proposed_ops=[], # the chunk-based mode writes directly; preview is via SSE
+ )
+
+
+def _rollback_new_entries(layer: str, key: str, ids: list[str]) -> None:
+ """Remove entries by id (used by ``apply_ops=False`` preview mode).
+
+ This is best-effort: if the doc was edited externally between the
+ update and rollback, ids not found are silently skipped.
+ """
+ if not ids:
+ return
+ path = paths.l2_file(key) if layer == "L2" else paths.l3_file(key) # type: ignore[arg-type]
+ if not path.exists():
+ return
+ doc = parse(path.read_text(encoding="utf-8"))
+ drop = set(ids)
+ for _name, entries in doc.sections:
+ entries[:] = [e for e in entries if e.id not in drop]
+ doc.sections[:] = [(n, e) for n, e in doc.sections if e]
+ path.write_text(serialize(doc), encoding="utf-8")
+
+
+__all__ = ["ConsolidateResult", "consolidate_l2", "consolidate_l3"]
diff --git a/deeptutor/services/memory/consolidator/modes/audit.py b/deeptutor/services/memory/consolidator/modes/audit.py
new file mode 100644
index 000000000..f8f90b213
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/modes/audit.py
@@ -0,0 +1,482 @@
+"""Audit mode — line-level edits checked against raw evidence.
+
+Algorithm
+---------
+1. Render the target md as a line-numbered, footnote-stripped view
+ (:func:`line_doc.render_view`).
+2. Chunk the rendered view into ≤ budget pieces; each chunk is a
+ contiguous slice of lines whose bullet entries get **annotated with
+ their full source content** (no truncation).
+3. Per chunk: LLM call → parse edits → apply against the in-memory doc
+ in reverse line order. Across chunks, edits stack — but because we
+ slice on whole-line boundaries and apply per-chunk before the next
+ chunk runs, the line numbers the next chunk sees are still the ones
+ the LLM was given.
+4. Atomic flush.
+
+The chunker is deliberately char-based (same as update) so chunk size
+behaves predictably alongside the annotation block (which can be much
+larger than the bare md). The annotated block fed to the LLM is what
+gets counted against the budget.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import logging
+
+from deeptutor.services.memory import paths
+from deeptutor.services.memory import snapshot as snap
+from deeptutor.services.memory.consolidator.chunker import (
+ chunk_with_boundary,
+)
+from deeptutor.services.memory.consolidator.line_doc import (
+ LineView,
+ apply_edits,
+ parse_edits_payload,
+ render_view,
+)
+from deeptutor.services.memory.consolidator.modes._runtime import (
+ OnEvent,
+ call_llm,
+ emit,
+ load_doc,
+ load_prompt,
+ slot_focus,
+ surface_focus,
+ today_iso,
+ write_doc_checkpoint,
+)
+from deeptutor.services.memory.consolidator.references import (
+ annotate_l2_line_with_evidence,
+ annotate_l3_line_with_evidence,
+)
+from deeptutor.services.memory.document import Document, Entry
+from deeptutor.services.memory.paths import L3Slot, Surface
+from deeptutor.services.memory.settings import load_memory_settings
+from deeptutor.services.memory.snapshot.entity import Entity
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class AuditResult:
+ layer: str
+ key: str
+ chunks_processed: int
+ edits_applied: int = 0
+ edits_rejected: int = 0
+ no_doc: bool = False
+
+
+# ── Public entry ────────────────────────────────────────────────────────
+
+
+async def run_audit(
+ layer: str,
+ key: str,
+ *,
+ language: str = "en",
+ user_label: str = "anonymous",
+ budget: int | None = None,
+ llm_selection: dict | None = None,
+ on_event: OnEvent | None = None,
+) -> AuditResult:
+ from deeptutor.services.model_selection.runtime import (
+ activate_llm_selection,
+ reset_llm_selection,
+ )
+
+ settings = load_memory_settings()
+ token = None
+ if llm_selection:
+ try:
+ _config, token = activate_llm_selection(llm_selection)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("memory audit: ignoring unresolvable llm_selection %s: %s", llm_selection, exc)
+ token = None
+ try:
+ if layer == "L2":
+ return await _run_audit_l2(
+ key, # type: ignore[arg-type]
+ language=language,
+ user_label=user_label,
+ budget=budget if budget is not None else settings.audit.l2_budget,
+ llm_selection=llm_selection,
+ on_event=on_event,
+ settings=settings,
+ )
+ if layer == "L3":
+ return await _run_audit_l3(
+ key, # type: ignore[arg-type]
+ language=language,
+ user_label=user_label,
+ budget=budget if budget is not None else settings.audit.l3_budget,
+ llm_selection=llm_selection,
+ on_event=on_event,
+ settings=settings,
+ )
+ raise ValueError(f"unknown layer {layer!r}")
+ finally:
+ reset_llm_selection(token)
+
+
+# ── L2 ──────────────────────────────────────────────────────────────────
+
+
+async def _run_audit_l2(
+ surface: Surface,
+ *,
+ language: str,
+ user_label: str,
+ budget: int,
+ llm_selection: dict | None,
+ on_event: OnEvent | None,
+ settings,
+) -> AuditResult:
+ l2_path = paths.l2_file(surface)
+ if not l2_path.exists():
+ await emit(on_event, {"stage": "done", "no_doc": True})
+ return AuditResult(layer="L2", key=surface, chunks_processed=0, no_doc=True)
+
+ doc = load_doc(l2_path, default_title=f"{surface} memory")
+ entity_lookup = {ent.id: ent for ent in snap.read_snapshot(surface)}
+ prompt = load_prompt("audit_l2", language)
+ focus, _sections = surface_focus(language, surface)
+
+ annotated_text, line_ranges = _build_annotated_l2(doc, surface, entity_lookup)
+ chunks = chunk_with_boundary(
+ annotated_text,
+ budget=budget,
+ overlap_ratio=settings.chunking.overlap_ratio,
+ min_chunk_chars=settings.chunking.min_chunk_chars,
+ max_chunk_chars=settings.chunking.max_chunk_chars,
+ boundary=settings.chunking.boundary,
+ )
+ await emit(
+ on_event,
+ {"stage": "chunked", "chunks": len(chunks), "budget": budget, "chars": len(annotated_text)},
+ )
+
+ edits_applied = 0
+ edits_rejected = 0
+ for chunk in chunks:
+ await emit(
+ on_event,
+ {
+ "stage": "progress",
+ "mode": "audit",
+ "turn": chunk.index + 1,
+ "total": len(chunks),
+ },
+ )
+ system = prompt["system"].format(
+ user_label=user_label,
+ surface=surface,
+ focus=focus,
+ today=today_iso(),
+ )
+ user = prompt["user"].format(surface=surface, chunk=chunk.text)
+ raw = await call_llm(
+ system_prompt=system,
+ user_prompt=user,
+ on_event=on_event,
+ turn=chunk.index + 1,
+ chunk_index=chunk.index,
+ label="audit",
+ )
+ edits = parse_edits_payload(raw, layer="L2")
+ if not edits:
+ await emit(
+ on_event,
+ {"stage": "facts_extracted", "turn": chunk.index + 1, "edits": 0},
+ )
+ continue
+ doc, report = apply_edits(doc, edits)
+ edits_applied += len(report.applied)
+ edits_rejected += len(report.rejected)
+ if report.applied:
+ await write_doc_checkpoint(
+ l2_path,
+ doc,
+ layer="L2",
+ key=surface,
+ on_event=on_event,
+ turn=chunk.index + 1,
+ label="audit",
+ action="apply_edits",
+ )
+ for res in report.applied:
+ await emit(
+ on_event,
+ {
+ "stage": "op_applied",
+ "turn": chunk.index + 1,
+ "op": res.op.op,
+ "detail": res.detail,
+ },
+ )
+ for res in report.rejected:
+ await emit(
+ on_event,
+ {
+ "stage": "op_rejected",
+ "turn": chunk.index + 1,
+ "op": res.op.op,
+ "detail": res.detail,
+ },
+ )
+ # Refresh annotation for the next chunk — line numbers shifted.
+ annotated_text, line_ranges = _build_annotated_l2(doc, surface, entity_lookup)
+
+ await emit(
+ on_event,
+ {
+ "stage": "done",
+ "edits_applied": edits_applied,
+ "edits_rejected": edits_rejected,
+ "chunks_processed": len(chunks),
+ },
+ )
+
+ if load_memory_settings().merge.auto_after_audit:
+ from deeptutor.services.memory.consolidator.modes.merge import run_merge
+
+ await run_merge(
+ "L2",
+ surface,
+ language=language,
+ user_label=user_label,
+ on_event=on_event,
+ )
+
+ return AuditResult(
+ layer="L2",
+ key=surface,
+ chunks_processed=len(chunks),
+ edits_applied=edits_applied,
+ edits_rejected=edits_rejected,
+ )
+
+
+# ── L3 ──────────────────────────────────────────────────────────────────
+
+
+async def _run_audit_l3(
+ slot: L3Slot,
+ *,
+ language: str,
+ user_label: str,
+ budget: int,
+ llm_selection: dict | None,
+ on_event: OnEvent | None,
+ settings,
+) -> AuditResult:
+ if slot == "preferences":
+ raise ValueError("preferences.md is not audited automatically")
+
+ l3_path = paths.l3_file(slot)
+ if not l3_path.exists():
+ await emit(on_event, {"stage": "done", "no_doc": True})
+ return AuditResult(layer="L3", key=slot, chunks_processed=0, no_doc=True)
+
+ doc = load_doc(l3_path, default_title=f"{slot} memory")
+ l2_lookup = _build_l2_entry_lookup()
+ prompt = load_prompt("audit_l3", language)
+ focus, _sections = slot_focus(language, slot)
+
+ annotated_text, _ranges = _build_annotated_l3(doc, l2_lookup)
+ chunks = chunk_with_boundary(
+ annotated_text,
+ budget=budget,
+ overlap_ratio=settings.chunking.overlap_ratio,
+ min_chunk_chars=settings.chunking.min_chunk_chars,
+ max_chunk_chars=settings.chunking.max_chunk_chars,
+ boundary=settings.chunking.boundary,
+ )
+ await emit(
+ on_event,
+ {"stage": "chunked", "chunks": len(chunks), "budget": budget, "chars": len(annotated_text)},
+ )
+
+ edits_applied = 0
+ edits_rejected = 0
+ for chunk in chunks:
+ await emit(
+ on_event,
+ {
+ "stage": "progress",
+ "mode": "audit",
+ "turn": chunk.index + 1,
+ "total": len(chunks),
+ },
+ )
+ system = prompt["system"].format(
+ user_label=user_label,
+ slot=slot,
+ focus=focus,
+ today=today_iso(),
+ )
+ user = prompt["user"].format(slot=slot, chunk=chunk.text)
+ raw = await call_llm(
+ system_prompt=system,
+ user_prompt=user,
+ on_event=on_event,
+ turn=chunk.index + 1,
+ chunk_index=chunk.index,
+ label="audit",
+ )
+ edits = parse_edits_payload(raw, layer="L3")
+ if not edits:
+ await emit(
+ on_event,
+ {"stage": "facts_extracted", "turn": chunk.index + 1, "edits": 0},
+ )
+ continue
+ doc, report = apply_edits(doc, edits)
+ edits_applied += len(report.applied)
+ edits_rejected += len(report.rejected)
+ if report.applied:
+ await write_doc_checkpoint(
+ l3_path,
+ doc,
+ layer="L3",
+ key=slot,
+ on_event=on_event,
+ turn=chunk.index + 1,
+ label="audit",
+ action="apply_edits",
+ )
+ for res in report.applied:
+ await emit(
+ on_event,
+ {
+ "stage": "op_applied",
+ "turn": chunk.index + 1,
+ "op": res.op.op,
+ "detail": res.detail,
+ },
+ )
+ for res in report.rejected:
+ await emit(
+ on_event,
+ {
+ "stage": "op_rejected",
+ "turn": chunk.index + 1,
+ "op": res.op.op,
+ "detail": res.detail,
+ },
+ )
+ annotated_text, _ranges = _build_annotated_l3(doc, l2_lookup)
+
+ await emit(
+ on_event,
+ {
+ "stage": "done",
+ "edits_applied": edits_applied,
+ "edits_rejected": edits_rejected,
+ "chunks_processed": len(chunks),
+ },
+ )
+
+ if load_memory_settings().merge.auto_after_audit:
+ from deeptutor.services.memory.consolidator.modes.merge import run_merge
+
+ await run_merge(
+ "L3",
+ slot,
+ language=language,
+ user_label=user_label,
+ on_event=on_event,
+ )
+
+ return AuditResult(
+ layer="L3",
+ key=slot,
+ chunks_processed=len(chunks),
+ edits_applied=edits_applied,
+ edits_rejected=edits_rejected,
+ )
+
+
+# ── Annotation builders ────────────────────────────────────────────────
+
+
+def _build_annotated_l2(
+ doc: Document, surface: str, entity_lookup: dict[str, Entity]
+) -> tuple[str, list[tuple[int, int]]]:
+ """Render the doc as `line N: ... ` + per-bullet source dumps.
+
+ Returns ``(text, ranges)`` where ``ranges`` is per-bullet
+ ``(start_char, end_char)`` for future fine-grained linking. Not
+ consumed by the LLM directly; reserved for the UI's diff view.
+ """
+ view = render_view(doc)
+ pieces: list[str] = [_render_line_index(view)]
+ ranges: list[tuple[int, int]] = []
+ cursor = len(pieces[0])
+ for line in view.lines:
+ if line.kind != "bullet" or not line.entry_id:
+ continue
+ entry = view.entry_by_id.get(line.entry_id)
+ if entry is None:
+ continue
+ block = annotate_l2_line_with_evidence(
+ line.number, entry, surface=surface, entity_lookup=entity_lookup
+ )
+ # Two newlines separate annotation blocks.
+ prefix = "\n\n"
+ start = cursor + len(prefix)
+ pieces.append(prefix + block)
+ cursor = start + len(block)
+ ranges.append((start, cursor))
+ return "".join(pieces), ranges
+
+
+def _build_annotated_l3(
+ doc: Document, l2_lookup: dict[str, Entry]
+) -> tuple[str, list[tuple[int, int]]]:
+ view = render_view(doc)
+ pieces: list[str] = [_render_line_index(view)]
+ ranges: list[tuple[int, int]] = []
+ cursor = len(pieces[0])
+ for line in view.lines:
+ if line.kind != "bullet" or not line.entry_id:
+ continue
+ entry = view.entry_by_id.get(line.entry_id)
+ if entry is None:
+ continue
+ block = annotate_l3_line_with_evidence(line.number, entry, l2_entry_lookup=l2_lookup)
+ prefix = "\n\n"
+ start = cursor + len(prefix)
+ pieces.append(prefix + block)
+ cursor = start + len(block)
+ ranges.append((start, cursor))
+ return "".join(pieces), ranges
+
+
+def _render_line_index(view: LineView) -> str:
+ width = max(2, len(str(len(view.lines))))
+ head = "# Line-numbered view (LLM-facing):\n"
+ body = "\n".join(f"{line.number:>{width}}: {line.text}" for line in view.lines)
+ return head + body
+
+
+def _build_l2_entry_lookup() -> dict[str, Entry]:
+ from deeptutor.services.memory.document import parse
+
+ out: dict[str, Entry] = {}
+ for surface in paths.SURFACES:
+ path = paths.l2_file(surface)
+ if not path.exists():
+ continue
+ try:
+ doc = parse(path.read_text(encoding="utf-8"))
+ except Exception:
+ continue
+ for entry in doc.all_entries():
+ out[entry.id] = entry
+ return out
+
+
+__all__ = ["AuditResult", "run_audit"]
diff --git a/deeptutor/services/memory/consolidator/modes/dedup.py b/deeptutor/services/memory/consolidator/modes/dedup.py
new file mode 100644
index 000000000..6450f15a2
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/modes/dedup.py
@@ -0,0 +1,223 @@
+"""Dedup mode — iterative line-level merge / delete over the full doc.
+
+Each iteration:
+1. Render the full md as a line-numbered view (footnote-stripped).
+2. One LLM call returns ``{"edits": [...]}`` (replace + delete only —
+ the dedup prompt forbids inserts).
+3. Apply in reverse line order.
+4. If the LLM returned zero edits, **stop early** (saves tokens).
+
+The configured ``iterations`` is the *upper bound*, not a quota.
+
+Dedup is invoked either:
+- automatically after a successful :func:`run_update` (controlled by
+ ``memory.dedup.auto_after_update``), or
+- explicitly via the workbench `[Dedup]` button.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import logging
+
+from deeptutor.services.memory import paths
+from deeptutor.services.memory.consolidator.line_doc import (
+ apply_edits,
+ parse_edits_payload,
+ render_view,
+)
+from deeptutor.services.memory.consolidator.modes._runtime import (
+ OnEvent,
+ call_llm,
+ emit,
+ load_doc,
+ load_prompt,
+ today_iso,
+ write_doc_checkpoint,
+)
+from deeptutor.services.memory.settings import load_memory_settings
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class DedupResult:
+ layer: str
+ key: str
+ iterations_run: int
+ edits_applied: int
+ converged_early: bool
+
+
+async def run_dedup(
+ layer: str,
+ key: str,
+ *,
+ language: str = "en",
+ user_label: str = "anonymous",
+ iterations: int | None = None,
+ llm_selection: dict | None = None,
+ on_event: OnEvent | None = None,
+) -> DedupResult:
+ from deeptutor.services.model_selection.runtime import (
+ activate_llm_selection,
+ reset_llm_selection,
+ )
+
+ settings = load_memory_settings()
+ iters = iterations if iterations is not None else settings.dedup.iterations
+
+ token = None
+ if llm_selection:
+ try:
+ _config, token = activate_llm_selection(llm_selection)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("memory dedup: ignoring unresolvable llm_selection %s: %s", llm_selection, exc)
+ token = None
+ try:
+ return await _run_dedup_inner(
+ layer, key, iters=iters, language=language, user_label=user_label, on_event=on_event
+ )
+ finally:
+ reset_llm_selection(token)
+
+
+async def _run_dedup_inner(
+ layer: str,
+ key: str,
+ *,
+ iters: int,
+ language: str,
+ user_label: str,
+ on_event: OnEvent | None,
+) -> DedupResult:
+
+ path = _path_for(layer, key)
+ if not path.exists():
+ await emit(on_event, {"stage": "done", "no_doc": True, "edits_applied": 0})
+ return DedupResult(layer=layer, key=key, iterations_run=0, edits_applied=0, converged_early=True)
+
+ doc = load_doc(path, default_title=_default_title(layer, key))
+ if not doc.all_entries():
+ await emit(on_event, {"stage": "done", "no_doc": True, "edits_applied": 0})
+ return DedupResult(layer=layer, key=key, iterations_run=0, edits_applied=0, converged_early=True)
+
+ prompt = load_prompt("dedup", language)
+ total_applied = 0
+ converged = False
+
+ for i in range(iters):
+ view = render_view(doc)
+ await emit(
+ on_event,
+ {
+ "stage": "progress",
+ "mode": "dedup",
+ "turn": i + 1,
+ "total": iters,
+ "lines": len(view.lines),
+ },
+ )
+ system = prompt["system"].format(user_label=user_label, today=today_iso())
+ user = prompt["user"].format(
+ doc=_render_with_numbers(view),
+ iteration=i + 1,
+ iterations_total=iters,
+ )
+ raw = await call_llm(
+ system_prompt=system,
+ user_prompt=user,
+ on_event=on_event,
+ turn=i + 1,
+ label="dedup",
+ )
+ edits = parse_edits_payload(raw, layer=layer)
+ if not edits:
+ converged = True
+ await emit(on_event, {"stage": "facts_extracted", "turn": i + 1, "edits": 0})
+ break
+
+ doc, report = apply_edits(doc, edits)
+ total_applied += len(report.applied)
+ if report.applied:
+ await write_doc_checkpoint(
+ path,
+ doc,
+ layer=layer,
+ key=key,
+ on_event=on_event,
+ turn=i + 1,
+ label="dedup",
+ action="apply_edits",
+ )
+ await emit(
+ on_event,
+ {
+ "stage": "op_applied",
+ "turn": i + 1,
+ "applied": len(report.applied),
+ "rejected": len(report.rejected),
+ },
+ )
+ if not report.applied and not report.rejected:
+ converged = True
+ break
+
+ await emit(
+ on_event,
+ {
+ "stage": "done",
+ "edits_applied": total_applied,
+ "iterations_run": min(iters, i + 1 if iters else 0),
+ "converged_early": converged,
+ },
+ )
+
+ if load_memory_settings().merge.auto_after_dedup:
+ from deeptutor.services.memory.consolidator.modes.merge import run_merge
+
+ await run_merge(
+ layer,
+ key,
+ language=language,
+ user_label=user_label,
+ on_event=on_event,
+ )
+
+ return DedupResult(
+ layer=layer,
+ key=key,
+ iterations_run=min(iters, (i + 1) if iters else 0),
+ edits_applied=total_applied,
+ converged_early=converged,
+ )
+
+
+# ── Helpers ─────────────────────────────────────────────────────────────
+
+
+def _path_for(layer: str, key: str):
+ if layer == "L2":
+ return paths.l2_file(key) # type: ignore[arg-type]
+ if layer == "L3":
+ return paths.l3_file(key) # type: ignore[arg-type]
+ raise ValueError(f"unknown layer {layer!r}")
+
+
+def _default_title(layer: str, key: str) -> str:
+ if layer == "L2":
+ return f"{key} memory"
+ return {
+ "recent": "Recent summary",
+ "profile": "User profile",
+ "scope": "Knowledge scope",
+ "preferences": "Preferences",
+ }.get(key, f"{key} memory")
+
+
+def _render_with_numbers(view) -> str:
+ width = max(2, len(str(len(view.lines))))
+ return "\n".join(f"{line.number:>{width}}: {line.text}" for line in view.lines)
+
+
+__all__ = ["DedupResult", "run_dedup"]
diff --git a/deeptutor/services/memory/consolidator/modes/merge.py b/deeptutor/services/memory/consolidator/modes/merge.py
new file mode 100644
index 000000000..535c70421
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/modes/merge.py
@@ -0,0 +1,227 @@
+"""Merge mode — consolidate footnote references on a single doc.
+
+This mode is a *no-LLM* refactor pass. It loads the L2 or L3 document
+and rewrites it through :func:`serialize`, which:
+
+1. Migrates legacy entry-keyed footnotes (``[^m_xxx]: r1, r2``) to the
+ new ref-keyed layout (``[^1]: r1``, ``[^2]: r2``).
+2. Collapses duplicate footnote definitions — N entries citing the same
+ source share one footnote label, so the rendered view stops repeating
+ ``notebook:3a563e6f`` once per entry.
+3. Re-numbers labels in first-appearance order so the output is stable.
+
+For **L3 docs only**, merge ALSO runs a one-shot data migration: every
+legacy ``m_<ULID>`` ref (which used to point at an L2 entry) is resolved
+to its owning surface name, so the doc becomes citeable as
+``L3 → L2 md → L1 raw traces``. After the next update pass nothing is
+left for this migration to do — it's a pure clean-up of pre-pivot docs.
+
+Merge is invoked either:
+
+* automatically after a successful :func:`run_update`, :func:`run_audit`,
+ or :func:`run_dedup` (controlled by the three
+ ``memory.merge.auto_after_*`` settings), or
+* explicitly via the workbench `[Merge]` button → ``mode="merge"``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import logging
+import re
+
+from deeptutor.services.memory import paths
+from deeptutor.services.memory.consolidator.modes._runtime import (
+ OnEvent,
+ emit,
+ load_doc,
+ write_doc_checkpoint,
+)
+from deeptutor.services.memory.ids import is_entry_id
+
+logger = logging.getLogger(__name__)
+
+# Cheap pre-write check: count footnote definitions in the on-disk text to
+# tell the workbench how many rows the merge collapsed. We do this on the
+# *raw* bytes rather than on parsed entries because the parsed model
+# already has consolidated refs (`Entry.refs` carries unique refs per
+# entry), so the meaningful "before" number is what's in the file.
+_FOOTNOTE_DEF_RE = re.compile(r"^\[\^[^\]]+\]:\s*", re.MULTILINE)
+
+
+@dataclass
+class MergeResult:
+ layer: str
+ key: str
+ footnote_rows_before: int
+ footnote_rows_after: int
+ rewrote: bool
+ legacy_l3_refs_migrated: int = 0
+
+
+async def run_merge(
+ layer: str,
+ key: str,
+ *,
+ language: str = "en",
+ user_label: str = "anonymous",
+ on_event: OnEvent | None = None,
+) -> MergeResult:
+ """Re-serialize ``layer/key``; collapse duplicate refs into one footnote each.
+
+ Idempotent: re-running on an already-merged doc rewrites the same
+ bytes and reports ``rewrote=False`` (no checkpoint is pushed).
+ """
+ # NOTE: ``language`` / ``user_label`` are accepted for signature symmetry
+ # with the other modes; merge itself does no localized work and no LLM
+ # calls, so neither is used inside the body.
+ del language, user_label
+
+ path = _path_for(layer, key)
+ if not path.exists():
+ await emit(on_event, {"stage": "done", "no_doc": True, "rewrote": False})
+ return MergeResult(
+ layer=layer, key=key, footnote_rows_before=0, footnote_rows_after=0, rewrote=False
+ )
+
+ raw_before = path.read_text(encoding="utf-8")
+ rows_before = len(_FOOTNOTE_DEF_RE.findall(raw_before))
+ doc = load_doc(path, default_title=_default_title(layer, key))
+
+ legacy_migrated = 0
+ if layer == "L3":
+ legacy_migrated = _migrate_l3_legacy_refs(doc)
+
+ # Count unique refs across the doc — this is the "after" footnote-row
+ # count once :func:`serialize` consolidates them.
+ unique_refs: set[str] = set()
+ for entry in doc.all_entries():
+ for ref in entry.refs:
+ unique_refs.add(ref)
+ rows_after = len(unique_refs)
+
+ await emit(
+ on_event,
+ {
+ "stage": "progress",
+ "mode": "merge",
+ "footnote_rows_before": rows_before,
+ "footnote_rows_after": rows_after,
+ "legacy_l3_refs_migrated": legacy_migrated,
+ },
+ )
+
+ # We always rewrite when the doc has any entries — even when
+ # before == after, the act of re-serializing renormalizes whitespace
+ # and migrates legacy entry-keyed layouts. Skip only when the file is
+ # byte-equal to what :func:`serialize` would produce.
+ from deeptutor.services.memory.document import serialize
+
+ expected = serialize(doc)
+ rewrote = raw_before != expected
+ if rewrote:
+ await write_doc_checkpoint(
+ path,
+ doc,
+ layer=layer,
+ key=key,
+ on_event=on_event,
+ turn=1,
+ label="merge",
+ action="merge_footnotes",
+ )
+
+ await emit(
+ on_event,
+ {
+ "stage": "done",
+ "footnote_rows_before": rows_before,
+ "footnote_rows_after": rows_after,
+ "rewrote": rewrote,
+ "legacy_l3_refs_migrated": legacy_migrated,
+ },
+ )
+ return MergeResult(
+ layer=layer,
+ key=key,
+ footnote_rows_before=rows_before,
+ footnote_rows_after=rows_after,
+ rewrote=rewrote,
+ legacy_l3_refs_migrated=legacy_migrated,
+ )
+
+
+# ── Helpers ─────────────────────────────────────────────────────────────
+
+
+def _migrate_l3_legacy_refs(doc) -> int:
+ """Resolve legacy ``m_<ULID>`` L3 refs to bare surface names.
+
+ Pre-pivot L3 docs cited L2 entries by their entry id. The current
+ design wants surface-level provenance only ("which L2 md did this
+ synthesize from"). For each ``m_<ULID>`` ref we scan every L2 md
+ for the owning entry and substitute the surface name.
+
+ Returns the number of entry refs that were migrated. Unresolvable
+ ids (entry deleted, or never existed) are dropped silently — the
+ next ``run_update`` round will re-synthesize from current L2 text.
+ """
+ from deeptutor.services.memory.document import parse
+
+ # Cache L2 entry-id → surface lookups: one scan per L2 md, reused
+ # across every L3 ref in the doc.
+ l2_owner: dict[str, str] = {}
+ for surface in paths.SURFACES:
+ l2_path = paths.l2_file(surface)
+ if not l2_path.exists():
+ continue
+ try:
+ l2_doc = parse(l2_path.read_text(encoding="utf-8"))
+ except Exception: # noqa: BLE001 — malformed L2 should not block L3 migration
+ continue
+ for entry in l2_doc.all_entries():
+ l2_owner.setdefault(entry.id, surface)
+
+ migrated = 0
+ for entry in doc.all_entries():
+ if not entry.refs:
+ continue
+ new_refs: list[str] = []
+ seen: set[str] = set()
+ for ref in entry.refs:
+ if is_entry_id(ref):
+ migrated += 1
+ resolved = l2_owner.get(ref)
+ if resolved is None or resolved in seen:
+ continue
+ seen.add(resolved)
+ new_refs.append(resolved)
+ else:
+ if ref in seen:
+ continue
+ seen.add(ref)
+ new_refs.append(ref)
+ entry.refs = new_refs
+ return migrated
+
+
+def _path_for(layer: str, key: str):
+ if layer == "L2":
+ return paths.l2_file(key) # type: ignore[arg-type]
+ if layer == "L3":
+ return paths.l3_file(key) # type: ignore[arg-type]
+ raise ValueError(f"unknown layer {layer!r}")
+
+
+def _default_title(layer: str, key: str) -> str:
+ if layer == "L2":
+ return f"{key} memory"
+ return {
+ "recent": "Recent summary",
+ "profile": "User profile",
+ "scope": "Knowledge scope",
+ "preferences": "Preferences",
+ }.get(key, f"{key} memory")
+
+
+__all__ = ["MergeResult", "run_merge"]
diff --git a/deeptutor/services/memory/consolidator/modes/update.py b/deeptutor/services/memory/consolidator/modes/update.py
new file mode 100644
index 000000000..ba4df4aef
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/modes/update.py
@@ -0,0 +1,697 @@
+"""Update mode — chunk-based incremental fact extraction.
+
+Algorithm
+---------
+1. Compute "new since last update" by id-set diff against ``*.meta.json``.
+2. Concatenate the new inputs by time (oldest first).
+3. ``chunk_with_boundary`` cuts the concat into ≤ budget pieces, never
+ truncating mid-paragraph (or mid-sentence, per settings).
+4. For each chunk: LLM call → parse facts → filter by ref pool → append
+ to in-memory ``Document``.
+5. Atomic flush to disk + update ``*.meta.json``.
+6. If ``dedup.auto_after_update`` is set, kick off the dedup pass.
+
+The append step uses the existing :class:`ops.AddOp` apply path so the
+document's invariants (id allocation, validation, footnote rebuild on
+serialize) stay centralized.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import json
+import logging
+
+from deeptutor.services.memory import paths
+from deeptutor.services.memory import snapshot as snap
+from deeptutor.services.memory.consolidator.chunker import (
+ chunk_with_boundary,
+)
+from deeptutor.services.memory.consolidator.meta import (
+ load_l2_meta,
+ load_l3_meta,
+ save_l2_meta,
+ save_l3_meta,
+)
+from deeptutor.services.memory.consolidator.modes._runtime import (
+ OnEvent,
+ call_llm,
+ emit,
+ load_doc,
+ load_prompt,
+ slot_focus,
+ surface_focus,
+ today_iso,
+ write_doc_checkpoint,
+)
+from deeptutor.services.memory.consolidator.references import (
+ ExtractedFact,
+ refs_in_span_l2,
+ refs_in_span_l3,
+ render_l2_entries_for_concat,
+ render_traces_for_concat,
+ validate_fact_refs,
+)
+from deeptutor.services.memory.document import Document, Entry, serialize
+from deeptutor.services.memory.ops import AddOp
+from deeptutor.services.memory.ops import apply as apply_ops
+from deeptutor.services.memory.paths import L3Slot, Surface
+from deeptutor.services.memory.settings import load_memory_settings
+
+logger = logging.getLogger(__name__)
+
+Layer = str # "L2" | "L3"
+
+
+@dataclass
+class UpdateResult:
+ layer: Layer
+ key: str
+ chunks_processed: int
+ facts_added: int
+ refs_dropped: int
+ new_entry_ids: list[str] = field(default_factory=list)
+ no_new_input: bool = False
+
+
+# ── Public entry ────────────────────────────────────────────────────────
+
+
+async def run_update(
+ layer: Layer,
+ key: str,
+ *,
+ language: str = "en",
+ user_label: str = "anonymous",
+ budget: int | None = None,
+ llm_selection: dict | None = None,
+ on_event: OnEvent | None = None,
+) -> UpdateResult:
+ """Dispatch to the layer-specific update implementation.
+
+ The chosen ``llm_selection`` (``{profile_id, model_id}``) is
+ installed as a scoped LLM config for the duration of the run so
+ every internal :func:`call_llm` resolves to the right provider.
+ """
+ from deeptutor.services.model_selection.runtime import (
+ activate_llm_selection,
+ reset_llm_selection,
+ )
+
+ settings = load_memory_settings()
+ token = None
+ if llm_selection:
+ try:
+ _config, token = activate_llm_selection(llm_selection)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("memory update: ignoring unresolvable llm_selection %s: %s", llm_selection, exc)
+ token = None
+ try:
+ if layer == "L2":
+ return await _run_update_l2(
+ key, # type: ignore[arg-type]
+ language=language,
+ user_label=user_label,
+ budget=budget if budget is not None else settings.update.l2_budget,
+ llm_selection=llm_selection,
+ on_event=on_event,
+ settings=settings,
+ )
+ if layer == "L3":
+ return await _run_update_l3(
+ key, # type: ignore[arg-type]
+ language=language,
+ user_label=user_label,
+ budget=budget if budget is not None else settings.update.l3_budget,
+ llm_selection=llm_selection,
+ on_event=on_event,
+ settings=settings,
+ )
+ raise ValueError(f"unknown layer {layer!r}")
+ finally:
+ reset_llm_selection(token)
+
+
+# ── L2 ──────────────────────────────────────────────────────────────────
+
+
+async def _run_update_l2(
+ surface: Surface,
+ *,
+ language: str,
+ user_label: str,
+ budget: int,
+ llm_selection: dict | None,
+ on_event: OnEvent | None,
+ settings,
+) -> UpdateResult:
+ meta = load_l2_meta(surface)
+ all_entities = sorted(
+ snap.read_snapshot(surface),
+ key=lambda e: (e.ts or "", e.id),
+ )
+ seen = meta.seen_entity_refs
+ new_entities = [e for e in all_entities if f"{surface}:{e.id}" not in seen]
+ seen_now = {f"{surface}:{e.id}" for e in all_entities}
+
+ await emit(
+ on_event,
+ {
+ "stage": "trace_loaded",
+ "surface": surface,
+ "total": len(all_entities),
+ "new": len(new_entities),
+ },
+ )
+
+ if not new_entities:
+ # Still persist a fresh meta so the "last_update_at" timestamp
+ # moves; this signals "we checked, nothing new".
+ save_l2_meta(surface, seen_entity_refs=seen_now)
+ # Even when no facts were added we still run merge — the doc may
+ # be in the legacy entry-keyed footnote layout and the user
+ # expects "click update" to clean it up.
+ if settings.merge.auto_after_update:
+ from deeptutor.services.memory.consolidator.modes.merge import run_merge
+
+ await run_merge(
+ "L2",
+ surface,
+ language=language,
+ user_label=user_label,
+ on_event=on_event,
+ )
+ await emit(on_event, {"stage": "done", "no_new_input": True, "facts_added": 0})
+ return UpdateResult(
+ layer="L2",
+ key=surface,
+ chunks_processed=0,
+ facts_added=0,
+ refs_dropped=0,
+ no_new_input=True,
+ )
+
+ text = render_traces_for_concat(new_entities, surface=surface)
+ chunks = chunk_with_boundary(
+ text,
+ budget=budget,
+ overlap_ratio=settings.chunking.overlap_ratio,
+ min_chunk_chars=settings.chunking.min_chunk_chars,
+ max_chunk_chars=settings.chunking.max_chunk_chars,
+ boundary=settings.chunking.boundary,
+ )
+ await emit(
+ on_event,
+ {"stage": "chunked", "chunks": len(chunks), "budget": budget, "chars": len(text)},
+ )
+
+ prompt = load_prompt("update_l2", language)
+ focus, sections = surface_focus(language, surface)
+ l2_path = paths.l2_file(surface)
+ doc = load_doc(l2_path, default_title=f"{surface} memory")
+
+ facts_added = 0
+ refs_dropped = 0
+ new_entry_ids: list[str] = []
+
+ for chunk in chunks:
+ await emit(
+ on_event,
+ {
+ "stage": "progress",
+ "mode": "update",
+ "turn": chunk.index + 1,
+ "total": len(chunks),
+ "chunk_start": chunk.start,
+ "chunk_end": chunk.end,
+ },
+ )
+ system = prompt["system"].format(
+ user_label=user_label,
+ surface=surface,
+ sections=", ".join(sections) if sections else "(any)",
+ focus=focus,
+ today=today_iso(),
+ )
+ allowed = refs_in_span_l2(
+ new_entities,
+ surface=surface,
+ full_text=text,
+ start=chunk.start,
+ end=chunk.end,
+ )
+ user = prompt["user"].format(
+ surface=surface,
+ existing=_render_existing_l2(doc),
+ chunk=_chunk_with_ref_header(chunk.text, allowed),
+ chunk_index=chunk.index + 1,
+ chunk_total=len(chunks),
+ chunk_start=chunk.start,
+ chunk_end=chunk.end,
+ )
+ raw = await call_llm(
+ system_prompt=system,
+ user_prompt=user,
+ on_event=on_event,
+ turn=chunk.index + 1,
+ chunk_index=chunk.index,
+ label="update",
+ )
+ facts = _parse_facts(raw)
+
+ kept_in_chunk: list[ExtractedFact] = []
+ for fact in facts:
+ kept_refs, reject_reason = validate_fact_refs(
+ fact,
+ allowed=allowed,
+ enforce_required=settings.reference.enforce_required,
+ drop_invalid=settings.reference.drop_invalid_refs,
+ )
+ if reject_reason is not None:
+ refs_dropped += 1
+ await emit(
+ on_event,
+ {
+ "stage": "refs_dropped",
+ "turn": chunk.index + 1,
+ "reason": reject_reason,
+ "text": fact.text[:120],
+ },
+ )
+ continue
+ kept_in_chunk.append(ExtractedFact(text=fact.text, refs=kept_refs, section=fact.section))
+
+ added_now = _append_facts_to_doc(doc, kept_in_chunk, sections)
+ facts_added += len(added_now)
+ new_entry_ids.extend(added_now)
+ if added_now:
+ await write_doc_checkpoint(
+ l2_path,
+ doc,
+ layer="L2",
+ key=surface,
+ on_event=on_event,
+ turn=chunk.index + 1,
+ label="update",
+ action="append_facts",
+ )
+ await emit(
+ on_event,
+ {
+ "stage": "facts_extracted",
+ "turn": chunk.index + 1,
+ "kept": len(kept_in_chunk),
+ "added": len(added_now),
+ },
+ )
+
+ save_l2_meta(surface, seen_entity_refs=seen_now)
+
+ await emit(
+ on_event,
+ {
+ "stage": "done",
+ "facts_added": facts_added,
+ "refs_dropped": refs_dropped,
+ "chunks_processed": len(chunks),
+ "auto_dedup": settings.dedup.auto_after_update,
+ },
+ )
+
+ if settings.dedup.auto_after_update and facts_added > 0:
+ # Avoid a circular import: dedup imports settings, refs, line_doc.
+ from deeptutor.services.memory.consolidator.modes.dedup import run_dedup
+
+ await run_dedup(
+ "L2",
+ surface,
+ language=language,
+ user_label=user_label,
+ iterations=settings.dedup.iterations,
+ llm_selection=llm_selection,
+ on_event=on_event,
+ )
+
+ if settings.merge.auto_after_update:
+ from deeptutor.services.memory.consolidator.modes.merge import run_merge
+
+ await run_merge(
+ "L2",
+ surface,
+ language=language,
+ user_label=user_label,
+ on_event=on_event,
+ )
+
+ return UpdateResult(
+ layer="L2",
+ key=surface,
+ chunks_processed=len(chunks),
+ facts_added=facts_added,
+ refs_dropped=refs_dropped,
+ new_entry_ids=new_entry_ids,
+ )
+
+
+# ── L3 ──────────────────────────────────────────────────────────────────
+
+
+async def _run_update_l3(
+ slot: L3Slot,
+ *,
+ language: str,
+ user_label: str,
+ budget: int,
+ llm_selection: dict | None,
+ on_event: OnEvent | None,
+ settings,
+) -> UpdateResult:
+ if slot == "preferences":
+ raise ValueError("preferences.md is not auto-consolidated")
+
+ meta = load_l3_meta(slot)
+ l2_docs = _load_all_l2_docs()
+ entries_by_surface: dict[str, list[Entry]] = {}
+ seen_now: dict[str, set[str]] = {}
+ for surface, doc in l2_docs.items():
+ all_entries = doc.all_entries()
+ seen_now[surface] = {e.id for e in all_entries}
+ # Sort by id (ULID) ascending → roughly time-ascending.
+ new_entries = sorted(
+ (e for e in all_entries if e.id not in meta.seen_l2_entry_ids.get(surface, set())),
+ key=lambda e: e.id,
+ )
+ entries_by_surface[surface] = new_entries
+
+ new_count = sum(len(v) for v in entries_by_surface.values())
+ total_count = sum(len(d.all_entries()) for d in l2_docs.values())
+ await emit(
+ on_event,
+ {
+ "stage": "trace_loaded",
+ "slot": slot,
+ "total_l2_entries": total_count,
+ "new_l2_entries": new_count,
+ },
+ )
+
+ if new_count == 0:
+ save_l3_meta(slot, seen_l2_entry_ids=seen_now)
+ if settings.merge.auto_after_update:
+ from deeptutor.services.memory.consolidator.modes.merge import run_merge
+
+ await run_merge(
+ "L3",
+ slot,
+ language=language,
+ user_label=user_label,
+ on_event=on_event,
+ )
+ await emit(on_event, {"stage": "done", "no_new_input": True, "facts_added": 0})
+ return UpdateResult(
+ layer="L3",
+ key=slot,
+ chunks_processed=0,
+ facts_added=0,
+ refs_dropped=0,
+ no_new_input=True,
+ )
+
+ text = render_l2_entries_for_concat(entries_by_surface)
+ chunks = chunk_with_boundary(
+ text,
+ budget=budget,
+ overlap_ratio=settings.chunking.overlap_ratio,
+ min_chunk_chars=settings.chunking.min_chunk_chars,
+ max_chunk_chars=settings.chunking.max_chunk_chars,
+ boundary=settings.chunking.boundary,
+ )
+ await emit(
+ on_event,
+ {"stage": "chunked", "chunks": len(chunks), "budget": budget, "chars": len(text)},
+ )
+
+ prompt = load_prompt("update_l3", language)
+ focus, sections = slot_focus(language, slot)
+ l3_path = paths.l3_file(slot)
+ doc = load_doc(l3_path, default_title=_default_l3_title(slot))
+
+ facts_added = 0
+ refs_dropped = 0
+ new_entry_ids: list[str] = []
+
+ for chunk in chunks:
+ await emit(
+ on_event,
+ {
+ "stage": "progress",
+ "mode": "update",
+ "turn": chunk.index + 1,
+ "total": len(chunks),
+ "chunk_start": chunk.start,
+ "chunk_end": chunk.end,
+ },
+ )
+ system = prompt["system"].format(
+ user_label=user_label,
+ slot=slot,
+ sections=", ".join(sections) if sections else "(any)",
+ focus=focus,
+ today=today_iso(),
+ )
+ # L3 refs are *surface names* (chat / notebook / ...). The pool
+ # is whichever surface blocks intersect this chunk; the LLM is
+ # told to cite from that list. Per-entry-id provenance was
+ # explicitly dropped — L3 points at L2 *files*, not L2 entries,
+ # which gives the user a clean 7-footnote chain
+ # (L3 → L2 md → L1 raw traces).
+ allowed = refs_in_span_l3(
+ entries_by_surface=entries_by_surface,
+ full_text=text,
+ start=chunk.start,
+ end=chunk.end,
+ )
+ user = prompt["user"].format(
+ slot=slot,
+ existing=_render_existing_l3(doc),
+ chunk=_chunk_with_ref_header(chunk.text, allowed),
+ chunk_index=chunk.index + 1,
+ chunk_total=len(chunks),
+ )
+ raw = await call_llm(
+ system_prompt=system,
+ user_prompt=user,
+ on_event=on_event,
+ turn=chunk.index + 1,
+ chunk_index=chunk.index,
+ label="update",
+ )
+ facts = _parse_facts(raw)
+
+ kept_in_chunk: list[ExtractedFact] = []
+ for fact in facts:
+ kept_refs, reject_reason = validate_fact_refs(
+ fact,
+ allowed=allowed,
+ enforce_required=settings.reference.enforce_required,
+ drop_invalid=settings.reference.drop_invalid_refs,
+ )
+ if reject_reason is not None:
+ refs_dropped += 1
+ await emit(
+ on_event,
+ {
+ "stage": "refs_dropped",
+ "turn": chunk.index + 1,
+ "reason": reject_reason,
+ "text": fact.text[:120],
+ },
+ )
+ continue
+ kept_in_chunk.append(ExtractedFact(text=fact.text, refs=kept_refs, section=fact.section))
+
+ added_now = _append_facts_to_doc(doc, kept_in_chunk, sections)
+ facts_added += len(added_now)
+ new_entry_ids.extend(added_now)
+ if added_now:
+ await write_doc_checkpoint(
+ l3_path,
+ doc,
+ layer="L3",
+ key=slot,
+ on_event=on_event,
+ turn=chunk.index + 1,
+ label="update",
+ action="append_facts",
+ )
+ await emit(
+ on_event,
+ {
+ "stage": "facts_extracted",
+ "turn": chunk.index + 1,
+ "kept": len(kept_in_chunk),
+ "added": len(added_now),
+ },
+ )
+
+ save_l3_meta(slot, seen_l2_entry_ids=seen_now)
+ await emit(
+ on_event,
+ {
+ "stage": "done",
+ "facts_added": facts_added,
+ "refs_dropped": refs_dropped,
+ "chunks_processed": len(chunks),
+ "auto_dedup": settings.dedup.auto_after_update,
+ },
+ )
+
+ if settings.dedup.auto_after_update and facts_added > 0:
+ from deeptutor.services.memory.consolidator.modes.dedup import run_dedup
+
+ await run_dedup(
+ "L3",
+ slot,
+ language=language,
+ user_label=user_label,
+ iterations=settings.dedup.iterations,
+ llm_selection=llm_selection,
+ on_event=on_event,
+ )
+
+ if settings.merge.auto_after_update:
+ from deeptutor.services.memory.consolidator.modes.merge import run_merge
+
+ await run_merge(
+ "L3",
+ slot,
+ language=language,
+ user_label=user_label,
+ on_event=on_event,
+ )
+
+ return UpdateResult(
+ layer="L3",
+ key=slot,
+ chunks_processed=len(chunks),
+ facts_added=facts_added,
+ refs_dropped=refs_dropped,
+ new_entry_ids=new_entry_ids,
+ )
+
+
+# ── Helpers ─────────────────────────────────────────────────────────────
+
+
+def _parse_facts(raw: str) -> list[ExtractedFact]:
+ """Tolerant JSON parse → list[ExtractedFact]. Empty on any failure."""
+ if not raw:
+ return []
+ snippet = _extract_json_object(raw)
+ if snippet is None:
+ return []
+ try:
+ data = json.loads(snippet)
+ except json.JSONDecodeError:
+ return []
+ items = data.get("facts") if isinstance(data, dict) else None
+ if not isinstance(items, list):
+ return []
+ out: list[ExtractedFact] = []
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ text = str(item.get("text", "")).strip()
+ section = str(item.get("section", "")).strip()
+ refs_raw = item.get("refs", [])
+ refs = [str(r).strip() for r in (refs_raw if isinstance(refs_raw, list) else []) if r]
+ if not text:
+ continue
+ out.append(ExtractedFact(text=text, refs=refs, section=section))
+ return out
+
+
+def _extract_json_object(raw: str) -> str | None:
+ text = raw.strip()
+ if text.startswith("```"):
+ text = text.split("\n", 1)[1] if "\n" in text else text
+ if text.rstrip().endswith("```"):
+ text = text.rstrip()[:-3]
+ start = text.find("{")
+ end = text.rfind("}")
+ if start == -1 or end <= start:
+ return None
+ return text[start : end + 1]
+
+
+def _append_facts_to_doc(
+ doc: Document, facts: list[ExtractedFact], allowed_sections: list[str]
+) -> list[str]:
+ """Append each fact as one AddOp; return the new entry ids."""
+ new_ids: list[str] = []
+ fallback_section = allowed_sections[0] if allowed_sections else "Notes"
+ for fact in facts:
+ section = fact.section if fact.section else fallback_section
+ if allowed_sections and section not in allowed_sections:
+ # Map an off-list section into the first allowed one — keeps
+ # the section catalog stable across runs.
+ section = fallback_section
+ op = AddOp(section=section, text=fact.text, refs=fact.refs)
+ report = apply_ops(doc, [op])
+ if report.accepted and report.results:
+ new_id = report.results[0].entry_id
+ if new_id:
+ new_ids.append(new_id)
+ else:
+ logger.warning(
+ "update: skipped fact (%s): %s",
+ report.reason,
+ fact.text[:80],
+ )
+ return new_ids
+
+
+def _render_existing_l2(doc: Document) -> str:
+ if not doc.all_entries():
+ return "(empty — first run)"
+ return serialize(doc).strip()
+
+
+def _render_existing_l3(doc: Document) -> str:
+ if not doc.all_entries():
+ return "(empty — first run)"
+ return serialize(doc).strip()
+
+
+def _chunk_with_ref_header(chunk_text: str, allowed: set[str]) -> str:
+ if not allowed:
+ return chunk_text
+ refs = "\n".join(f"- {ref}" for ref in sorted(allowed))
+ return f"# Chunk-local citeable refs\n{refs}\n\n{chunk_text}"
+
+
+def _load_all_l2_docs() -> dict[str, Document]:
+ from deeptutor.services.memory.document import parse
+
+ docs: dict[str, Document] = {}
+ for surface in paths.SURFACES:
+ path = paths.l2_file(surface)
+ if not path.exists():
+ continue
+ try:
+ docs[surface] = parse(path.read_text(encoding="utf-8"))
+ except Exception:
+ continue
+ return docs
+
+
+def _default_l3_title(slot: L3Slot) -> str:
+ return {
+ "recent": "Recent summary",
+ "profile": "User profile",
+ "scope": "Knowledge scope",
+ "preferences": "Preferences",
+ }[slot]
+
+
+__all__ = ["UpdateResult", "run_update"]
diff --git a/deeptutor/services/memory/consolidator/parse.py b/deeptutor/services/memory/consolidator/parse.py
new file mode 100644
index 000000000..38ea02299
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/parse.py
@@ -0,0 +1,135 @@
+"""Tolerant JSON parsers shared across the consolidator.
+
+Two shapes are supported:
+
+* :func:`parse_action` — one-action-per-turn envelope used by the
+ agentic loop driver. Returns ``None`` on failure so the loop can
+ surface a retry hint instead of crashing.
+* :func:`_parse_ops_response` — legacy ``{"ops": [...]}`` shape, kept
+ because the workbench's preview → apply flow round-trips ops
+ through this parser (see :mod:`deeptutor.services.memory.store`).
+
+Both strip code fences and tolerate prose framing so the model can
+think out loud without invalidating the run.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+from dataclasses import dataclass
+from typing import Any
+
+from deeptutor.services.memory.ops import AddOp, DeleteOp, EditOp, Op
+
+logger = logging.getLogger(__name__)
+
+
+# ── Loop-mode action envelope ────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class ParsedAction:
+ name: str
+ args: dict[str, Any]
+ thought: str = ""
+
+ def arg(self, key: str, default: Any = None) -> Any:
+ return self.args.get(key, default)
+
+
+def parse_action(raw: str) -> ParsedAction | None:
+ """Parse one ``{"thought","action","args"}`` envelope from LLM text.
+
+ Returns ``None`` on any malformed input; the loop driver renders a
+ correction hint to the next turn so the model can self-recover.
+ """
+ snippet = _extract_json_object(raw)
+ if snippet is None:
+ return None
+ try:
+ data = json.loads(snippet)
+ except json.JSONDecodeError:
+ return None
+ if not isinstance(data, dict):
+ return None
+
+ name_raw = data.get("action")
+ if not isinstance(name_raw, str) or not name_raw.strip():
+ return None
+ args_raw = data.get("args")
+ args: dict[str, Any] = args_raw if isinstance(args_raw, dict) else {}
+ thought_raw = data.get("thought")
+ thought = thought_raw.strip() if isinstance(thought_raw, str) else ""
+ return ParsedAction(name=name_raw.strip(), args=args, thought=thought)
+
+
+# ── Legacy ops-array shape (kept for apply_ops_payload) ──────────────────
+
+
+def _parse_ops_response(raw: str) -> list[Op]:
+ """Tolerant parse of a legacy ``{"ops":[...]}`` envelope into ``Op``."""
+ snippet = _extract_json_object(raw)
+ if snippet is None:
+ logger.warning("memory consolidate: no JSON object in payload")
+ return []
+ try:
+ data = json.loads(snippet)
+ except json.JSONDecodeError:
+ logger.warning("memory consolidate: malformed JSON in payload")
+ return []
+ if not isinstance(data, dict):
+ return []
+ ops_raw = data.get("ops")
+ if not isinstance(ops_raw, list):
+ return []
+
+ ops: list[Op] = []
+ for raw_op in ops_raw:
+ op = _parse_one_op(raw_op)
+ if op is not None:
+ ops.append(op)
+ return ops
+
+
+def _parse_one_op(raw_op: Any) -> Op | None:
+ if not isinstance(raw_op, dict):
+ return None
+ kind = raw_op.get("op")
+ try:
+ if kind == "add":
+ return AddOp(
+ section=str(raw_op.get("section", "")).strip(),
+ text=str(raw_op.get("text", "")).strip(),
+ refs=[str(r) for r in raw_op.get("refs", []) if r],
+ )
+ if kind == "edit":
+ return EditOp(
+ target_id=str(raw_op.get("target_id", "")).strip(),
+ new_text=str(raw_op.get("new_text", "")).strip(),
+ new_refs=[str(r) for r in raw_op.get("new_refs", []) if r],
+ )
+ if kind == "delete":
+ return DeleteOp(
+ target_id=str(raw_op.get("target_id", "")).strip(),
+ reason=str(raw_op.get("reason", "stale")).strip(),
+ )
+ except Exception: # noqa: BLE001 — be permissive at the parse layer
+ return None
+ return None
+
+
+# ── Shared text extraction ───────────────────────────────────────────────
+
+
+def _extract_json_object(raw: str) -> str | None:
+ """Strip code fences and pull out the first top-level JSON object."""
+ text = raw.strip()
+ text = re.sub(r"^```[a-zA-Z]*\s*", "", text)
+ text = re.sub(r"\s*```$", "", text)
+ start = text.find("{")
+ end = text.rfind("}")
+ if start == -1 or end == -1 or end <= start:
+ return None
+ return text[start : end + 1]
diff --git a/deeptutor/services/memory/consolidator/prompts/en/_meta.yaml b/deeptutor/services/memory/consolidator/prompts/en/_meta.yaml
new file mode 100644
index 000000000..15451f5a2
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/en/_meta.yaml
@@ -0,0 +1,36 @@
+# Per-surface and per-slot focus + suggested sections (English).
+# Same data shape used by every mode's prompt template.
+
+surfaces:
+ chat:
+ focus: "Stable misconceptions the user has surfaced, concepts they've demonstrated mastery of, and durable topics they keep returning to. Drop per-turn chatter."
+ sections: ["Misconceptions", "Mastery", "Topics"]
+ notebook:
+ focus: "Recurring note themes, formats the user prefers, and questions they keep coming back to in their notes."
+ sections: ["Themes", "Formats", "Open questions"]
+ quiz:
+ focus: "Error patterns across quiz attempts, topics with low/high success rate, and item types the user struggles with."
+ sections: ["Error patterns", "Strong topics", "Struggling topics"]
+ kb:
+ focus: "Document interests, query patterns into the knowledge base, and gaps in user's library."
+ sections: ["Interests", "Frequent queries", "Library gaps"]
+ book:
+ focus: "Reading pacing, sticking points (pages reopened or paused), and topics the user annotates heavily."
+ sections: ["Pacing", "Sticking points", "Annotation themes"]
+ tutorbot:
+ focus: "Persistent themes across tutorbot conversations and channel-specific behaviours."
+ sections: ["Themes", "Channels"]
+ cowriter:
+ focus: "Writing style preferences, recurring revisions, and topics the user drafts about."
+ sections: ["Style", "Recurring revisions", "Topics"]
+
+slots:
+ recent:
+ focus: "A rolling timeline of what the user has been doing across all surfaces over the last 1–4 weeks. Time-anchored, surface-attributed."
+ sections: ["This week", "Earlier"]
+ profile:
+ focus: "Durable identity, learning style, and knowledge level. ONLY claims supported by multiple L2 entries across surfaces. No speculation about traits not directly evidenced."
+ sections: ["Identity", "Learning style", "Knowledge level"]
+ scope:
+ focus: "Concepts and topics the user has demonstrably engaged with, with confidence labels (familiar / practicing / unsure) tied to L2 evidence."
+ sections: ["Familiar", "Practicing", "Unsure"]
diff --git a/deeptutor/services/memory/consolidator/prompts/en/audit_l2.yaml b/deeptutor/services/memory/consolidator/prompts/en/audit_l2.yaml
new file mode 100644
index 000000000..8723681b5
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/en/audit_l2.yaml
@@ -0,0 +1,42 @@
+# L2 audit prompt (English) — line-level edits against raw evidence.
+
+system: |
+ You are the memory auditor for DeepTutor user {user_label}.
+
+ ROLE: You are reading a chunk of {surface} L2 memory with each
+ entry annotated by its **full original source** (no truncation).
+ Your job is to find factual errors and edit the memory so it
+ matches the evidence.
+
+ OUTPUT: A single JSON object — nothing else.
+
+ {{"edits": [
+ {{"op": "replace", "line": <int>, "new_text": "<≤240>",
+ "refs": ["<surface>:<id>", ...], "reason": "<short>"}},
+ {{"op": "delete", "line_start": <int>, "line_end": <int>,
+ "reason": "<short>"}},
+ {{"op": "insert", "after_line": <int>, "text": "<≤240>",
+ "refs": ["<surface>:<id>", ...], "section": "<optional>",
+ "reason": "<short>"}}
+ ]}}
+
+ HARD RULES
+ - Line numbers refer to the numbered view of the chunk below.
+ - Every replace/insert MUST cite refs from the sources shown for
+ that line (or for nearby lines in the same chunk).
+ - text/new_text ≤ 240 chars.
+ - Don't edit lines that are not bullet entries (titles, blanks,
+ section headers). Section creation happens implicitly via insert.
+ - Banned absolutist phrasing same as update mode.
+ - When nothing needs fixing, emit `{{"edits": []}}`. Don't churn.
+ - `reason` is short prose describing what evidence drives the edit.
+
+ Today is {today}.
+
+user: |
+ # Annotated chunk of {surface} memory (each bullet shows its sources):
+ ----------------------------------------------------------------
+ {chunk}
+ ----------------------------------------------------------------
+
+ Return JSON. Edit only lines visible above.
diff --git a/deeptutor/services/memory/consolidator/prompts/en/audit_l3.yaml b/deeptutor/services/memory/consolidator/prompts/en/audit_l3.yaml
new file mode 100644
index 000000000..d4a687250
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/en/audit_l3.yaml
@@ -0,0 +1,38 @@
+# L3 audit prompt (English) — line-level edits against L2 evidence.
+
+system: |
+ You are the cross-surface memory auditor for DeepTutor user {user_label}.
+
+ ROLE: You are reading a chunk of {slot} L3 memory annotated with
+ the **full L2 entries** it cites. Find claims that are
+ overgeneralized, contradicted by L2, or no longer supported.
+
+ OUTPUT: A single JSON object — nothing else.
+
+ {{"edits": [
+ {{"op": "replace", "line": <int>, "new_text": "<≤240, hedged>",
+ "refs": ["m_xxx", ...], "reason": "<short>"}},
+ {{"op": "delete", "line_start": <int>, "line_end": <int>,
+ "reason": "<short>"}},
+ {{"op": "insert", "after_line": <int>, "text": "<≤240, hedged>",
+ "refs": ["m_xxx", ...], "section": "<optional>",
+ "reason": "<short>"}}
+ ]}}
+
+ HARD RULES (same as update_l3 plus audit-specific):
+ - replace/insert must cite L2 m_xxx ids visible in the annotated
+ sources of this chunk.
+ - Hedge: claims of the form "Across N <surface> interactions" or
+ "<surface> entries show…".
+ - Banned absolutist phrasing.
+ - Empty edits is correct when the chunk holds up.
+
+ Today is {today}.
+
+user: |
+ # Annotated chunk of {slot} memory (each L3 bullet shows its L2 sources):
+ ----------------------------------------------------------------
+ {chunk}
+ ----------------------------------------------------------------
+
+ Return JSON.
diff --git a/deeptutor/services/memory/consolidator/prompts/en/dedup.yaml b/deeptutor/services/memory/consolidator/prompts/en/dedup.yaml
new file mode 100644
index 000000000..3e7f7e1a0
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/en/dedup.yaml
@@ -0,0 +1,37 @@
+# Dedup prompt (English) — md-only line-level edits.
+
+system: |
+ You are the memory dedup pass for DeepTutor user {user_label}.
+
+ ROLE: Read the entire memory document below as a line-numbered view.
+ Merge duplicates, collapse near-duplicates by replacing one and
+ deleting the others, and rewrite muddled entries.
+
+ OUTPUT: A single JSON object — nothing else.
+
+ {{"edits": [
+ {{"op": "replace", "line": <int>, "new_text": "<≤240>",
+ "refs": ["<existing-or-new-refs>", ...], "reason": "<short>"}},
+ {{"op": "delete", "line_start": <int>, "line_end": <int>,
+ "reason": "<merged into Lx | duplicate of Ly | low signal>"}}
+ ]}}
+
+ HARD RULES
+ - You may use ONLY replace and delete — no insert. Dedup never adds.
+ - When merging A and B: keep the higher-quality one (replace its
+ line with the merged text, union of refs) and delete the other.
+ - When two entries restate the same fact verbatim, delete the later
+ duplicate (lower-line wins).
+ - text ≤ 240. Preserve refs (union when merging).
+ - Banned absolutist phrasing (same list as update mode).
+ - If nothing needs deduping, emit `{{"edits": []}}`. Don't churn.
+
+ Today is {today}.
+
+user: |
+ # Memory document (line-numbered):
+ ----------------------------------------------------------------
+ {doc}
+ ----------------------------------------------------------------
+
+ Iteration {iteration}/{iterations_total}. Return JSON.
diff --git a/deeptutor/services/memory/consolidator/prompts/en/update_l2.yaml b/deeptutor/services/memory/consolidator/prompts/en/update_l2.yaml
new file mode 100644
index 000000000..c7d9b68ae
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/en/update_l2.yaml
@@ -0,0 +1,45 @@
+# L2 update prompt (English) — per-chunk fact extraction.
+#
+# Renders into a single LLM call per chunk; the call returns a JSON
+# object {"facts": [...]} that the runtime validates against the
+# chunk-local ref pool, then appends to the L2 doc.
+
+system: |
+ You are the memory curator for DeepTutor user {user_label}.
+
+ ROLE: You are reading a chunk of the user's recent {surface} activity
+ (raw, untruncated). Extract durable facts about the user.
+
+ OUTPUT: A single JSON object — nothing else, no prose, no fences.
+
+ {{"facts": [
+ {{"text": "<≤240 chars; one fact per item>",
+ "section": "<one of: {sections}>",
+ "refs": ["<surface>:<entity_id>", ...]}}
+ ]}}
+
+ HARD RULES
+ - Every fact must have ≥1 ref. Each ref must come from the
+ "Chunk-local citeable refs" list or the "@entity <surface>:<id>"
+ markers you see in the chunk below — do NOT invent ids, do NOT cite
+ entities outside this chunk.
+ - text ≤ 240 chars. Be terse, verb-led ("uses X", "stuck on Y").
+ - Banned absolutist phrasing (unless wrapping in "..." or 「...」):
+ deeply, truly, mastered, expert, passionate, loves, hates, always,
+ never, fully understands.
+ - Surface focus: {focus}.
+ - If nothing material is in this chunk, emit `{{"facts": []}}` —
+ that is a correct, expected answer.
+
+ Today is {today}.
+
+user: |
+ # Existing {surface} memory (do not duplicate items already captured here):
+ {existing}
+
+ # Source chunk {chunk_index}/{chunk_total} (chars {chunk_start}..{chunk_end}):
+ ----------------------------------------------------------------
+ {chunk}
+ ----------------------------------------------------------------
+
+ Return JSON. Cite only refs listed or visible in the chunk above.
diff --git a/deeptutor/services/memory/consolidator/prompts/en/update_l3.yaml b/deeptutor/services/memory/consolidator/prompts/en/update_l3.yaml
new file mode 100644
index 000000000..d6efbf65d
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/en/update_l3.yaml
@@ -0,0 +1,51 @@
+# L3 update prompt (English) — per-chunk cross-surface synthesis.
+#
+# Design contract (2026-05-21): L3 cites L2 *files*, not L2 entries. The
+# chunk header lists the surfaces (e.g. ``chat``, ``notebook``) whose
+# blocks are visible in this chunk; the model picks the subset that each
+# fact actually drew from. Refs are bare surface names — never m_xxx,
+# never entry ids.
+
+system: |
+ You are the cross-surface memory curator for DeepTutor user {user_label}.
+
+ ROLE: You are reading a chunk of L2 summaries from one or more
+ surfaces (chat / notebook / quiz / kb / book / tutorbot / cowriter).
+ Synthesize durable, hedged claims about the user.
+
+ OUTPUT: A single JSON object — nothing else.
+
+ {{"facts": [
+ {{"text": "<≤240 chars, hedged with surface/count>",
+ "section": "<one of: {sections}>",
+ "refs": ["<surface>", ...]}}
+ ]}}
+
+ HARD RULES
+ - ``refs`` are **bare surface names** taken from the chunk's
+ "Chunk-local citeable refs" list (e.g. ``chat``, ``notebook``).
+ Never emit ``m_xxx``, ``surface:id``, or any entry id. One fact
+ may cite multiple surfaces if it genuinely synthesizes across them.
+ - text ≤ 240 chars. Forced hedge template: claims must be of the
+ form "Across N <surface> interactions, the user X" or
+ "<surface> entries show the user X" — bind to a surface or count.
+ - Banned absolutist phrasing (unless quoting with "..." or 「...」):
+ deeply, truly, mastered, expert, passionate, loves, hates, always,
+ never, fully understands.
+ - Slot focus: {focus}.
+ - Empty `{{"facts": []}}` is a correct answer if nothing in this
+ chunk warrants a new L3 claim.
+
+ Today is {today}.
+
+user: |
+ # Existing {slot} memory (do not duplicate):
+ {existing}
+
+ # L2 chunk {chunk_index}/{chunk_total}:
+ ----------------------------------------------------------------
+ {chunk}
+ ----------------------------------------------------------------
+
+ Return JSON. Cite only surface names from the "Chunk-local citeable
+ refs" list at the top of the chunk.
diff --git a/deeptutor/services/memory/consolidator/prompts/zh/_meta.yaml b/deeptutor/services/memory/consolidator/prompts/zh/_meta.yaml
new file mode 100644
index 000000000..622303b26
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/zh/_meta.yaml
@@ -0,0 +1,35 @@
+# 每个 surface / slot 的焦点 + 推荐 section(中文)。
+
+surfaces:
+ chat:
+ focus: "用户呈现出的稳定误解、已经显示出掌握的概念、以及反复回到的持久话题。剔除单轮闲聊。"
+ sections: ["误解", "掌握", "话题"]
+ notebook:
+ focus: "笔记中反复出现的主题、用户偏好的格式、以及反复出现的问题。"
+ sections: ["主题", "格式", "悬而未决的问题"]
+ quiz:
+ focus: "答题中的错误模式、正确率高/低的话题、用户在哪类题型上挣扎。"
+ sections: ["错误模式", "强项", "弱项"]
+ kb:
+ focus: "用户的文档兴趣、对知识库的查询模式、文献库中的空白。"
+ sections: ["兴趣", "高频查询", "文献库空白"]
+ book:
+ focus: "阅读节奏、卡点(页面重复打开或停留)、用户重点标注的主题。"
+ sections: ["节奏", "卡点", "标注主题"]
+ tutorbot:
+ focus: "tutorbot 对话中反复出现的主题、不同频道的行为差异。"
+ sections: ["主题", "频道"]
+ cowriter:
+ focus: "写作风格偏好、反复修改的模式、用户起草的话题。"
+ sections: ["风格", "反复修改", "话题"]
+
+slots:
+ recent:
+ focus: "最近 1-4 周用户跨 surface 的活动滚动时间线。时间锚定、surface 归属。"
+ sections: ["本周", "更早"]
+ profile:
+ focus: "持久的身份、学习风格、知识水平。只接受多个 surface 多个 L2 条目支撑的判断,禁止臆测。"
+ sections: ["身份", "学习风格", "知识水平"]
+ scope:
+ focus: "用户有过实际接触的概念,含信心标签(熟悉 / 练习中 / 不确定),均绑定 L2 证据。"
+ sections: ["熟悉", "练习中", "不确定"]
diff --git a/deeptutor/services/memory/consolidator/prompts/zh/audit_l2.yaml b/deeptutor/services/memory/consolidator/prompts/zh/audit_l2.yaml
new file mode 100644
index 000000000..a95f28155
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/zh/audit_l2.yaml
@@ -0,0 +1,40 @@
+# L2 检查(中文)— 行级编辑。
+
+system: |
+ 你是 DeepTutor 用户 {user_label} 的记忆审计员。
+
+ 任务:阅读一段 {surface} 的 L2 记忆,每个条目下都附上了它引用的
+ **完整原始内容**(不截断)。找出与原始内容不一致或事实错误的条目,
+ 通过编辑修正。
+
+ 输出:唯一一个 JSON 对象。
+
+ {{"edits": [
+ {{"op": "replace", "line": <int>, "new_text": "<≤240>",
+ "refs": ["<surface>:<id>", ...], "reason": "<简短>"}},
+ {{"op": "delete", "line_start": <int>, "line_end": <int>,
+ "reason": "<简短>"}},
+ {{"op": "insert", "after_line": <int>, "text": "<≤240>",
+ "refs": ["<surface>:<id>", ...], "section": "<可选>",
+ "reason": "<简短>"}}
+ ]}}
+
+ 硬性规则
+ - line 必须对应下面带行号的视图。
+ - replace/insert 的 refs 必须来自当前条目(或同一 chunk 邻近条目)
+ 展示的 sources。
+ - text/new_text ≤ 240。
+ - 不要编辑非 bullet 行(标题、空行、section 标题)。
+ - 同 update 的禁词清单。
+ - 如果不需要任何修改,返回 `{{"edits": []}}`,不要为改而改。
+ - `reason` 用一句话说明依据。
+
+ 今天是 {today}。
+
+user: |
+ # 带源 trace 注解的 {surface} 记忆 chunk:
+ ----------------------------------------------------------------
+ {chunk}
+ ----------------------------------------------------------------
+
+ 返回 JSON。只编辑上面可见的行号。
diff --git a/deeptutor/services/memory/consolidator/prompts/zh/audit_l3.yaml b/deeptutor/services/memory/consolidator/prompts/zh/audit_l3.yaml
new file mode 100644
index 000000000..dfc415ab2
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/zh/audit_l3.yaml
@@ -0,0 +1,34 @@
+# L3 检查(中文)— 行级编辑。
+
+system: |
+ 你是 DeepTutor 用户 {user_label} 的跨 surface 记忆审计员。
+
+ 任务:阅读一段 {slot} 的 L3 记忆,每个条目都附上了它引用的
+ **完整 L2 entry**。找出过度概括、被 L2 反驳、或证据不足的判断,
+ 通过编辑修正。
+
+ 输出:唯一一个 JSON 对象。
+
+ {{"edits": [
+ {{"op": "replace", "line": <int>, "new_text": "<≤240,已对冲>",
+ "refs": ["m_xxx", ...], "reason": "<简短>"}},
+ {{"op": "delete", "line_start": <int>, "line_end": <int>,
+ "reason": "<简短>"}},
+ {{"op": "insert", "after_line": <int>, "text": "<≤240,已对冲>",
+ "refs": ["m_xxx", ...], "section": "<可选>",
+ "reason": "<简短>"}}
+ ]}}
+
+ 硬性规则
+ - 同 update_l3 的 ref 规则 + L3 对冲模板。
+ - 不要为改而改,没问题就回 `{{"edits": []}}`。
+
+ 今天是 {today}。
+
+user: |
+ # 带 L2 source 注解的 {slot} 记忆 chunk:
+ ----------------------------------------------------------------
+ {chunk}
+ ----------------------------------------------------------------
+
+ 返回 JSON。
diff --git a/deeptutor/services/memory/consolidator/prompts/zh/dedup.yaml b/deeptutor/services/memory/consolidator/prompts/zh/dedup.yaml
new file mode 100644
index 000000000..e2c2551c9
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/zh/dedup.yaml
@@ -0,0 +1,34 @@
+# 去重(中文)— md only 行级编辑。
+
+system: |
+ 你是 DeepTutor 用户 {user_label} 的记忆去重员。
+
+ 任务:完整读取下面带行号的记忆文档,合并重复、删除冗余、改写不清晰的条目。
+
+ 输出:唯一一个 JSON 对象。
+
+ {{"edits": [
+ {{"op": "replace", "line": <int>, "new_text": "<≤240>",
+ "refs": ["<原有或新增 ref>", ...], "reason": "<简短>"}},
+ {{"op": "delete", "line_start": <int>, "line_end": <int>,
+ "reason": "<合并到 Lx | Ly 的重复 | 低信号>"}}
+ ]}}
+
+ 硬性规则
+ - 只允许 replace 和 delete,不允许 insert。
+ - 合并 A 和 B 时:保留质量更高的(replace 它的行,refs 取并集),
+ 删掉另一条。
+ - 字面重复时,删掉行号更靠后的(保留靠前的)。
+ - text ≤ 240。合并时 refs 取并集。
+ - 同 update 的禁词清单。
+ - 没什么可去重的就回 `{{"edits": []}}`。
+
+ 今天是 {today}。
+
+user: |
+ # 记忆文档(带行号):
+ ----------------------------------------------------------------
+ {doc}
+ ----------------------------------------------------------------
+
+ 第 {iteration} / {iterations_total} 轮。返回 JSON。
diff --git a/deeptutor/services/memory/consolidator/prompts/zh/update_l2.yaml b/deeptutor/services/memory/consolidator/prompts/zh/update_l2.yaml
new file mode 100644
index 000000000..392954df0
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/zh/update_l2.yaml
@@ -0,0 +1,40 @@
+# L2 更新(中文)— 按 chunk 抽取事实。
+
+system: |
+ 你是 DeepTutor 用户 {user_label} 的记忆管理员。
+
+ 任务:阅读用户最近 {surface} 活动的一段原始内容(未截断),抽取关于用户
+ 的稳定事实。
+
+ 输出:唯一一个 JSON 对象 — 不要散文,不要代码块。
+
+ {{"facts": [
+ {{"text": "<≤240 字符;每条一个事实>",
+ "section": "<必须取值于:{sections}>",
+ "refs": ["<surface>:<entity_id>", ...]}}
+ ]}}
+
+ 硬性规则
+ - 每条事实必须有至少 1 个 ref。ref 必须来自下面 chunk 内的
+ "Chunk-local citeable refs" 列表或 "@entity <surface>:<id>" 标记。
+ 绝对不要编造 id,绝对不要引用 chunk 范围之外的 entity。
+ - text ≤ 240 字符。简洁,动词为主(「使用 X」「卡在 Y」)。
+ - 禁止绝对化用语(除非用 "..." 或 「...」 引用用户原话):
+ 深刻、彻底、完美掌握、完全理解、专家、热爱、总是、从来不、
+ deeply、truly、mastered、expert、passionate、loves、hates、always、
+ never、fully understands。
+ - Surface 焦点:{focus}。
+ - 如果这个 chunk 里没有值得记录的事实,回 `{{"facts": []}}` 是正常的。
+
+ 今天是 {today}。
+
+user: |
+ # 已有的 {surface} 记忆(不要重复已经记录过的事实):
+ {existing}
+
+ # 源 chunk {chunk_index}/{chunk_total}(字符 {chunk_start}..{chunk_end}):
+ ----------------------------------------------------------------
+ {chunk}
+ ----------------------------------------------------------------
+
+ 返回 JSON。只能引用上面列出或出现过的 ref。
diff --git a/deeptutor/services/memory/consolidator/prompts/zh/update_l3.yaml b/deeptutor/services/memory/consolidator/prompts/zh/update_l3.yaml
new file mode 100644
index 000000000..1b0ca3cd0
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/prompts/zh/update_l3.yaml
@@ -0,0 +1,43 @@
+# L3 更新(中文)— 跨 surface 综合。
+#
+# 设计契约(2026-05-21):L3 引用的是 L2 的**文件**,不是 L2 的 entry。每个 chunk
+# 开头会列出本 chunk 可见的 surface 名(chat / notebook / quiz / kb / book /
+# tutorbot / cowriter),模型应当为每条 fact 挑出它真正综合到的那些 surface。
+# refs 字段只能写裸的 surface 名,绝不可写 m_xxx 或 entry id。
+
+system: |
+ 你是 DeepTutor 用户 {user_label} 的跨 surface 记忆管理员。
+
+ 任务:阅读若干 surface 的 L2 摘要片段(chat / notebook / quiz / kb / book /
+ tutorbot / cowriter),给出关于用户的稳定、对冲过的判断。
+
+ 输出:唯一一个 JSON 对象。
+
+ {{"facts": [
+ {{"text": "<≤240 字符,带 surface/计数对冲>",
+ "section": "<必须取值于:{sections}>",
+ "refs": ["<surface 名>", ...]}}
+ ]}}
+
+ 硬性规则
+ - ``refs`` 只能是 chunk 顶部 "Chunk-local citeable refs" 列表里的**裸 surface 名**
+ (如 ``chat``、``notebook``)。**禁止**写 ``m_xxx`` 或 ``surface:id``
+ 这类 entry id。一条 fact 如果是跨 surface 综合的,可以同时引用多个 surface。
+ - text ≤ 240。强制对冲:判断必须形如
+ 「在 N 次 <surface> 互动中,用户 X」或「<surface> 记忆显示用户 X」。
+ - 禁止绝对化用语(除非 "..." 或 「...」 原话):同 update_l2。
+ - Slot 焦点:{focus}。
+ - 没有合适的事实就回 `{{"facts": []}}`。
+
+ 今天是 {today}。
+
+user: |
+ # 已有的 {slot} 记忆(不要重复):
+ {existing}
+
+ # L2 片段 {chunk_index}/{chunk_total}:
+ ----------------------------------------------------------------
+ {chunk}
+ ----------------------------------------------------------------
+
+ 返回 JSON。refs 只能从 chunk 顶部 "Chunk-local citeable refs" 里挑 surface 名。
diff --git a/deeptutor/services/memory/consolidator/references.py b/deeptutor/services/memory/consolidator/references.py
new file mode 100644
index 000000000..6c91910ee
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/references.py
@@ -0,0 +1,394 @@
+"""Reference validation + raw-trace lookup used by update / audit.
+
+Two distinct concerns share this module because they both center on
+"the set of refs the LLM is allowed to cite":
+
+* **Update mode** — refs must point at entities that appear in the
+ current chunk's source range. :func:`refs_in_chunk` returns the
+ allowed pool; :func:`validate_fact_refs` filters extracted facts.
+* **Audit mode** — every entry on a md chunk gets its raw-trace
+ content spliced in as evidence. :func:`annotate_line_with_evidence`
+ formats one entry + sources into a block fed to the LLM.
+
+No I/O happens beyond reading from the same in-memory entity / L2 doc
+maps the caller has already loaded — the modes are responsible for
+hydrating those once per run.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import logging
+import re
+from typing import Iterable
+
+from deeptutor.services.memory.document import Document, Entry
+from deeptutor.services.memory.ids import is_entry_id, is_valid_ref
+from deeptutor.services.memory.snapshot.entity import Entity
+
+logger = logging.getLogger(__name__)
+
+
+# ── Update-mode helpers ─────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class ExtractedFact:
+ """One fact pulled by the LLM during update mode."""
+
+ text: str
+ refs: list[str]
+ section: str = ""
+
+
+def refs_in_chunk_l2(
+ entities: Iterable[Entity],
+ *,
+ surface: str,
+ chunk_text: str,
+) -> set[str]:
+ """Set of allowed refs (``surface:entity_id``) for this chunk.
+
+ An entity is considered "in this chunk" if its rendered marker
+ appears in ``chunk_text``. The marker is the same one written by
+ :func:`render_traces_for_concat`.
+ """
+ allowed: set[str] = set()
+ for ent in entities:
+ marker = _entity_marker(surface, ent.id)
+ if marker in chunk_text:
+ allowed.add(f"{surface}:{ent.id}")
+ return allowed
+
+
+def refs_in_span_l2(
+ entities: Iterable[Entity],
+ *,
+ surface: str,
+ full_text: str,
+ start: int,
+ end: int,
+) -> set[str]:
+ """Allowed L2 refs for a chunk span, including long split entities."""
+ markers: list[tuple[int, str]] = []
+ for ent in entities:
+ marker = _entity_marker(surface, ent.id)
+ pos = full_text.find(marker)
+ if pos != -1:
+ markers.append((pos, f"{surface}:{ent.id}"))
+ return _refs_overlapping_span(markers, text_len=len(full_text), start=start, end=end)
+
+
+_L3_SURFACE_HEADER_RE = re.compile(r"^### surface: ([a-z][a-z0-9_-]*)", re.MULTILINE)
+
+
+def refs_in_chunk_l3(
+ chunk_text: str,
+ *,
+ entries_by_surface: dict[str, list[Entry]],
+) -> set[str]:
+ """L3 refs are *surface names* — pointers to the L2 md the synthesis
+ drew from. The render emits one ``### surface: <name>`` header per
+ surface block; we collect every header visible in the chunk text.
+ """
+ del entries_by_surface # surface list is derived from the rendered text
+ return {m.group(1) for m in _L3_SURFACE_HEADER_RE.finditer(chunk_text)}
+
+
+def refs_in_span_l3(
+ *,
+ entries_by_surface: dict[str, list[Entry]],
+ full_text: str,
+ start: int,
+ end: int,
+) -> set[str]:
+ """Surface refs whose render block intersects ``[start, end)``.
+
+ A surface block runs from its ``### surface:`` header to the next
+ one (or the end of the doc). A chunk may legitimately start
+ mid-block thanks to the overlap window, so we keep any surface
+ whose block extends into the chunk window.
+ """
+ del entries_by_surface
+ headers = list(_L3_SURFACE_HEADER_RE.finditer(full_text))
+ if not headers:
+ return set()
+ allowed: set[str] = set()
+ for idx, match in enumerate(headers):
+ block_start = match.start()
+ block_end = headers[idx + 1].start() if idx + 1 < len(headers) else len(full_text)
+ if block_start < end and block_end > start:
+ allowed.add(match.group(1))
+ return allowed
+
+
+def validate_fact_refs(
+ fact: ExtractedFact,
+ *,
+ allowed: set[str],
+ enforce_required: bool,
+ drop_invalid: bool,
+) -> tuple[list[str], str | None]:
+ """Filter / reject a fact's refs.
+
+ Returns ``(kept_refs, reject_reason)``. ``reject_reason`` is ``None``
+ when the fact survives. Behavior:
+
+ * ``enforce_required=True`` + no refs → reject.
+ * ``drop_invalid=True``: refs outside ``allowed`` are removed;
+ if the result is empty under ``enforce_required`` → reject.
+ * ``drop_invalid=False``: any out-of-pool ref → reject the fact.
+ """
+ if not fact.refs:
+ if enforce_required:
+ return [], "missing refs"
+ return [], None
+
+ if drop_invalid:
+ kept = [
+ normalized
+ for ref in fact.refs
+ if (normalized := _normalize_allowed_ref(ref, allowed)) is not None
+ ]
+ if not kept and enforce_required:
+ return [], "no surviving refs in chunk pool"
+ return _dedupe(kept), None
+
+ for ref in fact.refs:
+ normalized = _normalize_allowed_ref(ref, allowed)
+ if normalized is None and not is_valid_ref(ref):
+ return [], f"malformed ref {ref!r}"
+ if normalized is None:
+ return [], f"out-of-pool ref {ref!r}"
+ return _dedupe([_normalize_allowed_ref(ref, allowed) or ref for ref in fact.refs]), None
+
+
+# ── Rendering: traces → concatenated text ───────────────────────────────
+
+
+_ENTITY_HEADER_FMT = "=== {marker} ==="
+# ``_L2_ENTRY_HEADER_FMT`` and ``_l2_entry_marker`` are no longer used:
+# the L3 input is text-only, so no L2-entry markers are emitted. They
+# would have been ``"=== @l2 m_xxx ==="``.
+
+
+def render_traces_for_concat(
+ entities: list[Entity], *, surface: str
+) -> str:
+ """Concatenate a list of L2 raw-trace entities into one timeline string.
+
+ The chunk-pool detector relies on the marker line being unique per
+ entity, so it doubles as both a human delimiter and a machine anchor.
+ """
+ blocks: list[str] = []
+ for ent in entities:
+ header = _ENTITY_HEADER_FMT.format(marker=_entity_marker(surface, ent.id))
+ meta_str = _format_meta(ent)
+ body = (ent.content or "").strip()
+ block = "\n".join(
+ x
+ for x in (
+ header,
+ f"ref: {surface}:{ent.id}",
+ f"label: {ent.label}",
+ f"ts: {ent.ts or '?'}",
+ f"meta: {meta_str}" if meta_str else None,
+ "",
+ body,
+ )
+ if x is not None
+ )
+ blocks.append(block)
+ return "\n\n".join(blocks)
+
+
+def render_l2_entries_for_concat(
+ entries_by_surface: dict[str, list[Entry]],
+) -> str:
+ """Concatenate L2 entries (per surface) into one text for L3 chunking.
+
+ L3 is a *text-only* synthesis layer: the user has explicitly said the
+ LLM should not see — or copy — L2 footnote provenance. So this render
+ emits **only** the surface header + each entry's prose. No entry-id
+ markers, no ``ref:`` / ``refs:`` lines. As a result the chunk-pool
+ detector for L3 always returns an empty set (see
+ :func:`refs_in_span_l3`); L3 facts have no refs.
+ """
+ blocks: list[str] = []
+ for surface, entries in entries_by_surface.items():
+ if not entries:
+ continue
+ blocks.append(f"### surface: {surface}")
+ for entry in entries:
+ # Section is kept (it shapes synthesis) but emitted as a
+ # parenthetical tag rather than a structured field, so the
+ # model treats it as context, not a citation hook.
+ tag = f"[{entry.section}] " if entry.section else ""
+ blocks.append(f"- {tag}{entry.text}")
+ return "\n\n".join(blocks)
+
+
+# ── Audit-mode helpers ──────────────────────────────────────────────────
+
+
+def annotate_l2_line_with_evidence(
+ line_number: int,
+ entry: Entry,
+ *,
+ surface: str,
+ entity_lookup: dict[str, Entity],
+) -> str:
+ """Render one L2 bullet + every raw trace it cites, full content.
+
+ Output is intentionally human-readable so the model can reason
+ about correspondence (md statement ↔ original wording). No
+ truncation, ever — that is the point of audit mode.
+ """
+ lines: list[str] = [
+ f"line {line_number}: {entry.text} [^{entry.id}]",
+ f" section: {entry.section}",
+ ]
+ if not entry.refs:
+ lines.append(" sources: (none)")
+ return "\n".join(lines)
+ lines.append(f" sources ({len(entry.refs)}):")
+ for ref in entry.refs:
+ if ":" not in ref:
+ lines.append(f" └ {ref}: (malformed)")
+ continue
+ _, ent_id = ref.split(":", 1)
+ ent = entity_lookup.get(ent_id)
+ if ent is None:
+ lines.append(f" └ {ref}: (entity not found in current workspace)")
+ continue
+ body = (ent.content or "").rstrip()
+ lines.append(f" └ {ref} (ts={ent.ts or '?'}, label={ent.label!r}):")
+ for src_line in body.splitlines():
+ lines.append(f" {src_line}")
+ return "\n".join(lines)
+
+
+def annotate_l3_line_with_evidence(
+ line_number: int,
+ entry: Entry,
+ *,
+ l2_entry_lookup: dict[str, Entry],
+) -> str:
+ """Render one L3 bullet + every L2 entry it cites, full text + refs."""
+ lines: list[str] = [
+ f"line {line_number}: {entry.text} [^{entry.id}]",
+ f" section: {entry.section}",
+ ]
+ if not entry.refs:
+ lines.append(" sources: (none)")
+ return "\n".join(lines)
+ lines.append(f" sources ({len(entry.refs)}):")
+ for ref in entry.refs:
+ if not is_entry_id(ref):
+ lines.append(f" └ {ref}: (malformed L2 id)")
+ continue
+ src = l2_entry_lookup.get(ref)
+ if src is None:
+ lines.append(f" └ {ref}: (L2 entry not found)")
+ continue
+ lines.append(f" └ {ref} (section={src.section!r}):")
+ lines.append(f" {src.text}")
+ if src.refs:
+ lines.append(f" upstream refs: {', '.join(src.refs)}")
+ return "\n".join(lines)
+
+
+# ── Internals ───────────────────────────────────────────────────────────
+
+
+def _entity_marker(surface: str, entity_id: str) -> str:
+ return f"@entity {surface}:{entity_id}"
+
+
+def _format_meta(ent: Entity) -> str:
+ if not ent.metadata:
+ return ""
+ bits = [
+ f"{k}={v}"
+ for k, v in ent.metadata.items()
+ if v not in (None, "", [], {})
+ ]
+ return " ".join(bits)
+
+
+def _normalize_allowed_ref(ref: str, allowed: set[str]) -> str | None:
+ """Return the canonical allowed ref when the model added label text.
+
+ LLMs often copy a rendered source as ``<label>:chat:<id>`` even though
+ the prompt asks for ``chat:<id>``. Treat that as a recoverable citation
+ as long as it unambiguously ends with an allowed chunk-local ref.
+ """
+ candidate = _strip_ref_wrappers(str(ref).strip())
+ if candidate in allowed and is_valid_ref(candidate):
+ return candidate
+ for allowed_ref in sorted(allowed, key=len, reverse=True):
+ if not is_valid_ref(allowed_ref):
+ continue
+ if _has_ref_suffix(candidate, allowed_ref):
+ return allowed_ref
+ return None
+
+
+def _strip_ref_wrappers(ref: str) -> str:
+ return ref.strip().strip("`[](){}<>").lstrip("^").strip()
+
+
+def _has_ref_suffix(candidate: str, allowed_ref: str) -> bool:
+ if candidate == allowed_ref:
+ return True
+ if not candidate.endswith(allowed_ref):
+ return False
+ prefix = candidate[: -len(allowed_ref)]
+ if not prefix:
+ return True
+ # Common hallucinated forms: "Title:chat:id", "Title?chat:id",
+ # "[^m_id]". Do not accept alnum/underscore adjacency.
+ return prefix[-1] in {":", ":", "?", "?", "#", "/", "|", " ", "\t", "\n", "^"}
+
+
+def _dedupe(refs: list[str]) -> list[str]:
+ seen: set[str] = set()
+ out: list[str] = []
+ for ref in refs:
+ if ref in seen:
+ continue
+ seen.add(ref)
+ out.append(ref)
+ return out
+
+
+def _refs_overlapping_span(
+ markers: list[tuple[int, str]], *, text_len: int, start: int, end: int
+) -> set[str]:
+ allowed: set[str] = set()
+ ordered = sorted(markers, key=lambda item: item[0])
+ for idx, (block_start, ref) in enumerate(ordered):
+ block_end = ordered[idx + 1][0] if idx + 1 < len(ordered) else text_len
+ if block_start < end and block_end > start:
+ allowed.add(ref)
+ return allowed
+
+
+def collect_l2_entries(docs: dict[str, Document]) -> dict[str, list[Entry]]:
+ """Helper for L3 — pull all entries from a {surface: Document} map."""
+ return {surface: doc.all_entries() for surface, doc in docs.items()}
+
+
+__all__ = [
+ "ExtractedFact",
+ "annotate_l2_line_with_evidence",
+ "annotate_l3_line_with_evidence",
+ "collect_l2_entries",
+ "refs_in_chunk_l2",
+ "refs_in_chunk_l3",
+ "refs_in_span_l2",
+ "refs_in_span_l3",
+ "render_l2_entries_for_concat",
+ "render_traces_for_concat",
+ "validate_fact_refs",
+]
diff --git a/deeptutor/services/memory/consolidator/runs.py b/deeptutor/services/memory/consolidator/runs.py
new file mode 100644
index 000000000..1c575f063
--- /dev/null
+++ b/deeptutor/services/memory/consolidator/runs.py
@@ -0,0 +1,424 @@
+"""Persistent, cancellable consolidator runs.
+
+A "run" is one invocation of :func:`run_update` / :func:`run_audit` /
+:func:`run_dedup`. The run is owned by an asyncio task; events flow
+through a buffered ring so a disconnecting client can re-attach by
+posting ``since=<cursor>`` to the events endpoint and replay everything
+it missed.
+
+Why an in-memory manager instead of a DB:
+- Memory consolidator runs are minutes-long at most.
+- Crash / restart wipes them — that's acceptable; the docs themselves
+ are atomically written per step and the meta-id-diff still gives us
+ "what's new since last refresh" correctness on restart.
+
+Concurrency rules
+-----------------
+At most one **active** run per ``(layer, key)``. Starting a second run
+while the first is active returns ``RunBusyError``. Once a run reaches
+a terminal status (``done`` / ``cancelled`` / ``error``) it stays in
+the registry indefinitely so the UI can re-attach to see the final
+trace; older runs evict on FIFO when ``_MAX_HISTORY`` is exceeded.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from contextvars import ContextVar
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+import logging
+import os
+from pathlib import Path
+import tempfile
+from typing import Any, Awaitable, Callable, Literal
+import uuid
+
+logger = logging.getLogger(__name__)
+
+RunMode = Literal["update", "audit", "dedup"]
+RunStatus = Literal["queued", "running", "cancelled", "done", "error"]
+
+_MAX_EVENTS_PER_RUN = 2000
+_MAX_HISTORY = 200
+
+
+@dataclass
+class RunEvent:
+ seq: int # 0-based, monotonic per run
+ ts: str # ISO-8601 UTC
+ payload: dict[str, Any]
+
+
+@dataclass
+class UndoCheckpoint:
+ id: str
+ ts: str
+ layer: str
+ key: str
+ path: str
+ existed: bool
+ previous_content: str
+ action: str
+ turn: int | None = None
+ label: str | None = None
+
+
+@dataclass
+class Run:
+ id: str
+ layer: str
+ key: str
+ mode: RunMode
+ params: dict[str, Any]
+ language: str
+ user_label: str
+ status: RunStatus = "queued"
+ started_at: str = ""
+ ended_at: str | None = None
+ error: str | None = None
+ events: list[RunEvent] = field(default_factory=list)
+ undo_stack: list[UndoCheckpoint] = field(default_factory=list)
+ _waiters: list[asyncio.Event] = field(default_factory=list, repr=False)
+ _task: asyncio.Task | None = field(default=None, repr=False)
+ _cancel_flag: asyncio.Event = field(default_factory=asyncio.Event, repr=False)
+
+ @property
+ def active(self) -> bool:
+ return self.status in ("queued", "running")
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "id": self.id,
+ "layer": self.layer,
+ "key": self.key,
+ "mode": self.mode,
+ "params": self.params,
+ "language": self.language,
+ "status": self.status,
+ "started_at": self.started_at,
+ "ended_at": self.ended_at,
+ "error": self.error,
+ "event_count": len(self.events),
+ "undo_count": len(self.undo_stack),
+ }
+
+
+class RunBusyError(RuntimeError):
+ """Raised when a (layer, key) already has an active run."""
+
+
+# ContextVar holds the current Run for handlers running inside the task.
+# Mode code uses :func:`emit` indirectly via ``modes._runtime.emit``;
+# we install our own on_event that pushes into the active run too.
+_current_run: ContextVar[Run | None] = ContextVar("memory_run", default=None)
+
+
+class RunManager:
+ """Process-wide singleton — one manager owns every consolidator run.
+
+ The instance is created on first call to :func:`get_run_manager`.
+ """
+
+ def __init__(self) -> None:
+ self._runs: dict[str, Run] = {}
+ self._order: list[str] = [] # FIFO for eviction
+ self._active: dict[tuple[str, str], str] = {}
+ self._lock = asyncio.Lock()
+
+ # ── Lookup ─────────────────────────────────────────────────────────
+
+ def get(self, run_id: str) -> Run | None:
+ return self._runs.get(run_id)
+
+ def active_for(self, layer: str, key: str) -> Run | None:
+ run_id = self._active.get((layer, key))
+ if run_id is None:
+ return None
+ run = self._runs.get(run_id)
+ return run if run is not None and run.active else None
+
+ def list_for(self, layer: str | None = None, key: str | None = None) -> list[Run]:
+ out: list[Run] = []
+ for rid in self._order:
+ run = self._runs.get(rid)
+ if run is None:
+ continue
+ if layer is not None and run.layer != layer:
+ continue
+ if key is not None and run.key != key:
+ continue
+ out.append(run)
+ return out
+
+ # ── Start ──────────────────────────────────────────────────────────
+
+ async def start(
+ self,
+ *,
+ layer: str,
+ key: str,
+ mode: RunMode,
+ runner: Callable[[Callable[[dict[str, Any]], Awaitable[None]]], Awaitable[None]],
+ params: dict[str, Any] | None = None,
+ language: str = "en",
+ user_label: str = "anonymous",
+ ) -> Run:
+ """Register and kick off a new run.
+
+ ``runner`` is an awaitable factory: takes a ``on_event`` callback
+ and runs the consolidator mode. The manager wires the callback to
+ the event buffer + waiter machinery.
+ """
+ async with self._lock:
+ if self.active_for(layer, key) is not None:
+ raise RunBusyError(
+ f"a run is already in progress for {layer}/{key}"
+ )
+ run = Run(
+ id=uuid.uuid4().hex,
+ layer=layer,
+ key=key,
+ mode=mode,
+ params=dict(params or {}),
+ language=language,
+ user_label=user_label,
+ status="queued",
+ started_at=_now_iso(),
+ )
+ self._runs[run.id] = run
+ self._order.append(run.id)
+ self._active[(layer, key)] = run.id
+ self._evict_if_needed()
+
+ run._task = asyncio.create_task(self._drive(run, runner))
+ return run
+
+ async def cancel(self, run_id: str) -> bool:
+ run = self._runs.get(run_id)
+ if run is None or not run.active:
+ return False
+ run._cancel_flag.set()
+ if run._task is not None and not run._task.done():
+ run._task.cancel()
+ return True
+
+ async def undo_last(self, run_id: str) -> RunEvent | None:
+ """Restore the document snapshot before the latest run write."""
+ run = self._runs.get(run_id)
+ if run is None:
+ raise KeyError(run_id)
+ if run.active:
+ raise RunBusyError("cancel the active run before undoing memory edits")
+ if not run.undo_stack:
+ return None
+
+ checkpoint = run.undo_stack.pop()
+ path = Path(checkpoint.path)
+ if checkpoint.existed:
+ await asyncio.to_thread(_atomic_write, path, checkpoint.previous_content)
+ else:
+ await asyncio.to_thread(_remove_if_exists, path)
+
+ return await self._emit(
+ run,
+ {
+ "stage": "undo_applied",
+ "run_id": run.id,
+ "undo_id": checkpoint.id,
+ "undo_depth": len(run.undo_stack),
+ "layer": checkpoint.layer,
+ "key": checkpoint.key,
+ "turn": checkpoint.turn,
+ "label": checkpoint.label,
+ "action": checkpoint.action,
+ },
+ )
+
+ # ── Event subscription ─────────────────────────────────────────────
+
+ async def wait_for_events(self, run: Run, *, since: int) -> list[RunEvent]:
+ """Return events since cursor; block until new ones arrive or done."""
+ if since < 0:
+ since = 0
+ # Fast path: events already buffered past cursor.
+ if since < len(run.events):
+ return run.events[since:]
+ if not run.active:
+ return []
+ waiter = asyncio.Event()
+ run._waiters.append(waiter)
+ try:
+ await waiter.wait()
+ finally:
+ try:
+ run._waiters.remove(waiter)
+ except ValueError:
+ pass
+ if since < len(run.events):
+ return run.events[since:]
+ return []
+
+ # ── Drive ──────────────────────────────────────────────────────────
+
+ async def _drive(
+ self,
+ run: Run,
+ runner: Callable[[Callable[[dict[str, Any]], Awaitable[None]]], Awaitable[None]],
+ ) -> None:
+ token = _current_run.set(run)
+ run.status = "running"
+ await self._emit(run, {"stage": "run_started", "run_id": run.id, "mode": run.mode})
+ try:
+ async def on_event(evt: dict[str, Any]) -> None:
+ await self._emit(run, evt)
+
+ await runner(on_event)
+ if run.status == "running":
+ run.status = "done"
+ except asyncio.CancelledError:
+ run.status = "cancelled"
+ await self._emit(run, {"stage": "cancelled"})
+ except Exception as exc: # noqa: BLE001
+ run.status = "error"
+ run.error = str(exc)
+ logger.warning(
+ "consolidator run failed (id=%s layer=%s key=%s mode=%s): %s",
+ run.id,
+ run.layer,
+ run.key,
+ run.mode,
+ exc,
+ exc_info=True,
+ )
+ await self._emit(run, {"stage": "error", "message": str(exc)})
+ finally:
+ run.ended_at = _now_iso()
+ await self._emit(run, {"stage": "run_ended", "status": run.status})
+ self._active.pop((run.layer, run.key), None)
+ # Wake any remaining waiters so they observe the terminal state.
+ for w in list(run._waiters):
+ w.set()
+ _current_run.reset(token)
+
+ async def _emit(self, run: Run, payload: dict[str, Any]) -> RunEvent:
+ event = RunEvent(seq=len(run.events), ts=_now_iso(), payload=payload)
+ run.events.append(event)
+ if len(run.events) > _MAX_EVENTS_PER_RUN:
+ # Drop the oldest non-meta event but renumber tail to keep
+ # monotonic seq stable — clients use seq to resume.
+ run.events.pop(0)
+ for i, ev in enumerate(run.events):
+ run.events[i] = RunEvent(seq=i, ts=ev.ts, payload=ev.payload)
+ for w in list(run._waiters):
+ w.set()
+ return event
+
+ def _evict_if_needed(self) -> None:
+ while len(self._order) > _MAX_HISTORY:
+ old = self._order.pop(0)
+ run = self._runs.pop(old, None)
+ if run is not None and run.active:
+ # Active runs are protected from eviction.
+ self._runs[old] = run
+ self._order.insert(0, old)
+ return
+
+
+_manager: RunManager | None = None
+
+
+def get_run_manager() -> RunManager:
+ global _manager
+ if _manager is None:
+ _manager = RunManager()
+ return _manager
+
+
+def reset_run_manager_for_tests() -> None:
+ global _manager
+ _manager = None
+
+
+def current_run() -> Run | None:
+ """Return the run currently driving the active task, if any.
+
+ Used by the LLM-IO event emitter so it can attach per-turn payloads
+ to whichever run is calling out to the model.
+ """
+ return _current_run.get()
+
+
+def push_undo_checkpoint(
+ *,
+ layer: str,
+ key: str,
+ path: Path,
+ existed: bool,
+ previous_content: str,
+ action: str,
+ turn: int | None = None,
+ label: str | None = None,
+) -> int:
+ """Register a per-write rollback snapshot on the active run."""
+ run = _current_run.get()
+ if run is None:
+ return 0
+ run.undo_stack.append(
+ UndoCheckpoint(
+ id=uuid.uuid4().hex,
+ ts=_now_iso(),
+ layer=layer,
+ key=key,
+ path=str(path),
+ existed=existed,
+ previous_content=previous_content,
+ action=action,
+ turn=turn,
+ label=label,
+ )
+ )
+ return len(run.undo_stack)
+
+
+def _now_iso() -> str:
+ return datetime.now(tz=timezone.utc).isoformat()
+
+
+def _atomic_write(path: Path, content: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp_str = tempfile.mkstemp(prefix=path.name + ".", dir=str(path.parent))
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ fh.write(content)
+ fh.flush()
+ os.fsync(fh.fileno())
+ os.replace(tmp_str, path)
+ finally:
+ if os.path.exists(tmp_str):
+ try:
+ os.remove(tmp_str)
+ except OSError:
+ pass
+
+
+def _remove_if_exists(path: Path) -> None:
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ return
+
+
+__all__ = [
+ "Run",
+ "RunBusyError",
+ "RunEvent",
+ "RunManager",
+ "RunMode",
+ "RunStatus",
+ "UndoCheckpoint",
+ "current_run",
+ "get_run_manager",
+ "push_undo_checkpoint",
+ "reset_run_manager_for_tests",
+]
diff --git a/deeptutor/services/memory/document.py b/deeptutor/services/memory/document.py
new file mode 100644
index 000000000..acf7ff418
--- /dev/null
+++ b/deeptutor/services/memory/document.py
@@ -0,0 +1,237 @@
+"""Markdown documents with footnote-style citations.
+
+Each L2/L3 file is a markdown document of the form::
+
+ # <Title>
+
+ ## <section_a>
+ - <text> [^1][^2] <!--m_xxx-->
+ - <text> [^1] <!--m_yyy-->
+
+ ## <section_b>
+ - <text> [^3] <!--m_zzz-->
+
+ ---
+
+ [^1]: notebook:abc
+ [^2]: chat:def
+ [^3]: chat:ghi
+
+Footnote labels are *integers* assigned per-document in first-appearance
+order over the bullet stream. Two entries citing the same source share a
+label, so duplicate footnote rows disappear from the rendered view.
+
+The HTML comment after each bullet (``<!--m_xxx-->``) is the entry id
+anchor. It survives round-trips and is used by audit / dedup line views
+and by ``DELETE /entry/{id}``. Parser also accepts the *legacy* format
+where the bullet ends in ``[^m_xxx]`` and footnote rows are
+``[^m_xxx]: ref1, ref2`` — this lets pre-existing docs continue working
+until the next save migrates them to the new layout.
+
+Parsing and serialization are pure functions — no I/O, no LLM. The
+round-trip ``serialize(parse(x))`` is idempotent for any document
+produced by ``serialize``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import re
+
+_ENTRY_ID_RE = r"m_[0-9A-HJKMNP-TV-Z]{26}"
+
+_TITLE_RE = re.compile(r"^#\s+(.+?)\s*$")
+_SECTION_RE = re.compile(r"^##\s+(.+?)\s*$")
+
+# New bullet: "- text [^1], [^3] <!--m_xxx-->"
+# Markers are optional (an entry may cite no refs); commas + whitespace
+# between markers are tolerated so the rendered superscripts read
+# ``¹, ³`` instead of the visually-merged ``¹³``.
+_NEW_BULLET_RE = re.compile(
+ rf"^\s*-\s+(?P<text>.*?)(?P<markers>(?:\s*,?\s*\[\^[^\]]+\])*)\s*<!--\s*(?P<id>{_ENTRY_ID_RE})\s*-->\s*$"
+)
+# Legacy bullet: "- text[^m_xxx]"
+_OLD_BULLET_RE = re.compile(rf"^\s*-\s+(?P<text>.*?)\[\^(?P<id>{_ENTRY_ID_RE})\]\s*$")
+
+# Legacy footnote def: "[^m_xxx]: ref1, ref2"
+_OLD_FOOTNOTE_RE = re.compile(rf"^\[\^(?P<id>{_ENTRY_ID_RE})\]:\s*(?P<refs>.*?)\s*$")
+# New footnote def: "[^1]: notebook:abc" (label is non-m_xxx)
+_NEW_FOOTNOTE_RE = re.compile(r"^\[\^(?P<label>[^\]]+)\]:\s*(?P<ref>.*?)\s*$")
+
+_MARKER_RE = re.compile(r"\[\^([^\]]+)\]")
+
+
+@dataclass
+class Entry:
+ id: str
+ section: str
+ text: str
+ refs: list[str] = field(default_factory=list)
+
+
+@dataclass
+class Document:
+ title: str = ""
+ sections: list[tuple[str, list[Entry]]] = field(default_factory=list)
+
+ def all_entries(self) -> list[Entry]:
+ return [e for _, entries in self.sections for e in entries]
+
+ def find(self, entry_id: str) -> Entry | None:
+ for _, entries in self.sections:
+ for entry in entries:
+ if entry.id == entry_id:
+ return entry
+ return None
+
+ def section_entries(self, name: str) -> list[Entry]:
+ """Return the entry list for ``name``, creating the section if absent."""
+ for section, entries in self.sections:
+ if section == name:
+ return entries
+ entries: list[Entry] = []
+ self.sections.append((name, entries))
+ return entries
+
+ def remove(self, entry_id: str) -> bool:
+ for _, entries in self.sections:
+ for i, entry in enumerate(entries):
+ if entry.id == entry_id:
+ del entries[i]
+ return True
+ return False
+
+
+def parse(md: str) -> Document:
+ """Parse memory md in either the new (ref-keyed) or legacy (entry-keyed) format."""
+ raw_lines = md.splitlines()
+
+ # Pass 1 — collect every footnote definition. We accept BOTH:
+ # * new ref-keyed: ``[^1]: notebook:abc`` → ref by label
+ # * old entry-keyed: ``[^m_xxx]: r1, r2`` → refs by entry id
+ refs_by_entry: dict[str, list[str]] = {}
+ ref_by_label: dict[str, str] = {}
+ for raw in raw_lines:
+ line = raw.rstrip()
+ m_old_fn = _OLD_FOOTNOTE_RE.match(line)
+ if m_old_fn:
+ refs_raw = m_old_fn.group("refs")
+ refs_by_entry[m_old_fn.group("id")] = [
+ r.strip() for r in refs_raw.split(",") if r.strip()
+ ]
+ continue
+ m_new_fn = _NEW_FOOTNOTE_RE.match(line)
+ if m_new_fn:
+ label = m_new_fn.group("label")
+ if label.startswith("m_"):
+ # Skip — that was an entry-keyed row already handled above.
+ continue
+ ref_by_label[label] = m_new_fn.group("ref").strip()
+
+ # Pass 2 — title, sections, bullets.
+ doc = Document()
+ current_entries: list[Entry] | None = None
+ current_section: str | None = None
+ for raw in raw_lines:
+ line = raw.rstrip()
+
+ if not doc.title:
+ m_title = _TITLE_RE.match(line)
+ if m_title:
+ doc.title = m_title.group(1).strip()
+ continue
+
+ m_section = _SECTION_RE.match(line)
+ if m_section:
+ current_section = m_section.group(1).strip()
+ current_entries = []
+ doc.sections.append((current_section, current_entries))
+ continue
+
+ # New format first: bullet ends with HTML-comment entry-id anchor.
+ m_new_b = _NEW_BULLET_RE.match(line)
+ if m_new_b and current_entries is not None and current_section is not None:
+ entry_id = m_new_b.group("id")
+ text = m_new_b.group("text").rstrip()
+ markers = _MARKER_RE.findall(m_new_b.group("markers") or "")
+ entry_refs: list[str] = []
+ for marker in markers:
+ ref = ref_by_label.get(marker)
+ if ref is not None and ref not in entry_refs:
+ entry_refs.append(ref)
+ current_entries.append(
+ Entry(id=entry_id, section=current_section, text=text, refs=entry_refs)
+ )
+ continue
+
+ # Legacy bullet: refs come from refs_by_entry built in pass 1.
+ m_old_b = _OLD_BULLET_RE.match(line)
+ if m_old_b and current_entries is not None and current_section is not None:
+ entry_id = m_old_b.group("id")
+ text = m_old_b.group("text").strip()
+ current_entries.append(
+ Entry(
+ id=entry_id,
+ section=current_section,
+ text=text,
+ refs=list(refs_by_entry.get(entry_id, [])),
+ )
+ )
+ continue
+
+ return doc
+
+
+def serialize(doc: Document) -> str:
+ """Render the doc in the new consolidated, ref-keyed format.
+
+ Every unique ref across all entries gets one footnote label, assigned
+ in first-appearance order. Bullets cite their refs as ``[^1][^3]``
+ inline. The entry id is preserved as a trailing HTML comment so the
+ round-trip ``parse(serialize(d)) == d``.
+ """
+ # 1. Build the consolidated ref → label map in first-appearance order.
+ ref_order: list[str] = []
+ ref_to_label: dict[str, int] = {}
+ for entry in doc.all_entries():
+ for ref in entry.refs:
+ if ref in ref_to_label:
+ continue
+ ref_to_label[ref] = len(ref_order) + 1
+ ref_order.append(ref)
+
+ lines: list[str] = []
+ if doc.title:
+ lines.append(f"# {doc.title}")
+ lines.append("")
+
+ for section, entries in doc.sections:
+ if not entries:
+ continue
+ lines.append(f"## {section}")
+ lines.append("")
+ for entry in entries:
+ # ``, ``-separate markers so the rendered superscripts read
+ # "¹, ²" not "¹²" — important when the same bullet cites two
+ # different sources.
+ markers = ", ".join(
+ f"[^{ref_to_label[r]}]" for r in entry.refs if r in ref_to_label
+ )
+ text = entry.text.rstrip()
+ if markers:
+ lines.append(f"- {text} {markers} <!--{entry.id}-->")
+ else:
+ lines.append(f"- {text} <!--{entry.id}-->")
+ lines.append("")
+
+ if ref_order:
+ lines.append("---")
+ lines.append("")
+ for i, ref in enumerate(ref_order, start=1):
+ lines.append(f"[^{i}]: {ref}")
+ lines.append("")
+
+ return "\n".join(lines).rstrip() + "\n"
+
+
+__all__ = ["Document", "Entry", "parse", "serialize"]
diff --git a/deeptutor/services/memory/ids.py b/deeptutor/services/memory/ids.py
new file mode 100644
index 000000000..282cd8ead
--- /dev/null
+++ b/deeptutor/services/memory/ids.py
@@ -0,0 +1,82 @@
+"""Stable, time-ordered identifiers for trace events and document entries.
+
+Format: 26-character Crockford-base32 (ULID-style).
+
+- Trace ids: ``<surface>:<ULID>`` — e.g. ``chat:01HZK4ABCDEFGHJKMNPQRSTVWX``
+- Entry ids: ``m_<ULID>`` — used in MD footnote labels
+
+The ULID's leading 10 characters encode a millisecond timestamp, giving
+natural chronological sort across files and within a file.
+"""
+
+from __future__ import annotations
+
+import re
+import secrets
+import time
+
+_BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" # Crockford
+_ULID_TS_LEN = 10
+_ULID_RAND_LEN = 16
+_ULID_LEN = _ULID_TS_LEN + _ULID_RAND_LEN
+
+_ENTRY_RE = re.compile(r"^m_[0-9A-HJKMNP-TV-Z]{26}$")
+_TRACE_RE = re.compile(r"^[a-z][a-z0-9_-]*:[0-9A-HJKMNP-TV-Z]{26}$")
+# Snapshot ref points to a current workspace entity. The id portion is
+# whatever the per-surface adapter chose (doc_id / record_id / kb_name /
+# bot name / session_id / "session:question" composites). Permissive
+# enough to allow embedded ``:``; restrictive enough to keep refs safe
+# to embed in the comma-separated footnote serialization.
+_SNAPSHOT_RE = re.compile(r"^[a-z][a-z0-9_-]*:[A-Za-z0-9_.:\-]+$")
+# L3 surface ref — bare surface name like ``chat``, ``notebook``. L3 is
+# a synthesis layer that points at L2 *files*, not L2 entries, so its
+# refs need no id portion. Whitelist (not a loose regex) so a malformed
+# ref like ``not-an-id`` doesn't accidentally validate. Mirrors
+# :data:`paths.SURFACES`; if you add a surface, add it here too.
+_SHORTNAME_REFS = frozenset(
+ {"chat", "notebook", "quiz", "kb", "book", "tutorbot", "cowriter"}
+)
+
+
+def _encode(n: int, length: int) -> str:
+ chars: list[str] = []
+ for _ in range(length):
+ chars.append(_BASE32[n & 0x1F])
+ n >>= 5
+ return "".join(reversed(chars))
+
+
+def new_ulid() -> str:
+ ts = int(time.time() * 1000) & ((1 << (_ULID_TS_LEN * 5)) - 1)
+ rand = secrets.randbits(_ULID_RAND_LEN * 5)
+ return _encode(ts, _ULID_TS_LEN) + _encode(rand, _ULID_RAND_LEN)
+
+
+def new_entry_id() -> str:
+ return f"m_{new_ulid()}"
+
+
+def new_trace_id(surface: str) -> str:
+ return f"{surface}:{new_ulid()}"
+
+
+def is_entry_id(s: str) -> bool:
+ return bool(_ENTRY_RE.match(s))
+
+
+def is_trace_id(s: str) -> bool:
+ return bool(_TRACE_RE.match(s))
+
+
+def is_snapshot_ref(s: str) -> bool:
+ return bool(_SNAPSHOT_RE.match(s))
+
+
+def is_shortname_ref(s: str) -> bool:
+ """Bare surface name — the form used by L3 refs (whitelist)."""
+ return s in _SHORTNAME_REFS
+
+
+def is_valid_ref(s: str) -> bool:
+ """Any form of ref the ops validator accepts."""
+ return is_entry_id(s) or is_trace_id(s) or is_snapshot_ref(s) or is_shortname_ref(s)
diff --git a/deeptutor/services/memory/ops.py b/deeptutor/services/memory/ops.py
new file mode 100644
index 000000000..c9a9d99e0
--- /dev/null
+++ b/deeptutor/services/memory/ops.py
@@ -0,0 +1,151 @@
+"""Atomic add/edit/delete operations on memory documents.
+
+A batch of ops is validated as a whole and applied only if all ops pass.
+Conflicting ops (e.g. ``delete`` and ``edit`` on the same id within one
+batch) reject the entire batch — the LLM doesn't get to self-contradict.
+
+Pure functions; no I/O, no LLM.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Literal, Union
+
+from deeptutor.services.memory.document import Document, Entry
+from deeptutor.services.memory.ids import is_entry_id, is_valid_ref, new_entry_id
+
+_MAX_TEXT_LEN = 240
+_MAX_SECTION_LEN = 80
+_DELETE_REASONS = frozenset({"contradicted", "superseded", "stale", "low-signal"})
+
+
+@dataclass(frozen=True)
+class AddOp:
+ section: str
+ text: str
+ refs: list[str]
+ op: Literal["add"] = "add"
+
+
+@dataclass(frozen=True)
+class EditOp:
+ target_id: str
+ new_text: str
+ new_refs: list[str]
+ op: Literal["edit"] = "edit"
+
+
+@dataclass(frozen=True)
+class DeleteOp:
+ target_id: str
+ reason: str
+ op: Literal["delete"] = "delete"
+
+
+Op = Union[AddOp, EditOp, DeleteOp]
+
+
+@dataclass
+class OpResult:
+ op: Op
+ status: Literal["applied"]
+ entry_id: str | None = None # populated for add ops
+ detail: str = ""
+
+
+@dataclass
+class ApplyReport:
+ accepted: bool
+ results: list[OpResult] = field(default_factory=list)
+ reason: str = ""
+
+
+class OpValidationError(Exception):
+ """Raised when a batch fails pre-flight validation."""
+
+
+def _validate(doc: Document, ops: list[Op]) -> None:
+ edits: set[str] = set()
+ deletes: set[str] = set()
+
+ for op in ops:
+ if isinstance(op, AddOp):
+ if not op.text or len(op.text) > _MAX_TEXT_LEN:
+ raise OpValidationError(
+ f"add: text length must be 1..{_MAX_TEXT_LEN} (got {len(op.text)})"
+ )
+ if not op.section or len(op.section) > _MAX_SECTION_LEN:
+ raise OpValidationError(f"add: invalid section {op.section!r}")
+ if not op.refs:
+ raise OpValidationError("add: refs must be non-empty")
+ for ref in op.refs:
+ if not is_valid_ref(ref):
+ raise OpValidationError(f"add: malformed ref {ref!r}")
+ elif isinstance(op, EditOp):
+ if not is_entry_id(op.target_id):
+ raise OpValidationError(f"edit: malformed target_id {op.target_id!r}")
+ if doc.find(op.target_id) is None:
+ raise OpValidationError(f"edit: target_id {op.target_id} not found")
+ if not op.new_text or len(op.new_text) > _MAX_TEXT_LEN:
+ raise OpValidationError(
+ f"edit: text length must be 1..{_MAX_TEXT_LEN} (got {len(op.new_text)})"
+ )
+ if not op.new_refs:
+ raise OpValidationError("edit: refs must be non-empty")
+ for ref in op.new_refs:
+ if not is_valid_ref(ref):
+ raise OpValidationError(f"edit: malformed ref {ref!r}")
+ if op.target_id in deletes:
+ raise OpValidationError(
+ f"batch conflict: edit and delete on same id {op.target_id}"
+ )
+ edits.add(op.target_id)
+ elif isinstance(op, DeleteOp):
+ if not is_entry_id(op.target_id):
+ raise OpValidationError(f"delete: malformed target_id {op.target_id!r}")
+ if doc.find(op.target_id) is None:
+ raise OpValidationError(f"delete: target_id {op.target_id} not found")
+ if op.reason not in _DELETE_REASONS:
+ raise OpValidationError(
+ f"delete: reason must be one of {sorted(_DELETE_REASONS)}"
+ )
+ if op.target_id in edits:
+ raise OpValidationError(
+ f"batch conflict: edit and delete on same id {op.target_id}"
+ )
+ deletes.add(op.target_id)
+ else:
+ raise OpValidationError(f"unknown op {type(op).__name__}")
+
+
+def apply(doc: Document, ops: list[Op]) -> ApplyReport:
+ """Apply ops as an atomic batch. Mutates ``doc`` in place on success.
+
+ On validation failure the document is untouched and the report carries
+ ``accepted=False`` with ``reason``.
+ """
+ try:
+ _validate(doc, ops)
+ except OpValidationError as exc:
+ return ApplyReport(accepted=False, reason=str(exc))
+
+ results: list[OpResult] = []
+ for op in ops:
+ if isinstance(op, AddOp):
+ new_id = new_entry_id()
+ doc.section_entries(op.section).append(
+ Entry(id=new_id, section=op.section, text=op.text, refs=list(op.refs))
+ )
+ results.append(OpResult(op=op, status="applied", entry_id=new_id))
+ elif isinstance(op, EditOp):
+ entry = doc.find(op.target_id)
+ assert entry is not None # _validate ensured this
+ entry.text = op.new_text
+ entry.refs = list(op.new_refs)
+ results.append(OpResult(op=op, status="applied"))
+ else: # DeleteOp
+ doc.remove(op.target_id)
+ results.append(OpResult(op=op, status="applied", detail=op.reason))
+
+ return ApplyReport(accepted=True, results=results)
diff --git a/deeptutor/services/memory/paths.py b/deeptutor/services/memory/paths.py
new file mode 100644
index 000000000..fdf75d119
--- /dev/null
+++ b/deeptutor/services/memory/paths.py
@@ -0,0 +1,76 @@
+"""Path resolution for the three-layer memory subsystem.
+
+Layout under the per-user memory root::
+
+ trace/<surface>/<YYYY-MM-DD>.jsonl (L1, append-only)
+ L2/<surface>.md (L2, per-surface summaries)
+ L3/<recent|profile|scope|preferences>.md (L3, cross-surface)
+ backup/<timestamp>/... (v1 migration archive)
+
+The root itself is resolved via :class:`PathService` so the multi-user
+context (workspace_root) is picked up at call time, not import time.
+"""
+
+from __future__ import annotations
+
+from datetime import date
+from pathlib import Path
+from typing import Literal, get_args
+
+from deeptutor.services.path_service import get_path_service
+
+Surface = Literal[
+ "chat",
+ "notebook",
+ "quiz",
+ "kb",
+ "book",
+ "tutorbot",
+ "cowriter",
+]
+L3Slot = Literal["recent", "profile", "scope", "preferences"]
+
+SURFACES: tuple[Surface, ...] = get_args(Surface)
+L3_SLOTS: tuple[L3Slot, ...] = get_args(L3Slot)
+
+
+def memory_root() -> Path:
+ return get_path_service().get_memory_dir()
+
+
+def trace_dir(surface: Surface) -> Path:
+ return memory_root() / "trace" / surface
+
+
+def trace_file(surface: Surface, day: date) -> Path:
+ return trace_dir(surface) / f"{day.isoformat()}.jsonl"
+
+
+def l2_dir() -> Path:
+ return memory_root() / "L2"
+
+
+def l2_file(surface: Surface) -> Path:
+ return l2_dir() / f"{surface}.md"
+
+
+def l3_dir() -> Path:
+ return memory_root() / "L3"
+
+
+def l3_file(slot: L3Slot) -> Path:
+ return l3_dir() / f"{slot}.md"
+
+
+def backup_root() -> Path:
+ return memory_root() / "backup"
+
+
+def ensure_dirs() -> None:
+ """Create the directory skeleton. Idempotent."""
+ root = memory_root()
+ root.mkdir(parents=True, exist_ok=True)
+ l2_dir().mkdir(parents=True, exist_ok=True)
+ l3_dir().mkdir(parents=True, exist_ok=True)
+ for surface in SURFACES:
+ trace_dir(surface).mkdir(parents=True, exist_ok=True)
diff --git a/deeptutor/services/memory/prompts/en.yaml b/deeptutor/services/memory/prompts/en.yaml
new file mode 100644
index 000000000..8189d17b7
--- /dev/null
+++ b/deeptutor/services/memory/prompts/en.yaml
@@ -0,0 +1,156 @@
+# Memory consolidation prompts (English).
+#
+# Used by deeptutor.services.memory.consolidator to turn raw L1 trace
+# events into L2 ops, and the seven L2 docs into L3 ops. Every prompt
+# uses the same output schema: {"ops": [...]}.
+
+system_l2: |
+ You are the memory curator for DeepTutor user {user_label}. You read
+ the user's current workspace entities (full content, not event logs)
+ for a single surface and propose surgical edit operations on that
+ surface's markdown memory document. You never chat, explain, or
+ apologise — you emit JSON only.
+
+ Today is {today}.
+
+ EVERY add/edit op MUST include `refs`: at least one entity reference
+ from the input, written as `<surface>:<entity_id>` (the `ref:` line
+ above each entity block tells you the exact string to cite). No refs
+ → do not emit. An empty `ops` list is a correct, expected output
+ when nothing material has changed.
+
+ Length cap: each `text`/`new_text` ≤ 240 characters. Be terse.
+
+ Banned phrases (unless quoted verbatim from the user, in which case
+ wrap them in 「 」): deeply, truly, mastered, expert, passionate,
+ loves, hates, always, never, fully understands.
+
+ Prefer verb phrases ("uses X", "prefers X over Y", "stuck on Z")
+ over adjectives. Quote the user's words for specific claims.
+
+ Delete reasons (enum): contradicted, superseded, stale, low-signal.
+
+user_l2: |
+ Surface: {surface}
+ Focus: {focus}
+ Suggested sections (use these names; add new sections only if
+ clearly needed): {sections}
+
+ Existing document (each entry is annotated with its `[m_xxx]` id):
+ ----
+ {existing}
+ ----
+
+ Current workspace entities (one block per item, each block shows
+ the `ref:` you must cite, the label, timestamp, metadata, and FULL
+ content):
+ ----
+ {entities}
+ ----
+
+ Changes since last refresh (informational; do NOT cite these as refs):
+ ----
+ {changes}
+ ----
+
+ Recent KB queries (only present for the `kb` surface):
+ ----
+ {kb_queries}
+ ----
+
+ Emit a JSON object with this shape exactly:
+
+ {{
+ "ops": [
+ {{"op": "add", "section": "<one of the sections>", "text": "<≤240 chars>", "refs": ["<surface>:<entity_id>", ...]}},
+ {{"op": "edit", "target_id": "<m_xxx>", "new_text": "<≤240 chars>", "new_refs": ["<surface>:<entity_id>", ...]}},
+ {{"op": "delete", "target_id": "<m_xxx>", "reason": "<contradicted|superseded|stale|low-signal>"}}
+ ]
+ }}
+
+ If nothing material changed, emit {{"ops": []}}. Do not wrap output
+ in markdown fences. Do not add any prose.
+
+system_l3: |
+ You are the cross-surface memory curator for DeepTutor user
+ {user_label}. You read the seven per-surface summaries (L2) and
+ propose surgical edit operations on ONE cross-surface document.
+ You never chat, explain, or apologise — you emit JSON only.
+
+ Today is {today}.
+
+ OBJECTIVITY IS NON-NEGOTIABLE for L3. Hard rules:
+
+ 1. Every claim MUST cite ≥1 L2 entry id in `refs` (form m_xxx).
+ No refs → do not emit.
+ 2. Banned absolutist phrasing: deeply, truly, mastered, expert,
+ passionate, loves, hates, always, never, fully understands.
+ Use only if quoting the user verbatim 「like this」.
+ 3. Forced hedge template — claims about the user must take the
+ form: "Across N <surface> interactions, the user X". Bind
+ observations to a count or a surface.
+
+ Length cap 240 chars per entry. Be terse.
+
+ Delete reasons (enum): contradicted, superseded, stale, low-signal.
+
+user_l3: |
+ Slot: {slot}
+ Focus: {focus}
+ Suggested sections: {sections}
+
+ Existing document:
+ ----
+ {existing}
+ ----
+
+ Seven L2 surface summaries (with their entry ids):
+ ----
+ {l2_corpus}
+ ----
+
+ Emit JSON in this exact shape:
+
+ {{
+ "ops": [
+ {{"op": "add", "section": "<section>", "text": "<≤240 chars, hedged>", "refs": ["m_xxx", ...]}},
+ {{"op": "edit", "target_id": "<m_xxx>", "new_text": "<≤240 chars, hedged>", "new_refs": ["m_xxx", ...]}},
+ {{"op": "delete", "target_id": "<m_xxx>", "reason": "<contradicted|superseded|stale|low-signal>"}}
+ ]
+ }}
+
+ Empty `ops` is fine and expected when no L2 changes warrant L3 motion.
+
+surfaces:
+ chat:
+ focus: "Stable misconceptions the user has surfaced, concepts they've demonstrated mastery of, and durable topics they keep returning to. Drop per-turn chatter."
+ sections: ["Misconceptions", "Mastery", "Topics"]
+ notebook:
+ focus: "Recurring note themes, formats the user prefers, and questions they keep coming back to in their notes."
+ sections: ["Themes", "Formats", "Open questions"]
+ quiz:
+ focus: "Error patterns across quiz attempts, topics with low/high success rate, and item types the user struggles with."
+ sections: ["Error patterns", "Strong topics", "Struggling topics"]
+ kb:
+ focus: "Document interests, query patterns into the knowledge base, and gaps in user's library."
+ sections: ["Interests", "Frequent queries", "Library gaps"]
+ book:
+ focus: "Reading pacing, sticking points (pages reopened or paused), and topics the user annotates heavily."
+ sections: ["Pacing", "Sticking points", "Annotation themes"]
+ tutorbot:
+ focus: "Persistent themes across tutorbot conversations and channel-specific behaviours."
+ sections: ["Themes", "Channels"]
+ cowriter:
+ focus: "Writing style preferences, recurring revisions, and topics the user drafts about."
+ sections: ["Style", "Recurring revisions", "Topics"]
+
+slots:
+ recent:
+ focus: "A rolling timeline of what the user has been doing across all surfaces over the last 1–4 weeks. Time-anchored, surface-attributed."
+ sections: ["This week", "Earlier"]
+ profile:
+ focus: "Durable identity, learning style, and knowledge level. ONLY claims supported by multiple L2 entries across surfaces. No speculation about traits not directly evidenced."
+ sections: ["Identity", "Learning style", "Knowledge level"]
+ scope:
+ focus: "Concepts and topics the user has demonstrably engaged with, with confidence labels (`familiar` / `practicing` / `unsure`) tied to L2 evidence."
+ sections: ["Familiar", "Practicing", "Unsure"]
diff --git a/deeptutor/services/memory/prompts/zh.yaml b/deeptutor/services/memory/prompts/zh.yaml
new file mode 100644
index 000000000..7c1395736
--- /dev/null
+++ b/deeptutor/services/memory/prompts/zh.yaml
@@ -0,0 +1,144 @@
+# 记忆 consolidation prompts(中文)。
+
+system_l2: |
+ 你是 DeepTutor 用户 {user_label} 的记忆策展员。你的工作是读取
+ 单个 surface 的**当前 workspace 实体内容**(不是事件流——是文档/
+ 记录/会话的完整原文),然后对该 surface 的 markdown 记忆文档
+ 发起外科式的修改操作。你不聊天、不解释、不道歉——只输出 JSON。
+
+ 今天是 {today}。
+
+ 每条 add/edit 必须带 `refs`:至少一个来自输入的实体引用,格式
+ 为 `<surface>:<entity_id>`(每个实体块上方的 `ref:` 行直接给你
+ 要引用的字符串)。没有引用就不要输出。当没有实质变化时,输出
+ 空 `ops` 数组是正确的、被期望的答案。
+
+ 长度上限:每条 `text`/`new_text` ≤ 240 字符。要简短。
+
+ 禁用词(除非引用用户原话,那要用 「 」 包起来):深刻、彻底、
+ 完美掌握、专家、热爱、总是、从来不、完全理解。
+
+ 用动词短语("使用 X"、"偏好 X 不偏好 Y"、"卡在 Z"),不用形容
+ 词。要做具体陈述就引用用户原话。
+
+ 删除理由(枚举):contradicted、superseded、stale、low-signal。
+
+user_l2: |
+ Surface: {surface}
+ Focus: {focus}
+ 建议 section(请使用这些名字,仅在必要时新增): {sections}
+
+ 当前文档(每条 entry 后标有 `[m_xxx]` 形式的 id):
+ ----
+ {existing}
+ ----
+
+ 当前 workspace 实体(一个块一个项目,每块顶端的 `ref:` 就是
+ 你必须引用的字符串,含 label / ts / metadata / 完整 content):
+ ----
+ {entities}
+ ----
+
+ 自上次 refresh 起的变更(仅供参考,不要把这些作为 refs 引用):
+ ----
+ {changes}
+ ----
+
+ 最近的 KB 查询(仅 `kb` surface 有内容):
+ ----
+ {kb_queries}
+ ----
+
+ 按以下 JSON 结构精确输出:
+
+ {{
+ "ops": [
+ {{"op": "add", "section": "<section 之一>", "text": "<≤240 字符>", "refs": ["<surface>:<entity_id>", ...]}},
+ {{"op": "edit", "target_id": "<m_xxx>", "new_text": "<≤240 字符>", "new_refs": ["<surface>:<entity_id>", ...]}},
+ {{"op": "delete", "target_id": "<m_xxx>", "reason": "<contradicted|superseded|stale|low-signal>"}}
+ ]
+ }}
+
+ 如果没有实质变化,输出 {{"ops": []}}。不要用 markdown 代码块包裹。
+ 不要输出任何额外说明文字。
+
+system_l3: |
+ 你是 DeepTutor 用户 {user_label} 的跨 surface 记忆策展员。你读取
+ 七份 per-surface 小结(L2),然后对**一份**跨 surface 的全局文档
+ 发起外科式的修改操作。你不聊天、不解释、不道歉——只输出 JSON。
+
+ 今天是 {today}。
+
+ L3 必须客观,这一条不可商量。硬规则:
+
+ 1. 每条结论必须在 `refs` 中至少引用 1 个 L2 entry id(m_xxx 形式)。
+ 没引用不要输出。
+ 2. 禁用绝对化词汇:深刻、彻底、完美掌握、专家、热爱、总是、从来
+ 不、完全理解。仅在引用用户原话「这样」时才允许使用。
+ 3. 强制 hedge 模板——关于用户的陈述必须形如:"在 N 次 <surface>
+ 互动中,用户 X"。把"观察"和"用户判断"绑死。
+
+ 长度上限:每条 240 字符。要简短。
+
+ 删除理由(枚举):contradicted、superseded、stale、low-signal。
+
+user_l3: |
+ Slot: {slot}
+ Focus: {focus}
+ 建议 section: {sections}
+
+ 当前文档:
+ ----
+ {existing}
+ ----
+
+ 七份 L2 surface 小结(含 entry id):
+ ----
+ {l2_corpus}
+ ----
+
+ 按以下 JSON 结构精确输出:
+
+ {{
+ "ops": [
+ {{"op": "add", "section": "<section>", "text": "<≤240 字符,带 hedge>", "refs": ["m_xxx", ...]}},
+ {{"op": "edit", "target_id": "<m_xxx>", "new_text": "<≤240 字符,带 hedge>", "new_refs": ["m_xxx", ...]}},
+ {{"op": "delete", "target_id": "<m_xxx>", "reason": "<contradicted|superseded|stale|low-signal>"}}
+ ]
+ }}
+
+ 没有需要变化时输出 {{"ops": []}}。
+
+surfaces:
+ chat:
+ focus: "用户暴露出来的稳定误解、已展示掌握的概念、反复回来的持久话题。临时的对话噪声不要记。"
+ sections: ["误解", "掌握", "话题"]
+ notebook:
+ focus: "笔记里反复出现的主题、用户偏好的格式、笔记里反复回到的问题。"
+ sections: ["主题", "格式偏好", "开放问题"]
+ quiz:
+ focus: "做题中的错误模式、正确率高/低的话题、用户卡住的题型。"
+ sections: ["错误模式", "擅长话题", "薄弱话题"]
+ kb:
+ focus: "感兴趣的文档、向知识库发起的查询模式、用户资料库的盲区。"
+ sections: ["兴趣方向", "高频查询", "资料盲区"]
+ book:
+ focus: "阅读节奏、卡点(被重新打开或停留的页)、用户重度批注的话题。"
+ sections: ["节奏", "卡点", "批注主题"]
+ tutorbot:
+ focus: "Tutorbot 对话中跨次出现的主题、频道相关的特定行为。"
+ sections: ["主题", "频道行为"]
+ cowriter:
+ focus: "写作风格偏好、反复改的地方、用户起草的话题。"
+ sections: ["风格", "反复修订", "话题"]
+
+slots:
+ recent:
+ focus: "用户最近 1–4 周在各 surface 上做了什么的滚动时间线。带时间,标 surface 出处。"
+ sections: ["本周", "更早"]
+ profile:
+ focus: "稳定的身份、学习风格、知识水平。仅当多个 L2 entry(跨 surface)共同支持时才能下断言。没直接证据的特质不要猜。"
+ sections: ["身份", "学习风格", "知识水平"]
+ scope:
+ focus: "用户已有实证接触的概念/话题,附置信度标签(`熟悉` / `练习中` / `不确定`),均挂回 L2 证据。"
+ sections: ["熟悉", "练习中", "不确定"]
diff --git a/deeptutor/services/memory/service.py b/deeptutor/services/memory/service.py
deleted file mode 100644
index 37ff91993..000000000
--- a/deeptutor/services/memory/service.py
+++ /dev/null
@@ -1,492 +0,0 @@
-"""
-Two-file public memory system: SUMMARY.md and PROFILE.md.
-
-- SUMMARY: Running summary of the user's learning journey (auto-updated).
-- PROFILE: User identity, preferences, knowledge levels (auto-updated).
-
-Per-bot files (SOUL.md, TOOLS.md, USER.md, etc.) live in each bot's
-workspace directory, not in the shared memory dir.
-"""
-
-from __future__ import annotations
-
-import asyncio
-from dataclasses import dataclass
-from datetime import datetime
-import logging
-from pathlib import Path
-import re
-from typing import Literal
-
-from deeptutor.services.llm import clean_thinking_tags
-from deeptutor.services.llm import stream as llm_stream
-from deeptutor.services.path_service import PathService, get_path_service
-from deeptutor.services.session.protocol import SessionStoreProtocol
-
-MemoryFile = Literal["summary", "profile"]
-MEMORY_FILES: list[MemoryFile] = ["summary", "profile"]
-
-_NO_CHANGE = "NO_CHANGE"
-
-logger = logging.getLogger(__name__)
-
-_FILENAMES: dict[MemoryFile, str] = {
- "summary": "SUMMARY.md",
- "profile": "PROFILE.md",
-}
-
-
-@dataclass
-class MemorySnapshot:
- summary: str
- profile: str
- summary_updated_at: str | None
- profile_updated_at: str | None
-
-
-@dataclass
-class MemoryUpdateResult:
- content: str
- changed: bool
- updated_at: str | None
-
-
-class MemoryService:
- """Two-file public memory: SUMMARY + PROFILE."""
-
- def __init__(
- self,
- path_service: PathService | None = None,
- store: SessionStoreProtocol | None = None,
- ) -> None:
- from deeptutor.services.session import get_session_store
-
- self.__path_service = path_service
- self._store = store or get_session_store()
- self._refresh_lock = asyncio.Lock()
- self._migrate_legacy()
-
- @property
- def _path_service(self) -> PathService:
- if self.__path_service is not None:
- return self.__path_service
- return get_path_service()
-
- @property
- def _memory_dir(self) -> Path:
- return self._path_service.get_memory_dir()
-
- def _path(self, which: MemoryFile) -> Path:
- return self._memory_dir / _FILENAMES[which]
-
- def _migrate_legacy(self) -> None:
- """One-time migration from old memory.md to the two-file system."""
- legacy = self._memory_dir / "memory.md"
- if not legacy.exists():
- return
- if self._path("profile").exists() or self._path("summary").exists():
- return
-
- content = legacy.read_text(encoding="utf-8").strip()
- if not content:
- legacy.rename(legacy.with_suffix(".md.bak"))
- return
-
- preferences, context = self._extract_legacy_sections(content)
- self._memory_dir.mkdir(parents=True, exist_ok=True)
- if preferences:
- self._path("profile").write_text(
- f"## Preferences\n{preferences}",
- encoding="utf-8",
- )
- if context:
- self._path("summary").write_text(
- f"## Learning Journey\n{context}",
- encoding="utf-8",
- )
- legacy.rename(legacy.with_suffix(".md.bak"))
-
- # ── Read ──────────────────────────────────────────────────────────
-
- def read_file(self, which: MemoryFile) -> str:
- path = self._path(which)
- if not path.exists():
- return ""
- try:
- raw = path.read_text(encoding="utf-8").strip()
- cleaned = _clean_memory_content(raw)
- if cleaned != raw:
- try:
- if cleaned:
- path.write_text(cleaned, encoding="utf-8")
- else:
- path.unlink()
- except Exception:
- pass
- return cleaned
- except Exception:
- return ""
-
- def read_summary(self) -> str:
- return self.read_file("summary")
-
- def read_profile(self) -> str:
- return self.read_file("profile")
-
- def _file_updated_at(self, which: MemoryFile) -> str | None:
- path = self._path(which)
- if not path.exists():
- return None
- try:
- return datetime.fromtimestamp(path.stat().st_mtime).astimezone().isoformat()
- except Exception:
- return None
-
- def read_snapshot(self) -> MemorySnapshot:
- return MemorySnapshot(
- summary=self.read_summary(),
- profile=self.read_profile(),
- summary_updated_at=self._file_updated_at("summary"),
- profile_updated_at=self._file_updated_at("profile"),
- )
-
- # ── Write ─────────────────────────────────────────────────────────
-
- def write_file(self, which: MemoryFile, content: str) -> MemorySnapshot:
- normalized = _clean_memory_content(str(content or ""))
- path = self._path(which)
- path.parent.mkdir(parents=True, exist_ok=True)
- if not normalized:
- if path.exists():
- path.unlink()
- else:
- path.write_text(normalized, encoding="utf-8")
- return self.read_snapshot()
-
- def write_memory(self, content: str) -> MemorySnapshot:
- """Legacy compat: write to profile (primary editable file)."""
- return self.write_file("profile", content)
-
- def clear_file(self, which: MemoryFile) -> MemorySnapshot:
- return self.write_file(which, "")
-
- def clear_memory(self) -> MemorySnapshot:
- for f in MEMORY_FILES:
- path = self._path(f)
- if path.exists():
- path.unlink()
- return self.read_snapshot()
-
- # ── Context building (injected into LLM prompts) ─────────────────
-
- def build_memory_context(
- self,
- files: list[MemoryFile] | None = None,
- max_chars: int = 4000,
- ) -> str:
- requested = {item for item in files or [] if item in MEMORY_FILES}
- if not requested:
- return ""
-
- parts: list[str] = []
-
- profile = self.read_profile() if "profile" in requested else ""
- if profile:
- parts.append(f"### User Profile\n{profile}")
-
- summary = self.read_summary() if "summary" in requested else ""
- if summary:
- parts.append(f"### Learning Context\n{summary}")
-
- if not parts:
- return ""
-
- combined = "\n\n".join(parts)
- if len(combined) > max_chars:
- combined = combined[:max_chars].rstrip() + "\n...[truncated]"
-
- return (
- "## Background Memory\n"
- "Use this memory sparingly — only when directly relevant.\n\n"
- f"{combined}"
- )
-
- def get_preferences_text(self) -> str:
- profile = self.read_profile()
- return f"## User Profile\n{profile}" if profile else ""
-
- # ── Auto-refresh from conversation ────────────────────────────────
-
- async def refresh_from_turn(
- self,
- *,
- user_message: str,
- assistant_message: str,
- session_id: str = "",
- capability: str = "",
- language: str = "en",
- timestamp: str = "",
- ) -> MemoryUpdateResult:
- if not user_message.strip() or not assistant_message.strip():
- return MemoryUpdateResult(content="", changed=False, updated_at=None)
-
- source = (
- f"[Session] {session_id or '(unknown)'}\n"
- f"[Capability] {capability or 'chat'}\n"
- f"[Timestamp] {timestamp or datetime.now().isoformat()}\n\n"
- f"[User]\n{user_message.strip()}\n\n"
- f"[Assistant]\n{assistant_message.strip()}"
- )
-
- async with self._refresh_lock:
- p_changed = await self._rewrite_one("profile", source, language)
- s_changed = await self._rewrite_one("summary", source, language)
-
- snap = self.read_snapshot()
- return MemoryUpdateResult(
- content=snap.profile,
- changed=p_changed or s_changed,
- updated_at=snap.profile_updated_at,
- )
-
- async def refresh_from_session(
- self,
- session_id: str | None = None,
- *,
- language: str = "en",
- max_messages: int = 10,
- ) -> MemoryUpdateResult:
- target = (session_id or "").strip()
- if not target:
- sessions = await self._store.list_sessions(limit=1)
- if sessions:
- target = str(sessions[0].get("session_id", "") or "")
-
- if not target:
- return MemoryUpdateResult(content="", changed=False, updated_at=None)
-
- messages = await self._store.get_messages_for_context(target)
- relevant = [
- m
- for m in messages
- if str(m.get("role", "")) in {"user", "assistant"}
- and str(m.get("content", "") or "").strip()
- ][-max_messages:]
-
- if not relevant:
- return MemoryUpdateResult(content="", changed=False, updated_at=None)
-
- transcript = "\n\n".join(
- f"{'User' if m.get('role') == 'user' else 'Assistant'}: "
- f"{str(m.get('content', '') or '').strip()}"
- for m in relevant
- )
-
- cap = ""
- sess = await self._store.get_session(target)
- if sess:
- cap = str(sess.get("capability", "") or "")
-
- source = (
- f"[Session] {target}\n[Capability] {cap or 'chat'}\n\n[Recent Transcript]\n{transcript}"
- )
-
- async with self._refresh_lock:
- p_changed = await self._rewrite_one("profile", source, language)
- s_changed = await self._rewrite_one("summary", source, language)
-
- snap = self.read_snapshot()
- return MemoryUpdateResult(
- content=snap.profile,
- changed=p_changed or s_changed,
- updated_at=snap.profile_updated_at,
- )
-
- # ── LLM rewrite for individual files ──────────────────────────────
-
- async def _rewrite_one(self, which: MemoryFile, source: str, language: str) -> bool:
- """Rewrite a single memory file. Returns True if changed."""
- current = self.read_file(which)
- zh = str(language).lower().startswith("zh")
-
- if which == "profile":
- sys_prompt, user_prompt = self._profile_prompts(current, source, zh)
- else:
- sys_prompt, user_prompt = self._summary_prompts(current, source, zh)
-
- chunks: list[str] = []
- async for c in llm_stream(
- prompt=user_prompt,
- system_prompt=sys_prompt,
- temperature=0.2,
- max_tokens=900,
- ):
- chunks.append(c)
-
- raw = _clean_memory_content("".join(chunks))
- if not raw or raw == _NO_CHANGE:
- return False
-
- if raw == current:
- return False
-
- if not _is_valid_memory_rewrite(which, raw):
- logger.warning(
- "Skipping invalid %s memory rewrite: missing expected section heading",
- which,
- )
- return False
-
- self.write_file(which, raw)
- return True
-
- @staticmethod
- def _profile_prompts(current: str, source: str, zh: bool) -> tuple[str, str]:
- if zh:
- return (
- "你负责维护一份用户画像文档。只保留稳定的用户身份、偏好、知识水平。"
- f"如果无需修改,请只返回 {_NO_CHANGE}。",
- "如果需要更新,请重写用户画像,可使用以下标题:\n"
- "## Identity\n## Learning Style\n## Knowledge Level\n## Preferences\n\n"
- "规则:保持简短,删除过时内容,不要记录临时对话。\n\n"
- f"[当前画像]\n{current or '(empty)'}\n\n"
- f"[新增材料]\n{source}",
- )
- return (
- "You maintain a user profile document. Only keep stable identity, "
- "preferences, and knowledge levels. "
- f"If nothing should change, return exactly {_NO_CHANGE}.",
- "Rewrite the user profile if needed. Suggested sections:\n"
- "## Identity\n## Learning Style\n## Knowledge Level\n## Preferences\n\n"
- "Rules: keep it short, remove stale items, no transient chatter.\n\n"
- f"[Current profile]\n{current or '(empty)'}\n\n"
- f"[New material]\n{source}",
- )
-
- @staticmethod
- def _summary_prompts(current: str, source: str, zh: bool) -> tuple[str, str]:
- if zh:
- return (
- "你负责维护一份学习旅程摘要。记录用户正在学什么、完成了什么、有哪些待解决的问题。"
- f"如果无需修改,请只返回 {_NO_CHANGE}。",
- "如果需要更新,请重写学习旅程摘要,可使用以下标题:\n"
- "## Current Focus\n## Accomplishments\n## Open Questions\n\n"
- "规则:保持简短,删除已完成或过时的条目。\n\n"
- f"[当前摘要]\n{current or '(empty)'}\n\n"
- f"[新增材料]\n{source}",
- )
- return (
- "You maintain a learning journey summary. Track what the user is studying, "
- "what they've accomplished, and what open questions remain. "
- f"If nothing should change, return exactly {_NO_CHANGE}.",
- "Rewrite the learning summary if needed. Suggested sections:\n"
- "## Current Focus\n## Accomplishments\n## Open Questions\n\n"
- "Rules: keep it short, remove completed/stale items.\n\n"
- f"[Current summary]\n{current or '(empty)'}\n\n"
- f"[New material]\n{source}",
- )
-
- # ── Helpers ───────────────────────────────────────────────────────
-
- @staticmethod
- def _extract_legacy_sections(content: str) -> tuple[str, str]:
- text = content.replace("\r\n", "\n").strip()
- preferences = ""
- context = ""
- pref_match = re.search(
- r"##\s*Preferences\s*(.*?)(?=\n##\s*Context\b|\Z)",
- text,
- flags=re.IGNORECASE | re.DOTALL,
- )
- ctx_match = re.search(
- r"##\s*Context\s*(.*)$",
- text,
- flags=re.IGNORECASE | re.DOTALL,
- )
- if pref_match:
- preferences = pref_match.group(1).strip()
- if ctx_match:
- context = ctx_match.group(1).strip()
- return preferences, context
-
-
-def _strip_code_fence(content: str) -> str:
- cleaned = str(content or "").strip()
- if cleaned.startswith("```"):
- cleaned = re.sub(r"^```[a-zA-Z0-9_-]*\n?", "", cleaned)
- cleaned = re.sub(r"\n?```$", "", cleaned)
- return cleaned.strip()
-
-
-_EXPECTED_MEMORY_HEADINGS: dict[MemoryFile, set[str]] = {
- "profile": {
- "identity",
- "user identity",
- "learning style",
- "knowledge level",
- "preferences",
- "preference",
- "身份",
- "用户身份",
- "学习风格",
- "学习方式",
- "知识水平",
- "偏好",
- "用户偏好",
- },
- "summary": {
- "current focus",
- "accomplishments",
- "open questions",
- "learning journey",
- "context",
- "当前关注",
- "当前学习",
- "学习重点",
- "已完成",
- "学习成果",
- "成就",
- "开放问题",
- "待解决问题",
- "学习旅程",
- "上下文",
- },
-}
-
-
-def _normalize_heading(value: str) -> str:
- heading = re.sub(r"[*_`]+", "", str(value or "")).strip()
- heading = re.sub(r"[::#\s]+$", "", heading).strip()
- return heading.lower()
-
-
-def _is_valid_memory_rewrite(which: MemoryFile, content: str) -> bool:
- """Accept only target-shaped LLM rewrites, not arbitrary model answers."""
- allowed = _EXPECTED_MEMORY_HEADINGS[which]
- headings = re.findall(r"^##(?!#)\s*(.+?)\s*$", content, flags=re.MULTILINE)
- return any(_normalize_heading(heading) in allowed for heading in headings)
-
-
-def _clean_memory_content(content: str) -> str:
- """Remove code fences and model scratchpad tags before durable memory writes."""
- return clean_thinking_tags(_strip_code_fence(content)).strip()
-
-
-_memory_services: dict[str, MemoryService] = {}
-
-
-def get_memory_service() -> MemoryService:
- path_service = get_path_service()
- key = str(path_service.get_memory_dir().resolve())
- if key not in _memory_services:
- _memory_services[key] = MemoryService(path_service=path_service)
- return _memory_services[key]
-
-
-__all__ = [
- "MemoryFile",
- "MemoryService",
- "MemorySnapshot",
- "MemoryUpdateResult",
- "get_memory_service",
-]
diff --git a/deeptutor/services/memory/settings.py b/deeptutor/services/memory/settings.py
new file mode 100644
index 000000000..758370a5c
--- /dev/null
+++ b/deeptutor/services/memory/settings.py
@@ -0,0 +1,196 @@
+"""User-tunable parameters for the memory consolidator.
+
+Single source of truth is ``data/user/settings/main.yaml`` under the
+``memory:`` subtree. Defaults live here. The frontend ``/settings/memory``
+page reads/writes the same subtree via the API.
+
+Decoupled from the algorithm code: every mode picks values up via
+:func:`load_memory_settings`, never via module-level constants.
+"""
+
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass, field, fields, is_dataclass
+from typing import Any, Literal
+
+from deeptutor.utils.config_manager import ConfigManager
+
+_SETTINGS_KEY = "memory"
+
+
+@dataclass(frozen=True)
+class UpdateSettings:
+ l2_budget: int = 20
+ l3_budget: int = 10
+
+
+@dataclass(frozen=True)
+class AuditSettings:
+ l2_budget: int = 20
+ l3_budget: int = 10
+
+
+@dataclass(frozen=True)
+class DedupSettings:
+ iterations: int = 3
+ auto_after_update: bool = True
+
+
+@dataclass(frozen=True)
+class MergeSettings:
+ """No-LLM footnote consolidation (collapse duplicate refs into one footnote each)."""
+
+ auto_after_update: bool = True
+ auto_after_audit: bool = True
+ auto_after_dedup: bool = True
+
+
+@dataclass(frozen=True)
+class ChunkingSettings:
+ overlap_ratio: float = 0.10
+ boundary: Literal["paragraph", "sentence"] = "paragraph"
+ min_chunk_chars: int = 1000
+ max_chunk_chars: int = 64000
+
+
+@dataclass(frozen=True)
+class ReferenceSettings:
+ enforce_required: bool = True
+ drop_invalid_refs: bool = True
+
+
+@dataclass(frozen=True)
+class MemorySettings:
+ update: UpdateSettings = field(default_factory=UpdateSettings)
+ audit: AuditSettings = field(default_factory=AuditSettings)
+ dedup: DedupSettings = field(default_factory=DedupSettings)
+ merge: MergeSettings = field(default_factory=MergeSettings)
+ chunking: ChunkingSettings = field(default_factory=ChunkingSettings)
+ reference: ReferenceSettings = field(default_factory=ReferenceSettings)
+
+
+def load_memory_settings() -> MemorySettings:
+ """Return the current ``memory:`` subtree merged on top of defaults.
+
+ Missing keys fall back to defaults. Out-of-range numeric values are
+ clamped to safe ranges so a malformed YAML never crashes a run.
+ """
+ raw = ConfigManager().load_config().get(_SETTINGS_KEY) or {}
+ return _from_dict(MemorySettings, raw)
+
+
+def save_memory_settings(payload: dict[str, Any]) -> MemorySettings:
+ """Merge ``payload`` into the on-disk ``memory:`` subtree.
+
+ Unknown keys are dropped; values are coerced to the schema's types
+ so the YAML never picks up junk. Returns the post-merge settings.
+ """
+ merged = _from_dict(MemorySettings, payload)
+ coerced = asdict(merged)
+ ConfigManager().save_config({_SETTINGS_KEY: coerced})
+ return merged
+
+
+def memory_settings_dict() -> dict[str, Any]:
+ """Settings as a plain dict — JSON-safe for the API response."""
+ return asdict(load_memory_settings())
+
+
+# ── Coercion + clamping ─────────────────────────────────────────────────
+
+
+_MIN_BUDGET = 1
+_MAX_BUDGET = 200
+_MIN_DEDUP_ITER = 1
+_MAX_DEDUP_ITER = 20
+_MIN_OVERLAP = 0.0
+_MAX_OVERLAP = 0.5
+_MIN_CHUNK_CHARS = 200
+_MAX_CHUNK_CHARS = 64000
+_BOUNDARIES = ("paragraph", "sentence")
+
+
+def _from_dict(cls: type, raw: Any) -> Any:
+ """Build a frozen dataclass from a partial dict.
+
+ Strategy: walk fields, if a field is itself a dataclass and the input
+ has a matching dict, recurse. Otherwise coerce + clamp. Defaults fill
+ any missing field.
+ """
+ if not is_dataclass(cls):
+ raise TypeError(f"{cls!r} is not a dataclass")
+
+ instance_defaults = cls() # type: ignore[call-arg]
+ if not isinstance(raw, dict):
+ return instance_defaults
+
+ kwargs: dict[str, Any] = {}
+ for f in fields(cls):
+ provided = raw.get(f.name)
+ default = getattr(instance_defaults, f.name)
+ if is_dataclass(f.type) if isinstance(f.type, type) else False:
+ kwargs[f.name] = _from_dict(f.type, provided) if provided is not None else default
+ continue
+ # nested dataclass detection through the actual default type
+ if is_dataclass(default):
+ kwargs[f.name] = _from_dict(type(default), provided) if provided is not None else default
+ continue
+ kwargs[f.name] = _coerce_scalar(f.name, provided, default)
+ return cls(**kwargs)
+
+
+def _coerce_scalar(name: str, raw: Any, default: Any) -> Any:
+ if raw is None:
+ return default
+ if isinstance(default, bool):
+ return bool(raw)
+ if isinstance(default, int):
+ try:
+ value = int(raw)
+ except (TypeError, ValueError):
+ return default
+ return _clamp_int(name, value, default)
+ if isinstance(default, float):
+ try:
+ value = float(raw)
+ except (TypeError, ValueError):
+ return default
+ return _clamp_float(name, value, default)
+ if isinstance(default, str):
+ value = str(raw)
+ if name == "boundary" and value not in _BOUNDARIES:
+ return default
+ return value
+ return raw
+
+
+def _clamp_int(name: str, value: int, default: int) -> int:
+ if name.endswith("budget"):
+ return max(_MIN_BUDGET, min(_MAX_BUDGET, value))
+ if name == "iterations":
+ return max(_MIN_DEDUP_ITER, min(_MAX_DEDUP_ITER, value))
+ if name == "min_chunk_chars":
+ return max(_MIN_CHUNK_CHARS, min(_MAX_CHUNK_CHARS, value))
+ if name == "max_chunk_chars":
+ return max(_MIN_CHUNK_CHARS, min(_MAX_CHUNK_CHARS, value))
+ return max(0, value)
+
+
+def _clamp_float(name: str, value: float, default: float) -> float:
+ if name == "overlap_ratio":
+ return max(_MIN_OVERLAP, min(_MAX_OVERLAP, value))
+ return value
+
+
+__all__ = [
+ "AuditSettings",
+ "ChunkingSettings",
+ "DedupSettings",
+ "MemorySettings",
+ "MergeSettings",
+ "ReferenceSettings",
+ "UpdateSettings",
+ "load_memory_settings",
+ "memory_settings_dict",
+ "save_memory_settings",
+]
diff --git a/deeptutor/services/memory/snapshot/__init__.py b/deeptutor/services/memory/snapshot/__init__.py
new file mode 100644
index 000000000..d4cf3921b
--- /dev/null
+++ b/deeptutor/services/memory/snapshot/__init__.py
@@ -0,0 +1,104 @@
+"""Workspace snapshot subsystem for L1 memory.
+
+Public API:
+
+- :func:`read_snapshot` — current entities for a surface (no I/O on
+ ``state.json`` / ``changes.jsonl``).
+- :func:`refresh_snapshot` — re-read workspace, diff against last
+ persisted state, append changes, persist new state. Returns the
+ computed change list. Idempotent: a no-change refresh writes nothing
+ to the changes log.
+- :func:`read_changes` — paginated history of past refreshes for one
+ surface (git-log-style display source).
+- :func:`current_state` — the persisted ``state.json`` for a surface
+ (consolidator uses ``last_refresh`` to gate L2 updates).
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from typing import Iterable
+
+from deeptutor.services.memory.paths import Surface
+from deeptutor.services.memory.snapshot import adapters, store
+from deeptutor.services.memory.snapshot.diff import diff_snapshots
+from deeptutor.services.memory.snapshot.entity import ChangeEntry, Entity
+
+
+def read_snapshot(surface: Surface) -> list[Entity]:
+ return adapters.read_entities(surface)
+
+
+def pending_changes(
+ surface: Surface, entities: list[Entity] | None = None
+) -> list[ChangeEntry]:
+ """Compute the diff between current workspace and the last persisted state.
+
+ Pure / read-only: never writes to ``state.json`` or ``changes.jsonl``.
+ Used by the L1 view to show "what would a refresh capture right now".
+ """
+ if entities is None:
+ entities = adapters.read_entities(surface)
+ curr_fp = {e.id: e.fingerprint for e in entities}
+ curr_labels = {e.id: e.label for e in entities}
+
+ prev = store.load_state(surface)
+ prev_fp = prev.get("fingerprints") or {}
+ prev_labels = prev.get("labels") or {}
+
+ return diff_snapshots(
+ prev_fp,
+ curr_fp,
+ label_map=curr_labels,
+ prev_label_map=prev_labels,
+ )
+
+
+def refresh_snapshot(surface: Surface) -> list[ChangeEntry]:
+ entities = adapters.read_entities(surface)
+ changes = pending_changes(surface, entities)
+ curr_fp = {e.id: e.fingerprint for e in entities}
+ curr_labels = {e.id: e.label for e in entities}
+ store.append_changes(surface, changes)
+ store.save_state(
+ surface,
+ fingerprints=curr_fp,
+ labels=curr_labels,
+ last_refresh=datetime.now(tz=timezone.utc).isoformat(),
+ )
+ return changes
+
+
+def read_changes(
+ surface: Surface, *, limit: int = 200, offset: int = 0
+) -> list[ChangeEntry]:
+ bound = max(1, min(limit, 1000))
+ all_changes: list[ChangeEntry] = list(store.iter_changes(surface))
+ # Most recent first — the file is append-order, reverse it.
+ all_changes.reverse()
+ return all_changes[offset : offset + bound]
+
+
+def current_state(surface: Surface) -> dict:
+ return store.load_state(surface)
+
+
+def clear_changes(surface: Surface) -> None:
+ store.clear_changes(surface)
+
+
+__all__ = [
+ "Entity",
+ "ChangeEntry",
+ "read_snapshot",
+ "pending_changes",
+ "refresh_snapshot",
+ "read_changes",
+ "current_state",
+ "clear_changes",
+ "adapters",
+]
+
+
+# Iterable kept for static-analyzer happiness when consumers import *.
+_: Iterable = []
diff --git a/deeptutor/services/memory/snapshot/adapters.py b/deeptutor/services/memory/snapshot/adapters.py
new file mode 100644
index 000000000..d3166a6d0
--- /dev/null
+++ b/deeptutor/services/memory/snapshot/adapters.py
@@ -0,0 +1,453 @@
+"""Workspace → ``Entity`` adapters.
+
+One pure read-only function per surface. Adapters never mutate
+workspace state. They read whatever lives under
+``data/user/workspace/`` (or, for chat/quiz, the chat history SQLite
+DB; for kb-list, the kb config JSON).
+
+Each adapter returns a ``list[Entity]`` with stable ``id`` and a
+deterministic ``fingerprint`` so the diff engine can detect changes
+across refreshes.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import sqlite3
+from datetime import datetime, timezone
+from pathlib import Path
+
+from deeptutor.services.memory.paths import Surface
+from deeptutor.services.memory.snapshot.entity import Entity
+from deeptutor.services.path_service import get_path_service
+
+logger = logging.getLogger(__name__)
+
+
+# ── Helpers ──────────────────────────────────────────────────────────
+
+
+def _sha1(*parts: object) -> str:
+ h = hashlib.sha1()
+ for part in parts:
+ if part is None:
+ continue
+ if isinstance(part, (dict, list)):
+ blob = json.dumps(part, sort_keys=True, ensure_ascii=False)
+ else:
+ blob = str(part)
+ h.update(blob.encode("utf-8"))
+ h.update(b"\0")
+ return h.hexdigest()[:16]
+
+
+def _iso(ts: float | int | str | None) -> str:
+ if isinstance(ts, str):
+ try:
+ datetime.fromisoformat(ts.replace("Z", "+00:00"))
+ return ts
+ except Exception:
+ pass
+ if isinstance(ts, (int, float)):
+ try:
+ return datetime.fromtimestamp(float(ts), tz=timezone.utc).isoformat()
+ except Exception:
+ pass
+ return ""
+
+
+# ── Adapters ─────────────────────────────────────────────────────────
+
+
+def read_notebook_entities() -> list[Entity]:
+ ps = get_path_service()
+ index_file = ps.get_notebook_index_file()
+ if not index_file.exists():
+ return []
+ try:
+ index = json.loads(index_file.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return []
+ notebooks = index.get("notebooks") or []
+ out: list[Entity] = []
+ for nb in notebooks:
+ if not isinstance(nb, dict):
+ continue
+ nb_id = nb.get("id")
+ nb_name = nb.get("name") or nb_id
+ if not nb_id:
+ continue
+ nb_file = ps.get_notebook_file(nb_id)
+ if not nb_file.exists():
+ continue
+ try:
+ nb_data = json.loads(nb_file.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ for r in nb_data.get("records") or []:
+ if not isinstance(r, dict):
+ continue
+ rid = r.get("id")
+ if not rid:
+ continue
+ title = r.get("title", "") or ""
+ user_query = r.get("user_query", "") or ""
+ output = r.get("output", "") or ""
+ summary = r.get("summary", "") or ""
+ content = "\n\n".join(
+ part
+ for part in (
+ f"# {title}" if title else "",
+ f"**User query**: {user_query}" if user_query else "",
+ f"**Summary**: {summary}" if summary else "",
+ output,
+ )
+ if part
+ )
+ out.append(
+ Entity(
+ id=rid,
+ label=f"{title} · {nb_name}" if title else f"({rid}) · {nb_name}",
+ ts=_iso(r.get("created_at")),
+ content=content,
+ metadata={
+ "notebook_id": nb_id,
+ "notebook_name": nb_name,
+ "record_type": r.get("record_type", ""),
+ "kb_name": r.get("kb_name"),
+ },
+ fingerprint=_sha1(title, user_query, output, summary),
+ )
+ )
+ return out
+
+
+def read_cowriter_entities() -> list[Entity]:
+ docs_dir = get_path_service().get_co_writer_docs_dir()
+ if not docs_dir.exists():
+ return []
+ out: list[Entity] = []
+ for entry in sorted(docs_dir.iterdir()):
+ manifest = entry / "manifest.json"
+ if not manifest.exists():
+ continue
+ try:
+ m = json.loads(manifest.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ doc_id = m.get("id")
+ if not doc_id:
+ continue
+ title = m.get("title", "") or ""
+ content = m.get("content", "") or ""
+ out.append(
+ Entity(
+ id=doc_id,
+ label=title or doc_id,
+ ts=_iso(m.get("updated_at") or m.get("created_at")),
+ content=content,
+ metadata={"doc_id": doc_id, "title": title},
+ fingerprint=_sha1(title, content),
+ )
+ )
+ return out
+
+
+def read_book_entities() -> list[Entity]:
+ books_dir = get_path_service().get_book_dir()
+ if not books_dir.exists():
+ return []
+ out: list[Entity] = []
+ for entry in sorted(books_dir.iterdir()):
+ if not entry.is_dir():
+ continue
+ manifest_path = entry / "manifest.json"
+ if not manifest_path.exists():
+ continue
+ try:
+ m = json.loads(manifest_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ book_id = m.get("id")
+ if not book_id:
+ continue
+ title = m.get("title", "") or ""
+ description = m.get("description", "") or ""
+ # Pull page titles + chapter outline from spine for L2 to chew on.
+ spine_path = entry / "spine.json"
+ page_titles: list[str] = []
+ if spine_path.exists():
+ try:
+ spine = json.loads(spine_path.read_text(encoding="utf-8"))
+ page_titles = [
+ str(p.get("title") or p.get("id") or "")
+ for p in (spine.get("pages") or [])
+ if isinstance(p, dict)
+ ]
+ except (OSError, json.JSONDecodeError):
+ page_titles = []
+ content = "\n\n".join(
+ part
+ for part in (
+ f"# {title}",
+ description,
+ "## Pages\n" + "\n".join(f"- {p}" for p in page_titles) if page_titles else "",
+ )
+ if part
+ )
+ out.append(
+ Entity(
+ id=book_id,
+ label=title or book_id,
+ ts=_iso(m.get("updated_at") or m.get("created_at")),
+ content=content,
+ metadata={
+ "book_id": book_id,
+ "page_count": m.get("page_count", 0),
+ "chapter_count": m.get("chapter_count", 0),
+ "knowledge_bases": m.get("knowledge_bases", []),
+ "status": m.get("status", ""),
+ },
+ fingerprint=_sha1(
+ title, description, m.get("updated_at"), len(page_titles)
+ ),
+ )
+ )
+ return out
+
+
+def read_tutorbot_entities() -> list[Entity]:
+ root = get_path_service().workspace_root / "tutorbot"
+ if not root.exists():
+ return []
+ out: list[Entity] = []
+ for entry in sorted(root.iterdir()):
+ if not entry.is_dir():
+ continue
+ cfg = entry / "config.yaml"
+ if not cfg.exists():
+ continue
+ try:
+ cfg_text = cfg.read_text(encoding="utf-8")
+ except OSError:
+ cfg_text = ""
+ try:
+ stat = cfg.stat()
+ ts = _iso(stat.st_mtime)
+ except OSError:
+ ts = ""
+ out.append(
+ Entity(
+ id=entry.name,
+ label=entry.name,
+ ts=ts,
+ content=cfg_text,
+ metadata={"bot_id": entry.name},
+ fingerprint=_sha1(cfg_text),
+ )
+ )
+ return out
+
+
+def read_kb_entities() -> list[Entity]:
+ """KB *list* snapshot — one Entity per registered knowledge base.
+
+ KB queries stay event-driven and live in the trace store; the L2
+ consolidator combines both signals.
+ """
+ kb_root = get_path_service().get_knowledge_bases_root()
+ cfg_file = kb_root / "kb_config.json"
+ if not cfg_file.exists():
+ return []
+ try:
+ cfg = json.loads(cfg_file.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return []
+ kbs = cfg.get("knowledge_bases") or {}
+ if not isinstance(kbs, dict):
+ return []
+ out: list[Entity] = []
+ for kb_name, kb_data in sorted(kbs.items()):
+ if not isinstance(kb_name, str):
+ continue
+ if not isinstance(kb_data, dict):
+ kb_data = {}
+ description = kb_data.get("description", "") or ""
+ versions = kb_data.get("index_versions") or []
+ sigs = sorted(
+ v.get("signature", "")
+ for v in versions
+ if isinstance(v, dict)
+ )
+ earliest_created = min(
+ (
+ v.get("created_at", "")
+ for v in versions
+ if isinstance(v, dict) and v.get("created_at")
+ ),
+ default="",
+ )
+ content = "\n\n".join(
+ part
+ for part in (
+ f"# {kb_name}",
+ description,
+ f"Index versions: {len(versions)}",
+ )
+ if part
+ )
+ out.append(
+ Entity(
+ id=kb_name,
+ label=kb_name,
+ ts=earliest_created,
+ content=content,
+ metadata={
+ "kb_name": kb_name,
+ "version_count": len(versions),
+ "rag_provider": kb_data.get("rag_provider", ""),
+ },
+ fingerprint=_sha1(description, sigs),
+ )
+ )
+ return out
+
+
+def read_chat_entities() -> list[Entity]:
+ """One Entity per chat session. ``content`` inlines all turns as
+ ``user / assistant`` blocks so L2 sees the actual conversation."""
+ db_path = get_path_service().get_chat_history_db()
+ if not db_path.exists():
+ return []
+ out: list[Entity] = []
+ try:
+ with sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) as conn:
+ conn.row_factory = sqlite3.Row
+ sessions = conn.execute(
+ "SELECT id, title, created_at, updated_at FROM sessions "
+ "ORDER BY updated_at DESC"
+ ).fetchall()
+ for sess in sessions:
+ sid = sess["id"]
+ msgs = conn.execute(
+ "SELECT id, role, content, capability, created_at "
+ "FROM messages WHERE session_id = ? "
+ "ORDER BY created_at ASC, id ASC",
+ (sid,),
+ ).fetchall()
+ blocks: list[str] = []
+ for m in msgs:
+ role = m["role"]
+ body = (m["content"] or "").strip()
+ if not body:
+ continue
+ blocks.append(f"### {role}\n{body}")
+ content = "\n\n".join(blocks)
+ last_msg_id = msgs[-1]["id"] if msgs else 0
+ out.append(
+ Entity(
+ id=sid,
+ label=sess["title"] or sid,
+ ts=_iso(sess["updated_at"]),
+ content=content,
+ metadata={
+ "session_id": sid,
+ "message_count": len(msgs),
+ },
+ fingerprint=_sha1(last_msg_id, sess["updated_at"]),
+ )
+ )
+ except sqlite3.Error as exc:
+ logger.warning("chat snapshot scan failed: %s", exc)
+ return []
+ return out
+
+
+def read_quiz_entities() -> list[Entity]:
+ """One Entity per recorded quiz attempt (notebook_entries row)."""
+ db_path = get_path_service().get_chat_history_db()
+ if not db_path.exists():
+ return []
+ out: list[Entity] = []
+ try:
+ with sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) as conn:
+ conn.row_factory = sqlite3.Row
+ rows = conn.execute(
+ "SELECT id, session_id, turn_id, question_id, question, "
+ "question_type, options_json, correct_answer, explanation, "
+ "difficulty, user_answer, is_correct, bookmarked, "
+ "created_at FROM notebook_entries "
+ "ORDER BY created_at DESC"
+ ).fetchall()
+ for r in rows:
+ qid = r["question_id"] or f"row_{r['id']}"
+ entity_id = f"{r['session_id']}:{qid}"
+ question = (r["question"] or "").strip()
+ user_answer = (r["user_answer"] or "").strip()
+ correct = (r["correct_answer"] or "").strip()
+ explanation = (r["explanation"] or "").strip()
+ is_correct = bool(int(r["is_correct"] or 0))
+ content = "\n\n".join(
+ part
+ for part in (
+ f"**Question**: {question}" if question else "",
+ f"**User answer**: {user_answer}" if user_answer else "",
+ f"**Correct answer**: {correct}" if correct else "",
+ f"**Explanation**: {explanation}" if explanation else "",
+ )
+ if part
+ )
+ out.append(
+ Entity(
+ id=entity_id,
+ label=question[:80] or qid,
+ ts=_iso(r["created_at"]),
+ content=content,
+ metadata={
+ "session_id": r["session_id"],
+ "turn_id": r["turn_id"],
+ "question_id": qid,
+ "question_type": r["question_type"],
+ "difficulty": r["difficulty"],
+ "is_correct": is_correct,
+ "bookmarked": bool(int(r["bookmarked"] or 0)),
+ },
+ fingerprint=_sha1(
+ question, user_answer, correct, is_correct
+ ),
+ )
+ )
+ except sqlite3.Error as exc:
+ logger.warning("quiz snapshot scan failed: %s", exc)
+ return []
+ return out
+
+
+# ── Dispatch ─────────────────────────────────────────────────────────
+
+
+_READERS = {
+ "notebook": read_notebook_entities,
+ "cowriter": read_cowriter_entities,
+ "book": read_book_entities,
+ "tutorbot": read_tutorbot_entities,
+ "kb": read_kb_entities,
+ "chat": read_chat_entities,
+ "quiz": read_quiz_entities,
+}
+
+
+def read_entities(surface: Surface) -> list[Entity]:
+ reader = _READERS.get(surface)
+ if reader is None:
+ return []
+ try:
+ return reader()
+ except Exception as exc:
+ logger.warning("snapshot adapter failed surface=%s: %s", surface, exc)
+ return []
+
+
+SUPPORTED_SURFACES: tuple[Surface, ...] = tuple(_READERS.keys()) # type: ignore[assignment]
diff --git a/deeptutor/services/memory/snapshot/diff.py b/deeptutor/services/memory/snapshot/diff.py
new file mode 100644
index 000000000..7f02ab39d
--- /dev/null
+++ b/deeptutor/services/memory/snapshot/diff.py
@@ -0,0 +1,69 @@
+"""Pure-function diff between two snapshot states.
+
+A ``state`` is ``{entity_id: fingerprint}``. ``label_map`` carries
+human-readable titles for the change-log so we don't have to re-read
+workspace state when rendering history.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+from deeptutor.services.memory.snapshot.entity import ChangeEntry
+
+
+def diff_snapshots(
+ prev: dict[str, str],
+ curr: dict[str, str],
+ *,
+ label_map: dict[str, str],
+ prev_label_map: dict[str, str] | None = None,
+) -> list[ChangeEntry]:
+ """Return the change list moving ``prev`` → ``curr``.
+
+ ``label_map`` provides labels for currently-present entities;
+ ``prev_label_map`` (optional) is consulted for removed-entity labels.
+ """
+ ts = datetime.now(tz=timezone.utc).isoformat()
+ out: list[ChangeEntry] = []
+ prev_keys = set(prev)
+ curr_keys = set(curr)
+
+ for entity_id in sorted(curr_keys - prev_keys):
+ out.append(
+ ChangeEntry(
+ ts=ts,
+ kind="added",
+ entity_id=entity_id,
+ label=label_map.get(entity_id, entity_id),
+ prev_fingerprint=None,
+ new_fingerprint=curr[entity_id],
+ )
+ )
+ for entity_id in sorted(prev_keys - curr_keys):
+ prior_label = (
+ (prev_label_map or {}).get(entity_id, "") or entity_id
+ )
+ out.append(
+ ChangeEntry(
+ ts=ts,
+ kind="removed",
+ entity_id=entity_id,
+ label=prior_label,
+ prev_fingerprint=prev[entity_id],
+ new_fingerprint=None,
+ )
+ )
+ for entity_id in sorted(prev_keys & curr_keys):
+ if prev[entity_id] != curr[entity_id]:
+ out.append(
+ ChangeEntry(
+ ts=ts,
+ kind="modified",
+ entity_id=entity_id,
+ label=label_map.get(entity_id, entity_id),
+ prev_fingerprint=prev[entity_id],
+ new_fingerprint=curr[entity_id],
+ )
+ )
+ return out
diff --git a/deeptutor/services/memory/snapshot/entity.py b/deeptutor/services/memory/snapshot/entity.py
new file mode 100644
index 000000000..5638c109c
--- /dev/null
+++ b/deeptutor/services/memory/snapshot/entity.py
@@ -0,0 +1,45 @@
+"""Snapshot data types.
+
+An ``Entity`` is one unit of L1 content for a non-KB surface — e.g. one
+notebook record, one co-writer document, one book, one chat session.
+The snapshot is the *current* set of these on disk; the diff log records
+how that set has changed across refreshes.
+
+These types are intentionally pure dataclasses with no I/O. Adapters
+build ``Entity`` lists; ``diff.diff_snapshots`` consumes two ``state``
+dicts to produce ``ChangeEntry`` records.
+"""
+
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass, field
+from typing import Any, Literal
+
+
+@dataclass
+class Entity:
+ id: str
+ label: str
+ ts: str
+ content: str
+ metadata: dict[str, Any] = field(default_factory=dict)
+ fingerprint: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+ChangeKind = Literal["added", "modified", "removed"]
+
+
+@dataclass
+class ChangeEntry:
+ ts: str
+ kind: ChangeKind
+ entity_id: str
+ label: str
+ prev_fingerprint: str | None = None
+ new_fingerprint: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
diff --git a/deeptutor/services/memory/snapshot/store.py b/deeptutor/services/memory/snapshot/store.py
new file mode 100644
index 000000000..94465d9f4
--- /dev/null
+++ b/deeptutor/services/memory/snapshot/store.py
@@ -0,0 +1,113 @@
+"""On-disk persistence for snapshot state + change log.
+
+Each surface gets its own ``<memory_dir>/snapshot/<surface>/`` directory
+holding:
+
+- ``state.json`` — current ``{entity_id: fingerprint}`` map plus
+ a parallel ``labels`` map (so removals can show
+ the old human-readable title) and ``last_refresh``.
+- ``changes.jsonl`` — append-only diff log (one ``ChangeEntry`` per line).
+
+State writes are atomic via temp-file + rename. Changes are appended
+line-by-line, which is naturally atomic on POSIX filesystems.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import asdict
+from pathlib import Path
+from typing import Iterator
+
+from deeptutor.services.memory.paths import Surface, memory_root
+from deeptutor.services.memory.snapshot.entity import ChangeEntry
+
+
+def snapshot_dir(surface: Surface) -> Path:
+ return memory_root() / "snapshot" / surface
+
+
+def state_file(surface: Surface) -> Path:
+ return snapshot_dir(surface) / "state.json"
+
+
+def changes_file(surface: Surface) -> Path:
+ return snapshot_dir(surface) / "changes.jsonl"
+
+
+def load_state(surface: Surface) -> dict:
+ path = state_file(surface)
+ if not path.exists():
+ return {"fingerprints": {}, "labels": {}, "last_refresh": None}
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return {"fingerprints": {}, "labels": {}, "last_refresh": None}
+ return {
+ "fingerprints": data.get("fingerprints") or {},
+ "labels": data.get("labels") or {},
+ "last_refresh": data.get("last_refresh"),
+ }
+
+
+def save_state(
+ surface: Surface,
+ *,
+ fingerprints: dict[str, str],
+ labels: dict[str, str],
+ last_refresh: str,
+) -> None:
+ target = state_file(surface)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ tmp = target.with_suffix(".json.tmp")
+ payload = {
+ "fingerprints": fingerprints,
+ "labels": labels,
+ "last_refresh": last_refresh,
+ }
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
+ os.replace(tmp, target)
+
+
+def append_changes(surface: Surface, changes: list[ChangeEntry]) -> None:
+ if not changes:
+ return
+ path = changes_file(surface)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("a", encoding="utf-8") as fh:
+ for change in changes:
+ fh.write(json.dumps(asdict(change), ensure_ascii=False, separators=(",", ":")))
+ fh.write("\n")
+
+
+def iter_changes(surface: Surface) -> Iterator[ChangeEntry]:
+ path = changes_file(surface)
+ if not path.exists():
+ return
+ with path.open("r", encoding="utf-8") as fh:
+ for raw in fh:
+ raw = raw.strip()
+ if not raw:
+ continue
+ try:
+ obj = json.loads(raw)
+ except json.JSONDecodeError:
+ continue
+ yield ChangeEntry(
+ ts=obj.get("ts", ""),
+ kind=obj.get("kind", "modified"),
+ entity_id=obj.get("entity_id", ""),
+ label=obj.get("label", ""),
+ prev_fingerprint=obj.get("prev_fingerprint"),
+ new_fingerprint=obj.get("new_fingerprint"),
+ )
+
+
+def clear_changes(surface: Surface) -> None:
+ path = changes_file(surface)
+ if path.exists():
+ try:
+ path.unlink()
+ except OSError:
+ pass
diff --git a/deeptutor/services/memory/store.py b/deeptutor/services/memory/store.py
new file mode 100644
index 000000000..ab4cffb0d
--- /dev/null
+++ b/deeptutor/services/memory/store.py
@@ -0,0 +1,347 @@
+"""High-level facade for the three-layer memory subsystem.
+
+All callers — API routers, LLM tools, surface event hooks — go through
+:class:`MemoryStore`. The store is stateless; per-user isolation is
+inherited from :func:`paths.memory_root` which resolves :class:`PathService`
+lazily via context variables.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shutil
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Literal
+
+from deeptutor.services.memory import consolidator, paths, trace
+from deeptutor.services.memory.consolidator import ConsolidateResult, OnEvent
+from deeptutor.services.memory.document import Document, parse, serialize
+from deeptutor.services.memory.ops import AddOp, ApplyReport, EditOp
+from deeptutor.services.memory.ops import apply as ops_apply
+from deeptutor.services.memory.paths import L3Slot, Surface
+from deeptutor.services.memory.trace import TraceEvent
+
+logger = logging.getLogger(__name__)
+
+Layer = Literal["L2", "L3"]
+
+_V1_FILES = ("PROFILE.md", "SUMMARY.md")
+_NO_MEMORY = "(No memory available — interact with DeepTutor and update from the Memory page to build one.)"
+
+
+@dataclass
+class DocOverview:
+ layer: Layer
+ key: str # surface name (L2) or slot name (L3)
+ exists: bool
+ updated_at: str | None
+ entry_count: int
+ backlog: int # L1 events since last update (L2 only; 0 for L3)
+
+
+class MemoryStore:
+ """Stateless facade. Safe to call as a process-wide singleton."""
+
+ def __init__(self) -> None:
+ self._write_locks: dict[str, asyncio.Lock] = {}
+
+ # ── L1 ────────────────────────────────────────────────────────────────
+
+ async def emit(self, event: TraceEvent) -> None:
+ await trace.append(event)
+
+ # ── L2 / L3 read ──────────────────────────────────────────────────────
+
+ def read_doc(self, layer: Layer, key: str) -> Document:
+ path = self._path(layer, key)
+ if not path.exists():
+ return Document(title=_default_title(layer, key))
+ return parse(path.read_text(encoding="utf-8"))
+
+ def read_raw(self, layer: Layer, key: str) -> str:
+ path = self._path(layer, key)
+ if not path.exists():
+ return ""
+ return path.read_text(encoding="utf-8")
+
+ def read_l3_concat(self) -> str:
+ """Concatenate all four L3 docs for the ``read_memory`` tool."""
+ parts: list[str] = []
+ for slot in paths.L3_SLOTS:
+ body = self.read_raw("L3", slot).strip()
+ if body:
+ parts.append(body)
+ if not parts:
+ return _NO_MEMORY
+ return "\n\n---\n\n".join(parts) + "\n"
+
+ # ── L2 / L3 write (manual paths) ──────────────────────────────────────
+
+ async def overwrite_doc(self, layer: Layer, key: str, md: str) -> None:
+ """Direct user-driven save from the workbench editor."""
+ path = self._path(layer, key)
+ async with self._lock_for(path):
+ await asyncio.to_thread(_atomic_write, path, md)
+
+ async def delete_entry(self, layer: Layer, key: str, entry_id: str) -> bool:
+ path = self._path(layer, key)
+ if not path.exists():
+ return False
+ async with self._lock_for(path):
+ doc = parse(path.read_text(encoding="utf-8"))
+ if not doc.remove(entry_id):
+ return False
+ await asyncio.to_thread(_atomic_write, path, serialize(doc))
+ return True
+
+ # ── L2 / L3 write (consolidator paths) ────────────────────────────────
+
+ async def update_l2(
+ self,
+ surface: Surface,
+ *,
+ language: str = "en",
+ user_label: str = "anonymous",
+ on_event: OnEvent | None = None,
+ apply_ops: bool = True,
+ ) -> ConsolidateResult:
+ path = paths.l2_file(surface)
+ async with self._lock_for(path):
+ return await consolidator.consolidate_l2(
+ surface,
+ language=language,
+ user_label=user_label,
+ on_event=on_event,
+ apply_ops=apply_ops,
+ )
+
+ async def update_l3(
+ self,
+ slot: L3Slot,
+ *,
+ language: str = "en",
+ user_label: str = "anonymous",
+ on_event: OnEvent | None = None,
+ apply_ops: bool = True,
+ ) -> ConsolidateResult:
+ if slot == "preferences":
+ raise ValueError("preferences.md is not auto-consolidated")
+ path = paths.l3_file(slot)
+ async with self._lock_for(path):
+ return await consolidator.consolidate_l3(
+ slot,
+ language=language,
+ user_label=user_label,
+ on_event=on_event,
+ apply_ops=apply_ops,
+ )
+
+ async def apply_ops_payload(
+ self, layer: Layer, key: str, ops_payload: list[dict]
+ ) -> ApplyReport:
+ """Apply a list of ops-as-JSON to a layer doc atomically.
+
+ Used by the workbench's preview → apply two-step flow. The
+ payload typically comes from a previous ``apply_ops=False``
+ consolidate call surfaced to the user for review.
+ """
+ from deeptutor.services.memory.consolidator import _parse_ops_response
+
+ path = self._path(layer, key)
+ json_like = {"ops": ops_payload}
+ import json as _json
+
+ ops = _parse_ops_response(_json.dumps(json_like, ensure_ascii=False))
+ async with self._lock_for(path):
+ default_title = _default_title(layer, key)
+ doc = (
+ parse(path.read_text(encoding="utf-8"))
+ if path.exists()
+ else Document(title=default_title)
+ )
+ report = ops_apply(doc, ops)
+ if report.accepted and ops:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ await asyncio.to_thread(_atomic_write, path, serialize(doc))
+ return report
+
+ async def write_preference(
+ self,
+ *,
+ op: Literal["add", "edit"],
+ text: str,
+ target_id: str | None = None,
+ reason: str | None = None,
+ trace_id: str,
+ ) -> ApplyReport:
+ """Write the chat-mode preference signal. The ``write_memory`` tool
+ is the only caller; ``trace_id`` is the current chat turn's L1 id
+ injected by runtime."""
+ path = paths.l3_file("preferences")
+ async with self._lock_for(path):
+ doc = (
+ parse(path.read_text(encoding="utf-8"))
+ if path.exists()
+ else Document(title=_default_title("L3", "preferences"))
+ )
+ section = "Preferences"
+ if op == "add":
+ report = ops_apply(
+ doc,
+ [AddOp(section=section, text=text, refs=[trace_id])],
+ )
+ else:
+ if not target_id:
+ return ApplyReport(accepted=False, reason="edit requires target_id")
+ report = ops_apply(
+ doc,
+ [
+ EditOp(
+ target_id=target_id,
+ new_text=text,
+ new_refs=[trace_id],
+ )
+ ],
+ )
+ if report.accepted:
+ await asyncio.to_thread(_atomic_write, path, serialize(doc))
+ if reason:
+ # Surface the reason in logs for workbench observability.
+ logger.info("write_memory %s id=%s reason=%s", op, target_id or "new", reason)
+ return report
+
+ # ── Workbench overview ────────────────────────────────────────────────
+
+ def overview(self) -> list[DocOverview]:
+ rows: list[DocOverview] = []
+ for surface in paths.SURFACES:
+ rows.append(self._overview_for("L2", surface))
+ for slot in paths.L3_SLOTS:
+ rows.append(self._overview_for("L3", slot))
+ return rows
+
+ def _overview_for(self, layer: Layer, key: str) -> DocOverview:
+ path = self._path(layer, key)
+ if not path.exists():
+ backlog = trace.count_since(key) if layer == "L2" else 0 # type: ignore[arg-type]
+ return DocOverview(
+ layer=layer,
+ key=key,
+ exists=False,
+ updated_at=None,
+ entry_count=0,
+ backlog=backlog,
+ )
+
+ stat = path.stat()
+ updated_at = datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat()
+ try:
+ doc = parse(path.read_text(encoding="utf-8"))
+ entry_count = len(doc.all_entries())
+ except Exception:
+ entry_count = 0
+
+ backlog = 0
+ if layer == "L2":
+ try:
+ cutoff = datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc)
+ backlog = trace.count_since(key, since=cutoff) # type: ignore[arg-type]
+ except Exception:
+ backlog = 0
+
+ return DocOverview(
+ layer=layer,
+ key=key,
+ exists=True,
+ updated_at=updated_at,
+ entry_count=entry_count,
+ backlog=backlog,
+ )
+
+ # ── Internals ─────────────────────────────────────────────────────────
+
+ def _path(self, layer: Layer, key: str) -> Path:
+ if layer == "L2":
+ if key not in paths.SURFACES:
+ raise ValueError(f"unknown surface {key!r}")
+ return paths.l2_file(key) # type: ignore[arg-type]
+ if key not in paths.L3_SLOTS:
+ raise ValueError(f"unknown L3 slot {key!r}")
+ return paths.l3_file(key) # type: ignore[arg-type]
+
+ def _lock_for(self, path: Path) -> asyncio.Lock:
+ key = str(path)
+ lock = self._write_locks.get(key)
+ if lock is None:
+ lock = asyncio.Lock()
+ self._write_locks[key] = lock
+ return lock
+
+
+# ── v1 → v2 startup migration ─────────────────────────────────────────────
+
+
+def migrate_v1_if_needed() -> Path | None:
+ """If any v1 memory files are present under the memory root, move the
+ whole memory directory's loose files into ``memory/backup/<ts>/``.
+
+ Idempotent: if there's nothing v1-shaped at the root, this is a no-op.
+
+ Returns the backup directory path on migration, or ``None`` otherwise.
+ """
+ root = paths.memory_root()
+ if not root.exists():
+ return None
+ v1_present = [name for name in _V1_FILES if (root / name).exists()]
+ if not v1_present:
+ return None
+
+ ts = datetime.now(tz=timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ backup_dir = paths.backup_root() / ts
+ backup_dir.mkdir(parents=True, exist_ok=True)
+ for item in list(root.iterdir()):
+ if item.name in {"trace", "L2", "L3", "backup"}:
+ continue
+ try:
+ shutil.move(str(item), str(backup_dir / item.name))
+ except OSError:
+ logger.warning("v1 memory migration: failed to move %s", item, exc_info=True)
+ logger.info("v1 memory migrated to %s", backup_dir)
+ return backup_dir
+
+
+# ── Singleton accessor ────────────────────────────────────────────────────
+
+
+_singleton: MemoryStore | None = None
+
+
+def get_memory_store() -> MemoryStore:
+ global _singleton
+ if _singleton is None:
+ _singleton = MemoryStore()
+ return _singleton
+
+
+# ── Helpers ───────────────────────────────────────────────────────────────
+
+
+def _default_title(layer: Layer, key: str) -> str:
+ if layer == "L2":
+ return f"{key} memory"
+ return {
+ "recent": "Recent summary",
+ "profile": "User profile",
+ "scope": "Knowledge scope",
+ "preferences": "Preferences",
+ }.get(key, key)
+
+
+def _atomic_write(path: Path, content: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(path.suffix + ".tmp")
+ tmp.write_text(content, encoding="utf-8")
+ tmp.replace(path)
diff --git a/deeptutor/services/memory/trace.py b/deeptutor/services/memory/trace.py
new file mode 100644
index 000000000..179d170fa
--- /dev/null
+++ b/deeptutor/services/memory/trace.py
@@ -0,0 +1,153 @@
+"""L1 raw event trace: append-only JSONL files, one per surface per UTC day.
+
+Trace capture must never break the producing surface — every append is
+wrapped and failures are logged-and-swallowed. Writes are serialized
+per-surface with an asyncio lock so multiple turns in the same process
+don't interleave JSON lines.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+from dataclasses import asdict, dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Iterator
+
+from deeptutor.services.memory.ids import new_trace_id
+from deeptutor.services.memory.paths import SURFACES, Surface, trace_dir, trace_file
+
+logger = logging.getLogger(__name__)
+
+_locks: dict[str, asyncio.Lock] = {}
+
+
+def _lock_for(surface: Surface) -> asyncio.Lock:
+ lock = _locks.get(surface)
+ if lock is None:
+ lock = asyncio.Lock()
+ _locks[surface] = lock
+ return lock
+
+
+@dataclass
+class TraceEvent:
+ id: str
+ ts: str
+ surface: Surface
+ kind: str
+ payload: dict[str, Any]
+ session_id: str | None = None
+ turn_id: str | None = None
+
+ @classmethod
+ def new(
+ cls,
+ surface: Surface,
+ kind: str,
+ payload: dict[str, Any],
+ *,
+ session_id: str | None = None,
+ turn_id: str | None = None,
+ ) -> "TraceEvent":
+ return cls(
+ id=new_trace_id(surface),
+ ts=datetime.now(tz=timezone.utc).isoformat(),
+ surface=surface,
+ kind=kind,
+ payload=payload,
+ session_id=session_id,
+ turn_id=turn_id,
+ )
+
+
+async def append(event: TraceEvent) -> None:
+ """Append one event to today's surface trace file. Never raises."""
+ try:
+ path = trace_file(event.surface, datetime.now(tz=timezone.utc).date())
+ line = json.dumps(asdict(event), ensure_ascii=False, separators=(",", ":"))
+ async with _lock_for(event.surface):
+ await asyncio.to_thread(_append_line, path, line)
+ except Exception:
+ logger.warning(
+ "memory trace append failed surface=%s kind=%s",
+ event.surface,
+ event.kind,
+ exc_info=True,
+ )
+
+
+def _append_line(path: Path, line: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("a", encoding="utf-8") as fh:
+ fh.write(line)
+ fh.write("\n")
+
+
+def iter_since(surface: Surface, since: datetime | None = None) -> Iterator[TraceEvent]:
+ """Yield events for ``surface`` in chronological order, optionally
+ filtering to events with ``ts >= since`` (UTC)."""
+ files = sorted(trace_dir(surface).glob("*.jsonl"))
+ cutoff_iso = since.isoformat() if since else ""
+ cutoff_date_iso = since.date().isoformat() if since else ""
+ for path in files:
+ if cutoff_date_iso and path.stem < cutoff_date_iso:
+ continue
+ try:
+ with path.open("r", encoding="utf-8") as fh:
+ for raw in fh:
+ raw = raw.strip()
+ if not raw:
+ continue
+ try:
+ obj = json.loads(raw)
+ except json.JSONDecodeError:
+ continue
+ if cutoff_iso and obj.get("ts", "") < cutoff_iso:
+ continue
+ yield TraceEvent(**obj)
+ except OSError:
+ continue
+
+
+def iter_by_ids(ids: list[str]) -> Iterator[TraceEvent]:
+ """Resolve trace ids back to their events. Cross-surface walk."""
+ wanted_by_surface: dict[str, set[str]] = {}
+ for tid in ids:
+ if ":" not in tid:
+ continue
+ surface, _ = tid.split(":", 1)
+ if surface in SURFACES:
+ wanted_by_surface.setdefault(surface, set()).add(tid)
+
+ for surface, wanted in wanted_by_surface.items():
+ for event in iter_since(surface): # type: ignore[arg-type]
+ if event.id in wanted:
+ yield event
+
+
+def count_since(surface: Surface, since: datetime | None = None) -> int:
+ return sum(1 for _ in iter_since(surface, since))
+
+
+def latest_ts(surface: Surface) -> str | None:
+ """Most recent event timestamp for ``surface``, or None."""
+ files = sorted(trace_dir(surface).glob("*.jsonl"), reverse=True)
+ for path in files:
+ try:
+ last = ""
+ with path.open("r", encoding="utf-8") as fh:
+ for raw in fh:
+ raw = raw.strip()
+ if raw:
+ last = raw
+ if last:
+ obj = json.loads(last)
+ ts = obj.get("ts")
+ if isinstance(ts, str):
+ return ts
+ except (OSError, json.JSONDecodeError):
+ continue
+ return None
diff --git a/deeptutor_cli/memory.py b/deeptutor_cli/memory.py
index 9e964bf97..71ed20bf1 100644
--- a/deeptutor_cli/memory.py
+++ b/deeptutor_cli/memory.py
@@ -1,18 +1,18 @@
-"""
-CLI memory commands for the two-file public memory system (SUMMARY/PROFILE).
-"""
+"""CLI memory commands for the three-layer memory subsystem (v2)."""
from __future__ import annotations
-from typing import cast
-
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
import typer
-from deeptutor.services.memory import get_memory_service
-from deeptutor.services.memory.service import MemoryFile
+from deeptutor.services.memory import (
+ L3_SLOTS,
+ SURFACES,
+ get_memory_store,
+ paths,
+)
console = Console()
@@ -20,54 +20,80 @@ console = Console()
def register(app: typer.Typer) -> None:
@app.command("show")
def memory_show(
- file: str = typer.Argument(
- "all",
- help="File to show: summary, profile, or all.",
+ target: str = typer.Argument(
+ "L3",
+ help="What to show: 'L3' (all four global docs), 'L2' (all seven surface docs), or a single doc name (e.g. 'profile', 'chat').",
),
) -> None:
- """Display memory file content."""
- svc = get_memory_service()
- if file == "all":
- snap = svc.read_snapshot()
- for label, content in [
- ("SUMMARY", snap.summary),
- ("PROFILE", snap.profile),
- ]:
- if content:
- console.print(Panel(Markdown(content), title=f"[bold]{label}.md[/]"))
+ """Display memory document content."""
+ store = get_memory_store()
+
+ if target == "L3":
+ text = store.read_l3_concat()
+ console.print(Panel(Markdown(text), title="[bold]L3 (concatenated)[/]"))
+ return
+
+ if target == "L2":
+ for surface in SURFACES:
+ content = store.read_raw("L2", surface)
+ if content.strip():
+ console.print(Panel(Markdown(content), title=f"[bold]L2/{surface}.md[/]"))
else:
- console.print(f"[dim]{label}.md: (empty)[/]")
- elif file in ("summary", "profile"):
- content = svc.read_file(cast(MemoryFile, file))
- if content:
- console.print(Panel(Markdown(content), title=f"[bold]{file.upper()}.md[/]"))
- else:
- console.print(f"[dim]{file.upper()}.md: (empty)[/]")
+ console.print(f"[dim]L2/{surface}.md: (empty)[/]")
+ return
+
+ # Single doc name — resolve to L2 or L3.
+ if target in L3_SLOTS:
+ content = store.read_raw("L3", target)
+ label = f"L3/{target}.md"
+ elif target in SURFACES:
+ content = store.read_raw("L2", target)
+ label = f"L2/{target}.md"
+ else:
+ console.print(
+ f"[red]Unknown doc: {target}. Use 'L2', 'L3', a surface ({', '.join(SURFACES)}), or a slot ({', '.join(L3_SLOTS)}).[/]"
+ )
+ raise typer.Exit(1)
+
+ if content.strip():
+ console.print(Panel(Markdown(content), title=f"[bold]{label}[/]"))
else:
- console.print(f"[red]Unknown file: {file}. Use summary, profile, or all.[/]")
+ console.print(f"[dim]{label}: (empty)[/]")
@app.command("clear")
def memory_clear(
- file: str = typer.Argument(
+ target: str = typer.Argument(
"all",
- help="File to clear: summary, profile, or all.",
+ help="What to clear: 'all' (entire memory), 'trace' (all L1 trace), or a surface name to clear that surface's L1.",
),
force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation."),
) -> None:
- """Clear memory file(s)."""
- svc = get_memory_service()
- if file not in ("summary", "profile", "all"):
- console.print(f"[red]Unknown file: {file}[/]")
+ """Clear memory (use 'all' for a full reset, or a surface name for L1 only)."""
+ if target != "all" and target != "trace" and target not in SURFACES:
+ console.print(f"[red]Unknown target: {target}[/]")
raise typer.Exit(1)
if not force:
- target = "all memory files" if file == "all" else f"{file.upper()}.md"
- if not typer.confirm(f"Clear {target}?"):
+ label = "all memory" if target == "all" else f"L1 trace for {target}"
+ if not typer.confirm(f"Clear {label}?"):
raise typer.Abort()
- if file == "all":
- svc.clear_memory()
- console.print("[green]Cleared all memory files.[/]")
+ if target == "all":
+ root = paths.memory_root()
+ for entry in root.iterdir() if root.exists() else []:
+ if entry.is_file():
+ entry.unlink()
+ elif entry.is_dir() and entry.name in {"trace", "L2", "L3"}:
+ for child in entry.rglob("*"):
+ if child.is_file():
+ child.unlink()
+ console.print("[green]Cleared all memory.[/]")
+ elif target == "trace":
+ for surface in SURFACES:
+ for f in paths.trace_dir(surface).glob("*.jsonl"):
+ f.unlink()
+ console.print("[green]Cleared all L1 trace.[/]")
else:
- svc.clear_file(cast(MemoryFile, file))
- console.print(f"[green]Cleared {file.upper()}.md.[/]")
+ for f in paths.trace_dir(target).glob("*.jsonl"): # type: ignore[arg-type]
+ f.unlink()
+ console.print(f"[green]Cleared L1 trace for {target}.[/]")
diff --git a/tests/api/test_memory_resolver.py b/tests/api/test_memory_resolver.py
new file mode 100644
index 000000000..744c05e82
--- /dev/null
+++ b/tests/api/test_memory_resolver.py
@@ -0,0 +1,84 @@
+"""GET /api/v1/memory/resolve_entry/{id} → (layer, key).
+
+L3 docs cite L2 entries by their ``m_<ULID>`` entry id. The resolver
+turns an L3 footnote click into "which L2 surface do I navigate to".
+"""
+
+from __future__ import annotations
+
+import importlib
+from pathlib import Path
+
+import pytest
+
+pytest.importorskip("fastapi")
+
+FastAPI = pytest.importorskip("fastapi").FastAPI
+TestClient = pytest.importorskip("fastapi.testclient").TestClient
+
+memory_router = importlib.import_module("deeptutor.api.routers.memory").router
+paths_mod = importlib.import_module("deeptutor.services.memory.paths")
+document_mod = importlib.import_module("deeptutor.services.memory.document")
+
+
+def client(tmp_path: Path, monkeypatch) -> TestClient:
+ monkeypatch.setattr(paths_mod, "memory_root", lambda: tmp_path)
+ (tmp_path / "L2").mkdir()
+ (tmp_path / "L3").mkdir()
+ app = FastAPI()
+ app.include_router(memory_router, prefix="/api/v1/memory")
+ return TestClient(app)
+
+
+def _seed_l2(tmp_path: Path, surface: str, entry_id: str) -> None:
+ doc = document_mod.Document(
+ title=f"{surface} memory",
+ sections=[
+ (
+ "Themes",
+ [
+ document_mod.Entry(
+ id=entry_id,
+ section="Themes",
+ text="some fact",
+ refs=[f"{surface}:r1"],
+ ),
+ ],
+ ),
+ ],
+ )
+ (tmp_path / "L2" / f"{surface}.md").write_text(
+ document_mod.serialize(doc), encoding="utf-8"
+ )
+
+
+def test_resolve_entry_returns_owning_surface(client: TestClient, tmp_path: Path) -> None:
+ entry_id = "m_01HZK1ABCDEFGHJKMNPQRSTVWX"
+ _seed_l2(tmp_path, "notebook", entry_id)
+
+ res = client.get(f"/api/v1/memory/resolve_entry/{entry_id}")
+ assert res.status_code == 200
+ body = res.json()
+ assert body == {"layer": "L2", "key": "notebook", "entry_id": entry_id}
+
+
+def test_resolve_entry_404_when_missing(client: TestClient) -> None:
+ res = client.get("/api/v1/memory/resolve_entry/m_01HZK1ABCDEFGHJKMNPQRSTVWX")
+ assert res.status_code == 404
+
+
+def test_resolve_entry_400_on_bad_id(client: TestClient) -> None:
+ res = client.get("/api/v1/memory/resolve_entry/not-an-entry-id")
+ assert res.status_code == 400
+
+
+def test_resolve_entry_first_hit_wins(client: TestClient, tmp_path: Path) -> None:
+ """Iteration order is the SURFACES tuple — chat before notebook."""
+ entry_id = "m_01HZK1ABCDEFGHJKMNPQRSTVWX"
+ _seed_l2(tmp_path, "chat", entry_id)
+ _seed_l2(tmp_path, "notebook", entry_id) # duplicate (shouldn't happen IRL)
+
+ res = client.get(f"/api/v1/memory/resolve_entry/{entry_id}")
+ assert res.status_code == 200
+ assert res.json()["key"] == "chat"
diff --git a/tests/api/test_memory_router.py b/tests/api/test_memory_router.py
deleted file mode 100644
index d56d455ab..000000000
--- a/tests/api/test_memory_router.py
+++ /dev/null
@@ -1,123 +0,0 @@
-from __future__ import annotations
-
-import importlib
-
-import pytest
-
-pytest.importorskip("fastapi")
-
-FastAPI = pytest.importorskip("fastapi").FastAPI
-TestClient = pytest.importorskip("fastapi.testclient").TestClient
-router = importlib.import_module("deeptutor.api.routers.memory").router
-
-
-def _build_app() -> FastAPI:
- app = FastAPI()
- app.include_router(router, prefix="/api/v1/memory")
- return app
-
-
-def _make_snapshot(
- summary: str = "",
- profile: str = "",
- summary_updated_at: str | None = None,
- profile_updated_at: str | None = None,
-):
- return type(
- "Snapshot",
- (),
- {
- "summary": summary,
- "profile": profile,
- "summary_updated_at": summary_updated_at,
- "profile_updated_at": profile_updated_at,
- },
- )()
-
-
-def test_memory_router_returns_single_document(monkeypatch) -> None:
- class FakeMemoryService:
- def read_snapshot(self):
- return _make_snapshot(
- profile="## Preferences\n- Prefer concise answers.",
- profile_updated_at="2026-03-13T12:00:00+08:00",
- )
-
- monkeypatch.setattr(
- "deeptutor.api.routers.memory.get_memory_service", lambda: FakeMemoryService()
- )
-
- with TestClient(_build_app()) as client:
- response = client.get("/api/v1/memory")
-
- assert response.status_code == 200
- body = response.json()
- assert body["profile"] == "## Preferences\n- Prefer concise answers."
- assert body["profile_updated_at"] == "2026-03-13T12:00:00+08:00"
- assert body["summary"] == ""
- assert body["summary_updated_at"] is None
-
-
-def test_memory_router_refreshes_from_session(monkeypatch) -> None:
- class FakeStore:
- async def get_session(self, session_id: str):
- if session_id == "missing":
- return None
- return {"session_id": session_id}
-
- _snapshot = _make_snapshot(
- profile="## Preferences\n- Prefer concise answers.",
- summary="## Current Focus\n- Working on memory.",
- profile_updated_at="2026-03-13T12:10:00+08:00",
- summary_updated_at="2026-03-13T12:10:00+08:00",
- )
-
- class FakeMemoryService:
- async def refresh_from_session(self, session_id, language="en"):
- return type("Result", (), {"changed": True})()
-
- def read_snapshot(self):
- return _snapshot
-
- monkeypatch.setattr(
- "deeptutor.api.routers.memory.get_sqlite_session_store", lambda: FakeStore()
- )
- monkeypatch.setattr(
- "deeptutor.api.routers.memory.get_memory_service", lambda: FakeMemoryService()
- )
-
- with TestClient(_build_app()) as client:
- response = client.post(
- "/api/v1/memory/refresh",
- json={"session_id": "unified_1", "language": "en"},
- )
-
- assert response.status_code == 200
- body = response.json()
- assert body["changed"] is True
- assert "Working on memory" in body["summary"]
- assert "Prefer concise answers" in body["profile"]
-
-
-def test_memory_router_updates_document(monkeypatch) -> None:
- class FakeMemoryService:
- def write_file(self, which, content: str):
- return _make_snapshot(
- profile=content if which == "profile" else "",
- profile_updated_at="2026-03-13T12:20:00+08:00",
- )
-
- monkeypatch.setattr(
- "deeptutor.api.routers.memory.get_memory_service", lambda: FakeMemoryService()
- )
-
- with TestClient(_build_app()) as client:
- response = client.put(
- "/api/v1/memory",
- json={"file": "profile", "content": "## Preferences\n- Prefer concise answers."},
- )
-
- assert response.status_code == 200
- body = response.json()
- assert body["saved"] is True
- assert body["profile"] == "## Preferences\n- Prefer concise answers."
diff --git a/tests/services/memory/test_chunker.py b/tests/services/memory/test_chunker.py
new file mode 100644
index 000000000..4415377a7
--- /dev/null
+++ b/tests/services/memory/test_chunker.py
@@ -0,0 +1,98 @@
+"""Tests for the character-based chunker with boundary expansion."""
+
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.services.memory.consolidator.chunker import (
+ ChunkSpan,
+ chunk_with_boundary,
+)
+
+
+def test_empty_input_returns_no_chunks() -> None:
+ assert chunk_with_boundary("", budget=5, overlap_ratio=0.1, min_chunk_chars=100, max_chunk_chars=1000) == []
+ assert chunk_with_boundary(" \n\n", budget=5, overlap_ratio=0.1, min_chunk_chars=100, max_chunk_chars=1000) == []
+
+
+def test_short_input_yields_one_chunk_covering_everything() -> None:
+ chunks = chunk_with_boundary(
+ "Hello world.", budget=5, overlap_ratio=0.1, min_chunk_chars=100, max_chunk_chars=1000
+ )
+ assert len(chunks) == 1
+ assert chunks[0].start == 0
+ assert chunks[0].end == len("Hello world.")
+
+
+def test_paragraph_boundary_extends_right_edge() -> None:
+ text = "A" * 100 + "\n\n" + "B" * 100 + "\n\n" + "C" * 100
+ chunks = chunk_with_boundary(
+ text, budget=2, overlap_ratio=0.0, min_chunk_chars=50, max_chunk_chars=400, boundary="paragraph"
+ )
+ # First chunk's end should land at a paragraph boundary (or end of text when budget=1).
+ assert chunks[0].text.endswith("\n\n") or chunks[0].end == len(text)
+ # Nothing is left out across the chunks (allowing for overlap).
+ assert chunks[-1].end == len(text)
+
+
+def test_sentence_boundary_used_when_configured() -> None:
+ sentences = " ".join(f"Sentence number {i}." for i in range(40))
+ chunks = chunk_with_boundary(
+ sentences,
+ budget=4,
+ overlap_ratio=0.05,
+ min_chunk_chars=80,
+ max_chunk_chars=400,
+ boundary="sentence",
+ )
+ # Each non-last chunk ends with terminal punctuation + space (the
+ # sentence boundary regex matches `.` followed by space).
+ for chunk in chunks[:-1]:
+ assert chunk.text[-1].isspace() or chunk.text.rstrip()[-1] in ".!?"
+
+
+def test_budget_caps_chunk_count() -> None:
+ text = ("paragraph body. " * 20 + "\n\n") * 30 # ~ 10k chars
+ chunks = chunk_with_boundary(
+ text, budget=5, overlap_ratio=0.1, min_chunk_chars=200, max_chunk_chars=8000
+ )
+ assert len(chunks) <= 5
+
+
+def test_overlap_visible_in_adjacent_chunks() -> None:
+ text = ("paragraph body. " * 20 + "\n\n") * 10
+ chunks = chunk_with_boundary(
+ text, budget=3, overlap_ratio=0.2, min_chunk_chars=200, max_chunk_chars=2000
+ )
+ if len(chunks) >= 2:
+ # The second chunk should start before the first ends.
+ assert chunks[1].start < chunks[0].end
+
+
+def test_min_chunk_chars_protects_against_tiny_chunks() -> None:
+ text = "x" * 500
+ chunks = chunk_with_boundary(
+ text, budget=50, overlap_ratio=0.0, min_chunk_chars=400, max_chunk_chars=1000
+ )
+ # 500 chars / budget=50 would suggest 10-char chunks; min_chunk_chars
+ # raises that to 400, so we get 1-2 chunks.
+ assert len(chunks) <= 2
+
+
+def test_max_chunk_chars_protects_against_huge_chunks() -> None:
+ text = "x" * 100_000
+ chunks = chunk_with_boundary(
+ text, budget=1, overlap_ratio=0.0, min_chunk_chars=200, max_chunk_chars=5000
+ )
+ # 1 chunk is impossible if max=5000 and input=100k; multiple chunks expected.
+ assert len(chunks) > 1
+ assert all(c.end - c.start <= 5000 * 2 for c in chunks) # boundary extension may push over
+
[email protected]("budget", [1, 5, 20, 100])
+def test_no_data_loss_chunks_cover_full_text(budget: int) -> None:
+ text = "\n\n".join(f"para {i}: " + "x" * 50 for i in range(50))
+ chunks = chunk_with_boundary(
+ text, budget=budget, overlap_ratio=0.1, min_chunk_chars=100, max_chunk_chars=2000
+ )
+ assert chunks[0].start == 0
+ assert chunks[-1].end == len(text)
diff --git a/tests/services/memory/test_consolidator.py b/tests/services/memory/test_consolidator.py
new file mode 100644
index 000000000..4d88a1622
--- /dev/null
+++ b/tests/services/memory/test_consolidator.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+from deeptutor.services.memory.consolidator import (
+ _filter_banned,
+ _has_banned,
+ _parse_ops_response,
+)
+from deeptutor.services.memory.ops import AddOp, DeleteOp, EditOp
+
+
+def test_has_banned_catches_english_absolutes() -> None:
+ assert _has_banned("user deeply understands")
+ assert _has_banned("Mastered the chain rule")
+ assert _has_banned("always picks examples first")
+
+
+def test_has_banned_catches_chinese_absolutes() -> None:
+ assert _has_banned("完全理解 ε-δ")
+ assert _has_banned("总是从极限切入")
+ assert _has_banned("用户彻底掌握了")
+
+
+def test_has_banned_allows_cjk_quoted_phrase() -> None:
+ # When wrapped in 「」 the phrase is a verbatim user quote.
+ assert not _has_banned("用户原话「彻底搞懂」是指掌握了符号")
+
+
+def test_has_banned_allows_double_quoted_phrase() -> None:
+ assert not _has_banned('user said "deeply" — context-specific')
+
+
+def test_has_banned_passes_neutral_text() -> None:
+ assert not _has_banned("Uses geometric intuition for limits")
+ assert not _has_banned("在 5 次 chat 互动中,呈现对极限的几何直觉")
+
+
+def test_filter_banned_drops_violating_ops_only() -> None:
+ ok_op = AddOp(section="S", text="uses Anki", refs=["chat:01HZK4AAAAAAAAAAAAAAAAAAAA"])
+ bad_op = AddOp(
+ section="S",
+ text="deeply understands FSRS",
+ refs=["chat:01HZK4BBBBBBBBBBBBBBBBBBBB"],
+ )
+ edit_bad = EditOp(
+ target_id="m_01HZK4ABCDEFGHJKMNPQRSTVWX",
+ new_text="mastered set theory",
+ new_refs=["chat:01HZK4CCCCCCCCCCCCCCCCCCCC"],
+ )
+ delete_neutral = DeleteOp(
+ target_id="m_01HZK5ABCDEFGHJKMNPQRSTVWX",
+ reason="stale",
+ )
+
+ kept = _filter_banned([ok_op, bad_op, edit_bad, delete_neutral])
+ assert kept == [ok_op, delete_neutral]
+
+
+def test_parse_ops_strips_code_fences() -> None:
+ raw = '```json\n{"ops": [{"op": "add", "section": "S", "text": "ok", "refs": ["chat:01HZK4AAAAAAAAAAAAAAAAAAAA"]}]}\n```'
+ ops = _parse_ops_response(raw)
+ assert len(ops) == 1
+ assert isinstance(ops[0], AddOp)
+ assert ops[0].text == "ok"
+
+
+def test_parse_ops_handles_prose_prefix() -> None:
+ raw = 'Here is my answer:\n{"ops": []}'
+ assert _parse_ops_response(raw) == []
+
+
+def test_parse_ops_returns_empty_on_garbage() -> None:
+ assert _parse_ops_response("not json at all") == []
+ assert _parse_ops_response('{"not_ops": []}') == []
diff --git a/tests/services/memory/test_document.py b/tests/services/memory/test_document.py
new file mode 100644
index 000000000..9ff4c542c
--- /dev/null
+++ b/tests/services/memory/test_document.py
@@ -0,0 +1,237 @@
+from __future__ import annotations
+
+from deeptutor.services.memory.document import Document, Entry, parse, serialize
+
+_SAMPLE = """\
+# Chat memory
+
+## Misconceptions
+- Student misreads "for all ε" as "for some ε"[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]
+- Forgets to multiply by g'(x) in chain rule[^m_01HZK5ABCDEFGHJKMNPQRSTVWX]
+
+## Mastery
+- Has geometric intuition for limits[^m_01HZK6ABCDEFGHJKMNPQRSTVWX]
+
+---
+
+[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]: chat:01HZK4AAAAAAAAAAAAAAAAAAAA, chat:01HZK4BBBBBBBBBBBBBBBBBBBB
+[^m_01HZK5ABCDEFGHJKMNPQRSTVWX]: chat:01HZK5CCCCCCCCCCCCCCCCCCCC
+[^m_01HZK6ABCDEFGHJKMNPQRSTVWX]: chat:01HZK6DDDDDDDDDDDDDDDDDDDD
+"""
+
+
+def test_parse_extracts_title_sections_entries() -> None:
+ doc = parse(_SAMPLE)
+ assert doc.title == "Chat memory"
+ assert len(doc.sections) == 2
+ section_names = [name for name, _ in doc.sections]
+ assert section_names == ["Misconceptions", "Mastery"]
+ assert len(doc.sections[0][1]) == 2
+ assert len(doc.sections[1][1]) == 1
+
+
+def test_parse_binds_refs_to_entries() -> None:
+ doc = parse(_SAMPLE)
+ first = doc.sections[0][1][0]
+ assert first.id == "m_01HZK4ABCDEFGHJKMNPQRSTVWX"
+ assert first.refs == [
+ "chat:01HZK4AAAAAAAAAAAAAAAAAAAA",
+ "chat:01HZK4BBBBBBBBBBBBBBBBBBBB",
+ ]
+
+
+def test_round_trip_is_idempotent() -> None:
+ doc = parse(_SAMPLE)
+ rendered = serialize(doc)
+ again = serialize(parse(rendered))
+ assert rendered == again
+
+
+def test_serialize_empty_doc() -> None:
+ assert serialize(Document()) == "\n"
+
+
+def test_serialize_skips_empty_sections() -> None:
+ doc = Document(title="X")
+ doc.sections.append(("Empty", []))
+ rendered = serialize(doc)
+ assert "Empty" not in rendered
+ assert rendered.startswith("# X")
+
+
+def test_find_and_remove() -> None:
+ doc = parse(_SAMPLE)
+ target = "m_01HZK5ABCDEFGHJKMNPQRSTVWX"
+ assert doc.find(target) is not None
+ assert doc.remove(target) is True
+ assert doc.find(target) is None
+ assert doc.remove(target) is False # already gone
+
+
+def test_section_entries_creates_when_missing() -> None:
+ doc = Document(title="X")
+ entries = doc.section_entries("New section")
+ entries.append(Entry(id="m_01HZK7ABCDEFGHJKMNPQRSTVWX", section="New section", text="hi"))
+ assert doc.sections == [("New section", entries)]
+ # Second call returns the same list, not a new one.
+ assert doc.section_entries("New section") is entries
+
+
+def test_parse_ignores_malformed_lines() -> None:
+ md = """\
+# T
+
+## S
+- text without id
+- text with id[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]
+
+random prose
+
+[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]: chat:01HZK4AAAAAAAAAAAAAAAAAAAA
+"""
+ doc = parse(md)
+ assert len(doc.sections[0][1]) == 1
+ assert doc.sections[0][1][0].text == "text with id"
+
+
+_NEW_SAMPLE = """\
+# Notebook memory
+
+## Concepts
+- Limit definition uses ε-δ pairing [^1] <!--m_01HZK4ABCDEFGHJKMNPQRSTVWX-->
+- Continuity implies sequential continuity [^1][^2] <!--m_01HZK5ABCDEFGHJKMNPQRSTVWX-->
+
+## Mastery
+- Has geometric intuition [^2] <!--m_01HZK6ABCDEFGHJKMNPQRSTVWX-->
+
+---
+
+[^1]: notebook:01HZK4AAAAAAAAAAAAAAAAAAAA
+[^2]: notebook:01HZK4BBBBBBBBBBBBBBBBBBBB
+"""
+
+
+def test_parse_new_format_resolves_refs_via_label_map() -> None:
+ doc = parse(_NEW_SAMPLE)
+ assert doc.title == "Notebook memory"
+ first = doc.sections[0][1][0]
+ assert first.id == "m_01HZK4ABCDEFGHJKMNPQRSTVWX"
+ assert first.refs == ["notebook:01HZK4AAAAAAAAAAAAAAAAAAAA"]
+ second = doc.sections[0][1][1]
+ assert second.refs == [
+ "notebook:01HZK4AAAAAAAAAAAAAAAAAAAA",
+ "notebook:01HZK4BBBBBBBBBBBBBBBBBBBB",
+ ]
+
+
+def test_serialize_consolidates_duplicate_refs() -> None:
+ """Five entries citing the same source render as ONE footnote definition."""
+ doc = Document(title="Notebook")
+ section: list[Entry] = []
+ doc.sections.append(("Concepts", section))
+ same_ref = "notebook:3a563e6f"
+ for i in range(5):
+ section.append(
+ Entry(
+ id=f"m_01HZK{i}ABCDEFGHJKMNPQRSTVWX",
+ section="Concepts",
+ text=f"fact {i}",
+ refs=[same_ref],
+ )
+ )
+ rendered = serialize(doc)
+ # All five bullets share the same [^1] marker.
+ assert rendered.count("[^1]") == 6 # 5 bullets + 1 def
+ # Only ONE footnote definition.
+ assert rendered.count(f"[^1]: {same_ref}") == 1
+ assert "[^2]" not in rendered
+
+
+def test_serialize_assigns_labels_in_first_appearance_order() -> None:
+ doc = Document(title="X")
+ section: list[Entry] = []
+ doc.sections.append(("S", section))
+ section.append(
+ Entry(
+ id="m_01HZK1ABCDEFGHJKMNPQRSTVWX",
+ section="S",
+ text="a",
+ refs=["chat:01", "chat:02"],
+ )
+ )
+ section.append(
+ Entry(
+ id="m_01HZK2ABCDEFGHJKMNPQRSTVWX",
+ section="S",
+ text="b",
+ refs=["chat:03", "chat:01"], # ``chat:01`` repeats earlier ref
+ )
+ )
+ rendered = serialize(doc)
+ assert "[^1]: chat:01" in rendered
+ assert "[^2]: chat:02" in rendered
+ assert "[^3]: chat:03" in rendered
+ # Second bullet cites refs in entry order — label 3 then label 1.
+ # Markers are ``, ``-separated so the rendered superscripts read
+ # "³, ¹" rather than the visually-merged "³¹".
+ assert "- b [^3], [^1] <!--m_01HZK2ABCDEFGHJKMNPQRSTVWX-->" in rendered
+
+
+def test_legacy_doc_serialized_then_reparsed_is_lossless() -> None:
+ """Migration path: old → new → parse → same entries."""
+ old = parse(_SAMPLE)
+ migrated = serialize(old)
+ reparsed = parse(migrated)
+ # Entry ids and refs are preserved across the migration.
+ assert [e.id for e in old.all_entries()] == [e.id for e in reparsed.all_entries()]
+ assert [e.refs for e in old.all_entries()] == [e.refs for e in reparsed.all_entries()]
+ assert [e.text for e in old.all_entries()] == [e.text for e in reparsed.all_entries()]
+
+
+def test_new_format_round_trip_is_idempotent() -> None:
+ doc = parse(_NEW_SAMPLE)
+ rendered = serialize(doc)
+ again = serialize(parse(rendered))
+ assert rendered == again
+
+
+def test_parse_tolerates_both_separator_styles_between_markers() -> None:
+ """Bullets emitted before the separator change had ``[^1][^2]`` —
+ the comma-tolerant parser still binds refs correctly on legacy
+ in-flight docs."""
+ md_compact = """\
+# X
+
+## S
+- a [^1][^2] <!--m_01HZK1ABCDEFGHJKMNPQRSTVWX-->
+
+---
+
+[^1]: chat:01
+[^2]: chat:02
+"""
+ md_spaced = """\
+# X
+
+## S
+- a [^1], [^2] <!--m_01HZK1ABCDEFGHJKMNPQRSTVWX-->
+
+---
+
+[^1]: chat:01
+[^2]: chat:02
+"""
+ a = parse(md_compact).all_entries()[0]
+ b = parse(md_spaced).all_entries()[0]
+ assert a.refs == b.refs == ["chat:01", "chat:02"]
+
+
+def test_serialize_omits_marker_when_entry_has_no_refs() -> None:
+ doc = Document(title="X")
+ section: list[Entry] = []
+ doc.sections.append(("S", section))
+ section.append(Entry(id="m_01HZK1ABCDEFGHJKMNPQRSTVWX", section="S", text="t", refs=[]))
+ rendered = serialize(doc)
+ assert "- t <!--m_01HZK1ABCDEFGHJKMNPQRSTVWX-->" in rendered
+ # No footnote definitions block at all when nothing has refs.
+ assert "---" not in rendered
diff --git a/tests/services/memory/test_ids.py b/tests/services/memory/test_ids.py
new file mode 100644
index 000000000..be0a5dbfc
--- /dev/null
+++ b/tests/services/memory/test_ids.py
@@ -0,0 +1,70 @@
+from __future__ import annotations
+
+import time
+
+from deeptutor.services.memory.ids import (
+ is_entry_id,
+ is_shortname_ref,
+ is_trace_id,
+ is_valid_ref,
+ new_entry_id,
+ new_trace_id,
+ new_ulid,
+)
+
+
+def test_ulid_length_and_charset() -> None:
+ u = new_ulid()
+ assert len(u) == 26
+ assert all(c in "0123456789ABCDEFGHJKMNPQRSTVWXYZ" for c in u)
+
+
+def test_ulid_monotonic_within_window() -> None:
+ # Within a few ms the timestamp prefix should sort consistently.
+ first = new_ulid()
+ time.sleep(0.005)
+ second = new_ulid()
+ assert first[:10] <= second[:10]
+
+
+def test_entry_id_shape_and_validation() -> None:
+ eid = new_entry_id()
+ assert eid.startswith("m_")
+ assert is_entry_id(eid)
+ assert not is_trace_id(eid)
+
+
+def test_trace_id_shape_and_validation() -> None:
+ tid = new_trace_id("chat")
+ assert tid.startswith("chat:")
+ assert is_trace_id(tid)
+ assert not is_entry_id(tid)
+
+
+def test_invalid_ids_rejected() -> None:
+ assert not is_entry_id("m_short")
+ assert not is_entry_id("foo")
+ assert not is_entry_id("")
+ assert not is_trace_id("01HZK4ABCDEFGHJKMNPQRSTVWX") # missing surface prefix
+ assert not is_trace_id("CHAT:01HZK4ABCDEFGHJKMNPQRSTVWX") # uppercase surface
+
+
+def test_uniqueness_across_calls() -> None:
+ ids = {new_ulid() for _ in range(1000)}
+ assert len(ids) == 1000
+
+
+def test_shortname_ref_accepts_known_surfaces() -> None:
+ """L3 refs are bare surface names. Whitelisted (not a loose regex)
+ so an LLM hallucination like ``not-an-id`` doesn't sneak through."""
+ for surface in ("chat", "notebook", "quiz", "kb", "book", "tutorbot", "cowriter"):
+ assert is_shortname_ref(surface), surface
+ # is_valid_ref must accept the new form so the ops validator does too.
+ assert is_valid_ref("chat")
+
+
+def test_shortname_ref_rejects_unknown_tokens() -> None:
+ assert not is_shortname_ref("CHAT")
+ assert not is_shortname_ref("not-an-id")
+ assert not is_shortname_ref("")
+ assert not is_shortname_ref("co-writer") # the actual surface is ``cowriter``
diff --git a/tests/services/memory/test_line_doc.py b/tests/services/memory/test_line_doc.py
new file mode 100644
index 000000000..6e77487cd
--- /dev/null
+++ b/tests/services/memory/test_line_doc.py
@@ -0,0 +1,201 @@
+"""Tests for the line-numbered document view + edit application."""
+
+from __future__ import annotations
+
+from deeptutor.services.memory.consolidator.line_doc import (
+ DeleteLinesOp,
+ InsertAfterOp,
+ ReplaceLineOp,
+ apply_edits,
+ parse_edits_payload,
+ render_view,
+)
+from deeptutor.services.memory.document import Document, Entry, serialize
+from deeptutor.services.memory.ids import new_entry_id
+
+
+def _doc_with_three_entries() -> tuple[Document, list[str]]:
+ ids = [new_entry_id() for _ in range(3)]
+ doc = Document(
+ title="notebook memory",
+ sections=[
+ (
+ "Themes",
+ [
+ Entry(id=ids[0], section="Themes", text="uses spaced repetition", refs=["notebook:r1"]),
+ Entry(id=ids[1], section="Themes", text="prefers Anki over Quizlet", refs=["notebook:r2"]),
+ ],
+ ),
+ (
+ "Open questions",
+ [
+ Entry(id=ids[2], section="Open questions", text="ε-δ geometric meaning", refs=["notebook:r3"]),
+ ],
+ ),
+ ],
+ )
+ return doc, ids
+
+
+def test_render_view_shows_lines_and_section_headers() -> None:
+ doc, ids = _doc_with_three_entries()
+ view = render_view(doc)
+ text = view.render()
+ assert "## Themes" in text
+ assert "## Open questions" in text
+ assert f"[^{ids[0]}]" in text
+
+
+def test_render_view_strips_footnote_block() -> None:
+ doc, _ = _doc_with_three_entries()
+ view = render_view(doc)
+ # Sanitized view never contains a footnote definition.
+ assert "[^" in view.render() # bullet markers ok
+ assert ": notebook:" not in view.render() # footnote-body line absent
+
+
+def test_replace_preserves_entry_id_and_replaces_refs() -> None:
+ doc, ids = _doc_with_three_entries()
+ view = render_view(doc)
+ target_line = next(l for l in view.lines if l.entry_id == ids[0])
+ edit = ReplaceLineOp(
+ line=target_line.number,
+ new_text="uses SRS with FSRS scheduling",
+ refs=["notebook:r1", "notebook:r1b"],
+ reason="more specific",
+ )
+ new_doc, report = apply_edits(doc, [edit])
+ assert not report.rejected
+ entry = next(e for e in new_doc.all_entries() if e.id == ids[0])
+ assert entry.text == "uses SRS with FSRS scheduling"
+ assert entry.refs == ["notebook:r1", "notebook:r1b"]
+
+
+def test_delete_lines_removes_entries_and_collapses_empty_section() -> None:
+ doc, ids = _doc_with_three_entries()
+ view = render_view(doc)
+ target_line = next(l for l in view.lines if l.entry_id == ids[2])
+ edit = DeleteLinesOp(line_start=target_line.number, line_end=target_line.number, reason="stale")
+ new_doc, report = apply_edits(doc, [edit])
+ assert not report.rejected
+ assert all(e.id != ids[2] for e in new_doc.all_entries())
+ section_names = [name for name, _ in new_doc.sections]
+ assert "Open questions" not in section_names # empty section dropped
+
+
+def test_insert_after_bullet_keeps_section_context() -> None:
+ doc, ids = _doc_with_three_entries()
+ view = render_view(doc)
+ anchor = next(l for l in view.lines if l.entry_id == ids[1])
+ edit = InsertAfterOp(
+ after_line=anchor.number,
+ text="uses Obsidian for daily notes",
+ refs=["notebook:r4"],
+ reason="new evidence",
+ )
+ new_doc, report = apply_edits(doc, [edit])
+ assert not report.rejected
+ themes = next(entries for name, entries in new_doc.sections if name == "Themes")
+ assert any(e.text == "uses Obsidian for daily notes" for e in themes)
+
+
+def test_replace_rejects_when_refs_empty() -> None:
+ doc, ids = _doc_with_three_entries()
+ view = render_view(doc)
+ target_line = next(l for l in view.lines if l.entry_id == ids[0])
+ edit = ReplaceLineOp(line=target_line.number, new_text="hello", refs=[], reason="bad")
+ new_doc, report = apply_edits(doc, [edit])
+ assert len(report.rejected) == 1
+ # Original text still there.
+ assert any(e.text == "uses spaced repetition" for e in new_doc.all_entries())
+
+
+def test_apply_in_reverse_order_does_not_shift_line_numbers() -> None:
+ doc, ids = _doc_with_three_entries()
+ view = render_view(doc)
+ l_first = next(l for l in view.lines if l.entry_id == ids[0])
+ l_third = next(l for l in view.lines if l.entry_id == ids[2])
+
+ # Delete line 8 (the third entry) and replace line 4 (the first
+ # entry) — these are valid line numbers in the original view.
+ edits = [
+ ReplaceLineOp(line=l_first.number, new_text="updated", refs=["notebook:r1"], reason="x"),
+ DeleteLinesOp(line_start=l_third.number, line_end=l_third.number, reason="stale"),
+ ]
+ new_doc, report = apply_edits(doc, edits)
+ assert not report.rejected
+ assert any(e.text == "updated" for e in new_doc.all_entries())
+ assert all(e.id != ids[2] for e in new_doc.all_entries())
+
+
+def test_parse_edits_payload_tolerates_fences_and_prose() -> None:
+ raw = """Here are my edits:
+ ```json
+ {"edits": [
+ {"op": "replace", "line": 4, "new_text": "x", "refs": ["a:b"], "reason": "y"},
+ {"op": "delete", "line_start": 8, "line_end": 8, "reason": "z"}
+ ]}
+ ```"""
+ edits = parse_edits_payload(raw)
+ assert len(edits) == 2
+ assert isinstance(edits[0], ReplaceLineOp)
+ assert isinstance(edits[1], DeleteLinesOp)
+
+
+def test_parse_edits_payload_strips_ref_wrapper_chars() -> None:
+ """LLM sometimes echoes ``[^m_xxx]`` markers from the line view —
+ caret and brackets included — into the refs array."""
+ raw = """{"edits": [
+ {"op": "replace", "line": 4, "new_text": "x",
+ "refs": ["^m_01HZK1ABCDEFGHJKMNPQRSTVWX", " [chat:01] "],
+ "reason": "y"}
+ ]}"""
+ edits = parse_edits_payload(raw, layer="L3")
+ assert isinstance(edits[0], ReplaceLineOp)
+ # In L3 mode the m_<ULID> form is legal (L3 refs are L2 entry ids),
+ # so it survives — but only with the ``^`` and surrounding noise
+ # stripped.
+ assert edits[0].refs == ["m_01HZK1ABCDEFGHJKMNPQRSTVWX", "chat:01"]
+
+
+def test_parse_edits_payload_drops_entry_id_refs_in_l2() -> None:
+ """L2 refs are ``surface:id`` shaped; ``m_<ULID>`` in L2 is the
+ audit/dedup LLM hallucinating from the line-numbered view (it sees
+ each bullet's entry-id anchor and copies it as a ref). Drop those."""
+ raw = """{"edits": [
+ {"op": "replace", "line": 4, "new_text": "x",
+ "refs": ["^m_01HZK1ABCDEFGHJKMNPQRSTVWX", "cowriter:abc"],
+ "reason": "y"}
+ ]}"""
+ edits = parse_edits_payload(raw, layer="L2")
+ assert isinstance(edits[0], ReplaceLineOp)
+ assert edits[0].refs == ["cowriter:abc"]
+
+
+def test_parse_edits_payload_default_layer_keeps_everything() -> None:
+ """Without a layer hint we only strip wrappers — never drop refs."""
+ raw = """{"edits": [
+ {"op": "insert", "after_line": 0, "text": "t",
+ "refs": ["^m_01HZK1ABCDEFGHJKMNPQRSTVWX", "chat:01"],
+ "reason": "r"}
+ ]}"""
+ edits = parse_edits_payload(raw)
+ assert isinstance(edits[0], InsertAfterOp)
+ assert edits[0].refs == ["m_01HZK1ABCDEFGHJKMNPQRSTVWX", "chat:01"]
+
+
+def test_serialize_roundtrip_after_edits_keeps_footnotes_consistent() -> None:
+ doc, ids = _doc_with_three_entries()
+ view = render_view(doc)
+ edit = ReplaceLineOp(
+ line=next(l for l in view.lines if l.entry_id == ids[0]).number,
+ new_text="updated text",
+ refs=["notebook:r1-new"],
+ reason="x",
+ )
+ new_doc, _ = apply_edits(doc, [edit])
+ md = serialize(new_doc)
+ # Footnote section reflects the updated refs (auto-rebuilt).
+ assert "notebook:r1-new" in md
+ # The old ref text is gone from footnotes (replaced, not appended).
+ assert "notebook:r1," not in md and "notebook:r1\n" not in md
diff --git a/tests/services/memory/test_memory_service.py b/tests/services/memory/test_memory_service.py
deleted file mode 100644
index bcaac9048..000000000
--- a/tests/services/memory/test_memory_service.py
+++ /dev/null
@@ -1,209 +0,0 @@
-from __future__ import annotations
-
-from deeptutor.services.memory.service import MemoryService
-from deeptutor.services.session.sqlite_store import SQLiteSessionStore
-
-
-def _make_service(tmp_path):
- store = SQLiteSessionStore(tmp_path / "chat_history.db")
- return MemoryService(
- path_service=type(
- "PathServiceStub",
- (),
- {"get_memory_dir": lambda self: tmp_path / "memory"},
- )(),
- store=store,
- )
-
-
-def test_memory_service_snapshot_is_empty_without_file(tmp_path) -> None:
- service = _make_service(tmp_path)
- snapshot = service.read_snapshot()
-
- assert snapshot.summary == ""
- assert snapshot.profile == ""
- assert snapshot.summary_updated_at is None
- assert snapshot.profile_updated_at is None
-
-
-def test_memory_context_requires_explicit_files(tmp_path) -> None:
- service = _make_service(tmp_path)
- service.write_file("summary", "## Current Focus\n- Linear algebra")
- service.write_file("profile", "## Preferences\n- Concise answers")
-
- assert service.build_memory_context() == ""
- assert service.build_memory_context([]) == ""
-
-
-def test_memory_context_can_include_summary_only(tmp_path) -> None:
- service = _make_service(tmp_path)
- service.write_file("summary", "## Current Focus\n- Linear algebra")
- service.write_file("profile", "## Preferences\n- Concise answers")
-
- context = service.build_memory_context(["summary"])
-
- assert "## Background Memory" in context
- assert "### Learning Context" in context
- assert "Linear algebra" in context
- assert "### User Profile" not in context
- assert "Concise answers" not in context
-
-
-def test_memory_context_can_include_profile_only(tmp_path) -> None:
- service = _make_service(tmp_path)
- service.write_file("summary", "## Current Focus\n- Linear algebra")
- service.write_file("profile", "## Preferences\n- Concise answers")
-
- context = service.build_memory_context(["profile"])
-
- assert "## Background Memory" in context
- assert "### User Profile" in context
- assert "Concise answers" in context
- assert "### Learning Context" not in context
- assert "Linear algebra" not in context
-
-
-async def _no_change_stream(**_kwargs):
- yield "NO_CHANGE"
-
-
-async def _rewrite_stream(**_kwargs):
- yield "## Preferences\n- Prefer concise answers.\n\n## Context\n- Working on DeepTutor memory."
-
-
-async def _thinking_rewrite_stream(**_kwargs):
- yield "<think>private reasoning</think>\n## Preferences\n- Prefer concise answers."
-
-
-async def _unclosed_thinking_stream(**_kwargs):
- yield "## Current Focus\n- Algebra\n<think>unfinished private reasoning"
-
-
-async def _invalid_profile_stream(**_kwargs):
- yield "The derivative of x^2 is 2x. This is an answer, not a profile."
-
-
-def test_memory_service_refresh_turn_writes_rewritten_document(monkeypatch, tmp_path) -> None:
- service = _make_service(tmp_path)
- monkeypatch.setattr("deeptutor.services.memory.service.llm_stream", _rewrite_stream)
-
- import asyncio
-
- result = asyncio.run(
- service.refresh_from_turn(
- user_message="Please remember that I like concise answers.",
- assistant_message="Sure, I'll keep answers concise.",
- session_id="s1",
- capability="chat",
- language="en",
- )
- )
-
- assert result.changed is True
- assert "concise answers" in result.content
- assert service._path("profile").exists() or service._path("summary").exists()
-
-
-def test_memory_service_refresh_turn_skips_when_model_returns_no_change(
- monkeypatch,
- tmp_path,
-) -> None:
- service = _make_service(tmp_path)
- monkeypatch.setattr("deeptutor.services.memory.service.llm_stream", _no_change_stream)
-
- import asyncio
-
- result = asyncio.run(
- service.refresh_from_turn(
- user_message="What is 2+2?",
- assistant_message="4",
- session_id="s1",
- capability="chat",
- language="en",
- )
- )
-
- assert result.changed is False
- assert result.content == ""
- assert not service._path("profile").exists()
- assert not service._path("summary").exists()
-
-
-def test_memory_service_refresh_strips_thinking_tags(monkeypatch, tmp_path) -> None:
- service = _make_service(tmp_path)
- monkeypatch.setattr("deeptutor.services.memory.service.llm_stream", _thinking_rewrite_stream)
-
- import asyncio
-
- result = asyncio.run(
- service.refresh_from_turn(
- user_message="Please remember that I like concise answers.",
- assistant_message="Sure.",
- session_id="s1",
- capability="chat",
- language="en",
- )
- )
-
- assert result.changed is True
- profile = service.read_profile()
- summary = service.read_summary()
- assert "Prefer concise answers" in profile
- assert "<think" not in profile.lower()
- assert "private reasoning" not in profile
- assert "<think" not in summary.lower()
- assert "private reasoning" not in summary
-
-
-def test_memory_service_refresh_strips_unclosed_thinking_tags(monkeypatch, tmp_path) -> None:
- service = _make_service(tmp_path)
- monkeypatch.setattr("deeptutor.services.memory.service.llm_stream", _unclosed_thinking_stream)
-
- import asyncio
-
- asyncio.run(
- service.refresh_from_turn(
- user_message="Study algebra.",
- assistant_message="Done.",
- session_id="s1",
- capability="chat",
- language="en",
- )
- )
-
- assert service.read_profile() == ""
- assert service.read_summary() == "## Current Focus\n- Algebra"
- assert "<think" not in service.read_summary().lower()
-
-
-def test_memory_service_rejects_invalid_profile_rewrite(monkeypatch, tmp_path) -> None:
- service = _make_service(tmp_path)
- monkeypatch.setattr("deeptutor.services.memory.service.llm_stream", _invalid_profile_stream)
-
- import asyncio
-
- changed = asyncio.run(
- service._rewrite_one(
- "profile",
- "[User]\nWhat is d/dx x^2?\n\n[Assistant]\n2x",
- "en",
- )
- )
-
- assert changed is False
- assert service.read_profile() == ""
- assert not service._path("profile").exists()
-
-
-def test_memory_service_repairs_existing_thinking_tags_on_read(tmp_path) -> None:
- service = _make_service(tmp_path)
- service._path("summary").parent.mkdir(parents=True, exist_ok=True)
- service._path("summary").write_text(
- "## Current Focus\n- Algebra\n<think>old private reasoning</think>",
- encoding="utf-8",
- )
-
- assert service.read_summary() == "## Current Focus\n- Algebra"
- persisted = service._path("summary").read_text(encoding="utf-8")
- assert "<think" not in persisted.lower()
- assert "old private reasoning" not in persisted
diff --git a/tests/services/memory/test_merge.py b/tests/services/memory/test_merge.py
new file mode 100644
index 000000000..91dc6cbb0
--- /dev/null
+++ b/tests/services/memory/test_merge.py
@@ -0,0 +1,259 @@
+"""Tests for the merge mode (footnote consolidation, no-LLM)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from deeptutor.services.memory import paths as paths_mod
+from deeptutor.services.memory.consolidator.modes import merge as merge_mod
+from deeptutor.services.memory.document import Document, Entry, parse, serialize
+
+
+def memory_dir(tmp_path: Path, monkeypatch):
+ monkeypatch.setattr(paths_mod, "memory_root", lambda: tmp_path)
+ (tmp_path / "L2").mkdir(parents=True, exist_ok=True)
+ (tmp_path / "L3").mkdir(parents=True, exist_ok=True)
+ yield tmp_path
+
+
+# A legacy doc: five entries, each citing the same ref. The on-disk file
+# has five identical-looking footnote rows that the workbench renders as
+# `25. notebook:3a563e6f`, `26. notebook:3a563e6f`, etc.
+_LEGACY_DOC_WITH_DUPLICATES = """\
+# notebook memory
+
+## Concepts
+- understands FSRS scheduling[^m_01HZK1ABCDEFGHJKMNPQRSTVWX]
+- understands ε-δ definition[^m_01HZK2ABCDEFGHJKMNPQRSTVWX]
+- understands monotone convergence[^m_01HZK3ABCDEFGHJKMNPQRSTVWX]
+- understands chain rule[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]
+- understands integration by parts[^m_01HZK5ABCDEFGHJKMNPQRSTVWX]
+
+---
+
+[^m_01HZK1ABCDEFGHJKMNPQRSTVWX]: notebook:3a563e6f
+[^m_01HZK2ABCDEFGHJKMNPQRSTVWX]: notebook:3a563e6f
+[^m_01HZK3ABCDEFGHJKMNPQRSTVWX]: notebook:3a563e6f
+[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]: notebook:3a563e6f
+[^m_01HZK5ABCDEFGHJKMNPQRSTVWX]: notebook:3a563e6f
+"""
+
+
+async def test_merge_collapses_duplicate_footnotes(memory_dir):
+ target = paths_mod.l2_file("notebook")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(_LEGACY_DOC_WITH_DUPLICATES, encoding="utf-8")
+
+ events: list[dict] = []
+
+ async def collect(evt):
+ events.append(evt)
+
+ result = await merge_mod.run_merge("L2", "notebook", on_event=collect)
+
+ assert result.rewrote is True
+ assert result.footnote_rows_before == 5 # five legacy [^m_xxx]: rows
+ assert result.footnote_rows_after == 1 # one unique ref → one footnote
+
+ new_text = target.read_text(encoding="utf-8")
+ # The on-disk file is now in the new format — one footnote definition.
+ assert new_text.count("[^1]: notebook:3a563e6f") == 1
+ assert "[^2]" not in new_text # no second unique ref
+ # All five bullets cite [^1].
+ assert new_text.count("[^1]") == 6 # 5 bullets + 1 def
+ # Round-trip preserves all five entries with the shared ref.
+ doc = parse(new_text)
+ assert len(doc.all_entries()) == 5
+ for entry in doc.all_entries():
+ assert entry.refs == ["notebook:3a563e6f"]
+
+ stages = [e["stage"] for e in events]
+ assert "doc_updated" in stages
+ done = next(e for e in events if e["stage"] == "done")
+ assert done["rewrote"] is True
+ assert done["footnote_rows_before"] == 5
+ assert done["footnote_rows_after"] == 1
+
+
+async def test_merge_is_idempotent_on_already_merged_doc(memory_dir):
+ target = paths_mod.l2_file("notebook")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(_LEGACY_DOC_WITH_DUPLICATES, encoding="utf-8")
+
+ # First pass migrates legacy → new and consolidates.
+ await merge_mod.run_merge("L2", "notebook")
+ after_first = target.read_text(encoding="utf-8")
+
+ # Second pass should leave the file byte-equal and skip the checkpoint.
+ events: list[dict] = []
+
+ async def collect(evt):
+ events.append(evt)
+
+ result = await merge_mod.run_merge("L2", "notebook", on_event=collect)
+ assert result.rewrote is False
+ assert target.read_text(encoding="utf-8") == after_first
+ # No doc_updated emitted on a no-op pass.
+ assert "doc_updated" not in {e["stage"] for e in events}
+
+
+async def test_merge_no_op_when_doc_missing(memory_dir):
+ events: list[dict] = []
+
+ async def collect(evt):
+ events.append(evt)
+
+ result = await merge_mod.run_merge("L2", "notebook", on_event=collect)
+ assert result.rewrote is False
+ assert result.footnote_rows_before == 0
+ assert result.footnote_rows_after == 0
+ done = next(e for e in events if e["stage"] == "done")
+ assert done["no_doc"] is True
+
+
+async def test_auto_merge_runs_even_when_update_added_no_facts(memory_dir, monkeypatch):
+ """Doc in legacy format gets migrated even on a no-op update.
+
+ This is the bug we hit in the wild: the user presses "Update" on a
+ surface with no new L1 entities; ``facts_added`` is 0; the old
+ ``if facts_added > 0`` guard meant merge never ran and the legacy
+ duplicate footnotes stayed on disk.
+ """
+ target = paths_mod.l2_file("notebook")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(_LEGACY_DOC_WITH_DUPLICATES, encoding="utf-8")
+
+ # No new entities → run_update hits the early-return path.
+ monkeypatch.setattr(
+ "deeptutor.services.memory.consolidator.modes.update.snap.read_snapshot",
+ lambda surface: [],
+ )
+
+ from deeptutor.services.memory.consolidator.modes import update as update_mod
+
+ result = await update_mod.run_update("L2", "notebook")
+ assert result.facts_added == 0
+ assert getattr(result, "no_new_input", False) is True
+
+ # ...but the legacy doc was still migrated by auto-merge.
+ new_text = target.read_text(encoding="utf-8")
+ assert new_text.count("[^1]: notebook:3a563e6f") == 1
+ assert new_text.count("[^m_") == 0 # legacy entry-keyed footnotes gone
+
+
+def _seed_l2(surface: str, entry_id: str) -> None:
+ """Write a one-entry L2 md owning ``entry_id``."""
+ doc = Document(
+ title=f"{surface} memory",
+ sections=[
+ (
+ "Themes",
+ [Entry(id=entry_id, section="Themes", text="fact", refs=[f"{surface}:r1"])],
+ ),
+ ],
+ )
+ target = paths_mod.l2_file(surface)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(serialize(doc), encoding="utf-8")
+
+
+async def test_merge_migrates_legacy_l3_entry_refs_to_surface_names(memory_dir):
+ """Pre-pivot L3 docs cite L2 entries by id (``m_<ULID>``); merge
+ resolves each id to its owning L2 surface so the rendered L3 doc
+ becomes a 7-footnote L3 → L2 → L1 chain.
+ """
+ chat_id = "m_01HZK1ABCDEFGHJKMNPQRSTVWX"
+ notebook_id = "m_01HZK2ABCDEFGHJKMNPQRSTVWX"
+ _seed_l2("chat", chat_id)
+ _seed_l2("notebook", notebook_id)
+
+ # Legacy L3: one entry citing both L2 entry ids (entry-keyed footnote
+ # layout, as written by pre-pivot consolidator runs).
+ legacy_l3 = f"""# User profile
+
+## Knowledge
+- claim about user[^m_01HZK9ABCDEFGHJKMNPQRSTVWX]
+
+[^m_01HZK9ABCDEFGHJKMNPQRSTVWX]: {chat_id}, {notebook_id}
+"""
+ target = paths_mod.l3_file("profile")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(legacy_l3, encoding="utf-8")
+
+ result = await merge_mod.run_merge("L3", "profile")
+ assert result.legacy_l3_refs_migrated == 2
+
+ new_text = target.read_text(encoding="utf-8")
+ # Both entry ids are gone; each was rewritten to its owning surface.
+ assert chat_id not in new_text
+ assert notebook_id not in new_text
+ assert "[^1]: chat" in new_text
+ assert "[^2]: notebook" in new_text
+
+
+async def test_merge_drops_legacy_l3_refs_when_l2_entry_missing(memory_dir):
+ """An ``m_<ULID>`` we can't resolve (entry deleted) is dropped, not
+ surfaced as a malformed ref."""
+ # No L2 seed — every m_<ULID> ref will be unresolvable, so the
+ # migration counts the visit but drops the ref.
+ legacy_l3 = """# User profile
+
+## Knowledge
+- orphaned claim[^m_01HZK9ABCDEFGHJKMNPQRSTVWX]
+
+[^m_01HZK9ABCDEFGHJKMNPQRSTVWX]: m_01HZKAAAAAAAAAAAAAAAAAAAAA
+"""
+ target = paths_mod.l3_file("profile")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(legacy_l3, encoding="utf-8")
+
+ result = await merge_mod.run_merge("L3", "profile")
+ assert result.legacy_l3_refs_migrated == 1
+
+ new_text = target.read_text(encoding="utf-8")
+ assert "m_01HZKAAAAAAAA" not in new_text
+ # Entry survives with no refs left.
+ doc = parse(new_text)
+ assert len(doc.all_entries()) == 1
+ assert doc.all_entries()[0].refs == []
+
+
+async def test_merge_handles_mixed_ref_set(memory_dir):
+ """Entries can cite different refs; only true duplicates collapse."""
+ mixed = """\
+# notebook memory
+
+## Concepts
+- fact A[^m_01HZK1ABCDEFGHJKMNPQRSTVWX]
+- fact B[^m_01HZK2ABCDEFGHJKMNPQRSTVWX]
+- fact C[^m_01HZK3ABCDEFGHJKMNPQRSTVWX]
+
+---
+
+[^m_01HZK1ABCDEFGHJKMNPQRSTVWX]: notebook:3a563e6f
+[^m_01HZK2ABCDEFGHJKMNPQRSTVWX]: notebook:7b778822
+[^m_01HZK3ABCDEFGHJKMNPQRSTVWX]: notebook:3a563e6f
+"""
+ target = paths_mod.l2_file("notebook")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(mixed, encoding="utf-8")
+
+ result = await merge_mod.run_merge("L2", "notebook")
+ assert result.footnote_rows_before == 3
+ assert result.footnote_rows_after == 2
+
+ new_text = target.read_text(encoding="utf-8")
+ # First-appearance order: 3a563e6f is [^1], 7b778822 is [^2].
+ assert "[^1]: notebook:3a563e6f" in new_text
+ assert "[^2]: notebook:7b778822" in new_text
+ assert "[^3]" not in new_text
diff --git a/tests/services/memory/test_meta_settings.py b/tests/services/memory/test_meta_settings.py
new file mode 100644
index 000000000..a5869d2de
--- /dev/null
+++ b/tests/services/memory/test_meta_settings.py
@@ -0,0 +1,95 @@
+"""Tests for meta.json sidecars + memory settings loader."""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+from deeptutor.services.memory.consolidator import meta as meta_mod
+from deeptutor.services.memory.settings import (
+ MemorySettings,
+ load_memory_settings,
+ save_memory_settings,
+)
+
+
+def test_settings_defaults_match_spec() -> None:
+ s = MemorySettings()
+ assert s.update.l2_budget == 30
+ assert s.update.l3_budget == 10
+ assert s.audit.l2_budget == 30
+ assert s.audit.l3_budget == 10
+ assert s.dedup.iterations == 3
+ assert s.dedup.auto_after_update is True
+ assert s.chunking.overlap_ratio == 0.10
+ assert s.chunking.boundary == "paragraph"
+ assert s.chunking.min_chunk_chars == 800
+ assert s.chunking.max_chunk_chars == 8000
+ assert s.reference.enforce_required is True
+ assert s.reference.drop_invalid_refs is True
+
+
+def test_settings_partial_payload_falls_back_to_defaults() -> None:
+ with patch.object(load_memory_settings.__wrapped__ if hasattr(load_memory_settings, "__wrapped__") else load_memory_settings, "__call__", create=True):
+ pass # no-op; the next assertion exercises the real coercion path
+ from deeptutor.services.memory.settings import _from_dict
+ merged = _from_dict(
+ MemorySettings,
+ {"update": {"l2_budget": 42}, "chunking": {"overlap_ratio": 0.25}},
+ )
+ assert merged.update.l2_budget == 42
+ assert merged.update.l3_budget == 10 # default
+ assert merged.chunking.overlap_ratio == 0.25
+ assert merged.chunking.min_chunk_chars == 800
+
+
+def test_settings_clamps_out_of_range_values() -> None:
+ from deeptutor.services.memory.settings import _from_dict
+ merged = _from_dict(
+ MemorySettings,
+ {
+ "update": {"l2_budget": 9999, "l3_budget": -10},
+ "dedup": {"iterations": 99},
+ "chunking": {"overlap_ratio": 2.0, "boundary": "not-real"},
+ },
+ )
+ assert 1 <= merged.update.l2_budget <= 200
+ assert 1 <= merged.update.l3_budget <= 200
+ assert 1 <= merged.dedup.iterations <= 20
+ assert 0.0 <= merged.chunking.overlap_ratio <= 0.5
+ assert merged.chunking.boundary == "paragraph" # invalid choice → default
+
+
+def test_l2_meta_roundtrip(tmp_path, monkeypatch) -> None:
+ # Redirect paths to a temp memory dir.
+ from deeptutor.services.memory import paths as paths_mod
+
+ monkeypatch.setattr(paths_mod, "memory_root", lambda: tmp_path)
+ (tmp_path / "L2").mkdir(parents=True, exist_ok=True)
+
+ refs = {"chat:01ABC", "chat:01DEF"}
+ meta = meta_mod.save_l2_meta("chat", seen_entity_refs=refs)
+ assert meta.seen_entity_refs == refs
+
+ reloaded = meta_mod.load_l2_meta("chat")
+ assert reloaded.seen_entity_refs == refs
+ assert reloaded.last_update_at is not None
+
+
+def test_l3_meta_roundtrip(tmp_path, monkeypatch) -> None:
+ from deeptutor.services.memory import paths as paths_mod
+
+ monkeypatch.setattr(paths_mod, "memory_root", lambda: tmp_path)
+ (tmp_path / "L3").mkdir(parents=True, exist_ok=True)
+
+ seen = {"chat": {"m_a", "m_b"}, "notebook": {"m_c"}}
+ meta_mod.save_l3_meta("recent", seen_l2_entry_ids=seen)
+ reloaded = meta_mod.load_l3_meta("recent")
+ assert reloaded.seen_l2_entry_ids == seen
+
+
+def test_l2_meta_missing_file_returns_empty() -> None:
+ from deeptutor.services.memory.consolidator.meta import L2Meta
+
+ m = L2Meta()
+ assert m.seen_entity_refs == set()
+ assert m.last_update_at is None
diff --git a/tests/services/memory/test_modes.py b/tests/services/memory/test_modes.py
new file mode 100644
index 000000000..9120bbaf3
--- /dev/null
+++ b/tests/services/memory/test_modes.py
@@ -0,0 +1,275 @@
+"""End-to-end (LLM-mocked) tests for the three modes.
+
+These are the load-bearing tests for the new pipeline. The LLM call is
+mocked at the ``call_llm`` boundary in :mod:`modes._runtime`; everything
+else (chunker, ref validation, doc IO, meta) runs for real on a temp
+memory dir.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from deeptutor.services.memory import paths as paths_mod
+from deeptutor.services.memory.consolidator.modes import update as update_mod
+from deeptutor.services.memory.consolidator.modes import audit as audit_mod
+from deeptutor.services.memory.consolidator.modes import dedup as dedup_mod
+from deeptutor.services.memory.document import Document, Entry, parse, serialize
+from deeptutor.services.memory.ids import new_entry_id
+from deeptutor.services.memory.snapshot.entity import Entity
+
+
+def memory_dir(tmp_path: Path, monkeypatch):
+ monkeypatch.setattr(paths_mod, "memory_root", lambda: tmp_path)
+ (tmp_path / "L2").mkdir(parents=True, exist_ok=True)
+ (tmp_path / "L3").mkdir(parents=True, exist_ok=True)
+ (tmp_path / "trace").mkdir(parents=True, exist_ok=True)
+ yield tmp_path
+
+
+def _entity(eid: str, content: str = "user uses spaced repetition with FSRS scheduler.") -> Entity:
+ return Entity(
+ id=eid,
+ label=f"entry {eid}",
+ ts="2026-05-19T00:00:00Z",
+ content=content,
+ metadata={},
+ fingerprint="fp",
+ )
+
+
+# ── update — L2 ─────────────────────────────────────────────────────────
+
+
+async def test_update_l2_appends_facts_from_chunk(memory_dir, monkeypatch):
+ entities = [_entity("01ABC"), _entity("01DEF")]
+
+ monkeypatch.setattr(
+ "deeptutor.services.memory.consolidator.modes.update.snap.read_snapshot",
+ lambda surface: entities,
+ )
+
+ async def fake_llm(*, system_prompt, user_prompt, **kwargs):
+ # Return one valid fact per call, citing a ref in the chunk.
+ if "01ABC" in user_prompt:
+ return '{"facts": [{"text": "uses FSRS scheduling", "section": "Mastery", "refs": ["chat:01ABC"]}]}'
+ if "01DEF" in user_prompt:
+ return '{"facts": [{"text": "scheduler customisation", "section": "Mastery", "refs": ["chat:01DEF"]}]}'
+ return '{"facts": []}'
+
+ # Force a tiny chunker so each entity ends up in its own chunk.
+ with patch("deeptutor.services.memory.consolidator.modes.update.call_llm", side_effect=fake_llm), \
+ patch.object(update_mod, "load_memory_settings") as mock_settings:
+ from deeptutor.services.memory.settings import MemorySettings, ChunkingSettings, DedupSettings
+ mock_settings.return_value = MemorySettings(
+ chunking=ChunkingSettings(min_chunk_chars=200, max_chunk_chars=400, overlap_ratio=0.0),
+ dedup=DedupSettings(auto_after_update=False),
+ )
+ result = await update_mod.run_update("L2", "chat", language="en")
+
+ assert result.facts_added >= 1
+ assert not result.no_new_input
+ md = (memory_dir / "L2" / "chat.md").read_text(encoding="utf-8")
+ assert "## Mastery" in md
+ assert "FSRS" in md or "scheduler" in md
+
+
+async def test_update_l2_idempotent_when_no_new_entities(memory_dir, monkeypatch):
+ entities = [_entity("01ABC")]
+ monkeypatch.setattr(
+ "deeptutor.services.memory.consolidator.modes.update.snap.read_snapshot",
+ lambda surface: entities,
+ )
+
+ # First run records the entity in meta.
+ async def llm_returns_one(*, system_prompt, user_prompt, **kwargs):
+ return '{"facts": [{"text": "uses Anki", "section": "Topics", "refs": ["chat:01ABC"]}]}'
+
+ with patch("deeptutor.services.memory.consolidator.modes.update.call_llm", side_effect=llm_returns_one), \
+ patch.object(update_mod, "load_memory_settings") as mock_settings:
+ from deeptutor.services.memory.settings import MemorySettings, DedupSettings
+ mock_settings.return_value = MemorySettings(dedup=DedupSettings(auto_after_update=False))
+ first = await update_mod.run_update("L2", "chat", language="en")
+ assert first.facts_added >= 0
+
+ # Second run with the same entities: no new traces → no LLM calls,
+ # no facts added.
+ llm_called = []
+
+ async def llm_should_not_run(*args, **kwargs):
+ llm_called.append(1)
+ return '{"facts": []}'
+
+ with patch("deeptutor.services.memory.consolidator.modes.update.call_llm", side_effect=llm_should_not_run), \
+ patch.object(update_mod, "load_memory_settings") as mock_settings:
+ from deeptutor.services.memory.settings import MemorySettings, DedupSettings
+ mock_settings.return_value = MemorySettings(dedup=DedupSettings(auto_after_update=False))
+ second = await update_mod.run_update("L2", "chat", language="en")
+ assert second.no_new_input is True
+ assert llm_called == []
+
+
+async def test_update_l2_drops_facts_with_out_of_pool_refs(memory_dir, monkeypatch):
+ entities = [_entity("01ABC")]
+ monkeypatch.setattr(
+ "deeptutor.services.memory.consolidator.modes.update.snap.read_snapshot",
+ lambda surface: entities,
+ )
+
+ async def fake_llm(*, system_prompt, user_prompt, **kwargs):
+ # Return one fact with a ref not in the chunk pool.
+ return '{"facts": [{"text": "uses Anki", "section": "Topics", "refs": ["chat:NOT_IN_CHUNK"]}]}'
+
+ with patch("deeptutor.services.memory.consolidator.modes.update.call_llm", side_effect=fake_llm), \
+ patch.object(update_mod, "load_memory_settings") as mock_settings:
+ from deeptutor.services.memory.settings import MemorySettings, DedupSettings, ReferenceSettings
+ mock_settings.return_value = MemorySettings(
+ dedup=DedupSettings(auto_after_update=False),
+ reference=ReferenceSettings(enforce_required=True, drop_invalid_refs=True),
+ )
+ result = await update_mod.run_update("L2", "chat", language="en")
+
+ # The fact had only an out-of-pool ref → dropped.
+ assert result.refs_dropped >= 1
+ assert result.facts_added == 0
+
+
+# ── audit — L2 ──────────────────────────────────────────────────────────
+
+
+async def test_audit_l2_applies_replace_edit(memory_dir, monkeypatch):
+ # Seed an existing L2 doc.
+ ids = [new_entry_id()]
+ doc = Document(
+ title="chat memory",
+ sections=[("Topics", [Entry(id=ids[0], section="Topics", text="claims X", refs=["chat:01ABC"])])],
+ )
+ path = memory_dir / "L2" / "chat.md"
+ path.write_text(serialize(doc), encoding="utf-8")
+
+ monkeypatch.setattr(
+ "deeptutor.services.memory.consolidator.modes.audit.snap.read_snapshot",
+ lambda surface: [_entity("01ABC", content="the user actually said Y, not X")],
+ )
+
+ async def fake_llm(*, system_prompt, user_prompt, **kwargs):
+ # Find the bullet line and emit a replace.
+ line_no = None
+ for ln in user_prompt.splitlines():
+ if "claims X" in ln and ln.lstrip().startswith(("3", "4", "5", "6", "7", "8")):
+ line_no = int(ln.strip().split(":")[0])
+ break
+ if line_no is None:
+ return '{"edits": []}'
+ return (
+ '{"edits": [{"op": "replace", "line": '
+ + str(line_no)
+ + ', "new_text": "claims Y", "refs": ["chat:01ABC"], "reason": "matched evidence"}]}'
+ )
+
+ with patch("deeptutor.services.memory.consolidator.modes.audit.call_llm", side_effect=fake_llm):
+ result = await audit_mod.run_audit("L2", "chat", language="en", budget=1)
+
+ new_md = path.read_text(encoding="utf-8")
+ assert "claims Y" in new_md
+ assert result.edits_applied >= 1
+
+
+# ── dedup ───────────────────────────────────────────────────────────────
+
+
+async def test_dedup_early_stop_when_no_edits(memory_dir, monkeypatch):
+ ids = [new_entry_id() for _ in range(2)]
+ doc = Document(
+ title="chat memory",
+ sections=[
+ (
+ "Topics",
+ [
+ Entry(id=ids[0], section="Topics", text="alpha", refs=["chat:01"]),
+ Entry(id=ids[1], section="Topics", text="beta", refs=["chat:02"]),
+ ],
+ )
+ ],
+ )
+ path = memory_dir / "L2" / "chat.md"
+ path.write_text(serialize(doc), encoding="utf-8")
+
+ llm_calls = []
+
+ async def fake_llm(*, system_prompt, user_prompt, **kwargs):
+ llm_calls.append(1)
+ return '{"edits": []}'
+
+ with patch("deeptutor.services.memory.consolidator.modes.dedup.call_llm", side_effect=fake_llm), \
+ patch.object(dedup_mod, "load_memory_settings") as mock_settings:
+ from deeptutor.services.memory.settings import MemorySettings, DedupSettings
+ mock_settings.return_value = MemorySettings(dedup=DedupSettings(iterations=5, auto_after_update=False))
+ result = await dedup_mod.run_dedup("L2", "chat", language="en")
+
+ assert result.converged_early is True
+ assert result.iterations_run == 1
+ assert len(llm_calls) == 1
+
+
+async def test_dedup_applies_delete_then_stops(memory_dir, monkeypatch):
+ ids = [new_entry_id() for _ in range(2)]
+ doc = Document(
+ title="chat memory",
+ sections=[
+ (
+ "Topics",
+ [
+ Entry(id=ids[0], section="Topics", text="duplicate fact", refs=["chat:01"]),
+ Entry(id=ids[1], section="Topics", text="duplicate fact", refs=["chat:02"]),
+ ],
+ )
+ ],
+ )
+ path = memory_dir / "L2" / "chat.md"
+ path.write_text(serialize(doc), encoding="utf-8")
+
+ call_count = [0]
+
+ async def fake_llm(*, system_prompt, user_prompt, **kwargs):
+ call_count[0] += 1
+ if call_count[0] == 1:
+ # Find the second bullet's line number.
+ line_no = None
+ seen = 0
+ for ln in user_prompt.splitlines():
+ if "duplicate fact" in ln and ln.lstrip()[:2].rstrip(":").isdigit():
+ seen += 1
+ if seen == 2:
+ line_no = int(ln.strip().split(":")[0])
+ break
+ if line_no is None:
+ return '{"edits": []}'
+ return (
+ '{"edits": [{"op": "delete", "line_start": '
+ + str(line_no)
+ + ', "line_end": '
+ + str(line_no)
+ + ', "reason": "duplicate"}]}'
+ )
+ return '{"edits": []}'
+
+ with patch("deeptutor.services.memory.consolidator.modes.dedup.call_llm", side_effect=fake_llm), \
+ patch.object(dedup_mod, "load_memory_settings") as mock_settings:
+ from deeptutor.services.memory.settings import MemorySettings, DedupSettings
+ mock_settings.return_value = MemorySettings(dedup=DedupSettings(iterations=3, auto_after_update=False))
+ result = await dedup_mod.run_dedup("L2", "chat", language="en")
+
+ assert result.edits_applied >= 1
+ new_doc = parse(path.read_text(encoding="utf-8"))
+ assert len([e for e in new_doc.all_entries() if e.text == "duplicate fact"]) == 1
diff --git a/tests/services/memory/test_ops.py b/tests/services/memory/test_ops.py
new file mode 100644
index 000000000..09b133a0e
--- /dev/null
+++ b/tests/services/memory/test_ops.py
@@ -0,0 +1,160 @@
+from __future__ import annotations
+
+from deeptutor.services.memory.document import Document, Entry, parse
+from deeptutor.services.memory.ops import AddOp, ApplyReport, DeleteOp, EditOp, apply
+
+
+_BASE_MD = """\
+# Chat memory
+
+## Misconceptions
+- Original text[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]
+
+---
+
+[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]: chat:01HZK4AAAAAAAAAAAAAAAAAAAA
+"""
+
+_VALID_REF = "chat:01HZK4AAAAAAAAAAAAAAAAAAAA"
+_EXISTING_ID = "m_01HZK4ABCDEFGHJKMNPQRSTVWX"
+
+
+def _fresh_doc() -> Document:
+ return parse(_BASE_MD)
+
+
+def test_add_op_creates_entry_with_new_id() -> None:
+ doc = _fresh_doc()
+ report = apply(doc, [AddOp(section="Mastery", text="solid", refs=[_VALID_REF])])
+ assert report.accepted
+ assert len(report.results) == 1
+ new_id = report.results[0].entry_id
+ assert new_id and new_id.startswith("m_") and new_id != _EXISTING_ID
+ entry = doc.find(new_id)
+ assert entry is not None
+ assert entry.text == "solid"
+ assert entry.refs == [_VALID_REF]
+
+
+def test_edit_op_updates_text_and_refs() -> None:
+ doc = _fresh_doc()
+ report = apply(
+ doc,
+ [
+ EditOp(
+ target_id=_EXISTING_ID,
+ new_text="rewritten",
+ new_refs=["chat:01HZK4BBBBBBBBBBBBBBBBBBBB"],
+ )
+ ],
+ )
+ assert report.accepted
+ entry = doc.find(_EXISTING_ID)
+ assert entry is not None
+ assert entry.text == "rewritten"
+ assert entry.refs == ["chat:01HZK4BBBBBBBBBBBBBBBBBBBB"]
+
+
+def test_delete_op_removes_entry() -> None:
+ doc = _fresh_doc()
+ report = apply(doc, [DeleteOp(target_id=_EXISTING_ID, reason="superseded")])
+ assert report.accepted
+ assert doc.find(_EXISTING_ID) is None
+
+
+def test_batch_conflict_edit_then_delete_rejects_whole_batch() -> None:
+ doc = _fresh_doc()
+ original_text = doc.find(_EXISTING_ID).text # type: ignore[union-attr]
+ report = apply(
+ doc,
+ [
+ EditOp(target_id=_EXISTING_ID, new_text="changed", new_refs=[_VALID_REF]),
+ DeleteOp(target_id=_EXISTING_ID, reason="stale"),
+ ],
+ )
+ assert not report.accepted
+ assert "edit and delete on same id" in report.reason
+ # Doc untouched.
+ assert doc.find(_EXISTING_ID).text == original_text # type: ignore[union-attr]
+
+
+def test_unknown_target_id_rejects() -> None:
+ doc = _fresh_doc()
+ report = apply(
+ doc,
+ [EditOp(target_id="m_01HZKZZZZZZZZZZZZZZZZZZZZZ", new_text="x", new_refs=[_VALID_REF])],
+ )
+ assert not report.accepted
+ assert "not found" in report.reason
+
+
+def test_add_without_refs_rejects() -> None:
+ doc = _fresh_doc()
+ report = apply(doc, [AddOp(section="Mastery", text="solid", refs=[])])
+ assert not report.accepted
+ assert "refs" in report.reason
+
+
+def test_add_with_text_too_long_rejects() -> None:
+ doc = _fresh_doc()
+ report = apply(doc, [AddOp(section="S", text="x" * 241, refs=[_VALID_REF])])
+ assert not report.accepted
+ assert "text length" in report.reason
+
+
+def test_add_with_invalid_ref_rejects() -> None:
+ doc = _fresh_doc()
+ report = apply(doc, [AddOp(section="S", text="ok", refs=["not-an-id"])])
+ assert not report.accepted
+ assert "malformed ref" in report.reason
+
+
+def test_delete_with_invalid_reason_rejects() -> None:
+ doc = _fresh_doc()
+ report = apply(doc, [DeleteOp(target_id=_EXISTING_ID, reason="because")])
+ assert not report.accepted
+ assert "reason" in report.reason
+
+
+def test_parallel_ops_applied_in_order() -> None:
+ doc = _fresh_doc()
+ report = apply(
+ doc,
+ [
+ AddOp(section="Mastery", text="a", refs=[_VALID_REF]),
+ AddOp(section="Mastery", text="b", refs=[_VALID_REF]),
+ EditOp(target_id=_EXISTING_ID, new_text="updated", new_refs=[_VALID_REF]),
+ ],
+ )
+ assert report.accepted
+ mastery = [e for s, ents in doc.sections if s == "Mastery" for e in ents]
+ assert [e.text for e in mastery] == ["a", "b"]
+ assert doc.find(_EXISTING_ID).text == "updated" # type: ignore[union-attr]
+
+
+def test_repeated_edit_on_same_id_last_wins() -> None:
+ doc = _fresh_doc()
+ report = apply(
+ doc,
+ [
+ EditOp(target_id=_EXISTING_ID, new_text="first", new_refs=[_VALID_REF]),
+ EditOp(target_id=_EXISTING_ID, new_text="second", new_refs=[_VALID_REF]),
+ ],
+ )
+ assert report.accepted
+ assert doc.find(_EXISTING_ID).text == "second" # type: ignore[union-attr]
+
+
+def test_validation_failure_leaves_doc_untouched() -> None:
+ doc = _fresh_doc()
+ snapshot_entries = [(e.id, e.text, list(e.refs)) for e in doc.all_entries()]
+ report = apply(
+ doc,
+ [
+ AddOp(section="OK", text="valid", refs=[_VALID_REF]),
+ AddOp(section="Bad", text="", refs=[_VALID_REF]), # text empty → invalid
+ ],
+ )
+ assert not report.accepted
+ after = [(e.id, e.text, list(e.refs)) for e in doc.all_entries()]
+ assert snapshot_entries == after
diff --git a/tests/services/memory/test_references.py b/tests/services/memory/test_references.py
new file mode 100644
index 000000000..c6f5369cf
--- /dev/null
+++ b/tests/services/memory/test_references.py
@@ -0,0 +1,159 @@
+"""Tests for ref pool validation and chunk-level concat helpers."""
+
+from __future__ import annotations
+
+from deeptutor.services.memory.consolidator.references import (
+ ExtractedFact,
+ refs_in_chunk_l2,
+ refs_in_chunk_l3,
+ refs_in_span_l2,
+ render_l2_entries_for_concat,
+ render_traces_for_concat,
+ validate_fact_refs,
+)
+from deeptutor.services.memory.document import Entry
+from deeptutor.services.memory.snapshot.entity import Entity
+
+
+def _entity(eid: str) -> Entity:
+ return Entity(
+ id=eid,
+ label=f"entity {eid}",
+ ts="2026-05-20T00:00:00Z",
+ content=f"body of {eid}",
+ metadata={},
+ fingerprint="fp",
+ )
+
+
+def test_render_traces_yields_unique_markers_per_entity() -> None:
+ text = render_traces_for_concat([_entity("01A"), _entity("01B")], surface="chat")
+ assert "@entity chat:01A" in text
+ assert "@entity chat:01B" in text
+
+
+def test_refs_in_chunk_l2_only_lists_refs_visible_in_chunk() -> None:
+ full = render_traces_for_concat([_entity("01A"), _entity("01B")], surface="chat")
+ # Take a substring that contains only 01A.
+ cut = full.index("@entity chat:01B")
+ chunk = full[:cut]
+ allowed = refs_in_chunk_l2([_entity("01A"), _entity("01B")], surface="chat", chunk_text=chunk)
+ assert "chat:01A" in allowed
+ assert "chat:01B" not in allowed
+
+
+def test_refs_in_span_l2_keeps_ref_when_chunk_starts_inside_entity_body() -> None:
+ full = render_traces_for_concat([_entity("01A"), _entity("01B")], surface="chat")
+ start = full.index("body of 01A")
+ end = start + len("body of 01A")
+ allowed = refs_in_span_l2(
+ [_entity("01A"), _entity("01B")],
+ surface="chat",
+ full_text=full,
+ start=start,
+ end=end,
+ )
+ assert "chat:01A" in allowed
+ assert "chat:01B" not in allowed
+
+
+def test_render_l2_for_concat_is_text_only_no_entry_ids() -> None:
+ """L3 input must NOT leak L2 footnote/entry-id structure (2026-05-21
+ design pivot: L3 cites L2 files, not L2 entries)."""
+ entries = {
+ "chat": [
+ Entry(
+ id="m_01HZK1ABCDEFGHJKMNPQRSTVWX",
+ section="Themes",
+ text="alpha",
+ refs=["chat:r1", "chat:r2"],
+ ),
+ ],
+ }
+ text = render_l2_entries_for_concat(entries)
+ assert "### surface: chat" in text
+ assert "alpha" in text
+ # No entry ids, no upstream refs leak through.
+ assert "m_01HZK1ABCDEFGHJKMNPQRSTVWX" not in text
+ assert "@l2" not in text
+ assert "chat:r1" not in text
+
+
+def test_refs_in_chunk_l3_returns_surface_names_visible_in_chunk() -> None:
+ """L3 pool is surface names — the ``### surface:`` headers found in
+ the chunk."""
+ entries = {
+ "chat": [Entry(id="m_01ABC", section="S", text="alpha", refs=[])],
+ "notebook": [Entry(id="m_02DEF", section="S", text="beta", refs=[])],
+ }
+ text = render_l2_entries_for_concat(entries)
+ # Take a substring that contains only the chat block.
+ cut = text.index("### surface: notebook")
+ chunk = text[:cut]
+ allowed = refs_in_chunk_l3(chunk, entries_by_surface=entries)
+ assert allowed == {"chat"}
+
+
+def test_refs_in_span_l3_keeps_surface_when_chunk_starts_mid_block() -> None:
+ """Chunker may start a chunk inside a surface block (overlap window);
+ that surface should still be in the allowed pool."""
+ from deeptutor.services.memory.consolidator.references import refs_in_span_l3
+
+ entries = {
+ "chat": [Entry(id="m_01A", section="S", text="alpha", refs=[])],
+ "notebook": [Entry(id="m_02B", section="S", text="beta", refs=[])],
+ }
+ text = render_l2_entries_for_concat(entries)
+ # Start mid-way through the chat body, end mid-way through notebook.
+ start = text.index("alpha") + 2
+ end = text.index("beta") + 2
+ allowed = refs_in_span_l3(
+ entries_by_surface=entries,
+ full_text=text,
+ start=start,
+ end=end,
+ )
+ assert allowed == {"chat", "notebook"}
+
+
+def test_validate_fact_refs_drops_out_of_pool_when_drop_invalid_true() -> None:
+ fact = ExtractedFact(text="x", refs=["chat:01A", "chat:01Z"])
+ kept, reject = validate_fact_refs(
+ fact,
+ allowed={"chat:01A"},
+ enforce_required=True,
+ drop_invalid=True,
+ )
+ assert kept == ["chat:01A"]
+ assert reject is None
+
+
+def test_validate_fact_refs_recovers_label_prefixed_l2_ref() -> None:
+ fact = ExtractedFact(
+ text="x",
+ refs=["AutoAgent:chat:unified_1773210349762_5680af00"],
+ )
+ kept, reject = validate_fact_refs(
+ fact,
+ allowed={"chat:unified_1773210349762_5680af00"},
+ enforce_required=True,
+ drop_invalid=True,
+ )
+ assert kept == ["chat:unified_1773210349762_5680af00"]
+ assert reject is None
+
+
+def test_validate_fact_refs_rejects_when_drop_invalid_false() -> None:
+ fact = ExtractedFact(text="x", refs=["chat:01A", "chat:01Z"])
+ _, reject = validate_fact_refs(
+ fact, allowed={"chat:01A"}, enforce_required=True, drop_invalid=False
+ )
+ assert reject is not None and "out-of-pool" in reject
+
+
+def test_validate_fact_refs_rejects_empty_refs_when_required() -> None:
+ fact = ExtractedFact(text="x", refs=[])
+ _, reject = validate_fact_refs(
+ fact, allowed={"chat:01A"}, enforce_required=True, drop_invalid=True
+ )
+ assert reject is not None and "missing refs" in reject
diff --git a/tests/services/memory/test_runs.py b/tests/services/memory/test_runs.py
new file mode 100644
index 000000000..ace1cc585
--- /dev/null
+++ b/tests/services/memory/test_runs.py
@@ -0,0 +1,153 @@
+"""Tests for the RunManager — start/cancel/replay semantics."""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from deeptutor.services.memory.consolidator.runs import (
+ RunBusyError,
+ RunManager,
+ push_undo_checkpoint,
+)
+
+
+def manager() -> RunManager:
+ return RunManager()
+
+
+async def test_start_runs_to_completion_and_buffers_events(manager: RunManager) -> None:
+ async def runner(on_event):
+ await on_event({"stage": "progress", "turn": 1})
+ await on_event({"stage": "progress", "turn": 2})
+
+ run = await manager.start(
+ layer="L2", key="chat", mode="update", runner=runner
+ )
+ if run._task is not None:
+ await run._task
+ assert run.status == "done"
+ stages = [ev.payload.get("stage") for ev in run.events]
+ assert "run_started" in stages
+ assert "progress" in stages
+ assert stages[-1] == "run_ended"
+
+
+async def test_busy_error_when_concurrent_start_same_doc(manager: RunManager) -> None:
+ started = asyncio.Event()
+ release = asyncio.Event()
+
+ async def runner(on_event):
+ started.set()
+ await release.wait()
+
+ first = await manager.start(layer="L2", key="chat", mode="update", runner=runner)
+ await started.wait()
+
+ with pytest.raises(RunBusyError):
+ await manager.start(layer="L2", key="chat", mode="audit", runner=runner)
+
+ # Concurrent run on a *different* doc is fine.
+ second = await manager.start(layer="L2", key="notebook", mode="update", runner=runner)
+ release.set()
+ if first._task is not None:
+ await first._task
+ if second._task is not None:
+ await second._task
+
+
+async def test_cancel_marks_run_cancelled(manager: RunManager) -> None:
+ started = asyncio.Event()
+
+ async def runner(on_event):
+ started.set()
+ await asyncio.sleep(10) # would hang forever; cancellation interrupts
+
+ run = await manager.start(layer="L2", key="chat", mode="update", runner=runner)
+ await started.wait()
+ cancelled = await manager.cancel(run.id)
+ assert cancelled is True
+ if run._task is not None:
+ # The driver swallows CancelledError into a terminal status.
+ await asyncio.gather(run._task, return_exceptions=True)
+ assert run.status == "cancelled"
+
+
+async def test_wait_for_events_replays_from_cursor(manager: RunManager) -> None:
+ async def runner(on_event):
+ for i in range(5):
+ await on_event({"stage": "progress", "turn": i})
+
+ run = await manager.start(layer="L2", key="chat", mode="update", runner=runner)
+ if run._task is not None:
+ await run._task
+
+ all_events = await manager.wait_for_events(run, since=0)
+ assert len(all_events) >= 5 # run_started + 5 progress + run_ended
+
+ tail = await manager.wait_for_events(run, since=3)
+ assert tail[0].seq == 3
+
+
+async def test_active_for_returns_none_after_done(manager: RunManager) -> None:
+ async def runner(on_event):
+ await on_event({"stage": "progress"})
+
+ run = await manager.start(layer="L2", key="chat", mode="update", runner=runner)
+ if run._task is not None:
+ await run._task
+ assert manager.active_for("L2", "chat") is None
+ assert manager.get(run.id) is not None # but still in history
+
+
+async def test_run_records_error_when_runner_raises(manager: RunManager) -> None:
+ async def runner(on_event):
+ raise RuntimeError("kaboom")
+
+ run = await manager.start(layer="L2", key="chat", mode="update", runner=runner)
+ if run._task is not None:
+ await run._task
+ assert run.status == "error"
+ assert "kaboom" in (run.error or "")
+
+
+async def test_undo_last_restores_previous_document(
+ manager: RunManager, tmp_path
+) -> None:
+ path = tmp_path / "chat.md"
+ path.write_text("before", encoding="utf-8")
+
+ async def runner(on_event):
+ previous = path.read_text(encoding="utf-8")
+ path.write_text("after", encoding="utf-8")
+ depth = push_undo_checkpoint(
+ layer="L2",
+ key="chat",
+ path=path,
+ existed=True,
+ previous_content=previous,
+ action="test_write",
+ turn=1,
+ label="update",
+ )
+ await on_event({"stage": "doc_updated", "undo_depth": depth})
+
+ run = await manager.start(layer="L2", key="chat", mode="update", runner=runner)
+ if run._task is not None:
+ await run._task
+
+ assert path.read_text(encoding="utf-8") == "after"
+ assert run.undo_stack
+ event = await manager.undo_last(run.id)
+ assert event is not None
+ assert path.read_text(encoding="utf-8") == "before"
+ assert event.payload["stage"] == "undo_applied"
diff --git a/tests/services/memory/test_store.py b/tests/services/memory/test_store.py
new file mode 100644
index 000000000..52d711300
--- /dev/null
+++ b/tests/services/memory/test_store.py
@@ -0,0 +1,198 @@
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+
+from deeptutor.services.memory import paths, store
+from deeptutor.services.memory.store import MemoryStore, migrate_v1_if_needed
+from deeptutor.services.memory.trace import TraceEvent
+
+
+def tmp_memory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Point ``paths.memory_root`` at an isolated tmp dir."""
+ root = tmp_path / "memory"
+ monkeypatch.setattr(paths, "memory_root", lambda: root)
+ paths.ensure_dirs()
+ # Reset the singleton so each test gets a fresh store with its own locks.
+ monkeypatch.setattr(store, "_singleton", None)
+ return root
+
+
+def _run(coro):
+ return asyncio.run(coro)
+
+
+def test_read_l3_concat_empty(tmp_memory: Path) -> None:
+ s = MemoryStore()
+ out = s.read_l3_concat()
+ assert "(No memory available" in out
+
+
+def test_read_l3_concat_joins_present_slots(tmp_memory: Path) -> None:
+ (tmp_memory / "L3" / "profile.md").write_text("# User profile\n\n## Identity\n- (none)\n")
+ (tmp_memory / "L3" / "preferences.md").write_text("# Preferences\n\n## Style\n- terse\n")
+ out = MemoryStore().read_l3_concat()
+ assert "# User profile" in out
+ assert "# Preferences" in out
+ assert "---" in out
+ # No "no memory" sentinel when something is present.
+ assert "(No memory available" not in out
+
+
+def test_overwrite_and_read_doc_roundtrip(tmp_memory: Path) -> None:
+ s = MemoryStore()
+ md = (
+ "# Chat memory\n\n"
+ "## Misconceptions\n"
+ "- Misreads quantifier order[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]\n\n"
+ "---\n\n"
+ "[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]: chat:01HZK4AAAAAAAAAAAAAAAAAAAA\n"
+ )
+ _run(s.overwrite_doc("L2", "chat", md))
+ doc = s.read_doc("L2", "chat")
+ assert doc.title == "Chat memory"
+ assert len(doc.all_entries()) == 1
+
+
+def test_delete_entry_removes_from_persisted_doc(tmp_memory: Path) -> None:
+ s = MemoryStore()
+ md = (
+ "# Chat memory\n\n"
+ "## Misconceptions\n"
+ "- A[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]\n"
+ "- B[^m_01HZK5ABCDEFGHJKMNPQRSTVWX]\n\n"
+ "---\n\n"
+ "[^m_01HZK4ABCDEFGHJKMNPQRSTVWX]: chat:01HZK4AAAAAAAAAAAAAAAAAAAA\n"
+ "[^m_01HZK5ABCDEFGHJKMNPQRSTVWX]: chat:01HZK5BBBBBBBBBBBBBBBBBBBB\n"
+ )
+ _run(s.overwrite_doc("L2", "chat", md))
+ ok = _run(s.delete_entry("L2", "chat", "m_01HZK4ABCDEFGHJKMNPQRSTVWX"))
+ assert ok
+ doc = s.read_doc("L2", "chat")
+ assert len(doc.all_entries()) == 1
+ assert doc.all_entries()[0].id == "m_01HZK5ABCDEFGHJKMNPQRSTVWX"
+
+
+def test_write_preference_add(tmp_memory: Path) -> None:
+ s = MemoryStore()
+ report = _run(
+ s.write_preference(
+ op="add",
+ text="prefers concise answers",
+ trace_id="chat:01HZK4AAAAAAAAAAAAAAAAAAAA",
+ )
+ )
+ assert report.accepted
+ doc = s.read_doc("L3", "preferences")
+ assert len(doc.all_entries()) == 1
+ assert doc.all_entries()[0].text == "prefers concise answers"
+
+
+def test_write_preference_edit(tmp_memory: Path) -> None:
+ s = MemoryStore()
+ add_report = _run(
+ s.write_preference(
+ op="add",
+ text="prefers concise",
+ trace_id="chat:01HZK4AAAAAAAAAAAAAAAAAAAA",
+ )
+ )
+ new_id = add_report.results[0].entry_id
+ assert new_id
+
+ edit_report = _run(
+ s.write_preference(
+ op="edit",
+ text="prefers concise but with examples",
+ target_id=new_id,
+ trace_id="chat:01HZK5BBBBBBBBBBBBBBBBBBBB",
+ )
+ )
+ assert edit_report.accepted
+ doc = s.read_doc("L3", "preferences")
+ entry = doc.find(new_id)
+ assert entry is not None
+ assert entry.text == "prefers concise but with examples"
+ assert entry.refs == ["chat:01HZK5BBBBBBBBBBBBBBBBBBBB"]
+
+
+def test_write_preference_edit_without_target_fails(tmp_memory: Path) -> None:
+ report = _run(
+ MemoryStore().write_preference(
+ op="edit",
+ text="x",
+ trace_id="chat:01HZK4AAAAAAAAAAAAAAAAAAAA",
+ )
+ )
+ assert not report.accepted
+ assert "target_id" in report.reason
+
+
+def test_update_l3_rejects_preferences_slot(tmp_memory: Path) -> None:
+ with pytest.raises(ValueError, match="preferences.md is not auto-consolidated"):
+ _run(MemoryStore().update_l3("preferences"))
+
+
+def test_emit_appends_trace_event(tmp_memory: Path) -> None:
+ event = TraceEvent.new(
+ "chat",
+ "turn",
+ {"user": "hi", "assistant": "hello"},
+ session_id="sess_1",
+ )
+ _run(MemoryStore().emit(event))
+ files = list((tmp_memory / "trace" / "chat").glob("*.jsonl"))
+ assert len(files) == 1
+ contents = files[0].read_text(encoding="utf-8").strip().splitlines()
+ assert len(contents) == 1
+ assert "sess_1" in contents[0]
+
+
+def test_overview_reports_all_layers(tmp_memory: Path) -> None:
+ rows = MemoryStore().overview()
+ keys = {(r.layer, r.key) for r in rows}
+ for surface in paths.SURFACES:
+ assert ("L2", surface) in keys
+ for slot in paths.L3_SLOTS:
+ assert ("L3", slot) in keys
+ # All start as exists=False, entry_count=0.
+ for r in rows:
+ assert not r.exists
+ assert r.entry_count == 0
+
+
+def test_migrate_v1_moves_loose_files(tmp_memory: Path) -> None:
+ (tmp_memory / "PROFILE.md").write_text("v1 profile content")
+ (tmp_memory / "SUMMARY.md").write_text("v1 summary content")
+ (tmp_memory / "stray.md").write_text("untracked")
+
+ backup = migrate_v1_if_needed()
+ assert backup is not None
+ assert backup.parent == tmp_memory / "backup"
+ assert (backup / "PROFILE.md").read_text() == "v1 profile content"
+ assert (backup / "SUMMARY.md").read_text() == "v1 summary content"
+ assert (backup / "stray.md").read_text() == "untracked"
+ assert not (tmp_memory / "PROFILE.md").exists()
+ assert not (tmp_memory / "SUMMARY.md").exists()
+
+
+def test_migrate_v1_noop_when_clean(tmp_memory: Path) -> None:
+ # Only v2 dirs present; nothing to migrate.
+ assert migrate_v1_if_needed() is None
+ assert not (tmp_memory / "backup").exists()
+
+
+def test_migrate_v1_preserves_v2_dirs(tmp_memory: Path) -> None:
+ (tmp_memory / "PROFILE.md").write_text("v1")
+ # Pre-existing v2 doc — must not be moved.
+ l2_chat = tmp_memory / "L2" / "chat.md"
+ l2_chat.write_text("# v2 doc\n")
+
+ backup = migrate_v1_if_needed()
+ assert backup is not None
+ assert l2_chat.exists()
+ assert l2_chat.read_text() == "# v2 doc\n"
+ assert (backup / "PROFILE.md").exists()
diff --git a/web/app/(utility)/memory/graph/page.tsx b/web/app/(utility)/memory/graph/page.tsx
new file mode 100644
index 000000000..d1ba39788
--- /dev/null
+++ b/web/app/(utility)/memory/graph/page.tsx
@@ -0,0 +1,7 @@
+"use client";
+
+import MemoryGraph from "@/components/memory/MemoryGraph";
+
+export default function MemoryGraphPage() {
+ return <MemoryGraph />;
+}
diff --git a/web/app/(utility)/memory/l1/page.tsx b/web/app/(utility)/memory/l1/page.tsx
new file mode 100644
index 000000000..d295c7f2e
--- /dev/null
+++ b/web/app/(utility)/memory/l1/page.tsx
@@ -0,0 +1,68 @@
+"use client";
+
+import { useSearchParams } from "next/navigation";
+import { Suspense } from "react";
+
+import MemoryL1Workbench from "@/components/memory/MemoryL1Workbench";
+
+type Surface =
+ | "chat"
+ | "notebook"
+ | "quiz"
+ | "kb"
+ | "book"
+ | "tutorbot"
+ | "cowriter";
+
+const VALID_SURFACES: ReadonlySet<Surface> = new Set([
+ "chat",
+ "notebook",
+ "quiz",
+ "kb",
+ "book",
+ "tutorbot",
+ "cowriter",
+]);
+
+function isSurface(s: string | null): s is Surface {
+ return s !== null && (VALID_SURFACES as ReadonlySet<string>).has(s);
+}
+
+function MemoryL1PageInner() {
+ // Deep-link contract — any footnote rendered in a memory doc links here:
+ // ``?ref=notebook:3a563e6f`` or ``?surface=notebook&ref=3a563e6f``.
+ const params = useSearchParams();
+ const rawRef = params.get("ref");
+ const rawSurface = params.get("surface");
+
+ let surface: Surface | undefined;
+ let focusRef: string | undefined;
+
+ if (rawRef) {
+ if (rawRef.includes(":")) {
+ const [pfx, rest] = rawRef.split(":", 2);
+ if (isSurface(pfx)) {
+ surface = pfx;
+ focusRef = `${pfx}:${rest}`;
+ }
+ } else if (isSurface(rawSurface)) {
+ surface = rawSurface;
+ focusRef = `${rawSurface}:${rawRef}`;
+ }
+ } else if (isSurface(rawSurface)) {
+ surface = rawSurface;
+ }
+
+ return (
+ <MemoryL1Workbench initialSurface={surface} initialFocusRef={focusRef} />
+ );
+}
+
+export default function MemoryL1Page() {
+ // useSearchParams requires a Suspense boundary in app-router client pages.
+ return (
+ <Suspense fallback={<MemoryL1Workbench />}>
+ <MemoryL1PageInner />
+ </Suspense>
+ );
+}
diff --git a/web/app/(utility)/memory/l2/[surface]/page.tsx b/web/app/(utility)/memory/l2/[surface]/page.tsx
new file mode 100644
index 000000000..c2724d4fc
--- /dev/null
+++ b/web/app/(utility)/memory/l2/[surface]/page.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { notFound, useParams, useSearchParams } from "next/navigation";
+import { Suspense } from "react";
+
+import MemoryWorkbench from "@/components/memory/MemoryWorkbench";
+
+const SURFACES = ["chat", "notebook", "quiz", "kb", "book", "tutorbot", "cowriter"];
+
+function L2WorkbenchInner() {
+ // ``?focus=m_xxx`` is the deep-link contract used by the resolver
+ // page when the user clicks an L3 footnote — scroll the matching
+ // bullet into view + flash it.
+ const params = useParams<{ surface: string }>();
+ const search = useSearchParams();
+ const surface = params?.surface;
+ if (!surface || !SURFACES.includes(surface)) {
+ notFound();
+ }
+ const focus = search.get("focus") || undefined;
+ return <MemoryWorkbench layer="L2" initialKey={surface} initialFocus={focus} />;
+}
+
+export default function MemoryL2WorkbenchPage() {
+ return (
+ <Suspense fallback={null}>
+ <L2WorkbenchInner />
+ </Suspense>
+ );
+}
diff --git a/web/app/(utility)/memory/l2/page.tsx b/web/app/(utility)/memory/l2/page.tsx
new file mode 100644
index 000000000..559441950
--- /dev/null
+++ b/web/app/(utility)/memory/l2/page.tsx
@@ -0,0 +1,7 @@
+"use client";
+
+import MemoryWorkbench from "@/components/memory/MemoryWorkbench";
+
+export default function MemoryL2Page() {
+ return <MemoryWorkbench layer="L2" />;
+}
diff --git a/web/app/(utility)/memory/l3/[slot]/page.tsx b/web/app/(utility)/memory/l3/[slot]/page.tsx
new file mode 100644
index 000000000..814080abd
--- /dev/null
+++ b/web/app/(utility)/memory/l3/[slot]/page.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { notFound, useParams, useSearchParams } from "next/navigation";
+import { Suspense } from "react";
+
+import MemoryWorkbench from "@/components/memory/MemoryWorkbench";
+
+const SLOTS = ["recent", "profile", "scope"];
+
+function L3WorkbenchInner() {
+ const params = useParams<{ slot: string }>();
+ const search = useSearchParams();
+ const slot = params?.slot;
+ if (!slot || !SLOTS.includes(slot)) {
+ notFound();
+ }
+ // L3 docs don't currently surface ?focus targets directly — but keep
+ // the param plumbed for symmetry (and so future resolver hops to L3
+ // entries work without another patch).
+ const focus = search.get("focus") || undefined;
+ return <MemoryWorkbench layer="L3" initialKey={slot} initialFocus={focus} />;
+}
+
+export default function MemoryL3WorkbenchPage() {
+ return (
+ <Suspense fallback={null}>
+ <L3WorkbenchInner />
+ </Suspense>
+ );
+}
diff --git a/web/app/(utility)/memory/l3/page.tsx b/web/app/(utility)/memory/l3/page.tsx
new file mode 100644
index 000000000..5da0f5204
--- /dev/null
+++ b/web/app/(utility)/memory/l3/page.tsx
@@ -0,0 +1,7 @@
+"use client";
+
+import MemoryWorkbench from "@/components/memory/MemoryWorkbench";
+
+export default function MemoryL3Page() {
+ return <MemoryWorkbench layer="L3" />;
+}
diff --git a/web/app/(utility)/memory/layout.tsx b/web/app/(utility)/memory/layout.tsx
new file mode 100644
index 000000000..f547af4c4
--- /dev/null
+++ b/web/app/(utility)/memory/layout.tsx
@@ -0,0 +1,15 @@
+// Bare shell — each memory page owns its own padding + scroll behavior.
+// Hub uses `overflow-y-auto` with a max-width container; the L2/L3
+// workbench pages use a full-height flex column with internal scrolling
+// per pane (preview / LLM workspace) so the outer page never grows.
+export default function MemoryLayout({
+ children,
+}: Readonly<{
+ children: React.ReactNode;
+}>) {
+ return (
+ <main className="flex h-full min-h-0 flex-col bg-[var(--background)]">
+ {children}
+ </main>
+ );
+}
diff --git a/web/app/(utility)/memory/page.tsx b/web/app/(utility)/memory/page.tsx
index 6dc61639f..3beb1d47d 100644
--- a/web/app/(utility)/memory/page.tsx
+++ b/web/app/(utility)/memory/page.tsx
@@ -1,5 +1,11 @@
-import { redirect } from "next/navigation";
+import MemoryHub from "@/components/memory/MemoryHub";
-export default function MemoryRedirect() {
- redirect("/space/memory");
+export default function MemoryPage() {
+ return (
+ <div className="h-full overflow-y-auto [scrollbar-gutter:stable]">
+ <div className="mx-auto max-w-6xl px-6 py-10 pb-16 md:px-10">
+ <MemoryHub />
+ </div>
+ </div>
+ );
}
diff --git a/web/app/(utility)/memory/resolve/page.tsx b/web/app/(utility)/memory/resolve/page.tsx
new file mode 100644
index 000000000..c6f967077
--- /dev/null
+++ b/web/app/(utility)/memory/resolve/page.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+// Resolver landing page for ``m_<ULID>`` citations clicked from an L3
+// doc. The id alone is not enough to navigate — we need to know which
+// L2 surface owns it. The backend resolver does the lookup; this page
+// is just the redirect shim.
+
+import Link from "next/link";
+import { useRouter, useSearchParams } from "next/navigation";
+import { Suspense, useEffect, useState } from "react";
+import { Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { apiFetch, apiUrl } from "@/lib/api";
+
+interface ResolveResponse {
+ layer: string;
+ key: string;
+ entry_id: string;
+}
+
+function ResolveInner() {
+ const { t } = useTranslation();
+ const params = useSearchParams();
+ const router = useRouter();
+ const id = params.get("id");
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!id) return;
+ let cancelled = false;
+ (async () => {
+ try {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/memory/resolve_entry/${encodeURIComponent(id)}`),
+ );
+ if (!res.ok) {
+ if (cancelled) return;
+ setError(
+ res.status === 404
+ ? t("Entry {{id}} not found in any L2 doc — it may have been deleted.", { id })
+ : t("Resolver failed ({{code}})", { code: res.status }),
+ );
+ return;
+ }
+ const data = (await res.json()) as ResolveResponse;
+ if (cancelled) return;
+ const layerPath = data.layer.toLowerCase();
+ router.replace(
+ `/memory/${layerPath}/${encodeURIComponent(data.key)}?focus=${encodeURIComponent(data.entry_id)}`,
+ );
+ } catch (e) {
+ if (cancelled) return;
+ setError(e instanceof Error ? e.message : t("Resolver failed"));
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [id, router, t]);
+
+ const message = !id ? t("Missing ?id= in URL") : error;
+
+ if (message) {
+ return (
+ <div className="grid h-full place-items-center px-6 py-10">
+ <div className="max-w-md space-y-3 text-center text-[13px]">
+ <p className="text-[var(--foreground)]">{message}</p>
+ <Link
+ href="/memory"
+ className="inline-block rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1 text-[12px] transition hover:bg-[var(--muted)]"
+ >
+ {t("Back to memory")}
+ </Link>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="grid h-full place-items-center px-6 py-10 text-[var(--muted-foreground)]">
+ <div className="flex items-center gap-2 text-[13px]">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span>{t("Resolving entry…")}</span>
+ </div>
+ </div>
+ );
+}
+
+export default function MemoryResolvePage() {
+ return (
+ <Suspense
+ fallback={
+ <div className="grid h-full place-items-center text-[var(--muted-foreground)]">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ </div>
+ }
+ >
+ <ResolveInner />
+ </Suspense>
+ );
+}
diff --git a/web/app/(utility)/space/memory/page.tsx b/web/app/(utility)/space/memory/page.tsx
index c0d3dbd02..87c304fa6 100644
--- a/web/app/(utility)/space/memory/page.tsx
+++ b/web/app/(utility)/space/memory/page.tsx
@@ -1,5 +1,5 @@
-import MemorySection from "@/components/space/MemorySection";
+import { redirect } from "next/navigation";
-export default function SpaceMemoryPage() {
- return <MemorySection />;
+export default function SpaceMemoryRedirect() {
+ redirect("/memory");
}
diff --git a/web/components/memory/MemoryArchivedBanner.tsx b/web/components/memory/MemoryArchivedBanner.tsx
new file mode 100644
index 000000000..1494d827d
--- /dev/null
+++ b/web/components/memory/MemoryArchivedBanner.tsx
@@ -0,0 +1,97 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import { Archive, ChevronDown, ChevronUp, X } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+const STORAGE_KEY = "dt:memory:banner-dismissed";
+
+interface MemoryArchivedBannerProps {
+ latestBackup: string | null;
+ variant?: "full" | "compact";
+}
+
+export default function MemoryArchivedBanner({
+ latestBackup,
+ variant = "compact",
+}: MemoryArchivedBannerProps) {
+ const { t } = useTranslation();
+ const [dismissed, setDismissed] = useState<string | null>(() => {
+ if (typeof window === "undefined") return null;
+ return window.localStorage.getItem(STORAGE_KEY);
+ });
+ const [expanded, setExpanded] = useState(false);
+
+ const dismiss = useCallback(() => {
+ if (!latestBackup) return;
+ if (typeof window !== "undefined") {
+ window.localStorage.setItem(STORAGE_KEY, latestBackup);
+ }
+ setDismissed(latestBackup);
+ }, [latestBackup]);
+
+ if (!latestBackup || dismissed === latestBackup) return null;
+
+ if (variant === "full") {
+ return (
+ <div className="relative flex items-start gap-3 rounded-2xl border border-[var(--border)] bg-[var(--muted)] px-5 py-4 pr-12 text-[13px]">
+ <Archive className="mt-0.5 h-4 w-4 shrink-0 text-[var(--muted-foreground)]" />
+ <div>
+ <p className="font-medium text-[var(--foreground)]">
+ {t("Your v1 memory was archived")}
+ </p>
+ <p className="mt-0.5 text-[var(--muted-foreground)]">
+ {t(
+ "Stored at memory/backup/{{name}}. v2 starts fresh — interact with DeepTutor and click Update on each doc to build memory.",
+ { name: latestBackup },
+ )}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={dismiss}
+ aria-label={t("Dismiss")}
+ className="absolute right-2 top-2 rounded-md p-1.5 text-[var(--muted-foreground)] transition hover:bg-[var(--background)] hover:text-[var(--foreground)]"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/60 text-[12px]">
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ className="flex w-full items-center justify-between gap-2 px-4 py-2 text-left"
+ >
+ <span className="flex items-center gap-2 text-[var(--muted-foreground)]">
+ <Archive className="h-3.5 w-3.5" />
+ {t("Your v1 memory was archived")}
+ </span>
+ {expanded ? (
+ <ChevronUp className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
+ ) : (
+ <ChevronDown className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
+ )}
+ </button>
+ {expanded && (
+ <div className="relative border-t border-[var(--border)] px-4 py-3 pr-10 text-[var(--muted-foreground)]">
+ {t(
+ "Stored at memory/backup/{{name}}. v2 starts fresh — interact with DeepTutor and click Update on each doc to build memory.",
+ { name: latestBackup },
+ )}
+ <button
+ type="button"
+ onClick={dismiss}
+ aria-label={t("Dismiss")}
+ className="absolute right-2 top-2 rounded-md p-1 text-[var(--muted-foreground)] transition hover:bg-[var(--background)] hover:text-[var(--foreground)]"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/memory/MemoryGraph.tsx b/web/components/memory/MemoryGraph.tsx
new file mode 100644
index 000000000..432e031c6
--- /dev/null
+++ b/web/components/memory/MemoryGraph.tsx
@@ -0,0 +1,980 @@
+"use client";
+
+import Link from "next/link";
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type CSSProperties,
+ type Dispatch,
+ type SetStateAction,
+ type WheelEvent as ReactWheelEvent,
+ type PointerEvent as ReactPointerEvent,
+} from "react";
+import {
+ ArrowLeft,
+ Eye,
+ EyeOff,
+ Loader2,
+ Maximize2,
+ RefreshCw,
+ ZoomIn,
+ ZoomOut,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import {
+ buildGraph,
+ DEFAULT_LAYOUT,
+ fetchMemorySnapshot,
+ L3_LABEL,
+ SURFACE_LABEL,
+ type ClusterMeta,
+ type GraphEdge,
+ type GraphNode,
+ type Layer,
+ type MemoryGraph,
+} from "@/lib/memory-graph";
+
+interface ViewState {
+ scale: number;
+ tx: number;
+ ty: number;
+}
+
+interface HoverState {
+ node: GraphNode;
+}
+
+const INITIAL_VIEW: ViewState = { scale: 1, tx: 0, ty: 0 };
+
+// One canonical hue per layer; alpha is per-state (idle/hover/dim).
+// Drawn from DeepTutor's primary palette so dark mode stays warm too.
+const LAYER_COLOR: Record<Layer, string> = {
+ L3: "var(--primary)",
+ L2: "color-mix(in srgb, var(--primary) 78%, var(--foreground) 22%)",
+ L1: "color-mix(in srgb, var(--primary) 38%, var(--foreground) 62%)",
+};
+
+const RING_LINE: Record<Layer, string> = {
+ L3: "color-mix(in srgb, var(--primary) 22%, transparent)",
+ L2: "color-mix(in srgb, var(--primary) 14%, transparent)",
+ L1: "color-mix(in srgb, var(--foreground) 10%, transparent)",
+};
+
+export default function MemoryGraph() {
+ const { t } = useTranslation();
+ const [graph, setGraph] = useState<MemoryGraph | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [layerOn, setLayerOn] = useState<Record<Layer, boolean>>({
+ L1: true,
+ L2: true,
+ L3: true,
+ });
+ const [hover, setHover] = useState<HoverState | null>(null);
+ const [selected, setSelected] = useState<string | null>(null);
+ const [view, setView] = useState<ViewState>(INITIAL_VIEW);
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const dragRef = useRef<{
+ pointerId: number;
+ startX: number;
+ startY: number;
+ origTx: number;
+ origTy: number;
+ } | null>(null);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const snap = await fetchMemorySnapshot();
+ setGraph(buildGraph(snap));
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ // ── Derived: active node id used by hover *or* explicit selection.
+ const activeId = selected ?? hover?.node.id ?? null;
+
+ const highlight = useMemo(() => {
+ if (!graph || !activeId) return null;
+ const neighbours = new Set<string>([activeId]);
+ const queue = [activeId];
+ // BFS limited to 2 hops so we get e.g. L3 → L2 → L1 chains.
+ for (let depth = 0; depth < 2 && queue.length; depth++) {
+ const next: string[] = [];
+ for (const id of queue) {
+ const adj = graph.adjacency.get(id) ?? [];
+ for (const n of adj) {
+ if (!neighbours.has(n)) {
+ neighbours.add(n);
+ next.push(n);
+ }
+ }
+ }
+ queue.length = 0;
+ queue.push(...next);
+ }
+ return neighbours;
+ }, [graph, activeId]);
+
+ // ── Pan / zoom handlers.
+ const onWheel = useCallback((e: ReactWheelEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ const rect = containerRef.current?.getBoundingClientRect();
+ if (!rect) return;
+ setView((v) => {
+ const factor = Math.exp(-e.deltaY * 0.001);
+ const next = Math.min(4, Math.max(0.35, v.scale * factor));
+ // Zoom centered on cursor: keep the world point under the cursor stationary.
+ const px = e.clientX - rect.left;
+ const py = e.clientY - rect.top;
+ const k = next / v.scale;
+ const tx = px - k * (px - v.tx);
+ const ty = py - k * (py - v.ty);
+ return { scale: next, tx, ty };
+ });
+ }, []);
+
+ const onPointerDown = useCallback(
+ (e: ReactPointerEvent<HTMLDivElement>) => {
+ // Only start a drag on background clicks — let node clicks bubble.
+ if ((e.target as HTMLElement).closest("[data-node]")) return;
+ (e.target as HTMLElement).setPointerCapture?.(e.pointerId);
+ dragRef.current = {
+ pointerId: e.pointerId,
+ startX: e.clientX,
+ startY: e.clientY,
+ origTx: view.tx,
+ origTy: view.ty,
+ };
+ setSelected(null);
+ },
+ [view],
+ );
+
+ const onPointerMove = useCallback(
+ (e: ReactPointerEvent<HTMLDivElement>) => {
+ const d = dragRef.current;
+ if (!d || d.pointerId !== e.pointerId) return;
+ setView((v) => ({
+ ...v,
+ tx: d.origTx + (e.clientX - d.startX),
+ ty: d.origTy + (e.clientY - d.startY),
+ }));
+ },
+ [],
+ );
+
+ const endDrag = useCallback(() => {
+ dragRef.current = null;
+ }, []);
+
+ // ── Center / fit the graph to the container on first paint.
+ useEffect(() => {
+ if (!graph) return;
+ const el = containerRef.current;
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ const target = DEFAULT_LAYOUT.width;
+ const scale = Math.min(rect.width / target, rect.height / target) * 0.95;
+ setView({
+ scale,
+ tx: (rect.width - target * scale) / 2,
+ ty: (rect.height - target * scale) / 2,
+ });
+ }, [graph]);
+
+ const fit = useCallback(() => {
+ if (!graph) return;
+ const el = containerRef.current;
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ const target = DEFAULT_LAYOUT.width;
+ const scale = Math.min(rect.width / target, rect.height / target) * 0.95;
+ setView({
+ scale,
+ tx: (rect.width - target * scale) / 2,
+ ty: (rect.height - target * scale) / 2,
+ });
+ }, [graph]);
+
+ const zoomBy = useCallback((factor: number) => {
+ const el = containerRef.current;
+ const rect = el?.getBoundingClientRect();
+ if (!rect) return;
+ setView((v) => {
+ const next = Math.min(4, Math.max(0.35, v.scale * factor));
+ const px = rect.width / 2;
+ const py = rect.height / 2;
+ const k = next / v.scale;
+ return {
+ scale: next,
+ tx: px - k * (px - v.tx),
+ ty: py - k * (py - v.ty),
+ };
+ });
+ }, []);
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <Header onRefresh={() => void load()} loading={loading} />
+
+ <div className="relative flex-1 min-h-0 overflow-hidden">
+ <div
+ ref={containerRef}
+ onWheel={onWheel}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={endDrag}
+ onPointerCancel={endDrag}
+ className="absolute inset-0 cursor-grab touch-none select-none active:cursor-grabbing"
+ style={{
+ background:
+ "radial-gradient(ellipse at center, color-mix(in srgb, var(--primary) 7%, var(--background)) 0%, var(--background) 65%)",
+ }}
+ >
+ {graph && (
+ <GraphView
+ graph={graph}
+ view={view}
+ layerOn={layerOn}
+ hover={hover}
+ setHover={setHover}
+ selected={selected}
+ setSelected={setSelected}
+ highlight={highlight}
+ />
+ )}
+
+ {loading && (
+ <div className="pointer-events-none absolute inset-0 grid place-items-center">
+ <div className="inline-flex items-center gap-2 rounded-full border border-[var(--border)] bg-[var(--card)]/80 px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] shadow-sm backdrop-blur">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ {t("Composing memory graph…")}
+ </div>
+ </div>
+ )}
+
+ {graph && !loading && (
+ <Controls
+ view={view}
+ layerOn={layerOn}
+ setLayerOn={setLayerOn}
+ zoomBy={zoomBy}
+ fit={fit}
+ />
+ )}
+
+ {hover && (
+ <HoverCard hover={hover} view={view} containerRef={containerRef} />
+ )}
+ </div>
+
+ {graph && !loading && <Legend graph={graph} />}
+ </div>
+ </div>
+ );
+}
+
+// ───────────────────────────────────────────────────────────── Header
+
+function Header({
+ onRefresh,
+ loading,
+}: {
+ onRefresh: () => void;
+ loading: boolean;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex items-center justify-between border-b border-[var(--border)] bg-[var(--background)]/80 px-6 py-3 backdrop-blur md:px-10">
+ <div className="flex items-center gap-3">
+ <Link
+ href="/memory"
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition hover:bg-[var(--muted)]"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ {t("Memory")}
+ </Link>
+ <div className="flex flex-col">
+ <h1 className="text-[16px] font-semibold tracking-tight text-[var(--foreground)]">
+ {t("Memory graph")}
+ </h1>
+ <p className="text-[11.5px] text-[var(--muted-foreground)]">
+ {t(
+ "L3 synthesis at the centre, L2 facts in the middle ring, L1 traces on the outside.",
+ )}
+ </p>
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={onRefresh}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] disabled:opacity-50"
+ disabled={loading}
+ >
+ <RefreshCw className={loading ? "h-3.5 w-3.5 animate-spin" : "h-3.5 w-3.5"} />
+ {t("Refresh")}
+ </button>
+ </div>
+ );
+}
+
+// ───────────────────────────────────────────────────────── GraphView
+
+interface GraphViewProps {
+ graph: MemoryGraph;
+ view: ViewState;
+ layerOn: Record<Layer, boolean>;
+ hover: HoverState | null;
+ setHover: Dispatch<SetStateAction<HoverState | null>>;
+ selected: string | null;
+ setSelected: Dispatch<SetStateAction<string | null>>;
+ highlight: Set<string> | null;
+}
+
+function GraphView({
+ graph,
+ view,
+ layerOn,
+ hover,
+ setHover,
+ selected,
+ setSelected,
+ highlight,
+}: GraphViewProps) {
+ const { t } = useTranslation();
+ // ── Cluster halos: large blurred translucent ellipses behind each
+ // slice so users see the cluster outlines before they read labels.
+ const haloPaths = useMemo(() => {
+ return graph.clusters.map((c) => buildClusterArc(c));
+ }, [graph.clusters]);
+
+ const visibleEdges = useMemo(() => {
+ return graph.edges.filter((e) => {
+ const sLayer = e.source.startsWith("L1")
+ ? "L1"
+ : e.source.startsWith("L2")
+ ? "L2"
+ : "L3";
+ const tLayer = e.target.startsWith("L1")
+ ? "L1"
+ : e.target.startsWith("L2")
+ ? "L2"
+ : "L3";
+ return layerOn[sLayer as Layer] && layerOn[tLayer as Layer];
+ });
+ }, [graph.edges, layerOn]);
+
+ // Pre-index nodes by id for fast endpoint lookup when drawing edges.
+ const nodeIdx = useMemo(() => {
+ const m = new Map<string, GraphNode>();
+ for (const n of graph.nodes) m.set(n.id, n);
+ return m;
+ }, [graph.nodes]);
+
+ return (
+ <svg
+ width="100%"
+ height="100%"
+ style={{ position: "absolute", inset: 0 }}
+ aria-label={t("Memory graph")}
+ >
+ <defs>
+ <radialGradient id="halo-l3" cx="50%" cy="50%" r="50%">
+ <stop offset="0%" stopColor="var(--primary)" stopOpacity="0.20" />
+ <stop offset="100%" stopColor="var(--primary)" stopOpacity="0.02" />
+ </radialGradient>
+ <radialGradient id="halo-l2" cx="50%" cy="50%" r="50%">
+ <stop offset="0%" stopColor="var(--primary)" stopOpacity="0.12" />
+ <stop offset="100%" stopColor="var(--primary)" stopOpacity="0.02" />
+ </radialGradient>
+ <radialGradient id="halo-l1" cx="50%" cy="50%" r="50%">
+ <stop offset="0%" stopColor="var(--foreground)" stopOpacity="0.08" />
+ <stop offset="100%" stopColor="var(--foreground)" stopOpacity="0.01" />
+ </radialGradient>
+ </defs>
+
+ <g
+ transform={`translate(${view.tx} ${view.ty}) scale(${view.scale})`}
+ >
+ {/* Concentric ring guides (faint). */}
+ <g pointerEvents="none">
+ {(["L1", "L2", "L3"] as const).map((layer) => {
+ if (!layerOn[layer]) return null;
+ const opt = DEFAULT_LAYOUT;
+ const inner =
+ layer === "L1"
+ ? opt.l1InnerRadius
+ : layer === "L2"
+ ? opt.l2InnerRadius
+ : opt.l3InnerRadius;
+ const outer =
+ layer === "L1"
+ ? opt.l1OuterRadius
+ : layer === "L2"
+ ? opt.l2OuterRadius
+ : opt.l3OuterRadius;
+ const cx = opt.width / 2;
+ const cy = opt.height / 2;
+ return (
+ <g key={`ring-${layer}`}>
+ <circle
+ cx={cx}
+ cy={cy}
+ r={inner}
+ fill="none"
+ stroke={RING_LINE[layer]}
+ strokeWidth={0.6}
+ strokeDasharray="2 3"
+ />
+ <circle
+ cx={cx}
+ cy={cy}
+ r={outer}
+ fill="none"
+ stroke={RING_LINE[layer]}
+ strokeWidth={0.6}
+ strokeDasharray="2 3"
+ />
+ </g>
+ );
+ })}
+ </g>
+
+ {/* Cluster halos. */}
+ <g pointerEvents="none">
+ {graph.clusters.map((c, i) => {
+ if (!layerOn[c.layer]) return null;
+ const fill = `url(#halo-${c.layer.toLowerCase()})`;
+ return (
+ <path
+ key={c.id}
+ d={haloPaths[i]}
+ fill={fill}
+ stroke="color-mix(in srgb, var(--primary) 8%, transparent)"
+ strokeWidth={0.6}
+ />
+ );
+ })}
+ </g>
+
+ {/* Cluster labels. L1 labels orbit *outside* the outer ring,
+ L2 labels sit just outside the L2 ring, L3 labels are
+ rendered as a single core badge (handled below). */}
+ <g pointerEvents="none">
+ {graph.clusters.map((c) => {
+ if (!layerOn[c.layer]) return null;
+ if (c.layer === "L3") return null;
+ const mid = (c.startAngle + c.endAngle) / 2;
+ const cx = DEFAULT_LAYOUT.width / 2;
+ const cy = DEFAULT_LAYOUT.height / 2;
+ const rOut = c.outerRadius + (c.layer === "L1" ? 30 : 18);
+ const x = cx + Math.cos(mid) * rOut;
+ const y = cy + Math.sin(mid) * rOut;
+ return (
+ <g key={`label-${c.id}`}>
+ <text
+ x={x}
+ y={y - 12}
+ fontSize={c.layer === "L2" ? 20 : 22}
+ fontWeight={600}
+ fill="var(--foreground)"
+ textAnchor="middle"
+ dominantBaseline="central"
+ style={{ userSelect: "none" }}
+ >
+ {t(c.label)}
+ </text>
+ <text
+ x={x}
+ y={y + 14}
+ fontSize={15}
+ fontWeight={500}
+ fill="var(--muted-foreground)"
+ textAnchor="middle"
+ dominantBaseline="central"
+ style={{ userSelect: "none" }}
+ >
+ {c.count.toLocaleString()}{" "}
+ {c.layer === "L2" ? t("facts") : t("traces")}
+ </text>
+ </g>
+ );
+ })}
+ </g>
+
+ {/* L3 core: a soft "core" plate at the centre with the three
+ slot labels placed at their slice mid-angles inside the
+ inner radius. */}
+ {layerOn.L3 && (
+ <g pointerEvents="none">
+ <circle
+ cx={DEFAULT_LAYOUT.width / 2}
+ cy={DEFAULT_LAYOUT.height / 2}
+ r={DEFAULT_LAYOUT.l3InnerRadius - 6}
+ fill="color-mix(in srgb, var(--primary) 12%, var(--background))"
+ stroke="color-mix(in srgb, var(--primary) 22%, transparent)"
+ strokeWidth={1}
+ />
+ <text
+ x={DEFAULT_LAYOUT.width / 2}
+ y={DEFAULT_LAYOUT.height / 2 - 10}
+ fontSize={22}
+ fontWeight={700}
+ fill="var(--primary)"
+ textAnchor="middle"
+ dominantBaseline="central"
+ style={{ letterSpacing: "0.08em", userSelect: "none" }}
+ >
+ L3
+ </text>
+ <text
+ x={DEFAULT_LAYOUT.width / 2}
+ y={DEFAULT_LAYOUT.height / 2 + 16}
+ fontSize={14}
+ fontWeight={500}
+ fill="var(--muted-foreground)"
+ textAnchor="middle"
+ dominantBaseline="central"
+ style={{ letterSpacing: "0.04em", userSelect: "none" }}
+ >
+ {t("synthesis")}
+ </text>
+ {graph.clusters
+ .filter((c) => c.layer === "L3")
+ .map((c) => {
+ const mid = (c.startAngle + c.endAngle) / 2;
+ const cx = DEFAULT_LAYOUT.width / 2;
+ const cy = DEFAULT_LAYOUT.height / 2;
+ const r = c.outerRadius + 14;
+ const x = cx + Math.cos(mid) * r;
+ const y = cy + Math.sin(mid) * r;
+ return (
+ <text
+ key={`l3-label-${c.id}`}
+ x={x}
+ y={y}
+ fontSize={18}
+ fontWeight={600}
+ fill="var(--primary)"
+ textAnchor="middle"
+ dominantBaseline="central"
+ style={{ letterSpacing: "0.04em", userSelect: "none" }}
+ >
+ {t(c.label)}
+ </text>
+ );
+ })}
+ </g>
+ )}
+
+ {/* Edges. */}
+ <g pointerEvents="none">
+ {visibleEdges.map((e) => {
+ const s = nodeIdx.get(e.source);
+ const t2 = nodeIdx.get(e.target);
+ if (!s || !t2) return null;
+ const dim =
+ highlight !== null && !highlight.has(e.source) &&
+ !highlight.has(e.target);
+ const focused =
+ highlight !== null &&
+ highlight.has(e.source) &&
+ highlight.has(e.target);
+ const opacity = dim
+ ? 0.04
+ : focused
+ ? e.kind === "strong"
+ ? 0.85
+ : 0.55
+ : e.kind === "strong"
+ ? 0.16
+ : 0.08;
+ const stroke = focused ? "var(--primary)" : LAYER_COLOR[layerOf(e)];
+ return (
+ <EdgePath
+ key={`${e.source}->${e.target}`}
+ edge={e}
+ s={s}
+ t={t2}
+ opacity={opacity}
+ stroke={stroke}
+ focused={focused}
+ />
+ );
+ })}
+ </g>
+
+ {/* Nodes. */}
+ <g>
+ {graph.nodes.map((n) => {
+ if (!layerOn[n.layer]) return null;
+ if (n.r === 0) return null; // synthetic anchor
+ const dim = highlight !== null && !highlight.has(n.id);
+ const focused = highlight !== null && highlight.has(n.id);
+ const isActive = n.id === (selected ?? hover?.node.id);
+ return (
+ <NodeDot
+ key={n.id}
+ node={n}
+ isActive={isActive}
+ focused={focused}
+ dim={dim}
+ onEnter={(node) => setHover({ node })}
+ onLeave={(node) =>
+ setHover((cur) => (cur?.node.id === node.id ? null : cur))
+ }
+ onClick={() =>
+ setSelected((cur) => (cur === n.id ? null : n.id))
+ }
+ />
+ );
+ })}
+ </g>
+ </g>
+ </svg>
+ );
+}
+
+function layerOf(e: GraphEdge): Layer {
+ // Pick the more synthetic layer for edge colour: L3 dominates,
+ // then L2.
+ if (e.source.startsWith("L3") || e.target.startsWith("L3")) return "L3";
+ if (e.source.startsWith("L2") || e.target.startsWith("L2")) return "L2";
+ return "L1";
+}
+
+function EdgePath({
+ edge,
+ s,
+ t,
+ opacity,
+ stroke,
+ focused,
+}: {
+ edge: GraphEdge;
+ s: GraphNode;
+ t: GraphNode;
+ opacity: number;
+ stroke: string;
+ focused: boolean;
+}) {
+ // Quadratic curve: control point pulled toward the canvas center
+ // gives the bundle a hub-and-spoke feel rather than a noisy mesh.
+ const cx = DEFAULT_LAYOUT.width / 2;
+ const cy = DEFAULT_LAYOUT.height / 2;
+ const mx = (s.x + t.x) / 2;
+ const my = (s.y + t.y) / 2;
+ const k = edge.kind === "soft" ? 0.45 : 0.25;
+ const cpx = mx + (cx - mx) * k;
+ const cpy = my + (cy - my) * k;
+ return (
+ <path
+ d={`M ${s.x} ${s.y} Q ${cpx} ${cpy} ${t.x} ${t.y}`}
+ stroke={stroke}
+ strokeWidth={focused ? 0.9 : edge.kind === "strong" ? 0.5 : 0.35}
+ strokeOpacity={opacity}
+ fill="none"
+ strokeLinecap="round"
+ />
+ );
+}
+
+function NodeDot({
+ node,
+ isActive,
+ focused,
+ dim,
+ onEnter,
+ onLeave,
+ onClick,
+}: {
+ node: GraphNode;
+ isActive: boolean;
+ focused: boolean;
+ dim: boolean;
+ onEnter: (node: GraphNode) => void;
+ onLeave: (node: GraphNode) => void;
+ onClick: () => void;
+}) {
+ const baseR = node.r;
+ const r = isActive ? baseR * 2.1 : focused ? baseR * 1.35 : baseR;
+ const fill = LAYER_COLOR[node.layer];
+ const opacity = dim ? 0.18 : 1;
+ // Always offer at least a 10-pixel-radius invisible target so the
+ // mouse doesn't need pixel-perfect aim. Larger of (3×base radius,
+ // 10px) gives small L1 dots a generous hit halo without making
+ // dense clusters fight over hover.
+ const hitR = Math.max(baseR * 3, 10);
+ return (
+ <g data-node={node.id} style={{ cursor: "pointer" }}>
+ <circle
+ cx={node.x}
+ cy={node.y}
+ r={hitR}
+ fill="transparent"
+ pointerEvents="all"
+ onPointerEnter={() => onEnter(node)}
+ onPointerLeave={() => onLeave(node)}
+ onClick={onClick}
+ />
+ {isActive && (
+ <circle
+ cx={node.x}
+ cy={node.y}
+ r={r * 2.5}
+ fill={fill}
+ opacity={0.18}
+ pointerEvents="none"
+ />
+ )}
+ <circle
+ cx={node.x}
+ cy={node.y}
+ r={r}
+ fill={fill}
+ opacity={opacity}
+ stroke={isActive ? "var(--background)" : "transparent"}
+ strokeWidth={isActive ? 1.5 : 0}
+ pointerEvents="none"
+ />
+ </g>
+ );
+}
+
+// Pie-slice "arc" path between two radii.
+function buildClusterArc(c: ClusterMeta): string {
+ const cx = DEFAULT_LAYOUT.width / 2;
+ const cy = DEFAULT_LAYOUT.height / 2;
+ const { startAngle, endAngle, innerRadius, outerRadius } = c;
+ const large = endAngle - startAngle > Math.PI ? 1 : 0;
+ const x1 = cx + Math.cos(startAngle) * outerRadius;
+ const y1 = cy + Math.sin(startAngle) * outerRadius;
+ const x2 = cx + Math.cos(endAngle) * outerRadius;
+ const y2 = cy + Math.sin(endAngle) * outerRadius;
+ const x3 = cx + Math.cos(endAngle) * innerRadius;
+ const y3 = cy + Math.sin(endAngle) * innerRadius;
+ const x4 = cx + Math.cos(startAngle) * innerRadius;
+ const y4 = cy + Math.sin(startAngle) * innerRadius;
+ return [
+ `M ${x1} ${y1}`,
+ `A ${outerRadius} ${outerRadius} 0 ${large} 1 ${x2} ${y2}`,
+ `L ${x3} ${y3}`,
+ `A ${innerRadius} ${innerRadius} 0 ${large} 0 ${x4} ${y4}`,
+ "Z",
+ ].join(" ");
+}
+
+// ─────────────────────────────────────────────────────────── Controls
+
+function Controls({
+ view,
+ layerOn,
+ setLayerOn,
+ zoomBy,
+ fit,
+}: {
+ view: ViewState;
+ layerOn: Record<Layer, boolean>;
+ setLayerOn: (next: Record<Layer, boolean>) => void;
+ zoomBy: (factor: number) => void;
+ fit: () => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="pointer-events-none absolute right-4 top-4 flex flex-col items-end gap-2">
+ <div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--card)]/95 shadow-sm backdrop-blur">
+ <IconButton onClick={() => zoomBy(1.25)} title={t("Zoom in")}>
+ <ZoomIn className="h-3.5 w-3.5" />
+ </IconButton>
+ <IconButton onClick={() => zoomBy(1 / 1.25)} title={t("Zoom out")}>
+ <ZoomOut className="h-3.5 w-3.5" />
+ </IconButton>
+ <IconButton onClick={fit} title={t("Fit")}>
+ <Maximize2 className="h-3.5 w-3.5" />
+ </IconButton>
+ <span className="px-2 text-[11px] tabular-nums text-[var(--muted-foreground)]">
+ {(view.scale * 100).toFixed(0)}%
+ </span>
+ </div>
+
+ <div className="pointer-events-auto flex flex-col gap-1 rounded-lg border border-[var(--border)] bg-[var(--card)]/95 p-1.5 shadow-sm backdrop-blur">
+ {(["L3", "L2", "L1"] as const).map((layer) => (
+ <button
+ key={layer}
+ type="button"
+ onClick={() => setLayerOn({ ...layerOn, [layer]: !layerOn[layer] })}
+ className="group inline-flex items-center gap-2 rounded-md px-2 py-1 text-[11.5px] text-[var(--foreground)] transition hover:bg-[var(--muted)]"
+ >
+ <span
+ className="inline-block h-2 w-2 rounded-full"
+ style={{ background: LAYER_COLOR[layer] }}
+ />
+ <span className="font-medium">{layer}</span>
+ <span className="text-[var(--muted-foreground)]">
+ {layer === "L3"
+ ? t("Synthesis")
+ : layer === "L2"
+ ? t("Per-surface")
+ : t("Raw traces")}
+ </span>
+ {layerOn[layer] ? (
+ <Eye className="ml-1 h-3 w-3 text-[var(--muted-foreground)]" />
+ ) : (
+ <EyeOff className="ml-1 h-3 w-3 text-[var(--muted-foreground)]/60" />
+ )}
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function IconButton({
+ onClick,
+ title,
+ children,
+}: {
+ onClick: () => void;
+ title: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ title={title}
+ className="grid h-8 w-8 place-items-center text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ {children}
+ </button>
+ );
+}
+
+// ──────────────────────────────────────────────────────────── Legend
+
+function Legend({ graph }: { graph: MemoryGraph }) {
+ const { t } = useTranslation();
+ // Aggregate counts.
+ const byLayer = useMemo(() => {
+ const out: Record<Layer, number> = { L1: 0, L2: 0, L3: 0 };
+ for (const n of graph.nodes) {
+ if (n.r === 0) continue; // ignore synthetic anchors
+ out[n.layer] += 1;
+ }
+ return out;
+ }, [graph.nodes]);
+
+ return (
+ <div className="pointer-events-none absolute bottom-4 left-4 max-w-md rounded-lg border border-[var(--border)] bg-[var(--card)]/92 p-3 text-[11.5px] shadow-sm backdrop-blur">
+ <div className="mb-2 flex items-center gap-3 text-[var(--muted-foreground)]">
+ {(["L3", "L2", "L1"] as const).map((layer) => (
+ <span key={layer} className="inline-flex items-center gap-1.5">
+ <span
+ className="inline-block h-2 w-2 rounded-full"
+ style={{ background: LAYER_COLOR[layer] }}
+ />
+ <span className="font-medium text-[var(--foreground)]">
+ {layer}
+ </span>
+ <span>{byLayer[layer]}</span>
+ </span>
+ ))}
+ </div>
+ <p className="leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ "Hover a node to preview the memory. Click to lock the highlight and trace its references inward (L1 → L2 → L3) or outward.",
+ )}
+ </p>
+ </div>
+ );
+}
+
+// ─────────────────────────────────────────────────────── HoverCard
+
+function HoverCard({
+ hover,
+ view,
+ containerRef,
+}: {
+ hover: HoverState;
+ view: ViewState;
+ containerRef: React.RefObject<HTMLDivElement | null>;
+}) {
+ const { t } = useTranslation();
+ const { node } = hover;
+ // Anchor the tooltip to the *node's* screen position (not the
+ // cursor), so we don't have to handle mousemove for every dot. The
+ // card is offset down-right of the node so the user can still read
+ // the dot underneath the cursor.
+ const rect = containerRef.current?.getBoundingClientRect();
+ const screenX = (rect?.left ?? 0) + node.x * view.scale + view.tx;
+ const screenY = (rect?.top ?? 0) + node.y * view.scale + view.ty;
+ const offset = Math.max(node.r * view.scale + 14, 18);
+ const style: CSSProperties = {
+ left: screenX + offset,
+ top: screenY + offset,
+ };
+ const meta = nodeMeta(node, t);
+ return (
+ <div
+ className="pointer-events-none fixed z-50 max-w-sm rounded-lg border border-[var(--border)] bg-[var(--card)] p-3 text-[12px] shadow-lg"
+ style={style}
+ >
+ <div className="mb-1 flex items-center gap-2 text-[10.5px] uppercase tracking-wider text-[var(--muted-foreground)]">
+ <span
+ className="inline-block h-2 w-2 rounded-full"
+ style={{ background: LAYER_COLOR[node.layer] }}
+ />
+ <span>{meta.layerLabel}</span>
+ <span className="text-[var(--border)]">·</span>
+ <span>{meta.clusterLabel}</span>
+ {node.section && (
+ <>
+ <span className="text-[var(--border)]">·</span>
+ <span className="text-[var(--foreground)]/80">{node.section}</span>
+ </>
+ )}
+ </div>
+ <p className="leading-relaxed text-[var(--foreground)] line-clamp-6">
+ {node.preview || node.label}
+ </p>
+ <p className="mt-2 text-[10.5px] text-[var(--muted-foreground)]">
+ {t("Click to lock · open in workbench")}
+ </p>
+ </div>
+ );
+}
+
+function nodeMeta(
+ n: GraphNode,
+ t: (key: string) => string,
+): { layerLabel: string; clusterLabel: string } {
+ const [, cluster] = n.cluster.split(":");
+ if (n.layer === "L3") {
+ return {
+ layerLabel: t("L3 · synthesis"),
+ clusterLabel: t(L3_LABEL[cluster as keyof typeof L3_LABEL] || cluster),
+ };
+ }
+ if (n.layer === "L2") {
+ return {
+ layerLabel: t("L2 · curated"),
+ clusterLabel: t(SURFACE_LABEL[cluster as keyof typeof SURFACE_LABEL] || cluster),
+ };
+ }
+ return {
+ layerLabel: t("L1 · raw trace"),
+ clusterLabel: t(SURFACE_LABEL[cluster as keyof typeof SURFACE_LABEL] || cluster),
+ };
+}
+
+export type { GraphNode, GraphEdge, MemoryGraph };
diff --git a/web/components/memory/MemoryHub.tsx b/web/components/memory/MemoryHub.tsx
new file mode 100644
index 000000000..f8dd07042
--- /dev/null
+++ b/web/components/memory/MemoryHub.tsx
@@ -0,0 +1,260 @@
+"use client";
+
+import Link from "next/link";
+import { useCallback, useEffect, useState } from "react";
+import {
+ ArrowRight,
+ Brain,
+ Layers,
+ Network,
+ RefreshCw,
+ Sparkles,
+ Workflow,
+ type LucideIcon,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { apiFetch, apiUrl } from "@/lib/api";
+import MemoryArchivedBanner from "@/components/memory/MemoryArchivedBanner";
+
+interface DocOverview {
+ layer: "L2" | "L3";
+ key: string;
+ exists: boolean;
+ updated_at: string | null;
+ entry_count: number;
+ backlog: number;
+}
+
+interface OverviewResponse {
+ docs: DocOverview[];
+ backups: string[];
+}
+
+interface SnapshotResponse {
+ surface: string;
+ entities: unknown[];
+}
+
+const SURFACES = [
+ "chat",
+ "notebook",
+ "quiz",
+ "kb",
+ "book",
+ "tutorbot",
+ "cowriter",
+] as const;
+
+const L3_VISIBLE = ["recent", "profile", "scope"] as const;
+
+export default function MemoryHub() {
+ const { t } = useTranslation();
+ const [overview, setOverview] = useState<OverviewResponse | null>(null);
+ const [l1Total, setL1Total] = useState<number | null>(null);
+ const [loading, setLoading] = useState(true);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const [ovRes, ...l1Counts] = await Promise.all([
+ apiFetch(apiUrl("/api/v1/memory/overview")).then((r) => r.json()),
+ ...SURFACES.map((s) =>
+ apiFetch(apiUrl(`/api/v1/memory/snapshot/${s}`))
+ .then((r) => r.json())
+ .then((d: SnapshotResponse) => d?.entities?.length ?? 0)
+ .catch(() => 0),
+ ),
+ ]);
+ setOverview(ovRes as OverviewResponse);
+ setL1Total(l1Counts.reduce<number>((acc, n) => acc + (n as number), 0));
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const l2Docs = (overview?.docs || []).filter((d) => d.layer === "L2");
+ const l3Docs = (overview?.docs || []).filter(
+ (d) => d.layer === "L3" && d.key !== "preferences",
+ );
+ const l2Total = l2Docs.reduce((acc, d) => acc + d.entry_count, 0);
+ const l3Total = l3Docs.reduce((acc, d) => acc + d.entry_count, 0);
+ const latestBackup =
+ overview?.backups?.[overview.backups.length - 1] ?? null;
+
+ return (
+ <div className="space-y-10">
+ <header className="space-y-3">
+ <div className="flex items-center gap-3">
+ <span className="grid h-10 w-10 place-items-center rounded-xl bg-[var(--primary)]/10 text-[var(--primary)]">
+ <Brain className="h-5 w-5" />
+ </span>
+ <h1 className="text-[28px] font-semibold tracking-tight text-[var(--foreground)] md:text-[32px]">
+ {t("Memory")}
+ </h1>
+ </div>
+ <p className="max-w-2xl text-[14px] text-[var(--muted-foreground)] md:text-[15px]">
+ {t(
+ "Everything DeepTutor remembers about you, organised across three layers. Click into any layer to inspect or curate it.",
+ )}
+ </p>
+ <div className="flex items-center gap-3 text-[12px] text-[var(--muted-foreground)]">
+ <button
+ type="button"
+ onClick={() => void load()}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 transition hover:bg-[var(--muted)]"
+ >
+ <RefreshCw className={loading ? "h-3 w-3 animate-spin" : "h-3 w-3"} />
+ {t("Refresh")}
+ </button>
+ <Link
+ href="/settings/memory"
+ className="inline-flex items-center gap-1.5 rounded-md border border-transparent px-2.5 py-1 transition hover:bg-[var(--muted)]"
+ >
+ {t("Memory settings")}
+ </Link>
+ </div>
+ </header>
+
+ <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
+ <LayerCard
+ href="/memory/l1"
+ icon={Layers}
+ title={t("L1 · Workspace mirror")}
+ tag={t("Live")}
+ stat={l1Total === null ? "…" : l1Total.toLocaleString()}
+ statLabel={t("entities tracked")}
+ detail={t(
+ "Snapshot of your live workspace across {{n}} surfaces. Refresh to record changes.",
+ { n: SURFACES.length },
+ )}
+ />
+ <LayerCard
+ href="/memory/l2"
+ icon={Workflow}
+ title={t("L2 · Per-surface summaries")}
+ tag={t("Curated")}
+ stat={l2Total.toLocaleString()}
+ statLabel={t("facts across {{n}} surfaces", { n: l2Docs.length || SURFACES.length })}
+ detail={t(
+ "Surface-specific facts extracted by the consolidator. Run Update / Audit / Dedup per doc.",
+ )}
+ />
+ <LayerCard
+ href="/memory/l3"
+ icon={Network}
+ title={t("L3 · Cross-surface knowledge")}
+ tag={t("Synthesis")}
+ stat={l3Total.toLocaleString()}
+ statLabel={t("propositions across {{n}} slots", { n: l3Docs.length || L3_VISIBLE.length })}
+ detail={t(
+ "Cross-surface synthesis: profile, recent timeline, knowledge scope. Hedged claims with L2 evidence.",
+ )}
+ />
+ </div>
+
+ <GraphCallout />
+
+ <MemoryArchivedBanner latestBackup={latestBackup} variant="compact" />
+ </div>
+ );
+}
+
+function GraphCallout() {
+ const { t } = useTranslation();
+ return (
+ <Link
+ href="/memory/graph"
+ className="group relative block overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 transition hover:-translate-y-[1px] hover:border-[var(--primary)]/40 hover:shadow-sm"
+ >
+ <div
+ className="pointer-events-none absolute inset-0 opacity-80"
+ style={{
+ background:
+ "radial-gradient(ellipse 60% 80% at 92% 50%, color-mix(in srgb, var(--primary) 16%, transparent), transparent 70%)",
+ }}
+ />
+ <div className="relative flex items-center gap-5">
+ <span className="grid h-12 w-12 shrink-0 place-items-center rounded-xl bg-[var(--primary)]/10 text-[var(--primary)]">
+ <Sparkles className="h-5 w-5" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <h3 className="text-[15px] font-semibold text-[var(--foreground)]">
+ {t("Memory graph")}
+ </h3>
+ <span className="rounded-full border border-[var(--border)] bg-[var(--background)]/60 px-2 py-0.5 text-[10.5px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
+ {t("New")}
+ </span>
+ </div>
+ <p className="mt-1 text-[13px] leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ "See all three layers at once — L3 synthesis at the centre, L2 facts in the middle, L1 traces on the outside. Hover any node for a preview.",
+ )}
+ </p>
+ </div>
+ <ArrowRight className="hidden h-4 w-4 shrink-0 text-[var(--primary)] transition group-hover:translate-x-0.5 md:block" />
+ </div>
+ </Link>
+ );
+}
+
+interface LayerCardProps {
+ href: string;
+ icon: LucideIcon;
+ title: string;
+ tag: string;
+ stat: string;
+ statLabel: string;
+ detail: string;
+}
+
+function LayerCard({
+ href,
+ icon: Icon,
+ title,
+ tag,
+ stat,
+ statLabel,
+ detail,
+}: LayerCardProps) {
+ return (
+ <Link
+ href={href}
+ className="group flex flex-col gap-4 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 transition hover:-translate-y-[1px] hover:border-[var(--primary)]/40 hover:shadow-sm"
+ >
+ <div className="flex items-start justify-between">
+ <span className="grid h-9 w-9 place-items-center rounded-lg bg-[var(--primary)]/10 text-[var(--primary)]">
+ <Icon className="h-4 w-4" />
+ </span>
+ <span className="rounded-full border border-[var(--border)] bg-[var(--background)] px-2 py-0.5 text-[10.5px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
+ {tag}
+ </span>
+ </div>
+ <div className="space-y-1">
+ <h2 className="text-[15px] font-semibold text-[var(--foreground)]">
+ {title}
+ </h2>
+ </div>
+ <div className="flex items-baseline gap-2">
+ <span className="text-[28px] font-semibold tracking-tight text-[var(--foreground)]">
+ {stat}
+ </span>
+ <span className="text-[12px] text-[var(--muted-foreground)]">
+ {statLabel}
+ </span>
+ </div>
+ <p className="text-[13px] leading-relaxed text-[var(--muted-foreground)]">
+ {detail}
+ </p>
+ <div className="mt-auto inline-flex items-center gap-1 text-[12px] font-medium text-[var(--primary)] opacity-0 transition group-hover:opacity-100">
+ <span>{tag}</span>
+ <ArrowRight className="h-3.5 w-3.5" />
+ </div>
+ </Link>
+ );
+}
diff --git a/web/components/memory/MemoryL1Workbench.tsx b/web/components/memory/MemoryL1Workbench.tsx
new file mode 100644
index 000000000..a0ec6f19c
--- /dev/null
+++ b/web/components/memory/MemoryL1Workbench.tsx
@@ -0,0 +1,272 @@
+"use client";
+
+import Link from "next/link";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ ArrowLeft,
+ BookOpen,
+ Bot,
+ ClipboardList,
+ Layers,
+ Library,
+ MessageSquare,
+ Network,
+ NotebookPen,
+ PenLine,
+ Workflow,
+ type LucideIcon,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { apiFetch, apiUrl } from "@/lib/api";
+import { L1View } from "@/components/memory/MemorySection";
+
+type Surface =
+ | "chat"
+ | "notebook"
+ | "quiz"
+ | "kb"
+ | "book"
+ | "tutorbot"
+ | "cowriter";
+
+interface NavEntry {
+ key: Surface;
+ label: string;
+ icon: LucideIcon;
+}
+
+const L1_NAV: NavEntry[] = [
+ { key: "chat", icon: MessageSquare, label: "Chat" },
+ { key: "notebook", icon: NotebookPen, label: "Notebook" },
+ { key: "quiz", icon: ClipboardList, label: "Quiz" },
+ { key: "kb", icon: BookOpen, label: "Knowledge base" },
+ { key: "book", icon: Library, label: "Book" },
+ { key: "tutorbot", icon: Bot, label: "TutorBot" },
+ { key: "cowriter", icon: PenLine, label: "Co-writer" },
+];
+
+interface SnapshotResponse {
+ surface: Surface;
+ entities: unknown[];
+ pending_changes: unknown[];
+}
+
+export interface MemoryL1WorkbenchProps {
+ initialSurface?: Surface;
+ initialFocusRef?: string;
+}
+
+export default function MemoryL1Workbench({
+ initialSurface,
+ initialFocusRef,
+}: MemoryL1WorkbenchProps) {
+ const { t } = useTranslation();
+ // ``initialSurface`` and ``initialFocusRef`` seed the picker + entity
+ // highlight on first mount. The URL only drives initial state; once the
+ // user clicks around the rail it's all local state again.
+ const [surface, setSurface] = useState<Surface>(initialSurface || "notebook");
+ const [counts, setCounts] = useState<Record<Surface, number>>({} as Record<Surface, number>);
+ const [pending, setPending] = useState<Record<Surface, number>>({} as Record<Surface, number>);
+ const [focusRef, setFocusRef] = useState<string | null>(initialFocusRef ?? null);
+ const [toast, setToast] = useState("");
+
+ // Fetch counts + pending badges for the left rail in parallel.
+ const loadCounts = useCallback(async () => {
+ const entries = await Promise.all(
+ L1_NAV.map(async ({ key }) => {
+ try {
+ const res = await apiFetch(apiUrl(`/api/v1/memory/snapshot/${key}`));
+ const data = (await res.json()) as SnapshotResponse;
+ return [
+ key,
+ data?.entities?.length ?? 0,
+ data?.pending_changes?.length ?? 0,
+ ] as const;
+ } catch {
+ return [key, 0, 0] as const;
+ }
+ }),
+ );
+ setCounts(
+ Object.fromEntries(entries.map(([k, n]) => [k, n])) as Record<Surface, number>,
+ );
+ setPending(
+ Object.fromEntries(entries.map(([k, , p]) => [k, p])) as Record<Surface, number>,
+ );
+ }, []);
+
+ useEffect(() => {
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ void loadCounts();
+ }, [loadCounts]);
+
+ // Re-fetch counts when the tab regains focus so the rail stays in sync.
+ useEffect(() => {
+ const refetch = () => {
+ if (typeof document !== "undefined" && document.hidden) return;
+ void loadCounts();
+ };
+ window.addEventListener("focus", refetch);
+ document.addEventListener("visibilitychange", refetch);
+ return () => {
+ window.removeEventListener("focus", refetch);
+ document.removeEventListener("visibilitychange", refetch);
+ };
+ }, [loadCounts]);
+
+ useEffect(() => {
+ if (!toast) return;
+ const id = setTimeout(() => setToast(""), 2500);
+ return () => clearTimeout(id);
+ }, [toast]);
+
+ const nicelabel = useMemo(
+ () => {
+ const entry = L1_NAV.find((n) => n.key === surface);
+ return entry ? t(entry.label) : surface;
+ },
+ [surface, t],
+ );
+
+ return (
+ <div className="flex h-full min-h-0 flex-col gap-3 px-6 py-4 md:px-10">
+ <div className="flex items-center justify-between gap-3">
+ <Breadcrumb label={nicelabel} t={t} />
+ <LayerSwitcher t={t} />
+ </div>
+
+ <div className="grid min-h-0 flex-1 grid-cols-[180px_minmax(0,1fr)] gap-4">
+ {/* Left rail */}
+ <aside className="min-h-0 overflow-y-auto rounded-2xl border border-[var(--border)] bg-[var(--card)] p-2">
+ <ul className="space-y-0.5">
+ {L1_NAV.map(({ key, icon: Icon, label }) => {
+ const active = key === surface;
+ const c = counts[key];
+ const p = pending[key];
+ return (
+ <li key={key}>
+ <button
+ type="button"
+ onClick={() => {
+ setSurface(key);
+ setFocusRef(null);
+ }}
+ className={
+ "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[12.5px] transition " +
+ (active
+ ? "bg-[var(--muted)] text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]")
+ }
+ >
+ <Icon className="h-3.5 w-3.5 shrink-0" />
+ <span className="flex-1 truncate">{t(label)}</span>
+ {p > 0 ? (
+ <span
+ className="rounded-full bg-amber-500/10 px-1.5 py-0.5 text-[10px] text-amber-600 dark:text-amber-400"
+ title={t("{{n}} pending", { n: p })}
+ >
+ {p}
+ </span>
+ ) : typeof c === "number" ? (
+ <span className="rounded-full bg-[var(--background)] px-1.5 py-0.5 text-[10px] text-[var(--muted-foreground)]">
+ {c}
+ </span>
+ ) : null}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </aside>
+
+ {/* Center: snapshot / changes / kb-queries preview */}
+ <section className="min-h-0 overflow-y-auto rounded-2xl border border-[var(--border)] bg-[var(--card)] p-5">
+ <L1View
+ surface={surface}
+ onSurfaceChange={(s) => {
+ setSurface(s as Surface);
+ setFocusRef(null);
+ }}
+ focusRef={focusRef}
+ onClearFocus={() => setFocusRef(null)}
+ onToast={setToast}
+ t={t}
+ compact
+ />
+ </section>
+ </div>
+
+ {toast && (
+ <div className="self-start rounded-md border border-[var(--primary)]/30 bg-[var(--primary)]/10 px-3 py-1 text-[11.5px] text-[var(--primary)]">
+ {toast}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function LayerSwitcher({ t }: { t: (k: string) => string }) {
+ // L1 is the current page, so it stays as a non-link pill; L2 + L3
+ // link to their respective hubs.
+ const entries: { key: "L1" | "L2" | "L3"; href: string; icon: LucideIcon; label: string }[] = [
+ { key: "L1", href: "/memory/l1", icon: Layers, label: t("L1") },
+ { key: "L2", href: "/memory/l2", icon: Workflow, label: t("L2") },
+ { key: "L3", href: "/memory/l3", icon: Network, label: t("L3") },
+ ];
+ return (
+ <nav className="flex items-center gap-0.5 rounded-full border border-[var(--border)] bg-[var(--card)] p-0.5">
+ {entries.map(({ key, href, icon: Icon, label }) => {
+ const active = key === "L1";
+ if (active) {
+ return (
+ <span
+ key={key}
+ className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)] px-2.5 py-0.5 text-[11.5px] font-medium text-[var(--foreground)]"
+ >
+ <Icon className="h-3 w-3" />
+ {label}
+ </span>
+ );
+ }
+ return (
+ <Link
+ key={key}
+ href={href}
+ className="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[11.5px] text-[var(--muted-foreground)] transition hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ >
+ <Icon className="h-3 w-3" />
+ {label}
+ </Link>
+ );
+ })}
+ </nav>
+ );
+}
+
+function Breadcrumb({
+ label,
+ t,
+}: {
+ label: string;
+ t: (k: string) => string;
+}) {
+ return (
+ <div className="flex items-center gap-2 text-[12.5px]">
+ <Link
+ href="/memory"
+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ {t("Memory")}
+ </Link>
+ <span className="text-[var(--muted-foreground)]">/</span>
+ <span className="inline-flex items-center gap-1.5 text-[var(--foreground)]">
+ <Layers className="h-3.5 w-3.5" />
+ {t("L1 · Workspace mirror")}
+ </span>
+ <span className="text-[var(--muted-foreground)]">/</span>
+ <span className="text-[var(--foreground)]">{label}</span>
+ </div>
+ );
+}
diff --git a/web/components/memory/MemoryRunPanel.tsx b/web/components/memory/MemoryRunPanel.tsx
new file mode 100644
index 000000000..d60e15f7a
--- /dev/null
+++ b/web/components/memory/MemoryRunPanel.tsx
@@ -0,0 +1,857 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ AlertCircle,
+ Bot,
+ CheckCircle2,
+ ChevronDown,
+ ChevronRight,
+ CircleSlash,
+ GitBranch,
+ Loader2,
+ Octagon,
+ PlayCircle,
+ RotateCcw,
+ ScanSearch,
+ Send,
+ Sparkles,
+ Trash2,
+ Undo2,
+ type LucideIcon,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import {
+ listLLMOptions,
+ llmSelectionKey,
+ sameLLMSelection,
+ type LLMOption,
+} from "@/lib/llm-options";
+import type { LLMSelection } from "@/lib/unified-ws";
+import { apiFetch, apiUrl } from "@/lib/api";
+import {
+ useMemoryRun,
+ type RunEvent,
+ type RunMode,
+} from "@/components/memory/useMemoryRun";
+
+interface MemoryRunPanelProps {
+ layer: "L2" | "L3";
+ docKey: string;
+ onRunComplete?: () => void;
+ onDocUpdated?: () => void;
+}
+
+interface MemorySettingsDTO {
+ update: { l2_budget: number; l3_budget: number };
+ audit: { l2_budget: number; l3_budget: number };
+ dedup: { iterations: number; auto_after_update: boolean };
+}
+
+const MODE_META: { key: RunMode; icon: LucideIcon; tKey: string }[] = [
+ { key: "update", icon: Sparkles, tKey: "Update memory" },
+ { key: "audit", icon: ScanSearch, tKey: "Audit memory" },
+ { key: "dedup", icon: GitBranch, tKey: "Dedup" },
+];
+
+export default function MemoryRunPanel({
+ layer,
+ docKey,
+ onRunComplete,
+ onDocUpdated,
+}: MemoryRunPanelProps) {
+ const { t, i18n } = useTranslation();
+ const { run, events, status, error, isRunning, start, cancel, undo, clear } =
+ useMemoryRun(layer, docKey);
+
+ const [mode, setMode] = useState<RunMode>("update");
+ // Per-mode overrides keep typed values stable while the user flips between
+ // modes — each mode has its own input value, defaulting to the settings
+ // value when no override exists. Avoids setState-in-effect entirely.
+ const [overrides, setOverrides] = useState<Record<RunMode, number | null>>({
+ update: null,
+ audit: null,
+ dedup: null,
+ });
+ const budgetOverride = mode === "dedup" ? null : overrides[mode];
+ const iterationsOverride = mode === "dedup" ? overrides.dedup : null;
+ const setBudgetOverride = useCallback(
+ (v: number | null) =>
+ setOverrides((prev) => ({ ...prev, [mode]: v })),
+ [mode],
+ );
+ const setIterationsOverride = useCallback(
+ (v: number | null) =>
+ setOverrides((prev) => ({ ...prev, dedup: v })),
+ [],
+ );
+ const [selection, setSelection] = useState<LLMSelection | null>(null);
+ const [activeDefault, setActiveDefault] = useState<LLMSelection | null>(null);
+ const [modelOptions, setModelOptions] = useState<LLMOption[]>([]);
+ const [modelLoading, setModelLoading] = useState(true);
+ const [modelError, setModelError] = useState(false);
+ const [settings, setSettings] = useState<MemorySettingsDTO | null>(null);
+
+ // Load LLM options + memory settings once.
+ useEffect(() => {
+ setModelLoading(true);
+ void (async () => {
+ try {
+ const data = await listLLMOptions();
+ setModelOptions(data.options);
+ setActiveDefault(data.active);
+ setModelError(false);
+ } catch {
+ setModelOptions([]);
+ setModelError(true);
+ } finally {
+ setModelLoading(false);
+ }
+ })();
+ void (async () => {
+ const res = await apiFetch(apiUrl("/api/v1/memory/settings"));
+ const data = (await res.json()) as MemorySettingsDTO;
+ setSettings(data);
+ })();
+ }, []);
+
+ const defaultBudget = useMemo(() => {
+ if (!settings) return null;
+ if (mode === "update") {
+ return layer === "L2" ? settings.update.l2_budget : settings.update.l3_budget;
+ }
+ if (mode === "audit") {
+ return layer === "L2" ? settings.audit.l2_budget : settings.audit.l3_budget;
+ }
+ return null;
+ }, [settings, mode, layer]);
+ const defaultIterations = settings?.dedup.iterations ?? null;
+ const budget = budgetOverride ?? defaultBudget ?? ("" as const);
+ const iterations = iterationsOverride ?? defaultIterations ?? ("" as const);
+
+
+ const effectiveSelection = useMemo(
+ () => selection ?? activeDefault ?? null,
+ [selection, activeDefault],
+ );
+ const handleRun = useCallback(() => {
+ if (isRunning) return;
+ const llmSelection = effectiveSelection
+ ? {
+ profile_id: effectiveSelection.profile_id,
+ model_id: effectiveSelection.model_id,
+ }
+ : null;
+ if (mode === "dedup") {
+ void start({
+ mode,
+ iterations: typeof iterations === "number" ? iterations : undefined,
+ llmSelection,
+ language: i18n.language || "en",
+ });
+ } else {
+ void start({
+ mode,
+ budget: typeof budget === "number" ? budget : undefined,
+ llmSelection,
+ language: i18n.language || "en",
+ });
+ }
+ }, [isRunning, mode, iterations, budget, effectiveSelection, i18n.language, start]);
+
+ // Notify parent when a run finishes (success or otherwise) so the doc
+ // preview can refresh.
+ const lastCompleted = useRef<string | null>(null);
+ useEffect(() => {
+ if (!run || isRunning) return;
+ if (
+ run.status === "done" ||
+ run.status === "cancelled" ||
+ run.status === "error"
+ ) {
+ if (lastCompleted.current !== run.id) {
+ lastCompleted.current = run.id;
+ onRunComplete?.();
+ }
+ }
+ }, [run, isRunning, onRunComplete]);
+
+ const lastDocEvent = useRef<number | null>(null);
+ useEffect(() => {
+ if (!onDocUpdated) return;
+ const latest = [...events]
+ .reverse()
+ .find(
+ (ev) =>
+ ev.payload.stage === "doc_updated" || ev.payload.stage === "undo_applied",
+ );
+ if (!latest || lastDocEvent.current === latest.seq) return;
+ lastDocEvent.current = latest.seq;
+ onDocUpdated();
+ }, [events, onDocUpdated]);
+
+ const undoDepth = useMemo(() => {
+ let depth = run?.undo_count ?? 0;
+ for (const ev of events) {
+ const value = ev.payload.undo_depth;
+ if (
+ (ev.payload.stage === "doc_updated" || ev.payload.stage === "undo_applied") &&
+ typeof value === "number"
+ ) {
+ depth = value;
+ }
+ }
+ return depth;
+ }, [events, run?.undo_count]);
+
+ const handleUndo = useCallback(() => {
+ if (isRunning || undoDepth <= 0) return;
+ void undo();
+ }, [isRunning, undo, undoDepth]);
+
+ const handleReset = useCallback(async () => {
+ if (isRunning) return;
+ const ok =
+ typeof window !== "undefined" &&
+ window.confirm(
+ t(
+ "Reset will delete the current memory file AND its seen-id state. The next Update will re-ingest every L1 entity from scratch. Continue?",
+ ),
+ );
+ if (!ok) return;
+ try {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/memory/doc/${layer}/${encodeURIComponent(docKey)}/reset`),
+ { method: "POST" },
+ );
+ if (!res.ok) {
+ const detail = await res.text();
+ throw new Error(
+ detail || t("reset failed: {{status}}", { status: res.status }),
+ );
+ }
+ // Clear local run trace + tell the parent workbench to re-fetch the
+ // (now empty) doc, line view, and overview badge.
+ clear();
+ onDocUpdated?.();
+ } catch (e) {
+ if (typeof window !== "undefined") {
+ window.alert(
+ t("Reset failed: {{msg}}", {
+ msg: e instanceof Error ? e.message : t("unknown error"),
+ }),
+ );
+ }
+ }
+ }, [isRunning, t, layer, docKey, clear, onDocUpdated]);
+
+ const turns = useMemo(() => groupByTurn(events), [events]);
+
+ return (
+ <div className="flex h-full min-h-0 flex-col rounded-2xl border border-[var(--border)] bg-[var(--card)]">
+ {/* Header */}
+ <header className="flex items-center justify-between gap-2 border-b border-[var(--border)] px-3 py-2">
+ <div className="flex items-center gap-1.5 text-[12.5px] font-semibold text-[var(--foreground)]">
+ <Bot className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
+ {t("LLM workspace")}
+ </div>
+ <div className="flex items-center gap-1">
+ {run && events.length > 0 && (
+ <>
+ <button
+ type="button"
+ onClick={handleUndo}
+ disabled={isRunning || undoDepth <= 0}
+ className="inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px] text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-40"
+ title={t("Undo last memory edit")}
+ >
+ <Undo2 className="h-3 w-3" />
+ {undoDepth > 0 && <span>{undoDepth}</span>}
+ </button>
+ <button
+ type="button"
+ onClick={clear}
+ disabled={isRunning}
+ className="inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px] text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-40"
+ title={t("Clear trace")}
+ >
+ <Trash2 className="h-3 w-3" />
+ </button>
+ </>
+ )}
+ <button
+ type="button"
+ onClick={() => void handleReset()}
+ disabled={isRunning}
+ className="inline-flex items-center gap-1 rounded-md border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-700 hover:bg-amber-500/20 hover:text-amber-800 disabled:opacity-40 dark:text-amber-300 dark:hover:text-amber-200"
+ title={t("Reset memory (delete md + seen-id state)")}
+ >
+ <RotateCcw className="h-3 w-3" />
+ <span>{t("Reset")}</span>
+ </button>
+ </div>
+ </header>
+
+ {/* Composer — two evenly-distributed rows pinned at the top */}
+ <div className="space-y-2 border-b border-[var(--border)] bg-[var(--background)]/40 px-3 py-2.5">
+ <div className="grid grid-cols-3 gap-1.5">
+ {MODE_META.map(({ key, icon: Icon, tKey }) => (
+ <button
+ key={key}
+ type="button"
+ disabled={isRunning}
+ onClick={() => setMode(key)}
+ className={
+ "inline-flex min-w-0 items-center justify-center gap-1 rounded-full border border-[var(--border)] px-2 py-1 text-[11.5px] transition disabled:opacity-50 " +
+ (mode === key
+ ? "bg-[var(--muted)] text-[var(--foreground)]"
+ : "bg-[var(--background)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]")
+ }
+ >
+ <Icon className="h-3 w-3 shrink-0" />
+ <span className="truncate">{t(tKey)}</span>
+ </button>
+ ))}
+ </div>
+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] items-center gap-1.5">
+ {mode === "dedup" ? (
+ <NumberInput
+ value={iterations}
+ setValue={(v) => setIterationsOverride(v === "" ? null : v)}
+ label={t("Iter")}
+ min={1}
+ max={20}
+ disabled={isRunning}
+ fullWidth
+ />
+ ) : (
+ <NumberInput
+ value={budget}
+ setValue={(v) => setBudgetOverride(v === "" ? null : v)}
+ label={t("Budget")}
+ min={1}
+ max={200}
+ disabled={isRunning}
+ fullWidth
+ />
+ )}
+ <ModelPill
+ options={modelOptions}
+ value={selection ?? activeDefault}
+ loading={modelLoading}
+ error={modelError}
+ disabled={isRunning}
+ onChange={(next) => setSelection(next)}
+ t={t}
+ />
+ {isRunning ? (
+ <button
+ type="button"
+ onClick={() => void cancel()}
+ className="inline-flex h-7 w-9 items-center justify-center rounded-full bg-[var(--muted)] text-[var(--foreground)] transition hover:opacity-90"
+ title={t("Cancel")}
+ >
+ <Octagon className="h-3.5 w-3.5" />
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={handleRun}
+ className="inline-flex h-7 w-9 items-center justify-center rounded-full bg-[var(--primary)] text-[var(--primary-foreground)] transition hover:opacity-90"
+ title={t("Run")}
+ >
+ <Send className="h-3.5 w-3.5" />
+ </button>
+ )}
+ </div>
+ </div>
+
+ {/* Stream */}
+ <div className="min-h-0 flex-1 overflow-y-auto px-3 py-3">
+ {events.length === 0 && status === "idle" ? (
+ <EmptyTrace t={t} />
+ ) : (
+ <ol className="space-y-2">
+ {turns.map((turn) => (
+ <TurnCard key={`${turn.kind}-${turn.id}`} turn={turn} t={t} />
+ ))}
+ {isRunning && (
+ <li className="flex items-center gap-2 rounded-md bg-[var(--muted)]/40 px-2.5 py-1.5 text-[11.5px] text-[var(--muted-foreground)]">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ {t("Working…")}
+ </li>
+ )}
+ {error && (
+ <li className="flex items-start gap-2 rounded-md border border-red-500/30 bg-red-500/5 px-2.5 py-1.5 text-[11.5px] text-red-500">
+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ {error}
+ </li>
+ )}
+ </ol>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// ── Trace pieces ─────────────────────────────────────────────────────
+
+type Turn =
+ | { kind: "system"; id: string; ts: string; payload: RunEvent["payload"] }
+ | { kind: "llm"; id: string; ts: string; turn: number; chunkIndex: number | null; system_prompt: string; user_prompt: string; response: string; error: string | null; label: string | null };
+
+function groupByTurn(events: RunEvent[]): Turn[] {
+ const out: Turn[] = [];
+ const pending: Record<string, Turn & { kind: "llm" }> = {};
+ for (const ev of events) {
+ const p = ev.payload as Record<string, unknown>;
+ const stage = String(p.stage || "");
+ if (stage === "llm_io_start") {
+ const turn = typeof p.turn === "number" ? p.turn : 0;
+ const chunkIndex = typeof p.chunk_index === "number" ? (p.chunk_index as number) : null;
+ const key = `${turn}:${chunkIndex}:${ev.seq}`;
+ const card: Turn & { kind: "llm" } = {
+ kind: "llm",
+ id: key,
+ ts: ev.ts,
+ turn,
+ chunkIndex,
+ system_prompt: String(p.system_prompt || ""),
+ user_prompt: String(p.user_prompt || ""),
+ response: "",
+ error: null,
+ label: typeof p.label === "string" ? p.label : null,
+ };
+ pending[`${turn}:${chunkIndex}`] = card;
+ out.push(card);
+ continue;
+ }
+ if (stage === "llm_io_end") {
+ const turn = typeof p.turn === "number" ? p.turn : 0;
+ const chunkIndex = typeof p.chunk_index === "number" ? (p.chunk_index as number) : null;
+ const card = pending[`${turn}:${chunkIndex}`];
+ if (card) {
+ card.response = String(p.response || "");
+ card.error = typeof p.error === "string" ? p.error : null;
+ delete pending[`${turn}:${chunkIndex}`];
+ }
+ continue;
+ }
+ if (stage === "llm_io_delta") {
+ const turn = typeof p.turn === "number" ? p.turn : 0;
+ const chunkIndex = typeof p.chunk_index === "number" ? (p.chunk_index as number) : null;
+ const card = pending[`${turn}:${chunkIndex}`];
+ if (card) {
+ card.response += String(p.delta || "");
+ }
+ continue;
+ }
+ out.push({
+ kind: "system",
+ id: `sys-${ev.seq}`,
+ ts: ev.ts,
+ payload: ev.payload,
+ });
+ }
+ return out;
+}
+
+function TurnCard({ turn, t }: { turn: Turn; t: (k: string) => string }) {
+ if (turn.kind === "system") {
+ return <SystemEventRow event={turn.payload} t={t} />;
+ }
+ return <LLMTurnCard turn={turn} t={t} />;
+}
+
+function SystemEventRow({
+ event,
+ t,
+}: {
+ event: RunEvent["payload"];
+ t: (k: string) => string;
+}) {
+ const stage = String(event.stage || "");
+ const display = systemEventDisplay(stage, event, t);
+ if (!display) return null;
+ return (
+ <li
+ className={
+ "flex items-start gap-2 rounded-md px-2 py-1.5 text-[11.5px] " +
+ (display.tone === "ok"
+ ? "border border-emerald-500/30 bg-emerald-500/5 text-emerald-700 dark:text-emerald-300"
+ : display.tone === "warn"
+ ? "border border-amber-500/30 bg-amber-500/5 text-amber-700 dark:text-amber-300"
+ : "bg-[var(--muted)]/40 text-[var(--muted-foreground)]")
+ }
+ >
+ <display.icon className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ <div className="min-w-0">
+ <div className="font-mono text-[10.5px] uppercase tracking-wide">
+ {display.title}
+ </div>
+ {display.detail && (
+ <div className="mt-0.5 break-words leading-snug">{display.detail}</div>
+ )}
+ </div>
+ </li>
+ );
+}
+
+function systemEventDisplay(
+ stage: string,
+ event: RunEvent["payload"],
+ t: (k: string) => string,
+):
+ | { icon: LucideIcon; title: string; detail: string; tone: "ok" | "warn" | "muted" }
+ | null {
+ const num = (k: string) =>
+ typeof event[k] === "number" ? String(event[k]) : null;
+ const str = (k: string) =>
+ typeof event[k] === "string" ? String(event[k]) : null;
+ switch (stage) {
+ case "run_started":
+ return { icon: PlayCircle, title: t("Run started"), detail: `${event.mode}`, tone: "muted" };
+ case "trace_loaded": {
+ const total = num("total") ?? num("total_l2_entries");
+ const fresh = num("new") ?? num("new_l2_entries");
+ const parts = [
+ total ? `total=${total}` : null,
+ fresh ? `new=${fresh}` : null,
+ ].filter(Boolean);
+ return { icon: PlayCircle, title: t("Traces loaded"), detail: parts.join(" · "), tone: "muted" };
+ }
+ case "chunked":
+ return {
+ icon: PlayCircle,
+ title: t("Chunked"),
+ detail: [
+ num("chunks") ? `chunks=${num("chunks")}` : null,
+ num("budget") ? `budget=${num("budget")}` : null,
+ num("chars") ? `chars=${num("chars")}` : null,
+ ].filter(Boolean).join(" · "),
+ tone: "muted",
+ };
+ case "progress": {
+ const turn = num("turn");
+ const total = num("total");
+ return { icon: PlayCircle, title: t("Progress"), detail: turn && total ? `${turn}/${total}` : "", tone: "muted" };
+ }
+ case "facts_extracted":
+ return {
+ icon: CheckCircle2,
+ title: t("Facts extracted"),
+ detail: [
+ num("kept") ? `kept=${num("kept")}` : null,
+ num("added") ? `added=${num("added")}` : null,
+ ].filter(Boolean).join(" · "),
+ tone: "ok",
+ };
+ case "refs_dropped":
+ return {
+ icon: CircleSlash,
+ title: t("Ref dropped"),
+ detail: `${str("reason") || "?"} :: ${str("text") || ""}`,
+ tone: "warn",
+ };
+ case "op_applied":
+ return {
+ icon: CheckCircle2,
+ title: t("Edit applied"),
+ detail: [str("op"), str("detail")].filter(Boolean).join(" · "),
+ tone: "ok",
+ };
+ case "op_rejected":
+ return {
+ icon: CircleSlash,
+ title: t("Edit rejected"),
+ detail: [str("op"), str("detail")].filter(Boolean).join(" · "),
+ tone: "warn",
+ };
+ case "doc_updated":
+ return {
+ icon: CheckCircle2,
+ title: t("Markdown updated"),
+ detail: [
+ str("action"),
+ num("turn") ? `turn=${num("turn")}` : null,
+ num("undo_depth") ? `undo=${num("undo_depth")}` : null,
+ ].filter(Boolean).join(" · "),
+ tone: "ok",
+ };
+ case "undo_applied":
+ return {
+ icon: Undo2,
+ title: t("Undo applied"),
+ detail: [
+ str("action"),
+ num("undo_depth") ? `remaining=${num("undo_depth")}` : "remaining=0",
+ ].filter(Boolean).join(" · "),
+ tone: "warn",
+ };
+ case "done":
+ return {
+ icon: CheckCircle2,
+ title: t("Done"),
+ detail: [
+ num("facts_added") ? `+${num("facts_added")} facts` : null,
+ num("edits_applied") ? `+${num("edits_applied")} edits` : null,
+ num("refs_dropped") ? `dropped=${num("refs_dropped")}` : null,
+ ].filter(Boolean).join(" · "),
+ tone: "ok",
+ };
+ case "run_ended":
+ return {
+ icon: CheckCircle2,
+ title: t("Run ended"),
+ detail: str("status") || "",
+ tone: "muted",
+ };
+ case "cancelled":
+ return { icon: CircleSlash, title: t("Cancelled"), detail: "", tone: "warn" };
+ case "error":
+ return { icon: AlertCircle, title: t("Error"), detail: str("message") || "", tone: "warn" };
+ default:
+ return null;
+ }
+}
+
+function LLMTurnCard({
+ turn,
+ t,
+}: {
+ turn: Extract<Turn, { kind: "llm" }>;
+ t: (k: string) => string;
+}) {
+ const [systemOpen, setSystemOpen] = useState(false);
+ const [userOpen, setUserOpen] = useState(false);
+ const tag = turn.chunkIndex !== null ? `t${turn.turn} · chunk ${turn.chunkIndex + 1}` : `t${turn.turn}`;
+ return (
+ <li className="space-y-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-2">
+ <div className="flex items-center gap-2 text-[10.5px] uppercase tracking-wide text-[var(--muted-foreground)]">
+ <Bot className="h-3 w-3" />
+ <span>{turn.label || "llm"}</span>
+ <span>·</span>
+ <span>{tag}</span>
+ </div>
+
+ <Disclosure
+ open={systemOpen}
+ setOpen={setSystemOpen}
+ label={t("System prompt")}
+ body={turn.system_prompt}
+ />
+ <Disclosure
+ open={userOpen}
+ setOpen={setUserOpen}
+ label={t("User prompt")}
+ body={turn.user_prompt}
+ />
+
+ <div className="text-[12px] text-[var(--foreground)]">
+ {turn.response ? (
+ <pre className="whitespace-pre-wrap break-words font-mono text-[11.5px] leading-relaxed">
+ {turn.response}
+ </pre>
+ ) : turn.error ? (
+ <div className="rounded border border-red-500/30 bg-red-500/5 px-2 py-1 text-[11px] text-red-500">
+ {turn.error}
+ </div>
+ ) : (
+ <div className="flex items-center gap-1.5 text-[11.5px] text-[var(--muted-foreground)]">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ {t("Streaming…")}
+ </div>
+ )}
+ </div>
+ </li>
+ );
+}
+
+function Disclosure({
+ open,
+ setOpen,
+ label,
+ body,
+}: {
+ open: boolean;
+ setOpen: (v: boolean) => void;
+ label: string;
+ body: string;
+}) {
+ if (!body) return null;
+ return (
+ <div className="text-[11px] text-[var(--muted-foreground)]">
+ <button
+ type="button"
+ onClick={() => setOpen(!open)}
+ className="inline-flex items-center gap-1 rounded px-1 py-0.5 hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ >
+ {open ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
+ {label}
+ <span className="opacity-60">·&nbsp;{body.length}</span>
+ </button>
+ {open && (
+ <pre className="mt-1 max-h-60 overflow-y-auto whitespace-pre-wrap break-words rounded bg-[var(--muted)]/40 px-2 py-1.5 font-mono text-[10.5px] text-[var(--foreground)]">
+ {body}
+ </pre>
+ )}
+ </div>
+ );
+}
+
+// ── Composer pieces ─────────────────────────────────────────────────
+
+function NumberInput({
+ value,
+ setValue,
+ label,
+ min,
+ max,
+ disabled,
+ fullWidth = false,
+}: {
+ value: number | "";
+ setValue: (n: number | "") => void;
+ label: string;
+ min: number;
+ max: number;
+ disabled: boolean;
+ fullWidth?: boolean;
+}) {
+ return (
+ <label
+ className={
+ "flex items-center justify-between gap-1 rounded-full border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[11.5px] text-[var(--muted-foreground)] " +
+ (fullWidth ? "w-full" : "")
+ }
+ >
+ <span>{label}</span>
+ <input
+ type="number"
+ value={value}
+ min={min}
+ max={max}
+ disabled={disabled}
+ onChange={(e) => {
+ const v = e.target.value;
+ if (v === "") return setValue("");
+ const n = parseInt(v, 10);
+ if (!Number.isNaN(n)) setValue(Math.max(min, Math.min(max, n)));
+ }}
+ className="w-14 bg-transparent text-right text-[11.5px] text-[var(--foreground)] outline-none"
+ />
+ </label>
+ );
+}
+
+interface ModelPillProps {
+ options: LLMOption[];
+ value: LLMSelection | null;
+ loading: boolean;
+ error: boolean;
+ disabled: boolean;
+ onChange: (next: LLMSelection | null) => void;
+ t: (k: string) => string;
+}
+
+function ModelPill({
+ options,
+ value,
+ loading,
+ error,
+ disabled,
+ onChange,
+ t,
+}: ModelPillProps) {
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ const onDown = (e: MouseEvent) => {
+ if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
+ };
+ document.addEventListener("mousedown", onDown);
+ return () => document.removeEventListener("mousedown", onDown);
+ }, [open]);
+
+ const selectedOption = useMemo(
+ () => options.find((o) => sameLLMSelection(o, value)) ?? null,
+ [options, value],
+ );
+ const label = loading
+ ? t("Loading models")
+ : error
+ ? t("Models unavailable")
+ : selectedOption?.model_name || t("Default model");
+ const inactive = disabled || loading || error || options.length === 0;
+
+ return (
+ <div ref={rootRef} className="relative w-full min-w-0">
+ <button
+ type="button"
+ disabled={inactive}
+ onClick={() => setOpen(!open)}
+ title={selectedOption ? `${selectedOption.profile_name} | ${selectedOption.provider}` : label}
+ className={
+ "flex w-full min-w-0 items-center gap-1 rounded-full border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[11.5px] text-[var(--foreground)] transition hover:bg-[var(--muted)]/60 disabled:opacity-50 " +
+ (open ? "border-[var(--primary)]/40" : "")
+ }
+ >
+ <Bot className="h-3 w-3 shrink-0 text-[var(--muted-foreground)]" />
+ <span className="flex-1 truncate text-left">{label}</span>
+ <ChevronDown className="h-3 w-3 shrink-0 text-[var(--muted-foreground)]" />
+ </button>
+
+ {open && !inactive && (
+ <div className="absolute right-0 top-full z-30 mt-1 max-h-72 w-[min(320px,calc(100vw-32px))] overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--card)] p-1 shadow-lg">
+ {options.map((opt) => {
+ const active = sameLLMSelection(opt, value);
+ return (
+ <button
+ key={llmSelectionKey(opt)}
+ type="button"
+ onClick={() => {
+ onChange({ profile_id: opt.profile_id, model_id: opt.model_id });
+ setOpen(false);
+ }}
+ className={
+ "flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-[11.5px] transition hover:bg-[var(--muted)] " +
+ (active
+ ? "bg-[var(--muted)] text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)]")
+ }
+ >
+ <span className="flex min-w-0 flex-1 items-baseline gap-2">
+ <span className="truncate text-[var(--foreground)]">{opt.model_name}</span>
+ <span className="shrink-0 text-[10px] opacity-60">{opt.provider}</span>
+ </span>
+ {opt.is_active_default && (
+ <span className="shrink-0 rounded bg-[var(--primary)]/10 px-1 py-0.5 text-[9.5px] uppercase text-[var(--primary)]">
+ {t("default")}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function EmptyTrace({ t }: { t: (k: string) => string }) {
+ return (
+ <div className="grid h-full place-items-center text-center text-[12.5px] text-[var(--muted-foreground)]">
+ <div className="max-w-xs space-y-1.5">
+ <Bot className="mx-auto h-6 w-6 opacity-60" />
+ <p>
+ {t(
+ "Pick a mode and click Run. The LLM trace — system prompt, user prompt, response — appears here, turn by turn.",
+ )}
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/memory/MemorySection.tsx b/web/components/memory/MemorySection.tsx
new file mode 100644
index 000000000..cba9d8aff
--- /dev/null
+++ b/web/components/memory/MemorySection.tsx
@@ -0,0 +1,1517 @@
+"use client";
+
+import dynamic from "next/dynamic";
+import Link from "next/link";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ Archive,
+ Bot,
+ BookOpen,
+ Brain,
+ ClipboardList,
+ ExternalLink,
+ GitCommit,
+ Library,
+ Loader2,
+ MessageSquare,
+ NotebookPen,
+ Pencil,
+ PenLine,
+ RefreshCw,
+ Save,
+ X,
+ type LucideIcon,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { apiFetch, apiUrl } from "@/lib/api";
+import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";
+
+const MarkdownRenderer = dynamic(
+ () => import("@/components/common/MarkdownRenderer"),
+ { ssr: false },
+);
+
+// ── Types ────────────────────────────────────────────────────────────
+
+type Layer = "L2" | "L3";
+
+type Surface =
+ | "chat"
+ | "notebook"
+ | "quiz"
+ | "kb"
+ | "book"
+ | "tutorbot"
+ | "cowriter";
+
+const SURFACES: readonly Surface[] = [
+ "chat",
+ "notebook",
+ "quiz",
+ "kb",
+ "book",
+ "tutorbot",
+ "cowriter",
+] as const;
+
+type Tab = "L1" | "L2" | "L3";
+
+interface Entity {
+ id: string;
+ label: string;
+ ts: string;
+ content: string;
+ metadata: Record<string, unknown>;
+ fingerprint: string;
+}
+
+interface SnapshotResponse {
+ surface: Surface;
+ entities: Entity[];
+ last_refresh: string | null;
+ pending_changes: ChangeEntryDTO[];
+}
+
+interface ChangeEntryDTO {
+ ts: string;
+ kind: "added" | "modified" | "removed";
+ entity_id: string;
+ label: string;
+ prev_fingerprint: string | null;
+ new_fingerprint: string | null;
+}
+
+interface ChangesResponse {
+ surface: Surface;
+ changes: ChangeEntryDTO[];
+}
+
+interface KbQueryDTO {
+ id: string;
+ ts: string;
+ surface: Surface;
+ kind: string;
+ payload: Record<string, unknown>;
+ session_id: string | null;
+ turn_id: string | null;
+}
+
+interface KbQueriesResponse {
+ surface: Surface;
+ events: KbQueryDTO[];
+}
+
+interface DocOverview {
+ layer: Layer;
+ key: string;
+ exists: boolean;
+ updated_at: string | null;
+ entry_count: number;
+ backlog: number;
+}
+
+interface OverviewResponse {
+ docs: DocOverview[];
+ backups: string[];
+}
+
+interface StreamStage {
+ stage: string;
+ count?: number;
+ delta?: string;
+ ops?: unknown[];
+ report?: { accepted: boolean; reason?: string; results?: unknown[] };
+ message?: string;
+ // Agentic-loop fields (tool_called / tool_observed / step_done / loop_summary)
+ turn?: number;
+ name?: string;
+ args?: Record<string, unknown>;
+ brief?: string;
+ action?: string;
+ turns_used?: number;
+ tools_used?: Record<string, number>;
+ ops_emitted?: number;
+ summary?: string;
+}
+
+// ── Surface metadata + helpers ───────────────────────────────────────
+
+interface SurfaceMeta {
+ icon: LucideIcon;
+ label: string;
+}
+
+const SURFACE_META: Record<Surface, SurfaceMeta> = {
+ chat: { icon: MessageSquare, label: "Chat" },
+ notebook: { icon: NotebookPen, label: "Notebook" },
+ quiz: { icon: ClipboardList, label: "题库" },
+ kb: { icon: BookOpen, label: "Knowledge base" },
+ book: { icon: Library, label: "Book" },
+ tutorbot: { icon: Bot, label: "TutorBot" },
+ cowriter: { icon: PenLine, label: "Co-writer" },
+};
+
+const L3_LABELS: Record<string, string> = {
+ recent: "近期总结",
+ profile: "用户画像",
+ scope: "知识 Scope",
+ preferences: "偏好",
+};
+
+// Entity refs in L2/L3 docs are written as `<surface>:<entity_id>`.
+// The id portion is intentionally permissive (notebook record_id, doc_id,
+// book_id, bot name, session_id, "session:question" composites, kb_name).
+const ENTITY_REF_RE =
+ /\b(chat|notebook|quiz|kb|book|tutorbot|cowriter):[A-Za-z0-9_.\-:]+/g;
+
+function entityAnchorId(ref: string): string {
+ // Anchor IDs can't contain ':' cleanly across CSS selectors — flatten
+ // it. We never round-trip from anchor back to ref, so the encoding
+ // can be lossy.
+ return `entity-${ref.replace(/:/g, "__")}`;
+}
+
+function parseEntityAnchor(anchor: string): {
+ surface: Surface;
+ ref: string;
+} | null {
+ if (!anchor.startsWith("entity-")) return null;
+ const body = anchor.slice("entity-".length);
+ const sep = body.indexOf("__");
+ if (sep <= 0) return null;
+ const surface = body.slice(0, sep);
+ const rest = body.slice(sep + 2).replace(/__/g, ":");
+ if (!(SURFACES as readonly string[]).includes(surface)) return null;
+ return { surface: surface as Surface, ref: `${surface}:${rest}` };
+}
+
+function linkifyEntityRefs(content: string): string {
+ return content.replace(
+ ENTITY_REF_RE,
+ (ref) => `[${ref}](#${entityAnchorId(ref)})`,
+ );
+}
+
+function labelFor(doc: DocOverview): string {
+ if (doc.layer === "L2")
+ return SURFACE_META[doc.key as Surface]?.label ?? doc.key;
+ return L3_LABELS[doc.key] ?? doc.key;
+}
+
+function formatTimestamp(value: string | null, fallback: string): string {
+ if (!value) return fallback;
+ const d = new Date(value);
+ if (Number.isNaN(d.getTime())) return value;
+ return d.toLocaleString();
+}
+
+function shorten(s: string, n: number): string {
+ const trimmed = (s || "").replace(/\s+/g, " ").trim();
+ return trimmed.length > n ? trimmed.slice(0, n - 1) + "…" : trimmed;
+}
+
+function asString(v: unknown): string {
+ if (typeof v === "string") return v;
+ if (typeof v === "number") return String(v);
+ return "";
+}
+
+function entityDeepLinkUrl(surface: Surface, ent: Entity): string | null {
+ const m = ent.metadata || {};
+ switch (surface) {
+ case "chat":
+ return `/chat/${encodeURIComponent(ent.id)}`;
+ case "cowriter":
+ return `/co-writer/${encodeURIComponent(ent.id)}`;
+ case "notebook": {
+ const nbId = asString(m.notebook_id);
+ return nbId
+ ? `/space/notebooks?notebook=${encodeURIComponent(nbId)}`
+ : "/space/notebooks";
+ }
+ case "book":
+ return `/book?book=${encodeURIComponent(ent.id)}`;
+ case "tutorbot":
+ return `/agents/${encodeURIComponent(ent.id)}/chat`;
+ case "quiz": {
+ // Quiz entity.id is `session:question`. Deep-link to the session.
+ const sessionId = asString(m.session_id) || ent.id.split(":")[0];
+ return sessionId
+ ? `/?session=${encodeURIComponent(sessionId)}`
+ : "/space/questions";
+ }
+ case "kb":
+ return `/knowledge?kb=${encodeURIComponent(ent.id)}`;
+ }
+ return null;
+}
+
+// ── Main component ──────────────────────────────────────────────────
+
+interface MemorySectionProps {
+ forcedTab?: Tab; // when provided, hides the TabStrip and locks the active tab
+ hideHeader?: boolean; // when true, skips the SpaceSectionHeader (parent page renders its own)
+}
+
+export default function MemorySection({
+ forcedTab,
+ hideHeader = false,
+}: MemorySectionProps = {}) {
+ const { t, i18n } = useTranslation();
+ const [tab, setTab] = useState<Tab>(forcedTab ?? "L2");
+ const [overview, setOverview] = useState<OverviewResponse | null>(null);
+ const [selected, setSelected] = useState<{
+ layer: Layer;
+ key: string;
+ } | null>(null);
+ const [content, setContent] = useState("");
+ const [editing, setEditing] = useState(false);
+ const [editorValue, setEditorValue] = useState("");
+ const [stream, setStream] = useState<StreamStage[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [busy, setBusy] = useState(false);
+ const [toast, setToast] = useState("");
+ const [l1Surface, setL1Surface] = useState<Surface>("notebook");
+ const [l1FocusRef, setL1FocusRef] = useState<string | null>(null);
+ const [dismissedBackup, setDismissedBackup] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ setDismissedBackup(
+ window.localStorage.getItem("dt:memory:banner-dismissed") || null,
+ );
+ }, []);
+
+ const latestBackup = overview?.backups?.[overview.backups.length - 1] ?? null;
+ const showArchivedBanner = !!latestBackup && latestBackup !== dismissedBackup;
+
+ const dismissArchivedBanner = useCallback(() => {
+ if (!latestBackup) return;
+ if (typeof window !== "undefined") {
+ window.localStorage.setItem("dt:memory:banner-dismissed", latestBackup);
+ }
+ setDismissedBackup(latestBackup);
+ }, [latestBackup]);
+
+ const loadOverview = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await apiFetch(apiUrl("/api/v1/memory/overview"));
+ const data = (await res.json()) as OverviewResponse;
+ setOverview(data);
+ } catch (e) {
+ setToast(e instanceof Error ? e.message : "Failed to load overview");
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void loadOverview();
+ }, [loadOverview]);
+
+ useEffect(() => {
+ if (!toast) return;
+ const id = setTimeout(() => setToast(""), 3500);
+ return () => clearTimeout(id);
+ }, [toast]);
+
+ const loadDoc = useCallback(async (layer: Layer, key: string) => {
+ setSelected({ layer, key });
+ setEditing(false);
+ setStream([]);
+ try {
+ const res = await apiFetch(apiUrl(`/api/v1/memory/doc/${layer}/${key}`));
+ const data = await res.json();
+ const md = String(data?.content || "");
+ setContent(md);
+ setEditorValue(md);
+ } catch (e) {
+ setToast(e instanceof Error ? e.message : "Failed to load document");
+ }
+ }, []);
+
+ const saveDoc = useCallback(async () => {
+ if (!selected) return;
+ setBusy(true);
+ try {
+ await apiFetch(
+ apiUrl(`/api/v1/memory/doc/${selected.layer}/${selected.key}`),
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ content: editorValue }),
+ },
+ );
+ setContent(editorValue);
+ setEditing(false);
+ setToast(t("Saved"));
+ void loadOverview();
+ } catch (e) {
+ setToast(e instanceof Error ? e.message : "Failed to save");
+ } finally {
+ setBusy(false);
+ }
+ }, [editorValue, loadOverview, selected, t]);
+
+ const runUpdate = useCallback(async () => {
+ if (!selected) return;
+ if (selected.layer === "L3" && selected.key === "preferences") {
+ setToast(
+ t("Preferences is written by the chat assistant, not consolidated."),
+ );
+ return;
+ }
+ setBusy(true);
+ setStream([]);
+ try {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/memory/doc/${selected.layer}/${selected.key}/update`),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ language: i18n.language || "en" }),
+ },
+ );
+ const reader = res.body?.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ while (reader) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ let nl = buffer.indexOf("\n\n");
+ while (nl !== -1) {
+ const chunk = buffer.slice(0, nl);
+ buffer = buffer.slice(nl + 2);
+ const line = chunk
+ .split("\n")
+ .find((l) => l.startsWith("data:"))
+ ?.replace(/^data:\s?/, "");
+ if (line) {
+ try {
+ const evt = JSON.parse(line) as StreamStage;
+ setStream((prev) => [...prev, evt]);
+ } catch {
+ // ignore malformed chunk
+ }
+ }
+ nl = buffer.indexOf("\n\n");
+ }
+ }
+ void loadDoc(selected.layer, selected.key);
+ void loadOverview();
+ } catch (e) {
+ setToast(e instanceof Error ? e.message : "Update failed");
+ } finally {
+ setBusy(false);
+ }
+ }, [i18n.language, loadDoc, loadOverview, selected, t]);
+
+ // Clicking a `<surface>:<entity_id>` ref inside an L2/L3 doc opens
+ // the L1 tab focused on that entity.
+ const handleEntityLinkClick = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ const link = (e.target as HTMLElement | null)?.closest("a");
+ if (!link) return;
+ const href = link.getAttribute("href") || "";
+ if (!href.startsWith("#entity-")) return;
+ const parsed = parseEntityAnchor(href.slice(1));
+ if (!parsed) return;
+ setTab("L1");
+ setL1Surface(parsed.surface);
+ setL1FocusRef(parsed.ref);
+ },
+ [],
+ );
+
+ const l2Rows = useMemo(
+ () => (overview?.docs || []).filter((d) => d.layer === "L2"),
+ [overview],
+ );
+ const l3Rows = useMemo(
+ () => (overview?.docs || []).filter((d) => d.layer === "L3"),
+ [overview],
+ );
+
+ return (
+ <div className="space-y-6">
+ {!hideHeader && (
+ <SpaceSectionHeader
+ icon={Brain}
+ title={t("Memory")}
+ description={t(
+ "L1 mirrors your workspace, L2 summarises per-surface content, L3 is cross-surface knowledge.",
+ )}
+ meta={
+ toast ? (
+ <span className="rounded-full border border-[var(--primary)]/30 bg-[var(--primary)]/10 px-2 py-0.5 text-[10.5px] font-medium text-[var(--primary)]">
+ {toast}
+ </span>
+ ) : null
+ }
+ />
+ )}
+
+ {!forcedTab && showArchivedBanner && latestBackup && (
+ <div className="relative flex items-start gap-2 rounded-xl border border-[var(--border)] bg-[var(--muted)] px-4 py-3 pr-10 text-[13px]">
+ <Archive className="mt-0.5 h-4 w-4 shrink-0 text-[var(--muted-foreground)]" />
+ <div>
+ <p className="font-medium text-[var(--foreground)]">
+ {t("Your v1 memory was archived")}
+ </p>
+ <p className="mt-0.5 text-[var(--muted-foreground)]">
+ {t(
+ "Stored at memory/backup/{{name}}. v2 starts fresh — interact with DeepTutor and click Update on each doc to build memory.",
+ { name: latestBackup },
+ )}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={dismissArchivedBanner}
+ aria-label={t("Dismiss")}
+ className="absolute right-2 top-2 rounded-md p-1.5 text-[var(--muted-foreground)] transition hover:bg-[var(--background)] hover:text-[var(--foreground)]"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ )}
+
+ {!forcedTab && (
+ <TabStrip
+ tab={tab}
+ onChange={setTab}
+ l2Count={l2Rows.length}
+ l3Count={l3Rows.length}
+ t={t}
+ />
+ )}
+
+ {tab === "L1" && (
+ <L1View
+ surface={l1Surface}
+ onSurfaceChange={(s) => {
+ setL1Surface(s);
+ setL1FocusRef(null);
+ }}
+ focusRef={l1FocusRef}
+ onClearFocus={() => setL1FocusRef(null)}
+ onToast={setToast}
+ t={t}
+ />
+ )}
+
+ {tab !== "L1" && (
+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-[280px,1fr]">
+ <div className="space-y-4">
+ <DocList
+ title={t(
+ tab === "L2" ? "L2 · Per-surface" : "L3 · Cross-surface",
+ )}
+ rows={tab === "L2" ? l2Rows : l3Rows}
+ selected={selected}
+ onSelect={loadDoc}
+ />
+ </div>
+
+ <div className="space-y-4">
+ {loading ? (
+ <div className="flex min-h-[300px] items-center justify-center">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ ) : !selected || selected.layer !== tab ? (
+ <div className="flex min-h-[300px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
+ <Brain className="mb-3 h-5 w-5 text-[var(--muted-foreground)]" />
+ <p className="text-[14px] text-[var(--foreground)]">
+ {t("Pick a document to view or update")}
+ </p>
+ </div>
+ ) : (
+ <DocPane
+ selected={selected}
+ content={content}
+ editing={editing}
+ editorValue={editorValue}
+ busy={busy}
+ onEditValue={setEditorValue}
+ onEditToggle={() => {
+ setEditing((v) => !v);
+ setEditorValue(content);
+ }}
+ onSave={saveDoc}
+ onUpdate={runUpdate}
+ onEntityLinkClick={handleEntityLinkClick}
+ t={t}
+ />
+ )}
+
+ {stream.length > 0 && (
+ <StreamPanel
+ stages={stream}
+ onDismiss={() => setStream([])}
+ t={t}
+ />
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+// ── TabStrip ────────────────────────────────────────────────────────
+
+interface TabStripProps {
+ tab: Tab;
+ onChange: (tab: Tab) => void;
+ l2Count: number;
+ l3Count: number;
+ t: (key: string, opts?: Record<string, unknown>) => string;
+}
+
+function TabStrip({ tab, onChange, l2Count, l3Count, t }: TabStripProps) {
+ const tabs: Array<{ key: Tab; label: string; count?: number; hint: string }> =
+ [
+ {
+ key: "L1",
+ label: t("L1 · Workspace"),
+ hint: t(
+ "Live snapshot of your workspace — one entry per real artifact.",
+ ),
+ },
+ {
+ key: "L2",
+ label: t("L2 · Per-surface"),
+ count: l2Count,
+ hint: t("Per-surface summaries consolidated from L1 content."),
+ },
+ {
+ key: "L3",
+ label: t("L3 · Cross-surface"),
+ count: l3Count,
+ hint: t("Cross-surface knowledge consolidated from L2."),
+ },
+ ];
+ return (
+ <div className="border-b border-[var(--border)]">
+ <div className="flex gap-1">
+ {tabs.map(({ key, label, count, hint }) => {
+ const active = tab === key;
+ return (
+ <button
+ key={key}
+ onClick={() => onChange(key)}
+ title={hint}
+ className={`relative px-4 py-2 text-[13px] font-medium transition-colors ${
+ active
+ ? "text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {label}
+ {typeof count === "number" && (
+ <span className="ml-2 rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-normal text-[var(--muted-foreground)]">
+ {count}
+ </span>
+ )}
+ {active && (
+ <span
+ aria-hidden
+ className="absolute -bottom-px left-0 right-0 h-[2px] bg-[var(--foreground)]"
+ />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+// ── L1View (snapshot + changes per surface) ─────────────────────────
+
+type L1Mode = "snapshot" | "changes" | "queries";
+
+export interface L1ViewProps {
+ surface: Surface;
+ onSurfaceChange: (s: Surface) => void;
+ focusRef: string | null;
+ onClearFocus: () => void;
+ onToast: (msg: string) => void;
+ t: (key: string, opts?: Record<string, unknown>) => string;
+ // When true, the surface pill bar is hidden — the parent renders its own
+ // surface picker (e.g. a left rail in the workbench layout).
+ compact?: boolean;
+}
+
+export function L1View({
+ surface,
+ onSurfaceChange,
+ focusRef,
+ onClearFocus,
+ onToast,
+ t,
+ compact = false,
+}: L1ViewProps) {
+ const [mode, setMode] = useState<L1Mode>("snapshot");
+ const [snapshot, setSnapshot] = useState<SnapshotResponse | null>(null);
+ const [changes, setChanges] = useState<ChangeEntryDTO[]>([]);
+ const [kbQueries, setKbQueries] = useState<KbQueryDTO[]>([]);
+ const [loadingSnapshot, setLoadingSnapshot] = useState(false);
+ const [loadingChanges, setLoadingChanges] = useState(false);
+ const [loadingQueries, setLoadingQueries] = useState(false);
+ const [refreshing, setRefreshing] = useState(false);
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ // Default mode when switching surfaces:
+ // - kb: prefer "snapshot" but kb-only "queries" mode is accessible.
+ // - others: snapshot.
+ useEffect(() => {
+ if (mode === "queries" && surface !== "kb") {
+ setMode("snapshot");
+ }
+ }, [surface, mode]);
+
+ const loadSnapshot = useCallback(async () => {
+ setLoadingSnapshot(true);
+ try {
+ const res = await apiFetch(apiUrl(`/api/v1/memory/snapshot/${surface}`));
+ const data = (await res.json()) as SnapshotResponse;
+ setSnapshot(data);
+ } catch (e) {
+ onToast(e instanceof Error ? e.message : "Failed to load snapshot");
+ } finally {
+ setLoadingSnapshot(false);
+ }
+ }, [surface, onToast]);
+
+ const loadChanges = useCallback(async () => {
+ setLoadingChanges(true);
+ try {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/memory/snapshot/${surface}/changes`),
+ );
+ const data = (await res.json()) as ChangesResponse;
+ setChanges(data.changes);
+ } catch (e) {
+ onToast(e instanceof Error ? e.message : "Failed to load changes");
+ } finally {
+ setLoadingChanges(false);
+ }
+ }, [surface, onToast]);
+
+ const loadKbQueries = useCallback(async () => {
+ if (surface !== "kb") return;
+ setLoadingQueries(true);
+ try {
+ const res = await apiFetch(apiUrl("/api/v1/memory/trace/kb?limit=200"));
+ const data = (await res.json()) as KbQueriesResponse;
+ setKbQueries(data.events);
+ } catch (e) {
+ onToast(e instanceof Error ? e.message : "Failed to load queries");
+ } finally {
+ setLoadingQueries(false);
+ }
+ }, [surface, onToast]);
+
+ useEffect(() => {
+ setSnapshot(null);
+ setChanges([]);
+ setKbQueries([]);
+ void loadSnapshot();
+ void loadChanges();
+ if (surface === "kb") void loadKbQueries();
+ }, [surface, loadSnapshot, loadChanges, loadKbQueries]);
+
+ // Auto-refetch snapshot when the tab regains focus or becomes visible —
+ // workspace can mutate while the user is in another tab (notebook write,
+ // co-writer edit, etc.) so the snapshot must reflect that without a click.
+ useEffect(() => {
+ const refetch = () => {
+ if (typeof document !== "undefined" && document.hidden) return;
+ void loadSnapshot();
+ };
+ window.addEventListener("focus", refetch);
+ document.addEventListener("visibilitychange", refetch);
+ return () => {
+ window.removeEventListener("focus", refetch);
+ document.removeEventListener("visibilitychange", refetch);
+ };
+ }, [loadSnapshot]);
+
+ // Auto-scroll to focused entity when snapshot finishes loading.
+ useEffect(() => {
+ if (!focusRef || !containerRef.current) return;
+ if (!snapshot) return;
+ const el = containerRef.current.querySelector(
+ `[data-entity-ref="${focusRef}"]`,
+ ) as HTMLElement | null;
+ if (el) {
+ el.scrollIntoView({ block: "center", behavior: "smooth" });
+ }
+ }, [focusRef, snapshot]);
+
+ const pendingByEntity = useMemo(() => {
+ const m = new Map<string, ChangeEntryDTO["kind"]>();
+ for (const c of snapshot?.pending_changes ?? []) {
+ m.set(c.entity_id, c.kind);
+ }
+ return m;
+ }, [snapshot?.pending_changes]);
+ const pendingCount = snapshot?.pending_changes?.length ?? 0;
+
+ const onRefresh = useCallback(async () => {
+ setRefreshing(true);
+ try {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/memory/snapshot/${surface}/refresh`),
+ { method: "POST" },
+ );
+ const data = await res.json();
+ const newChanges: ChangeEntryDTO[] = data?.changes || [];
+ onToast(
+ newChanges.length > 0
+ ? t("Refreshed: {{n}} changes", { n: newChanges.length })
+ : t("Refreshed: no changes"),
+ );
+ await loadSnapshot();
+ await loadChanges();
+ } catch (e) {
+ onToast(e instanceof Error ? e.message : "Refresh failed");
+ } finally {
+ setRefreshing(false);
+ }
+ }, [surface, loadSnapshot, loadChanges, onToast, t]);
+
+ return (
+ <div className="space-y-3" ref={containerRef}>
+ {!compact && (
+ <div className="flex flex-wrap items-center gap-2">
+ {SURFACES.map((s) => {
+ const meta = SURFACE_META[s];
+ return (
+ <SurfacePill
+ key={s}
+ active={surface === s}
+ onClick={() => onSurfaceChange(s)}
+ icon={meta.icon}
+ label={meta.label}
+ />
+ );
+ })}
+ <div className="ml-auto flex items-center gap-2">
+ {pendingCount > 0 && (
+ <span
+ className="inline-flex items-center gap-1 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-700 dark:text-amber-300"
+ title={t(
+ "Workspace changed since last refresh. Click Refresh to commit these to the changes log.",
+ )}
+ >
+ {t("{{n}} pending", { n: pendingCount })}
+ </span>
+ )}
+ <button
+ onClick={() => void onRefresh()}
+ disabled={refreshing}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)] disabled:opacity-50"
+ title={t("Re-scan workspace and record any changes")}
+ >
+ {refreshing ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <RefreshCw className="h-3 w-3" />
+ )}
+ {t("Refresh")}
+ </button>
+ </div>
+ </div>
+ )}
+
+ <div className="flex items-center justify-between gap-2">
+ <ModeStrip mode={mode} setMode={setMode} surface={surface} t={t} />
+ {compact && (
+ <div className="flex items-center gap-2">
+ {pendingCount > 0 && (
+ <span
+ className="inline-flex items-center gap-1 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-700 dark:text-amber-300"
+ title={t(
+ "Workspace changed since last refresh. Click Refresh to commit these to the changes log.",
+ )}
+ >
+ {t("{{n}} pending", { n: pendingCount })}
+ </span>
+ )}
+ <button
+ onClick={() => void onRefresh()}
+ disabled={refreshing}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)] disabled:opacity-50"
+ title={t("Re-scan workspace and record any changes")}
+ >
+ {refreshing ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <RefreshCw className="h-3 w-3" />
+ )}
+ {t("Refresh")}
+ </button>
+ </div>
+ )}
+ </div>
+
+ {mode === "snapshot" && (
+ <SnapshotList
+ surface={surface}
+ loading={loadingSnapshot}
+ snapshot={snapshot}
+ pendingByEntity={pendingByEntity}
+ focusRef={focusRef}
+ onClearFocus={onClearFocus}
+ t={t}
+ />
+ )}
+
+ {mode === "changes" && (
+ <ChangesList
+ loading={loadingChanges}
+ changes={changes}
+ pending={snapshot?.pending_changes ?? []}
+ t={t}
+ />
+ )}
+
+ {mode === "queries" && surface === "kb" && (
+ <KbQueriesList loading={loadingQueries} queries={kbQueries} t={t} />
+ )}
+ </div>
+ );
+}
+
+// ── SurfacePill ─────────────────────────────────────────────────────
+
+interface SurfacePillProps {
+ active: boolean;
+ onClick: () => void;
+ icon: LucideIcon;
+ label: string;
+}
+
+function SurfacePill({ active, onClick, icon: Icon, label }: SurfacePillProps) {
+ return (
+ <button
+ onClick={onClick}
+ className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-[12px] transition-colors ${
+ active
+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/10 text-[var(--primary)]"
+ : "border-[var(--border)] text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50 hover:text-[var(--foreground)]"
+ }`}
+ >
+ <Icon className="h-3 w-3" />
+ <span>{label}</span>
+ </button>
+ );
+}
+
+// ── ModeStrip (snapshot / changes / [kb queries]) ───────────────────
+
+interface ModeStripProps {
+ mode: L1Mode;
+ setMode: (m: L1Mode) => void;
+ surface: Surface;
+ t: (key: string, opts?: Record<string, unknown>) => string;
+}
+
+function ModeStrip({ mode, setMode, surface, t }: ModeStripProps) {
+ const tabs: Array<{ key: L1Mode; label: string; hidden?: boolean }> = [
+ { key: "snapshot", label: t("Snapshot") },
+ { key: "changes", label: t("Changes") },
+ { key: "queries", label: t("Queries"), hidden: surface !== "kb" },
+ ];
+ return (
+ <div className="inline-flex items-center gap-0.5 rounded-md border border-[var(--border)] bg-[var(--card)] p-0.5 text-[12px]">
+ {tabs
+ .filter((x) => !x.hidden)
+ .map(({ key, label }) => {
+ const active = mode === key;
+ return (
+ <button
+ key={key}
+ onClick={() => setMode(key)}
+ className={`rounded px-2.5 py-1 transition-colors ${
+ active
+ ? "bg-[var(--muted)] text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+// ── SnapshotList ─────────────────────────────────────────────────────
+
+interface SnapshotListProps {
+ surface: Surface;
+ loading: boolean;
+ snapshot: SnapshotResponse | null;
+ pendingByEntity: Map<string, ChangeEntryDTO["kind"]>;
+ focusRef: string | null;
+ onClearFocus: () => void;
+ t: (key: string, opts?: Record<string, unknown>) => string;
+}
+
+function SnapshotList({
+ surface,
+ loading,
+ snapshot,
+ pendingByEntity,
+ focusRef,
+ onClearFocus,
+ t,
+}: SnapshotListProps) {
+ const entities = snapshot?.entities ?? [];
+ return (
+ <>
+ <div className="flex items-baseline justify-between text-[11.5px] text-[var(--muted-foreground)]">
+ <span>
+ {t("{{n}} entities", { n: entities.length })}
+ {snapshot?.last_refresh && (
+ <>
+ {" · "}
+ {t("last refresh {{ts}}", {
+ ts: formatTimestamp(snapshot.last_refresh, ""),
+ })}
+ </>
+ )}
+ </span>
+ {focusRef && (
+ <button
+ onClick={onClearFocus}
+ className="text-[var(--primary)] hover:underline"
+ >
+ {t("Clear focus")}
+ </button>
+ )}
+ </div>
+ {loading && entities.length === 0 ? (
+ <div className="flex items-center justify-center rounded-xl border border-[var(--border)] py-12">
+ <Loader2 className="h-4 w-4 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ ) : entities.length === 0 ? (
+ <p className="rounded-xl border border-[var(--border)] px-4 py-10 text-center text-[13px] text-[var(--muted-foreground)]">
+ {t("Nothing in workspace yet.")}
+ </p>
+ ) : (
+ <ol className="rounded-xl border border-[var(--border)]">
+ {entities.map((ent, idx) => (
+ <EntityRow
+ key={`${ent.id}#${idx}`}
+ surface={surface}
+ ent={ent}
+ focused={focusRef === `${surface}:${ent.id}`}
+ pendingKind={pendingByEntity.get(ent.id) ?? null}
+ t={t}
+ />
+ ))}
+ </ol>
+ )}
+ </>
+ );
+}
+
+// ── EntityRow ───────────────────────────────────────────────────────
+
+interface EntityRowProps {
+ surface: Surface;
+ ent: Entity;
+ focused: boolean;
+ pendingKind: ChangeEntryDTO["kind"] | null;
+ t: (key: string, opts?: Record<string, unknown>) => string;
+}
+
+function EntityRow({ surface, ent, focused, pendingKind, t }: EntityRowProps) {
+ const url = entityDeepLinkUrl(surface, ent);
+ const ref = `${surface}:${ent.id}`;
+ const meta = SURFACE_META[surface];
+ const Icon = meta.icon;
+ const preview = shorten(ent.content, 220);
+
+ const inner = (
+ <>
+ <span
+ className={`mt-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded ${
+ focused
+ ? "bg-[var(--primary)]/25 text-[var(--primary)]"
+ : "bg-[var(--muted)] text-[var(--muted-foreground)]"
+ }`}
+ >
+ <Icon className="h-3 w-3" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-baseline gap-x-2 text-[11px] text-[var(--muted-foreground)]">
+ <span className="truncate text-[13px] font-medium text-[var(--foreground)]">
+ {ent.label}
+ </span>
+ <span className="font-mono opacity-70">{ent.id}</span>
+ {ent.ts && <span>{formatTimestamp(ent.ts, "")}</span>}
+ {pendingKind && <PendingBadge kind={pendingKind} t={t} />}
+ </div>
+ {preview && (
+ <p className="mt-1 line-clamp-2 text-[12px] text-[var(--muted-foreground)]/90">
+ {preview}
+ </p>
+ )}
+ </div>
+ {url && (
+ <ExternalLink className="mt-1 h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)] group-hover:text-[var(--primary)]" />
+ )}
+ </>
+ );
+
+ const focusedRing = focused
+ ? "border-l-[3px] border-l-[var(--primary)] bg-[var(--primary)]/12 ring-1 ring-[var(--primary)]/30"
+ : pendingKind === "added"
+ ? "border-l-[3px] border-l-emerald-500 bg-emerald-500/5 hover:bg-emerald-500/10"
+ : pendingKind === "modified"
+ ? "border-l-[3px] border-l-amber-500 bg-amber-500/5 hover:bg-amber-500/10"
+ : "border-l-[3px] border-l-transparent hover:bg-[var(--muted)]/40";
+ const rowClass = `group flex items-start gap-3 border-b border-[var(--border)]/50 px-4 py-2.5 transition-colors last:border-0 ${focusedRing}`;
+
+ return (
+ <li
+ id={entityAnchorId(ref)}
+ data-entity-ref={ref}
+ title={t("Open in {{label}}", { label: meta.label })}
+ >
+ {url ? (
+ <Link href={url} className={rowClass}>
+ {inner}
+ </Link>
+ ) : (
+ <div className={rowClass}>{inner}</div>
+ )}
+ </li>
+ );
+}
+
+// ── PendingBadge (row-level pending marker) ─────────────────────────
+
+function PendingBadge({
+ kind,
+ t,
+}: {
+ kind: ChangeEntryDTO["kind"];
+ t: (key: string, opts?: Record<string, unknown>) => string;
+}) {
+ const map = {
+ added: {
+ label: t("new"),
+ cls: "border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
+ },
+ modified: {
+ label: t("modified"),
+ cls: "border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",
+ },
+ removed: {
+ label: t("removed"),
+ cls: "border-rose-500/40 bg-rose-500/10 text-rose-700 dark:text-rose-300",
+ },
+ } as const;
+ const cfg = map[kind];
+ return (
+ <span
+ className={`inline-flex items-center rounded-full border px-1.5 py-0 text-[10px] font-medium ${cfg.cls}`}
+ title={t("Pending — not yet committed to changes log")}
+ >
+ {cfg.label}
+ </span>
+ );
+}
+
+// ── ChangesList (git-log style) ─────────────────────────────────────
+
+interface ChangesListProps {
+ loading: boolean;
+ changes: ChangeEntryDTO[];
+ pending: ChangeEntryDTO[];
+ t: (key: string, opts?: Record<string, unknown>) => string;
+}
+
+function ChangesList({ loading, changes, pending, t }: ChangesListProps) {
+ if (loading && changes.length === 0 && pending.length === 0) {
+ return (
+ <div className="flex items-center justify-center rounded-xl border border-[var(--border)] py-12">
+ <Loader2 className="h-4 w-4 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ );
+ }
+ const hasAny = changes.length > 0 || pending.length > 0;
+ if (!hasAny) {
+ return (
+ <p className="rounded-xl border border-[var(--border)] px-4 py-10 text-center text-[13px] text-[var(--muted-foreground)]">
+ {t("No changes recorded yet. Run Refresh to capture the baseline.")}
+ </p>
+ );
+ }
+ return (
+ <div className="space-y-2">
+ {pending.length > 0 && (
+ <div className="rounded-xl border border-amber-500/40 bg-amber-500/5">
+ <div className="flex items-center justify-between border-b border-amber-500/30 px-4 py-1.5 text-[11px] font-medium text-amber-700 dark:text-amber-300">
+ <span>
+ {t("Pending — {{n}} change(s) since last refresh", {
+ n: pending.length,
+ })}
+ </span>
+ <span className="opacity-70">{t("Click Refresh to commit")}</span>
+ </div>
+ <ol>
+ {pending.map((c, i) => (
+ <ChangeRow key={`pending-${c.entity_id}-${i}`} c={c} />
+ ))}
+ </ol>
+ </div>
+ )}
+ {changes.length > 0 && (
+ <ol className="rounded-xl border border-[var(--border)]">
+ {changes.map((c, i) => (
+ <ChangeRow key={`${c.ts}-${c.entity_id}-${i}`} c={c} />
+ ))}
+ </ol>
+ )}
+ </div>
+ );
+}
+
+function ChangeRow({ c }: { c: ChangeEntryDTO }) {
+ return (
+ <li className="flex items-start gap-3 border-b border-[var(--border)]/50 px-4 py-2 last:border-0">
+ <ChangeGlyph kind={c.kind} />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-baseline gap-x-2 text-[11px] text-[var(--muted-foreground)]">
+ <span className="font-medium text-[var(--foreground)]">
+ {c.label || c.entity_id}
+ </span>
+ <span className="font-mono opacity-70">{c.entity_id}</span>
+ <span>{formatTimestamp(c.ts, "")}</span>
+ </div>
+ </div>
+ </li>
+ );
+}
+
+function ChangeGlyph({ kind }: { kind: ChangeEntryDTO["kind"] }) {
+ const map = {
+ added: { ch: "+", bg: "bg-emerald-500/15", fg: "text-emerald-600" },
+ modified: { ch: "~", bg: "bg-amber-500/15", fg: "text-amber-600" },
+ removed: { ch: "−", bg: "bg-rose-500/15", fg: "text-rose-600" },
+ } as const;
+ const cfg = map[kind];
+ return (
+ <span
+ className={`mt-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded font-mono text-[12px] font-bold ${cfg.bg} ${cfg.fg}`}
+ >
+ {cfg.ch}
+ </span>
+ );
+}
+
+// ── KbQueriesList (event-driven, only for KB) ───────────────────────
+
+interface KbQueriesListProps {
+ loading: boolean;
+ queries: KbQueryDTO[];
+ t: (key: string, opts?: Record<string, unknown>) => string;
+}
+
+function KbQueriesList({ loading, queries, t }: KbQueriesListProps) {
+ if (loading && queries.length === 0) {
+ return (
+ <div className="flex items-center justify-center rounded-xl border border-[var(--border)] py-12">
+ <Loader2 className="h-4 w-4 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ );
+ }
+ if (queries.length === 0) {
+ return (
+ <p className="rounded-xl border border-[var(--border)] px-4 py-10 text-center text-[13px] text-[var(--muted-foreground)]">
+ {t("No RAG queries recorded yet.")}
+ </p>
+ );
+ }
+ return (
+ <ol className="rounded-xl border border-[var(--border)]">
+ {queries.map((q) => {
+ const kb = asString(q.payload?.kb_name) || "?";
+ const query = asString(q.payload?.query);
+ return (
+ <li
+ key={q.id}
+ className="flex items-start gap-3 border-b border-[var(--border)]/50 px-4 py-2 last:border-0"
+ >
+ <GitCommit className="mt-0.5 h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)]" />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-baseline gap-x-2 text-[11px] text-[var(--muted-foreground)]">
+ <span className="font-medium text-[var(--foreground)]">
+ {kb}
+ </span>
+ <span>{formatTimestamp(q.ts, "")}</span>
+ </div>
+ <p className="mt-0.5 truncate text-[12.5px] text-[var(--foreground)]">
+ {query}
+ </p>
+ </div>
+ </li>
+ );
+ })}
+ </ol>
+ );
+}
+
+// ── DocList / DocPane / StreamPanel (mostly unchanged) ──────────────
+
+interface DocListProps {
+ title: string;
+ rows: DocOverview[];
+ selected: { layer: Layer; key: string } | null;
+ onSelect: (layer: Layer, key: string) => void;
+}
+
+function DocList({ title, rows, selected, onSelect }: DocListProps) {
+ const { t } = useTranslation();
+ return (
+ <div className="rounded-xl border border-[var(--border)]">
+ <div className="border-b border-[var(--border)] px-4 py-2 text-[11px] font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">
+ {title}
+ </div>
+ <ul>
+ {rows.map((row) => {
+ const isActive =
+ selected?.layer === row.layer && selected.key === row.key;
+ return (
+ <li
+ key={`${row.layer}-${row.key}`}
+ className={`flex items-center justify-between border-b border-[var(--border)]/50 px-4 py-2 text-[13px] last:border-0 ${
+ isActive ? "bg-[var(--muted)]" : "hover:bg-[var(--muted)]/50"
+ }`}
+ >
+ <button
+ onClick={() => onSelect(row.layer, row.key)}
+ className="flex-1 text-left"
+ >
+ <span className="font-medium text-[var(--foreground)]">
+ {labelFor(row)}
+ </span>
+ <span className="ml-2 text-[11px] text-[var(--muted-foreground)]">
+ {row.entry_count} ·{" "}
+ {formatTimestamp(row.updated_at, t("not built"))}
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+}
+
+interface DocPaneProps {
+ selected: { layer: Layer; key: string };
+ content: string;
+ editing: boolean;
+ editorValue: string;
+ busy: boolean;
+ onEditValue: (v: string) => void;
+ onEditToggle: () => void;
+ onSave: () => void;
+ onUpdate: () => void;
+ onEntityLinkClick: (e: React.MouseEvent<HTMLDivElement>) => void;
+ t: (key: string, opts?: Record<string, unknown>) => string;
+}
+
+function DocPane({
+ selected,
+ content,
+ editing,
+ editorValue,
+ busy,
+ onEditValue,
+ onEditToggle,
+ onSave,
+ onUpdate,
+ onEntityLinkClick,
+ t,
+}: DocPaneProps) {
+ const isPrefs = selected.layer === "L3" && selected.key === "preferences";
+ const renderedContent = useMemo(() => linkifyEntityRefs(content), [content]);
+ return (
+ <div className="rounded-xl border border-[var(--border)]">
+ <div className="flex items-center justify-between border-b border-[var(--border)] px-4 py-2">
+ <span className="text-[14px] font-medium text-[var(--foreground)]">
+ {selected.layer} ·{" "}
+ {labelFor({
+ layer: selected.layer,
+ key: selected.key,
+ } as DocOverview)}
+ </span>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={onEditToggle}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ >
+ <Pencil className="h-3 w-3" />
+ {editing ? t("Cancel") : t("Edit")}
+ </button>
+ {editing && (
+ <button
+ onClick={onSave}
+ disabled={busy}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--primary)]/40 bg-[var(--primary)]/10 px-2.5 py-1 text-[12px] font-medium text-[var(--primary)] disabled:opacity-50"
+ >
+ {busy ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Save className="h-3 w-3" />
+ )}
+ {t("Save")}
+ </button>
+ )}
+ {!isPrefs && (
+ <button
+ onClick={onUpdate}
+ disabled={busy || editing}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--primary)]/40 bg-[var(--primary)]/10 px-2.5 py-1 text-[12px] font-medium text-[var(--primary)] disabled:opacity-50"
+ >
+ {busy ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <RefreshCw className="h-3 w-3" />
+ )}
+ {t("Update")}
+ </button>
+ )}
+ </div>
+ </div>
+ <div className="px-5 py-4">
+ {editing ? (
+ <textarea
+ value={editorValue}
+ onChange={(e) => onEditValue(e.target.value)}
+ spellCheck={false}
+ className="min-h-[420px] w-full resize-none rounded-lg border border-[var(--border)] bg-transparent p-3 font-mono text-[13px] leading-6 outline-none focus:border-[var(--ring)]"
+ />
+ ) : content.trim() ? (
+ <div onClick={onEntityLinkClick}>
+ <MarkdownRenderer
+ content={renderedContent}
+ variant="prose"
+ className="text-[14px]"
+ />
+ </div>
+ ) : (
+ <p className="text-[13px] text-[var(--muted-foreground)]">
+ {isPrefs
+ ? t(
+ "Preferences are written when you explicitly tell the chat assistant your preferences (style, language, format).",
+ )
+ : t(
+ "Empty. Click Update to consolidate from the current snapshot.",
+ )}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
+
+interface StreamPanelProps {
+ stages: StreamStage[];
+ onDismiss: () => void;
+ t: (key: string, opts?: Record<string, unknown>) => string;
+}
+
+function StreamPanel({ stages, onDismiss, t }: StreamPanelProps) {
+ return (
+ <div className="rounded-xl border border-[var(--border)]">
+ <div className="flex items-center justify-between border-b border-[var(--border)] px-4 py-2">
+ <span className="text-[12px] font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">
+ {t("Update progress")}
+ </span>
+ <button
+ onClick={onDismiss}
+ className="rounded p-1 text-[var(--muted-foreground)] hover:bg-[var(--muted)]"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </div>
+ <ol className="space-y-2 px-4 py-3 text-[12px]">
+ {stages.map((s, i) => (
+ <li
+ key={i}
+ className="rounded bg-[var(--muted)]/50 px-3 py-2 font-mono"
+ >
+ <span className="font-semibold text-[var(--foreground)]">
+ {s.stage}
+ {typeof s.turn === "number" ? ` · t${s.turn}` : ""}
+ {s.name ? ` · ${s.name}` : ""}
+ </span>
+ {typeof s.count === "number" && (
+ <span className="ml-2 text-[var(--muted-foreground)]">
+ count={s.count}
+ </span>
+ )}
+ {s.delta && (
+ <div className="mt-1 whitespace-pre-wrap text-[var(--muted-foreground)]">
+ {s.delta}
+ </div>
+ )}
+ {s.brief && (
+ <div className="mt-1 text-[var(--muted-foreground)]">
+ {s.brief}
+ </div>
+ )}
+ {s.args && Object.keys(s.args).length > 0 && (
+ <div className="mt-1 text-[var(--muted-foreground)]">
+ args: {JSON.stringify(s.args)}
+ </div>
+ )}
+ {s.ops && (
+ <div className="mt-1 text-[var(--muted-foreground)]">
+ ops: {s.ops.length}
+ </div>
+ )}
+ {typeof s.ops_emitted === "number" && (
+ <div className="mt-1 text-[var(--muted-foreground)]">
+ ops_emitted={s.ops_emitted} · turns={s.turns_used ?? "?"}
+ {s.tools_used
+ ? ` · ${Object.entries(s.tools_used)
+ .map(([k, v]) => `${k}=${v}`)
+ .join(", ")}`
+ : ""}
+ </div>
+ )}
+ {s.report && (
+ <div className="mt-1 text-[var(--muted-foreground)]">
+ accepted={String(s.report.accepted)}
+ {s.report.reason ? ` · ${s.report.reason}` : ""}
+ </div>
+ )}
+ {s.message && (
+ <div className="mt-1 text-[var(--muted-foreground)]">
+ {s.message}
+ </div>
+ )}
+ {s.summary && (
+ <div className="mt-1 text-[var(--muted-foreground)]">
+ {s.summary}
+ </div>
+ )}
+ </li>
+ ))}
+ </ol>
+ </div>
+ );
+}
diff --git a/web/components/memory/MemoryWorkbench.tsx b/web/components/memory/MemoryWorkbench.tsx
new file mode 100644
index 000000000..7d22e0c7a
--- /dev/null
+++ b/web/components/memory/MemoryWorkbench.tsx
@@ -0,0 +1,634 @@
+"use client";
+
+import dynamic from "next/dynamic";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ ArrowLeft,
+ BookOpen,
+ Bot,
+ ClipboardList,
+ FileText,
+ Hash,
+ Layers,
+ Library,
+ Loader2,
+ MessageSquare,
+ Network,
+ NotebookPen,
+ PenLine,
+ Pencil,
+ Save,
+ Workflow,
+ type LucideIcon,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { apiFetch, apiUrl } from "@/lib/api";
+import MemoryRunPanel from "@/components/memory/MemoryRunPanel";
+
+const MarkdownRenderer = dynamic(
+ () => import("@/components/common/MarkdownRenderer"),
+ { ssr: false },
+);
+
+type Layer = "L2" | "L3";
+
+// Each bullet ends with an HTML comment carrying the entry id
+// (``<!--m_01HZK...-->``). The parser round-trips it but the rendered
+// view should not show it as text — and we want clicking a same-doc
+// m_xxx footnote to scroll the user back to the citing bullet. Convert
+// the comment to an inline span with an ``id`` so:
+// * the rendered output is visually empty (zero-width span)
+// * ``#m_xxx`` hash navigation works within the doc
+// Requires ``allowHtml`` on the markdown renderer (we set it below).
+const _ENTRY_ANCHOR_RE =
+ /\s*<!--\s*(m_[0-9A-HJKMNP-TV-Z]{26})\s*-->/g;
+
+// Rewrite footnote definitions so the ref text becomes a markdown link.
+//
+// Four link targets, picked by (ref shape, current layer):
+// * ``surface:id`` → ``/memory/l1?ref=surface:id`` (L2 → L1 hop)
+// * ``m_<ULID>`` in L2 → ``#m_<ULID>`` (same-doc scroll; anchor
+// span above provides the target)
+// * ``m_<ULID>`` in L3 → ``/memory/resolve?id=m_<ULID>``
+// (legacy pre-pivot doc; resolver page redirects to the right L2)
+// * bare ``<surface>`` → ``/memory/l2/<surface>`` (L3 → L2 hop;
+// new design, L3 cites L2 files not L2 entries)
+//
+// The label regex is intentionally loose so this hits BOTH layouts —
+// the new consolidated ``[^1]:`` and the legacy entry-keyed
+// ``[^m_xxx]:`` — so docs that pre-date the merge step still get
+// clickable footnotes until the next mode pass migrates them.
+const _FOOTNOTE_DEF_LINKIFY_SURFACE_REF_RE =
+ /^(\[\^[^\]]+\]:\s*)([a-z][a-z0-9_-]*):([A-Za-z0-9_-]+)\s*$/gm;
+const _FOOTNOTE_DEF_LINKIFY_ENTRY_RE =
+ /^(\[\^[^\]]+\]:\s*)(m_[0-9A-HJKMNP-TV-Z]{26})\s*$/gm;
+// Bare surface name — keep tight (whitelist) so a typo can't accidentally
+// turn into an L2 hub link.
+const _L3_SURFACES = new Set([
+ "chat",
+ "notebook",
+ "quiz",
+ "kb",
+ "book",
+ "tutorbot",
+ "cowriter",
+]);
+const _FOOTNOTE_DEF_LINKIFY_BARE_RE =
+ /^(\[\^[^\]]+\]:\s*)([a-z][a-z0-9_-]*)\s*$/gm;
+
+function prepareDocForRender(md: string, layer: Layer): string {
+ // Anchor injection MUST come before linkify so that ``m_xxx`` text on
+ // a footnote-definition line is matched as a ref, not chewed up by the
+ // anchor regex (which only matches inside HTML comments).
+ const withAnchors = md.replace(
+ _ENTRY_ANCHOR_RE,
+ ' <span id="$1" class="memory-entry-anchor"></span>',
+ );
+ // ``surface:id`` must be tried before bare-surface because the bare
+ // regex would otherwise match the surface prefix and leave ``:id``
+ // dangling.
+ const withSurfaceLinks = withAnchors.replace(
+ _FOOTNOTE_DEF_LINKIFY_SURFACE_REF_RE,
+ (_match, prefix: string, surface: string, entityId: string) => {
+ const ref = `${surface}:${entityId}`;
+ const url = `/memory/l1?ref=${encodeURIComponent(ref)}`;
+ return `${prefix}[${ref}](${url})`;
+ },
+ );
+ const withEntryLinks = withSurfaceLinks.replace(
+ _FOOTNOTE_DEF_LINKIFY_ENTRY_RE,
+ (_match, prefix: string, entryId: string) => {
+ // L2: entry id refers to a bullet in *this* doc → local anchor.
+ // L3: entry id refers to a bullet in some L2 doc → resolver page
+ // does the surface lookup, then redirects.
+ const href =
+ layer === "L2"
+ ? `#${entryId}`
+ : `/memory/resolve?id=${encodeURIComponent(entryId)}`;
+ return `${prefix}[${entryId}](${href})`;
+ },
+ );
+ // Bare surface name — only meaningful for L3 refs (new design).
+ // Whitelist guards against linkifying arbitrary words that happen to
+ // end up alone on a footnote definition line.
+ return withEntryLinks.replace(
+ _FOOTNOTE_DEF_LINKIFY_BARE_RE,
+ (match, prefix: string, name: string) => {
+ if (!_L3_SURFACES.has(name)) return match;
+ return `${prefix}[${name}](/memory/l2/${name})`;
+ },
+ );
+}
+
+interface DocResponse {
+ layer: Layer;
+ key: string;
+ content: string;
+}
+
+interface LineRowDTO {
+ number: number;
+ kind: "title" | "blank" | "section" | "bullet";
+ text: string;
+ entry_id: string | null;
+ section: string | null;
+}
+
+interface DocOverview {
+ layer: Layer;
+ key: string;
+ exists: boolean;
+ updated_at: string | null;
+ entry_count: number;
+ backlog: number;
+}
+
+interface NavEntry {
+ key: string;
+ label: string;
+ icon: LucideIcon;
+}
+
+const L2_NAV: NavEntry[] = [
+ { key: "chat", icon: MessageSquare, label: "Chat" },
+ { key: "notebook", icon: NotebookPen, label: "Notebook" },
+ { key: "quiz", icon: ClipboardList, label: "Quiz" },
+ { key: "kb", icon: BookOpen, label: "Knowledge base" },
+ { key: "book", icon: Library, label: "Book" },
+ { key: "tutorbot", icon: Bot, label: "TutorBot" },
+ { key: "cowriter", icon: PenLine, label: "Co-writer" },
+];
+
+const L3_NAV: NavEntry[] = [
+ { key: "recent", icon: Network, label: "Recent summary" },
+ { key: "profile", icon: Network, label: "User profile" },
+ { key: "scope", icon: Network, label: "Knowledge scope" },
+];
+
+type ViewMode = "plain" | "lines";
+
+export interface MemoryWorkbenchProps {
+ layer: Layer;
+ initialKey?: string;
+ /**
+ * Entry id to scroll into view + briefly highlight after the markdown
+ * renders. Set by the deep-link contract (``?focus=m_xxx``) when the
+ * user lands here from an L3 footnote click.
+ */
+ initialFocus?: string;
+}
+
+export default function MemoryWorkbench({
+ layer,
+ initialKey,
+ initialFocus,
+}: MemoryWorkbenchProps) {
+ const { t } = useTranslation();
+ const router = useRouter();
+ const nav = layer === "L2" ? L2_NAV : L3_NAV;
+ const [docKey, setDocKey] = useState<string>(initialKey || nav[0].key);
+
+ useEffect(() => {
+ if (initialKey) setDocKey(initialKey);
+ }, [initialKey]);
+
+ const [overview, setOverview] = useState<Record<string, DocOverview>>({});
+ const [content, setContent] = useState("");
+ const [lines, setLines] = useState<LineRowDTO[]>([]);
+ const [view, setView] = useState<ViewMode>("plain");
+ const [editing, setEditing] = useState(false);
+ const [editorValue, setEditorValue] = useState("");
+ const [saving, setSaving] = useState(false);
+ const [toast, setToast] = useState("");
+ // Focus is one-shot — once we've scrolled-to + flashed the anchor we
+ // don't want subsequent content reloads (e.g. after a Run) to keep
+ // re-scrolling. ``initialFocus`` seeds it; the effect clears it.
+ const [pendingFocus, setPendingFocus] = useState<string | null>(
+ initialFocus || null,
+ );
+ const previewRef = useRef<HTMLDivElement | null>(null);
+
+ useEffect(() => {
+ if (initialFocus) setPendingFocus(initialFocus);
+ }, [initialFocus]);
+
+ const loadOverview = useCallback(async () => {
+ const res = await apiFetch(apiUrl("/api/v1/memory/overview"));
+ const data = await res.json();
+ const map: Record<string, DocOverview> = {};
+ for (const d of data.docs || []) {
+ if (d.layer === layer) map[d.key] = d;
+ }
+ setOverview(map);
+ }, [layer]);
+
+ const loadDoc = useCallback(async () => {
+ const res = await apiFetch(apiUrl(`/api/v1/memory/doc/${layer}/${docKey}`));
+ const data = (await res.json()) as DocResponse;
+ setContent(data?.content || "");
+ setEditorValue(data?.content || "");
+ }, [layer, docKey]);
+
+ const loadLines = useCallback(async () => {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/memory/doc/${layer}/${docKey}/lines`),
+ );
+ const data = (await res.json()) as { lines: LineRowDTO[] };
+ setLines(data?.lines || []);
+ }, [layer, docKey]);
+
+ useEffect(() => {
+ void loadOverview();
+ }, [loadOverview]);
+ useEffect(() => {
+ void loadDoc();
+ void loadLines();
+ }, [loadDoc, loadLines]);
+ useEffect(() => {
+ if (!toast) return;
+ const id = setTimeout(() => setToast(""), 2200);
+ return () => clearTimeout(id);
+ }, [toast]);
+
+ // Scroll-to + flash the focused entry once the markdown is in the
+ // DOM. Markdown renders via a dynamic import → we can't fire on
+ // ``content`` change alone; wait a frame so the anchor span exists.
+ // ``editing`` mode hides the rendered preview, so skip then.
+ useEffect(() => {
+ if (!pendingFocus || editing) return;
+ if (!content || !previewRef.current) return;
+ const anchorId = pendingFocus.startsWith("m_") ? pendingFocus : `m_${pendingFocus}`;
+ let cancelled = false;
+ const id = window.setTimeout(() => {
+ if (cancelled) return;
+ const span = document.getElementById(anchorId);
+ // Highlight the bullet, not the zero-width anchor span.
+ const li = (span?.closest("li") as HTMLElement | null) ?? span;
+ if (!li) return;
+ li.scrollIntoView({ block: "center", behavior: "smooth" });
+ const prev = {
+ outline: li.style.outline,
+ outlineOffset: li.style.outlineOffset,
+ borderRadius: li.style.borderRadius,
+ transition: li.style.transition,
+ };
+ li.style.outline = "2px solid var(--primary)";
+ li.style.outlineOffset = "4px";
+ li.style.borderRadius = "6px";
+ li.style.transition = "outline-color 1.4s ease-out";
+ const clear = window.setTimeout(() => {
+ li.style.outline = prev.outline;
+ li.style.outlineOffset = prev.outlineOffset;
+ li.style.borderRadius = prev.borderRadius;
+ li.style.transition = prev.transition;
+ }, 1800);
+ // Consume the focus token so reloads don't re-trigger.
+ setPendingFocus(null);
+ return () => window.clearTimeout(clear);
+ }, 80);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(id);
+ };
+ }, [pendingFocus, content, editing]);
+
+ const selectDoc = useCallback(
+ (next: string) => {
+ if (next === docKey) return;
+ setDocKey(next);
+ // Reflect selection in the URL so refresh + share keep state.
+ router.replace(
+ layer === "L2" ? `/memory/l2/${next}` : `/memory/l3/${next}`,
+ );
+ },
+ [docKey, layer, router],
+ );
+
+ const saveDoc = useCallback(async () => {
+ setSaving(true);
+ try {
+ await apiFetch(apiUrl(`/api/v1/memory/doc/${layer}/${docKey}`), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ content: editorValue }),
+ });
+ setContent(editorValue);
+ setEditing(false);
+ setToast(t("Saved"));
+ void loadLines();
+ } catch (e) {
+ setToast(e instanceof Error ? e.message : t("Save failed"));
+ } finally {
+ setSaving(false);
+ }
+ }, [editorValue, layer, docKey, t, loadLines]);
+
+ const nicelabel = useMemo(
+ () => {
+ const entry = nav.find((n) => n.key === docKey);
+ return entry ? t(entry.label) : docKey;
+ },
+ [docKey, nav, t],
+ );
+
+ const handleRunComplete = useCallback(() => {
+ void loadDoc();
+ void loadLines();
+ void loadOverview();
+ }, [loadDoc, loadLines, loadOverview]);
+
+ return (
+ <div className="flex h-full min-h-0 flex-col gap-3 px-6 py-4 md:px-10">
+ <div className="flex items-center justify-between gap-3">
+ <Breadcrumb layer={layer} label={nicelabel} t={t} />
+ <LayerSwitcher current={layer} t={t} />
+ </div>
+
+ <div className="grid min-h-0 flex-1 grid-cols-[180px_minmax(0,1fr)_360px] gap-4">
+ {/* ── Left rail ── */}
+ <aside className="min-h-0 overflow-y-auto rounded-2xl border border-[var(--border)] bg-[var(--card)] p-2">
+ <ul className="space-y-0.5">
+ {nav.map(({ key, icon: Icon, label }) => {
+ const doc = overview[key];
+ const active = key === docKey;
+ return (
+ <li key={key}>
+ <button
+ type="button"
+ onClick={() => selectDoc(key)}
+ className={
+ "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-[12.5px] text-left transition " +
+ (active
+ ? "bg-[var(--muted)] text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]")
+ }
+ >
+ <Icon className="h-3.5 w-3.5 shrink-0" />
+ <span className="flex-1 truncate">{t(label)}</span>
+ {doc?.exists && (
+ <span className="rounded-full bg-[var(--background)] px-1.5 py-0.5 text-[10px] text-[var(--muted-foreground)]">
+ {doc.entry_count}
+ </span>
+ )}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </aside>
+
+ {/* ── Center: preview ── */}
+ <section className="flex min-h-0 flex-col gap-3">
+ <div className="flex items-center justify-between gap-2">
+ <ViewSwitch view={view} setView={setView} t={t} />
+ {!editing ? (
+ <button
+ type="button"
+ onClick={() => setEditing(true)}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[12px] transition hover:bg-[var(--muted)]"
+ >
+ <Pencil className="h-3.5 w-3.5" />
+ {t("Edit raw")}
+ </button>
+ ) : (
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => {
+ setEditorValue(content);
+ setEditing(false);
+ }}
+ className="rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1 text-[12px]"
+ >
+ {t("Cancel")}
+ </button>
+ <button
+ type="button"
+ onClick={() => void saveDoc()}
+ disabled={saving}
+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1 text-[12px] text-[var(--primary-foreground)] disabled:opacity-50"
+ >
+ {saving ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Save className="h-3.5 w-3.5" />
+ )}
+ {t("Save")}
+ </button>
+ </div>
+ )}
+ </div>
+ <div
+ ref={previewRef}
+ className="min-h-0 flex-1 overflow-y-auto rounded-2xl border border-[var(--border)] bg-[var(--card)] p-5"
+ >
+ {editing ? (
+ <textarea
+ value={editorValue}
+ onChange={(e) => setEditorValue(e.target.value)}
+ className="h-[60vh] w-full resize-none rounded-md border border-[var(--border)] bg-[var(--background)] p-3 font-mono text-[12.5px] outline-none focus:border-[var(--primary)]"
+ />
+ ) : view === "lines" ? (
+ <LineNumberedView lines={lines} t={t} />
+ ) : content.trim().length > 0 ? (
+ // The wrapper hides the default footnote backref arrow
+ // (``data-footnote-backref``). Without this the rendered
+ // doc has two clickable elements per footnote: the L1
+ // text link we inject (correct) and the ↩ icon
+ // remark-gfm auto-generates that jumps back to the
+ // citation marker (confusing — users expect every link
+ // in the footnote to go to L1).
+ <div className="memory-doc-content [&_.data-footnote-backref]:hidden">
+ <MarkdownRenderer
+ content={prepareDocForRender(content, layer)}
+ variant="prose"
+ className="text-[14px]"
+ allowHtml
+ />
+ </div>
+ ) : (
+ <EmptyState t={t} />
+ )}
+ </div>
+ {toast && (
+ <div className="self-start rounded-md border border-[var(--primary)]/30 bg-[var(--primary)]/10 px-3 py-1 text-[11.5px] text-[var(--primary)]">
+ {toast}
+ </div>
+ )}
+ </section>
+
+ {/* ── Right: LLM work area ── */}
+ <aside className="min-h-0">
+ <MemoryRunPanel
+ layer={layer}
+ docKey={docKey}
+ onRunComplete={handleRunComplete}
+ onDocUpdated={handleRunComplete}
+ />
+ </aside>
+ </div>
+ </div>
+ );
+}
+
+// ── Sub-components ──────────────────────────────────────────────────
+
+function Breadcrumb({
+ layer,
+ label,
+ t,
+}: {
+ layer: Layer;
+ label: string;
+ t: (k: string) => string;
+}) {
+ return (
+ <div className="flex items-center gap-2 text-[12.5px]">
+ <Link
+ href="/memory"
+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ {t("Memory")}
+ </Link>
+ <span className="text-[var(--muted-foreground)]">/</span>
+ <span className="inline-flex items-center gap-1.5 text-[var(--foreground)]">
+ {layer === "L2" ? (
+ <Workflow className="h-3.5 w-3.5" />
+ ) : (
+ <Network className="h-3.5 w-3.5" />
+ )}
+ {layer === "L2"
+ ? t("L2 · Per-surface summaries")
+ : t("L3 · Cross-surface knowledge")}
+ </span>
+ <span className="text-[var(--muted-foreground)]">/</span>
+ <span className="text-[var(--foreground)]">{label}</span>
+ </div>
+ );
+}
+
+function LayerSwitcher({
+ current,
+ t,
+}: {
+ current: Layer;
+ t: (k: string) => string;
+}) {
+ // L1 page is a single workbench (no per-key route); L2/L3 hubs land
+ // on /memory/l2 and /memory/l3 which list the surfaces / slots.
+ const entries: { key: "L1" | Layer; href: string; icon: LucideIcon; label: string }[] = [
+ { key: "L1", href: "/memory/l1", icon: Layers, label: t("L1") },
+ { key: "L2", href: "/memory/l2", icon: Workflow, label: t("L2") },
+ { key: "L3", href: "/memory/l3", icon: Network, label: t("L3") },
+ ];
+ return (
+ <nav className="flex items-center gap-0.5 rounded-full border border-[var(--border)] bg-[var(--card)] p-0.5">
+ {entries.map(({ key, href, icon: Icon, label }) => {
+ const active = key === current;
+ if (active) {
+ return (
+ <span
+ key={key}
+ className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)] px-2.5 py-0.5 text-[11.5px] font-medium text-[var(--foreground)]"
+ >
+ <Icon className="h-3 w-3" />
+ {label}
+ </span>
+ );
+ }
+ return (
+ <Link
+ key={key}
+ href={href}
+ className="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[11.5px] text-[var(--muted-foreground)] transition hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ >
+ <Icon className="h-3 w-3" />
+ {label}
+ </Link>
+ );
+ })}
+ </nav>
+ );
+}
+
+function ViewSwitch({
+ view,
+ setView,
+ t,
+}: {
+ view: ViewMode;
+ setView: (v: ViewMode) => void;
+ t: (k: string) => string;
+}) {
+ const items: { key: ViewMode; label: string; icon: LucideIcon }[] = [
+ { key: "plain", label: t("Rendered"), icon: FileText },
+ { key: "lines", label: t("Line numbers"), icon: Hash },
+ ];
+ return (
+ <div className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)] bg-[var(--background)] p-1">
+ {items.map(({ key, label, icon: Icon }) => (
+ <button
+ key={key}
+ type="button"
+ onClick={() => setView(key)}
+ className={
+ "inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11.5px] transition " +
+ (view === key
+ ? "bg-[var(--muted)] text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60")
+ }
+ >
+ <Icon className="h-3.5 w-3.5" />
+ {label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function LineNumberedView({
+ lines,
+ t,
+}: {
+ lines: LineRowDTO[];
+ t: (k: string) => string;
+}) {
+ if (lines.length === 0) return <EmptyState t={t} />;
+ const width = Math.max(2, String(lines[lines.length - 1].number).length);
+ return (
+ <pre className="overflow-x-auto whitespace-pre-wrap font-mono text-[12.5px] leading-relaxed text-[var(--foreground)]">
+ {lines.map((line) => {
+ const num = String(line.number).padStart(width, " ");
+ const muted = line.kind === "blank" || line.kind === "title";
+ return (
+ <div
+ key={line.number}
+ className={
+ muted ? "text-[var(--muted-foreground)]" : "text-[var(--foreground)]"
+ }
+ >
+ <span className="select-none pr-3 text-[var(--muted-foreground)]">
+ {num}:
+ </span>
+ {line.text || " "}
+ </div>
+ );
+ })}
+ </pre>
+ );
+}
+
+function EmptyState({ t }: { t: (k: string) => string }) {
+ return (
+ <div className="grid h-[300px] place-items-center text-center text-[13px] text-[var(--muted-foreground)]">
+ <div className="max-w-sm space-y-2">
+ <Workflow className="mx-auto h-6 w-6 opacity-60" />
+ <p>{t("Empty. Click Update to extract facts from your traces.")}</p>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/memory/useMemoryRun.ts b/web/components/memory/useMemoryRun.ts
new file mode 100644
index 000000000..dc323a26a
--- /dev/null
+++ b/web/components/memory/useMemoryRun.ts
@@ -0,0 +1,349 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import i18n from "i18next";
+
+import { apiFetch, apiUrl } from "@/lib/api";
+import type { LLMSelection } from "@/lib/unified-ws";
+
+export type RunMode = "update" | "audit" | "dedup";
+export type RunStatus = "queued" | "running" | "cancelled" | "done" | "error";
+
+export interface RunHandle {
+ id: string;
+ layer: "L2" | "L3";
+ key: string;
+ mode: RunMode;
+ status: RunStatus;
+ started_at: string;
+ ended_at: string | null;
+ error: string | null;
+ event_count: number;
+ undo_count: number;
+}
+
+export interface RunEventPayload {
+ stage: string;
+ [key: string]: unknown;
+}
+
+export interface RunEvent {
+ seq: number;
+ ts: string;
+ payload: RunEventPayload;
+}
+
+export interface StartArgs {
+ mode: RunMode;
+ budget?: number;
+ iterations?: number;
+ llmSelection?: LLMSelection | null;
+ language?: string;
+}
+
+interface State {
+ run: RunHandle | null;
+ events: RunEvent[];
+ status: RunStatus | "idle";
+ error: string | null;
+ reconnecting: boolean;
+}
+
+// One row per `(layer, key)` survives a page refresh by persisting the
+// active run_id in localStorage. The hook reads this on mount and tries
+// to re-attach to a still-running run on the server.
+const STORAGE_PREFIX = "dt:memory:active-run";
+
+function storageKey(layer: string, key: string) {
+ return `${STORAGE_PREFIX}:${layer}:${key}`;
+}
+
+function readPersistedRunId(layer: string, key: string): string | null {
+ if (typeof window === "undefined") return null;
+ return window.localStorage.getItem(storageKey(layer, key));
+}
+
+function writePersistedRunId(layer: string, key: string, runId: string | null) {
+ if (typeof window === "undefined") return;
+ if (runId) {
+ window.localStorage.setItem(storageKey(layer, key), runId);
+ } else {
+ window.localStorage.removeItem(storageKey(layer, key));
+ }
+}
+
+export function useMemoryRun(layer: "L2" | "L3", key: string) {
+ const [state, setState] = useState<State>({
+ run: null,
+ events: [],
+ status: "idle",
+ error: null,
+ reconnecting: false,
+ });
+ const abortRef = useRef<AbortController | null>(null);
+ const cursorRef = useRef<number>(0);
+ // Track if we've initialised for this (layer, key) so a parent re-render
+ // doesn't trigger duplicate reconnects.
+ const initialisedFor = useRef<string>("");
+
+ const close = useCallback(() => {
+ abortRef.current?.abort();
+ abortRef.current = null;
+ }, []);
+
+ // Reset when the doc changes; re-attach to that doc's persisted run if any.
+ useEffect(() => {
+ const tag = `${layer}:${key}`;
+ if (initialisedFor.current === tag) return;
+ initialisedFor.current = tag;
+ close();
+ cursorRef.current = 0;
+ setState({ run: null, events: [], status: "idle", error: null, reconnecting: false });
+
+ void (async () => {
+ const persistedId = readPersistedRunId(layer, key);
+ let runId: string | null = persistedId;
+ // Verify the persisted run exists; otherwise see if the server thinks
+ // this doc has an active run.
+ try {
+ if (runId) {
+ const res = await apiFetch(apiUrl(`/api/v1/memory/runs/${runId}`));
+ if (!res.ok) runId = null;
+ }
+ if (!runId) {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/memory/runs?layer=${layer}&key=${encodeURIComponent(key)}`),
+ );
+ if (res.ok) {
+ const data = (await res.json()) as { runs: RunHandle[] };
+ const active = data.runs.find((r) => r.status === "running" || r.status === "queued");
+ if (active) {
+ runId = active.id;
+ writePersistedRunId(layer, key, runId);
+ }
+ }
+ }
+ } catch {
+ // best-effort recovery — if the API is unreachable we'll just start
+ // a new run when the user clicks Run.
+ }
+ if (runId) {
+ await attach(runId);
+ }
+ })();
+
+ return () => {
+ close();
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [layer, key]);
+
+ const attach = useCallback(
+ async (runId: string, since = 0): Promise<void> => {
+ // Pull the run handle first.
+ try {
+ const res = await apiFetch(apiUrl(`/api/v1/memory/runs/${runId}`));
+ if (!res.ok) {
+ writePersistedRunId(layer, key, null);
+ return;
+ }
+ const run = (await res.json()) as RunHandle;
+ setState((s) => ({ ...s, run, status: run.status, reconnecting: false }));
+ } catch {
+ return;
+ }
+
+ abortRef.current?.abort();
+ const ctl = new AbortController();
+ abortRef.current = ctl;
+ cursorRef.current = since;
+
+ try {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/memory/runs/${runId}/events?since=${since}`),
+ { signal: ctl.signal, cache: "no-store" },
+ );
+ const reader = res.body?.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ while (reader) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ let nl = buffer.indexOf("\n\n");
+ while (nl !== -1) {
+ const chunk = buffer.slice(0, nl);
+ buffer = buffer.slice(nl + 2);
+ const line = chunk
+ .split("\n")
+ .find((l) => l.startsWith("data:"))
+ ?.replace(/^data:\s?/, "");
+ if (line) {
+ try {
+ const parsed = JSON.parse(line);
+ const seq = typeof parsed.seq === "number" ? parsed.seq : cursorRef.current;
+ const ts = typeof parsed.ts === "string" ? parsed.ts : new Date().toISOString();
+ const { seq: _s, ts: _t, ...payload } = parsed;
+ cursorRef.current = seq + 1;
+ setState((s) => {
+ const undoDepth =
+ typeof payload.undo_depth === "number" ? payload.undo_depth : null;
+ const endedStatus =
+ payload.stage === "run_ended" && typeof payload.status === "string"
+ ? (payload.status as RunStatus)
+ : null;
+ return {
+ ...s,
+ status: endedStatus ?? s.status,
+ run: s.run
+ ? {
+ ...s.run,
+ status: endedStatus ?? s.run.status,
+ undo_count: undoDepth ?? s.run.undo_count,
+ }
+ : s.run,
+ events: s.events.some((ev) => ev.seq === seq)
+ ? s.events
+ : [...s.events, { seq, ts, payload: payload as RunEventPayload }],
+ };
+ });
+ if (payload.stage === "run_ended" && typeof payload.status === "string") {
+ writePersistedRunId(layer, key, null);
+ }
+ } catch {
+ // ignore malformed chunks
+ }
+ }
+ nl = buffer.indexOf("\n\n");
+ }
+ }
+ } catch (e) {
+ if ((e as Error).name === "AbortError") return;
+ setState((s) => ({
+ ...s,
+ error: e instanceof Error ? e.message : i18n.t("stream failed"),
+ }));
+ }
+ },
+ [layer, key],
+ );
+
+ const start = useCallback(
+ async (args: StartArgs): Promise<void> => {
+ setState((s) => ({ ...s, error: null, events: [], status: "queued" }));
+ try {
+ const res = await apiFetch(apiUrl("/api/v1/memory/runs/start"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ layer,
+ key,
+ mode: args.mode,
+ budget: args.budget ?? null,
+ iterations: args.iterations ?? null,
+ llm_selection: args.llmSelection ?? null,
+ language: args.language ?? "en",
+ }),
+ });
+ if (!res.ok) {
+ const detail = await res.text();
+ throw new Error(
+ detail || i18n.t("start failed: {{status}}", { status: res.status }),
+ );
+ }
+ const run = (await res.json()) as RunHandle;
+ writePersistedRunId(layer, key, run.id);
+ await attach(run.id, 0);
+ } catch (e) {
+ setState((s) => ({
+ ...s,
+ status: "error",
+ error: e instanceof Error ? e.message : i18n.t("start failed"),
+ }));
+ }
+ },
+ [layer, key, attach],
+ );
+
+ const cancel = useCallback(async (): Promise<void> => {
+ if (!state.run) return;
+ try {
+ await apiFetch(apiUrl(`/api/v1/memory/runs/${state.run.id}/cancel`), {
+ method: "POST",
+ });
+ } catch {
+ // ignore: the server may already have terminated naturally.
+ }
+ }, [state.run]);
+
+ const undo = useCallback(async (): Promise<boolean> => {
+ if (!state.run) return false;
+ try {
+ const res = await apiFetch(apiUrl(`/api/v1/memory/runs/${state.run.id}/undo`), {
+ method: "POST",
+ });
+ if (!res.ok) {
+ const detail = await res.text();
+ throw new Error(
+ detail || i18n.t("undo failed: {{status}}", { status: res.status }),
+ );
+ }
+ const data = (await res.json()) as {
+ undo_count?: number;
+ event?: { seq: number; ts: string; [key: string]: unknown };
+ };
+ const ev = data.event;
+ setState((s) => {
+ const nextRun = s.run
+ ? { ...s.run, undo_count: data.undo_count ?? s.run.undo_count }
+ : s.run;
+ if (!ev || typeof ev.seq !== "number") return { ...s, run: nextRun };
+ const { seq, ts, ...payload } = ev;
+ return {
+ ...s,
+ run: nextRun,
+ events: s.events.some((item) => item.seq === seq)
+ ? s.events
+ : [
+ ...s.events,
+ {
+ seq,
+ ts: typeof ts === "string" ? ts : new Date().toISOString(),
+ payload: payload as RunEventPayload,
+ },
+ ],
+ };
+ });
+ return true;
+ } catch (e) {
+ setState((s) => ({
+ ...s,
+ error: e instanceof Error ? e.message : i18n.t("undo failed"),
+ }));
+ return false;
+ }
+ }, [state.run]);
+
+ const clear = useCallback(() => {
+ setState({ run: null, events: [], status: "idle", error: null, reconnecting: false });
+ writePersistedRunId(layer, key, null);
+ close();
+ }, [layer, key, close]);
+
+ const isRunning = useMemo(
+ () => state.status === "queued" || state.status === "running",
+ [state.status],
+ );
+
+ return {
+ run: state.run,
+ events: state.events,
+ status: state.status,
+ error: state.error,
+ isRunning,
+ start,
+ cancel,
+ undo,
+ clear,
+ };
+}
diff --git a/web/components/space/MemorySection.tsx b/web/components/space/MemorySection.tsx
deleted file mode 100644
index 491e09457..000000000
--- a/web/components/space/MemorySection.tsx
+++ /dev/null
@@ -1,379 +0,0 @@
-"use client";
-
-import dynamic from "next/dynamic";
-import { useCallback, useEffect, useRef, useState } from "react";
-import {
- BookOpen,
- Brain,
- Eraser,
- Loader2,
- RefreshCw,
- Save,
- User,
-} from "lucide-react";
-import { useTranslation } from "react-i18next";
-import { useAppShell } from "@/context/AppShellContext";
-import { apiFetch, apiUrl } from "@/lib/api";
-import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";
-
-const MarkdownRenderer = dynamic(
- () => import("@/components/common/MarkdownRenderer"),
- { ssr: false },
-);
-
-type MemoryFile = "summary" | "profile";
-
-interface MemoryData {
- summary: string;
- profile: string;
- summary_updated_at: string | null;
- profile_updated_at: string | null;
-}
-
-interface MemoryApiData extends MemoryData {
- changed?: boolean;
-}
-
-const TABS: {
- key: MemoryFile;
- label: string;
- icon: typeof Brain;
- hint: string;
- placeholder: string;
-}[] = [
- {
- key: "summary",
- label: "Summary",
- icon: BookOpen,
- hint: "Running summary of the learning journey. Auto-updated after conversations.",
- placeholder:
- "## Current Focus\n- ...\n\n## Accomplishments\n- ...\n\n## Open Questions\n- ...",
- },
- {
- key: "profile",
- label: "Profile",
- icon: User,
- hint: "User identity, preferences, and knowledge levels. Auto-updated after conversations.",
- placeholder:
- "## Identity\n- ...\n\n## Learning Style\n- ...\n\n## Knowledge Level\n- ...\n\n## Preferences\n- ...",
- },
-];
-
-const EMPTY: MemoryData = {
- summary: "",
- profile: "",
- summary_updated_at: null,
- profile_updated_at: null,
-};
-
-function formatUpdatedAt(
- value: string | null,
- t: (key: string) => string,
-): string {
- if (!value) return t("Not updated yet");
- const date = new Date(value);
- if (Number.isNaN(date.getTime())) return t("Unknown");
- return date.toLocaleString();
-}
-
-async function readMemoryResponse(res: Response): Promise<MemoryApiData> {
- const payload = (await res.json().catch(() => ({}))) as {
- detail?: unknown;
- };
- if (!res.ok) {
- throw new Error(
- typeof payload.detail === "string"
- ? payload.detail
- : "Memory request failed",
- );
- }
- return payload as MemoryApiData;
-}
-
-export default function MemorySection() {
- const { t } = useTranslation();
- const { activeSessionId, language } = useAppShell();
- const [data, setData] = useState<MemoryData>(EMPTY);
- const [loading, setLoading] = useState(true);
- const [refreshing, setRefreshing] = useState(false);
- const [clearing, setClearing] = useState(false);
- const [saving, setSaving] = useState(false);
- const [activeTab, setActiveTab] = useState<MemoryFile>("summary");
- const [activeView, setActiveView] = useState<"edit" | "preview">("edit");
- const [editors, setEditors] = useState<Record<MemoryFile, string>>({
- summary: "",
- profile: "",
- });
- const [toast, setToast] = useState("");
- const textareaRef = useRef<HTMLTextAreaElement>(null);
-
- const tab = TABS.find((tabItem) => tabItem.key === activeTab)!;
- const editorValue = editors[activeTab];
- const hasChanges = editorValue !== data[activeTab];
- const updatedAt = data[`${activeTab}_updated_at` as keyof MemoryData] as
- | string
- | null;
-
- useEffect(() => {
- if (!toast) return;
- const timer = setTimeout(() => setToast(""), 3500);
- return () => clearTimeout(timer);
- }, [toast]);
-
- const loadMemory = useCallback(async () => {
- setLoading(true);
- try {
- const res = await apiFetch(apiUrl("/api/v1/memory"));
- const d = await readMemoryResponse(res);
- setData(d);
- setEditors({ summary: d.summary || "", profile: d.profile || "" });
- } catch (error) {
- setToast(
- error instanceof Error ? error.message : t("Memory request failed"),
- );
- } finally {
- setLoading(false);
- }
- }, [t]);
-
- useEffect(() => {
- void loadMemory();
- }, [loadMemory]);
-
- const saveMemory = useCallback(async () => {
- setSaving(true);
- try {
- const res = await apiFetch(apiUrl("/api/v1/memory"), {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ file: activeTab, content: editorValue }),
- });
- const d = await readMemoryResponse(res);
- setData(d);
- setEditors((prev) => ({ ...prev, [activeTab]: d[activeTab] || "" }));
- setToast(t("{{label}} saved", { label: t(tab.label) }));
- } catch (error) {
- setToast(
- error instanceof Error ? error.message : t("Memory save failed"),
- );
- } finally {
- setSaving(false);
- }
- }, [activeTab, editorValue, t, tab.label]);
-
- const refreshMemory = useCallback(async () => {
- setRefreshing(true);
- try {
- const res = await apiFetch(apiUrl("/api/v1/memory/refresh"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- session_id: activeSessionId || undefined,
- language,
- }),
- });
- const d = await readMemoryResponse(res);
- setData(d);
- setEditors({ summary: d.summary || "", profile: d.profile || "" });
- setToast(
- d.changed === false
- ? t("Memory checked; no long-term updates")
- : t("Memory refreshed from session"),
- );
- } catch (error) {
- setToast(
- error instanceof Error ? error.message : t("Memory refresh failed"),
- );
- } finally {
- setRefreshing(false);
- }
- }, [activeSessionId, language, t]);
-
- const clearMemory = useCallback(async () => {
- if (!window.confirm(t("Clear {{label}}?", { label: t(tab.label) }))) return;
- setClearing(true);
- try {
- const res = await apiFetch(apiUrl("/api/v1/memory/clear"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ file: activeTab }),
- });
- const d = await readMemoryResponse(res);
- setData(d);
- setEditors((prev) => ({ ...prev, [activeTab]: d[activeTab] || "" }));
- setToast(t("{{label}} cleared", { label: t(tab.label) }));
- } catch (error) {
- setToast(
- error instanceof Error ? error.message : t("Memory clear failed"),
- );
- } finally {
- setClearing(false);
- }
- }, [activeTab, t, tab.label]);
-
- const handleKeyDown = useCallback(
- (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if ((e.metaKey || e.ctrlKey) && e.key === "s") {
- e.preventDefault();
- void saveMemory();
- }
- },
- [saveMemory],
- );
-
- return (
- <div className="space-y-6">
- <SpaceSectionHeader
- icon={Brain}
- title={t("Memory")}
- description={t(
- "Long-form memory the assistant carries across sessions — your running summary and learner profile.",
- )}
- meta={
- toast ? (
- <span className="rounded-full border border-[var(--primary)]/30 bg-[var(--primary)]/10 px-2 py-0.5 text-[10.5px] font-medium text-[var(--primary)]">
- {toast}
- </span>
- ) : (
- <span className="rounded-full border border-[var(--border)] bg-[var(--card)] px-2 py-0.5 text-[10.5px] font-medium text-[var(--muted-foreground)]">
- {hasChanges ? t("Unsaved changes") : t("All changes saved")}
- </span>
- )
- }
- action={
- <div className="flex items-center gap-2">
- <button
- onClick={saveMemory}
- disabled={saving}
- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"
- >
- {saving ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <Save className="h-3 w-3" />
- )}
- {t("Save")}
- </button>
- <button
- onClick={refreshMemory}
- disabled={refreshing}
- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"
- >
- {refreshing ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <RefreshCw className="h-3 w-3" />
- )}
- {t("Refresh")}
- </button>
- <button
- onClick={clearMemory}
- disabled={clearing}
- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"
- >
- {clearing ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <Eraser className="h-3 w-3" />
- )}
- {t("Clear")}
- </button>
- </div>
- }
- />
-
- {/* Tab selector */}
- <div className="flex items-center gap-1 border-b border-[var(--border)]/50 pb-3">
- {TABS.map((tabItem) => {
- const Icon = tabItem.icon;
- const active = activeTab === tabItem.key;
- return (
- <button
- key={tabItem.key}
- onClick={() => setActiveTab(tabItem.key)}
- className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
- active
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- <Icon className="h-3.5 w-3.5" />
- {t(tabItem.label)}
- </button>
- );
- })}
- </div>
-
- {/* Meta & View toggle */}
- <div className="flex items-center justify-between">
- <p className="max-w-lg text-[12px] text-[var(--muted-foreground)]">
- {t(tab.hint)}
- </p>
- <div className="flex items-center gap-3">
- <div className="flex items-center gap-1">
- {(["edit", "preview"] as const).map((v) => (
- <button
- key={v}
- onClick={() => setActiveView(v)}
- className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
- activeView === v
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- {v === "edit" ? t("Edit") : t("Preview")}
- </button>
- ))}
- </div>
- <span className="text-[12px] text-[var(--muted-foreground)]">
- {t("Updated")}: {formatUpdatedAt(updatedAt, t)}
- </span>
- </div>
- </div>
-
- {/* Content */}
- {loading ? (
- <div className="flex min-h-[420px] items-center justify-center">
- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
- </div>
- ) : activeView === "edit" ? (
- <div>
- <textarea
- ref={textareaRef}
- value={editorValue}
- onChange={(e) =>
- setEditors((prev) => ({ ...prev, [activeTab]: e.target.value }))
- }
- onKeyDown={handleKeyDown}
- spellCheck={false}
- className="min-h-[480px] w-full resize-none rounded-xl border border-[var(--border)] bg-transparent px-5 py-4 font-mono text-[13px] leading-7 text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
- placeholder={tab.placeholder}
- />
- <p className="mt-2 text-[11px] text-[var(--muted-foreground)]/40">
- {t("Cmd+S to save · Markdown supported")}
- </p>
- </div>
- ) : editorValue.trim() ? (
- <div className="rounded-xl border border-[var(--border)] px-6 py-5">
- <MarkdownRenderer
- content={editorValue}
- variant="prose"
- className="text-[14px] leading-relaxed"
- />
- </div>
- ) : (
- <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
- <div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
- <Brain size={18} />
- </div>
- <p className="text-[14px] font-medium text-[var(--foreground)]">
- {t("No {{label}} yet", { label: t(tab.label).toLowerCase() })}
- </p>
- <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
- {t("Refresh from a session or write directly in the editor.")}
- </p>
- </div>
- )}
- </div>
- );
-}
diff --git a/web/lib/memory-graph.ts b/web/lib/memory-graph.ts
new file mode 100644
index 000000000..932448287
--- /dev/null
+++ b/web/lib/memory-graph.ts
@@ -0,0 +1,742 @@
+// Memory graph data layer: fetch L1/L2/L3 from the workbench APIs,
+// parse markdown citations, build nodes + edges, compute a concentric
+// layout. Pure TypeScript so the React component stays thin.
+
+import { apiFetch, apiUrl } from "@/lib/api";
+
+export type Surface =
+ | "chat"
+ | "notebook"
+ | "quiz"
+ | "kb"
+ | "book"
+ | "tutorbot"
+ | "cowriter";
+
+export const SURFACES: Surface[] = [
+ "chat",
+ "notebook",
+ "quiz",
+ "kb",
+ "book",
+ "tutorbot",
+ "cowriter",
+];
+
+export type L3Slot = "profile" | "recent" | "scope";
+export const L3_SLOTS: L3Slot[] = ["profile", "recent", "scope"];
+
+export type Layer = "L1" | "L2" | "L3";
+
+export interface L1Entity {
+ id: string;
+ label: string;
+ ts: string;
+ content: string;
+}
+
+export interface ParsedEntry {
+ // entry ULID like ``m_01KS...``
+ id: string;
+ section: string;
+ text: string;
+ // raw ref strings as they appear in the footnote table
+ refs: string[];
+}
+
+export interface ParsedDoc {
+ title: string;
+ entries: ParsedEntry[];
+}
+
+// ── Node + edge schema ────────────────────────────────────────────────
+
+export interface GraphNode {
+ id: string; // unique key across all layers
+ layer: Layer;
+ // L1: surface; L2: surface; L3: slot
+ cluster: string;
+ // For L2/L3 entries: section heading within the doc
+ section?: string;
+ label: string; // tooltip header
+ preview: string; // hover body
+ // Click navigation target
+ href: string;
+ // Layout (filled in by layoutGraph)
+ x: number;
+ y: number;
+ r: number;
+}
+
+export interface GraphEdge {
+ source: string;
+ target: string;
+ // ``strong`` when the target is a specific entry; ``soft`` when only
+ // the surface was cited (L3 → L2 cluster).
+ kind: "strong" | "soft";
+}
+
+export interface MemoryGraph {
+ nodes: GraphNode[];
+ edges: GraphEdge[];
+ clusters: ClusterMeta[];
+ // Adjacency lookup keyed by node id
+ adjacency: Map<string, string[]>;
+ // Maps node id → its cluster id
+ nodeCluster: Map<string, string>;
+}
+
+export interface ClusterMeta {
+ id: string;
+ layer: Layer;
+ key: string; // surface or slot name
+ label: string;
+ // Center of the cluster's bounding pie slice (used for soft edges
+ // and the cluster halo).
+ cx: number;
+ cy: number;
+ // Pie slice geometry
+ startAngle: number;
+ endAngle: number;
+ innerRadius: number;
+ outerRadius: number;
+ count: number;
+}
+
+// ── Parsing ───────────────────────────────────────────────────────────
+
+// Bullet shapes accepted by the consolidator (see services/memory/document.py):
+// - "- text [^1], [^3] <!--m_xxx-->" (new layout)
+// - "- text [^m_xxx]" (legacy)
+const ENTRY_ID = "m_[0-9A-HJKMNP-TV-Z]{26}";
+const NEW_BULLET_RE = new RegExp(
+ String.raw`^\s*-\s+(.*?)((?:\s*,?\s*\[\^[^\]]+\])*)\s*<!--\s*(` +
+ ENTRY_ID +
+ String.raw`)\s*-->\s*$`,
+);
+const OLD_BULLET_RE = new RegExp(
+ String.raw`^\s*-\s+(.*?)\[\^(` + ENTRY_ID + String.raw`)\]\s*$`,
+);
+const NEW_FOOTNOTE_RE = /^\[\^([^\]]+)\]:\s*(.*?)\s*$/;
+const OLD_FOOTNOTE_RE = new RegExp(
+ String.raw`^\[\^(` + ENTRY_ID + String.raw`)\]:\s*(.*?)\s*$`,
+);
+const MARKER_RE = /\[\^([^\]]+)\]/g;
+
+export function parseDoc(content: string): ParsedDoc {
+ const lines = content.split(/\r?\n/);
+ let title = "";
+ let section = "";
+ const entries: ParsedEntry[] = [];
+ // Map label → ref(s). Legacy footnotes can carry a comma-separated
+ // list, new ones carry a single ref.
+ const footnotes = new Map<string, string[]>();
+
+ for (const raw of lines) {
+ const line = raw.trimEnd();
+ if (!line) continue;
+ if (line.startsWith("# ") && !title) {
+ title = line.slice(2).trim();
+ continue;
+ }
+ if (line.startsWith("## ")) {
+ section = line.slice(3).trim();
+ continue;
+ }
+ if (line === "---") continue;
+
+ const mNew = NEW_BULLET_RE.exec(line);
+ if (mNew) {
+ const [, text, markersBlock, id] = mNew;
+ const markerIds = Array.from(
+ markersBlock.matchAll(MARKER_RE),
+ (m) => m[1],
+ );
+ entries.push({
+ id,
+ section,
+ text: text.trim(),
+ // Defer ref resolution until we've finished collecting footnotes.
+ refs: markerIds,
+ });
+ continue;
+ }
+
+ const mOld = OLD_BULLET_RE.exec(line);
+ if (mOld) {
+ const [, text, id] = mOld;
+ entries.push({ id, section, text: text.trim(), refs: [id] });
+ continue;
+ }
+
+ const mOldFn = OLD_FOOTNOTE_RE.exec(line);
+ if (mOldFn) {
+ const [, id, payload] = mOldFn;
+ footnotes.set(
+ id,
+ payload
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean),
+ );
+ continue;
+ }
+
+ const mNewFn = NEW_FOOTNOTE_RE.exec(line);
+ if (mNewFn) {
+ const [, label, ref] = mNewFn;
+ const cur = footnotes.get(label) ?? [];
+ cur.push(ref.trim());
+ footnotes.set(label, cur);
+ continue;
+ }
+ }
+
+ // Resolve marker labels → actual ref strings.
+ for (const entry of entries) {
+ const resolved: string[] = [];
+ for (const marker of entry.refs) {
+ const refs = footnotes.get(marker);
+ if (refs && refs.length) {
+ for (const r of refs) if (r && !resolved.includes(r)) resolved.push(r);
+ } else if (marker.startsWith("m_")) {
+ // Legacy bullet where the marker *is* the entry id; refs come
+ // from a separate footnote we may already have stored.
+ } else {
+ // Unknown label — keep it so the graph at least shows a stub.
+ resolved.push(marker);
+ }
+ }
+ entry.refs = resolved;
+ }
+
+ return { title, entries };
+}
+
+// Split a footnote ref like "chat:unified_xxx" into surface + id.
+// The id is allowed to contain colons (e.g. ``quiz:unified_xxx:q_1`` →
+// surface=quiz, id=unified_xxx:q_1).
+export function splitRef(ref: string): { surface: string; entityId: string } {
+ const idx = ref.indexOf(":");
+ if (idx < 0) return { surface: ref, entityId: "" };
+ return { surface: ref.slice(0, idx), entityId: ref.slice(idx + 1) };
+}
+
+// ── Fetching ──────────────────────────────────────────────────────────
+
+interface SnapshotResponse {
+ entities: L1Entity[];
+}
+
+interface DocResponse {
+ content: string;
+}
+
+export interface RawMemorySnapshot {
+ l1: Record<Surface, L1Entity[]>;
+ l2: Record<Surface, ParsedDoc>;
+ l3: Record<L3Slot, ParsedDoc>;
+}
+
+export async function fetchMemorySnapshot(): Promise<RawMemorySnapshot> {
+ const l1Promises = SURFACES.map(async (s): Promise<[Surface, L1Entity[]]> => {
+ try {
+ const res = await apiFetch(apiUrl(`/api/v1/memory/snapshot/${s}`));
+ const data = (await res.json()) as SnapshotResponse;
+ return [s, data?.entities ?? []];
+ } catch {
+ return [s, []];
+ }
+ });
+
+ const l2Promises = SURFACES.map(async (s): Promise<[Surface, ParsedDoc]> => {
+ try {
+ const res = await apiFetch(apiUrl(`/api/v1/memory/doc/L2/${s}`));
+ const data = (await res.json()) as DocResponse;
+ return [s, parseDoc(data?.content ?? "")];
+ } catch {
+ return [s, { title: "", entries: [] }];
+ }
+ });
+
+ const l3Promises = L3_SLOTS.map(async (slot): Promise<[L3Slot, ParsedDoc]> => {
+ try {
+ const res = await apiFetch(apiUrl(`/api/v1/memory/doc/L3/${slot}`));
+ const data = (await res.json()) as DocResponse;
+ return [slot, parseDoc(data?.content ?? "")];
+ } catch {
+ return [slot, { title: "", entries: [] }];
+ }
+ });
+
+ const [l1Entries, l2Entries, l3Entries] = await Promise.all([
+ Promise.all(l1Promises),
+ Promise.all(l2Promises),
+ Promise.all(l3Promises),
+ ]);
+
+ const l1 = Object.fromEntries(l1Entries) as Record<Surface, L1Entity[]>;
+ const l2 = Object.fromEntries(l2Entries) as Record<Surface, ParsedDoc>;
+ const l3 = Object.fromEntries(l3Entries) as Record<L3Slot, ParsedDoc>;
+ return { l1, l2, l3 };
+}
+
+// ── Layout (concentric clusters) ─────────────────────────────────────
+
+export interface LayoutOptions {
+ // Display size (the layout is centered at width/2, height/2).
+ width: number;
+ height: number;
+ // Inner ring (L3) radius range.
+ l3InnerRadius: number;
+ l3OuterRadius: number;
+ // Middle ring (L2) radius range.
+ l2InnerRadius: number;
+ l2OuterRadius: number;
+ // Outer ring (L1) radius range.
+ l1InnerRadius: number;
+ l1OuterRadius: number;
+ // Padding between adjacent cluster slices, in radians. ``clusterGap``
+ // applies to L1/L2 (7-way split, narrow gaps look right); the L3 ring
+ // only has three clusters, so it gets its own (larger) gap.
+ clusterGap: number;
+ l3ClusterGap: number;
+}
+
+export const DEFAULT_LAYOUT: LayoutOptions = {
+ width: 1200,
+ height: 1200,
+ l3InnerRadius: 70,
+ l3OuterRadius: 190,
+ l2InnerRadius: 240,
+ l2OuterRadius: 360,
+ l1InnerRadius: 400,
+ l1OuterRadius: 570,
+ clusterGap: 0.05,
+ l3ClusterGap: 0.22,
+};
+
+// Build nodes + edges + cluster metadata + layout coordinates.
+export function buildGraph(
+ snap: RawMemorySnapshot,
+ opts: LayoutOptions = DEFAULT_LAYOUT,
+): MemoryGraph {
+ const { width, height } = opts;
+ const cx = width / 2;
+ const cy = height / 2;
+
+ const nodes: GraphNode[] = [];
+ const edges: GraphEdge[] = [];
+ const clusters: ClusterMeta[] = [];
+ const adjacency = new Map<string, string[]>();
+ const nodeCluster = new Map<string, string>();
+
+ // Pre-dedupe per surface / slot so React keys stay unique AND the
+ // cluster counts driving angular allocation match what we actually
+ // render. Quiz L1 is the offender today — one row per question
+ // variant, with the same composite ``unified_xxx:q_N`` id appearing
+ // twice or more in the same snapshot.
+ const dedupedL1: Record<Surface, L1Entity[]> = {} as Record<Surface, L1Entity[]>;
+ for (const s of SURFACES) {
+ const seen = new Set<string>();
+ dedupedL1[s] = snap.l1[s].filter((e) => {
+ if (seen.has(e.id)) return false;
+ seen.add(e.id);
+ return true;
+ });
+ }
+ const dedupedL2: Record<Surface, ParsedEntry[]> = {} as Record<Surface, ParsedEntry[]>;
+ for (const s of SURFACES) {
+ const seen = new Set<string>();
+ dedupedL2[s] = snap.l2[s].entries.filter((e) => {
+ if (seen.has(e.id)) return false;
+ seen.add(e.id);
+ return true;
+ });
+ }
+ const dedupedL3: Record<L3Slot, ParsedEntry[]> = {} as Record<L3Slot, ParsedEntry[]>;
+ for (const slot of L3_SLOTS) {
+ const seen = new Set<string>();
+ dedupedL3[slot] = snap.l3[slot].entries.filter((e) => {
+ if (seen.has(e.id)) return false;
+ seen.add(e.id);
+ return true;
+ });
+ }
+
+ // ── Build L3 cluster geometry: slot arcs proportional to count.
+ // Place ``profile`` first so the most-meaningful summary sits at
+ // 12 o'clock when the canvas first renders.
+ const l3Counts = L3_SLOTS.map((s) => dedupedL3[s].length);
+ const l3Total = l3Counts.reduce((a, b) => a + b, 0) || 1;
+ const l3MinFrac = 0.12; // 43° floor — keeps even empty slots labelable
+ const l3MinPool = l3MinFrac * L3_SLOTS.length;
+ const l3ElasticPool = Math.max(0, 1 - l3MinPool);
+ const l3Frac = l3Counts.map(
+ (c) => l3MinFrac + (c / l3Total) * l3ElasticPool,
+ );
+ const l3FracSum = l3Frac.reduce((a, b) => a + b, 0);
+ for (let i = 0; i < l3Frac.length; i++) l3Frac[i] /= l3FracSum;
+
+ const l3ClusterMap = new Map<string, ClusterMeta>();
+ let l3Cursor = -Math.PI / 2;
+ L3_SLOTS.forEach((slot, idx) => {
+ const span = l3Frac[idx] * 2 * Math.PI;
+ const start = l3Cursor + opts.l3ClusterGap / 2;
+ const end = l3Cursor + span - opts.l3ClusterGap / 2;
+ l3Cursor += span;
+ const mid = (start + end) / 2;
+ const r = (opts.l3InnerRadius + opts.l3OuterRadius) / 2;
+ const cluster: ClusterMeta = {
+ id: `L3:${slot}`,
+ layer: "L3",
+ key: slot,
+ label: L3_LABEL[slot],
+ cx: cx + Math.cos(mid) * r,
+ cy: cy + Math.sin(mid) * r,
+ startAngle: start,
+ endAngle: end,
+ innerRadius: opts.l3InnerRadius,
+ outerRadius: opts.l3OuterRadius,
+ count: dedupedL3[slot].length,
+ };
+ clusters.push(cluster);
+ l3ClusterMap.set(slot, cluster);
+ });
+
+ // ── Build L2 + L1 cluster geometry: angular share per surface is
+ // proportional to the *combined* L1+L2 count so dense surfaces own
+ // a bigger arc and the whole outer ring stays uniformly dense.
+ // Each surface gets a minimum slice so tiny ones (book, tutorbot)
+ // still register visually.
+ const minSliceFraction = 0.025; // ≈ 9° floor
+ const rawWeights = SURFACES.map((s) => dedupedL1[s].length + dedupedL2[s].length);
+ const totalRaw = rawWeights.reduce((a, b) => a + b, 0) || 1;
+ const minPool = minSliceFraction * SURFACES.length;
+ const elasticPool = Math.max(0, 1 - minPool);
+ const surfaceFraction = rawWeights.map(
+ (w) => minSliceFraction + (w / totalRaw) * elasticPool,
+ );
+ // Renormalise (rounding can drift it off 1.0).
+ const sumFrac = surfaceFraction.reduce((a, b) => a + b, 0);
+ for (let i = 0; i < surfaceFraction.length; i++) surfaceFraction[i] /= sumFrac;
+
+ const l2ClusterMap = new Map<string, ClusterMeta>();
+ const l1ClusterMap = new Map<string, ClusterMeta>();
+ let cursor = -Math.PI / 2;
+ SURFACES.forEach((surf, idx) => {
+ const span = surfaceFraction[idx] * 2 * Math.PI;
+ const start = cursor + opts.clusterGap / 2;
+ const end = cursor + span - opts.clusterGap / 2;
+ cursor += span;
+ const mid = (start + end) / 2;
+ const r2 = (opts.l2InnerRadius + opts.l2OuterRadius) / 2;
+ const r1 = (opts.l1InnerRadius + opts.l1OuterRadius) / 2;
+ const c2: ClusterMeta = {
+ id: `L2:${surf}`,
+ layer: "L2",
+ key: surf,
+ label: SURFACE_LABEL[surf],
+ cx: cx + Math.cos(mid) * r2,
+ cy: cy + Math.sin(mid) * r2,
+ startAngle: start,
+ endAngle: end,
+ innerRadius: opts.l2InnerRadius,
+ outerRadius: opts.l2OuterRadius,
+ count: dedupedL2[surf].length,
+ };
+ const c1: ClusterMeta = {
+ id: `L1:${surf}`,
+ layer: "L1",
+ key: surf,
+ label: SURFACE_LABEL[surf],
+ cx: cx + Math.cos(mid) * r1,
+ cy: cy + Math.sin(mid) * r1,
+ startAngle: start,
+ endAngle: end,
+ innerRadius: opts.l1InnerRadius,
+ outerRadius: opts.l1OuterRadius,
+ count: dedupedL1[surf].length,
+ };
+ clusters.push(c2);
+ clusters.push(c1);
+ l2ClusterMap.set(surf, c2);
+ l1ClusterMap.set(surf, c1);
+ });
+
+ const center = { x: cx, y: cy };
+
+ // ── Place L3 nodes inside their slice.
+ L3_SLOTS.forEach((slot) => {
+ const cluster = l3ClusterMap.get(slot)!;
+ const entries = dedupedL3[slot];
+ placeNodesInSlice(entries.length, cluster, center, (i) => {
+ const entry = entries[i];
+ const id = `L3:${slot}:${entry.id}`;
+ nodeCluster.set(id, cluster.id);
+ return {
+ id,
+ layer: "L3",
+ cluster: cluster.id,
+ section: entry.section,
+ label: `${cluster.label} · ${entry.section || ""}`.trim(),
+ preview: entry.text,
+ href: `/memory/l3/${slot}`,
+ x: 0,
+ y: 0,
+ r: 6,
+ } satisfies Omit<GraphNode, "x" | "y" | "r"> & {
+ x: number;
+ y: number;
+ r: number;
+ };
+ }).forEach((n) => nodes.push(n));
+ });
+
+ // ── Place L2 nodes inside their slice.
+ // Track entry ULID → node id so L3 footnotes that cite specific
+ // ``m_xxx`` entries (the future-proof path) can wire up cleanly.
+ const l2EntryNodeIdx = new Map<string, string>();
+ SURFACES.forEach((surf) => {
+ const cluster = l2ClusterMap.get(surf)!;
+ const entries = dedupedL2[surf];
+ placeNodesInSlice(entries.length, cluster, center, (i) => {
+ const entry = entries[i];
+ const id = `L2:${surf}:${entry.id}`;
+ l2EntryNodeIdx.set(entry.id, id);
+ nodeCluster.set(id, cluster.id);
+ return {
+ id,
+ layer: "L2",
+ cluster: cluster.id,
+ section: entry.section,
+ label: `${cluster.label} · ${entry.section || ""}`.trim(),
+ preview: entry.text,
+ href: `/memory/l2/${surf}`,
+ x: 0,
+ y: 0,
+ r: 4.5,
+ } satisfies Omit<GraphNode, "x" | "y" | "r"> & {
+ x: number;
+ y: number;
+ r: number;
+ };
+ }).forEach((n) => nodes.push(n));
+ });
+
+ // ── Place L1 nodes inside their slice.
+ const l1EntityNodeIdx = new Map<string, string>(); // ``${surf}:${id}`` → node id
+ SURFACES.forEach((surf) => {
+ const cluster = l1ClusterMap.get(surf)!;
+ const entities = dedupedL1[surf];
+ placeNodesInSlice(entities.length, cluster, center, (i) => {
+ const entity = entities[i];
+ const id = `L1:${surf}:${entity.id}`;
+ l1EntityNodeIdx.set(`${surf}:${entity.id}`, id);
+ nodeCluster.set(id, cluster.id);
+ return {
+ id,
+ layer: "L1",
+ cluster: cluster.id,
+ label: entity.label || entity.id,
+ preview: entity.content?.slice(0, 280) ?? "",
+ href: `/memory/l1?surface=${surf}&ref=${encodeURIComponent(
+ `${surf}:${entity.id}`,
+ )}`,
+ x: 0,
+ y: 0,
+ r: 2.8,
+ } satisfies Omit<GraphNode, "x" | "y" | "r"> & {
+ x: number;
+ y: number;
+ r: number;
+ };
+ }).forEach((n) => nodes.push(n));
+ });
+
+ // ── Edges. L2 → L1 (specific entity), L3 → L2 (specific entry OR
+ // soft to surface cluster centroid).
+ const pushEdge = (e: GraphEdge) => {
+ edges.push(e);
+ if (!adjacency.has(e.source)) adjacency.set(e.source, []);
+ if (!adjacency.has(e.target)) adjacency.set(e.target, []);
+ adjacency.get(e.source)!.push(e.target);
+ adjacency.get(e.target)!.push(e.source);
+ };
+
+ SURFACES.forEach((surf) => {
+ for (const entry of dedupedL2[surf]) {
+ const sourceId = `L2:${surf}:${entry.id}`;
+ for (const ref of entry.refs) {
+ const { surface: s, entityId } = splitRef(ref);
+ if (!s || !entityId) continue;
+ const targetId = l1EntityNodeIdx.get(`${s}:${entityId}`);
+ if (targetId) {
+ pushEdge({ source: sourceId, target: targetId, kind: "strong" });
+ }
+ }
+ }
+ });
+
+ // Soft edges from L3 → L2 cluster centroid synthetic node. Real L3
+ // citations today are surface-level ("chat"), so we add one synthetic
+ // anchor per surface that lives at the cluster's geometric centroid.
+ // Synthetic anchors are hidden from the user (rendered as a faint
+ // halo) but appear in the adjacency map so hover highlighting can
+ // light up the whole surface.
+ const surfaceAnchors = new Map<string, string>();
+ SURFACES.forEach((surf) => {
+ const cluster = l2ClusterMap.get(surf)!;
+ const id = `L2:${surf}:__anchor__`;
+ surfaceAnchors.set(surf, id);
+ nodeCluster.set(id, cluster.id);
+ nodes.push({
+ id,
+ layer: "L2",
+ cluster: cluster.id,
+ label: cluster.label,
+ preview: `${cluster.label} surface`,
+ href: `/memory/l2/${surf}`,
+ x: cluster.cx,
+ y: cluster.cy,
+ // Hidden — see GraphView. We keep ``r = 0`` so hit-testing skips it.
+ r: 0,
+ });
+ });
+
+ L3_SLOTS.forEach((slot) => {
+ for (const entry of dedupedL3[slot]) {
+ const sourceId = `L3:${slot}:${entry.id}`;
+ // Track which surfaces this L3 entry cites so we don't draw
+ // duplicate edges into the same cluster anchor.
+ const cited = new Set<string>();
+ for (const ref of entry.refs) {
+ // ``ref`` here is the *resolved* footnote payload, e.g.
+ // ``chat`` → surface-level
+ // ``chat:m_01KS...`` (future) → specific L2 entry
+ const { surface: s, entityId } = splitRef(ref);
+ if (s && entityId.startsWith("m_")) {
+ const targetId = l2EntryNodeIdx.get(entityId);
+ if (targetId) {
+ pushEdge({ source: sourceId, target: targetId, kind: "strong" });
+ cited.add(s);
+ }
+ } else if (!s && (SURFACES as readonly string[]).includes(ref)) {
+ if (cited.has(ref)) continue;
+ const anchor = surfaceAnchors.get(ref);
+ if (anchor) {
+ pushEdge({ source: sourceId, target: anchor, kind: "soft" });
+ cited.add(ref);
+ }
+ } else if (s && (SURFACES as readonly string[]).includes(s)) {
+ if (cited.has(s)) continue;
+ const anchor = surfaceAnchors.get(s);
+ if (anchor) {
+ pushEdge({ source: sourceId, target: anchor, kind: "soft" });
+ cited.add(s);
+ }
+ }
+ }
+ }
+ });
+
+ return { nodes, edges, clusters, adjacency, nodeCluster };
+}
+
+// Spread ``count`` points across a pie-slice using a deterministic
+// jittered-grid: divide the annular slice into a roughly hex-packed
+// lattice, then perturb each lattice point with a stable hash so the
+// cluster reads as a soft galaxy rather than a starburst.
+function placeNodesInSlice<T extends { x: number; y: number; r: number }>(
+ count: number,
+ cluster: ClusterMeta,
+ center: { x: number; y: number },
+ factory: (i: number) => T,
+): T[] {
+ if (count === 0) return [];
+ const out: T[] = [];
+ const sliceSpan = cluster.endAngle - cluster.startAngle;
+ const pad = 8;
+ const inner = cluster.innerRadius + pad;
+ const outer = cluster.outerRadius - pad;
+ // Decide how many radial rows to use based on the cluster's area.
+ // A thin sector with few items uses one row; a thick sector with
+ // hundreds of items uses many.
+ const sliceArea = ((outer * outer - inner * inner) * sliceSpan) / 2;
+ // Target one point per ~sqrt(area/count) square area.
+ const densityCell = Math.sqrt(sliceArea / Math.max(1, count));
+ // Number of radial rows ≈ thickness / cell size.
+ const thickness = outer - inner;
+ const rows = Math.max(1, Math.round(thickness / densityCell));
+ // Per-row capacity allocated by arc length (proportional to radius).
+ const rowMidR = (r: number) => inner + (thickness * (r + 0.5)) / rows;
+ const totalCapacity = (() => {
+ let sum = 0;
+ for (let r = 0; r < rows; r++) {
+ sum += (rowMidR(r) * sliceSpan) / densityCell;
+ }
+ return sum;
+ })();
+ // Map item index i to (row, slot within row).
+ type Slot = { row: number; col: number; cols: number };
+ const slots: Slot[] = [];
+ let acc = 0;
+ for (let r = 0; r < rows; r++) {
+ const rowCols = Math.max(
+ 1,
+ Math.round((count * (rowMidR(r) * sliceSpan)) / (densityCell * totalCapacity)),
+ );
+ for (let c = 0; c < rowCols; c++) {
+ slots.push({ row: r, col: c, cols: rowCols });
+ }
+ acc += rowCols;
+ if (acc >= count) break;
+ }
+ // Fill remaining slots if rounding under-shot; pad by re-using the
+ // outermost row.
+ while (slots.length < count) {
+ const r = rows - 1;
+ slots.push({ row: r, col: slots.length, cols: slots[slots.length - 1].cols + 1 });
+ }
+ // Deterministic pseudo-random for jitter, indexed by item id.
+ const hash = (n: number) => {
+ let x = (n + 1) * 2654435761;
+ x = (x ^ (x >>> 13)) >>> 0;
+ return ((x * 1597334677) >>> 0) / 4294967296;
+ };
+ for (let i = 0; i < count; i++) {
+ const slot = slots[i];
+ const rowMid = rowMidR(slot.row);
+ const colFrac = (slot.col + 0.5) / slot.cols;
+ // Hex offset: alternate rows shift by half a column.
+ const colShift = slot.row % 2 === 0 ? 0 : 0.5 / slot.cols;
+ const a =
+ cluster.startAngle + sliceSpan * (colFrac + colShift) +
+ (hash(i) - 0.5) * (sliceSpan / slot.cols) * 0.45;
+ const r =
+ rowMid + (hash(i + 9311) - 0.5) * Math.min(densityCell * 0.85, thickness / rows);
+ const node = factory(i);
+ node.x = center.x + Math.cos(a) * r;
+ node.y = center.y + Math.sin(a) * r;
+ out.push(node);
+ }
+ return out;
+}
+
+// ── Display labels ───────────────────────────────────────────────────
+
+export const SURFACE_LABEL: Record<Surface, string> = {
+ chat: "Chat",
+ notebook: "Notebook",
+ quiz: "Quiz",
+ kb: "Knowledge base",
+ book: "Book",
+ tutorbot: "TutorBot",
+ cowriter: "Co-writer",
+};
+
+export const L3_LABEL: Record<L3Slot, string> = {
+ profile: "Profile",
+ recent: "Recent",
+ scope: "Scope",
+};