Repository navigation
kb: knowledgebase — RAG over operator documents (kb_search / kb_get) - #214
Conversation
Big-RAG-style document retrieval: `pasclaw kb add <file-or-dir>` registers
sources (indexed IN PLACE, never copied) into workspace/kb.db; the agent
gains two read-only tools the moment the corpus is non-empty:
kb_search(query, k) -> path#cN citations + snippets + scores
kb_get(path, chunk, window) -> full chunk text ± neighbouring chunks
Deliberately separate from conversation memory (memory_search): different
retrieval intent ("what do my reference documents say" vs "what did we
decide"), separate DB, separate tools. Tools register conditionally so the
model never sees an empty knowledgebase.
Engine: SQLite FTS5 BM25 always (reuses memory's SanitizeFtsQuery);
hybrid keyword+vector via the existing localvector runtime when
provisioned (`pasclaw memory provision`, gated by vector_search_enabled —
the exact same artifacts memory_search uses), with a kb.db.vec sidecar
rebuilt on sync. FTS side is mtime-incremental; sync is explicit
(`pasclaw kb sync`), never on the query hot path.
Ingestion: paragraph-accumulating chunker (~1.6KB target, 3.2KB hard cap,
UTF-8-sequence-safe splits), text/markdown/HTML(tag-stripped)/source
extensions, binary sniff, 4MB file cap, dot-dir + node_modules skip.
PDFs intentionally unsupported (convert with pdftotext first).
CLI: pasclaw kb add/remove/list/sync/search/get/status. Registered in
root help/dispatch; RegisterKBTools wired at every RegisterMemoryTools
site (agent, TUI, gateway, serve, embedded agent, umbrella unit).
Tests: kb_index_tests (chunker incl. UTF-8 boundary + locale-safe bytes,
extension filter, binary sniff, HTML strip) wired into `make test`;
`kb status` added to smoke. Verified end-to-end on FPC 3.2.2: add/list/
search/get/sync/remove against a real corpus, conditional tool
registration confirmed via gateway /v1/tools (absent without KB, both
tools present with one), full test suite green.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a8647826e7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if Changed and TryEnsureVector then | ||
| RebuildVectorSidecar; |
There was a problem hiding this comment.
Rebuild the vector sidecar when enabling vectors
When an operator provisions/enables vector search after an existing KB was indexed, a subsequent kb sync with unchanged files leaves Changed false, so the new kb.db.vec sidecar is never populated. Search then takes the vector path once TryEnsureVector succeeds and queries that empty sidecar, causing previously searchable FTS documents to disappear until a file is touched or re-added; rebuild when the sidecar is missing/empty or out of sync, not only when file mtimes changed.
Useful? React with 👍 / 👎.
| if Length(Body) > KB_MAX_FILE_BYTES then | ||
| begin | ||
| LogWarn('kb.index: %s is %d bytes (> %d) — skipping', | ||
| [Path, Length(Body), KB_MAX_FILE_BYTES]); | ||
| Exit; |
There was a problem hiding this comment.
Drop stale chunks before skipping oversized files
If a previously indexed source file later grows past KB_MAX_FILE_BYTES, this early Exit leaves its old kb_files, kb_chunks, and kb_fts rows intact because DropFile(Path) only runs below. After kb sync, searches can still return obsolete content from the old version of a file that is now intentionally skipped; remove any existing rows before returning for unindexable changed files.
Useful? React with 👍 / 👎.
Codex review on PR #214, both legit: P1 — sidecar never populated when vector is enabled after indexing. Worse than reported: Search took the vector path unconditionally and TryEnsureVector's OpenStore CREATED the empty sidecar, so every document vanished from results on the first post-provisioning query. Fix: the previously-dead kb_meta table now tracks 'vec_chunks' — the chunk population recorded by the last fully-successful rebuild (poisoned to -1 while a rebuild is in flight, so a crashed rebuild reads as stale). VectorInSync (sidecar exists AND meta == COUNT of kb_chunks) now gates Search's vector path — out-of-sync falls back to the always-correct FTS path — and Sync rebuilds when Changed OR not VectorInSync (with a ChunkCount>0 guard so an empty corpus doesn't load the ONNX model every sync). P2 — a previously-indexed file that grows past KB_MAX_FILE_BYTES (or turns binary/unreadable) left its old kb_files/kb_chunks/kb_fts rows serving stale content forever. ReindexFile is only called when mtime advanced, so existing rows are stale by definition on every early-out: all three skip paths now DropFile first. Deterministic skips (oversized, binary) also record a kb_files row with nchunks=0 so the mtime gate stops re-reading the same unindexable file every sync; the size check moved BEFORE the read (rejecting a 100MB dump no longer costs reading 100MB). Stats/GetSources count only nchunks>0 rows so skip markers aren't reported as documents. Verified on FPC 3.2.2: full E2E of the P2 lifecycle (index -> grows past cap -> sync -> stale content gone, status shows 0 documents, second sync no-ops -> shrink back -> re-indexed and findable); P1 logic is fail-safe by construction (VectorInSync=false until a clean rebuild) and the FTS fallback path is what the E2E exercises. Full `make test` green.
# Conflicts: # Makefile
… and dcc cfg (Codex P2 #222) Codex P2: PR #222 added pkg\checkpoints to the three RAD Studio .dproj files but the same samples/component-console directory has three OTHER search-path sources that drive the documented `make` and command-line `dcc64 SampleConsole.dpr` flows: - samples/component-console/Makefile (the $(ROOT)/src/pkg/<x> list) - samples/component-console/dcc32.cfg - samples/component-console/dcc64.cfg All three were stuck on the pre-stream-reliability lineup -- they had neither pkg/checkpoints (this PR's target) nor pkg/stream nor pkg/kb, even though PRs #213 / #214 etc. landed long ago. Anyone using the documented sample build path would F2613 at the FIRST missing unit dcc reached, not just on checkpoints. Fix: add pkg/stream, pkg/checkpoints, and pkg/kb to all three sources, slotted in the same canonical order PasClaw.dproj uses (providers -> stream -> tokenizer; skills -> checkpoints -> session; memory -> kb -> updater) so a future grep -A1 across these files stays comprehensible. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Both changelog files were stuck at the 2026-06-10 TUI / background- subagent / session_search / tool-RPC entries. ~7 weeks of merged PRs (#214 through #244) had landed without a corresponding entry in either file -- the git log was the only record of features like the knowledgebase, inbound MCP server mode, checkpoints + /undo, heartbeat daemon, shell backends (local | docker), send_message, promptware defense, Windows shell-output encoding fixes, fs_grep ripgrep optimisations, OpenTelemetry traces, and `pasclaw agent --quiet`. Added (newest first): 2026-06-13 #244 agent --quiet log-level clamp 2026-06-12 #243 dcc64 search path + agent --quiet / -q #242 OpenTelemetry traces (OTLP/HTTP+JSON) #241 fs_grep tier 5+6 (byte walker + Boyer-Moore-Horspool) #240 fs_grep tier 1-4 (deferred hash + skip-dirs + binary sniff + size cap) 2026-06-11 #239 Windows shell output: auto-detect UTF-8 vs OEM #238 Hashline fs_read header mojibake fix (¶ vs ¶) #237 Windows shell output: OEM codepage decode 2026-06-10 #233 Shell backends (local | docker via IShellBackend) #232 Heartbeat daemon + reversible condensation (CCR) #230 send_message tool + condenser families + promptware defense + task-aware MEMORY.md slicing 2026-06-09 #223 /goal Ralph loop + judge model + JSON-aware condenser #222 /undo wired into agent + sample dprojs #221 Checkpoints (auto-snapshot + TUI /undo) #220 mcp catalog: lenient hub projector #219 mcp: SSE / Streamable HTTP / stdio hub transports #218 Inbound MCP server mode #217 onboard: offer to index docs into the knowledgebase #214 Knowledgebase (RAG over operator-curated docs) Skipped from this changelog (build-system / Delphi-fix / FPC-fix PRs visible in the git log but not user-facing features): #215, #216, #224, #225, #226, #227, #228, #229, #231, #234, #236. Both files (README.md and docs/changelog.md) updated with the same entries -- intentional mirror so a reader on either surface sees the same history. Same prose in both; same footnote refs at the bottom. Validated: every [#N] reference in both files has a matching [#N]: URL footnote (no broken links).
dcc64 failed with "F2613 Unit 'PasClaw.KB.Index' not found" because the knowledgebase package (added in FMXExpress#214) was wired into the Makefile's UNIT_DIRS but not into the Delphi/Windows build configs, which carry their own unit-path lists: - src/pasclaw/PasClaw.dproj DCC_UnitSearchPath — was missing only ..\pkg\kb (this is what produced the F2613 under RAD Studio/msbuild). - build-delphi.bat UNIT_PATH and build-fpc.bat FPCFLAGS — both had drifted well behind the Makefile, each missing stream, crypto, net, search, session, identity, memory\localvector, markdown AND kb. Resync all three to the Makefile's package set (adds kb everywhere plus the other drifted packages), so the Delphi and Windows-FPC builds match the Linux/macOS build. Pure search-path additions — no code change. Can't run dcc64 here (no Delphi/Windows toolchain), but verified by inspection that PasClaw.KB.Index/.Tools.KB/.Cmd.KB live under src/pkg/kb and src/cmd, which are now on every path list; the FPC Makefile build (which already had kb) is unaffected.
Knowledgebase: RAG over operator documents
"Big RAG"-style document retrieval for the agent: register reference documents (manuals, books, source trees), and the agent can search and read them while answering.
Once the corpus is non-empty, two read-only agent tools register automatically (and not before — the model never sees an empty KB; the tool description embeds the live corpus size):
kb_search(query, k)path#cNcitations + snippets + scoreskb_get(path, chunk, window)Design
memory_searchanswers "what did we decide earlier"; the KB answers "what do my reference documents say". Own DB (workspace/kb.db), own tools.kb addregisters sources;kb syncwalks them mtime-incrementally. Sync is explicit (never on the query hot path), sokb_searchstays fast on large corpora.SanitizeFtsQueryfrom memory). When the localvector runtime is provisioned (pasclaw memory provision— same artifacts +vector_search_enabledflag asmemory_search), search upgrades automatically to hybrid keyword+semantic (RRF fusion) via akb.db.vecsidecar rebuilt on sync. Embeddings stay local.node_modulesskip. PDFs intentionally unsupported (convert withpdftotextfirst) — per scope decision.Surface
pasclaw kb add|remove|list|sync|search|get|status(+ root help/dispatch).RegisterKBToolswired at everyRegisterMemoryToolssite (agent, TUI, gateway, serve, embedded agent ×2, umbrella unit).make test-kb-index;kb statusin smoke.Verified (FPC 3.2.2, Linux)
add→ 2 files/2 chunks indexed; both searches hit the right documents with highlighted snippets and#cNcitations;getreturns full chunk + window;syncreports "up to date" (incremental);removecleans all rows./v1/tools: kb tools absent without a KB,kb_search+kb_getpresent with one.make testfully green including the newkb_index_tests(chunker incl. UTF-8 boundary handling with locale-safe byte literals, extension filter, binary sniff, HTML strip) and thekbsmoke line.PasClaw.Memory.Indexexactly but are untested here (no Delphi in CI), same status as the rest of the codebase.Not in scope (per plan)
PDF extraction (Phase 2, skipped by decision), background re-sync, alternate embed models.
https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
Generated by Claude Code