Commit Graph

69 Commits

Author SHA1 Message Date
Bingxi Zhao (Frank)
96d6df9eb1 release: v1.5.13
Book is the bulk of this one. Compilation outlives the request that
started it, so a bus owned by that request dropped every background event
and "watch your book being written" degraded into a frozen page; the
stream is now owned per book by the process and survives a refresh or a
reconnect. Reading progress is finally recorded — `visited_page_ids` and
`bookmarked_page_ids` had been declared but never written for the life of
the feature — and rolls up into a completion score and weak chapters. A
book can also leave the app now, as one self-contained Markdown document,
with non-ASCII titles surviving the download.

Two scheduling defects that were invisible in production are fixed: the
same page compiled twice concurrently (billed twice, one result
discarded), and a book grinding on through a provider outage until every
chapter was half-generated. The source sweep is bounded and allocated
round-robin rather than spent on the first few knowledge bases, and
retrieval now tells indexed bases from connected pointers, so an Obsidian
vault or a remote IMA library no longer contributes zero while looking
like a source with nothing relevant. Confirming a spine shows a live
per-chapter estimate derived from the Section Architect's own templates.

Also here: three home starter suggestions built from memory recall,
mastery-path handoff moved into one module that changes lease, session
preference, and live turn together, and account-level Tencent IMA
credentials with the per-KB pair still winning.

Notes: assets/releases/ver1-5-13.md

This commit also carries the README prose sync, the eleven translated
READMEs, the release-notes archive sweep, and the version bump. Two gate
fixes ride along: the `Stamped` protocol is declared read-only so the
frozen `EntityStamp` satisfies it, and six GraphRAG adapter tests that
reached a deep `graphrag` import without guarding it now skip like their
four neighbours instead of failing where the extra is not installed.
2026-08-17 11:22:26 +08:00
Bingxi Zhao (Frank)
94a6edd563 feat(mastery): harden path state and turn recovery 2026-08-17 09:57:55 +08:00
Bingxi Zhao
8560157d5a fix: schedule qualitative mastery reviews (#840)
Create first-interval review state for concept/design mastery, advance only due reviews, and keep early duplicate assessments idempotent.
2026-08-16 23:35:52 +08:00
Bingxi Zhao (Frank)
712d4137f0 feat: DSML streaming robustness, memory observability, and mastery pending questions
Work in progress carried over from earlier sessions, committed together.

Chat / DSML:
- Tolerate partial and malformed tool-call tags mid-stream, with a character
  ceiling so a stray "<" cannot make the live stream wait forever for its
  closing bracket.
- Narration rounds can now mark their prose as visible, so a DSML round that
  keeps the text surrounding a call has it persisted as part of the answer.

Runtime observability:
- New deeptutor/runtime/memory_probe.py reports resident memory across the
  process tree, exposed at /api/v1/system/memory and surfaced in the settings
  status strip. psutil is a soft dependency, imported lazily with a /proc
  fallback, so a missing wheel costs the strip and not the app.

Mastery:
- New deeptutor/learning/pending.py projects a persisted PendingQuestion into
  the smaller public contract safe to hand the tutor model, and owns the
  multiple-choice translations shared by registration and grading.

LightRAG:
- New pipelines/lightrag/worker.py moves local indexing onto a worker thread's
  own event loop, so RAG-Anything's synchronous graph merging stops stalling
  unrelated API and LLM work.

Also: request-scoped output artifact delivery (api/routers/outputs.py),
partner runtime and path_service adjustments, and CLI chat renderer updates.
2026-08-09 02:31:44 +08:00
wayblink
be14c3ef23 feat: separate UI and model response languages (#758)
* feat: separate UI and model response languages

* refactor(settings): keep one owner for the interface.json language rules

The legacy migration — a file written before the UI/response split
inherits its single language into both fields — had been duplicated into
both readers of interface.json, as had the theme/language defaults. Two
copies of a migration rule drift.

Move the rule into resolve_languages() in the module that owns the file,
have the router compose its superset of defaults on top of the service's,
and cover the agreement with a test that reads one legacy file through
both paths. The helper also drops the separate key-presence check:
_normalize_language already falls back to its default for missing, null
and unrecognized values alike.

* fix: keep the language bootstrap single and local-choice-first

Merging dev surfaced three collisions this branch had not seen:

- The new bootstrap fetched /settings/ui unconditionally and overwrote
  writeStoredLanguage on every mount, undoing #730's rule that a choice
  made in this browser is the more specific signal and must win. Folded it
  into the existing guarded effect so one fetch serves both language
  fields and neither can clobber a local selection.
- apiFetch/apiUrl ended up imported twice in AppShellContext, which git
  merged without a conflict and tsc rejects outright.
- Three tests still stubbed get_ui_language at call sites that now ask for
  get_response_language: the question router's stand-in module and two
  mastery_path patches (renamed the zh case to say response language).

* fix(api): include response_language in the pre-session UI read

The bootstrap adopts both languages from this one endpoint, so leaving
response_language out of the projection meant a fresh browser always
inherited the interface locale and never saw the saved output-language
preference. It belongs with the other two: all three are the visitor's
own presentation choices, none describe the deployment.

---------

Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
2026-08-07 03:13:04 +08:00
Bingxi Zhao (Frank)
591329322d fix(i18n): stop collapsing every non-English language to Chinese (#712)
`parse_language()` ended in a bare `return "zh"`, so ja/ko/fr/de/ru/ar
all resolved to Chinese. Book prose normalized its code correctly while
quiz, Deep Research and Mastery Path went through this parser — which is
why a Japanese book came back with Chinese quizzes.

Delegate to the existing `normalize_language()` instead of keeping a
second, weaker implementation, and pass unknown codes through. What makes
the model answer in a language is the directive built from the code, not
the prompt file, so no new locale resources are needed.

Two fallback chains assumed the result was zh or en and had to follow:

* `PromptManager` now tries `[code, base locale, "en"]`, so "zh-tw" reuses
  the Chinese files and "ja" lands on English rather than Chinese. The
  chains for zh and en are unchanged.
* Mastery Path's `[lang, "zh" if lang != "zh" else "en"]` gets the same
  treatment, and its notebook prompts now append the shared language
  directive — without it a Japanese learner would only have traded
  Chinese output for English.

An unconfigured language still defaults to "zh", so deployments that
never set one keep the behaviour they shipped with.

Reported with an exact root-cause analysis by @takeshi-o.
2026-07-27 21:24:00 +08:00
Bingxi Zhao
f8ede5e20f Merge pull request #622 from whm8016/fix/mastery-recency-weighting
fix: restore recency weighting in compute_mastery (#618)
2026-07-19 00:31:31 +08:00
Bingxi Zhao (Frank)
fb3c568697 fix pageindex & minor bugs 2026-07-18 19:47:03 +08:00
whm
5d7647002e fix: restore recency weighting in compute_mastery (#618) 2026-07-12 16:36:02 +08:00
Bingxi Zhao (Frank)
4fab448977 minor fix & new channel 2026-06-30 22:11:40 +08:00
R-Turing
943e9fb7e8 fix mastery choice persistence and grading 2026-06-30 20:52:47 +08:00
Bingxi Zhao (Frank)
f8349fc1e5 Release v1.4.9
Settings polish and a Mastery -> Question Bank link:
- Search settings show only the connection fields the selected provider uses
- Connection profiles can be renamed and auto-name after their provider
- Graded Mastery Path questions sync into the session Question Bank
- Fix untranslated Settings-tour Tools step (en/zh) + guard test
- Refresh README / translated READMEs for the current v1.4.6+ UI

Bump __version__ to 1.4.9, add assets/releases/ver1-4-9.md, restore the
v1.4.7/v1.4.8 README rows dropped by an earlier docs-update commit, and
compress every README release row to <=30 words.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 20:05:19 +08:00
Bingxi Zhao (Frank)
b364ffc593 minor fixes & docs update 2026-06-19 17:34:13 +08:00
Bingxi Zhao (Frank)
dcb9bce8df release: v1.4.5 — Guided Learning on the chat loop + loop-plugin framework
Guided Learning is rebuilt on the chat agent loop: the bespoke stage
machine is gone, replaced by a tutor chat driving a hard, per-type mastery
gate, with the /learning page reworked into a status dashboard. Existing
learning progress loads unchanged.

A new loop-plugin framework (deeptutor/loop_plugins/) makes the chat loop
extensible — mastery is the first plugin, contributing its tools, system
block, and server-owned kwargs without the pipeline hard-coding it — and
the loop gains context-checkpoint folding. Partner Chat/Archive
conversations gain Markdown export + save-to-notebook (one shared
serializer), and every chat turn now signals done the moment the answer is
saved so the composer/clock free up before title generation.

Bump __version__ to 1.4.5, add assets/releases/ver1-4-5.md, archive notes
older than two weeks into past_releases/ (fixing the one cross-link that
crosses the boundary), and add the README release row.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 01:10:49 +08:00
Bingxi Zhao (Frank)
04cc156fa8 daily update 2026-06-13 19:51:44 +08:00
Bingxi Zhao (Frank)
452de66729 release: v1.4.3 — TutorBot→Partners, single-loop Chat, real multi-user isolation
The biggest cut since v1.4.0:

- Partners: TutorBot renamed and rebuilt on the product chat agent loop —
  production IM pipeline (retry/dedup/coalescing, per-channel delivery),
  live streaming on Telegram/Discord/Feishu, new WeCom AI Bot channel
  (15 connectors), web-chat attachments, soul template library + editor.
  Automatic non-destructive migration from data/tutorbot/; HTTP API moved
  to /api/v1/partners.
- Chat: single exploring agent loop with native tool calling; Activity
  header with collapsible thinking/tool trace.
- Multi-user: per-user grants v2 (tools/MCP/exec), data/users + data/system
  layout with automatic migration, runner mounts only the user workspace.
- Visualize: inline themed SVG, structured prompts, local validate+repair
  replacing the LLM review round.
- Co-writer Mermaid diagrams + selection RAG/web; file viewer docx/xlsx
  previews; MinerU cloud parsing backend; office skills on by default;
  CLI chat renderer rewrite.
- Docs rebuilt at deeptutor.info: per-channel setup guides (en+zh),
  refreshed screenshots.
- Pre-commit clean sweep: defusedxml for SVG validation, usedforsecurity
  flags on content hashes, mypy fixes, types-croniter stub.

Release notes: assets/releases/ver1-4-3.md

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 17:17:43 +08:00
Bingxi Zhao (Frank)
46093e5e2b update msg 2026-06-11 20:03:34 +08:00
Bingxi Zhao (Frank)
e3a351a488 refactor(guided-learning): post-merge hardening of #500
Security/correctness:
- Stop leaking diagnostic answers: persist a _sanitize_diagnostic() snapshot
  (drops top-level answers + inline answer keys) into progress.diagnostic,
  which is returned verbatim by the /progress endpoints. Grading is unaffected
  (authoritative answers live in LearningStore).
- _safe_json_parse + generate_from_notebook now use the shared fence-stripping
  parse_json_response instead of bare json.loads, so the common fenced/lightly
  -malformed LLM output is recovered instead of silently dropped / 500'd.

Decoupling:
- unified_ws change_module: move module lookup + PRETEST reset into
  LearningService.switch_module(); router keeps only the WS ordering
  (module_changed before cancel) and no longer imports learning.models.
- unified_ws check_active_turn: use new public TurnRuntimeManager
  .has_live_execution() instead of reaching into _lock/_executions.
- redo endpoint: LearningStore.clear_questions() instead of poking _questions_path.
- remove unused StreamEventType.USER_INPUT enum; document the WS message types.

Stability:
- LearningStore: question read-modify-write (save_question_answers/_meta),
  delete(), and clear_questions() now hold _cas_lock — consistent concurrency
  model; _atomic_write_text cleans up its temp file on failure.

Cleanliness/clarity:
- router: shared _validate_book_id() (9 endpoints) + _parse_modules()
  (init/replace); _classify_error drops unused expected_answer param.
- guided_learning: hoist logging/RAGService imports + module logger; move tuning
  constants to class top; ContextVar declared after imports.
- storage: hoist json import (7 inline copies removed).
- pocketbase_store: move _VALID_ID/_validate_id below the import block.
- rename misleading mastered_pct -> avg_mastery_pct (service + web consumers).

Frontend:
- learning [bookId] page uses lib fetchProgress (apiFetch -> auth redirect)
  instead of a raw credentials fetch; track/clear the retry + auto-advance
  timers on unmount; drop dead currentStage state + ModuleTree prop.
- learning-api: remove orphaned submitAnswer + AnswerRequest.
- CreateModuleDialog: use the static bookApi import; reset manualBookId to ''
  to match initial state; learning list page: stop shadowing the t() translator.

Conflict-resolution carryover: dropped the PR's incidental 300s factory timeout
(kept dev's stream runner).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-29 14:28:32 +08:00
whf
a0ee477ff9 fix: ruff auto-fix (22 issues), mypy type fixes for KnowledgeType 2026-05-21 14:41:51 +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
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
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
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
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
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
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
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
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
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
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
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
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
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
fb7787b089 Block 5+6: DELETE/redo endpoints, change_module WS, LLM progress hints 2026-05-16 23:33:56 +08:00
whf
3fd2d8e809 Block 2: backend list_all + list_progress + GET /progress endpoint 2026-05-16 21:53:22 +08:00
unknown
80ccbe9dfb Block 7.5: Practice quiz phase, auto-advance fix, cancel streaming safety
- Add PRACTICE_QUIZ stage between Feynman Check and Error Diagnosis
- Generate 5-10 practice questions per module, record attempts but don't gate mastery
- Fix auto-advance race: move stagesRef updates outside React setState callbacks
- Fix stale handleStreamEvent closure via ref pattern
- Fix PLAN stage permanent deadlock when modules not initialized
- Clear error state unconditionally on new stage_start
- Add cancelStreamingTurn to sidebar and chat page for proper cleanup
- Fix cancelStreamingTurn to handle missing turnId gracefully
- Keep empty page_ids refs for whole-book resolution in guided learning
2026-05-16 11:33:45 +08:00
whf
6f3070f8d3 Block 21: Auto-mastery calculation, mock module cleanup, quiz_attempts tracking, global review passed 2026-05-15 00:58:34 +08:00