Commit Graph

800 Commits

Author SHA1 Message Date
unknown
c1aea77577 chore: clean up temp files and update gitignore
- Untrack .claude/settings.local.json (local config, already in .gitignore)
- Add .pytest_tmp/ to .gitignore
- Add 启动 DeepTutor.bat to .gitignore (local script)
2026-05-21 11:36:14 +08:00
unknown
707aaab4b7 fix: pre-launch P1/P2 blockers — failure count reset, notebook escaping, E2E test
- P1-B: Reset stage_failure_counts on LLM success in _call_llm_with_degradation
  so a recovered stage is not permanently penalized by prior transient failures
- P1-A: HTML-escape notebook records (<, >, &) before embedding in
  <notebook_records> XML tags to prevent prompt injection; truncate type to 50 chars
- P2-A: Remove redundant `except (Exception, asyncio.TimeoutError)` (3 places)
  since Python 3.11+ TimeoutError is already a subclass of Exception
- P1-C: Add E2E flow test covering PRETEST → EXPLAIN → FEYNMAN_CHECK →
  PRACTICE_QUIZ → ERROR_DIAGNOSIS → MODULE_TEST → REVIEW → COMPLETED

164 tests pass.
2026-05-21 11:16:39 +08:00
unknown
edfdd1535e fix: sanitize notebook LLM output type and module name
- Add ALLOWED_KP_TYPES whitelist (memory/concept/procedure/design), fallback to concept
- Strip and truncate module name to 200 chars
2026-05-21 02:12:20 +08:00
unknown
bb60b1dcbd fix: clean feynman_explanations and stage failures on replace_modules
replace_modules() now filters feynman_explanations by new_kp_ids and
clears stage_failure_counts/stage_failure_notes entirely, preventing
stale failure records from skipping stages in newly created modules.
2026-05-21 02:11:47 +08:00
unknown
ec63d0f566 fix: reset stage_failure_counts and feynman_explanations on /redo
Without this, users who accumulated 4+ failures on a stage would find
it permanently skipped even after redo, with no self-service recovery.
2026-05-21 01:26:16 +08:00
unknown
6c970a7a68 fix: unify list_progress mastery calculation with frontend
Change from threshold-based pass rate (count of KPs >= 0.7) to average
mastery percentage, matching the frontend ModuleTree display logic.
2026-05-21 01:16:03 +08:00
unknown
70e12ea31c fix: isolate internal error details from user-facing messages
- run(): remove exception text from user-visible error message
- error_diagnosis: remove exc from metadata and ai_confirmation
- RAG retrieval: remove exception detail from warning string
- All exception details now only go to logs with exc_info=True
2026-05-21 01:11:07 +08:00
unknown
7099424354 fix: strengthen prompt injection protection in generate-from-notebook
- Wrap user content in <notebook_records> XML tags for trust boundary
- Strengthen system prompt to explicitly treat tagged content as data
- Sanitize LLM output: strip, truncate to 200 chars, skip names < 2 chars
2026-05-21 01:04:22 +08:00
unknown
00338e79b4 feat: persist Feynman unevaluated explanations in LearningProgress
When LLM evaluation fails in feynman_check, the user's explanation text
is now saved to progress.feynman_explanations[kp_id] instead of being
lost. Cleared on successful evaluation. New field: feynman_explanations.
2026-05-21 01:02:06 +08:00
unknown
4e072537bc feat: add cross-turn cumulative failure gate for stage degradation
stage_failure_counts was previously write-only. Now _call_llm_with_degradation
checks cumulative failures at entry — if a stage has failed >= 4 times across
turns, it skips directly without attempting LLM calls. Users can reset via /redo.
2026-05-21 01:00:09 +08:00
unknown
e219b0b898 fix: rename passRate to masteryPercent, relax module name validation
- Rename passRate variable to masteryPercent in ModuleTree to match average mastery semantics
- Remove module name requirement from CreateModuleDialog (only KP count matters)
- Sync i18n strings for updated validation message
2026-05-21 00:56:15 +08:00
unknown
6934db4a91 perf: unified LLM/RAG timeout, per-stage degradation, and code cleanup
- Add stage_failure_counts/stage_failure_notes to LearningProgress for persistent failure tracking
- Wrap RAG retrieval with 10s independent timeout in _call_llm_impl
- Add _call_llm_with_timeout (default 60s) and _call_llm_with_degradation (bounded retry + skip)
- Apply degradation to all 12 stage handlers with stage-specific fallback paths
- Extract _run_interactive_quiz_loop shared helper for practice/practice_quiz
- Extract StructuredStageContent component from page.tsx
- Add TypeError to JSON parse except clauses across 7 files
- Simplify _record_attempt_and_update_mastery to single save exit
- Move import logging to module top in service.py
2026-05-21 00:07:31 +08:00
unknown
9a2160ca80 fix: scope RAG warnings to turn-local state, break empty-module diagnosis loop
- Replace shared self._call_llm monkeypatch with a contextvars.ContextVar
  so concurrent guided-learning turns get isolated RAG warning tracking.
- Extract _call_llm_impl for the raw LLM+RAG logic; _call_llm delegates
  to the context-var wrapper when present, avoiding recursion.
- Break the ERROR_DIAGNOSIS ↔ MODULE_TEST loop: when modules are empty
  and no active errors remain, advance to COMPLETED instead of cycling.
2026-05-20 15:13:57 +08:00
unknown
3eceacafa5 fix: scope RAG warnings to turn-local state, fallback kp_id to kps[0]
_call_llm now returns (response, rag_error) tuple. run() wraps it with a
tracking shim that collects warnings into a local list, eliminating shared
mutable _last_rag_error on the singleton capability instance.

_build_question_meta accepts default_kp_id parameter. When LLM omits or
misspells knowledge_point_id, resolved value falls back to kps[0].id
instead of storing empty string.

Codex P2 review items.
2026-05-20 13:06:18 +08:00
unknown
95f584e307 fix: update tests for list_progress {summaries, errors} format and RAG tuple
4 list_progress tests now access resp.json()["summaries"] instead of
resp.json() directly. test_retrieve_context_no_kb expects ("", "") tuple.
2026-05-20 12:54:26 +08:00
unknown
a6cef24c2f fix: update tests for extra=ignore and RAG tuple return type
test_extra_allowed → test_extra_ignored (fields silently dropped).
test_call_llm_injects_rag_context mock returns (content, error) tuple.
2026-05-20 12:52:43 +08:00
unknown
c6faab4dfc fix: frontend error handling, submit debounce, i18n, API format adaptation
fetchProgress catch block logs warning instead of silently swallowing.
Submit button protected by submittingRef to prevent double-sends.
Four hardcoded English strings replaced with i18n keys.
fetchAllProgress adapted to new {summaries, errors} API format.
book/page.tsx updated for new fetchAllProgress return type.

P2-4, P2-5, P2-6
2026-05-20 12:51:16 +08:00
unknown
6d478bcbd3 fix: model strictness, empty-module guards, list_progress error reporting
LearningProgress model_config changed from extra="allow" to extra="ignore"
to reject unknown fields (P1-9). All stage handlers now guard against empty
modules to avoid wasted LLM calls (P2-1). list_progress returns
{summaries, errors} instead of silently swallowing load failures (P2-3).

P1-9, P2-1, P2-3
2026-05-20 12:49:18 +08:00
unknown
8f3a4d6c06 fix: error_diagnosis writeback, RAG error surfacing, per-question KP attribution
Block A: parse structured JSON from error_diagnosis LLM call and write back
error_type + ai_confirmation to ErrorRecord. Surface RAG retrieval failures
via stream metadata instead of silent warning. Skip LLM call when no active
error records exist.

Block B: request per-question knowledge_point_id from LLM in practice_quiz
and practice stages. Build kp_id_map from LLM response to attribute each
question to its correct KP instead of defaulting all to kps[0].id. Old
format question files with empty kp_id continue to work via fallback.

P1-4, P1-5, P1-10
2026-05-20 12:47:22 +08:00
unknown
f83e950dd8 fix: mark stale turns cancelled before reporting no active turn (P2-11)
After server restart, persisted "running" turns have no live execution.
Mark them cancelled so create_turn won't reject the upcoming start_turn.
2026-05-20 10:35:16 +08:00
unknown
1224036111 fix: suppress Turn cancelled error during module switch (P1-1)
Add moduleSwitchRef set on module_changed, checked in error handler
to suppress the "Turn cancelled" error from cancel_turn. Cleared on
done so the old turn's auto-advance fires and starts the new module's
guided_learning turn.
2026-05-20 10:35:11 +08:00
unknown
c2dd63d7ef fix: use module-level lock for save/save_cas across all store instances (P2-10)
The per-instance _cas_lock only serialized save_cas on the same
LearningStore instance. save() was unprotected and request handlers
create fresh instances. Moving to a module-level _cas_lock ensures
compare-and-semantics hold across concurrent requests.
2026-05-20 10:26:52 +08:00
unknown
37aafbb73d fix: send module_changed before cancelling active turn (P2-9)
Reorder change_module handler: send module_changed first, then cancel
the active turn, then save progress. This ensures the frontend processes
the module switch before receiving any cancellation error, preventing
the UI from getting stuck on a "Turn cancelled" dead end.
2026-05-20 10:25:52 +08:00
unknown
c4c411abb0 fix: make save_cas atomic with a threading lock (P2-8)
The previous check-then-write was not atomic — two concurrent callers
with the same expected_version could both pass the version check and
write, with the last writer silently dropping the first update.
2026-05-20 10:16:17 +08:00
unknown
5bb807ab7e fix: cancel active turns before replace-modules via HTTP (P2-7)
The WS change_module path cancels active turns to prevent stale
progress overwrites, but the HTTP /replace-modules endpoint was
missing this protection. A concurrent turn's finally block could
restore old modules after replacement.
2026-05-20 10:16:13 +08:00
unknown
3f12e43272 fix: subscribe to turn_id instead of session_id after active-turn check (P2-6)
subscribe_session re-checks for a running turn on the server, so if the
turn finishes between check_active_turn and subscribe, the page misses
the terminal done event. subscribe_turn targets the specific turn and
replays its backlog regardless of current status.
2026-05-20 10:16:08 +08:00
unknown
5ff2e28825 fix: use refs for connect() guard to avoid stale closure (P2-4 rework)
Store modulesLength, moduleSelected, currentModuleId in refs synced on
render. connect() reads refs instead of closing over state, keeping the
guard correct without adding those values as useCallback deps — which
would teardown the socket on every progress fetch or module selection.
2026-05-20 10:10:01 +08:00
unknown
48d8fd7382 fix: clear stale review_queue on module replacement (P2-5)
replace_modules now filters review_queue to remove tasks whose
knowledge points no longer exist, preventing users from receiving
review tasks for deleted content.
2026-05-20 10:08:24 +08:00
unknown
5cd638c268 fix: stabilize connect() deps so module picker socket stays open (P2-4)
Removing modules.length, moduleSelected, and currentModuleId from the
connect dependency array prevents the socket from closing when progress
loads multiple modules with none selected, allowing change_module to
be sent from the module picker.
2026-05-20 10:08:20 +08:00
unknown
c40628346a fix: add continue after change_module to prevent spurious error (P2-3)
The change_module handler fell through to the generic unknown-type
error, so every module switch sent both module_changed and an error.
2026-05-20 10:08:17 +08:00
unknown
d9f7128501 test: add replace/merge and CAS save tests (Block5)
- 3 merge_modules tests (add, update, alias)
- 7 replace_modules tests (remove old, clean stale KP state)
- 4 CAS save tests (match, mismatch, increment, nonexistent)
2026-05-20 00:22:09 +08:00
unknown
261865c2a5 fix: split init_modules into replace/merge (P2-2)
- Add replace_modules() that cleans stale KP state (mastery, repetition, errors, feynman)
- Rename init_modules to merge_modules, keep alias for backward compat
- Add /replace-modules API endpoint for full module replacement
2026-05-20 00:21:15 +08:00
unknown
b611c2b11c fix: restore active turn on page refresh (P1-8)
- Add check_active_turn WS message handler returning turn_id + status
- Frontend sends check_active_turn on connect instead of start_turn
- If active turn exists, subscribe_session to resume; otherwise start_turn
2026-05-20 00:20:26 +08:00
unknown
783776ad26 fix: connect() closure deps (P1-6) + change_module race guard (P1-7)
- Add modules.length, moduleSelected, currentModuleId to connect() useCallback deps
- Add version field to LearningProgress and CAS save to LearningStore
- Cancel active turn before change_module (await task completion)
- Clear pending auto-advance timer on module_changed event
2026-05-20 00:18:50 +08:00
whf
a27b2749f0 fix: preserve question metadata in save_question_answers merge; clear feynman_retries on redo 2026-05-19 22:25:34 +08:00
whf
1e9f2a56d5 fix: load_question_answers backward compat with dict values from save_question_meta 2026-05-19 22:18:54 +08:00
unknown
1f7c3feae0 fix: use JSON-structured records in notebook prompt, prevent injection (Block2) 2026-05-19 22:07:07 +08:00
unknown
10a1936367 fix: add FEYNMAN_CHECK retry limit, skip after 3 failures (Block1) 2026-05-19 22:04:48 +08:00
unknown
9933509ca5 test: add 6 /answer endpoint regression tests (Block3) 2026-05-19 22:01:02 +08:00
unknown
e70a24d574 fix: server-side KP/module mapping, remove client-trusted fields (Block5) 2026-05-19 21:58:09 +08:00
unknown
2a49676a68 fix: unify grade_answer, remove substring false positive (Block4) 2026-05-19 21:52:16 +08:00
unknown
b816db053b Archive block spec files to docs/specs/ 2026-05-18 22:10:35 +08:00
whf
97d6976f34 Block 23: loading feedback, module picker, git cleanup
Issue 1: Add waitingForLLM state — show spinner with
'Generating diagnostic questions...' text while waiting for LLM
response after WS connect, instead of silent 'Ready to start learning'.

Issue 2: Module picker — when multiple modules exist and none
selected, show module selection cards before auto-connecting WS.
Single-module books still auto-start. ModuleTree clickable after.

Issue 3: Git rm middleware.ts, git add proxy.ts (Next.js 16 compat).

92/92 tests passing.
2026-05-18 21:56:40 +08:00
whf
a321b0a21f Fix 3 UI polish issues from frontend audit
Issue #2: Add knowledgePointsLabel locale key for standalone label usage
instead of reusing number-suffix key ('个知识点' → '知识点').

Issue #3: Delete 9 empty auto-generated test modules cluttering /learning
page (retain 'default' with 3 modules and 'init3').

Issue #4: Default manual book ID to empty string instead of 'manual'
to avoid leaking implementation detail to users.
2026-05-18 20:50:49 +08:00
whf
95f4498942 Block 22: display module name on /learning cards instead of raw book_id
Backend: list_progress() derives display name from first module name,
falling back to book_id for empty-module books.
Frontend: ProgressSummary gains 'name' field, card heading uses
card.name || card.book_id instead of raw book_id.
Tests: 2 new negative tests (name from module, empty-module fallback).

92/92 passing.
2026-05-18 20:40:47 +08:00
whf
d086a06b90 Fix 3 P2 bugs from Codex global review: manual module id collision, stale chapters on book switch, stage not reset on module switch 2026-05-17 12:56:24 +08:00
whf
97496d6511 Block 9: backend endpoint tests (21 new + 3 list_all), fix stale local HTTPException imports 2026-05-17 02:42:09 +08:00
whf
7b273d8db8 Block 8 refinement: remove KB placeholder tab, use bookApi.list, LLM parsing type safety, toast on import failure 2026-05-17 02:22:36 +08:00
unknown
64989bd3e7 Block 7+8: Book integration + Create Module dialog (4 tabs)
Block 7: "Start learning" button on BookLibrary cards, import-from-book
endpoint, handleLearn with duplicate progress check, i18n keys.

Block 8: CreateModuleDialog with manual/book/KB/notebook tabs,
generate-from-notebook backend endpoint with LLM extraction,
listBooks/generateModulesFromNotebook API functions, 30+ i18n keys.
2026-05-17 00:05:16 +08:00
whf
cdc1b73ed8 Block 7: /book integration — Start Learning button in BookLibrary 2026-05-16 23:52:15 +08:00