74 Commits

Author SHA1 Message Date
Axton Ji
04eb2ac82e fix: batch indexing journal writes for per-document status updates (#3137)
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>
2026-12-01 16:56:02 +08:00
iron ox
8fe2567c65 fix(knowledge): report live progress for LlamaIndex folder batches (#2483)
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>
2026-12-01 15:01:46 +08:00
AleFlyX
e542e3ff0e fix(knowledge): drop visual assets on every document-delete path (#3022)
* 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>
2026-11-30 15:37:35 +08:00
AleFlyX
5ff2627aee fix(knowledge): reclaim parse cache when a document or KB is deleted (#2941)
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.
2026-11-30 14:17:47 +08:00
Chen jizhou
4d4a0b7524 fix: preserve embedding checkpoint pointer across preflight failures (#2698)
Co-authored-by: chen-12-03 <184723954+chen-12-03@users.noreply.github.com>
2026-11-28 18:23:30 +08:00
lazytalk
9e20ebc9d7 fix(knowledge): skip unreadable index versions instead of failing the KB list
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>
2026-11-09 22:49:11 +08:00
RRFZ
0c8593bf00 fix(knowledge): stop Windows readers from wiping kb_config.json
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.
2026-10-31 21:22:25 -04:00
fanjiahe
cfd1e2e3b6 fix: publish one LlamaIndex version per folder sync
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>
2026-10-31 00:53:47 +08:00
xunguangzlj-cloud
f06a84e95a fix: 暂存重试复用发生文件名冲突的文档 2026-10-29 00:17:20 +08:00
ZQR1101
8899ae6df6 fix(knowledge): keep same-named documents when creating a KB
`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
2026-10-24 17:44:13 +00:00
Bingxi Zhao (Frank)
35cea56187 fix(parsing): isolate native MinerU failures during KB indexing (#1982) 2026-10-19 02:10:06 +08:00
Bingxi Zhao
c0c5cbd5a7 Merge pull request #1858 from dajiaohuang/fix/marginnote-delete-confirmation
fix(knowledge): confirm before deleting MarginNote state
2026-10-19 00:24:20 +08:00
Mohammad Hijjawi
b273dc584a fix: retry transient locks and decode UTF-8 when reading the indexing journal
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
2026-10-11 01:23:40 +01:00
dajiaohuang
2eefb2c935 Merge commit '6cf793bd868ba5ecbe64722936d4be8fab5a01df' into fix/marginnote-delete-confirmation 2026-10-08 12:40:43 +08:00
dajiaohuang
857b7b48e7 fix(knowledge): confirm MarginNote deletion before removing data 2026-10-08 12:40:43 +08:00
Bingxi Zhao (Frank)
e79e1b0ad2 fix(knowledge): make long-document indexing recoverable and publication verified (#1612) 2026-10-08 08:10:40 +08:00
evan188199-tech
50a3ba4e4d fix(knowledge): surface swallowed KB status, progress and folder-sync failures (#1706)
* 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>
2026-10-07 20:22:32 +08:00
Bingxi Zhao (Frank)
4d7b080fbe fix(knowledge): reuse catalog probes without blocking the API (#1711) 2026-10-04 18:04:10 +08:00
Bingxi Zhao (Frank)
55490af65e Merge issue fixes into PR synthesis
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.
2026-09-23 12:06:19 +08:00
Bingxi Zhao (Frank)
ce02c1fdbb fix(knowledge): track confirmed files during empty-index bootstrap (#1481) 2026-09-23 11:12:10 +08:00
Bingxi Zhao (Frank)
777babc382 Preserve linked-folder sync snapshots and empty KB bootstrap 2026-09-23 10:49:20 +08:00
Bingxi Zhao (Frank)
e7f9528335 Merge PR #1459 runtime UID remapping 2026-09-23 10:28:56 +08:00
Bingxi Zhao (Frank)
6ad2dab582 Merge PR #1488 empty KB bootstrap 2026-09-23 10:28:42 +08:00
Bingxi Zhao (Frank)
b38a2245eb Merge PR #1334 linked folder manual sync 2026-09-23 10:28:15 +08:00
Bingxi Zhao (Frank)
8534cea581 Merge PR #1372 linked folder sync controls 2026-09-23 10:27:32 +08:00
NoxsMedia
ac8cc4a97d fix: preserve selected embeddings in confirmed LightRAG rebuilds 2026-09-21 02:57:39 +00:00
Bingxi Zhao (Frank)
da856ad670 release: v1.6.9
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.
2026-09-21 02:30:40 +08:00
Gao-Chenkai
c7a253d2d6 fix(knowledge): bootstrap empty KBs on first upload
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>
2026-09-16 16:46:16 +08:00
Bingxi Zhao (Frank)
c547a5a31c fix: resolve verified learning, ingestion and delivery regressions
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 #1461
Fixes #1458
Fixes #1451
Fixes #1448
Fixes #1392
Fixes #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>
2026-09-15 20:06:57 +08:00
Gao-Chenkai
388399c3a1 fix(docker): remap PUID/PGID for Unraid bind mounts (#1458)
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>
2026-09-14 22:13:48 +08:00
XZH
2992a7e73f feat(knowledge): expose linked folder sync controls 2026-09-10 10:35:10 -07:00
Gao-Chenkai
d033272f93 feat(knowledge): add linked folder manual sync 2026-09-09 21:24:41 +08:00
NoxsMedia
7266c7aacf chore: sync PR #1265 with current dev 2026-09-07 23:33:46 +00:00
Bingxi Zhao (Frank)
e7d04fccfc fix(knowledge): validate KB names on the manager, and let a bad one be deleted
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.
2026-09-08 00:31:59 +08:00
NoxsMedia
80d257d55e refactor: unify LightRAG defaults and confirmed rebuilds 2026-09-07 08:07:00 +00:00
NoxsMedia
1eaa27e4f3 test(lightrag): isolate role configuration in offline fixtures 2026-09-06 10:52:18 +00:00
NoxsMedia
446b3aab7e feat(lightrag): configure independent role models and pinned vision indexing 2026-09-06 09:58:42 +00:00
NoxsMedia
ecc150d960 feat: pin LightRAG indexing models per knowledge base (#1171)
* feat(lightrag): pin indexing model per knowledge base

* fix(lightrag): close indexing isolation gaps

* fix(lightrag): integrate released dedicated model contract

* fix(lightrag): fingerprint vision capability

* test(rag): update LightRAG policy fixtures and harden redaction

---------

Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
2026-09-03 15:55:27 +08:00
XZH
e12d97b58f fix(knowledge): enforce web source sync bounds 2026-08-26 02:26:58 +08:00
XZH
0d8b734a76 feat(knowledge): add web source sync 2026-08-26 02:26:58 +08:00
evan188199-tech
50f8ccbaa4 feat: split knowledge sync - add GitHub source sync (#903)
* 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>
2026-08-24 16:55:47 +08:00
Bingxi Zhao (Frank)
081a73a15c fix(marginnote4): stop two libraries from claiming one store
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.
2026-08-21 23:03:41 +08:00
Bingxi Zhao (Frank)
0989dcbbd9 fix(marginnote4): one rule for where a library's store lives
"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.
2026-08-21 22:50:55 +08:00
Bingxi Zhao (Frank)
10297532b5 feat(knowledge): make indexing progress lines translatable
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.
2026-08-21 16:58:42 +08:00
evan188199-tech
1413cd8ed0 feat(knowledge): add MarginNote 4 as a connected knowledge base (#931)
* 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>
2026-08-21 16:10:22 +08:00
Bingxi Zhao (Frank)
2739a28871 fix(knowledge): keep same-named documents instead of dropping one
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.
2026-08-20 00:56:34 +08:00
Bingxi Zhao
ed6e552f95 fix: harden post-merge cleanup and image loading (#872)
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.
2026-08-20 00:10:43 +08:00
Amir Fathi
3c20bb9251 fix(knowledge): preserve source-relative directory structure when syncing linked folders (#899)
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.
2026-08-19 23:37:33 +08:00
Bingxi Zhao (Frank)
7c6bcfaef7 release: v1.5.14
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
2026-08-19 17:34:52 +08:00
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