DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(learning): expose a durable workspace journal overview (#1407)
Bingxi Zhao (Frank)64bc0d8e7c8c
diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.pyindex cb813b21f..51219c949 100644--- a/deeptutor/agents/_shared/tool_composition.py+++ b/deeptutor/agents/_shared/tool_composition.py@@ -190,7 +190,7 @@ def compose_enabled_tools(KB is attached, ``read_source`` if a source index exists, …).3. Active loop capabilities' *owned* tools (``capability_owned``) — thecapability's own tools, added on top.- 4. Always-on auto-mounts (``write_memory`` / ``web_fetch`` / ``github`` /+ 4. Always-on auto-mounts (``write_memory`` / ``learning_status`` / ``learning_update`` / ``web_fetch`` / ``github`` /``ask_user`` / ``cron``).A loop capability (solve, mastery) reuses the *full* chat surface and only@@ -259,7 +259,15 @@ def compose_enabled_tools(if getattr(mount_flags, flag) and _builtin_allowed(tool_name):composed.append(tool_name)composed.extend(str(name) for name in capability_owned if str(name).strip())- for always_on in ("write_memory", "web_fetch", "github", "ask_user", "cron"):+ for always_on in (+ "write_memory",+ "learning_status",+ "learning_update",+ "web_fetch",+ "github",+ "ask_user",+ "cron",+ ):if _builtin_allowed(always_on):composed.append(always_on)return _finalize([*WORKSPACE_BASELINE_TOOLS, *composed], forced, suppressed)diff --git a/deeptutor/agents/loop/context_budget.py b/deeptutor/agents/loop/context_budget.pyindex 56237ce12..c9de8cd7e 100644--- a/deeptutor/agents/loop/context_budget.py+++ b/deeptutor/agents/loop/context_budget.py@@ -42,6 +42,7 @@ _BLOCK_SEGMENTS: dict[str, str] = {"persona_style": "persona_style","partner_turn_policy": "partner_turn_policy","memory": "memory",+ "learning_journal": "learning_journal","tools": "tool_manifest","knowledge_base_note": "knowledge_base_note","skills": "skills",diff --git a/deeptutor/agents/loop/prompt_blocks.py b/deeptutor/agents/loop/prompt_blocks.pyindex 47cb7473b..5bd5ba256 100644--- a/deeptutor/agents/loop/prompt_blocks.py+++ b/deeptutor/agents/loop/prompt_blocks.py@@ -28,6 +28,7 @@ RUNTIME_BLOCK_NAMES = frozenset({"runtime_context","memory",+ "learning_journal","learner_profile","sources","notebooks",@@ -162,6 +163,11 @@ class LoopPromptAssembler:blocks.append(PromptBlock("partner_turn_policy", partner_policy))if context.memory_context:blocks.append(PromptBlock("memory", context.memory_context))+ # Carried-over learning state sits with memory rather than behind a+ # tool call: a learner who says "继续上次那个" in a brand-new+ # conversation expects the tutor to already know what "上次" was.+ if context.learning_journal_context:+ blocks.append(PromptBlock("learning_journal", context.learning_journal_context))if include_tool_manifest:tools = tool_manifest or self._fallback_empty_tool_list()if kb_note:diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex bef13a253..d4a72a29c 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -536,6 +536,7 @@ from deeptutor.api.routers import (file_preview,imports,knowledge,+ learning_journal,marginnote4,mastery_path,mcp_settings,@@ -649,6 +650,12 @@ app.include_router(dependencies=_auth,)app.include_router(memory.router, prefix="/api/memory", tags=["memory"], dependencies=_auth)+app.include_router(+ learning_journal.router,+ prefix="/api/learning-journal",+ tags=["learning-journal"],+ dependencies=_auth,+)app.include_router(capabilities_settings.router,prefix="/api/capabilities",diff --git a/deeptutor/api/routers/learning_journal.py b/deeptutor/api/routers/learning_journal.pynew file mode 100644index 000000000..9617bbd14--- /dev/null+++ b/deeptutor/api/routers/learning_journal.py@@ -0,0 +1,18 @@+"""Read-only view of the workspace's conversational learning journal."""++from fastapi import APIRouter, HTTPException++from deeptutor.services.learning_journal import get_learning_journal_store++router = APIRouter()+++def overview():+ try:+ return get_learning_journal_store().overview()+ except (OSError, ValueError) as exc:+ raise HTTPException(+ status_code=409,+ detail="Learning journal could not be read. Its original file has been preserved.",+ ) from excdiff --git a/deeptutor/core/context.py b/deeptutor/core/context.pyindex 1f7d74175..b97701633 100644--- a/deeptutor/core/context.py+++ b/deeptutor/core/context.py@@ -105,6 +105,7 @@ class UnifiedContext:config_overrides: Per-request config tweaks (e.g. temperature).language: UI / response language ("en" | "zh").memory_context: Memory text in the latest runtime-context snapshot.+ learning_journal_context: Mission and handoff snapshot taken at turn start.persona_context: Selected persona's instructions, eagerly injectedinto the system prompt (a persona must shape the voice from thefirst token; empty when no persona is active).@@ -137,6 +138,7 @@ class UnifiedContext:config_overrides: dict[str, Any] = field(default_factory=dict)language: str = "en"memory_context: str = ""+ learning_journal_context: str = ""persona_context: str = ""sidebar_context: str = ""skills_manifest: str = ""diff --git a/deeptutor/services/learning_journal/__init__.py b/deeptutor/services/learning_journal/__init__.pynew file mode 100644index 000000000..eebb1c14c--- /dev/null+++ b/deeptutor/services/learning_journal/__init__.py@@ -0,0 +1,28 @@+"""Stateful learning journal — soft multi-session teaching state (#740).++Complements Mastery Path (hard curriculum gates) and Memory (preferences /+profile). Stores a mission, last-session handoff, and ADR-style learning+records under the per-user workspace. Not a second mastery engine.+"""++from __future__ import annotations++from deeptutor.services.learning_journal.models import (+ LearningJournal,+ LearningMission,+ LearningRecord,+ LearningSessionNote,+)+from deeptutor.services.learning_journal.store import (+ LearningJournalStore,+ get_learning_journal_store,+)++__all__ = [+ "LearningJournal",+ "LearningJournalStore",+ "LearningMission",+ "LearningRecord",+ "LearningSessionNote",+ "get_learning_journal_store",+]diff --git a/deeptutor/services/learning_journal/models.py b/deeptutor/services/learning_journal/models.pynew file mode 100644index 000000000..006b19922--- /dev/null+++ b/deeptutor/services/learning_journal/models.py@@ -0,0 +1,143 @@+"""Dataclasses for the learning journal aggregate."""++from __future__ import annotations++from dataclasses import asdict, dataclass, field+from datetime import datetime, timezone+from typing import Any+++def _utc_now() -> str:+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")+++@dataclass(slots=True)+class LearningMission:+ """Why the learner is studying — grounds subsequent sessions."""++ topic: str = ""+ why: str = ""+ level: str = ""+ updated_at: str = ""++ def is_empty(self) -> bool:+ return not (self.topic.strip() or self.why.strip() or self.level.strip())++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)++ @classmethod+ def from_dict(cls, raw: Any) -> LearningMission:+ if not isinstance(raw, dict):+ return cls()+ return cls(+ topic=str(raw.get("topic") or "").strip(),+ why=str(raw.get("why") or "").strip(),+ level=str(raw.get("level") or "").strip(),+ updated_at=str(raw.get("updated_at") or "").strip(),+ )+++@dataclass(slots=True)+class LearningSessionNote:+ """Handoff between sessions: what happened and what to do next."""++ summary: str = ""+ next_focus: str = ""+ updated_at: str = ""++ def is_empty(self) -> bool:+ return not (self.summary.strip() or self.next_focus.strip())++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)++ @classmethod+ def from_dict(cls, raw: Any) -> LearningSessionNote:+ if not isinstance(raw, dict):+ return cls()+ return cls(+ summary=str(raw.get("summary") or "").strip(),+ next_focus=str(raw.get("next_focus") or "").strip(),+ updated_at=str(raw.get("updated_at") or "").strip(),+ )+++@dataclass(slots=True)+class LearningRecord:+ """One durable insight (ADR-style) that shapes the next lesson."""++ id: str+ title: str+ insight: str+ created_at: str = ""++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)++ @classmethod+ def from_dict(cls, raw: Any) -> LearningRecord | None:+ if not isinstance(raw, dict):+ return None+ record_id = str(raw.get("id") or "").strip()+ title = str(raw.get("title") or "").strip()+ insight = str(raw.get("insight") or "").strip()+ if not record_id or not (title or insight):+ return None+ return cls(+ id=record_id,+ title=title,+ insight=insight,+ created_at=str(raw.get("created_at") or "").strip(),+ )+++@dataclass(slots=True)+class LearningJournal:+ """Per-user soft learning state (mission + session + records)."""++ version: int = 1+ updated_at: str = ""+ mission: LearningMission = field(default_factory=LearningMission)+ last_session: LearningSessionNote = field(default_factory=LearningSessionNote)+ records: list[LearningRecord] = field(default_factory=list)++ def is_empty(self) -> bool:+ return self.mission.is_empty() and self.last_session.is_empty() and not self.records++ def to_dict(self) -> dict[str, Any]:+ return {+ "version": self.version,+ "updated_at": self.updated_at,+ "mission": self.mission.to_dict(),+ "last_session": self.last_session.to_dict(),+ "records": [record.to_dict() for record in self.records],+ }++ @classmethod+ def from_dict(cls, raw: Any) -> LearningJournal:+ if not isinstance(raw, dict):+ return cls()+ records: list[LearningRecord] = []+ for item in raw.get("records") or []:+ parsed = LearningRecord.from_dict(item)+ if parsed is not None:+ records.append(parsed)+ return cls(+ version=int(raw.get("version") or 1),+ updated_at=str(raw.get("updated_at") or "").strip(),+ mission=LearningMission.from_dict(raw.get("mission")),+ last_session=LearningSessionNote.from_dict(raw.get("last_session")),+ records=records,+ )++ def touch(self) -> None:+ self.updated_at = _utc_now()+++__all__ = [+ "LearningJournal",+ "LearningMission",+ "LearningRecord",+ "LearningSessionNote",+]diff --git a/deeptutor/services/learning_journal/store.py b/deeptutor/services/learning_journal/store.pynew file mode 100644index 000000000..35b75b606--- /dev/null+++ b/deeptutor/services/learning_journal/store.py@@ -0,0 +1,368 @@+"""File-backed learning journal store (atomic JSON under workspace)."""++from __future__ import annotations++from contextlib import contextmanager+from dataclasses import dataclass+import json+import logging+from pathlib import Path+import sys+import threading+from typing import Literal++from deeptutor.services.file_io import atomic_write_json+from deeptutor.services.learning_journal.models import (+ LearningJournal,+ LearningMission,+ LearningRecord,+ LearningSessionNote,+)+from deeptutor.services.path_service import get_path_service++logger = logging.getLogger(__name__)++JOURNAL_VERSION = 1+MAX_RECORDS = 50+MAX_TOPIC_CHARS = 200+MAX_WHY_CHARS = 800+MAX_LEVEL_CHARS = 40+MAX_SUMMARY_CHARS = 800+MAX_NEXT_FOCUS_CHARS = 400+MAX_TITLE_CHARS = 120+MAX_INSIGHT_CHARS = 800++UpdateOp = Literal["set_mission", "note_session", "add_record"]+++def _clip(text: str, limit: int) -> str:+ cleaned = " ".join(str(text or "").split())+ if len(cleaned) <= limit:+ return cleaned+ return cleaned[: max(0, limit - 1)].rstrip() + "…"+++def _normalize_key(*parts: str) -> str:+ return " ".join(" ".join(parts).split()).casefold()+++@dataclass(frozen=True, slots=True)+class JournalWriteResult:+ accepted: bool+ message: str+ journal: LearningJournal+ record_id: str | None = None+ deduplicated: bool = False+++class LearningJournalStore:+ """Stateless facade; path resolves via the active PathService."""++ def __init__(self) -> None:+ self._locks: dict[str, threading.Lock] = {}++ def journal_path(self) -> Path:+ return get_path_service().get_learning_journal_file()++ def load(self) -> LearningJournal:+ path = self.journal_path()+ try:+ raw = json.loads(path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return LearningJournal(version=JOURNAL_VERSION)+ # Never reinterpret corruption as an empty aggregate before a write.+ if not isinstance(raw, dict) or raw.get("version", 1) != JOURNAL_VERSION:+ raise ValueError("Invalid or unsupported learning journal; original file preserved")+ if not isinstance(raw.get("records", []), list):+ raise ValueError("Invalid learning journal records; original file preserved")+ for key in ("mission", "last_session"):+ value = raw.get(key, {})+ if not isinstance(value, dict) or any(not isinstance(v, str) for v in value.values()):+ raise ValueError(f"Invalid learning journal {key}; original file preserved")+ for record in raw.get("records", []):+ if LearningRecord.from_dict(record) is None:+ raise ValueError("Invalid learning record; original file preserved")+ journal = LearningJournal.from_dict(raw)+ journal.version = JOURNAL_VERSION+ return journal++ def status_markdown(self, *, recent_records: int = 8) -> str:+ journal = self.load()+ if journal.is_empty():+ return (+ "(No learning journal yet. When the user wants to learn a topic "+ "across sessions, call learning_update with op=set_mission, then "+ "note_session / add_record as you teach. Prefer this soft journal "+ "for free-form multi-session study; use Mastery Path tools for "+ "hard curriculum gates.)\n"+ )++ lines: list[str] = ["# Learning journal", ""]+ mission = journal.mission+ if not mission.is_empty():+ lines.append("## Mission")+ lines.extend(self._mission_lines(mission))+ lines.append("")++ session = journal.last_session+ if not session.is_empty():+ lines.append("## Last session")+ lines.extend(self._session_lines(session))+ lines.append("")++ if journal.records:+ lines.append("## Recent learning records")+ for record in reversed(journal.records[-max(1, recent_records) :]):+ title = record.title or "(untitled)"+ lines.append(f"- `{record.id}` **{title}**: {record.insight}")+ lines.append("")++ lines.append(+ "_Use Mastery Path (`mastery_status` / Guided Learning) for scored "+ "curriculum progress; this journal is the soft mission + insight layer._"+ )+ return "\n".join(lines).rstrip() + "\n"++ def overview(self) -> dict:+ """Read-only public snapshot, including the exact injected slice (#1407)."""+ journal = self.load()+ snapshot = journal.to_dict()+ snapshot["records"] = [record.to_dict() for record in reversed(journal.records)]+ snapshot["injected_context"] = self.injection_markdown(journal=journal)+ return snapshot++ def injection_markdown(self, *, journal: LearningJournal | None = None) -> str:+ """The resumable slice of the journal, for the per-turn system prompt.++ Records are left out on purpose, and an empty journal yields ``""`` so+ nothing is injected: both keep a turn's overhead from scaling with+ journal history. ``learning_status`` advertises the journal to the+ model through its own description, so an empty one needs no repeated+ advertisement, and the full history stays one tool call away.+ """+ journal = journal if journal is not None else self.load()+ parts: list[list[str]] = []+ mission_lines = self._mission_lines(journal.mission)+ if mission_lines:+ parts.append(["## Mission", *mission_lines])+ session_lines = self._session_lines(journal.last_session)+ if session_lines:+ parts.append(["## Last session", *session_lines])+ if not parts:+ return ""+ body = "\n\n".join("\n".join(part) for part in parts)+ return (+ "# Learning journal (carried over from earlier sessions)\n\n"+ f"{body}\n\n"+ "_Pick up from where this leaves off, and record what this session "+ "changes with `learning_update`._\n"+ )++ @staticmethod+ def _mission_lines(mission: LearningMission) -> list[str]:+ lines: list[str] = []+ if mission.topic:+ lines.append(f"- Topic: {mission.topic}")+ if mission.why:+ lines.append(f"- Why: {mission.why}")+ if mission.level:+ lines.append(f"- Level: {mission.level}")+ if mission.updated_at:+ lines.append(f"- Updated: {mission.updated_at}")+ return lines++ @staticmethod+ def _session_lines(session: LearningSessionNote) -> list[str]:+ lines: list[str] = []+ if session.summary:+ lines.append(f"- Summary: {session.summary}")+ if session.next_focus:+ lines.append(f"- Next focus: {session.next_focus}")+ if session.updated_at:+ lines.append(f"- Updated: {session.updated_at}")+ return lines++ def set_mission(+ self,+ *,+ topic: str,+ why: str = "",+ level: str = "",+ ) -> JournalWriteResult:+ topic_c = _clip(topic, MAX_TOPIC_CHARS)+ why_c = _clip(why, MAX_WHY_CHARS)+ level_c = _clip(level, MAX_LEVEL_CHARS)+ if not topic_c:+ return JournalWriteResult(+ accepted=False,+ message="set_mission requires a non-empty topic.",+ journal=self.load(),+ )++ def mutate(journal: LearningJournal) -> JournalWriteResult:+ journal.mission = LearningMission(+ topic=topic_c,+ why=why_c,+ level=level_c,+ updated_at=journal.updated_at,+ )+ journal.mission.updated_at = journal.updated_at+ return JournalWriteResult(+ accepted=True,+ message=f"mission set for topic={topic_c!r}.",+ journal=journal,+ )++ return self._mutate(mutate)++ def note_session(+ self,+ *,+ summary: str,+ next_focus: str = "",+ ) -> JournalWriteResult:+ summary_c = _clip(summary, MAX_SUMMARY_CHARS)+ next_c = _clip(next_focus, MAX_NEXT_FOCUS_CHARS)+ if not summary_c and not next_c:+ return JournalWriteResult(+ accepted=False,+ message="note_session requires summary and/or next_focus.",+ journal=self.load(),+ )++ def mutate(journal: LearningJournal) -> JournalWriteResult:+ journal.last_session = LearningSessionNote(+ summary=summary_c,+ next_focus=next_c,+ updated_at=journal.updated_at,+ )+ return JournalWriteResult(+ accepted=True,+ message="session note saved.",+ journal=journal,+ )++ return self._mutate(mutate)++ def add_record(self, *, title: str, insight: str) -> JournalWriteResult:+ title_c = _clip(title, MAX_TITLE_CHARS)+ insight_c = _clip(insight, MAX_INSIGHT_CHARS)+ if not insight_c:+ return JournalWriteResult(+ accepted=False,+ message="add_record requires a non-empty insight.",+ journal=self.load(),+ )+ if not title_c:+ title_c = _clip(insight_c, 60)++ def mutate(journal: LearningJournal) -> JournalWriteResult:+ key = _normalize_key(title_c, insight_c)+ for existing in journal.records:+ if _normalize_key(existing.title, existing.insight) == key:+ return JournalWriteResult(+ accepted=True,+ message=f"record already saved (id={existing.id}); skipped duplicate.",+ journal=journal,+ record_id=existing.id,+ deduplicated=True,+ )+ next_n = self._next_record_number(journal)+ record_id = f"lr_{next_n:04d}"+ journal.records.append(+ LearningRecord(+ id=record_id,+ title=title_c,+ insight=insight_c,+ created_at=journal.updated_at,+ )+ )+ if len(journal.records) > MAX_RECORDS:+ journal.records = journal.records[-MAX_RECORDS:]+ return JournalWriteResult(+ accepted=True,+ message=f"record added (id={record_id}).",+ journal=journal,+ record_id=record_id,+ )++ return self._mutate(mutate)++ def _next_record_number(self, journal: LearningJournal) -> int:+ highest = 0+ for record in journal.records:+ suffix = record.id.removeprefix("lr_")+ if suffix.isdigit():+ highest = max(highest, int(suffix))+ return highest + 1++ def _mutate(self, mutator) -> JournalWriteResult: # noqa: ANN001+ path = self.journal_path()+ lock = self._lock_for(path)+ with lock, self._file_lock(path):+ journal = self.load()+ journal.touch()+ result = mutator(journal)+ if not result.accepted:+ return result+ if not result.deduplicated:+ self._atomic_write(path, result.journal)+ return result++ def _lock_for(self, path: Path) -> threading.Lock:+ key = str(path.resolve())+ lock = self._locks.get(key)+ if lock is None:+ lock = threading.Lock()+ self._locks[key] = lock+ return lock++ def _atomic_write(self, path: Path, journal: LearningJournal) -> None:+ atomic_write_json(path, journal.to_dict())++ @staticmethod+ @contextmanager+ def _file_lock(path: Path):+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.with_suffix(".lock").open("a+b") as handle:+ handle.seek(0)+ if sys.platform == "win32":+ import msvcrt++ if not handle.read(1):+ handle.write(b"\0")+ handle.flush()+ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)+ else:+ import fcntl++ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)+ try:+ yield+ finally:+ handle.seek(0)+ if sys.platform == "win32":+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)+ else:+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)+++_STORE: LearningJournalStore | None = None+++def get_learning_journal_store() -> LearningJournalStore:+ global _STORE+ if _STORE is None:+ _STORE = LearningJournalStore()+ return _STORE+++__all__ = [+ "JOURNAL_VERSION",+ "JournalWriteResult",+ "LearningJournalStore",+ "MAX_RECORDS",+ "UpdateOp",+ "get_learning_journal_store",+]diff --git a/deeptutor/services/path_service.py b/deeptutor/services/path_service.pyindex 9da60822e..380c2671c 100644--- a/deeptutor/services/path_service.py+++ b/deeptutor/services/path_service.py@@ -299,6 +299,13 @@ class PathService:def get_memory_dir(self) -> Path:return self.workspace_root / "memory"+ def get_learning_journal_dir(self) -> Path:+ """Soft multi-session learning journal (#740), sibling of memory."""+ return self.workspace_root / "learning_journal"++ def get_learning_journal_file(self) -> Path:+ return self.get_learning_journal_dir() / "journal.json"+def migrate_legacy_memory_markdown(self) -> bool:"""Move the old workspace memory files into the canonical memory root once.diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.pyindex 4c82029fb..2cacdb7ec 100644--- a/deeptutor/services/session/turns/executor.py+++ b/deeptutor/services/session/turns/executor.py@@ -238,6 +238,7 @@ class TurnExecutor:from deeptutor.agents.notebook import NotebookAnalysisAgentfrom deeptutor.book.context import build_book_contextfrom deeptutor.core.context import Attachment, TurnRuntimeContext, UnifiedContext+ from deeptutor.services.learning_journal import get_learning_journal_storefrom deeptutor.services.memory import get_memory_storefrom deeptutor.services.model_selection.runtime import (activate_llm_selection,@@ -560,6 +561,15 @@ class TurnExecutor:memory_store = get_memory_store()memory_context = memory_store.read_l3_concat() if memory_references else ""+ # One snapshot per turn; selected-text tutoring stays independent+ # of an unrelated mission from earlier conversations (#1407).+ learning_journal_context = ""+ if not selection_tutor_context:+ try:+ learning_journal_context = get_learning_journal_store().injection_markdown()+ except (OSError, ValueError):+ logger.exception("Unable to read the learning journal; preserving its file")+# Persona: at most one behaviour preset per turn, eagerly# injected (a persona must shape the voice from the first# token). Resolution: the user's own workspace first, then@@ -910,6 +920,7 @@ class TurnExecutor:config_overrides=request_config,language=payload.get("language", "en"),memory_context=memory_context,+ learning_journal_context=learning_journal_context,persona_context=persona_context,sidebar_context=sidebar_system_context,skills_manifest=skills_manifest,diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex e36995aa3..31c250e55 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -1936,6 +1936,8 @@ CONFIGURABLE_BUILTIN_TOOL_NAMES: tuple[str, ...] = ("read_source","read_memory","write_memory",+ "learning_status",+ "learning_update","read_skill","list_notebook","write_note",diff --git a/deeptutor/tools/builtin_specs.py b/deeptutor/tools/builtin_specs.pyindex 5242843a0..6f32ec015 100644--- a/deeptutor/tools/builtin_specs.py+++ b/deeptutor/tools/builtin_specs.py@@ -70,6 +70,13 @@ BUILTIN_TOOL_SPECS: tuple[BuiltinToolSpec, ...] = (("geogebra_analysis", "GeoGebraAnalysisTool"),),),+ *_specs(+ "deeptutor.tools.learning_journal_tools",+ (+ ("learning_status", "LearningStatusTool"),+ ("learning_update", "LearningUpdateTool"),+ ),+ ),BuiltinToolSpec("exec", "deeptutor.tools.exec_tool:ExecTool"),*_specs("deeptutor.tools.workspace",diff --git a/deeptutor/tools/learning_journal_tools.py b/deeptutor/tools/learning_journal_tools.pynew file mode 100644index 000000000..359d186f9--- /dev/null+++ b/deeptutor/tools/learning_journal_tools.py@@ -0,0 +1,173 @@+"""Chat tools for the soft learning journal (#740)."""++from __future__ import annotations++from typing import Any++from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult+from deeptutor.tools.prompting import load_prompt_hints+++class _PromptHintsMixin:+ def get_prompt_hints(self, language: str = "en"):+ return load_prompt_hints(self.name, language=language)+++class LearningStatusTool(_PromptHintsMixin, BaseTool):+ """Read the learner's mission / last-session handoff / recent records."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="learning_status",+ description=(+ "Read the soft learning journal: mission (topic + why + level), "+ "last-session handoff, and recent learning records. The mission "+ "and handoff are already in your context when a journal exists "+ "— call this for the record history, or when the user asks to "+ "continue learning and nothing was carried over. Not a "+ "substitute for Mastery Path progress (use mastery_status for "+ "scored curriculum)."+ ),+ parameters=[],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.services.learning_journal import get_learning_journal_store++ try:+ text = get_learning_journal_store().status_markdown()+ except (OSError, ValueError):+ return ToolResult(+ content="Learning journal could not be read. Original data preserved.",+ success=False,+ )+ return ToolResult(content=text, metadata={"char_count": len(text)})+++class LearningUpdateTool(_PromptHintsMixin, BaseTool):+ """Write mission / session notes / learning records into the journal."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="learning_update",+ description=(+ "Update the soft learning journal across sessions. "+ "op=set_mission pins topic/why/level; op=note_session records "+ "what happened and the next focus; op=add_record stores one "+ "durable insight (ADR-style). Use for free-form multi-session "+ "study, recording only takeaways confirmed by the learner; "+ "do not dump preferences here (use write_memory) and do "+ "not replace Mastery Path gates."+ ),+ parameters=[+ ToolParameter(+ name="op",+ type="string",+ description=(+ "set_mission | note_session | add_record. "+ "set_mission needs topic (+ optional why/level); "+ "note_session needs summary and/or next_focus; "+ "add_record needs insight (+ optional title)."+ ),+ enum=["set_mission", "note_session", "add_record"],+ required=True,+ ),+ ToolParameter(+ name="topic",+ type="string",+ description="set_mission: what they are learning.",+ required=False,+ ),+ ToolParameter(+ name="why",+ type="string",+ description="set_mission: why it matters to them.",+ required=False,+ ),+ ToolParameter(+ name="level",+ type="string",+ description="set_mission: beginner | intermediate | advanced | short free text.",+ required=False,+ ),+ ToolParameter(+ name="summary",+ type="string",+ description="note_session: what was covered this session.",+ required=False,+ ),+ ToolParameter(+ name="next_focus",+ type="string",+ description="note_session: what to pick up next time.",+ required=False,+ ),+ ToolParameter(+ name="title",+ type="string",+ description="add_record: short label for the insight.",+ required=False,+ ),+ ToolParameter(+ name="insight",+ type="string",+ description="add_record: the durable takeaway (non-obvious lesson).",+ required=False,+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ try:+ return await self._update(**kwargs)+ except (OSError, ValueError):+ return ToolResult(+ content="Learning journal update failed. Original data preserved; retry after repairing the file or storage.",+ success=False,+ )++ async def _update(self, **kwargs: Any) -> ToolResult:+ from deeptutor.services.learning_journal import get_learning_journal_store++ op = str(kwargs.get("op") or "").strip().lower()+ store = get_learning_journal_store()++ if op == "set_mission":+ result = store.set_mission(+ topic=str(kwargs.get("topic") or ""),+ why=str(kwargs.get("why") or ""),+ level=str(kwargs.get("level") or ""),+ )+ elif op == "note_session":+ result = store.note_session(+ summary=str(kwargs.get("summary") or ""),+ next_focus=str(kwargs.get("next_focus") or ""),+ )+ elif op == "add_record":+ result = store.add_record(+ title=str(kwargs.get("title") or ""),+ insight=str(kwargs.get("insight") or ""),+ )+ else:+ return ToolResult(+ content=(+ f"Error: op must be set_mission, note_session, or add_record; got {op!r}."+ ),+ success=False,+ )++ return ToolResult(+ content=result.message,+ success=result.accepted,+ metadata={+ "op": op,+ "record_id": result.record_id,+ "deduplicated": result.deduplicated,+ },+ )+++__all__ = [+ "LearningStatusTool",+ "LearningUpdateTool",+]diff --git a/deeptutor/tools/prompting/hints/en/learning_status.yaml b/deeptutor/tools/prompting/hints/en/learning_status.yamlnew file mode 100644index 000000000..4801bcd73--- /dev/null+++ b/deeptutor/tools/prompting/hints/en/learning_status.yaml@@ -0,0 +1,6 @@+short_description: "Read the soft learning journal (mission, last session, recent insights)."+when_to_use: "You need the full insight history behind the journal, or the user asks where they left off and no learning journal was carried into this conversation. Prefer mastery_status for Guided Learning curriculum progress."+input_format: "{}"+guideline: "The mission and last-session handoff are already in your context when a journal exists — do not re-read them. Call this for the record list, or when nothing was carried over. If empty, offer to set a mission via learning_update rather than inventing progress. Do not confuse this with Memory preferences."+note: "Complements Mastery Path and Memory. Soft state only — no scored gates."+phase: "exploration"diff --git a/deeptutor/tools/prompting/hints/en/learning_update.yaml b/deeptutor/tools/prompting/hints/en/learning_update.yamlnew file mode 100644index 000000000..0d0fda95f--- /dev/null+++ b/deeptutor/tools/prompting/hints/en/learning_update.yaml@@ -0,0 +1,6 @@+short_description: "Update the soft learning journal: mission, session handoff, or one durable insight."+when_to_use: "The user commits to a multi-session learning goal; a teaching session ends and you should leave a next-focus note; or they hit a non-obvious insight worth keeping. Not for preferences (write_memory) or Mastery Path scores."+input_format: "{\"op\": \"set_mission\"|\"note_session\"|\"add_record\", \"topic\"?, \"why\"?, \"level\"?, \"summary\"?, \"next_focus\"?, \"title\"?, \"insight\"?}"+guideline: "set_mission early when intent is clear. note_session near the end of a productive teaching turn. add_record sparingly for durable takeaways. One insight per add_record call."+note: "Persists under the user's workspace learning_journal.json. Complements Mastery Path; does not replace it."+phase: "execution"diff --git a/deeptutor/tools/prompting/hints/zh/learning_status.yaml b/deeptutor/tools/prompting/hints/zh/learning_status.yamlnew file mode 100644index 000000000..2b94421b2--- /dev/null+++ b/deeptutor/tools/prompting/hints/zh/learning_status.yaml@@ -0,0 +1,6 @@+short_description: "读取软学习日志(使命、上次会话、近期洞见)。"+when_to_use: "需要日志背后的完整洞见记录,或用户问上次学到哪、而本次会话没有继承到学习日志时。Guided Learning 的课程进度请用 mastery_status。"+input_format: "{}"+guideline: "已有日志时,使命和上次会话的交接已经在你的上下文里,不要重复读取。要看记录列表、或什么都没继承到时才调用。若为空,用 learning_update 帮用户立使命,不要捏造进度。不要和 Memory 偏好混淆。"+note: "与 Mastery Path、Memory 互补。只有软状态,没有打分门闩。"+phase: "exploration"diff --git a/deeptutor/tools/prompting/hints/zh/learning_update.yaml b/deeptutor/tools/prompting/hints/zh/learning_update.yamlnew file mode 100644index 000000000..4013c65a6--- /dev/null+++ b/deeptutor/tools/prompting/hints/zh/learning_update.yaml@@ -0,0 +1,6 @@+short_description: "更新软学习日志:使命、会话交接,或一条持久洞见。"+when_to_use: "用户明确要跨会话学某个主题;一节教学结束需要留下 next focus;或出现值得保留的非显然洞见。偏好用 write_memory;Mastery 打分别写这里。"+input_format: "{\"op\": \"set_mission\"|\"note_session\"|\"add_record\", \"topic\"?, \"why\"?, \"level\"?, \"summary\"?, \"next_focus\"?, \"title\"?, \"insight\"?}"+guideline: "意图明确时尽早 set_mission。有收获的教学回合结束时 note_session。add_record 只记持久洞见,一次一条。"+note: "落在用户工作区 learning_journal.json。与 Mastery Path 互补,不替代。"+phase: "execution"diff --git a/tests/agents/chat/test_context_budget.py b/tests/agents/chat/test_context_budget.pyindex 10388baea..b4314c767 100644--- a/tests/agents/chat/test_context_budget.py+++ b/tests/agents/chat/test_context_budget.py@@ -121,6 +121,13 @@ def test_capability_blocks_are_summed_under_one_key() -> None:}+def test_learning_journal_is_not_folded_into_capability() -> None:+ snapshot = "## Mission\n- Topic: Fourier transform"+ budget = _budget(blocks=[PromptBlock("learning_journal", snapshot)])++ assert _tokens(budget) == {"learning_journal": _chars(f"## learning_journal\n{snapshot}")}++def test_segments_sorted_desc_with_empty_ones_dropped() -> None:budget = _budget(blocks=[diff --git a/tests/agents/chat/test_learning_journal_injection.py b/tests/agents/chat/test_learning_journal_injection.pynew file mode 100644index 000000000..d5811ab86--- /dev/null+++ b/tests/agents/chat/test_learning_journal_injection.py@@ -0,0 +1,52 @@+"""Carried-over learning state reaches the system prompt without a tool call (#740).++Stage 1 only advertised the journal through ``learning_status``, so a learner+who opened a new conversation and said "继续上次那个" got a tutor that had to+think to look. These tests pin stage 2: the snapshot the turn executor takes+before the loop runs mounts as its own block, right beside memory.+"""++from __future__ import annotations++from deeptutor.agents.loop.prompt_blocks import ChatPromptAssembler+from deeptutor.core.context import UnifiedContext++PROMPTS = {+ "general": "You are DeepTutor, an interactive tutor.",+ "runtime_policy": "policy",+ "loop": {"system": "loop"},+}++SNAPSHOT = "# Learning journal\n\n## Mission\n- Topic: Fourier transform"+++def _blocks(context: UnifiedContext) -> list[str]:+ assembler = ChatPromptAssembler(prompts=PROMPTS, language="en")+ return [b.name for b in assembler.blocks(context=context, tool_manifest="- none")]+++def test_journal_snapshot_mounts_as_its_own_block():+ names = _blocks(UnifiedContext(user_message="继续", learning_journal_context=SNAPSHOT))+ assert "learning_journal" in names+++def test_journal_block_sits_with_memory_not_behind_a_tool_call():+ names = _blocks(+ UnifiedContext(+ user_message="继续",+ memory_context="## Preferences",+ learning_journal_context=SNAPSHOT,+ )+ )+ assert names.index("learning_journal") == names.index("memory") + 1+++def test_empty_journal_mounts_nothing():+ assert "learning_journal" not in _blocks(UnifiedContext(user_message="hi"))+++def test_system_prompt_keeps_the_snapshot_verbatim():+ assembler = ChatPromptAssembler(prompts=PROMPTS, language="en")+ context = UnifiedContext(user_message="继续", learning_journal_context=SNAPSHOT)+ prompt = assembler.system_prompt(context=context, tool_manifest="- none")+ assert SNAPSHOT in promptdiff --git a/tests/api/test_learning_journal.py b/tests/api/test_learning_journal.pynew file mode 100644index 000000000..174e264b5--- /dev/null+++ b/tests/api/test_learning_journal.py@@ -0,0 +1,37 @@+from fastapi import FastAPI+from fastapi.testclient import TestClient++from deeptutor.api.routers import learning_journal+from deeptutor.services.learning_journal.store import LearningJournalStore+from deeptutor.services.path_service import PathService+from deeptutor.services.workspace.context import WorkspacePathService, WorkspaceScope+++def test_read_only_overview_is_scoped_and_preserves_corruption(tmp_path, monkeypatch):+ account = PathService(workspace_root=tmp_path / "account")+ a = WorkspacePathService(account, WorkspaceScope("a", account.workspace_root, tmp_path / "a"))+ b = WorkspacePathService(account, WorkspaceScope("b", account.workspace_root, tmp_path / "b"))+ active = [a]+ store = LearningJournalStore()+ monkeypatch.setattr(+ "deeptutor.services.learning_journal.store.get_path_service", lambda: active[0]+ )+ monkeypatch.setattr(learning_journal, "get_learning_journal_store", lambda: store)+ app = FastAPI()+ app.include_router(learning_journal.router, prefix="/api/learning-journal")+ client = TestClient(app)+ store.set_mission(topic="Workspace A")+ assert client.get("/api/learning-journal").json()["mission"]["topic"] == "Workspace A"+ active[0] = b+ assert client.get("/api/learning-journal").json()["mission"]["topic"] == ""+ assert not b.get_learning_journal_dir().exists()+ assert (+ client.post("/api/learning-journal", json={"mission": {"topic": "overwrite"}}).status_code+ == 405+ )+ b.get_learning_journal_dir().mkdir(parents=True)+ b.get_learning_journal_file().write_bytes(b"{corrupt")+ assert client.get("/api/learning-journal").status_code == 409+ assert b.get_learning_journal_file().read_bytes() == b"{corrupt"+ active[0] = a+ assert store.load().mission.topic == "Workspace A"diff --git a/tests/api/test_unified_ws_turn_runtime.py b/tests/api/test_unified_ws_turn_runtime.pyindex a18d223b7..350adb02c 100644--- a/tests/api/test_unified_ws_turn_runtime.py+++ b/tests/api/test_unified_ws_turn_runtime.py@@ -1069,6 +1069,7 @@ async def test_turn_runtime_injects_memory_and_refreshes_after_completion(async def handle(self, context):captured["conversation_history"] = context.conversation_historycaptured["memory_context"] = context.memory_context+ captured["learning_journal_context"] = context.learning_journal_contextcaptured["conversation_context_text"] = context.metadata.get("conversation_context_text")@@ -1099,6 +1100,12 @@ async def test_turn_runtime_injects_memory_and_refreshes_after_completion(emit=fake_emit,),)+ monkeypatch.setattr(+ "deeptutor.services.learning_journal.get_learning_journal_store",+ lambda: SimpleNamespace(+ injection_markdown=lambda: "# Learning journal\n## Mission\n- Topic: FFT",+ ),+ )monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)monkeypatch.setattr("deeptutor.services.persona.get_persona_service", _fake_persona_service)@@ -1121,6 +1128,7 @@ async def test_turn_runtime_injects_memory_and_refreshes_after_completion(passassert captured["memory_context"] == "## Memory\n## Preferences\n- Prefer concise answers."+ assert captured["learning_journal_context"] == ("# Learning journal\n## Mission\n- Topic: FFT")assert captured["conversation_history"] == []assert captured["conversation_context_text"] == "Recent chat summary"@@ -1367,3 +1375,97 @@ async def test_reattaching_the_same_image_does_not_duplicate_it(# record and the re-attached prior entry share one URL, and the URL is# the dedupe key.assert [att.url for att in captured[1]] == [image_attachment["url"]]+++async def test_selection_tutoring_never_mounts_the_learning_journal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ """A selected-text question must not inherit a carried-over study mission (#740).++ The journal snapshot is a standing part of the system prompt, so a sidebar+ question about one passage would otherwise answer *as if* it knew what the+ learner is studying. Memory avoids this by only reading what the client+ asks for; the journal has no such client input, so it needs its own guard.+ Asserting the store is never consulted pins that guard, rather than a+ snapshot that merely happens to be empty.+ """+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ captured: dict[str, object] = {}+ journal_reads: list[str] = []++ class FakeContextBuilder:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ async def build(self, **_kwargs):+ return SimpleNamespace(+ conversation_history=[],+ conversation_summary="",+ context_text="",+ token_count=0,+ budget=0,+ )++ class FakeOrchestrator:+ async def handle(self, context):+ captured["learning_journal_context"] = context.learning_journal_context+ yield StreamEvent(+ type=StreamEventType.CONTENT,+ source="chat",+ stage="responding",+ content="It forks the process.",+ metadata={"call_kind": "llm_final_response"},+ )+ yield StreamEvent(type=StreamEventType.DONE, source="chat")++ class FakeJournalStore:+ def injection_markdown(self) -> str:+ journal_reads.append("consulted")+ return "# Learning journal\n## Mission\n- Topic: FFT"++ monkeypatch.setattr("deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace())+ monkeypatch.setattr(+ "deeptutor.services.session.context_builder.ContextBuilder", FakeContextBuilder+ )+ monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)+ monkeypatch.setattr(+ "deeptutor.services.memory.get_memory_store",+ lambda: SimpleNamespace(read_l3_concat=lambda: "## Preferences\n- Concise.", emit=None),+ )+ monkeypatch.setattr(+ "deeptutor.services.learning_journal.get_learning_journal_store",+ lambda: FakeJournalStore(),+ )+ monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)+ monkeypatch.setattr("deeptutor.services.persona.get_persona_service", _fake_persona_service)++ _session, turn = await runtime.start_turn(+ {+ "type": "start_turn",+ "content": "what does this line mean?",+ "session_id": None,+ "capability": None,+ "tools": [],+ "knowledge_bases": [],+ "attachments": [],+ # Deliberately still requested: the client opting into memory must+ # not be what keeps the journal out of a selection turn.+ "memory_references": ["preferences"],+ "language": "en",+ "config": {},+ "selection_tutor_context": {+ "selected_text": "fork() returns in two processes.",+ "source_message_text": "In Unix, fork() returns in two processes.",+ "source_message_role": "assistant",+ },+ }+ )++ async for _event in runtime.subscribe_turn(turn["id"], after_seq=0):+ pass++ assert captured["learning_journal_context"] == ""+ assert journal_reads == []diff --git a/tests/services/learning_journal/test_store.py b/tests/services/learning_journal/test_store.pynew file mode 100644index 000000000..18306cc5f--- /dev/null+++ b/tests/services/learning_journal/test_store.py@@ -0,0 +1,163 @@+"""Tests for the soft learning journal store (#740)."""++from __future__ import annotations++from pathlib import Path++import pytest++from deeptutor.services.learning_journal.store import LearningJournalStore+from deeptutor.services.path_service import PathService+++def journal_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> LearningJournalStore:+ service = PathService(workspace_root=tmp_path / "data")+ monkeypatch.setattr(+ "deeptutor.services.learning_journal.store.get_path_service",+ lambda: service,+ )+ return LearningJournalStore()+++def test_empty_status_explains_how_to_start(journal_store: LearningJournalStore) -> None:+ text = journal_store.status_markdown()+ assert "No learning journal yet" in text+ assert "learning_update" in text+++def test_mission_session_and_records_round_trip(journal_store: LearningJournalStore) -> None:+ mission = journal_store.set_mission(+ topic="Fourier transform",+ why="Need it for signals coursework",+ level="intermediate",+ )+ assert mission.accepted+ session = journal_store.note_session(+ summary="Covered continuous FT definition and duality.",+ next_focus="Discrete FT and sampling intuition",+ )+ assert session.accepted+ record = journal_store.add_record(+ title="Duality",+ insight="Time stretch ↔ frequency squeeze is the first intuition to keep.",+ )+ assert record.accepted+ assert record.record_id == "lr_0001"++ text = journal_store.status_markdown()+ assert "Fourier transform" in text+ assert "Discrete FT" in text+ assert "lr_0001" in text+ assert "Duality" in text++ path = journal_store.journal_path()+ assert path.exists()+ again = journal_store.load()+ assert again.mission.topic == "Fourier transform"+ assert len(again.records) == 1+ assert path.read_text(encoding="utf-8").count("Fourier") >= 1+++def test_add_record_dedupes(journal_store: LearningJournalStore) -> None:+ first = journal_store.add_record(title="Nyquist", insight="Sample at >2B.")+ second = journal_store.add_record(title="Nyquist", insight="Sample at >2B.")+ assert first.accepted and second.accepted+ assert second.deduplicated+ assert second.record_id == first.record_id+ assert len(journal_store.load().records) == 1+++def test_set_mission_requires_topic(journal_store: LearningJournalStore) -> None:+ result = journal_store.set_mission(topic=" ")+ assert not result.accepted+++def test_injection_snapshot_carries_mission_and_handoff(+ journal_store: LearningJournalStore,+) -> None:+ journal_store.set_mission(+ topic="Fourier transform",+ why="Signals coursework",+ level="intermediate",+ )+ journal_store.note_session(+ summary="Covered continuous FT definition.",+ next_focus="Discrete FT and sampling intuition",+ )+ text = journal_store.injection_markdown()+ assert "Fourier transform" in text+ assert "Discrete FT and sampling intuition" in text+++def test_injection_snapshot_leaves_records_out(journal_store: LearningJournalStore) -> None:+ journal_store.set_mission(topic="Fourier transform")+ journal_store.add_record(title="Duality", insight="Time stretch means frequency squeeze.")+ text = journal_store.injection_markdown()+ assert "Duality" not in text+ assert "Time stretch" not in text+++def test_injection_snapshot_is_empty_for_a_new_learner(journal_store: LearningJournalStore) -> None:+ assert journal_store.injection_markdown() == ""+++def test_injection_snapshot_skips_records_only_journal(+ journal_store: LearningJournalStore,+) -> None:+ journal_store.add_record(title="Nyquist", insight="Sample at more than 2B.")+ assert journal_store.injection_markdown() == ""+++ "content", ["{broken", "[]", '{"version": 2}', '{"mission": []}', '{"records": [{}]}']+)+def test_corrupt_journal_is_preserved_on_read_and_write(journal_store, content):+ path = journal_store.journal_path()+ path.parent.mkdir(parents=True)+ path.write_text(content)+ with pytest.raises(ValueError):+ journal_store.overview()+ with pytest.raises(ValueError):+ journal_store.set_mission(topic="new")+ assert path.read_text() == content+++def test_panel_snapshot_matches_injection_and_reads_create_nothing(journal_store):+ path = journal_store.journal_path()+ assert journal_store.overview()["injected_context"] == ""+ assert not path.parent.exists()+ journal_store.set_mission(topic="Signals", why="Exam", level="beginner")+ journal_store.note_session(summary="Sampling", next_focus="Aliasing")+ journal_store.add_record(title="First", insight="First confirmed takeaway")+ journal_store.add_record(title="Second", insight="Second confirmed takeaway")+ before = path.read_bytes()+ snapshot = journal_store.overview()+ assert snapshot["injected_context"] == journal_store.injection_markdown()+ assert [r["title"] for r in snapshot["records"]] == ["Second", "First"]+ assert path.read_bytes() == before+++def _write_records(root, prefix):+ import deeptutor.services.learning_journal.store as module++ module.get_path_service = lambda: PathService(workspace_root=Path(root))+ store = module.LearningJournalStore()+ for n in range(10):+ store.add_record(title=f"{prefix}-{n}", insight=f"confirmed {prefix}-{n}")+++def test_two_workers_do_not_drop_confirmed_records(journal_store):+ import multiprocessing++ root = journal_store.journal_path().parent.parent+ context = multiprocessing.get_context("spawn")+ workers = [context.Process(target=_write_records, args=(str(root), p)) for p in ("a", "b")]+ for worker in workers:+ worker.start()+ for worker in workers:+ worker.join(15)+ assert worker.exitcode == 0+ records = journal_store.load().records+ assert len(records) == 20+ assert len({record.id for record in records}) == 20diff --git a/tests/tools/test_learning_journal_tools.py b/tests/tools/test_learning_journal_tools.pynew file mode 100644index 000000000..aaf1af896--- /dev/null+++ b/tests/tools/test_learning_journal_tools.py@@ -0,0 +1,66 @@+"""Tests for learning_status / learning_update tools (#740)."""++from __future__ import annotations++from pathlib import Path++import pytest++from deeptutor.services.path_service import PathService+from deeptutor.tools.learning_journal_tools import LearningStatusTool, LearningUpdateTool+++def journal_workspace(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> PathService:+ service = PathService(workspace_root=tmp_path / "data")+ monkeypatch.setattr(+ "deeptutor.services.learning_journal.store.get_path_service",+ lambda: service,+ )+ return service+++async def test_learning_update_and_status_tools(journal_workspace: PathService) -> None:+ update = LearningUpdateTool()+ status = LearningStatusTool()++ assert update.name == "learning_update"+ assert status.name == "learning_status"++ mission = await update.execute(+ op="set_mission",+ topic="Linear algebra",+ why="ML foundations",+ level="beginner",+ )+ assert mission.success+ assert "mission set" in mission.content++ note = await update.execute(+ op="note_session",+ summary="Vectors and linear combinations.",+ next_focus="Matrices as linear maps",+ )+ assert note.success++ record = await update.execute(+ op="add_record",+ title="Span",+ insight="Span is the set of all linear combinations of the generators.",+ )+ assert record.success+ assert record.metadata.get("record_id") == "lr_0001"++ snapshot = await status.execute()+ assert snapshot.success+ assert "Linear algebra" in snapshot.content+ assert "Matrices as linear maps" in snapshot.content+ assert "lr_0001" in snapshot.content+ assert journal_workspace.get_learning_journal_file().exists()+++async def test_learning_update_rejects_bad_op(journal_workspace: PathService) -> None:+ result = await LearningUpdateTool().execute(op="wipe")+ assert not result.successdiff --git a/web/app/(utility)/space/journal/page.tsx b/web/app/(utility)/space/journal/page.tsxnew file mode 100644index 000000000..6b1451a48--- /dev/null+++ b/web/app/(utility)/space/journal/page.tsx@@ -0,0 +1,6 @@+import { Suspense } from "react";+import LearningJournalPanel from "@/components/space/LearningJournalPanel";++export default function JournalPage() {+ return <Suspense><LearningJournalPanel /></Suspense>;+}diff --git a/web/components/chat/home/ContextBudgetChip.tsx b/web/components/chat/home/ContextBudgetChip.tsxindex 90d7e6c73..543ce88c0 100644--- a/web/components/chat/home/ContextBudgetChip.tsx+++ b/web/components/chat/home/ContextBudgetChip.tsx@@ -32,6 +32,7 @@ const SEGMENT_COLORS: Record<string, string> = {persona_style: "#f97316",partner_turn_policy: "#d946ef",memory: "#a855f7",+ learning_journal: "#3b82f6",knowledge_base_note: "#8b5cf6",skills: "#06b6d4",sources: "#0891b2",diff --git a/web/components/space/LearningJournalPanel.tsx b/web/components/space/LearningJournalPanel.tsxnew file mode 100644index 000000000..428204fd6--- /dev/null+++ b/web/components/space/LearningJournalPanel.tsx@@ -0,0 +1,65 @@+"use client";++import { useEffect, useState } from "react";+import { useSearchParams } from "next/navigation";+import { useTranslation } from "react-i18next";+import { getLearningJournal, type LearningJournal } from "@/lib/learning-journal-api";+import SpaceSectionHeader from "./SpaceSectionHeader";++export default function LearningJournalPanel() {+ const { t } = useTranslation();+ const params = useSearchParams();+ const workspace = params.get("dt_workspace") ?? params.get("workspace") ?? "";+ const [result, setResult] = useState<{ workspace: string; revision: number; journal?: LearningJournal; error?: boolean } | null>(null);+ const [revision, setRevision] = useState(0);+ const current = result?.workspace === workspace && result.revision === revision ? result : null;+ const journal = current?.journal;+ const error = current?.error;++ useEffect(() => {+ const controller = new AbortController();+ void getLearningJournal(controller.signal).then((snapshot) => {+ if (!controller.signal.aborted) setResult({ workspace, revision, journal: snapshot });+ }).catch(() => {+ if (!controller.signal.aborted) setResult({ workspace, revision, error: true });+ });+ return () => controller.abort();+ }, [workspace, revision]);++ const card = "rounded-xl border border-[var(--border)] p-5 space-y-3";+ return (+ <section className="space-y-5">+ <SpaceSectionHeader title={t("Learning journal")} description={t("Your tutor's mission, handoff and confirmed learning records.")}+ action={<button className="text-sm underline" onClick={() => setRevision((n) => n + 1)}>{t("Refresh")}</button>} />+ {error ? <div role="alert" className={card}>{t("Could not read the learning journal. Its original data is preserved. Try refreshing.")}</div>+ : !journal ? <p role="status">{t("Loading...")}</p>+ : <>+ <section className={card} aria-label={t("Current mission")}>+ <h2 className="font-semibold">{t("Current mission")}</h2>+ {journal.mission.topic ? <>+ <p className="font-medium break-words">{journal.mission.topic}</p>+ {journal.mission.why && <p className="whitespace-pre-wrap break-words">{journal.mission.why}</p>}+ {journal.mission.level && <p className="text-sm">{t("Level")}: {journal.mission.level}</p>}+ {journal.mission.updated_at && <time className="text-xs text-[var(--muted-foreground)]" dateTime={journal.mission.updated_at}>{journal.mission.updated_at}</time>}+ </> : <p>{t("Your tutor has no mission for you yet. Ask it to set one in conversation.")}</p>}+ </section>+ <section className={card} aria-label={t("Last-session handoff")}>+ <h2 className="font-semibold">{t("Last-session handoff")}</h2>+ {journal.last_session.summary || journal.last_session.next_focus ? <>+ <p className="whitespace-pre-wrap break-words">{journal.last_session.summary}</p>+ {journal.last_session.next_focus && <p className="whitespace-pre-wrap break-words"><strong>{t("Next focus")}: </strong>{journal.last_session.next_focus}</p>}+ {journal.last_session.updated_at && <time className="text-xs text-[var(--muted-foreground)]" dateTime={journal.last_session.updated_at}>{journal.last_session.updated_at}</time>}+ </> : <p>{t("No session handoff yet.")}</p>}+ </section>+ <section className={card} aria-label={t("Confirmed learning records")}>+ <h2 className="font-semibold">{t("Confirmed learning records")}</h2>+ {journal.records.length ? <ol className="space-y-4">{journal.records.map((record) => <li key={record.id}>+ <h3 className="font-medium break-words">{record.title}</h3>+ <p className="whitespace-pre-wrap break-words">{record.insight}</p>+ {record.created_at && <time className="text-xs text-[var(--muted-foreground)]" dateTime={record.created_at}>{record.created_at}</time>}+ </li>)}</ol> : <p>{t("No confirmed learning records yet.")}</p>}+ </section>+ </>}+ </section>+ );+}diff --git a/web/components/space/SpaceDashboard.tsx b/web/components/space/SpaceDashboard.tsxindex 90dd2d743..340323174 100644--- a/web/components/space/SpaceDashboard.tsx+++ b/web/components/space/SpaceDashboard.tsx@@ -28,6 +28,7 @@ import { listNotebooks, listNotebookEntries } from "@/lib/notebook-api";import { listPersonas } from "@/lib/personas-api";import { listKnowledgeBases } from "@/features/knowledge/api/catalog";import { listSkills } from "@/lib/skills-api";+import { scopedUrl } from "@/lib/workspace-scope";/*** Learning Space dashboard — the hub of `/space`.@@ -45,6 +46,7 @@ type DashKey =| "memory"| "chat_history"| "notebooks"+ | "journal"| "question_bank"| "personas"| "skills"@@ -117,6 +119,14 @@ const GROUPS: DashboardGroup[] = [tile: "bg-amber-500/10 text-amber-600 dark:text-amber-400",load: async () => (await listNotebooks()).length,},+ {+ key: "journal",+ href: "/space/journal",+ icon: NotebookPen,+ title: { zh: "学习日志", en: "Learning journal" },+ blurb: { zh: "查看当前目标、上次会话交接和已确认的学习记录。", en: "Inspect your mission, session handoff and confirmed records." },+ tile: "bg-teal-500/10 text-teal-600 dark:text-teal-400",+ },{key: "question_bank",href: "/space/questions",@@ -354,7 +364,7 @@ function DashboardCard({return (<Link- href={item.href}+ href={item.key === "journal" ? scopedUrl(item.href) : item.href}className="group relative flex flex-col rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 transition-all duration-150 hover:-translate-y-0.5 hover:border-[var(--foreground)]/20 hover:shadow-[0_6px_20px_-12px_rgba(0,0,0,0.25)]"><div className="flex items-start gap-3">diff --git a/web/lib/learning-journal-api.ts b/web/lib/learning-journal-api.tsnew file mode 100644index 000000000..10ba4dc33--- /dev/null+++ b/web/lib/learning-journal-api.ts@@ -0,0 +1,16 @@+import { apiFetch } from "@/shared/api/client";++export interface LearningJournal {+ version: number;+ updated_at: string;+ mission: { topic: string; why: string; level: string; updated_at: string };+ last_session: { summary: string; next_focus: string; updated_at: string };+ records: { id: string; title: string; insight: string; created_at: string }[];+ injected_context: string;+}++export async function getLearningJournal(signal?: AbortSignal): Promise<LearningJournal> {+ const response = await apiFetch("/api/learning-journal", { cache: "no-store", signal });+ if (!response.ok) throw new Error(`Learning journal request failed: ${response.status}`);+ return response.json();+}diff --git a/web/locales/de/app.json b/web/locales/de/app.jsonindex 42f7fd6d0..487445cc3 100644--- a/web/locales/de/app.json+++ b/web/locales/de/app.json@@ -5446,5 +5446,16 @@"Add segment note": "Notiz zum Abschnitt hinzufügen","Add a note for this segment": "Eine Notiz zu diesem Abschnitt hinzufügen","Delete note": "Notiz löschen",- "New note": "Neue Notiz"+ "New note": "Neue Notiz",+ "Learning journal": "Lernjournal",+ "Your tutor's mission, handoff and confirmed learning records.": "Lernziel, Sitzungsübergabe und bestätigte Lernnotizen deines Tutors.",+ "Current mission": "Aktuelles Lernziel",+ "Last-session handoff": "Übergabe der letzten Sitzung",+ "Next focus": "Nächster Schwerpunkt",+ "Confirmed learning records": "Bestätigte Lernnotizen",+ "No confirmed learning records yet.": "Noch keine bestätigten Lernnotizen.",+ "No session handoff yet.": "Noch keine Sitzungsübergabe.",+ "Your tutor has no mission for you yet. Ask it to set one in conversation.": "Dein Tutor hat noch kein Lernziel für dich. Bitte ihn im Gespräch, eines festzulegen.",+ "Could not read the learning journal. Its original data is preserved. Try refreshing.": "Das Lernjournal konnte nicht gelesen werden. Die Originaldaten bleiben erhalten. Versuche es erneut.",+ "Level": "Niveau"}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 450c4cf53..e01968356 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -5446,5 +5446,16 @@"Add segment note": "Add segment note","Add a note for this segment": "Add a note for this segment","Delete note": "Delete note",- "New note": "New note"+ "New note": "New note",+ "Learning journal": "Learning journal",+ "Your tutor's mission, handoff and confirmed learning records.": "Your tutor's mission, handoff and confirmed learning records.",+ "Current mission": "Current mission",+ "Last-session handoff": "Last-session handoff",+ "Next focus": "Next focus",+ "Confirmed learning records": "Confirmed learning records",+ "No confirmed learning records yet.": "No confirmed learning records yet.",+ "No session handoff yet.": "No session handoff yet.",+ "Your tutor has no mission for you yet. Ask it to set one in conversation.": "Your tutor has no mission for you yet. Ask it to set one in conversation.",+ "Could not read the learning journal. Its original data is preserved. Try refreshing.": "Could not read the learning journal. Its original data is preserved. Try refreshing.",+ "Level": "Level"}diff --git a/web/locales/pl/app.json b/web/locales/pl/app.jsonindex 2a84196b8..fee6c5b7c 100644--- a/web/locales/pl/app.json+++ b/web/locales/pl/app.json@@ -5462,5 +5462,16 @@"Add segment note": "Dodaj notatkę do fragmentu","Add a note for this segment": "Dodaj notatkę do tego fragmentu","Delete note": "Usuń notatkę",- "New note": "Nowa notatka"+ "New note": "Nowa notatka",+ "Learning journal": "Dziennik nauki",+ "Your tutor's mission, handoff and confirmed learning records.": "Cel, przekazanie sesji i potwierdzone notatki zapisane przez tutora.",+ "Current mission": "Bieżący cel nauki",+ "Last-session handoff": "Przekazanie ostatniej sesji",+ "Next focus": "Następny temat",+ "Confirmed learning records": "Potwierdzone notatki z nauki",+ "No confirmed learning records yet.": "Brak potwierdzonych notatek z nauki.",+ "No session handoff yet.": "Brak przekazania sesji.",+ "Your tutor has no mission for you yet. Ask it to set one in conversation.": "Tutor nie zapisał jeszcze twojego celu. Poproś go o ustalenie celu w rozmowie.",+ "Could not read the learning journal. Its original data is preserved. Try refreshing.": "Nie udało się odczytać dziennika. Oryginalne dane są zachowane. Spróbuj odświeżyć.",+ "Level": "Poziom"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex e96f9aa67..5fd532d74 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -5446,5 +5446,16 @@"Add segment note": "添加片段笔记","Add a note for this segment": "为当前片段添加笔记","Delete note": "删除笔记",- "New note": "新笔记"+ "New note": "新笔记",+ "Learning journal": "学习日志",+ "Your tutor's mission, handoff and confirmed learning records.": "查看导师记录的学习目标、会话交接和已确认的学习记录。",+ "Current mission": "当前学习目标",+ "Last-session handoff": "上次会话交接",+ "Next focus": "下次重点",+ "Confirmed learning records": "已确认的学习记录",+ "No confirmed learning records yet.": "暂无已确认的学习记录。",+ "No session handoff yet.": "暂无会话交接。",+ "Your tutor has no mission for you yet. Ask it to set one in conversation.": "导师尚未记录你的学习目标。在对话中请导师设置一个目标。",+ "Could not read the learning journal. Its original data is preserved. Try refreshing.": "无法读取学习日志,原始数据已保留。请尝试刷新。",+ "Level": "学习程度"}diff --git a/web/tests/learning-journal-panel.spec.tsx b/web/tests/learning-journal-panel.spec.tsxnew file mode 100644index 000000000..95f2cf8e4--- /dev/null+++ b/web/tests/learning-journal-panel.spec.tsx@@ -0,0 +1,50 @@+import React from "react";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import LearningJournalPanel from "@/components/space/LearningJournalPanel";+import { getLearningJournal, type LearningJournal } from "@/lib/learning-journal-api";++const route = vi.hoisted(() => ({ workspace: "a" }));+vi.mock("next/navigation", () => ({ useSearchParams: () => new URLSearchParams({ dt_workspace: route.workspace }) }));+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock("@/lib/learning-journal-api", () => ({ getLearningJournal: vi.fn() }));+const empty: LearningJournal = {+ version: 1, updated_at: "", injected_context: "",+ mission: { topic: "", why: "", level: "", updated_at: "" },+ last_session: { summary: "", next_focus: "", updated_at: "" }, records: [],+};++beforeEach(() => { vi.clearAllMocks(); route.workspace = "a"; });+describe("Learning journal overview", () => {+ it("shows the mission, handoff and newest-first records without editing controls", async () => {+ vi.mocked(getLearningJournal).mockResolvedValue({ ...empty,+ mission: { ...empty.mission, topic: "Signals", why: "Exam", level: "Beginner" },+ last_session: { ...empty.last_session, summary: "Sampling", next_focus: "Aliasing" },+ records: [{ id: "new", title: "Newer", insight: "Second", created_at: "" }, { id: "old", title: "Older", insight: "First", created_at: "" }],+ });+ render(<LearningJournalPanel />);+ await screen.findByText("Signals");+ expect(screen.getByText("Sampling")).toBeInTheDocument();+ expect(screen.getByText("Aliasing")).toBeInTheDocument();+ expect(screen.getAllByRole("listitem").map((el) => el.textContent)).toEqual(["NewerSecond", "OlderFirst"]);+ expect(screen.queryByRole("textbox")).toBeNull();+ });+ it("explains an empty journal and retries failed reads", async () => {+ vi.mocked(getLearningJournal).mockRejectedValueOnce(new Error("409")).mockResolvedValue(empty);+ render(<LearningJournalPanel />);+ await screen.findByRole("alert");+ fireEvent.click(screen.getByRole("button", { name: "Refresh" }));+ await screen.findByText("Your tutor has no mission for you yet. Ask it to set one in conversation.");+ expect(screen.queryByRole("alert")).toBeNull();+ });+ it("does not display an old workspace response after switching", async () => {+ let resolve!: (journal: LearningJournal) => void;+ vi.mocked(getLearningJournal).mockImplementationOnce(() => new Promise((done) => { resolve = done; })).mockResolvedValue(empty);+ const view = render(<LearningJournalPanel />);+ route.workspace = "b";+ view.rerender(<LearningJournalPanel />);+ await screen.findByText("No session handoff yet.");+ resolve({ ...empty, mission: { ...empty.mission, topic: "Old workspace secret" } });+ await waitFor(() => expect(screen.queryByText("Old workspace secret")).toBeNull());+ });+});