64 Commits

Author SHA1 Message Date
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
Lan-zk
3f1894e0c4 fix(knowledge): harden GraphRAG model and embedding compatibility (#747)
* fix(knowledge): add GraphRAG model compatibility layer

* fix(graphrag): harden compatibility preflight

* fix: align GraphRAG compatibility with current dev

* test: skip GraphRAG config test without optional extra

---------

Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
2026-08-17 01:12:05 +08:00
0xTidalBore
cbc6538273 fix: cache and dedupe docstore probes in kb list / knowledge API (#859) (#870)
Co-authored-by: 0xtidalbore <ahmed@itcloud.ca>
2026-08-16 19:08:41 +08:00
PenaFong
a8534ed336 fix: keep knowledge-base listing linear (#778)
Reuse the reconciled manager snapshot while building one knowledge-base list response so each item does not reload configuration and rescan every index.

Constraint: Preserve fresh config reads for standalone callers and target the upstream dev branch.

Rejected: Raise the proxy timeout | it masks repeated full-index scans and leaves list cost quadratic.

Confidence: high

Scope-risk: moderate

Directive: Do not reuse manager snapshots across await boundaries or write operations.

Tested: 53 focused pytest cases; Ruff check and format; 58-KB read-only benchmark completed in 2.114 seconds.

Not-tested: Full repository pre-commit suite.

Co-authored-by: OmX <omx@oh-my-codex.dev>
2026-08-06 19:19:53 +08:00
Bingxi Zhao (Frank)
e1c669f02a feat(knowledge): add Tencent IMA as a connected knowledge engine
IMA (ima.qq.com) is where a lot of users already keep their library, and
its OpenAPI exposes retrieval over it. Adding it as a sixth engine follows
the `lightrag-server` shape exactly: a KB bound to `ima` is a connection
pointer, not an index. Nothing is copied and nothing is stored locally —
documents are added in IMA, retrieval calls IMA, and DeepTutor's chat loop
still writes the answer.

The wire is plain HTTP POST to `/openapi/wiki/v1/<method>` with two auth
headers and a `{code,msg,data}` envelope; `search_knowledge` returns
cursor-paginated items carrying a `highlight_content` snippet. Only the two
read-only calls we need are wrapped, and pagination is bounded so a server
that never reports the end cannot spin.

Credentials (`client_id` + `api_key`) and the library id live per-KB in
`kb_config.json` rather than as one global account key. IMA credentials
identify a person, so per-KB means each user on a shared deployment
retrieves through their own account, and connecting stays self-contained
with no separate settings surface to fill in first. Both metadata paths
already work off an allowlist, so the credentials cannot leak into
surfaced metadata; only the library id is exposed, for the UI to show.

`connect-ima` re-probes server-side and never trusts the client's verdict,
matching the LightRAG-server route. IMA KBs are registered as a connected
type — no folder under `base_dir`, no embedding reconcile, deletion drops
only our pointer — and are reported as non-enumerable in the manifest,
since claiming "0 documents" for a library held behind an API would be a
lie.

Backend only; the connect flow in the knowledge center UI is not wired up
yet.
2026-07-29 00:38:10 +08:00
Bingxi Zhao (Frank)
a43f9fdf2a feat(knowledge): answer "how many files" from an inventory, not retrieval
Asked how many files a knowledge base holds, or whether some document is in
it, the model had only `rag` — and retrieval cannot answer either question:
the passages it returns say nothing about the size of the collection they
came from, so the model guessed from whichever chunks the query happened to
match. PageIndex KBs already answered correctly (their doc list is injected
into the system prompt) and Obsidian vaults have `list_notes`, which makes
this a wiring gap in the default engines rather than a limit of retrieval.

`deeptutor/knowledge/manifest.py` now owns a KB's document inventory as facts
read off disk, with two consumers that cannot disagree:

- the chat system prompt carries a per-KB inventory (count plus a truncated
  name list), so a count costs no tool round-trip — the failure mode where a
  weaker model never emits the call at all (cf. #532). Built once per turn on
  a worker thread, keeping the prompt byte-stable for the whole turn;
- a new `kb_files` tool enumerates on demand with glob / substring filtering,
  mounted under `rag`'s gate (a KB is attached) and deniable per partner the
  same way.

The inventory reports the document set and the KB's index status, and stops
there. It deliberately does not report how many documents reached the index:
every per-file record available is unreliable — LlamaIndex's docstore.json
counts nodes (chunk-level, so it drifts with the chunking config, and costs a
multi-MB parse to read), metadata.json's file_hashes is only written on the
incremental-add path, and last_indexed_count is the last batch's size rather
than a total. A confidently wrong count is worse than none. The prompt block
also states the rule that retrieved passages must never be used to infer how
many documents a KB holds or whether one exists in it.

Connected KBs degrade honestly instead of reporting zero: linked folders and
Obsidian vaults are enumerated in place, while a remote LightRAG server and a
connected subagent are declared unlistable. Hidden OS/editor entries
(.DS_Store, .obsidian/) stop counting as documents, and get_info's
raw_documents reads the same definition, so the KB page and the chat answer
can no longer disagree about the same KB.

Deep Research is untouched: its block loop narrows tools to the four that
produce block-level evidence, and a file list is not evidence for a subtopic.
2026-07-26 22:02:54 +08:00
Bingxi Zhao (Frank)
96a3b5db6b refactor(knowledge): unify all manager JSON writes on services.file_io atomic writer
Follow-up to #619: every kb_config.json / metadata.json write in
KnowledgeBaseManager now goes through atomic_write_json (temp file +
fsync + os.replace) instead of the truncate-then-lock pattern, so a
crash mid-write can no longer leave a truncated config and concurrent
readers always see a complete previous or new file. The JSON variant
in services.file_io gains the same tolerant fsync as its text sibling,
the now-redundant private helper and dead file_lock_exclusive are
removed, and the atomicity-contract test moves next to the shared
writer in tests/services/test_file_io.py.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 00:50:07 +08:00
Bingxi Zhao
38f2e8cf1d Merge pull request #619 from huytg2610/fix/persist-linked-folder-sync-state
fix(knowledge): persist linked folder sync state updates
2026-07-19 00:31:27 +08:00
Bingxi Zhao (Frank)
fb3c568697 fix pageindex & minor bugs 2026-07-18 19:47:03 +08:00
huy
6ae7a68120 fix(knowledge): persist linked folder sync state updates
update_folder_sync_state() mutated the loaded metadata dict and
returned without writing it back, so last_sync/synced_files never
reached metadata.json while the API layer logged success. Future
scans re-treated already-synced files as new.

Write back through a same-directory temp file + os.replace so
readers never observe a truncated metadata.json.
2026-07-11 23:01:04 +07:00
Bingxi Zhao (Frank)
3e3b9a6ecb release: v1.5.1
Knowledge Center: remove a single raw document from a knowledge base —
even one stuck in an error state — instead of deleting and rebuilding
the whole base. A file that failed to parse (e.g. one over the cloud
parser's page limit) can now be dropped in place, with replace/retry.

- backend: remove_raw_document() decoupled from DocumentAdder (needs no
  ready index) + DELETE /{kb_name}/files/{filename:path}; shared
  _read_metadata / _write_metadata / _raw_hash_key helpers so indexing
  and removal agree on the hash key. Connected/legacy KBs still rejected.
- web: deleteKbFile() API, per-file delete in the Files tab, and
  error-state KBs unlocked for drop / upload-replacement / retry.
- release notes ver1-5-1.md (old notes archived to past_releases/),
  __version__ bump to 1.5.1, README Releases row + one-week fold.
- README KB prose + all 10 translations synced; docs knowledge page
  updated separately in site/.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 23:23:27 +08:00