IndexingRun.document() re-reads the journal and atomically rewrites the
whole .indexing-run.json on every call. The LlamaIndex loader marks each
accepted source "embedding" in a synchronous loop on the event loop, and
publication marks every loaded Document (one per page) "completed" the
same way, so recording n statuses costs O(n^2) bytes of I/O with no
await in between. On a 4,320-document reindex this held the loop for
over 100 s, /health/ready stopped answering, and the desktop supervisor
killed the core.
Add IndexingRun.documents(sources, status, **details), which applies one
status to many sources under a single ownership check and a single
journal write, and use it from the loader, the LlamaIndex publication
step and the RAG service's indexed-file callback. document() now
delegates to it, so single updates behave as before.
Fixes#3046
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Forward embedding-batch progress through DocumentAdder so LlamaIndex folder
syncs and multi-file uploads no longer stay at 0% until the whole batch returns.
Co-authored-by: zhouyao01 <zhouyao01@mucang.cn>
* fix(knowledge): drop visual assets on every document-delete path
Extracted figures are tracked in `visual_assets/` (manifest + image files) and
were only cleaned by the HTTP delete-file route, which called
`VisualAssetStore.remove_source` itself. `remove_raw_document` has three
callers - that route plus the GitHub and web source syncs - so the two sync
paths deleted the document and left its figures and manifest entries behind
forever. Images are capped at 5 MB each, so a sync that drops figure-heavy
documents leaks a lot of disk.
Reproduced before the fix: a KB with one raw PDF and a matching asset entry,
then `remove_raw_document(kb, doc)` (exactly what both syncs do) -> the doc was
gone while the asset file and its manifest entry both remained.
Cleanup now happens in `remove_raw_document`, the single layer all three
deletion paths share, keyed by the module's existing `_raw_hash_key` - the same
rule indexing uses to record `source_path`, so nested raw/ paths cannot be
missed. The route's now-redundant call is removed rather than left as a second
owner: it also removes a second, lexical relative-path computation, and the old
uncaught call could 500 a delete on a corrupt manifest, which contradicts the
"cleanup never fails a user's delete" contract.
Best-effort like the surrounding code: a corrupt or read-only manifest logs a
warning and never turns a delete into an error. `VisualAssetStore.__init__`
only assigns paths, and `remove_source` returns before writing when no entry
matches, so KBs that never had images are not given an empty `visual_assets/`
directory (pinned by a test).
Verified: 7 new tests; mutation check shows disabling the cleanup fails 4 of
them. Independent checks: nested `papers/2024/` asset removed while a sibling
document's asset is preserved; no `visual_assets/` created for an image-free
KB; re-running the original repro now reports no leak.
Tests: 264 passed (knowledge, visual assets, source sync, HTTP file deletion).
Note: assets for an older parser signature are deliberately kept so a rollback
to an older index version still resolves its figures; that is retention, not a
leak, and is unchanged here.
* fix(api): 更新路由索引指纹
重新生成 knowledge 路由变更后的索引。原生引擎和路由加载器的 18 个测试均已通过。
---------
Co-authored-by: zszz3 <zszz3@users.noreply.github.com>
The parse cache is content-addressed and has no eviction of any kind: no size
cap, no TTL, no LRU, no CLI command, no settings entry. Neither deleting a raw
document nor deleting a whole knowledge base removed anything from it, and the
only cleanup that exists (clean_rag_storage) removes index storage - not the
parse cache - and is CLI-only. A deleted KB therefore kept its entire derived
parse output on disk forever.
Measured with a realistic document: a 30-page PDF with ~18 extracted images
leaves about 6.5 MB under parse_cache/. 64 such documents accumulate ~418 MB
that is never reclaimed; the directory only grows.
cache.reclaim_sources(paths, cache_root=...) removes the
<parse_cache>/<hash[:2]>/<hash>/ shard for each document being deleted - every
parser signature for that source, since the cache is derived and the next parse
recreates what it needs. It hashes the bytes while they still exist, because
the cache key is the content hash. Wired into two call sites, both before the
bytes disappear:
- remove_raw_document (single file, before unlink())
- KnowledgeBaseManager.delete_knowledge_base (every raw document, before the
KB directory is removed)
The cache root is derived from the KB directory (a sibling of knowledge_bases/)
rather than from the ambient path service, because requests served from the
knowledge-base library run in the account workspace scope. Deriving it from the
request scope would reclaim another workspace's cache while leaking this KB's
own. KB deletion enumerates exactly what rmtree removes: dotfiles included,
symlinks skipped because only the link goes away.
Reclaiming is scoped strictly to the hashes of the files being deleted, so
nothing else under the cache root is touched. The cache is shared across all
parse consumers in the workspace (KB indexing, chat attachments, reading
figures), so a byte-identical copy loses its entry too and is re-parsed once on
next use - slower, never incorrect. Proving liveness would mean hashing every
live source on every delete, and metadata.json only records documents that
indexed successfully; that tradeoff is documented on the helper and at both
call sites. The key is a truncated 64-bit hash; a collision costs one extra
re-parse, never wrong output.
Best-effort by contract: an unreadable source, a locked shard (a stale Windows
handle is the common case) or a missing cache root is logged and skipped, and
both call sites additionally wrap the call, so no cache failure can fail a
user's delete.
Note: this reclaims on delete; it does not bound growth of the live cache. A
size cap / LRU sweeper is a separate change and should be its own issue (the
scope split is recorded on #2946).
Verified on the current dev base (14796c70f): 14 new tests; mutation checks show
disabling the helper at either call site fails its positive-reclamation test.
A workspace/library-view reproduction (real ContentWorkspaceService, account
scope, KB stored in a workspace) confirms the KB's own shard is now reclaimed
while an account-level lookalike shard is left alone. tests/knowledge: 205
passed, 6 pre-existing failures (same as dev, missing llama_index/jose). ruff
check/format clean with the pinned 0.16.0.
A knowledge base whose data files are unreadable (for example root-owned
files in a container whose app runs as uid 1000) used to take down the
entire KB catalogue: list_kb_versions() -> _read_json() -> Path.exists()
raised PermissionError, so list_knowledge_bases() and the web-source
scheduler failed for every KB.
- _read_json() opens the file directly and treats FileNotFoundError as
"no metadata"; other OSError/ValueError degrades to a warning. This also
avoids Path.exists(), which propagates EACCES on Python >= 3.8.
- _is_storage_ready(), _flat_version_dirs() and list_kb_versions() skip
unreadable versions with a warning instead of raising.
- KnowledgeBaseManager._list_knowledge_bases() isolates per-KB failures
and an unreadable base directory, keeping the rest of the catalogue.
Tests cover unreadable metadata, an unreadable version dir, an unreadable
storage probe, and a manager listing with one unreadable KB.
Co-Authored-By: Claude Code <noreply@anthropic.com>
On Windows, file_lock_shared took msvcrt LK_NBLCK, which is an
exclusive, mandatory byte-range lock (msvcrt has no shared lock). A
reader that overlapped another reader failed with PermissionError,
_read_and_reconcile_config mapped that to an empty catalog, and the next
update_kb_status auto-registered its KB into the empty catalog and saved
it, dropping every other knowledge base's entry from kb_config.json.
Writers already replace the file atomically, so readers need no lock:
take none on Windows. POSIX keeps its LOCK_SH.
Linked-folder sync wrote a full snapshot for every file and never deleted the old ones. Index a staged batch in one publish and keep the newest three snapshots per embedding signature.
Co-authored-by: Cursor <cursoragent@cursor.com>
`kb create --docs-dir` staged every source at `raw/<basename>` with an
unconditional copy, so a docs tree with one `full.md` per volume kept only
the last file and still reported success. Both KB entry points now share one
staging rule (`knowledge/staging.py`): a taken name is reused only when the
content matches, otherwise the newcomer gets a free sibling name, so nothing
the user asked to index is dropped.
Issue: #2041
load_run() read .indexing-run.json and .indexing-cancel.json with a bare
Path.read_text(), so a brief Windows sharing lock (antivirus, indexer, a
concurrent reader) failed the safety check at once with "Indexing journal
is unreadable", and the locale default encoding garbled or rejected the
UTF-8 that atomic_write_json writes (a document named "ÁLGEBRA.pdf" makes
every check fail under cp1252).
Add file_io.read_text(), which reads UTF-8 and shares the bounded
PermissionError backoff already used by _atomic_replace(). Missing files,
corrupt JSON and locks that outlast the backoff keep their existing
behaviour.
Closes#1912
* fix(knowledge): make update_kb_status write failures observable
The ready-transition metadata refresh swallowed every exception
(`except Exception: pass`), and a kb_config.json persist failure
surfaced only as an opaque raise inside fire-and-forget callers, so
a lost status update left the persisted KB state stale with no
diagnostic.
- Log a warning naming the KB when the best-effort ready-transition
metadata refresh fails, instead of silently passing.
- Log an error with the KB name and status when persisting the
config fails, then re-raise so callers still receive the exception
(the write is authoritative, not best-effort).
Tests: a persist failure is logged and re-raised; a metadata refresh
failure is logged and does not propagate.
* fix(knowledge): make progress WS failures visible instead of silent
The websocket_progress endpoint swallowed five failure points with
`except Exception: pass`: timestamp parsing (x2), error-frame delivery,
socket close, and user-context reset. A corrupt progress snapshot or a
broken teardown path therefore vanished without a trace.
- Share a _progress_age_seconds helper for both freshness checks: narrow
the catch to (TypeError, ValueError), keep the inactive/stale fallback,
and log unparseable timestamps at warning level.
- Reuse the already-parsed snapshot age in the replay decision, so one
corrupt timestamp warns once per connection instead of once per
freshness check.
- Trace failed error-frame delivery and failed close at debug level
(usually an already-disconnected client, not a fault).
- Log a failed reset_current_user at warning level: leaking the user
context is a real fault, not a disconnect.
Tests: malformed timestamp degrades with a warning; cleanup failures are
logged and never propagate; normal disconnects stay silent.
* fix(knowledge): stop swallowing a failed reindex error-progress write
The reindex failure path wrapped its ProgressTracker ERROR update in
`except Exception: pass`, so when that write itself failed the rebuild's
failure alert disappeared and the KB progress view silently stayed stale.
Log a warning instead; the task-level error status remains authoritative.
* fix(knowledge): log folder sync state recording failures
update_folder_sync_state() swallowed per-file mtime recording errors
with 'except Exception: pass', so a file whose state could not be
recorded silently degraded the persisted sync state while last_sync
still advanced. Log the failure at WARNING and keep the un-recorded
fallback so the next scan re-syncs the file.
* test(codebuddy): make credential fixture expiry relative to now
test_load_credentials_parses_session wrote a hard-coded expiresAt of
1791055241000 (2026-10-03 15:40:41 UTC) and asserted is_expired() is
False. Once that instant passed the assertion flipped, so the test now
fails on every Python version for every branch.
Derive expiresAt / refreshExpiresAt from time.time() so the fixture
always describes a live session, and assert against the value written.
---------
Co-authored-by: XZH <cto@xzh.ai>
Combine knowledge bootstrap coverage and preserve later progress-isolation tests, native notebook tooltip, and locale-aware tool-hint fallback. Regenerate frontend contracts and align test fixtures with merged APIs.
Ship folder-based workspaces and data migration, daily practice, redesigned
provider and model settings, and streaming conversation improvements.
Synchronize README translations and document the archive/permanent-delete
upgrade behavior in assets/releases/ver1-6-9.md.
Reduce initial JavaScript by deduplicating English resources and loading
animation features after hydration. Keep the existing route size budgets.
Update regression fixtures and browser audits for scoped URLs and the new
settings and learning interfaces.
Empty-KB create marks the KB ready without writing an index. DocumentAdder
only allowed LightRAG to bootstrap that state, so later LlamaIndex uploads
failed with "not initialized". Treat a KB with no version dirs as first-index
for every local engine, matching the pipelines' create-from-scratch path.
Co-authored-by: Cursor <cursoragent@cursor.com>
Bind mastery drafts before their opening turn and preserve stored session modes.
Track chat duration from submission through terminal completion. Run async reading
extensions on their event loop and allow retries after cancellable timeouts.
Allow first uploads into empty LlamaIndex knowledge bases, preserve Telegram
thread routing, parse embedding Retry-After dates, and enforce robots rules and
host pacing during documentation crawls, including redirects.
Fixes#1461Fixes#1458Fixes#1451Fixes#1448Fixes#1392Fixes#1429
Refs #1435, #1412
Reuses contributions from PRs #1462, #1452 and #1403.
Co-authored-by: sjagadee <srini.jagadeesh@gmail.com>
Co-authored-by: AoHanBei <dongaohan21@gmail.com>
Co-authored-by: Gao-Chenkai <DevChenkai@outlook.com>
Empty LlamaIndex KBs and UID-mismatched volumes were reported as
"not initialized". Fail-fast on unwritable data dirs and remap the
non-root deeptutor user instead of swallowing chown failures.
Co-authored-by: Cursor <cursoragent@cursor.com>
A knowledge-base name is three things at once: a kb_config.json key, a
directory under data/knowledge_bases, and a path segment in every per-KB API
route. `validate_knowledge_base_name` exists to keep those three uses
compatible — its docstring says so — but it was called from one of the eight
HTTP entry points that can write a name into the config. The seven connect-*
endpoints (Obsidian, MarginNote, folder, LightRAG server, WeKnora, IMA, and
the subagent connection) did `(name or "").strip()` and wrote the result.
A name holding a "/" registers fine that way and is then unreachable.
uvicorn percent-decodes the path before routing, so %2F is a real separator
by the time Starlette matches `{kb_name}` — compiled to `[^/]+`, which cannot
span it. All 29 per-KB routes 404, delete included, while the list endpoint
takes no path parameter and keeps rendering the KB. Connected KBs are also
exempt from the orphan prune, so nothing collects it either: visible, unusable,
and removable only by hand-editing kb_config.json.
Two changes, both needed. Validation moves onto the eight `register_*`
methods, which is the seam every route already goes through — no route file
changes, since they all map ValueError to 400 — and the now-unreachable
"name is required" guards go with it. And a path-free
`POST /knowledge-bases/delete` gives the entries that predate the guard a way
out; a body is never split into segments. Widening the path route to
`{kb_name:path}` would not work: it is declared ahead of the DELETE routes
for linked folders, GitHub sources and web sources, and a greedy converter
would silently swallow all three.
Two smaller fixes ride along. The delete handler's catch-all swallowed its
own HTTPException and answered 500 with "404: ... not found" in the detail;
it now re-raises. And CreateKbModal states the rule under the field instead
of letting an untranslated English 400 be the first the user hears of it.
test_marginnote4_kb's store-collision case used "My Lib" / "My/Lib"; the
slash is now refused before that guard is reached, so it uses "My.Lib" —
still a name the rule allows, still sanitized to the same My_Lib.db.
* feat(knowledge): add GitHub source sync
* fix(github-sync): contain downloaded paths inside the KB raw dir
Destinations were built as `raw_dir / rel` where `rel` is derived from the
GitHub tree/compare response — remote input. Two shapes escaped: a `..`
segment, and an absolute path, which is the quieter one because
`Path("/kb") / "/etc/x"` is `/etc/x`, silently discarding the base. The only
filters in the way checked the file extension and the glob, so a matching
path would have been written — and, on the removal branch, deleted — outside
the knowledge base.
git rejects both shapes in tree entries today, so this is defence in depth
rather than a live exploit; a downloader still should not delegate to the
remote the question of where it writes. One `_contained_dest` seam now guards
the full-sync write, the incremental write, and the removal, and logs what it
refused.
---------
Co-authored-by: XZH <cto@xzh.ai>
Co-authored-by: Frank <bingxizhao@novix.science>
Registration checked the name and nothing else, but the default store
path keeps only alphanumerics, `-` and `_`, so "My Lib" and "My/Lib" both
resolve to My_Lib.db. Two libraries sharing that file would merge their
objects, and a device paired to either would sync into both.
Reject at registration instead, naming the library that already owns the
store. The same check covers an explicitly pinned `db_path` pointing at
another library's file.
"Pinned `db_path`, else derived from the name" was written twice — in the
capability binding and, in its derived half only, in the HTTP bridge. A
KB that pinned a path therefore paired devices into one file while the
tools read another, so the add-on would have synced into a store nothing
queried. `resolve_db_path` is now the single rule, and the binding, the
pairing endpoints and the device endpoints all go through it.
Deleting the KB now removes that store. Unlike an Obsidian vault it is
ours — `data/user/marginnote4/<name>.db`, created by us — so leaving it
behind both contradicted what the delete says and resurrected every
paired device as soon as a library of the same name was connected again.
Best-effort, on the same reasoning as the index directory above it: an
orphan file beats a config entry stuck in the list.
Every progress line the knowledge log box shows was a hardcoded English
string — 22 producers across the initializer, the document adder and the
router, rendered verbatim in the UI. #933 added one more ("Describing
images: m/n"), which is what surfaced the class.
Indexing runs detached from any request, so the backend has no viewer
language and the language of record lives in the browser anyway. So the
wire now carries the English `{{name}}` template plus its values, and the
frontend renders it with `t()` where the language is actually known.
`ProgressTracker.update` fills `message` from that same template, so
every consumer without i18n of its own — logs, the persisted snapshot,
the CLI — reads what it read before, and no call site spells the string
twice.
Untouched producers keep working: `progressMessage()` falls back to the
rendered `message` when no template is named.
* feat(marginnote4): add connected KB type, read-only tools, and sync bridge
Add MarginNote 4 as a connected knowledge base type that syncs study data
(notes, excerpts, cards, mindmap nodes) from MN4 via the official Add-on API
into a dedicated SQLite store, then exposes it to the chat loop through seven
read-only tools.
New package: deeptutor/capabilities/marginnote4/
- models.py: MarginNoteObject, SyncBatch, PairedDevice, LearningEvent
- store.py: SQLite CRUD + search + device pairing with hashed tokens
- binding.py: per-turn resolution of the selected MN4 library
- tools.py: search, read, list, documents, links, tags, cards
- capability.py: KnowledgeCapability (exclusive turn ownership)
- prompts/{en,zh}/system.md
HTTP bridge: deeptutor/api/routers/marginnote4.py
- POST /pair (session auth) -- register a device, get one-time token
- POST /sync (device-token auth) -- incremental upsert + tombstones
- POST /heartbeat (device-token auth) -- liveness + object count
- GET /devices, DELETE /devices/{id}, GET /status (session auth)
Integration points:
- kb_types.py: MARGINNOTE4_KB_TYPE added to CONNECTED_KB_TYPES
- manager.py: db_path surfaced in get_metadata allowlist
- registry.py: MarginNoteCapability registered in LOOP_CAPABILITIES
- builtin/__init__.py: MARGINNOTE_TOOL_TYPES in BUILTIN_TOOL_TYPES
- api/main.py: router mounted at /api/v1/marginnote4
Phase 1 scope: device pairing, read-only sync, tool navigation.
Write-back (propose/apply/verify), learning events, and mastery bridge
are planned for Phase 2-3.
Refs: #756 (Obsidian external knowledge source pattern), #180
* fix(marginnote4): search scope, store caching, prompts, KB registration
Testing and experience improvements:
- Search now includes document_title in scope: searching for a textbook
name returns results instead of zero hits
- Store instances cached by db_path so schema init runs once, not per
tool call within a turn
- object_type parameters carry enum constraints so the LLM knows valid
types without guessing
- System prompts (en/zh) rewritten with domain context: explains the
five object types, link traversal strategy, and citation guidance
- KB registration: register_marginnote4_kb manager method +
/connect-marginnote4 API endpoint, mirroring the Obsidian connect flow
- Fix indentation inconsistencies in manager.py and main.py
- New tests: document_title search scope, KB registration (create,
default path, duplicate rejection)
65 tests pass, 0 regressions, ruff clean.
* style(marginnote4): apply repository formatter
* fix(marginnote4): keep MN4 libraries out of the rag_search sweep
``MARGINNOTE4_KB_TYPE`` joined ``CONNECTED_KB_TYPES`` but not
``NON_RETRIEVABLE_KB_TYPES``, so ``supports_rag_retrieval`` answered true
for a library that has no index and no retrieval API — its objects live
in ``mn4_objects`` and are reachable only through the seven
``marginnote_*`` tools. Book's source explorer would have swept it,
gotten nothing back, and reported it as a source with no relevant
content rather than one that needs its own tools.
MN4 belongs with ``obsidian`` and ``subagent``, not with ``linked`` /
``lightrag_server`` / ``ima``, which do resolve to an index or an HTTP
retrieval API. Tests pin both halves of that split, since collapsing it
the other way has cost Book its connected sources before.
---------
Co-authored-by: XZH <cto@xzh.ai>
Co-authored-by: evan <evan@dazongguandeMac-mini.local>
Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
Builds on #899, which stopped a linked folder's subdirectories from
collapsing into raw/'s top level. Preserving structure removes most name
clashes but not the one #866 actually hit: a folder too large to sync at
once is added one subfolder at a time, and each batch roots at its own
folder, so `cli/README.md` and `events/README.md` both want raw/README.md.
The second was skipped as a "filename collision" — a document the user
asked to index, dropped with nothing in the response to say so.
A clash between different bytes now stages under a free sibling name.
Identical bytes still recover the staged copy, and content-level dedup via
file_hashes is untouched, so a repeated sync neither duplicates nor churns.
The staging log also reports the path a file actually landed at rather than
its source basename, which is no longer the same thing.
Preserve POSIX directory traversal bits when retrying failed knowledge-base cleanup, so a failed rmtree leaves an orphan a later pass can still enter. Resolve the LlamaIndex image LLM client only after the embedding prerequisite passes, keeping text-only embedding setups independent of LLM configuration.
Fixes#866. DocumentAdder staged every externally-sourced file at raw/<basename>, collapsing a linked folder's subdirectories and colliding same-named files. Pass the sync root through so each file stages at its path relative to it.
Immersive Reading, self-configuration, and a two-way IMA library.
- Immersive Reading: a new capability that opens a document beside the
thread. New reading engine (PDF pages / slides / page-sized sections),
five reading tools, a deterministic locate pre-pass that grounds the
turn without a second LLM call, /api/v1/reading, and a reader pane with
selection, highlights, notes, and export to an annotated PDF or Markdown.
- Setup capability: inspect the install, apply a setting, install a
parsing engine, or request a credential from a chat turn. New settings
spec table; a candidate value is probed before it is committed, and API
keys never enter the model's context.
- Tencent IMA: pipeline split into transport/envelope/models/sources/
notes/media/inventory, an additive capability with five tools, and
connected libraries that can finally be enumerated (bounded listings
are reported as a lower bound).
- Retrieval: supports_rag_retrieval() replaces is_connected_kb() for the
"can I sweep this?" question, so linked / lightrag_server / ima sources
stop being silently dropped from every book.
- Notebooks: their own console at /notebook, per-notebook locks and atomic
writes, copy / move / export routes, damaged files surfaced instead of
dropped, and renaming a record no longer clears its knowledge-base link.
- Settings persistence: one lock and one atomic replace shared by every
writer of interface.json; the PUT endpoints stop writing the
defaults-merged view back to disk.
Release notes: assets/releases/ver1-5-14.md
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.