Skip to content

kb: knowledgebase — RAG over operator documents (kb_search / kb_get) - #214

Merged
FMXExpress merged 3 commits into
mainfrom
claude/kb-search
Jun 10, 2026
Merged

FMXExpress merged 3 commits into
mainfrom
claude/kb-search

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

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.

pasclaw kb add ~/docs/delphi-book.md ~/projects/mylib/
pasclaw kb search "constructor constraints in generics"

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):

Tool Purpose
kb_search(query, k) Search; returns path#cN citations + snippets + scores
kb_get(path, chunk, window) Expand a citation into full chunk text ± neighbouring chunks

Design

  • Separate from conversation memory by intent: memory_search answers "what did we decide earlier"; the KB answers "what do my reference documents say". Own DB (workspace/kb.db), own tools.
  • Indexed in place, never copied — kb add registers sources; kb sync walks them mtime-incrementally. Sync is explicit (never on the query hot path), so kb_search stays fast on large corpora.
  • FTS5 BM25 always (reuses SanitizeFtsQuery from memory). When the localvector runtime is provisioned (pasclaw memory provision — same artifacts + vector_search_enabled flag as memory_search), search upgrades automatically to hybrid keyword+semantic (RRF fusion) via a kb.db.vec sidecar rebuilt on sync. Embeddings stay local.
  • Ingestion: paragraph-accumulating chunker (~1.6 KB target / 3.2 KB hard cap, UTF-8-sequence-safe splits), markdown/text/HTML(tag-stripped)/source extensions, binary sniff, 4 MB cap, dot-dir + node_modules skip. PDFs intentionally unsupported (convert with pdftotext first) — per scope decision.
  • Graceful degradation everywhere, same philosophy as memory: missing libsqlite3 → tools report unavailable; missing vector runtime → FTS-only.

Surface

  • CLI: pasclaw kb add|remove|list|sync|search|get|status (+ root help/dispatch).
  • RegisterKBTools wired at every RegisterMemoryTools site (agent, TUI, gateway, serve, embedded agent ×2, umbrella unit).
  • README section; make test-kb-index; kb status in smoke.

Verified (FPC 3.2.2, Linux)

  • Full E2E against a real corpus: add → 2 files/2 chunks indexed; both searches hit the right documents with highlighted snippets and #cN citations; get returns full chunk + window; sync reports "up to date" (incremental); remove cleans all rows.
  • Conditional registration confirmed via gateway /v1/tools: kb tools absent without a KB, kb_search+kb_get present with one.
  • make test fully green including the new kb_index_tests (chunker incl. UTF-8 boundary handling with locale-safe byte literals, extension filter, binary sniff, HTML strip) and the kb smoke line.
  • Delphi/FireDAC paths mirror PasClaw.Memory.Index exactly 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

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/pkg/kb/PasClaw.KB.Index.pas Outdated
Comment on lines +952 to +953
if Changed and TryEnsureVector then
RebuildVectorSidecar;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread src/pkg/kb/PasClaw.KB.Index.pas Outdated
Comment on lines +855 to +859
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

claude added 2 commits June 10, 2026 14:33
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.
@FMXExpress
FMXExpress merged commit 02d5900 into main Jun 10, 2026
FMXExpress pushed a commit that referenced this pull request Jun 11, 2026
… 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
FMXExpress pushed a commit that referenced this pull request Jun 13, 2026
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).
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants