Skip to content

feat(knowledge): add a built-in knowledge engine alongside LightCloud - #1338

Open
hxy91819 wants to merge 80 commits into
Tencent:mainfrom
hxy91819:feat/builtin-knowledge-engine
Open

hxy91819 wants to merge 80 commits into
Tencent:mainfrom
hxy91819:feat/builtin-knowledge-engine

Conversation

@hxy91819

@hxy91819 hxy91819 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

What changed

平台部署者可以在同一套 LoopForge 中选择 MySQL 托管的内置知识引擎,或沿用已部署的 LightCloud MCP。平台管理员在「知识中心 → 引擎设置」保存选项后,新的检索和发布请求应用新配置。两种模式共用知识中心、角色开关、knowledge.Upstream 和 /runners/knowledge/mcp。

  • KnowledgeSettings.Provider 对应 JSON 字段 provider,支持 builtin 和 lightcloud。已有 URL 和 Token 的安装沿用 LightCloud 以及原来的启用、来源和写回设置。其余默认进入内置模式。
  • LightCloud 使用单连接、Bearer Token、默认来源和项目来源覆盖。Agent 只能调用 kb_search、kb_fetch、kb_list_sources、kb_get_source。人工发布通过服务端的 kb_write_document 写回,须开启写回并符合项目来源授权。
  • 内置模式保留托管文档、Git 同步、公共库、向量检索、自动沉淀、治理、引用统计、撤回及 Git MR 写回。LightCloud 模式隐藏对应入口,平台 API 返回清楚的模式错误。
  • 切换保留连接配置和内置内容。审核记录随创建时的引擎保留,切回该引擎后可以继续处理。

Relationship to #1104

沿用 #1104 的 KnowledgeSettings.Provider、lightcloud 和五个方法的 Upstream 签名。本 PR 的新增适配器范围是内置引擎。LightCloud 客户端来自当前主干已有的单连接实现。#1104 可在同一 provider 路由添加 weknora、连接管理和对应工具白名单。

Scope

  • Platform core / API / runner
  • Public adapter / deployment
  • Classic
  • Portable
  • Shared behavior contract
  • Installer / CLI
  • Documentation only

Compatibility

Compose 和原生安装均需在新进程启动前应用知识 schema,包括仅使用 LightCloud 或未启用知识库的部署。先停止所有 API 和 worker,备份控制库及独立内容库,再运行 scripts/knowledge-schema.sh apply 和 check。安装器和 ./start.sh pull 已接入该顺序。新二进制要求 schema 版本 59。

知识迁移从 047 排到 059。runner 显式执行已发布的 002 基线及这 13 个脚本。上游迁移(至 046)文件名与字节保持一致。056 标记上游已有审核记录为 LightCloud,057 将待审正文移入内容面,058 为来源 ID 加命名空间,059 记录最终 schema 版本。LightCloud 设置及 Token 保存在原表,默认引擎在读取时推断。

Platform impact

范围 影响
Web 与 Main Bot 知识中心提供管理员设置、按模式显示标签和审核操作,Main Bot 按引擎提供工具及反馈入口。
HTTP / Agent 检索、原文、审核沿用共享入口。MCP 按当前引擎筛选工具,沿用项目签名与来源授权。内置管理 API 在外部模式下返回 400。
SOP 与 Runner 现有角色开关注入同一代理地址和按引擎生成的规则。定时助手继续遵守非交互工具策略。
控制面 / 内容面 控制面存 provider、授权、审核元数据。待审正文和内置索引留在内容面。切换保持两个引擎各自的审核记录。
Worker 内置 Git 同步、MR 状态轮询、向量维护、治理和自动沉淀按模式工作。
安装 / 升级 保留主干凭据、沙箱迁移、镜像源选择和 schema extensions,先执行知识 schema 后启动 API。
Classic / Portable 知识变更集中在 LoopForge 平台。

Compatibility with #1314 (asset evolution / RSI workbench)

上游 #1314 把知识中心放到 web/knowledge.js / web/knowledge.css。本 PR 以上游文件位置为准,把双引擎界面并入同一个知识中心,不保留第二套入口;RSI 工作台沿用共享抽屉与样式。

Browser walkthrough on the merged head

在合并最新主干后的版本上用真实浏览器复验:内置引擎十步流程(托管文档、Git 同步、公共库、混合检索、Main Bot 引用、LOOP 角色检索、沉淀审核、治理、写回、跨项目隔离),内置 ↔ LightCloud 双向切换(只读白名单、审核写回、数据与审核记录保留),关闭知识库时的核心冒烟(登录、项目、需求、LOOP 含人工门禁、Main Bot、运行记录)与 RSI 工作台,以及两种引擎的带数据升级。

Validation

  • 全量 Go 在分支和干净的主干基线运行。知识相关测试通过,分支剩余失败均在主干复现。
  • Chatbot 构建和测试通过,共 499 项。Web 测试、迁移及安装器结果见下表。
  • 用主干容器真实创建项目、配置 LightCloud 并保存待审记录。升级后保留配置、项目、授权和正文,并将旧审核条目发布到假 MCP。
  • 在 8090 用浏览器完成内置 → LightCloud → 内置。验证连接测试、检索、原文、授权与模式限制。切回后原混合检索结果一致,21 张原有知识、项目及绑定表的行数据与升级前一致。
验证命令 结果
env GOFLAGS=-buildvcs=false GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=tag.gpgsign GIT_CONFIG_VALUE_0=false go test -p=8 ./... -count=1 -timeout=7m 执行全量,剩余 6 项本机失败,均在主干复现
go vet ./... 通过
npm --prefix chatbot run build、npm --prefix chatbot run coverage 构建通过,499 项测试通过
npm --prefix webtest run coverage 298 项测试通过,行覆盖率 85.48%
python3 scripts/test-install.py -v 76 项中 74 项通过,2 项因缺 Bash 3.2 跳过
go test ./internal/repo -run 'TestKnowledgeMigrationsOnSeparateContentDatabase|TestKnowledge.*MySQL' -count=1 -timeout=180s 真实 MySQL 分库及重复迁移测试通过
python3 scripts/check-public.py、bash scripts/scan-secrets.sh 通过
bash scripts/knowledge-schema.sh apply --native、bash scripts/knowledge-schema.sh check --native 主干带数据升级演练和体验库均通过
git diff --name-status --diff-filter=DMRT origin/main HEAD -- migrations 空输出,上游已有迁移未改动

干净主干同样复现 Git wrapper 的 stash / autostash 拦截、签名 tag 的编辑器错误、VCS ownership 导致的构建状态错误,以及 Docker 发布端口的 OTLP 403。主干与分支在容器内部使用回环地址访问 OTLP 均返回 200。

Safety

  • I did not include credentials, internal endpoints, production data, or organization-specific infrastructure.
  • I preserved user files and unrelated changes.
  • I updated generated Classic host bundles when applicable.
  • I documented third-party content and licensing changes when applicable.

Describe the minimal local slice, package seam, split MySQL tables, and ordered implementation tasks without changing runtime code.
Control plane tables/models on KnowledgeRepo; content plane on the new KnowledgeContentRepo with its own gorm handle. Open accepts optional AGENTFLOW_KNOWLEDGE_MYSQL_DSN: empty or equal DSN reuses the main pool, and Close only releases a separate pool.

migrations/026_builtin_knowledge.sql adds the two-plane tables, drops knowledge_settings and creates the ngram fulltext index. compose.yaml sets --ngram_token_size=2 and scripts/dev.sh applies 026. AGENTS.md domain table and rules updated per design 4.3.
Add the phase-one library packages for splitting Markdown, checking
frontmatter, and keeping an unwired in-memory index. Git sync only
clones, fetches, lists Markdown, and reads files inside the worktree.
…(S5)

- Engine implements the five Upstream methods for hosted knowledge bases:
  write document (body + revision + rebuilt index chunks in one content
  transaction, source revision/doc count updated), search, line-based fetch,
  list sources, read-only tool catalog. Git sources reject writes as
  not-implemented; only the current indexed version is served on fetch.
- Index chunk searchable text excludes frontmatter (kept only for title/
  metadata) while preserving line numbers.
- Internal KeywordIndex seam with a default MySQL ngram NATURAL LANGUAGE MODE
  adapter: restricted to caller-provided sources, default 10 / max 50 results;
  options struct leaves room for future rerank/BOOLEAN/nav-downweight without
  changing Upstream or the schema.
- Content plane gains WriteHostedDocument (single transaction) and
  FulltextChunks; domain gains KnowledgeChunkMatch.
- Tests: fake adapter covers scoping, line reading, all five methods,
  frontmatter exclusion and overwrite; MySQL case covers 2-char hit,
  single-char no error, overwrite dropping old body, frontmatter not indexed.
- Service 新方法(manage.go):幂等保证项目托管库、来源/文档清单、登记公开 Git 来源、触发同步只置待同步、按项目授权收窄的试搜与读原文
- HTTP 管理接口(knowledge_bases.go):bases/documents/document/sources/sync/search
- projectsHandlers 注入 knowledge.Service,建项目后保证托管库
- 前端移除连接配置表单,改为知识库/来源/文档/试搜/读原文,含同步状态与错误展示
- design.md 知识中心一节与托管库对齐;测试覆盖创建/试搜/读原文/拒绝其他项目/并发幂等/不再提交 url-token
The Git sync work copy lives under the sandbox workspace root. The
reclaimer deleted every other directory, including a clone still being
written, so public Git sources failed with a missing pack file.
Move Git sync work copies to an independent cache root
(AGENTFLOW_KNOWLEDGE_CACHE_DIR, default $HOME/.agentflow/knowledge-cache)
and drop the sandbox reclaimer's knowledge-cache exception. The cache is
rebuildable and must not live under the workspace root.

The external client was removed in S7 and 026 dropped knowledge_settings,
so the review-publishing preference can never be enabled. Delete the
remaining domain/repo/HTTP settings plumbing and gate review publishing
only on the project's bound sources.
Add the knowledge_activity control table (027) owned by KnowledgeRepo. SOP proxy and Main Bot tool calls now write role/session, tool, query, hits, success, time and run ID; the 知识中心 usage endpoint reads the newest 200 per project after restart instead of an in-memory log.

Writes are best effort and never change the tool result. The proxy token carries the run id; Main Bot fills run and chat session ids. Project scope is enforced on both write and read paths.
Normalize colloquial Chinese questions before the ngram query, downweight
function-word bigrams, and gate results by the candidate score distribution
instead of returning ten fragment matches. Add generic Chinese-to-English
technical expansions so deployment answers rank for spoken questions.

Return a Chinese message when kb_search has no hits, and cover the walkthrough
questions against the LoopForge docs corpus.
…cent#1)

# Conflicts:
#	internal/httpapi/knowledge_proxy.go
- 融合层 HybridRetriever 置于关键词适配器之上,RRF 融合关键词与向量;
  向量通道故障降级为关键词并在结果里标记 mode/degraded/degrade_reason。
- embedding 三来源:不启用 / 本地 BGE-M3 sidecar / OpenAI 兼容远程(带
  Bearer 鉴权头,放宽 sidecar 特有健康字段校验);qdrant 最小客户端。
- 索引契约固定在知识库行(模型/维度/collection),换模型换 collection
  并全量重建;向量只从 MySQL 正文/索引块重建;托管写入与 Git 同步由租约
  实例增量更新向量。
- 未启用或未配置 Qdrant/embedding 时行为与纯关键词完全一致(只需 MySQL)。
- 028 可重复执行迁移补列;compose 新增可选 vector profile(公开镜像、
  固定模型版本与 SHA-256);试搜结果最小展示降级与向量启用状态。
- 新增向量关闭/降级/换模型重建/增量更新等测试。
- Keep hosted document line 1 as written; validate user frontmatter without auto-insertion.
- Count revisions per document and use the document revision in citations.
- Reject traversal/absolute/backslash document paths and bad path prefixes instead of rewriting.
- Classify sync failures into user-facing Chinese and log raw git errors server-side only.
- Expose Git citations as repository web links and keep citation identifiers on one line.
- Browse indexed documents from hosted and Git sources; use registered source names, index root Markdown for empty prefixes, and allow deleting Git sources (content first, then control plane).
- Update role/audit/read-only copy, remove MySQL/ngram wording, and validate Git URLs with in-page Chinese hints.
- Update the knowledge-center webtest for the current UI.
# Conflicts:
#	internal/httpapi/knowledge_bases.go
#	internal/httpapi/knowledge_bases_test.go
#	web/knowledge.js
- Commit a reviewed document on a new writeback branch, push it with the
  source-level canWrite credential, then create a merge request on GitHub or
  GitLab. Unsupported hosts and credentials without an HTTP token still push
  the branch and return a Chinese hint.
- Serialize sync and writeback through the source lease. The working copy
  remains a disposable cache; retries rebuild a single commit and refuse to
  overwrite a branch a peer moved.
- Record branch, commit, MR link and state in knowledge_writebacks (031,
  repeatable). The review drawer and list show the writeback status.
- Refresh merge state from the hosting API, falling back to commit ancestry.
  A merged writeback queues the source, and the sync worker now applies only
  changed/removed documents so the new document joins the index without
  rewriting untouched ones.
- Keep credentials in short-lived child environments, never in logs, errors
  or .git/config. Tests cover local bare repos, fake GitHub/GitLab APIs,
  concurrent leases, incremental indexing and the review UI.
- read the namespaced hosted source ID from the store in the trial search test
- allowlist the historical synthetic key by commit instead of a private-key line
- apply the 002 knowledge baseline before 026+ so a fresh install works
- split 037 into control/content/control, import its ID mapping into a
  separate content database and migrate retraction fences
- mark missing review bodies and refuse empty edit/publish writes
- fail startup without schema version 37 and refuse pre-037 hosted sources
- detect live workers before data migrations and document the stop-all step
- extend installer/migration tests and align deployment/.env docs
- bound kb_grep document reads by pages and fix the gitleaks fixture allowlist
Apply the keyword adapter's candidate-distribution relevance idea to the
fusion path. Pure-vector hits must be close to the vector head and well
above the candidate median; weak vector batches contribute no tails and
return empty when the keyword channel is also empty. Results are no
longer padded to the limit. When both channels have an ambiguous head,
restore a small keyword-score weight to keep the keyword top result.

Add walkthrough P1-1 regressions, including a live Qdrant/embedding case
that overwrites a hosted document and verifies the old body's vectors
disappear. The 31-query hybrid benchmark stays at R@10 0.8988 / MRR
0.9677, matching the tuned baseline.
- Main Bot citations link to hosted drawer or Git commit line; hosted drawer citation wraps and is clickable.
- Split missing repository from authentication failures; ambiguous 404 says the address may need credentials.
- Skip content rewrite and vector re-embedding when a Git source HEAD is unchanged; show per-source vector rebuild progress.
- Describe hosted versions as 修订 N in tool output and assistant answers; keep Git commits as commit.
- Refresh governance after feedback with no page reload.
- Require an SSH deployment key in the source form when an SSH URL is entered.
- Stabilize the Blob URL test shim under Vitest 4.
Check owner and staleness only for documents that have frontmatter, and let a manager turn those checks off per source. Collapse short repeats of the same gap and hide ignored or handled queries without deleting them. Probe unchanged Git heads with ls-remote and show pull, compare, and index on the source row.
Upstream migration filenames are a published contract. Restore
026_assistant_session_reads.sql and 027_cli_model_catalog.sql byte-for-byte
and move every knowledge migration forward by two without changing order.

knowledge-schema.sh now applies an explicit knowledge list (002 and
028-040) instead of scanning a numeric range, so optional upstream DDL is
never swept into install/upgrade. Schema ledger and startup check move to
minimum 40. Docs, tests, and the regression harness use the new numbers.
@Robert0622

Copy link
Copy Markdown
Collaborator

Code Review: ISSUES FOUND ⚠️

Reviewed changes: Adds a built-in knowledge engine alongside LightCloud.

Issues found:

P2 — Repo walk not restricted to PathPrefix:
In gitsync/gitsync.go, the walk is not restricted to PathPrefix. A single oversized or broken .md file anywhere in the repo aborts the entire sync permanently, also blocking writeback.

P3s (non-blocking but worth fixing):

  • knowledgeMCPServerForRun injects the MCP server even when LightCloud is disabled (inconsistent with the Main Bot path).
  • Concurrent Sync requests corrupt the in-flight sync pass and write a spurious index_status='error'.
  • importGit does a full non-shallow clone on every sync despite comments claiming a reusable cache.
  • NormalizeDocPath now rejects paths it previously cleaned, breaking existing items in the queue.
  • KnowledgeDocuments does SELECT * on full MEDIUMTEXT bodies and silently returns an empty list on DB error (causing missed removals).
  • knowledge-schema.sh exposes the DB password in ps output.

Please fix the P2 PathPrefix issue before merge.

loopforge-pr-review:a236184c0480dcf3139735fde8f9432dcebce14f

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