DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(notebook): decouple evidence from chat sessions (#1519)
Bingxi Zhao (Frank)1fe74df0ed86
diff --git a/deeptutor/api/routers/book.py b/deeptutor/api/routers/book.pyindex 288458d08..de5d18535 100644--- a/deeptutor/api/routers/book.py+++ b/deeptutor/api/routers/book.py@@ -1115,53 +1115,50 @@ async def quiz_attempt(req: QuizAttemptRequest) -> dict[str, Any]:or book.chat_session_idor "").strip()- # Notebook entries belong to real conversations. Creating a hidden- # ``book_<id>`` chat solely to satisfy the FK polluted history and- # made a Book Focus Check look like Immersive Reading. If the page- # has no conversation yet, progress still persists and the optional- # review sync waits for a later attempt after chat exists.- if session_id and await store.get_session(session_id) is not None:- from deeptutor.learning.assessment import (- AssessmentRecord,- is_correct_to_result,- record_assessment,- )+ has_session = bool(session_id and await store.get_session(session_id) is not None)+ from deeptutor.learning.assessment import (+ AssessmentRecord,+ is_correct_to_result,+ record_assessment,+ )- latest_attempt = progress.quiz_attempts[-1]- attempt_count = sum(- 1- for attempt in progress.quiz_attempts- if attempt.block_id == req.block_id and attempt.question_id == req.question_id- )- await record_assessment(- AssessmentRecord(- session_id=session_id,- turn_id=req.block_id,- question_id=question_id,- question=str(question.get("question") or block.title or "Focus check"),- question_type=str(question.get("question_type") or ""),- options=question.get("options") or {},- correct_answer=str(question.get("correct_answer") or ""),- explanation=str(question.get("explanation") or ""),- difficulty=str(question.get("difficulty") or ""),- user_answer=req.user_answer,- is_correct=bool(req.is_correct),- result=is_correct_to_result(bool(req.is_correct)),- source="book",- assessment_type="focus_check",- material_id=req.book_id,- material_title=book.title,- section_id=req.page_id,- section_title=page.title if page is not None else "",- mastery_path_id=str(question.get("mastery_path_id") or ""),- knowledge_point_id=str(question.get("knowledge_point_id") or ""),- attempt_count=max(1, attempt_count),- attempt_id=(- f"book:{req.book_id}:{req.block_id}:{question_id}:"- f"{latest_attempt.timestamp:.9f}"- ),- )+ latest_attempt = progress.quiz_attempts[-1]+ attempt_count = sum(+ 1+ for attempt in progress.quiz_attempts+ if attempt.block_id == req.block_id and attempt.question_id == req.question_id+ )+ await record_assessment(+ AssessmentRecord(+ session_id=session_id if has_session else "",+ origin_type="conversation" if has_session else "document_analysis",+ origin_ref=session_id if has_session else f"book:{req.book_id}",+ turn_id=req.block_id,+ question_id=question_id,+ question=str(question.get("question") or block.title or "Focus check"),+ question_type=str(question.get("question_type") or ""),+ options=question.get("options") or {},+ correct_answer=str(question.get("correct_answer") or ""),+ explanation=str(question.get("explanation") or ""),+ difficulty=str(question.get("difficulty") or ""),+ user_answer=req.user_answer,+ is_correct=bool(req.is_correct),+ result=is_correct_to_result(bool(req.is_correct)),+ source="book",+ assessment_type="focus_check",+ material_id=req.book_id,+ material_title=book.title,+ section_id=req.page_id,+ section_title=page.title if page is not None else "",+ mastery_path_id=str(question.get("mastery_path_id") or ""),+ knowledge_point_id=str(question.get("knowledge_point_id") or ""),+ attempt_count=max(1, attempt_count),+ attempt_id=(+ f"book:{req.book_id}:{req.block_id}:{question_id}:"+ f"{latest_attempt.timestamp:.9f}"+ ),)+ )except Exception:logger.warning("Failed to sync Focus-Check %s to question bank for book %s",diff --git a/deeptutor/api/routers/question_notebook.py b/deeptutor/api/routers/question_notebook.pyindex e695e3f0d..a6c426a24 100644--- a/deeptutor/api/routers/question_notebook.py+++ b/deeptutor/api/routers/question_notebook.py@@ -5,14 +5,15 @@ Question Notebook API — persists quiz questions, bookmarks, and categories.from __future__ import annotationsimport base64 as _b64+from hashlib import sha256 as _sha256import loggingfrom typing import Any, Literalimport uuid as _uuidfrom fastapi import APIRouter, HTTPException, Query, Response-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, model_validator-from deeptutor.core.assessment import AssessmentResult, AssessmentSource+from deeptutor.core.assessment import AssessmentResult, AssessmentSource, QuestionOriginTypefrom deeptutor.services.session import get_sqlite_session_storefrom deeptutor.services.storage import get_attachment_store@@ -46,8 +47,10 @@ class CategoryItem(BaseModel):class NotebookEntryItem(BaseModel):id: int- session_id: str+ session_id: str = ""session_title: str = ""+ origin_type: QuestionOriginType = "conversation"+ origin_ref: str = ""turn_id: str = ""question_id: str = ""question: str@@ -153,7 +156,9 @@ class AnswerImageUpload(BaseModel):class UpsertEntryRequest(BaseModel):- session_id: str+ session_id: str = ""+ origin_type: QuestionOriginType = "conversation"+ origin_ref: str = ""turn_id: str = ""question_id: strquestion: str@@ -183,12 +188,38 @@ class UpsertEntryRequest(BaseModel):response_time: float | None = Nonequality: float | None = None+ @model_validator(mode="after")+ def _validate_origin(self) -> "UpsertEntryRequest":+ self.session_id = self.session_id.strip()+ self.origin_ref = self.origin_ref.strip()+ if self.origin_type == "conversation":+ if not self.session_id:+ raise ValueError("conversation entries require session_id")+ if self.origin_ref and self.origin_ref != self.session_id:+ raise ValueError("conversation origin_ref must match session_id")+ self.origin_ref = self.session_id+ elif not self.origin_ref:+ raise ValueError(f"{self.origin_type} entries require origin_ref")+ return self+# ── Entry endpoints ──────────────────────────────────────────────+def _answer_image_owner(+ session_id: str,+ origin_type: str,+ origin_ref: str,+) -> str:+ """Stable AttachmentStore owner for conversation and independent entries."""+ if session_id:+ return session_id+ digest = _sha256(f"{origin_type}:{origin_ref}".encode()).hexdigest()[:24]+ return f"question-notebook-{digest}"++async def _persist_answer_images(- session_id: str, images: list[AnswerImageUpload] | None+ owner_id: str, images: list[AnswerImageUpload] | None) -> list[dict[str, str]] | None:"""Materialise base64 image uploads into the AttachmentStore.@@ -217,7 +248,7 @@ async def _persist_answer_images(continuetry:url = await attachment_store.put(- session_id=session_id,+ session_id=owner_id,attachment_id=record_id,filename=filename,data=raw_bytes,@@ -244,7 +275,18 @@ async def _persist_answer_images(@router.post("/entries/upsert")async def upsert_single_entry(payload: UpsertEntryRequest):store = get_sqlite_session_store()- images_records = await _persist_answer_images(payload.session_id, payload.user_answer_images)+ existing = await store.find_notebook_entry_by_origin(+ payload.origin_type,+ payload.origin_ref,+ payload.question_id,+ turn_id=payload.turn_id,+ )+ owner_id = _answer_image_owner(+ payload.session_id,+ payload.origin_type,+ payload.origin_ref,+ )+ images_records = await _persist_answer_images(owner_id, payload.user_answer_images)item = payload.model_dump()# The store expects ``user_answer_images`` as a plain list of dicts# (or absent to mean "leave the stored images alone"). Strip the@@ -253,24 +295,40 @@ async def upsert_single_entry(payload: UpsertEntryRequest):if images_records is not None:item["user_answer_images"] = images_recordstry:- await store.upsert_notebook_entries(payload.session_id, [item])+ await store.upsert_notebook_entries(payload.session_id or None, [item])except ValueError as e:raise HTTPException(status_code=404, detail=str(e))- entry = await store.find_notebook_entry(- payload.session_id, payload.question_id, turn_id=payload.turn_id+ entry = await store.find_notebook_entry_by_origin(+ payload.origin_type,+ payload.origin_ref,+ payload.question_id,+ turn_id=payload.turn_id,)if entry is None:raise HTTPException(status_code=500, detail="Upsert failed")+ if images_records is not None and existing is not None:+ retained = {str(image.get("id") or "") for image in images_records}+ old_owner = _answer_image_owner(+ str(existing.get("session_id") or ""),+ str(existing.get("origin_type") or "conversation"),+ str(existing.get("origin_ref") or ""),+ )+ attachment_store = get_attachment_store()+ for image in existing.get("user_answer_images") or []:+ image_id = str(image.get("id") or "")+ if image_id and image_id not in retained:+ await attachment_store.delete_attachment(old_owner, image_id)return entryasync def _course_session_ids(store: Any, course_id: str) -> list[str] | None:"""Resolve a course to the sessions whose questions belong to it.- Entries carry a session, never a course, so "this course's questions" is- always this indirection. Returns ``None`` for no course (do not scope) and- ``[]`` for a course with no conversations yet — which must scope to nothing- rather than quietly fall back to the whole library.+ Course membership remains conversation-derived until Question Bank entries+ gain an explicit course association. Independent origins are intentionally+ excluded. Returns ``None`` for no course (do not scope) and ``[]`` for a+ course with no conversations yet — which must scope to nothing rather than+ quietly fall back to the whole library."""if not course_id:return None@@ -347,7 +405,9 @@ async def list_entries(@router.get("/entries/lookup/by-question")async def lookup_entry(- session_id: str = Query(...),+ session_id: str = Query(default=""),+ origin_type: QuestionOriginType = Query(default="conversation"),+ origin_ref: str = Query(default=""),question_id: str = Query(...),turn_id: str | None = Query(default=None),missing_ok: bool = Query(@@ -358,7 +418,20 @@ async def lookup_entry(),):store = get_sqlite_session_store()- entry = await store.find_notebook_entry(session_id, question_id, turn_id=turn_id)+ resolved_ref = origin_ref.strip() or session_id.strip()+ if not resolved_ref:+ raise HTTPException(status_code=400, detail="session_id or origin_ref is required")+ if origin_type == "conversation" and session_id.strip() and resolved_ref != session_id.strip():+ raise HTTPException(+ status_code=400,+ detail="conversation origin_ref must match session_id",+ )+ entry = await store.find_notebook_entry_by_origin(+ origin_type,+ resolved_ref,+ question_id,+ turn_id=turn_id,+ )if entry is None:if missing_ok:return Response(status_code=204)@@ -390,9 +463,22 @@ async def update_entry(entry_id: int, payload: EntryUpdateRequest):@router.delete("/entries/{entry_id}")async def delete_entry(entry_id: int):store = get_sqlite_session_store()+ entry = await store.get_notebook_entry(entry_id)+ if entry is None:+ raise HTTPException(status_code=404, detail="Entry not found")deleted = await store.delete_notebook_entry(entry_id)if not deleted:raise HTTPException(status_code=404, detail="Entry not found")+ owner_id = _answer_image_owner(+ str(entry.get("session_id") or ""),+ str(entry.get("origin_type") or "conversation"),+ str(entry.get("origin_ref") or ""),+ )+ attachment_store = get_attachment_store()+ for image in entry.get("user_answer_images") or []:+ image_id = str(image.get("id") or "")+ if image_id:+ await attachment_store.delete_attachment(owner_id, image_id)return {"deleted": True, "id": entry_id}diff --git a/deeptutor/api/routers/reading_extensions.py b/deeptutor/api/routers/reading_extensions.pyindex a98b69941..86899562a 100644--- a/deeptutor/api/routers/reading_extensions.py+++ b/deeptutor/api/routers/reading_extensions.py@@ -297,11 +297,8 @@ async def submit_quiz_answers(material_id: str, payload: QuizAnswersPayload) ->if session_id:if await store.get_session(session_id) is None:raise HTTPException(status_code=404, detail="Reading session not found.")- else:- # A notebook container keeps standalone reading quizzes without requiring- # the learner to open a conversation first; it holds no invented messages.- session_id = f"reading-notebook:{material_id}"- await store.ensure_notebook_session(session_id, material_title or "Reading quiz")+ origin_type = "conversation" if session_id else "document_analysis"+ origin_ref = session_id or f"reading:{material_id}"turn_id = payload.turn_id.strip() or f"reading:{material_id}:loc:{payload.locator}"graded: list[dict[str, Any]] = []for item in payload.answers:@@ -322,6 +319,8 @@ async def submit_quiz_answers(material_id: str, payload: QuizAnswersPayload) ->await record_assessment(AssessmentRecord(session_id=session_id,+ origin_type=origin_type,+ origin_ref=origin_ref,turn_id=turn_id,question_id=item.question_id.strip(),question=str(question.get("prompt") or "Reading quiz"),diff --git a/deeptutor/core/assessment.py b/deeptutor/core/assessment.pyindex 69018eb80..084cd0538 100644--- a/deeptutor/core/assessment.py+++ b/deeptutor/core/assessment.py@@ -5,9 +5,11 @@ from typing import Literal, get_argsAssessmentSource = Literal["deep_question", "mastery_path", "immersive_reading", "book", "partner_chat", "import"]+QuestionOriginType = Literal["conversation", "external_import", "document_analysis"]AssessmentType = Literal["quiz", "focus_check", "qualitative", "review"]AssessmentResult = Literal["correct", "incorrect", "partial", "ungraded", "voided"]ASSESSMENT_SOURCES = frozenset(get_args(AssessmentSource))+QUESTION_ORIGIN_TYPES = frozenset(get_args(QuestionOriginType))ASSESSMENT_TYPES = frozenset(get_args(AssessmentType))ASSESSMENT_RESULTS = frozenset(get_args(AssessmentResult))diff --git a/deeptutor/learning/assessment.py b/deeptutor/learning/assessment.pyindex 51aaa1375..63cca3573 100644--- a/deeptutor/learning/assessment.py+++ b/deeptutor/learning/assessment.py@@ -1,11 +1,12 @@"""Unified assessment adapter for the Question Notebook review layer.Mastery Path, Book Focus-Check, and Immersive Reading persist graded attempts-through :func:`record_assessment`. Identity is the existing-``(session_id, turn_id, question_id)`` remains the latest-state notebook-projection. Every graded submission is also appended to the immutable shared-attempt log, and explicit objective linkage can update the same retention-state from any learning surface.+through :func:`record_assessment`. Identity is+``(origin_type, origin_ref, turn_id, question_id)``; conversation-backed+records use their session id as ``origin_ref`` for backward compatibility.+Every graded submission is also appended to the immutable shared attempt log,+and explicit objective linkage can update the same retention state from any+learning surface."""from __future__ import annotations@@ -22,9 +23,11 @@ from deeptutor.core.assessment import (ASSESSMENT_RESULTS,ASSESSMENT_SOURCES,ASSESSMENT_TYPES,+ QUESTION_ORIGIN_TYPES,AssessmentResult,AssessmentSource,AssessmentType,+ QuestionOriginType,)logger = logging.getLogger(__name__)@@ -75,7 +78,9 @@ class AssessmentRecord(BaseModel):model_config = ConfigDict(extra="ignore")- session_id: str+ session_id: str = ""+ origin_type: QuestionOriginType = "conversation"+ origin_ref: str = ""turn_id: str = ""question_id: strsource: AssessmentSource = "deep_question"@@ -112,6 +117,12 @@ class AssessmentRecord(BaseModel):raw = str(value or "").strip()return raw if raw in ASSESSMENT_SOURCES else "deep_question"+ @field_validator("origin_type", mode="before")+ @classmethod+ def _normalize_origin_type(cls, value: object) -> str:+ raw = str(value or "").strip()+ return raw if raw in QUESTION_ORIGIN_TYPES else "conversation"+@field_validator("assessment_type", mode="before")@classmethoddef _normalize_type(cls, value: object) -> str:@@ -126,6 +137,7 @@ class AssessmentRecord(BaseModel):@field_validator("session_id",+ "origin_ref","turn_id","question_id","question",@@ -172,8 +184,16 @@ class AssessmentRecord(BaseModel):@model_validator(mode="after")def _require_identity(self) -> "AssessmentRecord":- if not self.session_id or not self.question_id:- raise ValueError("session_id and question_id are required")+ if self.origin_type == "conversation":+ if not self.session_id:+ raise ValueError("conversation assessments require session_id")+ if self.origin_ref and self.origin_ref != self.session_id:+ raise ValueError("conversation origin_ref must match session_id")+ self.origin_ref = self.session_id+ elif not self.origin_ref:+ raise ValueError(f"{self.origin_type} assessments require origin_ref")+ if not self.question_id:+ raise ValueError("question_id is required")if not self.question:raise ValueError("question is required")return self@@ -181,7 +201,12 @@ class AssessmentRecord(BaseModel):@propertydef assessment_id(self) -> str:"""Audit id derived from the notebook unique key — not a second identity."""- raw = f"{self.session_id}|{self.turn_id}|{self.question_id}"+ owner = (+ self.session_id+ if self.origin_type == "conversation"+ else f"{self.origin_type}:{self.origin_ref}"+ )+ raw = f"{owner}|{self.turn_id}|{self.question_id}"return sha1(raw.encode("utf-8"), usedforsecurity=False).hexdigest()@property@@ -195,9 +220,14 @@ class AssessmentRecord(BaseModel):"""if self.attempt_id:return self.attempt_id+ owner = (+ self.session_id+ if self.origin_type == "conversation"+ else f"{self.origin_type}:{self.origin_ref}"+ )raw = "|".join((- self.session_id,+ owner,self.turn_id,self.question_id,self.source,@@ -331,6 +361,8 @@ def to_notebook_item(record: AssessmentRecord, diagnostics: list[str]) -> dict[smastery_path_id, knowledge_point_id = _apply_linkage(record, diagnostics)is_correct = result_to_is_correct(result)item: dict[str, Any] = {+ "origin_type": record.origin_type,+ "origin_ref": record.origin_ref,"turn_id": record.turn_id,"question_id": record.question_id,"question": record.question,@@ -368,15 +400,18 @@ async def record_assessment(record: AssessmentRecord) -> AssessmentOutcome:from deeptutor.services.session import get_sqlite_session_storestore = get_sqlite_session_store()- upserted = await store.upsert_notebook_entries(record.session_id, [item])- entry = await store.find_notebook_entry(- record.session_id, record.question_id, turn_id=record.turn_id+ upserted = await store.upsert_notebook_entries(record.session_id or None, [item])+ entry = await store.find_notebook_entry_by_origin(+ record.origin_type,+ record.origin_ref,+ record.question_id,+ turn_id=record.turn_id,)entry_id = (int(entry["id"]) if isinstance(entry, dict) and entry.get("id") is not None else None)attempt_recorded = await store.append_assessment_attempt(- record.session_id,+ record.session_id or None,entry_id,{**record.model_dump(mode="json"),@@ -433,6 +468,7 @@ __all__ = ["AssessmentResult","AssessmentSource","AssessmentType",+ "QuestionOriginType","RecordAssessmentError","build_grade_result","is_correct_to_result",diff --git a/deeptutor/learning/tests/test_assessment.py b/deeptutor/learning/tests/test_assessment.pyindex 69ca8c1d8..a1af16b4a 100644--- a/deeptutor/learning/tests/test_assessment.py+++ b/deeptutor/learning/tests/test_assessment.py@@ -170,6 +170,38 @@ def test_repeated_record_is_idempotent(store: SQLiteSessionStore) -> None:assert len(attempts) == 1+def test_document_assessment_persists_without_a_chat_session(+ store: SQLiteSessionStore,+) -> None:+ record = AssessmentRecord(+ origin_type="document_analysis",+ origin_ref="book:calculus:focus-check-3",+ question_id="q-3",+ question="Differentiate x².",+ user_answer="2x",+ result="correct",+ source="book",+ material_id="calculus",+ )++ first = asyncio.run(record_assessment(record))+ second = asyncio.run(record_assessment(record))++ assert first.entry_id == second.entry_id+ assert first.attempt_recorded is True+ assert second.attempt_recorded is False+ entry = asyncio.run(+ store.find_notebook_entry_by_origin(+ "document_analysis",+ "book:calculus:focus-check-3",+ "q-3",+ )+ )+ assert entry is not None+ assert entry["session_id"] == ""+ assert entry["origin_type"] == "document_analysis"++def test_reanswer_keeps_immutable_attempts_and_updates_latest_projection(store: SQLiteSessionStore,) -> None:diff --git a/deeptutor/services/practice/analytics.py b/deeptutor/services/practice/analytics.pyindex df8d5df8e..a39d0d27d 100644--- a/deeptutor/services/practice/analytics.py+++ b/deeptutor/services/practice/analytics.py@@ -43,7 +43,7 @@ def analytics(rows = conn.execute(f"""SELECT practice_day({timestamp}) AS day,COALESCE(NULLIF(n.source, ''), 'deep_question') AS source, COUNT(*) AS count- FROM notebook_entries n JOIN sessions s ON s.id=n.session_id {join}+ FROM notebook_entries n LEFT JOIN sessions s ON s.id=n.session_id {join}WHERE {scope} {extra} AND {timestamp}>=? AND {timestamp}<=?GROUP BY day, source""", # nosec B608 - identifiers and scope are internal literals[*params, start, now],diff --git a/deeptutor/services/practice/storage.py b/deeptutor/services/practice/storage.pyindex 07cfeb1ee..e7c6a89ec 100644--- a/deeptutor/services/practice/storage.py+++ b/deeptutor/services/practice/storage.py@@ -114,7 +114,10 @@ class PracticeStore:@staticmethoddef _scope(session_ids: list[str] | None) -> tuple[str, list]:- sql = "s.deleted_at IS NULL"+ # Independent imports/document questions have no chat to delete. They+ # stay visible in the global bank, while an explicit course/session+ # scope continues to select conversation-backed entries only.+ sql = "(n.session_id IS NULL OR s.deleted_at IS NULL)"params: list = []if session_ids is not None:sql += " AND n.session_id IN (" + (",".join("?" for _ in session_ids) or "NULL") + ")"@@ -135,7 +138,7 @@ class PracticeStore:COALESCE(SUM({_DUE_AT_SQL} <= ?), 0) AS due,COALESCE(SUM({_DUE_AT_SQL} <= ?), 0) AS overdue,MIN({_DUE_AT_SQL}) AS next_due_at- FROM notebook_entries n JOIN sessions s ON s.id = n.session_id+ FROM notebook_entries n LEFT JOIN sessions s ON s.id = n.session_idLEFT JOIN practice_review_state r ON r.entry_id = n.id WHERE {scope}""", # nosec B608 - fixed scope SQL; values bound[now, start, *params],@@ -143,7 +146,7 @@ class PracticeStore:completed = conn.execute(f"""SELECT COUNT(DISTINCT e.entry_id) FROM practice_review_events e- JOIN notebook_entries n ON n.id = e.entry_id JOIN sessions s ON s.id = n.session_id+ JOIN notebook_entries n ON n.id = e.entry_id LEFT JOIN sessions s ON s.id = n.session_idWHERE e.reviewed_at >= ? AND e.reviewed_at < ? AND {scope}""", # nosec B608 - fixed scope SQL; values bound[start, end, *params],@@ -182,7 +185,7 @@ class PracticeStore:with self.connect() as conn:rows = conn.execute(f"""- SELECT n.id FROM notebook_entries n JOIN sessions s ON s.id=n.session_id+ SELECT n.id FROM notebook_entries n LEFT JOIN sessions s ON s.id=n.session_idLEFT JOIN practice_review_state r ON r.entry_id=n.idWHERE {_DUE_AT_SQL} <= ? AND {scope}ORDER BY {_DUE_AT_SQL}, n.id LIMIT ?@@ -213,8 +216,8 @@ class PracticeStore:with self.connect() as conn:return (conn.execute(- """SELECT 1 FROM notebook_entries n JOIN sessions s ON s.id=n.session_id- WHERE n.id=? AND s.deleted_at IS NULL""",+ """SELECT 1 FROM notebook_entries n LEFT JOIN sessions s ON s.id=n.session_id+ WHERE n.id=? AND (n.session_id IS NULL OR s.deleted_at IS NULL)""",(entry_id,),).fetchone()is not None@@ -249,8 +252,8 @@ class PracticeStore:)return json.loads(previous["outcome_json"])entry = conn.execute(- """SELECT n.* FROM notebook_entries n JOIN sessions s ON s.id=n.session_id- WHERE n.id=? AND s.deleted_at IS NULL""",+ """SELECT n.* FROM notebook_entries n LEFT JOIN sessions s ON s.id=n.session_id+ WHERE n.id=? AND (n.session_id IS NULL OR s.deleted_at IS NULL)""",(entry_id,),).fetchone()if not entry:@@ -357,33 +360,23 @@ class PracticeStore:raise ValueError("Import preview expired. Select the file again.")payload = json.loads(staged["payload_json"])questions = payload if isinstance(payload, list) else payload["questions"]- course_id = "" if isinstance(payload, list) else payload.get("course_id", "")- session_id = f"practice-imports:{course_id}" if course_id else "practice-imports"- conn.execute(- "INSERT OR IGNORE INTO sessions(id, title, created_at, updated_at, preferences_json) VALUES(?, ?, ?, ?, ?)",- (- session_id,- "Imported practice questions",- now,- now,- json.dumps(- {"course_id": course_id, "internal_notebook": True, "archived": True}- ),- ),- )- # An import should be visible even if the old synthetic session was trashed.- conn.execute("UPDATE sessions SET deleted_at=NULL WHERE id=?", (session_id,))+ # All practice-file imports share one durable origin namespace.+ # ``question_id`` is a content hash, so re-importing the same+ # question remains idempotent without tying ownership to an+ # ephemeral preview receipt or a synthetic chat session.+ origin_ref = "practice-import"created, skipped = 0, 0for question in questions:cursor = conn.execute("""- INSERT OR IGNORE INTO notebook_entries(session_id, question_id, question, question_type,+ INSERT OR IGNORE INTO notebook_entries(+ session_id, origin_type, origin_ref, question_id, question, question_type,options_json, correct_answer, explanation, difficulty, user_answer, source,result, assessment_type, created_at, updated_at, material_title, material_id)- VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, 'import', ?, 'quiz', ?, ?, ?, ?)+ VALUES(NULL, 'external_import', ?, ?, ?, ?, ?, ?, ?, ?, ?, 'import', ?, 'quiz', ?, ?, ?, ?)""",(- session_id,+ origin_ref,question["question_id"],question["question"],question["question_type"],@@ -402,8 +395,10 @@ class PracticeStore:created += cursor.rowcountskipped += 1 - cursor.rowcountentry_id = conn.execute(- "SELECT id FROM notebook_entries WHERE session_id=? AND question_id=? AND turn_id=''",- (session_id, question["question_id"]),+ """SELECT id FROM notebook_entries+ WHERE origin_type='external_import' AND origin_ref=?+ AND question_id=? AND turn_id=''""",+ (origin_ref, question["question_id"]),).fetchone()[0]if staged["target"] == "mistakes":conn.execute(diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pyindex 57f368bfc..142320031 100644--- a/deeptutor/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -22,7 +22,12 @@ try: # POSIX is the supported production target; fallback keeps Windows dev usaexcept ImportError: # pragma: no cover - exercised only on Windowsfcntl = None # type: ignore[assignment]-from deeptutor.core.assessment import ASSESSMENT_RESULTS, ASSESSMENT_SOURCES, ASSESSMENT_TYPES+from deeptutor.core.assessment import (+ ASSESSMENT_RESULTS,+ ASSESSMENT_SOURCES,+ ASSESSMENT_TYPES,+ QUESTION_ORIGIN_TYPES,+)from deeptutor.services.path_service import get_path_servicefrom deeptutor.services.session.protocol import ActiveTurnConflictfrom deeptutor.utils.secret_files import ensure_private_directory, ensure_private_file@@ -347,7 +352,9 @@ class SQLiteSessionStore:CREATE TABLE IF NOT EXISTS notebook_entries (id INTEGER PRIMARY KEY AUTOINCREMENT,- session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,+ session_id TEXT REFERENCES sessions(id) ON DELETE SET NULL,+ origin_type TEXT NOT NULL DEFAULT 'conversation',+ origin_ref TEXT NOT NULL,turn_id TEXT NOT NULL DEFAULT '',question_id TEXT NOT NULL,question TEXT NOT NULL,@@ -380,7 +387,7 @@ class SQLiteSessionStore:ai_judgment TEXT DEFAULT '',created_at REAL NOT NULL,updated_at REAL NOT NULL,- UNIQUE(session_id, turn_id, question_id)+ UNIQUE(origin_type, origin_ref, turn_id, question_id));CREATE INDEX IF NOT EXISTS idx_notebook_entries_session@@ -392,7 +399,9 @@ class SQLiteSessionStore:CREATE TABLE IF NOT EXISTS assessment_attempts (attempt_id TEXT PRIMARY KEY,notebook_entry_id INTEGER,- session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,+ session_id TEXT REFERENCES sessions(id) ON DELETE SET NULL,+ origin_type TEXT NOT NULL DEFAULT 'conversation',+ origin_ref TEXT NOT NULL,turn_id TEXT NOT NULL DEFAULT '',question_id TEXT NOT NULL,source TEXT NOT NULL,@@ -483,6 +492,8 @@ class SQLiteSessionStore:self._migrate_notebook_entries_add_ai_judgment(conn)self._migrate_notebook_entries_add_assessment_review(conn)self._migrate_notebook_entries_add_assessment_v2(conn)+ self._migrate_notebook_entry_origins(conn)+ self._migrate_assessment_attempt_origins(conn)self._migrate_turn_runtime_columns(conn)from deeptutor.services.practice.storage import initialize_practice@@ -799,6 +810,247 @@ class SQLiteSessionStore:""")+ @staticmethod+ def _migrate_notebook_entry_origins(conn: sqlite3.Connection) -> None:+ """Detach Question Notebook identity from conversation ownership.++ SQLite cannot relax a ``NOT NULL`` foreign key or replace a table-level+ unique constraint in place, so this migration rebuilds the table once.+ IDs are copied verbatim, which preserves categories, practice state,+ bookmarks, answer images and external references. Existing rows become+ conversation origins; future non-conversation rows may keep+ ``session_id`` NULL without manufacturing a chat.+ """+ info = {+ row[1]: row for row in conn.execute("PRAGMA table_info(notebook_entries)").fetchall()+ }+ if not info:+ return+ origin_unique = False+ for index in conn.execute("PRAGMA index_list(notebook_entries)").fetchall():+ if not index[2]:+ continue+ columns = [row[2] for row in conn.execute(f"PRAGMA index_info({index[1]})").fetchall()]+ if columns == ["origin_type", "origin_ref", "turn_id", "question_id"]:+ origin_unique = True+ break+ if (+ "origin_type" in info+ and "origin_ref" in info+ and not bool(info["session_id"][3])+ and origin_unique+ ):+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_notebook_entries_origin "+ "ON notebook_entries(origin_type, origin_ref, created_at DESC)"+ )+ return++ origin_type = (+ "CASE WHEN origin_type IN ('conversation','external_import','document_analysis') "+ "THEN origin_type WHEN session_id IS NOT NULL AND session_id != '' "+ "THEN 'conversation' ELSE 'external_import' END"+ if "origin_type" in info+ else "CASE WHEN session_id IS NOT NULL AND session_id != '' "+ "THEN 'conversation' ELSE 'external_import' END"+ )+ origin_ref = (+ "COALESCE(NULLIF(origin_ref, ''), NULLIF(session_id, ''), 'legacy:' || id)"+ if "origin_ref" in info+ else "COALESCE(NULLIF(session_id, ''), 'legacy:' || id)"+ )++ conn.commit()+ conn.execute("PRAGMA foreign_keys = OFF")+ try:+ conn.execute("BEGIN IMMEDIATE")+ conn.execute("DROP TABLE IF EXISTS notebook_entries_new")+ conn.execute(+ """+ CREATE TABLE notebook_entries_new (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ session_id TEXT REFERENCES sessions(id) ON DELETE SET NULL,+ origin_type TEXT NOT NULL DEFAULT 'conversation',+ origin_ref TEXT NOT NULL,+ turn_id TEXT NOT NULL DEFAULT '',+ question_id TEXT NOT NULL,+ question TEXT NOT NULL,+ question_type TEXT DEFAULT '',+ options_json TEXT DEFAULT '{}',+ correct_answer TEXT DEFAULT '',+ explanation TEXT DEFAULT '',+ difficulty TEXT DEFAULT '',+ user_answer TEXT DEFAULT '',+ user_answer_images_json TEXT DEFAULT '[]',+ source TEXT NOT NULL DEFAULT 'deep_question',+ material_id TEXT NOT NULL DEFAULT '',+ material_title TEXT NOT NULL DEFAULT '',+ section_id TEXT NOT NULL DEFAULT '',+ section_title TEXT NOT NULL DEFAULT '',+ score_trend TEXT NOT NULL DEFAULT 'new',+ assessment_type TEXT NOT NULL DEFAULT '',+ result TEXT NOT NULL DEFAULT '',+ mastery_path_id TEXT NOT NULL DEFAULT '',+ knowledge_point_id TEXT NOT NULL DEFAULT '',+ attempt_count INTEGER NOT NULL DEFAULT 1,+ hints_used INTEGER NOT NULL DEFAULT 0,+ confidence REAL,+ response_time REAL,+ quality REAL,+ is_correct INTEGER DEFAULT 0,+ resolved INTEGER DEFAULT 0,+ bookmarked INTEGER DEFAULT 0,+ followup_session_id TEXT DEFAULT '',+ ai_judgment TEXT DEFAULT '',+ created_at REAL NOT NULL,+ updated_at REAL NOT NULL,+ UNIQUE(origin_type, origin_ref, turn_id, question_id)+ )+ """+ )+ conn.execute(+ f"""+ INSERT INTO notebook_entries_new (+ id, session_id, origin_type, origin_ref, turn_id, question_id,+ question, question_type, options_json, correct_answer,+ explanation, difficulty, user_answer, user_answer_images_json,+ source, material_id, material_title, section_id, section_title,+ score_trend, assessment_type, result, mastery_path_id,+ knowledge_point_id, attempt_count, hints_used, confidence,+ response_time, quality, is_correct, resolved, bookmarked,+ followup_session_id, ai_judgment, created_at, updated_at+ )+ SELECT+ id, NULLIF(session_id, ''), {origin_type}, {origin_ref},+ COALESCE(turn_id, ''), question_id, question, question_type,+ options_json, correct_answer, explanation, difficulty,+ user_answer, user_answer_images_json, source, material_id,+ material_title, section_id, section_title, score_trend,+ assessment_type, result, mastery_path_id, knowledge_point_id,+ attempt_count, hints_used, confidence, response_time, quality,+ is_correct, resolved, bookmarked, followup_session_id,+ ai_judgment, created_at, updated_at+ FROM notebook_entries+ """ # nosec B608 - expressions depend only on inspected schema columns+ )+ conn.execute("DROP TABLE notebook_entries")+ conn.execute("ALTER TABLE notebook_entries_new RENAME TO notebook_entries")+ conn.execute(+ "CREATE INDEX idx_notebook_entries_session "+ "ON notebook_entries(session_id, created_at DESC)"+ )+ conn.execute(+ "CREATE INDEX idx_notebook_entries_origin "+ "ON notebook_entries(origin_type, origin_ref, created_at DESC)"+ )+ conn.execute(+ "CREATE INDEX idx_notebook_entries_bookmarked "+ "ON notebook_entries(bookmarked, created_at DESC)"+ )+ conn.execute(+ "CREATE INDEX idx_notebook_entries_review "+ "ON notebook_entries(source, material_id, resolved, created_at DESC)"+ )+ conn.execute(+ "CREATE INDEX idx_notebook_entries_linkage "+ "ON notebook_entries(mastery_path_id, knowledge_point_id)"+ )+ conn.commit()+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.execute("PRAGMA foreign_keys = ON")++ @staticmethod+ def _migrate_assessment_attempt_origins(conn: sqlite3.Connection) -> None:+ """Give immutable attempts the same independent origin as their projection."""+ info = {+ row[1]: row for row in conn.execute("PRAGMA table_info(assessment_attempts)").fetchall()+ }+ if not info:+ return+ if "origin_type" in info and "origin_ref" in info and not bool(info["session_id"][3]):+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_assessment_attempts_origin_time "+ "ON assessment_attempts(origin_type, origin_ref, occurred_at DESC)"+ )+ return+ origin_type = (+ "CASE WHEN origin_type IN ('conversation','external_import','document_analysis') "+ "THEN origin_type WHEN session_id IS NOT NULL AND session_id != '' "+ "THEN 'conversation' ELSE 'external_import' END"+ if "origin_type" in info+ else "CASE WHEN session_id IS NOT NULL AND session_id != '' "+ "THEN 'conversation' ELSE 'external_import' END"+ )+ origin_ref = (+ "COALESCE(NULLIF(origin_ref, ''), NULLIF(session_id, ''), 'attempt:' || attempt_id)"+ if "origin_ref" in info+ else "COALESCE(NULLIF(session_id, ''), 'attempt:' || attempt_id)"+ )+ conn.commit()+ conn.execute("PRAGMA foreign_keys = OFF")+ try:+ conn.execute("BEGIN IMMEDIATE")+ conn.execute("DROP TABLE IF EXISTS assessment_attempts_new")+ conn.execute(+ """+ CREATE TABLE assessment_attempts_new (+ attempt_id TEXT PRIMARY KEY,+ notebook_entry_id INTEGER,+ session_id TEXT REFERENCES sessions(id) ON DELETE SET NULL,+ origin_type TEXT NOT NULL DEFAULT 'conversation',+ origin_ref TEXT NOT NULL,+ turn_id TEXT NOT NULL DEFAULT '',+ question_id TEXT NOT NULL,+ source TEXT NOT NULL,+ assessment_type TEXT NOT NULL,+ result TEXT NOT NULL,+ mastery_path_id TEXT NOT NULL DEFAULT '',+ knowledge_point_id TEXT NOT NULL DEFAULT '',+ occurred_at REAL NOT NULL,+ assessment_json TEXT NOT NULL+ )+ """+ )+ conn.execute(+ f"""+ INSERT INTO assessment_attempts_new (+ attempt_id, notebook_entry_id, session_id, origin_type,+ origin_ref, turn_id, question_id, source, assessment_type,+ result, mastery_path_id, knowledge_point_id, occurred_at,+ assessment_json+ )+ SELECT+ attempt_id, notebook_entry_id, NULLIF(session_id, ''),+ {origin_type}, {origin_ref}, turn_id, question_id, source,+ assessment_type, result, mastery_path_id,+ knowledge_point_id, occurred_at, assessment_json+ FROM assessment_attempts+ """ # nosec B608 - expressions depend only on inspected schema columns+ )+ conn.execute("DROP TABLE assessment_attempts")+ conn.execute("ALTER TABLE assessment_attempts_new RENAME TO assessment_attempts")+ conn.execute(+ "CREATE INDEX idx_assessment_attempts_session_time "+ "ON assessment_attempts(session_id, occurred_at DESC)"+ )+ conn.execute(+ "CREATE INDEX idx_assessment_attempts_origin_time "+ "ON assessment_attempts(origin_type, origin_ref, occurred_at DESC)"+ )+ conn.execute(+ "CREATE INDEX idx_assessment_attempts_linkage "+ "ON assessment_attempts(mastery_path_id, knowledge_point_id, occurred_at DESC)"+ )+ conn.commit()+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.execute("PRAGMA foreign_keys = ON")+async def _run(self, fn, *args):async with self._lock:return await asyncio.to_thread(fn, *args)@@ -2686,18 +2938,48 @@ class SQLiteSessionStore:cls._optional_float(item.get("quality")),)- def _upsert_notebook_entries_sync(self, session_id: str, items: list[dict[str, Any]]) -> int:+ @staticmethod+ def _notebook_origin(+ session_id: str | None,+ item: dict[str, Any],+ ) -> tuple[str | None, str, str]:+ """Return the optional navigation session and durable entry identity."""+ navigation_session = str(session_id or item.get("session_id") or "").strip() or None+ origin_type = str(item.get("origin_type") or "conversation").strip()+ if origin_type not in QUESTION_ORIGIN_TYPES:+ raise ValueError(f"Unsupported question origin: {origin_type}")+ origin_ref = str(item.get("origin_ref") or "").strip()+ if origin_type == "conversation":+ if navigation_session is None:+ raise ValueError("Conversation question origins require session_id")+ if origin_ref and origin_ref != navigation_session:+ raise ValueError("Conversation origin_ref must match session_id")+ origin_ref = navigation_session+ elif not origin_ref:+ raise ValueError(f"{origin_type} question origins require origin_ref")+ return navigation_session, origin_type, origin_ref++ def _upsert_notebook_entries_sync(+ self,+ session_id: str | None,+ items: list[dict[str, Any]],+ ) -> int:if not items:return 0now = time.time()with self._connect() as conn:- if (- conn.execute("SELECT id FROM sessions WHERE id = ?", (session_id,)).fetchone()- is None- ):- raise ValueError(f"Session not found: {session_id}")upserted = 0for item in items:+ navigation_session, origin_type, origin_ref = self._notebook_origin(+ session_id, item+ )+ if navigation_session is not None and (+ conn.execute(+ "SELECT id FROM sessions WHERE id = ?", (navigation_session,)+ ).fetchone()+ is None+ ):+ raise ValueError(f"Session not found: {navigation_session}")question = (item.get("question") or "").strip()question_id = (item.get("question_id") or "").strip()if not question or not question_id:@@ -2718,9 +3000,10 @@ class SQLiteSessionStore:existing = conn.execute("""SELECT is_correct FROM notebook_entries- WHERE session_id = ? AND turn_id = ? AND question_id = ?+ WHERE origin_type = ? AND origin_ref = ?+ AND turn_id = ? AND question_id = ?""",- (session_id, turn_id, question_id),+ (origin_type, origin_ref, turn_id, question_id),).fetchone()previous = bool(existing["is_correct"]) if existing is not None else Noneif previous is None or previous == bool(is_correct):@@ -2743,148 +3026,94 @@ class SQLiteSessionStore:if assessment[1] == "voided" or is_correctelse 0)- if images_json is None:- conn.execute(- """- INSERT INTO notebook_entries (- session_id, turn_id, question_id, question, question_type,- options_json, correct_answer, explanation, difficulty,- user_answer, user_answer_images_json, source, material_id,- material_title, section_id, section_title, score_trend,- assessment_type, result, mastery_path_id, knowledge_point_id,- attempt_count, hints_used, confidence, response_time, quality,- is_correct, resolved, bookmarked, followup_session_id,- created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '[]', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '', ?, ?)- ON CONFLICT(session_id, turn_id, question_id) DO UPDATE SET- question = excluded.question,- question_type = excluded.question_type,- options_json = excluded.options_json,- correct_answer = excluded.correct_answer,- explanation = excluded.explanation,- difficulty = excluded.difficulty,- user_answer = excluded.user_answer,- source = excluded.source,- material_id = excluded.material_id,- material_title = excluded.material_title,- section_id = excluded.section_id,- section_title = excluded.section_title,- score_trend = excluded.score_trend,- assessment_type = excluded.assessment_type,- result = excluded.result,- mastery_path_id = excluded.mastery_path_id,- knowledge_point_id = excluded.knowledge_point_id,- attempt_count = excluded.attempt_count,- hints_used = excluded.hints_used,- confidence = excluded.confidence,- response_time = excluded.response_time,- quality = excluded.quality,- is_correct = excluded.is_correct,- resolved = CASE- WHEN excluded.result = 'ungraded' THEN notebook_entries.resolved- WHEN excluded.result = 'voided' THEN 1- WHEN excluded.is_correct = 1 THEN 1- WHEN excluded.is_correct = 0 AND notebook_entries.is_correct = 1 THEN 0- ELSE notebook_entries.resolved- END,- updated_at = excluded.updated_at- """,- (- session_id,- turn_id,- question_id,- question,- item.get("question_type") or "",- _json_dumps(item.get("options") or {}),- item.get("correct_answer") or "",- item.get("explanation") or "",- item.get("difficulty") or "",- item.get("user_answer") or "",- *provenance,- *assessment,- is_correct,- resolved_on_insert,- now,- now,- ),- )- else:- conn.execute(- """- INSERT INTO notebook_entries (- session_id, turn_id, question_id, question, question_type,- options_json, correct_answer, explanation, difficulty,- user_answer, user_answer_images_json, source, material_id,- material_title, section_id, section_title, score_trend,- assessment_type, result, mastery_path_id, knowledge_point_id,- attempt_count, hints_used, confidence, response_time, quality,- is_correct, resolved, bookmarked, followup_session_id,- created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '', ?, ?)- ON CONFLICT(session_id, turn_id, question_id) DO UPDATE SET- question = excluded.question,- question_type = excluded.question_type,- options_json = excluded.options_json,- correct_answer = excluded.correct_answer,- explanation = excluded.explanation,- difficulty = excluded.difficulty,- user_answer = excluded.user_answer,- source = excluded.source,- material_id = excluded.material_id,- material_title = excluded.material_title,- section_id = excluded.section_id,- section_title = excluded.section_title,- score_trend = excluded.score_trend,- assessment_type = excluded.assessment_type,- result = excluded.result,- mastery_path_id = excluded.mastery_path_id,- knowledge_point_id = excluded.knowledge_point_id,- attempt_count = excluded.attempt_count,- hints_used = excluded.hints_used,- confidence = excluded.confidence,- response_time = excluded.response_time,- quality = excluded.quality,- user_answer_images_json = excluded.user_answer_images_json,- is_correct = excluded.is_correct,- resolved = CASE- WHEN excluded.result = 'ungraded' THEN notebook_entries.resolved- WHEN excluded.result = 'voided' THEN 1- WHEN excluded.is_correct = 1 THEN 1- WHEN excluded.is_correct = 0 AND notebook_entries.is_correct = 1 THEN 0- ELSE notebook_entries.resolved- END,- updated_at = excluded.updated_at- """,- (- session_id,- turn_id,- question_id,- question,- item.get("question_type") or "",- _json_dumps(item.get("options") or {}),- item.get("correct_answer") or "",- item.get("explanation") or "",- item.get("difficulty") or "",- item.get("user_answer") or "",- images_json,- *provenance,- *assessment,- is_correct,- resolved_on_insert,- now,- now,- ),- )+ conn.execute(+ """+ INSERT INTO notebook_entries (+ session_id, origin_type, origin_ref, turn_id, question_id,+ question, question_type, options_json, correct_answer,+ explanation, difficulty, user_answer,+ user_answer_images_json, source, material_id,+ material_title, section_id, section_title, score_trend,+ assessment_type, result, mastery_path_id, knowledge_point_id,+ attempt_count, hints_used, confidence, response_time, quality,+ is_correct, resolved, bookmarked, followup_session_id,+ created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '', ?, ?)+ ON CONFLICT(origin_type, origin_ref, turn_id, question_id) DO UPDATE SET+ session_id = excluded.session_id,+ question = excluded.question,+ question_type = excluded.question_type,+ options_json = excluded.options_json,+ correct_answer = excluded.correct_answer,+ explanation = excluded.explanation,+ difficulty = excluded.difficulty,+ user_answer = excluded.user_answer,+ user_answer_images_json = CASE+ WHEN ? THEN notebook_entries.user_answer_images_json+ ELSE excluded.user_answer_images_json+ END,+ source = excluded.source,+ material_id = excluded.material_id,+ material_title = excluded.material_title,+ section_id = excluded.section_id,+ section_title = excluded.section_title,+ score_trend = excluded.score_trend,+ assessment_type = excluded.assessment_type,+ result = excluded.result,+ mastery_path_id = excluded.mastery_path_id,+ knowledge_point_id = excluded.knowledge_point_id,+ attempt_count = excluded.attempt_count,+ hints_used = excluded.hints_used,+ confidence = excluded.confidence,+ response_time = excluded.response_time,+ quality = excluded.quality,+ is_correct = excluded.is_correct,+ resolved = CASE+ WHEN excluded.result = 'ungraded' THEN notebook_entries.resolved+ WHEN excluded.result = 'voided' THEN 1+ WHEN excluded.is_correct = 1 THEN 1+ WHEN excluded.is_correct = 0 AND notebook_entries.is_correct = 1 THEN 0+ ELSE notebook_entries.resolved+ END,+ updated_at = excluded.updated_at+ """,+ (+ navigation_session,+ origin_type,+ origin_ref,+ turn_id,+ question_id,+ question,+ item.get("question_type") or "",+ _json_dumps(item.get("options") or {}),+ item.get("correct_answer") or "",+ item.get("explanation") or "",+ item.get("difficulty") or "",+ item.get("user_answer") or "",+ images_json if images_json is not None else "[]",+ *provenance,+ *assessment,+ is_correct,+ resolved_on_insert,+ now,+ now,+ images_json is None,+ ),+ )upserted += 1conn.commit()return upserted- async def upsert_notebook_entries(self, session_id: str, items: list[dict[str, Any]]) -> int:+ async def upsert_notebook_entries(+ self,+ session_id: str | None,+ items: list[dict[str, Any]],+ ) -> int:return await self._run(self._upsert_notebook_entries_sync, session_id, items)def _append_assessment_attempt_sync(self,- session_id: str,+ session_id: str | None,notebook_entry_id: int | None,attempt: dict[str, Any],) -> bool:@@ -2892,25 +3121,30 @@ class SQLiteSessionStore:question_id = str(attempt.get("question_id") or "").strip()if not attempt_id or not question_id:raise ValueError("attempt_id and question_id are required")+ navigation_session, origin_type, origin_ref = self._notebook_origin(session_id, attempt)with self._connect() as conn:- if (- conn.execute("SELECT id FROM sessions WHERE id = ?", (session_id,)).fetchone()+ if navigation_session is not None and (+ conn.execute(+ "SELECT id FROM sessions WHERE id = ?", (navigation_session,)+ ).fetchone()is None):- raise ValueError(f"Session not found: {session_id}")+ raise ValueError(f"Session not found: {navigation_session}")conn.execute("""INSERT OR IGNORE INTO assessment_attempts (- attempt_id, notebook_entry_id, session_id, turn_id,- question_id, source, assessment_type, result,+ attempt_id, notebook_entry_id, session_id, origin_type,+ origin_ref, turn_id, question_id, source, assessment_type, result,mastery_path_id, knowledge_point_id, occurred_at,assessment_json- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",(attempt_id,notebook_entry_id,- session_id,+ navigation_session,+ origin_type,+ origin_ref,str(attempt.get("turn_id") or ""),question_id,str(attempt.get("source") or "deep_question"),@@ -2928,7 +3162,7 @@ class SQLiteSessionStore:async def append_assessment_attempt(self,- session_id: str,+ session_id: str | None,notebook_entry_id: int | None,attempt: dict[str, Any],) -> bool:@@ -3069,8 +3303,14 @@ class SQLiteSessionStore:assessment_type = (row["assessment_type"] or "") if "assessment_type" in keys else ""return {"id": int(row["id"]),- "session_id": row["session_id"],+ "session_id": (row["session_id"] or "") if "session_id" in keys else "","session_title": row["session_title"] or "" if "session_title" in keys else "",+ "origin_type": (row["origin_type"] or "conversation")+ if "origin_type" in keys+ else "conversation",+ "origin_ref": (row["origin_ref"] or row["session_id"] or "")+ if "origin_ref" in keys+ else (row["session_id"] or ""),"turn_id": (row["turn_id"] or "") if "turn_id" in keys else "","question_id": row["question_id"] or "","question": row["question"],@@ -3261,7 +3501,8 @@ class SQLiteSessionStore:base = f"""SELECTn.id, n.session_id, COALESCE(s.title, '') AS session_title,- n.turn_id, n.question_id, n.question, n.question_type, n.options_json,+ n.origin_type, n.origin_ref, n.turn_id, n.question_id,+ n.question, n.question_type, n.options_json,n.correct_answer, n.explanation, n.difficulty,n.user_answer, n.user_answer_images_json, n.source, n.material_id,n.material_title, n.section_id, n.section_title, n.score_trend,@@ -3498,29 +3739,59 @@ class SQLiteSessionStore:# (``q_1``..``q_N``) repeat across quizzes in one session, so a# cross-turn match would leak a previous quiz's answers into a new# quiz (issues #487 / #677).+ return self._find_notebook_entry_by_origin_sync(+ "conversation",+ session_id,+ question_id,+ turn_id,+ )++ async def find_notebook_entry(+ self,+ session_id: str,+ question_id: str,+ turn_id: str | None = None,+ ) -> dict[str, Any] | None:+ return await self._run(self._find_notebook_entry_sync, session_id, question_id, turn_id)++ def _find_notebook_entry_by_origin_sync(+ self,+ origin_type: str,+ origin_ref: str,+ question_id: str,+ turn_id: str | None = None,+ ) -> dict[str, Any] | None:with self._connect() as conn:row = conn.execute("""SELECT n.*, COALESCE(s.title, '') AS session_titleFROM notebook_entries nLEFT JOIN sessions s ON s.id = n.session_id- WHERE n.session_id = ?+ WHERE n.origin_type = ?+ AND n.origin_ref = ?AND n.turn_id = ?AND n.question_id = ?""",- (session_id, turn_id if turn_id is not None else "", question_id),+ (origin_type, origin_ref, turn_id if turn_id is not None else "", question_id),).fetchone()if row is None:return Nonereturn self._serialize_notebook_entry(row)- async def find_notebook_entry(+ async def find_notebook_entry_by_origin(self,- session_id: str,+ origin_type: str,+ origin_ref: str,question_id: str,turn_id: str | None = None,) -> dict[str, Any] | None:- return await self._run(self._find_notebook_entry_sync, session_id, question_id, turn_id)+ return await self._run(+ self._find_notebook_entry_by_origin_sync,+ origin_type,+ origin_ref,+ question_id,+ turn_id,+ )def _update_notebook_entry_sync(self, entry_id: int, updates: dict[str, Any]) -> bool:allowed = {diff --git a/deeptutor/services/workspace/dependencies.py b/deeptutor/services/workspace/dependencies.pyindex 7890e87e2..f171f6252 100644--- a/deeptutor/services/workspace/dependencies.py+++ b/deeptutor/services/workspace/dependencies.py@@ -274,8 +274,13 @@ def _question_sessions(paths, entry_ids=None) -> set[str]:f"SELECT session_id FROM notebook_entries WHERE id IN ({placeholders})", # nosec B608 - placeholders onlylist(entry_ids),)+ if row[0]}- return {row[0] for row in conn.execute("SELECT DISTINCT session_id FROM notebook_entries")}+ return {+ row[0]+ for row in conn.execute("SELECT DISTINCT session_id FROM notebook_entries")+ if row[0]+ }def _with_historical_references(paths, sessions: list[dict]) -> list[dict]:diff --git a/deeptutor/services/workspace/session_transfer.py b/deeptutor/services/workspace/session_transfer.pyindex e06b73ead..c3df81ee9 100644--- a/deeptutor/services/workspace/session_transfer.py+++ b/deeptutor/services/workspace/session_transfer.py@@ -57,6 +57,7 @@ def transfer_sessions("notebook_entry_categories",f"entry_id IN (SELECT id FROM main.notebook_entries WHERE session_id IN ({selected}))", # nosec B608 - fixed tables and local schema; values bound),+ ("assessment_attempts", f"session_id IN ({selected})"),]for table, where in tables:rows = conn.execute(f'SELECT * FROM main."{table}" WHERE {where}').fetchall() # nosec B608 - fixed tables and local schema; values bound@@ -114,6 +115,16 @@ def transfer_sessions().fetchone()[0]if copied != len(ids):raise WorkspaceError("The conversation copy could not be verified.")+ # Notebook and assessment evidence normally survives a conversation+ # deletion by detaching from it. A workspace transfer is different:+ # verified copies now belong to the destination, so remove the source+ # copies explicitly before deleting their conversations.+ conn.execute(+ f"DELETE FROM main.notebook_entries WHERE session_id IN ({selected})" # nosec B608 - fixed tables and local schema; values bound+ )+ conn.execute(+ f"DELETE FROM main.assessment_attempts WHERE session_id IN ({selected})" # nosec B608 - fixed tables and local schema; values bound+ )conn.execute(f"DELETE FROM main.sessions WHERE id IN ({selected})") # nosec B608 - fixed tables and local schema; values boundconn.commit()return copieddiff --git a/deeptutor/tools/question_bank.py b/deeptutor/tools/question_bank.pyindex 742638ec2..9df5d1463 100644--- a/deeptutor/tools/question_bank.py+++ b/deeptutor/tools/question_bank.py@@ -366,17 +366,17 @@ MAX_RECORD_FIELD = 2000def _record_question_id(question: str) -> str:"""Stable content hash so re-recording the same mistake updates the row- (the store dedups on ``session_id + turn_id + question_id``) instead of+ (the store dedups on origin + turn + question id) instead ofpiling up duplicates each time the learner revisits it."""normalized = " ".join(question.split()).casefold()return "pq_" + hashlib.sha1(normalized.encode("utf-8"), usedforsecurity=False).hexdigest()[:16]-def _partner_record_session() -> tuple[str, str]:- """Stable ``(session_id, title)`` naming one partner pairing's mistakes.+def _partner_record_origin() -> tuple[str, str]:+ """Stable ``(origin_ref, title)`` naming one partner pairing's mistakes.Deterministic per partner + partner-of pairing so every recorded mistake- lands in the same notebook session the family can review as one list.+ lands in the same external origin the family can review as one list."""partner_id = ""actor_id = ""@@ -391,14 +391,14 @@ def _partner_record_session() -> tuple[str, str]:partner_id = str(getattr(context, "partner_id", "") or "")actor_id = str(getattr(context, "actor_id", "") or "")name = str(getattr(context, "partner_name", "") or "").strip()- session_id = f"partner-notebook:{partner_id or 'unknown'}:{actor_id or 'admin'}"+ origin_ref = f"partner:{partner_id or 'unknown'}:{actor_id or 'admin'}"if name:title = f"{name} (Partner)"elif partner_id:title = f"Partner {partner_id} notebook"else:title = "Partner notebook"- return session_id, title+ return origin_ref, titleasync def _record(@@ -419,17 +419,10 @@ async def _record(action="record",error="`question` is required — the problem as the learner wrote or photographed it.",)- session_id, session_title = _partner_record_session()- try:- await store.ensure_notebook_session(session_id, session_title)- except Exception:- logger.warning("question_bank: could not ensure a notebook session", exc_info=True)- return QuestionBankOutcome(- ok=False,- action="record",- error="The question bank is not available in this conversation; nothing was recorded.",- )+ origin_ref, origin_title = _partner_record_origin()item = {+ "origin_type": "external_import",+ "origin_ref": origin_ref,"question_id": _record_question_id(text),"question": text[:MAX_RECORD_QUESTION],"question_type": str(question_type or "").strip()[:100],@@ -437,24 +430,29 @@ async def _record("explanation": _truncate(explanation, MAX_RECORD_FIELD),"user_answer": _truncate(user_answer, MAX_RECORD_FIELD),"source": "partner_chat",+ "material_title": origin_title,"is_correct": bool(is_correct),}- upserted = await store.upsert_notebook_entries(session_id, [item])+ upserted = await store.upsert_notebook_entries(None, [item])if not upserted:return QuestionBankOutcome(ok=False,action="record",error="The bank rejected the entry; nothing was recorded.",)- parts = [f"Recorded 1 wrong question into the bank ({session_title})."]+ parts = [f"Recorded 1 wrong question into the bank ({origin_title})."]summary: dict[str, Any] = {- "session_id": session_id,+ "session_id": "",+ "origin_type": "external_import",+ "origin_ref": origin_ref,"question_id": item["question_id"],"source": "partner_chat",}name = (category or "").strip()[:MAX_CATEGORY_NAME]if name:- entry = await store.find_notebook_entry(session_id, item["question_id"])+ entry = await store.find_notebook_entry_by_origin(+ "external_import", origin_ref, item["question_id"]+ )entry_id = int(entry["id"]) if entry and entry.get("id") is not None else Noneif entry_id is None:parts.append("Could not file it into a category (entry not found after recording).")diff --git a/tests/api/test_book_quiz_attempt_notebook.py b/tests/api/test_book_quiz_attempt_notebook.pyindex c22569fa8..4771fa110 100644--- a/tests/api/test_book_quiz_attempt_notebook.py+++ b/tests/api/test_book_quiz_attempt_notebook.py@@ -124,4 +124,8 @@ def test_quiz_attempt_does_not_create_a_synthetic_chat_session(tmp_path, monkeypassert response.status_code == 200assert len(resolved.learning.saved) == 1assert asyncio.run(store.get_session("book_book-1")) is None- assert asyncio.run(store.list_notebook_entries(source="book"))["total"] == 0+ entries = asyncio.run(store.list_notebook_entries(source="book"))+ assert entries["total"] == 1+ assert entries["items"][0]["session_id"] == ""+ assert entries["items"][0]["origin_type"] == "document_analysis"+ assert entries["items"][0]["origin_ref"] == "book:book-1"diff --git a/tests/api/test_notebook_router.py b/tests/api/test_notebook_router.pyindex 8166a239e..2e0a3c0eb 100644--- a/tests/api/test_notebook_router.py+++ b/tests/api/test_notebook_router.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asyncioimport base64+from hashlib import sha256import importlibfrom pathlib import Path@@ -156,6 +157,55 @@ def test_upsert_entry_persists_base64_answer_image(assert stored_path.read_bytes() == b"image-bytes"+def test_independent_entry_uses_stable_answer_image_owner_and_cleans_up(+ store: SQLiteSessionStore, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ attachment_store = LocalDiskAttachmentStore(root=tmp_path / "attachments")+ monkeypatch.setattr(+ "deeptutor.api.routers.question_notebook.get_attachment_store",+ lambda: attachment_store,+ )+ origin_ref = "document:guide.pdf:page-4"+ owner = (+ "question-notebook-" + sha256(f"document_analysis:{origin_ref}".encode()).hexdigest()[:24]+ )++ with TestClient(_build_app(store)) as client:+ response = client.post(+ "/api/question-notebook/entries/upsert",+ json={+ "origin_type": "document_analysis",+ "origin_ref": origin_ref,+ "question_id": "image-question",+ "question": "Identify the diagram.",+ "user_answer_images": [+ {+ "id": "answer-image-1",+ "base64": base64.b64encode(b"image-bytes").decode("ascii"),+ "filename": "answer.png",+ "mime_type": "image/png",+ }+ ],+ },+ )+ assert response.status_code == 200+ entry_id = response.json()["id"]+ assert response.json()["user_answer_images"][0]["url"].startswith(+ f"/files/attachments/{owner}/answer-image-1/"+ )+ stored_path = attachment_store.resolve_path(+ session_id=owner,+ attachment_id="answer-image-1",+ filename="answer.png",+ )+ assert stored_path is not None and stored_path.read_bytes() == b"image-bytes"++ deleted = client.delete(f"/api/question-notebook/entries/{entry_id}")+ assert deleted.status_code == 200++ assert not stored_path.exists()++def test_list_entries_filters_by_course_and_total(store: SQLiteSessionStore, course_service) -> None:diff --git a/tests/api/test_practice.py b/tests/api/test_practice.pyindex bccce0a92..13d4e75a3 100644--- a/tests/api/test_practice.py+++ b/tests/api/test_practice.py@@ -324,22 +324,19 @@ def test_course_imports_keep_their_course_and_file_provenance(bank, monkeypatch)store, repo, client = bankquestion = normalize_question({"question": "Q", "answer": "A"})repo.commit_import(repo.stage_import("lesson.csv", "mistakes", [question], "course-a"))- session_id = "practice-imports:course-a"- listing = asyncio.run(store.list_notebook_entries(session_ids=[session_id]))+ listing = asyncio.run(store.list_notebook_entries())assert listing["total"] == 1- assert listing["items"][0]["material_id"].startswith("import:")- assert repo.overview("UTC", session_ids=[session_id])["mistakes"] == 1- session = asyncio.run(store.get_session(session_id))- assert session["preferences"]["course_id"] == "course-a"- assert session["preferences"]["archived"] is True- # Metadata enumeration includes archived notebook sessions, preserving course scope.- from deeptutor.services.session.organization import list_all_sessions_snapshot-- assert session_id in {- item["session_id"] for item in asyncio.run(list_all_sessions_snapshot(store))- }- assert client.get("/bank/entries?course_id=course-a").json()["total"] == 1- assert client.get("/practice/summary?course_id=course-a").json()["mistakes"] == 1+ item = listing["items"][0]+ assert item["session_id"] == ""+ assert item["origin_type"] == "external_import"+ assert item["origin_ref"] == "practice-import"+ assert item["material_id"].startswith("import:")+ assert repo.overview("UTC")["mistakes"] == 1+ # Import provenance must not manufacture a conversation or leak into a+ # conversation-derived course scope.+ assert asyncio.run(store.list_sessions()) == []+ assert client.get("/bank/entries?course_id=course-a").json()["total"] == 0+ assert client.get("/practice/summary?course_id=course-a").json()["mistakes"] == 0assert client.get("/bank/entries?course_id=course-b").json()["total"] == 0diff --git a/tests/api/test_question_bank_api.py b/tests/api/test_question_bank_api.pyindex 6600c0940..b41dacad3 100644--- a/tests/api/test_question_bank_api.py+++ b/tests/api/test_question_bank_api.py@@ -107,6 +107,56 @@ def test_unknown_assessment_source_is_rejected(client):assert response.status_code == 422+def test_document_entry_without_session_is_idempotent_and_lookupable(client):+ payload = {+ "origin_type": "document_analysis",+ "origin_ref": "book:linear-algebra:section-2",+ "question_id": "focus-1",+ "question": "What is the rank?",+ "source": "book",+ "material_id": "linear-algebra",+ "material_title": "Linear Algebra",+ "section_title": "Rank",+ }+ first = client.post(f"{PREFIX}/entries/upsert", json=payload)+ second = client.post(+ f"{PREFIX}/entries/upsert",+ json={**payload, "user_answer": "2"},+ )++ assert first.status_code == 200+ assert second.status_code == 200+ assert first.json()["id"] == second.json()["id"]+ assert second.json()["session_id"] == ""+ assert second.json()["origin_type"] == "document_analysis"+ assert second.json()["origin_ref"] == payload["origin_ref"]+ assert second.json()["user_answer"] == "2"++ lookup = client.get(+ f"{PREFIX}/entries/lookup/by-question",+ params={+ "origin_type": "document_analysis",+ "origin_ref": payload["origin_ref"],+ "question_id": payload["question_id"],+ },+ )+ assert lookup.status_code == 200+ assert lookup.json()["id"] == first.json()["id"]+ assert client.get(f"{PREFIX}/entries").json()["total"] == 1+++def test_independent_entry_requires_a_stable_origin_reference(client):+ response = client.post(+ f"{PREFIX}/entries/upsert",+ json={+ "origin_type": "external_import",+ "question_id": "q-1",+ "question": "Imported?",+ },+ )+ assert response.status_code == 422++def test_listing_carries_each_entry_categories(client):ids = _seed(client)category_id = client.post(f"{PREFIX}/categories", json={"name": "Set A"}).json()["id"]diff --git a/tests/api/test_reading_quiz_answers.py b/tests/api/test_reading_quiz_answers.pyindex fb82f9bae..1cc401ca7 100644--- a/tests/api/test_reading_quiz_answers.py+++ b/tests/api/test_reading_quiz_answers.py@@ -136,7 +136,7 @@ def test_focus_check_entries_land_in_unified_list(assert by_id["q_2"]["user_answer"] == "3"-def test_no_session_saves_in_a_reading_notebook_container(store: SQLiteSessionStore) -> None:+def test_no_session_saves_with_document_provenance(store: SQLiteSessionStore) -> None:asyncio.run(store.put_reading_quiz_pending(MATERIAL_ID, LOCATOR, _quiz_questions()))with TestClient(_build_app(store)) as client:resp = client.post(@@ -147,7 +147,10 @@ def test_no_session_saves_in_a_reading_notebook_container(store: SQLiteSessionStassert resp.json()["answers"][0]["is_correct"] is Truelisting = asyncio.run(store.list_notebook_entries())assert listing["total"] == 2- assert {item["session_id"] for item in listing["items"]} == {f"reading-notebook:{MATERIAL_ID}"}+ assert {item["session_id"] for item in listing["items"]} == {""}+ assert {item["origin_type"] for item in listing["items"]} == {"document_analysis"}+ assert {item["origin_ref"] for item in listing["items"]} == {f"reading:{MATERIAL_ID}"}+ assert asyncio.run(store.list_sessions()) == []def test_missing_answer_key_is_409(store: SQLiteSessionStore) -> None:@@ -245,7 +248,7 @@ def test_regenerated_quiz_rejects_the_previous_cards(store):assert response.status_code == 409-def test_standalone_submission_retry_keeps_one_container_and_one_record(store):+def test_standalone_submission_retry_keeps_one_origin_and_one_record(store):asyncio.run(store.put_reading_quiz_pending(MATERIAL_ID, LOCATOR, _quiz_questions()))with TestClient(_build_app(store)) as client:for _ in range(2):diff --git a/tests/services/session/test_sqlite_store.py b/tests/services/session/test_sqlite_store.pyindex 4de350336..c00f97861 100644--- a/tests/services/session/test_sqlite_store.py+++ b/tests/services/session/test_sqlite_store.py@@ -116,6 +116,8 @@ def test_store_migrates_legacy_notebook_review_columns(tmp_path: Path) -> None:assert listing["total"] == 1entry = listing["items"][0]assert entry["source"] == "deep_question"+ assert entry["origin_type"] == "conversation"+ assert entry["origin_ref"] == "session-1"assert entry["score_trend"] == "new"assert entry["resolved"] is Falseassert all(not entry[key] for key in ("material_id", "section_id"))@@ -457,6 +459,51 @@ def test_upsert_unknown_session_raises(store: SQLiteSessionStore) -> None:asyncio.run(store.upsert_notebook_entries("nope", _make_items(("q1", "Q?", False))))+def test_non_conversation_origin_upserts_without_a_session(+ store: SQLiteSessionStore,+) -> None:+ item = {+ "origin_type": "document_analysis",+ "origin_ref": "book:algebra:page-12",+ "question_id": "q1",+ "question": "What is the slope?",+ "source": "book",+ "material_id": "algebra",+ "is_correct": False,+ }++ assert asyncio.run(store.upsert_notebook_entries(None, [item])) == 1+ item["user_answer"] = "3"+ assert asyncio.run(store.upsert_notebook_entries(None, [item])) == 1++ listing = asyncio.run(store.list_notebook_entries())+ assert listing["total"] == 1+ entry = listing["items"][0]+ assert entry["session_id"] == ""+ assert entry["origin_type"] == "document_analysis"+ assert entry["origin_ref"] == "book:algebra:page-12"+ assert entry["user_answer"] == "3"+ assert asyncio.run(store.list_notebook_entries(session_ids=[]))["total"] == 0+++def test_non_conversation_origin_requires_a_stable_reference(+ store: SQLiteSessionStore,+) -> None:+ with pytest.raises(ValueError, match="require origin_ref"):+ asyncio.run(+ store.upsert_notebook_entries(+ None,+ [+ {+ "origin_type": "external_import",+ "question_id": "q1",+ "question": "Imported?",+ }+ ],+ )+ )++def test_list_entries_filters_bookmarked(store: SQLiteSessionStore) -> None:session = asyncio.run(store.create_session())asyncio.run(@@ -710,25 +757,27 @@ def test_entries_follow_a_session_into_and_out_of_the_recycle_bin(asyncio.run(store.soft_delete_session(session["id"]))assert asyncio.run(store.hard_delete_session(session["id"]))- assert asyncio.run(store.list_notebook_entries())["total"] == 0+ detached = asyncio.run(store.list_notebook_entries())+ assert detached["total"] == 1+ assert detached["items"][0]["session_id"] == ""+ assert detached["items"][0]["origin_ref"] == session["id"]-def test_entries_cascade_when_a_session_is_deleted_outright(+def test_entries_keep_provenance_when_a_session_is_deleted_outright(store: SQLiteSessionStore,) -> None:- """`delete_session` skips the bin, so ON DELETE CASCADE fires at once.-- This is the path the reading cleanups take: a workspace that is gone- takes its sessions with it, and those must not surface in the learner's- recycle bin to be restored into a workspace that no longer exists.- """+ """Deleting a chat removes navigation without deleting learning evidence."""session = asyncio.run(store.create_session())asyncio.run(store.upsert_notebook_entries(session["id"], _make_items(("q1", "Q?", False))))assert asyncio.run(store.list_notebook_entries())["total"] == 1assert asyncio.run(store.delete_session(session["id"]))- assert asyncio.run(store.list_notebook_entries())["total"] == 0+ listing = asyncio.run(store.list_notebook_entries())+ assert listing["total"] == 1+ assert listing["items"][0]["session_id"] == ""+ assert listing["items"][0]["origin_type"] == "conversation"+ assert listing["items"][0]["origin_ref"] == session["id"]assert asyncio.run(store.list_deleted_sessions()) == []assert asyncio.run(store.restore_session(session["id"])) is Falsediff --git a/tests/services/workspace/test_data_migration.py b/tests/services/workspace/test_data_migration.pyindex 73ca28792..59323aa00 100644--- a/tests/services/workspace/test_data_migration.py+++ b/tests/services/workspace/test_data_migration.py@@ -25,6 +25,20 @@ async def test_migration_keeps_messages_branches_questions_and_source_backup(accreply_id = await store.add_message(session["id"], "assistant", "answer", parent_message_id=user_id)+ await store.upsert_notebook_entries(+ session["id"],+ [{"question_id": "question-one", "question": "Keep this question"}],+ )+ notebook_id = (await store.find_notebook_entry(session["id"], "question-one"))["id"]+ await store.append_assessment_attempt(+ session["id"],+ notebook_id,+ {+ "attempt_id": "attempt-one",+ "question_id": "question-one",+ "result": "correct",+ },+ )paths = get_path_service()book = paths.get_book_dir() / "book_one"book.mkdir(parents=True)@@ -52,9 +66,17 @@ async def test_migration_keeps_messages_branches_questions_and_source_backup(accmessages = await migrated.get_messages(session["id"])assert [row["id"] for row in messages] == [user_id, reply_id]assert messages[1]["parent_message_id"] == user_id+ questions = await migrated.list_notebook_entries(session_id=session["id"])+ assert questions["items"][0]["question"] == "Keep this question"+ attempts = await migrated.list_assessment_attempts(+ session["id"], question_id="question-one"+ )+ assert attempts[0]["attempt_id"] == "attempt-one"assert (get_path_service().get_book_dir() / "book_one" / "inputs.json").exists()with workspace_context():assert await store.get_session(session["id"]) is None+ assert not (await store.list_notebook_entries(session_id=session["id"]))["items"]+ assert not await store.list_assessment_attempts(session["id"], question_id="question-one")assert not book.exists()diff --git a/tests/tools/test_question_bank_tool.py b/tests/tools/test_question_bank_tool.pyindex c84c72ad2..fa7f14c2a 100644--- a/tests/tools/test_question_bank_tool.py+++ b/tests/tools/test_question_bank_tool.py@@ -190,7 +190,7 @@ class _FakePartnerContext:@pytest.mark.asyncio-async def test_record_files_a_partner_mistake_into_a_browsable_session(+async def test_record_files_a_partner_mistake_without_a_placeholder_session(store: SQLiteSessionStore,) -> None:outcome = await run_question_bank(@@ -204,16 +204,20 @@ async def test_record_files_a_partner_mistake_into_a_browsable_session()assert outcome.ok, outcome.error- session_id = outcome.summary["session_id"]+ assert outcome.summary["session_id"] == ""+ assert outcome.summary["origin_type"] == "external_import"+ origin_ref = outcome.summary["origin_ref"]assert outcome.summary["source"] == "partner_chat"- # The placeholder session exists so the entry is browsable, and the- # mistake landed in it, labelled as coming from a partner conversation.stats = await store.question_bank_stats()assert stats["total"] == 1- entry = await store.find_notebook_entry(session_id, outcome.summary["question_id"])+ entry = await store.find_notebook_entry_by_origin(+ "external_import", origin_ref, outcome.summary["question_id"]+ )assert entry is not None+ assert entry["session_id"] == ""assert entry["source"] == "partner_chat"assert entry["question"] == "What is 7 × 8?"+ assert await store.list_sessions() == []# The optional category was created and the entry filed into it.assert "Filed under 'Multiplication drills'" in outcome.textdiff --git a/web/components/chat/QuestionBankPicker.tsx b/web/components/chat/QuestionBankPicker.tsxindex 468af1a75..8eecc9ae6 100644--- a/web/components/chat/QuestionBankPicker.tsx+++ b/web/components/chat/QuestionBankPicker.tsx@@ -27,6 +27,15 @@ export interface SelectedQuestionEntry {difficulty: string;}+function provenanceLabel(entry: NotebookEntry): string {+ return (+ entry.session_title ||+ entry.section_title ||+ entry.material_title ||+ (entry.origin_type === "conversation" ? "" : entry.origin_ref || "")+ );+}+interface QuestionBankPickerProps {open: boolean;onClose: () => void;@@ -101,8 +110,8 @@ export default function QuestionBankPicker({if (!keyword) return entries;return entries.filter((entry) => {const question = String(entry.question || "").toLowerCase();- const session = String(entry.session_title || "").toLowerCase();- return question.includes(keyword) || session.includes(keyword);+ const provenance = provenanceLabel(entry).toLowerCase();+ return question.includes(keyword) || provenance.includes(keyword);});}, [entries, query]);@@ -280,9 +289,9 @@ export default function QuestionBankPicker({<p className="mt-1 line-clamp-2 text-[13px] leading-5 text-[var(--foreground)]">{entry.question}</p>- {entry.session_title && (+ {provenanceLabel(entry) && (<div className="mt-1 truncate text-[11px] text-[var(--muted-foreground)]/85">- {entry.session_title}+ {provenanceLabel(entry)}</div>)}</div>diff --git a/web/components/space/question-bank/QuestionCard.tsx b/web/components/space/question-bank/QuestionCard.tsxindex 8b7275ee7..d126973b4 100644--- a/web/components/space/question-bank/QuestionCard.tsx+++ b/web/components/space/question-bank/QuestionCard.tsx@@ -190,6 +190,13 @@ export default function QuestionCard({const badge = resultBadge(entry);const showReviewState =!!entry.practice?.is_mistake || mistakesOnly || result === "incorrect" || result === "partial";+ const independentProvenance =+ !entry.session_id &&+ entry.source !== "book" &&+ entry.source !== "immersive_reading" &&+ entry.source !== "mastery_path"+ ? entry.material_title || entry.section_title || entry.origin_ref || ""+ : "";return (<li@@ -462,7 +469,9 @@ export default function QuestionCard({</button></span>))}- {entry.source !== "import" && !entry.session_id.startsWith("reading-notebook:") && (+ {entry.session_id &&+ entry.source !== "import" &&+ !entry.session_id.startsWith("reading-notebook:") && (<Linkhref={entry.source === "mastery_path" && (entry.mastery_path_id || entry.material_id)@@ -478,6 +487,11 @@ export default function QuestionCard({{entry.session_title || t("Original Session")}</Link>)}+ {independentProvenance && (+ <span className="inline-flex items-center rounded-md border border-[var(--border)] bg-[var(--muted)]/40 px-2 py-0.5 text-[var(--muted-foreground)]">+ {independentProvenance}+ </span>+ )}{entry.source === "book" && entry.material_id && (<Linkhref={bookRoute(entry.material_id, entry.section_id)}diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.tsindex 01ca021d9..890aef188 100644--- a/web/lib/notebook-api.ts+++ b/web/lib/notebook-api.ts@@ -201,6 +201,9 @@ export interface NotebookEntry {id: number;session_id: string;session_title: string;+ /** Present on servers with independent Question Bank provenance support. */+ origin_type?: QuestionOriginType;+ origin_ref?: string;turn_id: string;question_id: string;question: string;@@ -259,6 +262,11 @@ export type AssessmentSource =| "partner_chat"| "import";+export type QuestionOriginType =+ | "conversation"+ | "external_import"+ | "document_analysis";+export type AssessmentType = "quiz" | "focus_check" | "qualitative" | "review";export type AssessmentResult =@@ -323,9 +331,10 @@ export interface NotebookEntryFilter {/*** Restrict to questions produced by one course's conversations.*- * Entries carry a session, not a course, so the server resolves this to the- * course's sessions. A course with no sessions yet correctly yields nothing- * rather than falling back to everything.+ * The server resolves course membership through real conversation sessions;+ * independent document/import origins stay outside that scope until they+ * gain an explicit course association. A course with no sessions correctly+ * yields nothing rather than falling back to everything.*/course_id?: string;}@@ -400,6 +409,26 @@ export async function lookupNotebookEntry(return expectJson<NotebookEntry>(response);}+export async function lookupNotebookEntryByOrigin(+ originType: Exclude<QuestionOriginType, "conversation">,+ originRef: string,+ questionId: string,+ turnId?: string | null,+): Promise<NotebookEntry | null> {+ const params = new URLSearchParams({+ origin_type: originType,+ origin_ref: originRef,+ question_id: questionId,+ missing_ok: "true",+ });+ if (turnId) params.set("turn_id", turnId);+ const response = await apiFetch(+ apiUrl(`/api/question-notebook/entries/lookup/by-question?${params}`),+ );+ if (response.status === 204 || response.status === 404) return null;+ return expectJson<NotebookEntry>(response);+}+export async function updateNotebookEntry(entryId: number,updates: {@@ -431,7 +460,9 @@ export interface NotebookAnswerImageUpload {}export async function upsertNotebookEntry(data: {- session_id: string;+ session_id?: string;+ origin_type?: QuestionOriginType;+ origin_ref?: string;turn_id?: string;question_id: string;question: string;diff --git a/web/tests/practice-display-stats.spec.tsx b/web/tests/practice-display-stats.spec.tsxindex 17412cb5f..e7cfea453 100644--- a/web/tests/practice-display-stats.spec.tsx+++ b/web/tests/practice-display-stats.spec.tsx@@ -110,6 +110,47 @@ it("keeps the complete stem and choices visible while hiding answer evidence", aexpect(screen.getByText("Fields are merged.")).toBeVisible();});+it("shows independent provenance without inventing an original-session link", () => {+ const entry = {+ id: 2,+ question: "Imported question",+ question_type: "short",+ options: {},+ correct_answer: "A",+ user_answer: "B",+ result: "incorrect",+ source: "import",+ origin_type: "external_import",+ origin_ref: "practice-import:receipt-1",+ session_id: "",+ session_title: "",+ material_title: "lesson.csv",+ categories: [],+ created_at: 100,+ updated_at: 100,+ } as unknown as NotebookEntry;+ render(+ <ul>+ <QuestionCard+ entry={entry}+ categories={[]}+ selected={false}+ disabled={false}+ onToggleSelected={vi.fn()}+ onToggleBookmark={vi.fn()}+ onToggleResolved={vi.fn()}+ onDelete={vi.fn()}+ onFile={vi.fn()}+ onUnfile={vi.fn()}+ onCreateAndFile={vi.fn()}+ />+ </ul>+ );++ expect(screen.queryByRole("link", { name: "Original Session" })).not.toBeInTheDocument();+ expect(screen.getByText("lesson.csv")).toBeVisible();+});+it("switches metrics and charts without losing course scope and exposes exact daily values", async () => {const { rerender } = render(<PracticeInsights courseId="course-a" revision={0} />);await screen.findByText("Mastery Path");