Building a Traceable Local Knowledge Base with LLMs
A practical guide to using LLMs to maintain a local, linked knowledge base whose claims can be traced back to source material. It separates literal traceability from semantic correctness, reviews the limits of project rule files, automatic summaries, and RAG, and presents a six-step workflow with page templates, a source-verification script, maintenance practices, and clear usage boundaries.
Building a Traceable Local Knowledge Base with LLMs
1. Starting with “I Have to Explain It Again in Every New Session”
After working with an AI coding assistant for more than a few days, almost everyone runs into the same problem: in a new session, the model knows nothing about the project. The project goals, customer background, principles agreed on last quarter, and the reasons two candidate approaches were rejected all have to be explained again. The first few items can often be handled with documents. The hardest part is the “decision process.” When people recall the same discussion for the third time, their account may already differ from the first. Yet the model can continue smoothly, making it hard to tell which version is closer to the facts.
This is not simply a case of the model having a bad memory. The deeper issue is that memory lacks verifiable anchors. Two capabilities are needed. First, when someone asks “Why do you remember it this way?”, the system should be able to bring up the original material. Second, someone still needs to verify whether that material is correct and whether the quotation, when put back into context, still means what the page says it means. If these two layers are mixed together, it becomes unclear what part of the work the system is actually saving.
2. Splitting Memory into Two Problems: Traceability and Correctness
2.1 A Quotation Trap
Imagine a knowledge page containing a quoted statement with a citation, formatted exactly like a real quotation elsewhere on the same page, but with the year or source deliberately wrong. In the next session, the model reads that page. What reason does it have to doubt the quotation? By reading the page alone, almost none.
The fix is simple: let a script open the original file pointed to by the note and search for the quotation verbatim. If it cannot find it, the script reports the quotation, the page where it was misrecorded, and the file that should be checked. The script does not need to understand what the quotation means or determine who the author is. It only performs string comparison. In this way, every quotation on a page can be checked for whether it actually appears in the source.
2.2 Two Conclusions That Must Not Be Confused
- Literal traceability: the quotation really exists in the source file, and the page did not invent it or copy it incorrectly.
- Semantic correctness: the source file itself is reliable, the quotation is not taken out of context, and there is a real supporting relationship between the quotation and the conclusion.
The first task can be automated. The second still requires human judgment or a stronger fact-checking process. Once the two are separated, the system’s boundary becomes clear: it can guarantee that an answer has a checkable record, but it cannot guarantee that the evidence itself is correct.
3. Existing Continuity Mechanisms and Their Limits
Before building a local knowledge base, teams commonly rely on at least three kinds of context-continuity mechanisms.
3.1 Project Rule Files
A convention file is maintained in the project root, describing code style, directory conventions, build commands, and prohibited practices. The advantage is simplicity and stability: it takes effect automatically in every session. The disadvantage is that it is only suitable for “stable conventions,” not for “evolving facts and decisions.” Putting customer requirement changes and the reasons an approach was rejected into a rule file makes the file grow quickly and become hard to maintain.
3.2 Automatic Summary Memory
A tool generates a summary at the end of a session and loads it next time. This is convenient. But a summary is lossy compression: it keeps conclusions and drops the chain of evidence; it keeps tendencies and drops opposing views. When a conclusion is challenged, the summary cannot answer “What is the basis for this?”
3.3 Retrieval-Augmented Generation
Raw material is chunked and vectorized. When a question is asked, the most similar chunks are retrieved and passed to the model to organize an answer. The advantage is broad coverage and relatively low integration cost. The disadvantage is that every question-and-answer session performs “on-the-spot re-reasoning”: this time these chunks are retrieved, next time different ones may be. After the answer is produced, there is no correctable record. If an architecture decision originally had three objections, but retrieval only returns the supporting reasons, the model will give a one-sided answer, and no one knows what was missed. In long-running projects, the greatest risk is not a single wrong answer; it is that wrong answers leave no trace that can be corrected.
The following table summarizes these mechanisms:
| Mechanism | Good for carrying | Main limitation |
|---|---|---|
| Project rule file | Stable conventions, commands, standards | Not suitable for evolving facts and decisions |
| Automatic summary memory | Session highlights, short-term continuity | Lossy compression, missing evidence chain |
| Retrieval augmentation | Broad recall of raw text | Rebuilds conclusions every time, lacks a correctable record |
| Preprocessed knowledge pages | Decisions, sources, relationships | Requires ongoing maintenance |
4. An Alternative Arrangement: Curate Materials into Linked Pages First
To address these limits, one approach is to stop asking the model to assemble answers from raw material only at question time. Instead, curate materials into linked knowledge pages during normal work. When new material arrives, update the relevant entries. When a question comes, the model reads knowledge that has already been organized.
This idea is not entirely new. Industry experts have publicly proposed something similar: a model maintains a network of entries during daily work, each conclusion carries sources, and links between entries express causal relationships, alternatives, and conflicts. Community practitioners have since turned this into actionable tutorials: a step-by-step setup flow, automation hooks, a sample project scaffold, and a lightweight source-verification script. Notably, this setup does not depend on any companion application. Plain text files are enough. That means low migration cost, version control, readability in any editor, and no platform lock-in.
4.1 Designing Page Types
A minimal usable structure can contain four kinds of pages:
- Entry page: one decision, one concept, or one customer requirement per page.
- Source page: points to the location of the original material and records excerpts and context notes.
- Index page: organizes entry points by project, time, and topic.
- Changelog: records the date, reason, and scope of impact for each change.
An entry page should ideally contain fixed fields:
# Decision: Adopt Option A or Option B- Status: Decided / Pending / Deprecated- Date: YYYY-MM-DD- Conclusion: Adopt Option A- Key reasons: ... (each reason followed by a source link)- Objections: ... (also with sources)- Related entries: Requirement-customer-report; Constraint-delivery-cycle- To review: Whether the quotation from Source 3 is taken out of context
4.2 Why “Linked” Matters
In long-running projects, individual facts rarely exist in isolation. An architecture decision is often connected to requirements, constraints, budget, people, and previous attempts. Linear documents can only organize information by time or topic. Links can express “this decision overturned that premise” or “this approach was rejected because of that constraint.” When a question involves “why,” the model can follow links and read the full context instead of guessing from a few retrieval results.
4.3 Curate at Write Time, Read at Query Time
The core tradeoff is this: move curation cost earlier, into the write stage, in exchange for stability at query time. Retrieval augmentation is “curation at query time”; every query has to re-judge which chunks are relevant. Preprocessed knowledge pages are “curation at write time”; queries read conclusions and evidence directly. The former is suitable for large volumes of raw material with low value density. The latter is suitable for high-value project knowledge that needs to be cited repeatedly. The two are not mutually exclusive; their combination is discussed later.
5. A Six-Step Build Process
The following is a general build process that is not tied to a specific platform or tool.
Step 1: Define the Knowledge Boundary
First decide what deserves to enter the knowledge base: project background that must be reused across sessions, decision records, glossaries, customer constraints, and tradeoffs between approaches. One-off queries, pure code details, and content that can be read directly from the codebase do not need duplicate documentation. An unclear boundary causes page sprawl, and maintenance cost quickly exceeds the benefit.
Step 2: Design the Directory and Naming Convention
A usable starting point:
knowledge/index.mddecisions/requirements/concepts/sources/changelog.md
Use stable identifiers for file names, such as decision-report-engine.md. Avoid putting dates at the very beginning if that causes confusing ordering; if dates are used, keep them consistent globally. Once the directory structure is fixed, have the model write according to it instead of improvising every time.
Step 3: Define Page Templates
Templates are key to constraining model output. Without a template, the model writes prose in varying styles. With a template, fields can be extracted and validated in batches. A template should include at least: conclusion, evidence, source, date, status, related entries, and items to review.
Step 4: Implement Source Verification
This is the step most easily overlooked in the whole system, and the one most worth automating. The concrete approach is shown in the script example in the next section. The goal is not to judge whether a statement is “right,” but to judge whether a quotation actually exists in the cited source.
Step 5: Add Trigger Hooks
Make curation happen at the right time instead of relying on people to remember:
- When new material enters the directory, prompt updates to related entries.
- Before a session ends, check whether conclusions from the session have been written to a page.
- Before answering a question, read the index and relevant entries first, then decide whether raw-text retrieval is needed.
- Run periodic inspections and report broken links, expired statuses, and entries that have not been reviewed for a long time.
Triggers can be simple command-line scripts, file watchers, or custom instructions in an AI coding tool. The key is to make maintenance part of the workflow rather than an extra act of discipline.
Step 6: Establish Review and Closure Processes
Having pages does not mean the knowledge base is usable. Teams need to clarify:
- Who is responsible for changing “pending” to “decided.”
- When quotation verification fails, whether to fix the quotation or fix the source.
- When an entry is deprecated, whether to delete it or mark it.
- How conflicting conclusions are merged, which version is kept, and why.
These rules can be written at the top of the index page so that the model reads them before every write.
6. Source Verification Script Example
Below is a simplified verification script that demonstrates the core mechanism. A page records quotations in blockquotes, followed immediately by a comment that marks the source path.
import reimport sysfrom pathlib import PathQUOTE_RE = re.compile(r'^>\s*[“"](.+?)[”"]\s*$')SOURCE_RE = re.compile(r'^<!--\s*source:\s*(.+?)\s*-->$')def collect_quotes(page: Path):"""Collect (quote, source path) pairs from a page."""pairs = []current = Nonefor raw in page.read_text(encoding="utf-8").splitlines():line = raw.strip()m = QUOTE_RE.match(line)if m:current = m.group(1)continuem = SOURCE_RE.match(line)if m and current is not None:pairs.append((current, m.group(1)))current = Nonereturn pairsdef normalize(text: str) -> str:"""Normalize whitespace only; preserve all other characters."""return re.sub(r"\s+", "", text)def check_page(page: Path, base: Path):problems = []for quote, source in collect_quotes(page):src = (base / source).resolve()if not src.exists():problems.append((page, quote, source, "Source file does not exist"))continuecontent = src.read_text(encoding="utf-8", errors="replace")if normalize(quote) not in normalize(content):problems.append((page, quote, source, "Quote not found verbatim in source"))return problemsdef main(root: str) -> int:base = Path(root).resolve()issues = []for page in base.rglob("*.md"):issues.extend(check_page(page, base))if not issues:print("All quotes were found verbatim in their cited sources")return 0for page, quote, source, reason in issues:print(f"[FAIL] {page}")print(f" Quote: {quote}")print(f" Source: {source}")print(f" Reason: {reason}")return 1if __name__ == "__main__":sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "."))
The script is deliberately simple. Several design points are worth explaining:
- It performs only literal comparison. It does not need to understand the meaning of the quotation, so it will not let a copying error pass because the meaning is “similar,” nor will it raise a false alarm because the wording is “different”—provided that the quotation on the page is indeed a verbatim excerpt.
- Whitespace normalization is a necessary compromise. Copying across files often introduces differences in line breaks and indentation. But the more aggressive the normalization, the fewer false positives and the more false negatives. It is better to normalize whitespace only and preserve punctuation and case. If the source itself has large formatting differences, record a normalized version on the source page instead of loosening the verification rule.
- Ellipses and excerpts must be explicitly marked. If a page says “beginning omitted,” the script should skip that item or switch it to manual review. Ellipses must not become a backdoor for bypassing verification.
- Failure messages must be actionable. The output should include the page, quotation, source, and reason, so that the paragraph needing correction can be located directly.
- Passing verification does not mean the conclusion holds. The script can only prove that “this sentence really appears in the source.” It cannot prove that “this sentence supports the page’s conclusion.” The latter requires a review process, such as human spot checks of key entries or having the model search specifically for counterexamples in review mode.
One detail from the original discussion is worth emphasizing: the verification program “does not even need to know who the author is.” This is exactly what makes it useful in engineering: separate out semantic judgment and leave the deterministic, low-cost, batch-executable part behind. Semantic judgment is left to humans and the model during review, with a clear division of labor.
7. Maintenance Cost and Engineering Recommendations
The cost of this system is concrete and should not be avoided.
7.1 Main Costs
- Page updates: when new material arrives, related entries must be changed. The faster the project moves, the more frequent the updates.
- Broken links: file moves, directory restructuring, and source address changes all break links.
- Finishing half-done work: half-discussed entries, pending conclusions, and unreviewed quotations need someone to close them out.
- Repeated curation: the model may repeatedly polish the same page, consuming invocation cost.
Many personal knowledge bases die here: there is high enthusiasm during setup, but no one takes over maintenance.
7.2 Using Models to Reduce Maintenance Cost
Models are well suited to work such as batch-reading directories, finding missing fields, merging duplicate entries, generating change summaries, rewriting formats according to templates, and reporting suspicious quotations. Reading a dozen files at once is not difficult. Mechanical labor that used to consume maintainer patience can be handed to the model, turning the cost from “human time” into “token consumption.”
But note that model-driven curation can also introduce new errors: information may be lost when merging entries, meaning may change when rewriting, and autocomplete may fabricate sources. Therefore, the model can propose changes, but key entries should retain human confirmation. All automatic changes should be written to the changelog for rollback.
7.3 Concrete Ways to Control Cost
- Layered storage: a summary layer holds conclusions and indexes, an evidence layer holds quotations and sources, and a raw-material layer remains read-only. Queries read the summary layer first and drill down only when needed, reducing the input size of each session.
- Incremental updates: change only affected entries instead of rewriting everything. Use the changelog to record the scope of impact.
- Tiered inspection: high-risk entries such as external commitments, compliance-related items, and monetary items are verified every time; ordinary entries are spot-checked weekly or monthly.
- Visible failures: mark entries that fail verification on the index page. Do not let them remain silently in the knowledge base.
- Limit the scope of automatic curation: the model may change formats, fill in fields, and add links, but it must not delete sources or rewrite quotations.
7.4 Observable Metrics
If this system is to be used by a team, it is worth tracking a few simple metrics:
- Traceability rate: the proportion of sampled entries whose quotations can be found in their sources.
- Broken-link ratio: the number of problem links found during inspection divided by the total number of links.
- Stale-entry ratio: the proportion of entries marked “decided” that exceed the agreed review cycle.
- Mean time to repair: the time from discovering a problem to completing the fix.
- Query hit rate: the proportion of questions that can find relevant entries in the index without scanning the entire knowledge base.
These metrics do not require a complex platform. A regular script-generated report is enough.
8. Combining with Other Approaches
Preprocessed knowledge pages are not meant to replace retrieval augmentation or rule files. They add a “correctable conclusion layer.”
- Combining with rule files: put stable conventions in rule files and evolving facts and decisions in knowledge pages. Keep rule files short; let knowledge pages carry change.
- Combining with retrieval augmentation: knowledge pages provide conclusions, sources, and relationships; retrieval augmentation locates details in large-scale raw material. At query time, first use knowledge pages to narrow the scope, then use retrieval to supplement raw-text chunks, and finally write new evidence back to the pages. Retrieval results are no longer one-off; they are deposited.
- Combining with automatic summaries: summaries handle short-term continuity at the session level; knowledge pages handle long-term facts across sessions. When a conclusion appears in a summary, the system should prompt whether it has been written to a page. If it has not, it will still be untraceable in the next session.
9. Applicable Boundaries
This method is suitable for:
- Projects with long cycles, many participants, and decisions that need auditing.
- Scenarios such as architecture selection, requirement changes, and rejected approaches, where “the process matters more than the conclusion.”
- Teams that need to answer “Why did we decide this back then?” repeatedly.
- Scenarios with data-localization requirements, where knowledge should be managed in plain text.
It is less suitable for:
- One-off question-and-answer use, where curation cost exceeds the benefit.
- Exploration stages with high-frequency changes and no stable conclusions yet. At this stage, it is better to keep only an “exploration log” and not rush to create entries.
- Full-text search over massive unstructured material. That remains the main strength of retrieval augmentation.
- Teams where no one is willing to take responsibility for review. Automation can reduce maintenance cost, but it cannot eliminate responsibility.
10. Conclusion
The hard part of building a local knowledge base with LLMs is not “making the model remember.” It is making memory verifiable, correctable, and maintainable. Separate traceability from correctness, separate write-time curation from query-time reading, and separate automatic verification from human review. Then it becomes clear what the system can and cannot do.
A good local knowledge base is not the one that stores the most material. It is the one where every answer can return to the same record, and every discovered error points to the page that should be fixed. What it saves is not thinking itself, but the effort of repeatedly explaining, repeatedly aligning, and repeatedly guessing “What exactly did the previous version say?” Whether the material itself is correct still requires human oversight. That is both the boundary and the reason the system can be trusted.
