Knowledge management知识管理
Collect, validate, name, tier, and retire documents before any index sees them.在任何索引接触文档之前,先完成收集、校验、命名、分级和退役。
What it is and why it exists它是什么,为什么需要它
What是什么
Knowledge management is the pipeline and the rules that decide what enters the knowledge bank: where documents come from, how they are validated and filed, which are authoritative, and when a document is retired.知识管理是一套流程和规则,决定什么能进入知识库:文档从哪里来、如何校验和归档、哪些是权威来源、何时让一份文档退役。
Why为什么
Retrieval ranks whatever it is given. The reference build's own guide calls this work 90 percent librarianship and 10 percent technology. Folder taxonomy, file names, and pruning duplicates moved quality more than any algorithm change.检索只会对给它的内容排序。参考系统自己的指南把这项工作称为 90% 的图书管理加 10% 的技术。目录分类、文件命名和清理重复,对质量的提升超过任何算法改动。
How it works工作原理
- New files land in an inbox. A validation step checks type by content and rejects error pages saved as documents.新文件先进入收件箱。校验步骤按内容检查文件类型,拒绝被保存成文档的错误页面。
- A ledger records every file with its content hash, authority tier, and status. Re-scans skip unchanged files.台账记录每个文件的内容哈希、权威等级和状态。重复扫描时跳过未变化的文件。
- Path rules assign each source a tier. Primary rules outrank guides, which outrank commentary.路径规则为每个来源分配等级。正式规定高于指南,指南高于评论。
- A retired file stays in the ledger with a reason. The index skips it.退役的文件仍留在台账里并注明原因,索引会跳过它。
Where it sits in the build order它在搭建顺序中的位置
Needs first前置模块
Nothing. You can start here.没有。可以从这里开始。
Unlocks解锁
- RAG and knowledge graphRAG 与知识图谱Retrieval returns what was ingested and ranks by signals made at ingestion: chunk boundaries, paths, tiers. Curation mistakes become retrieval mistakes that no ranking fix removes.检索只能返回入库的内容,并依靠入库时产生的信号排序:切块边界、路径、等级。整理阶段的错误会变成检索错误,任何排序手段都修不回来。
- Evaluation评估Held-out material is sampled from the corpus. You cannot seal chunks that have not been ingested.留出材料是从语料中抽样的。没有入库的文本块无法封存。
In the reference build在参考系统中
| Path路径 | Role作用 |
|---|---|
| KNOWLEDGE_MANAGEMENT_GUIDE.md | The three-tier plan: vector search, curated wiki, graph.三层规划:向量检索、人工整理的 wiki、图。 |
| knowledge-bank/_inbox/ | Drop zone for new files.新文件的投放区。 |
| knowledge-bank/source_authority.json | Path rules for authority tiers.权威等级的路径规则。 |
| apps/llm-wiki/llm_wiki.py | Drafts one page per concept for human review.为每个概念起草一页,交人工审核。 |
Process map流程图
From a downloaded file to something the index may read从下载的文件到索引可以读取的内容
- 1Inbox收件箱Every new file starts here. Nothing is indexed from the inbox.所有新文件从这里开始。收件箱里的内容不会被索引。
- 2Validate校验Leading bytes must match the extension. Empty files and HTML saved as text are rejected.文件头字节必须与扩展名匹配。空文件和被存成文本的 HTML 会被拒绝。
- 3File归档Move into the collection folder that matches its kind.移入与其类别对应的集合目录。
- 4Ledger row写入台账Hash, tier, kind, status. One row per file.哈希、等级、类别、状态。每个文件一行。
- 5Retire when superseded被取代时退役Status changes and a reason is recorded. The row stays.状态改变并记录原因。这一行保留。
- 6Hand to the index交给索引Only rows with status filed are indexed.只有状态为 filed 的行会被索引。
Build steps搭建步骤
Follow them in order the first time. Each step names what it uses from earlier steps and what it leaves for later ones. Code is read from the lab files, and output is what the lab printed when it was run.第一次请按顺序做。每一步都写明它用到前面步骤的什么成果,又为后面的步骤留下什么。代码直接读取自 lab 文件,输出是 lab 实际运行时打印的内容。
- 1Fix the folder taxonomy and file names确定目录分类和文件命名
- 2Validate files by content按内容校验文件
- 3Write the authority rules编写权威等级规则
- 4Create the ledger建立台账
- 5Run intake: scan the bank and process the inbox执行入库:扫描知识库并处理收件箱
- 6Retire, do not delete退役,而不是删除
- 7Add collectors with a relevance filter加入带相关性过滤的采集器
- 8Add a curated tier for judgment为经验判断增加一个人工整理层
01Fix the folder taxonomy and file names确定目录分类和文件命名
Do this操作
- Create one folder per collection. A collection is a body of documents that should never mix with another in an answer.每个集合建一个目录。集合是一批文档,在同一个回答里不应与其他集合混用。
- Inside it, create one folder per kind of authority: `policy/`, `guides/`, `memos/`.在集合内,按权威类别各建一个目录:`policy/`、`guides/`、`memos/`。
- Name files for what they are and when they apply. Avoid `final_v2`.文件名要说明内容和适用时间。不要用 `final_v2` 这类名字。
bank/
policy/ travel-policy.md the rule itself tier 1
guides/ traveler-quick-guide.md explains the rule tier 2
memos/ 2026-lodging-memo.md commentary tier 3
inbox/ everything new lands here first- Knowledge management知识管理 3: Write the authority rules编写权威等级规则 (folder names to match on用于匹配的目录名)
02Validate files by content按内容校验文件
Do this操作
- For binary types, compare the leading bytes with the expected signature.对二进制类型,比较文件头字节与预期的签名。
- For text types, reject files that start with an HTML tag.对文本类型,拒绝以 HTML 标签开头的文件。
- Return the reason as a string. It goes into the ledger.把拒绝原因以字符串返回,它会写进台账。
MAGIC = {".pdf": b"%PDF-", ".zip": b"PK\x03\x04", ".docx": b"PK\x03\x04"}
TEXT_TYPES = {".md", ".txt"}
def validate(path: Path) -> Optional[str]:
"""Return None when the file is what its name claims, else the reason it is not."""
ext = path.suffix.lower()
head = path.read_bytes()[:512]
if not head.strip():
return "empty file"
if ext in MAGIC:
return None if head.startswith(MAGIC[ext]) else f"not a real {ext} file (wrong leading bytes)"
if ext in TEXT_TYPES:
low = head.lstrip().lower()
return "an HTML page saved as text" if low.startswith((b"<!doctype html", b"<html")) else None
return f"unsupported type {ext}"- Knowledge management知识管理 5: Run intake: scan the bank and process the inbox执行入库:扫描知识库并处理收件箱 (validate()validate())
03Write the authority rules编写权威等级规则
- folder names to match on用于匹配的目录名 ← Knowledge management知识管理 1: Fix the folder taxonomy and file names确定目录分类和文件命名
Do this操作
- Write rules as path patterns, first match wins.把规则写成路径模式,先匹配到的生效。
- Give anything unmatched the lowest tier. Unknown sources must not outrank known ones.未匹配到的一律给最低等级。来源不明的文档不能排在已知来源前面。
DEFAULT_RULES = [ # first match wins; lower tier = more authoritative
{"pattern": "policy/*", "tier": 1, "kind": "rule"},
{"pattern": "guides/*", "tier": 2, "kind": "guide"},
{"pattern": "memos/*", "tier": 3, "kind": "commentary"},
]
def authority(source: str, rules: Optional[list] = None) -> dict:
for r in rules or DEFAULT_RULES:
if fnmatch.fnmatch(source, r["pattern"]):
return {"tier": r["tier"], "kind": r["kind"]}
return {"tier": 3, "kind": "unclassified"}- Knowledge management知识管理 4: Create the ledger建立台账 (tier and kind for each row每一行的等级和类别)
- RAG and knowledge graphRAG 与知识图谱 6: Add the authority nudge and collapse duplicates加入权威度微调并合并重复 (the tier on every chunk每个块上的等级)
- Self-evolving agents自进化智能体 8: Extend the loop to learn from documents把循环扩展到从文档中学习 (tiers to order the reading queue用于给阅读队列排序的等级)
04Create the ledger建立台账
- tier and kind for each row每一行的等级和类别 ← Knowledge management知识管理 3: Write the authority rules编写权威等级规则
Do this操作
- One row per file, keyed by collection and path.每个文件一行,以集合和路径为主键。
- Store the SHA-256 of the content. `record()` returns `unchanged` when the hash matches.保存内容的 SHA-256。哈希一致时 `record()` 返回 `unchanged`。
- Store status as one of: filed, indexed, retired, rejected.状态取值为:filed、indexed、retired、rejected。
class Ledger:
"""One row per file: what it is, where it is, and what state it is in."""
def __init__(self, db_path: Path):
self.db = sqlite3.connect(str(db_path))
self.db.execute("""CREATE TABLE IF NOT EXISTS files (
collection TEXT NOT NULL, source TEXT NOT NULL, sha256 TEXT NOT NULL,
tier INTEGER NOT NULL, kind TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'filed', -- filed | indexed | retired | rejected
note TEXT, PRIMARY KEY (collection, source))""")
self.db.commit()
def record(self, collection: str, source: str, sha: str, status: str = "filed", note: str = "") -> str:
old = self.db.execute("SELECT sha256, status FROM files WHERE collection=? AND source=?",
(collection, source)).fetchone()
if old and old[0] == sha and old[1] != "rejected":
return "unchanged"
a = authority(source)
self.db.execute("INSERT OR REPLACE INTO files VALUES (?,?,?,?,?,?,?)",
(collection, source, sha, a["tier"], a["kind"], status, note))
self.db.commit()
return "updated" if old else "new"
def retire(self, collection: str, source: str, reason: str) -> None:
self.db.execute("UPDATE files SET status='retired', note=? WHERE collection=? AND source=?",
(reason, collection, source))
self.db.commit()
def rows(self, collection: str, status: Optional[str] = None) -> list:
q = "SELECT source, tier, kind, status, note FROM files WHERE collection=?"
args = [collection]
if status:
q += " AND status=?"
args.append(status)
return self.db.execute(q + " ORDER BY tier, source", args).fetchall()- Knowledge management知识管理 5: Run intake: scan the bank and process the inbox执行入库:扫描知识库并处理收件箱 (Ledger.record()Ledger.record())
- RAG and knowledge graphRAG 与知识图谱 2: Embed and load, driven by the ledger由台账驱动,向量化并入库 (which files to index and their tier要索引哪些文件及其等级)
05Run intake: scan the bank and process the inbox执行入库:扫描知识库并处理收件箱
- validate()validate() ← Knowledge management知识管理 2: Validate files by content按内容校验文件
- Ledger.record()Ledger.record() ← Knowledge management知识管理 4: Create the ledger建立台账
Do this操作
- Run the demo. It scans the sample bank twice, then processes three inbox files.运行 demo。它先扫描样例知识库两次,再处理收件箱里的三个文件。
- Read the inbox lines: one file is rejected, two are filed.看收件箱那几行:一个文件被拒绝,两个被归档。
- Read the ledger: every file has a tier, a kind, and a status.看台账:每个文件都有等级、类别和状态。
def scan_bank(ledger: Ledger, collection: str, bank: Path) -> dict:
"""Record every file already in the bank. Safe to run again: unchanged files are skipped."""
counts = {"new": 0, "updated": 0, "unchanged": 0, "rejected": 0}
for p in sorted(bank.rglob("*")):
if not p.is_file():
continue
source = p.relative_to(bank).as_posix()
problem = validate(p)
if problem:
ledger.record(collection, source, sha256(p), "rejected", problem)
counts["rejected"] += 1
else:
counts[ledger.record(collection, source, sha256(p))] += 1
return counts
def process_inbox(ledger: Ledger, collection: str, inbox: Path, bank: Path, routing: dict) -> list:
"""Validate each inbox file. Good files move into the bank folder named by `routing`
(file name -> subfolder). Bad files stay put and are recorded as rejected."""
report = []
for p in sorted(inbox.iterdir()):
problem = validate(p)
if problem:
ledger.record(collection, "_inbox/" + p.name, sha256(p), "rejected", problem)
report.append((p.name, "REJECTED", problem))
continue
dest = bank / routing.get(p.name, "memos") / p.name
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(p, dest)
state = ledger.record(collection, dest.relative_to(bank).as_posix(), sha256(dest))
report.append((p.name, "FILED", f"{dest.relative_to(bank).as_posix()} ({state})"))
return reportpython3 -m labs.m03_knowledge.demofirst scan : {'new': 3, 'updated': 0, 'unchanged': 0, 'rejected': 0}
second scan: {'new': 0, 'updated': 0, 'unchanged': 3, 'rejected': 0} (nothing re-read as new)
inbox:
air-travel-annex.pdf REJECTED not a real .pdf file (wrong leading bytes)
remote-work-policy.md FILED policy/remote-work-policy.md (new)
vendor-rates.pdf FILED guides/vendor-rates.pdf (new)
ledger:
tier 1 rule filed policy/remote-work-policy.md
tier 1 rule filed policy/travel-policy.md
tier 2 guide filed guides/traveler-quick-guide.md
tier 2 guide retired guides/vendor-rates.pdf <- placeholder file, superseded
tier 3 unclassified rejected _inbox/air-travel-annex.pdf <- not a real .pdf file (wrong leading bytes)
tier 3 commentary filed memos/2026-lodging-memo.md- Knowledge management知识管理 6: Retire, do not delete退役,而不是删除 (ledger rows to change要修改的台账记录)
- Knowledge management知识管理 7: Add collectors with a relevance filter加入带相关性过滤的采集器 (the inbox routine that receives downloads接收下载文件的收件箱流程)
- Knowledge management知识管理 8: Add a curated tier for judgment为经验判断增加一个人工整理层 (source documents to distill用于提炼的原始文档)
- RAG and knowledge graphRAG 与知识图谱 1: Chunk with a context line切块时带上上下文行 (validated files in a known layout已校验、目录结构明确的文件)
06Retire, do not delete退役,而不是删除
- ledger rows to change要修改的台账记录 ← Knowledge management知识管理 5: Run intake: scan the bank and process the inbox执行入库:扫描知识库并处理收件箱
Do this操作
- Call `retire()` with a reason when a file is superseded, duplicated, or off topic.文件被取代、重复或跑题时,调用 `retire()` 并写明原因。
- Leave the file on disk or move it to an archive folder. The ledger status is what the index obeys.文件可以留在磁盘上,或移到归档目录。索引只认台账里的状态。
ledger.retire("POLICY", "guides/vendor-rates.pdf", "placeholder file, superseded")07Add collectors with a relevance filter加入带相关性过滤的采集器Not executed in the labslab 中未执行
- the inbox routine that receives downloads接收下载文件的收件箱流程 ← Knowledge management知识管理 5: Run intake: scan the bank and process the inbox执行入库:扫描知识库并处理收件箱
Do this操作
- For each feed, write the terms that make an item relevant.为每个信息源写下判断条目是否相关的关键词。
- Match broad terms on the title only. Match specific names on title and summary.宽泛的词只匹配标题。具体的名称可以匹配标题和摘要。
- Download matches into the inbox. Intake does the rest.把匹配到的条目下载到收件箱。其余交给入库流程。
def relevant(item: dict, broad: set, specific: set) -> bool:
title = item["title"].lower()
text = title + " " + item.get("summary", "").lower()
return any(w in title for w in broad) or any(w in text for w in specific)This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。
python3 labs/machine/check.py --write08Add a curated tier for judgment为经验判断增加一个人工整理层Not executed in the labslab 中未执行
- source documents to distill用于提炼的原始文档 ← Knowledge management知识管理 5: Run intake: scan the bank and process the inbox执行入库:扫描知识库并处理收件箱
Do this操作
- For any concept you have explained twice, have a model draft a one-page note from the sources.凡是你解释过两次的概念,就让模型根据原始文档起草一页说明。
- Review it yourself. Only reviewed pages move into the bank, in their own folder and tier.由你亲自审核。只有审核过的页面才进入知识库,放在单独的目录和等级下。
- Date each page with when it was last verified.在每一页上注明最近一次核实的日期。
This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。
python3 labs/machine/check.py --writeHow it works with the other parts它如何与其他部分协作
- RAG and knowledge graphRAG 与知识图谱The indexer reads the ledger. Tier and path become ranking signals.索引程序读取台账。等级和路径成为排序信号。
- Evaluation评估Held-out chunks are sampled from what was ingested. Retired files leave the gold set's pool.留出的文本块从已入库的内容中抽样。退役文件会从评估集的候选池中移除。
- Self-evolving agents自进化智能体The learner's reading queue is ordered by tier, and it skips retired files.学习任务的阅读队列按等级排序,并跳过退役文件。
- Operations and deployment运维与部署Collectors and the weekly intake run on a schedule.采集器和每周入库按计划运行。
What went wrong in the real build真实搭建中踩过的坑
HTML error pages saved as PDFsHTML 错误页被存成了 PDF
- What happened发生了什么
- A size check let 15 files through that were error pages with a .pdf extension.文件大小检查放过了 15 个扩展名为 .pdf 的错误页面。
- Fix修复
- Check leading bytes for every binary type.对每种二进制类型都检查文件头字节。
- Lesson教训
- Validate what a file is, never what it is called.校验文件的真实内容,而不是它的名字。
A 56 GB table corpus in a document folder文档目录里放了 56 GB 的表格数据
- What happened发生了什么
- Spending records sat in the document bank as CSV files. The ingester skipped them, so none of it was searchable, and chunking it would have produced nonsense.支出记录以 CSV 形式放在文档库里。入库程序跳过了它们,所以完全无法检索;如果硬去切块,只会产生无意义的内容。
- Fix修复
- Load tabular data into a query engine and expose query tools.把表格数据加载进查询引擎,并提供查询工具。
- Lesson教训
- Documents are retrieved. Records are queried. Decide which one you have.文档靠检索,记录靠查询。先判断你手里的是哪一种。
One regulation stored three times同一份规章被存了三遍
- What happened发生了什么
- The same document existed as per-volume files and two full copies. Search results filled with one paragraph repeated.同一份文档既有分卷文件,又有两份完整副本。检索结果里全是同一段话的重复。
- Fix修复
- Retire duplicate copies in the ledger and collapse identical passages at query time.在台账里退役重复副本,并在查询时合并相同段落。
- Lesson教训
- Duplicates are a curation problem first and a ranking problem second.重复首先是整理问题,其次才是排序问题。
The same idea on other platforms同样的思路在其他平台上
| Platform平台 | How this module maps本模块如何对应 |
|---|---|
| Databricks | Land raw files in a Unity Catalog volume. Use a Lakeflow pipeline for validation and chunk tables. The ledger is a Delta table, and tier is a column.把原始文件放进 Unity Catalog volume。用 Lakeflow 流水线做校验并生成文本块表。台账是一张 Delta 表,等级是其中一列。 |
| IBM watsonx | Store documents in watsonx.data or object storage and register them as knowledge sources. Keep the ledger and tier rules as your own tables.把文档存到 watsonx.data 或对象存储,并注册为知识来源。台账和等级规则仍用你自己的表维护。 |
| Codex | Not provided. Keep the bank as a repo or bucket with the same ledger, and let agents reach it through a search tool.平台不提供。把知识库放在代码仓库或存储桶里,配同样的台账,让智能体通过检索工具访问。 |
| Cursor | Not provided. Same approach: your pipeline, your ledger, exposed through a tool.平台不提供。做法相同:你自己的流程和台账,通过工具暴露出去。 |
| Claude Code / Agent SDK | Not provided by the coding agent. Project knowledge features hold small document sets. A large bank still needs this pipeline.编程智能体不提供这一层。项目知识功能只适合少量文档,大型知识库仍需要这套流程。 |
| Another machine | Folders, a hash ledger, and a rules file work on any filesystem. The lab uses only the standard library.目录、哈希台账和规则文件在任何文件系统上都能用。lab 只用了标准库。 |
Step-by-step guides per platform各平台的分步指南
Explain it back讲给自己听
Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。
Why keep retired files in the ledger?为什么要把退役文件留在台账里?
A folder holds 56 GB of CSV files. Should it be chunked and embedded?一个目录里有 56 GB 的 CSV 文件。应该切块并向量化吗?
Why do tier rules come before the ledger and after the taxonomy?为什么等级规则排在目录分类之后、台账之前?
What can you build with this module alone, before any model exists?在没有任何模型的情况下,仅凭这个模块能做成什么?
Terms术语
| Collection集合 | A body of documents indexed and searched as one unit, kept apart from other collections.作为一个整体被索引和检索的一批文档,与其他集合相互隔离。 |
| Ledger台账 | The table with one row per file: hash, tier, status.每个文件一行的表:哈希、等级、状态。 |
| Authority tier权威等级 | A trust level assigned by path rule. Tier 1 is the rule itself.按路径规则分配的可信度等级。1 级是规定本身。 |
From the live build来自实时构建
Recent changes and files the sync job filed under this module. These lines are in English as written in the build.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。
- Claim fidelity: sample by bank folder, not by chunk
- Learner queue: tier 3 sorts after core material; documents that get no vocabulary pass move to claims in one statement
- Collector: feed filter matches broad terms on the title only, domain organizations on title and summary
- Collector: per-feed relevance filter; the oversight body all-reports and legal feeds keep only domain and financial-management items
- the spending dataset collector: fiscal-year scope never starts later than FY2021
- Stream eval in the weekly cycle and the report; spending skill: a follow-up means another query; tests keep out of the production guard log; wiki watcher drops queued triggers; tuner skips manual-only sources
- Answers that used tools stream line by line as they clear the guard; new chunks get their Qwen3 embedding after ingest
- Guard: a requested made-up example is recorded, not rejected; wiki ingest runs 23:00-07:00
- Eval set v2 — built 2026-08-19
- 02 — The Build Process, Step by Step
- 00 — Project Timeline: How build-host Got Built
- Self-assessment: the learning system after ~100 hours of autonomous running
- AIDATA — Consolidation & Streamlining Assessment
- 05 — Gap Analysis
- the same paragraph from two copies of a document is one result. The the regulation is in the bank three times: the per-volume PDFs, Download-the regulation-PDF and Full-the regulation-Policy-PDF. Appropriations acts and committee reports repeat each other.
- Stage 1 of learning: KNOW WHAT YOU HAVE. This is the layer that was missing, and its absence is why the first attempt at Diet B was wrong.
- go over EVERY file, in stages, resumably. This replaces the first Diet B, which walked 81,636 chunks in database order and had no idea what any of them were.
- the "hook" that auto-triggers llm_wiki.py when the knowledge banks change. What it does: watches knowledge-bank/ (excluding Wiki/, _index/, _archive/, _inbox/) with fswatch, and on any change, runs `llm_wiki.py ingest` for BOTH banks.
- a local, Karpathy-pattern "LLM Wiki" for the AI_DATA knowledge banks. Three layers (see knowledge-bank/Wiki/WIKI-SCHEMA.md for the full spec): 1. RAW — knowledge-bank/<Bank>/** (immutable source documents — never touched) 2.
- turn a source file into clean, structure-aware chunks. Replaces the extraction and chunking half of kb_ingest.py (2026-09-22). WHAT WAS WRONG pypdf's extract_text() returns a flat string per page with no notion of headings, columns, tables or running headers.
- build the chunk index that tools/knowledge_base.py searches. 2026-09-22 — REWRITTEN FOR POSTGRES + PGVECTOR. What changed and why: STORE chroma -> kb_finance.chunks / kb_k12.chunks (pgstore.py).
- put the code and scripts on AI_DATA under git (2026-09-30). Idempotent: re-running commits whatever changed since, with the same checks. 1. whitelist .gitignore (only code + config; secrets and data never) 2.