Skip to content

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

feat(tools): add a question_bank tool so the tutor can file questions

Bingxi Zhao (Frank)2503c2ccc4bb
diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.py
index 77306e81a..68a9b8931 100644
--- a/deeptutor/agents/_shared/tool_composition.py
+++ b/deeptutor/agents/_shared/tool_composition.py
@@ -51,6 +51,7 @@ _CONDITIONAL_MOUNT_FLAGS: dict[str, str] = {
"read_memory": "has_memory",
"list_notebook": "has_notebooks",
"write_note": "has_notebooks",
+ "question_bank": "has_question_bank",
"read_skill": "has_skills",
"load_tools": "has_deferred_tools",
"exec": "has_exec",
@@ -136,6 +137,7 @@ class ToolMountFlags:
has_sources: bool = False
has_memory: bool = False
has_notebooks: bool = False
+ has_question_bank: bool = False
has_skills: bool = False
has_deferred_tools: bool = False
has_exec: bool = False
@@ -294,6 +296,22 @@ def user_has_notebooks() -> bool:
return False
+def user_has_question_bank() -> bool:
+ """Whether the learner has any saved quiz questions.
+
+ Auto-mount gate for ``question_bank``. Separate from
+ :func:`user_has_notebooks` on purpose — the bank and the notebooks are
+ different stores, and a learner routinely has one without the other.
+ Same fail-closed posture as its siblings.
+ """
+ try:
+ from deeptutor.services.session import get_sqlite_session_store
+
+ return get_sqlite_session_store().has_question_bank_entries()
+ except Exception:
+ return False
+
+
__all__ = [
"AUTO_MOUNTED_TOOLS",
"ToolMountFlags",
@@ -302,4 +320,5 @@ __all__ = [
"default_optional_tools",
"user_has_memory",
"user_has_notebooks",
+ "user_has_question_bank",
]
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 04a3e2a08..dff3b0a4a 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -12,6 +12,7 @@ from deeptutor.agents._shared.tool_composition import (
default_optional_tools,
user_has_memory,
user_has_notebooks,
+ user_has_question_bank,
)
from deeptutor.agents.chat.agent_loop import AgentLoop
from deeptutor.agents.chat.context_budget import LLMRequestSnapshot, build_context_budget
@@ -625,6 +626,7 @@ class AgenticChatPipeline:
has_sources=False,
has_memory=user_has_memory(),
has_notebooks=user_has_notebooks(),
+ has_question_bank=user_has_question_bank(),
has_skills=bool(context.skills_manifest),
has_deferred_tools=getattr(self, "_deferred_loader", None) is not None,
has_exec=getattr(self, "_exec_enabled", False),
diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.py
index fa634b35b..c21222916 100644
--- a/deeptutor/agents/question/pipeline.py
+++ b/deeptutor/agents/question/pipeline.py
@@ -40,6 +40,7 @@ from deeptutor.agents._shared.tool_composition import (
default_optional_tools,
user_has_memory,
user_has_notebooks,
+ user_has_question_bank,
)
from deeptutor.core.agentic import (
DispatchOutcome,
@@ -1500,6 +1501,7 @@ class QuestionPipeline:
has_sources=bool(self._source_index(context)),
has_memory=user_has_memory(),
has_notebooks=user_has_notebooks(),
+ has_question_bank=user_has_question_bank(),
has_code=exec_capability_available(),
)
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index edaa6fb9d..b6c447ca3 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -25,6 +25,8 @@ from deeptutor.tools.partner_memory import (
PartnerSearchTool,
)
from deeptutor.tools.prompting import load_prompt_hints
+from deeptutor.tools.question_bank import ACTIONS as QB_ACTIONS
+from deeptutor.tools.question_bank import FILTERS as QB_FILTERS
logger = logging.getLogger(__name__)
@@ -990,6 +992,120 @@ class ListNotebookTool(_PromptHintsMixin, BaseTool):
)
+class QuestionBankTool(_PromptHintsMixin, BaseTool):
+ """Read and organise the learner's question bank.
+
+ The bank (Learning Space → Question Bank) holds every graded quiz
+ question the learner has answered. It is a different store from the
+ notebooks ``write_note`` writes to; without this tool the agent had
+ no writable handle on it, so "file my wrong answers into my mistakes
+ set" silently became a note. Auto-mounted iff the bank has entries.
+
+ Actions are name-addressed, never id-addressed, for the one write
+ that matters: ``organize`` takes a category *name* and creates it
+ when missing, so filing is a single call from a single listing.
+ """
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="question_bank",
+ description=(
+ "Read and organise the learner's question bank — the graded "
+ "quiz questions saved under Learning Space → Question Bank. "
+ "This is where wrong answers and quiz history live; it is NOT "
+ "the notebook (`write_note`). Use it whenever the learner asks "
+ "to review, group, file, or tidy their questions or mistakes. "
+ "action='overview' for counts + existing categories; "
+ "action='list' to see entries (each prefixed with its id); "
+ "action='organize' to file entry_ids into a category by name "
+ "(the category is created if it does not exist); "
+ "action='unfile' to remove them; "
+ "action='bookmark' to star or unstar them."
+ ),
+ parameters=[
+ ToolParameter(
+ name="action",
+ type="string",
+ description=(
+ "'overview' (counts + categories, needs nothing else), "
+ "'list', 'organize', 'unfile', or 'bookmark'."
+ ),
+ enum=list(QB_ACTIONS),
+ ),
+ ToolParameter(
+ name="filter",
+ type="string",
+ description=(
+ "For action='list'. 'wrong' = answered incorrectly, "
+ "'uncategorized' = not filed anywhere yet (the triage "
+ "inbox), 'bookmarked', or 'all'. Default 'all'."
+ ),
+ enum=list(QB_FILTERS),
+ required=False,
+ ),
+ ToolParameter(
+ name="category",
+ type="string",
+ description=(
+ "Category name. Required for 'organize' / 'unfile'; "
+ "optional on 'list' to look inside one category. "
+ "'organize' creates the category when it is new."
+ ),
+ required=False,
+ ),
+ ToolParameter(
+ name="search",
+ type="string",
+ description="For action='list'. Free-text match over question and answers.",
+ required=False,
+ ),
+ ToolParameter(
+ name="entry_ids",
+ type="array",
+ description=(
+ "Entry ids to act on, from a `list` call (the number in "
+ "[brackets]). Required for 'organize' / 'unfile' / 'bookmark'."
+ ),
+ items={"type": "integer"},
+ required=False,
+ ),
+ ToolParameter(
+ name="bookmarked",
+ type="boolean",
+ description="For action='bookmark'. true to star, false to unstar. Default true.",
+ required=False,
+ ),
+ ToolParameter(
+ name="limit",
+ type="integer",
+ description="For action='list'. Max entries to return (default 20, max 100).",
+ required=False,
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.tools.question_bank import run_question_bank
+
+ outcome = await run_question_bank(
+ action=str(kwargs.get("action") or "overview"),
+ # ``filter`` is the schema name the model sees; the pure
+ # function avoids shadowing the builtin.
+ filter_mode=str(kwargs.get("filter") or "all"),
+ category=str(kwargs.get("category") or ""),
+ search=str(kwargs.get("search") or ""),
+ entry_ids=kwargs.get("entry_ids"),
+ bookmarked=bool(kwargs.get("bookmarked", True)),
+ limit=int(kwargs.get("limit") or 20),
+ )
+ if not outcome.ok:
+ return ToolResult(content=outcome.error, success=False)
+ return ToolResult(
+ content=outcome.text,
+ metadata={"question_bank": outcome.summary or {}},
+ )
+
+
class WriteNoteTool(_PromptHintsMixin, BaseTool):
"""Create OR edit a notebook record from the chat agent.
@@ -1579,6 +1695,7 @@ BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (
WebFetchTool,
ListNotebookTool,
WriteNoteTool,
+ QuestionBankTool,
GithubTool,
AskUserTool,
CronTool,
@@ -1667,6 +1784,7 @@ CONFIGURABLE_BUILTIN_TOOL_NAMES: tuple[str, ...] = (
"read_skill",
"list_notebook",
"write_note",
+ "question_bank",
"web_fetch",
"github",
"exec",
@@ -1703,6 +1821,7 @@ __all__ = [
"VideogenTool",
"ListNotebookTool",
"PaperSearchToolWrapper",
+ "QuestionBankTool",
"PartnerMemorizeTool",
"PartnerReadTool",
"PartnerSearchTool",
diff --git a/deeptutor/tools/prompting/hints/en/question_bank.yaml b/deeptutor/tools/prompting/hints/en/question_bank.yaml
new file mode 100644
index 000000000..34549df87
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/en/question_bank.yaml
@@ -0,0 +1,6 @@
+short_description: "Read and organise the learner's question bank — the graded quiz questions under Learning Space → Question Bank. NOT the notebook."
+when_to_use: "Whenever the learner talks about their questions, wrong answers, mistakes, or a question set / 题库: reviewing them, grouping them, filing them into a set, or tidying them up. Start with action='overview' (counts + existing category names), then action='list' to get entry ids, then action='organize' to file those ids under a category name. Do NOT reach for `write_note` for this — a note is prose, the bank is graded questions, and filing mistakes into a notebook is the wrong store."
+input_format: "overview: {\"action\": \"overview\"}. list: {\"action\": \"list\", \"filter\": \"wrong\" | \"uncategorized\" | \"bookmarked\" | \"all\", \"category\": optional name, \"search\": optional text, \"limit\": optional}. organize / unfile: {\"action\": \"organize\", \"entry_ids\": [12, 15], \"category\": \"Calculus mistakes\"}. bookmark: {\"action\": \"bookmark\", \"entry_ids\": [12], \"bookmarked\": true}."
+guideline: "`entry_ids` are the numbers shown in [brackets] by a `list` call — never invent them, always list first. `organize` creates the category when the name is new, so a learner asking to file mistakes into a brand-new set is ONE organize call, not a create-then-file. Reuse an existing category name verbatim when one already fits (overview lists them) instead of making a near-duplicate. filter='uncategorized' is the triage inbox — the right starting point for 'tidy up my question bank'."
+note: "Auto-mounted only when the bank actually has entries. Changes are live: the learner sees them immediately under Learning Space → Question Bank. Report what actually happened — the result says how many were filed and whether a new category was created."
+phase: "synthesis"
diff --git a/deeptutor/tools/prompting/hints/en/write_note.yaml b/deeptutor/tools/prompting/hints/en/write_note.yaml
index 5cc2853dc..0948482cd 100644
--- a/deeptutor/tools/prompting/hints/en/write_note.yaml
+++ b/deeptutor/tools/prompting/hints/en/write_note.yaml
@@ -1,5 +1,5 @@
short_description: "Save a new notebook record OR edit an existing one. mode='append' (new) or 'edit' (patch existing)."
-when_to_use: "append: user explicitly asked to save, or the turn produced a self-contained walkthrough worth keeping. edit: user asked to revise / extend / correct a record they previously saved. For edit, always run `list_notebook` first so you have the right record_id."
+when_to_use: "append: user explicitly asked to save, or the turn produced a self-contained walkthrough worth keeping. Filing quiz questions or wrong answers is `question_bank`'s job, not a notebook record. edit: user asked to revise / extend / correct a record they previously saved. For edit, always run `list_notebook` first so you have the right record_id."
input_format: "append: {\"mode\": \"append\", \"notebook_id\": \"...\", \"title\": \"...\", \"turns_to_include\": \"3\" | \"all\", \"note\": \"optional\"}. edit: {\"mode\": \"edit\", \"notebook_id\": \"...\", \"record_id\": \"...\", \"title\": optional, \"content\": optional, \"note\": optional}. In append mode you do NOT write the body — the tool inserts the real chat transcript itself; only pass `content` when you intentionally want to save an agent-authored summary."
guideline: "Default `turns_to_include` is 3. Use 'all' when the user says 'save this whole conversation'. Never invent notebook ids or record ids — the schema enum lists valid notebook_ids, and `list_notebook` gives you record ids. The optional `note` is short commentary ('why this matters', 'context to remember'), not the body."
note: "Auto-mounted only when the user has at least one notebook. On success the result includes the destination notebook name + record id — surface those to the user as confirmation. For edits the result confirms which field(s) changed."
diff --git a/deeptutor/tools/prompting/hints/zh/question_bank.yaml b/deeptutor/tools/prompting/hints/zh/question_bank.yaml
new file mode 100644
index 000000000..c2c190560
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/zh/question_bank.yaml
@@ -0,0 +1,6 @@
+short_description: "查看和整理用户的题库——即「学习空间 → 题库」里已作答的题目。注意:这不是笔记本。"
+when_to_use: "只要用户提到自己的题目、错题、题库、想复习/归类/整理它们,就用这个工具。标准顺序:先 action='overview'(拿到统计和已有的分类名),再 action='list' 拿到题目 id,最后 action='organize' 把这些 id 归入某个分类。这种需求绝不要用 `write_note`——笔记本存的是文字记录,题库存的是带答案的题目,把错题写进笔记本是存错了地方。"
+input_format: "overview: {\"action\": \"overview\"}。list: {\"action\": \"list\", \"filter\": \"wrong\" | \"uncategorized\" | \"bookmarked\" | \"all\", \"category\": 可选分类名, \"search\": 可选关键词, \"limit\": 可选}。organize / unfile: {\"action\": \"organize\", \"entry_ids\": [12, 15], \"category\": \"微积分错题\"}。bookmark: {\"action\": \"bookmark\", \"entry_ids\": [12], \"bookmarked\": true}。"
+guideline: "`entry_ids` 是 `list` 输出中方括号里的数字——不要凭空编造,一定先 list 再操作。`organize` 在分类名不存在时会自动新建,所以「把错题归到我新建的 X 题库」是一次 organize 调用就能完成,不需要先建后归。已有分类能对上就原样复用(overview 会列出来),不要造出近似重名的分类。filter='uncategorized' 是尚未归类的待整理区,用户说「帮我整理题库」时从这里入手。"
+note: "题库里没有任何题目时此工具不会出现。改动即时生效,用户在「学习空间 → 题库」里立刻能看到。结果里会说明实际归入了几道、是否新建了分类——如实转述,不要夸大。"
+phase: "synthesis"
diff --git a/deeptutor/tools/prompting/hints/zh/write_note.yaml b/deeptutor/tools/prompting/hints/zh/write_note.yaml
index 29a94ebfc..326d39593 100644
--- a/deeptutor/tools/prompting/hints/zh/write_note.yaml
+++ b/deeptutor/tools/prompting/hints/zh/write_note.yaml
@@ -1,5 +1,5 @@
short_description: "新增笔记本记录(mode='append')或修改已有记录(mode='edit')。"
-when_to_use: "append:用户明确要求保存,或本轮产生了自包含的解题过程 / 新概念整理 / 错题分析。edit:用户要求修改、扩展或更正之前保存的记录——edit 之前一定要先用 `list_notebook` 拿到正确的 record_id。"
+when_to_use: "append:用户明确要求保存,或本轮产生了自包含的解题过程 / 新概念整理。注意:归类错题、整理题库属于 `question_bank`,不要写进笔记本。edit:用户要求修改、扩展或更正之前保存的记录——edit 之前一定要先用 `list_notebook` 拿到正确的 record_id。"
input_format: "append: {\"mode\": \"append\", \"notebook_id\": \"...\", \"title\": \"...\", \"turns_to_include\": \"3\" 或 \"all\", \"note\": \"可选\"}。edit: {\"mode\": \"edit\", \"notebook_id\": \"...\", \"record_id\": \"...\", \"title\": 可选, \"content\": 可选, \"note\": 可选}。append 模式下你不需要写 body——工具会自己读真实对话历史拼好;只有在确实想保存你自己撰写的总结时才主动传 `content`。"
guideline: "`turns_to_include` 默认 3。用户说『把整段对话存下来』时用 'all'。永远不要凭空发明笔记本 id 或 record id——schema 枚举列出了合法 notebook_id,record_id 通过 `list_notebook` 拿到。`note` 是简短评注(『为什么值得保存』『以后看这条要记得的背景』),不是正文。"
note: "用户没有任何笔记本时此工具不会出现。append 成功后返回 notebook_name + record_id;edit 成功后会确认改了哪些字段,告诉用户即可。"
diff --git a/deeptutor/tools/question_bank.py b/deeptutor/tools/question_bank.py
new file mode 100644
index 000000000..9408b003a
--- /dev/null
+++ b/deeptutor/tools/question_bank.py
@@ -0,0 +1,380 @@
+"""Read and organise the learner's question bank from the chat agent.
+
+The question bank is the ``notebook_entries`` table behind
+``/space/questions``: every quiz question the learner has answered, in
+chat, in a quiz, or on a mastery path. It is a *different* store from
+the notebooks that :mod:`deeptutor.tools.write_note` writes to — notes
+are prose the learner keeps, bank entries are graded questions with a
+correct answer. Before this tool existed the agent had no way to touch
+the bank, so "file my wrong answers into my new question set" landed in
+a notebook instead: the only writable surface it could see.
+
+One tool, five actions, because the useful sequence is short and always
+the same — look, then file:
+
+* ``overview`` — counts + the existing category names (one call, no ids
+ needed; the natural first step).
+* ``list`` — entries under a filter, each prefixed with the id the
+ other actions consume.
+* ``organize`` — file entries into a category **by name**, creating it
+ when it does not exist yet. Name-addressed on purpose: the learner
+ says "my mistakes set", not "category 7", and a two-step
+ create-then-file is one more place for the model to drop the ball.
+* ``unfile`` — take entries back out of a category.
+* ``bookmark`` — star / unstar entries for later review.
+
+Every action is dependency-injected with ``store`` so tests never touch
+a real database, and every failure returns ``ok=False`` with a sentence
+the model can act on rather than raising.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import logging
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+ACTIONS = ("overview", "list", "organize", "unfile", "bookmark")
+
+FILTERS = ("all", "wrong", "bookmarked", "uncategorized")
+
+# Ceilings. The bank can hold thousands of rows; a listing is a working
+# set for one decision, not a dump. Both are echoed in the rendered text
+# when they bite so the model knows it is seeing a slice.
+DEFAULT_LIST_LIMIT = 20
+MAX_LIST_LIMIT = 100
+MAX_ENTRY_IDS = 200
+MAX_QUESTION_PREVIEW = 160
+MAX_ANSWER_PREVIEW = 60
+MAX_CATEGORY_NAME = 100
+
+
+@dataclass(frozen=True)
+class QuestionBankOutcome:
+ """Result of one ``question_bank`` invocation."""
+
+ ok: bool
+ action: str = ""
+ text: str = ""
+ error: str = ""
+ # Structured echo for the frontend; deliberately small.
+ summary: dict[str, Any] = field(default_factory=dict)
+
+
+def _truncate(value: str, limit: int) -> str:
+ text = " ".join(str(value or "").split())
+ return text if len(text) <= limit else text[: limit - 1] + "…"
+
+
+def _coerce_ids(raw: Any) -> tuple[list[int], list[str]]:
+ """Parse the model's ``entry_ids`` into ints, reporting what was junk.
+
+ Models hand back ``[3, "4", "id-5"]`` often enough that silently
+ dropping the bad ones would make a partial file look complete.
+ """
+ if raw is None:
+ return [], []
+ if isinstance(raw, (int, str)):
+ raw = [raw]
+ if not isinstance(raw, (list, tuple)):
+ return [], [str(raw)]
+ ids: list[int] = []
+ rejected: list[str] = []
+ for item in raw:
+ try:
+ value = int(str(item).strip())
+ except (TypeError, ValueError):
+ rejected.append(str(item))
+ continue
+ if value <= 0:
+ rejected.append(str(item))
+ continue
+ if value not in ids:
+ ids.append(value)
+ return ids[:MAX_ENTRY_IDS], rejected
+
+
+def _render_entry(entry: dict[str, Any]) -> str:
+ mark = "✓" if entry.get("is_correct") else "✗"
+ star = " ★" if entry.get("bookmarked") else ""
+ line = f"- [{entry.get('id')}] {mark}{star} {_truncate(entry.get('question', ''), MAX_QUESTION_PREVIEW)}"
+ given = _truncate(entry.get("user_answer", ""), MAX_ANSWER_PREVIEW)
+ expected = _truncate(entry.get("correct_answer", ""), MAX_ANSWER_PREVIEW)
+ if given or expected:
+ line += f"\n answered: {given or '—'} | correct: {expected or '—'}"
+ cats = [str(c.get("name", "")) for c in (entry.get("categories") or []) if c.get("name")]
+ line += f"\n filed in: {', '.join(cats)}" if cats else "\n filed in: (nothing yet)"
+ return line
+
+
+def _render_categories(categories: list[dict[str, Any]]) -> str:
+ if not categories:
+ return "(no categories yet — `organize` creates one by name)"
+ return ", ".join(f"{c.get('name')} ({c.get('entry_count', 0)})" for c in categories)
+
+
+async def _resolve_store(store: Any) -> Any:
+ if store is not None:
+ return store
+ from deeptutor.services.session import get_sqlite_session_store
+
+ return get_sqlite_session_store()
+
+
+async def _overview(store: Any) -> QuestionBankOutcome:
+ stats = await store.question_bank_stats()
+ categories = await store.list_categories()
+ if not stats.get("total"):
+ return QuestionBankOutcome(
+ ok=True,
+ action="overview",
+ text="The question bank is empty — the learner has not answered any quiz questions yet.",
+ summary={"stats": stats, "categories": []},
+ )
+ text = (
+ f"Question bank: {stats['total']} questions "
+ f"({stats['wrong']} answered wrong, {stats['bookmarked']} bookmarked, "
+ f"{stats['uncategorized']} not filed in any category).\n"
+ f"Categories: {_render_categories(categories)}\n\n"
+ "Next: `list` the entries you want (filter='wrong' or 'uncategorized'), "
+ "then `organize` them into a category by name."
+ )
+ return QuestionBankOutcome(
+ ok=True,
+ action="overview",
+ text=text,
+ summary={"stats": stats, "categories": categories},
+ )
+
+
+async def _list(
+ store: Any,
+ *,
+ filter_mode: str,
+ category: str,
+ search: str,
+ limit: int,
+) -> QuestionBankOutcome:
+ mode = (filter_mode or "all").strip().lower()
+ if mode not in FILTERS:
+ return QuestionBankOutcome(
+ ok=False,
+ action="list",
+ error=f"Unknown filter {filter_mode!r}. Use one of: {', '.join(FILTERS)}.",
+ )
+
+ category_id: int | None = None
+ wanted = (category or "").strip()
+ if wanted:
+ match = await store.find_category_by_name(wanted)
+ if match is None:
+ categories = await store.list_categories()
+ return QuestionBankOutcome(
+ ok=False,
+ action="list",
+ error=(
+ f"No category named {wanted!r}. Existing: {_render_categories(categories)}."
+ ),
+ )
+ category_id = int(match["id"])
+
+ capped = max(1, min(int(limit or DEFAULT_LIST_LIMIT), MAX_LIST_LIMIT))
+ result = await store.list_notebook_entries(
+ category_id=category_id,
+ uncategorized=mode == "uncategorized",
+ bookmarked=True if mode == "bookmarked" else None,
+ is_correct=False if mode == "wrong" else None,
+ search=search or "",
+ limit=capped,
+ )
+ items = list(result.get("items") or [])
+ total = int(result.get("total") or 0)
+ if not items:
+ return QuestionBankOutcome(
+ ok=True,
+ action="list",
+ text="No question-bank entries match that filter.",
+ summary={"count": 0, "total": 0, "filter": mode},
+ )
+
+ header = f"Question bank — {mode}"
+ if wanted:
+ header += f" in category '{wanted}'"
+ if search:
+ header += f" matching '{search}'"
+ header += f" ({len(items)} of {total}):"
+ lines = [header, ""]
+ lines.extend(_render_entry(entry) for entry in items)
+ if total > len(items):
+ lines.append(f"\n... {total - len(items)} more; raise `limit` or narrow with `search`.")
+ lines.append(
+ "\nThe number in [brackets] is the entry id — pass those ids to "
+ "`organize` to file them into a category."
+ )
+ return QuestionBankOutcome(
+ ok=True,
+ action="list",
+ text="\n".join(lines),
+ summary={
+ "count": len(items),
+ "total": total,
+ "filter": mode,
+ "entry_ids": [int(i["id"]) for i in items],
+ },
+ )
+
+
+async def _resolve_or_create_category(store: Any, name: str) -> tuple[dict[str, Any], bool]:
+ """Return ``(category, created)`` for a display name.
+
+ Reuses an existing name case-insensitively so "Wrong Answers" and
+ "wrong answers" cannot become two piles of the same thing.
+ """
+ existing = await store.find_category_by_name(name)
+ if existing is not None:
+ return existing, False
+ created = await store.create_category(name)
+ return created, True
+
+
+async def _organize(
+ store: Any, *, entry_ids: Any, category: str, link: bool
+) -> QuestionBankOutcome:
+ action = "organize" if link else "unfile"
+ name = (category or "").strip()[:MAX_CATEGORY_NAME]
+ if not name:
+ return QuestionBankOutcome(
+ ok=False,
+ action=action,
+ error="`category` is required — the name of the set to file these questions under.",
+ )
+ ids, rejected = _coerce_ids(entry_ids)
+ if not ids:
+ return QuestionBankOutcome(
+ ok=False,
+ action=action,
+ error=(
+ "`entry_ids` must contain at least one numeric entry id from a "
+ "`list` call (the number in [brackets])."
+ ),
+ )
+
+ if link:
+ category_row, created = await _resolve_or_create_category(store, name)
+ else:
+ match = await store.find_category_by_name(name)
+ if match is None:
+ return QuestionBankOutcome(
+ ok=False,
+ action=action,
+ error=f"No category named {name!r} to remove entries from.",
+ )
+ category_row, created = match, False
+
+ changed = await store.link_entries_to_category(ids, int(category_row["id"]), link=link)
+ verb = "filed into" if link else "removed from"
+ parts = [f"{changed} of {len(ids)} question(s) {verb} '{category_row['name']}'."]
+ if created:
+ parts.append("The category did not exist and was created.")
+ if changed < len(ids) and link:
+ parts.append(
+ f"{len(ids) - changed} skipped (already filed there, or no longer in the bank)."
+ )
+ if rejected:
+ parts.append(f"Ignored non-numeric ids: {', '.join(rejected[:5])}.")
+ parts.append("The learner sees this immediately under Learning Space → Question Bank.")
+ return QuestionBankOutcome(
+ ok=True,
+ action=action,
+ text=" ".join(parts),
+ summary={
+ "changed": changed,
+ "requested": len(ids),
+ "category": category_row["name"],
+ "category_id": int(category_row["id"]),
+ "created_category": created,
+ "link": link,
+ },
+ )
+
+
+async def _bookmark(store: Any, *, entry_ids: Any, bookmarked: bool) -> QuestionBankOutcome:
+ ids, rejected = _coerce_ids(entry_ids)
+ if not ids:
+ return QuestionBankOutcome(
+ ok=False,
+ action="bookmark",
+ error="`entry_ids` must contain at least one numeric entry id from a `list` call.",
+ )
+ updated = 0
+ for entry_id in ids:
+ try:
+ if await store.update_notebook_entry(entry_id, {"bookmarked": bookmarked}):
+ updated += 1
+ except Exception:
+ logger.warning("question_bank: bookmark failed for entry %s", entry_id, exc_info=True)
+ verb = "bookmarked" if bookmarked else "un-bookmarked"
+ text = f"{updated} of {len(ids)} question(s) {verb}."
+ if rejected:
+ text += f" Ignored non-numeric ids: {', '.join(rejected[:5])}."
+ return QuestionBankOutcome(
+ ok=updated > 0,
+ action="bookmark",
+ text=text,
+ error="" if updated else "No matching entries were updated.",
+ summary={"updated": updated, "requested": len(ids), "bookmarked": bookmarked},
+ )
+
+
+async def run_question_bank(
+ *,
+ action: str = "overview",
+ filter_mode: str = "all",
+ category: str = "",
+ search: str = "",
+ entry_ids: Any = None,
+ bookmarked: bool = True,
+ limit: int = DEFAULT_LIST_LIMIT,
+ store: Any = None,
+) -> QuestionBankOutcome:
+ """Run one question-bank action. Never raises — errors come back typed."""
+ verb = (action or "overview").strip().lower()
+ if verb not in ACTIONS:
+ return QuestionBankOutcome(
+ ok=False,
+ action=verb,
+ error=f"Unknown action {action!r}. Use one of: {', '.join(ACTIONS)}.",
+ )
+ try:
+ resolved = await _resolve_store(store)
+ if verb == "overview":
+ return await _overview(resolved)
+ if verb == "list":
+ return await _list(
+ resolved,
+ filter_mode=filter_mode,
+ category=category,
+ search=search,
+ limit=limit,
+ )
+ if verb in {"organize", "unfile"}:
+ return await _organize(
+ resolved,
+ entry_ids=entry_ids,
+ category=category,
+ link=verb == "organize",
+ )
+ return await _bookmark(resolved, entry_ids=entry_ids, bookmarked=bookmarked)
+ except Exception as exc:
+ logger.warning("question_bank action %s failed", verb, exc_info=True)
+ return QuestionBankOutcome(ok=False, action=verb, error=f"Question bank error: {exc}")
+
+
+__all__ = [
+ "ACTIONS",
+ "FILTERS",
+ "QuestionBankOutcome",
+ "run_question_bank",
+]
diff --git a/tests/tools/test_question_bank_tool.py b/tests/tools/test_question_bank_tool.py
new file mode 100644
index 000000000..16f54c2bd
--- /dev/null
+++ b/tests/tools/test_question_bank_tool.py
@@ -0,0 +1,174 @@
+"""The ``question_bank`` tool: the agent's only writable handle on the bank.
+
+Regression cover for the reported failure — "file my wrong answers into
+my new mistakes set" ended up in a notebook because no tool could reach
+the question bank. These tests pin the shape that makes the ask a single
+call: list gives ids, organize files them under a *name* and creates the
+category when it is new.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from deeptutor.services.session.sqlite_store import SQLiteSessionStore
+from deeptutor.tools.question_bank import run_question_bank
+
+
+def store(tmp_path: Path) -> SQLiteSessionStore:
+ return SQLiteSessionStore(db_path=tmp_path / "bank.db")
+
+
+async def _seed(store: SQLiteSessionStore) -> str:
+ session = await store.create_session(title="Drill")
+ session_id = session["id"]
+ await store.upsert_notebook_entries(
+ session_id,
+ [
+ {
+ "turn_id": "t1",
+ "question_id": "q1",
+ "question": "Derivative of sin(x)?",
+ "correct_answer": "cos(x)",
+ "user_answer": "-cos(x)",
+ "is_correct": False,
+ },
+ {
+ "turn_id": "t1",
+ "question_id": "q2",
+ "question": "Integral of 1/x?",
+ "correct_answer": "ln|x| + C",
+ "user_answer": "ln|x| + C",
+ "is_correct": True,
+ },
+ ],
+ )
+ return session_id
+
+
+async def test_overview_on_empty_bank_is_explicit(store: SQLiteSessionStore) -> None:
+ outcome = await run_question_bank(action="overview", store=store)
+ assert outcome.ok
+ assert "empty" in outcome.text
+
+
+async def test_list_wrong_exposes_ids_for_filing(store: SQLiteSessionStore) -> None:
+ await _seed(store)
+ outcome = await run_question_bank(action="list", filter_mode="wrong", store=store)
+ assert outcome.ok
+ assert outcome.summary["count"] == 1
+ assert len(outcome.summary["entry_ids"]) == 1
+ # The rendered id is what the model copies into ``organize``.
+ assert f"[{outcome.summary['entry_ids'][0]}]" in outcome.text
+
+
+async def test_organize_creates_the_category_it_is_given(store: SQLiteSessionStore) -> None:
+ await _seed(store)
+ listing = await run_question_bank(action="list", filter_mode="wrong", store=store)
+ ids = listing.summary["entry_ids"]
+
+ outcome = await run_question_bank(
+ action="organize", entry_ids=ids, category="微积分错题", store=store
+ )
+ assert outcome.ok
+ assert outcome.summary["created_category"] is True
+ assert outcome.summary["changed"] == len(ids)
+
+ categories = await store.list_categories()
+ assert [(c["name"], c["entry_count"]) for c in categories] == [("微积分错题", len(ids))]
+
+
+async def test_organize_is_idempotent_and_never_duplicates_a_category(
+ store: SQLiteSessionStore,
+) -> None:
+ await _seed(store)
+ ids = (await run_question_bank(action="list", store=store)).summary["entry_ids"]
+ await run_question_bank(action="organize", entry_ids=ids, category="Mistakes", store=store)
+
+ repeat = await run_question_bank(
+ action="organize", entry_ids=ids, category="mistakes", store=store
+ )
+ assert repeat.ok
+ assert repeat.summary["created_category"] is False
+ assert repeat.summary["changed"] == 0
+ assert len(await store.list_categories()) == 1
+
+
+async def test_uncategorized_is_the_triage_inbox(store: SQLiteSessionStore) -> None:
+ await _seed(store)
+ ids = (await run_question_bank(action="list", filter_mode="wrong", store=store)).summary[
+ "entry_ids"
+ ]
+ await run_question_bank(action="organize", entry_ids=ids, category="Filed", store=store)
+
+ inbox = await run_question_bank(action="list", filter_mode="uncategorized", store=store)
+ assert inbox.summary["count"] == 1
+ assert inbox.summary["entry_ids"] != ids
+
+
+async def test_bad_ids_do_not_sink_the_good_ones(store: SQLiteSessionStore) -> None:
+ await _seed(store)
+ ids = (await run_question_bank(action="list", store=store)).summary["entry_ids"]
+
+ outcome = await run_question_bank(
+ action="organize",
+ entry_ids=[ids[0], "not-an-id", 987654],
+ category="Partial",
+ store=store,
+ )
+ assert outcome.ok
+ assert outcome.summary["changed"] == 1
+ assert "not-an-id" in outcome.text
+
+
+ "kwargs, fragment",
+ [
+ ({"action": "nope"}, "Unknown action"),
+ ({"action": "list", "filter_mode": "weird"}, "Unknown filter"),
+ ({"action": "organize", "entry_ids": [1], "category": ""}, "`category` is required"),
+ ({"action": "organize", "entry_ids": [], "category": "X"}, "`entry_ids`"),
+ ({"action": "unfile", "entry_ids": [1], "category": "ghost"}, "No category named"),
+ ({"action": "list", "category": "ghost"}, "No category named"),
+ ],
+)
+async def test_errors_are_actionable_sentences(
+ store: SQLiteSessionStore, kwargs: dict, fragment: str
+) -> None:
+ await _seed(store)
+ outcome = await run_question_bank(store=store, **kwargs)
+ assert not outcome.ok
+ assert fragment in outcome.error
+
+
+async def test_bookmark_round_trip(store: SQLiteSessionStore) -> None:
+ await _seed(store)
+ ids = (await run_question_bank(action="list", store=store)).summary["entry_ids"]
+
+ starred = await run_question_bank(action="bookmark", entry_ids=ids, store=store)
+ assert starred.ok
+ assert (await store.question_bank_stats())["bookmarked"] == len(ids)
+
+ cleared = await run_question_bank(
+ action="bookmark", entry_ids=ids, bookmarked=False, store=store
+ )
+ assert cleared.ok
+ assert (await store.question_bank_stats())["bookmarked"] == 0
+
+
+async def test_mount_gate_follows_the_data(store: SQLiteSessionStore) -> None:
+ assert store.has_question_bank_entries() is False
+ await _seed(store)
+ assert store.has_question_bank_entries() is True