01 — Vấn đề

Memory chưa phải knowledge

AI agent có memory — nhưng memory không phải knowledge. GoClaw đã có 3-tier memory: Working → Episodic → Semantic. Nhưng khi agent cần tìm document cụ thể, cross-reference giữa files, hoặc track mối quan hệ tài liệu — memory system không đủ.

1

Tìm kiếm phân mảnh — phải query từng store riêng

2

Không có document relationships — backlinks không tồn tại

3

Stale content — external edits không đồng bộ vào DB

Knowledge Vault giải quyết cả 3: document registry + wikilinks + hybrid search + filesystem sync.

02 — Kiến trúc

Query layer trên memory system

ComponentVai trò
VaultStoreDocument CRUD, quản lý links, hybrid search (FTS + vector)
VaultSearchServiceĐiều phối search: fan-out song song qua vault, episodic, KG
EnrichWorkerPipeline async 5 phase: prepare → summarize → embed → classify → wikilinks
VaultSyncWorkerGiám sát filesystem: phát hiện file thay đổi, đồng bộ hash
VaultInterceptorHook file operations: tự đăng ký document khi agent write
VaultRetrieverCầu nối vault search vào agent L0 memory

Write Path

Write Path — Agent ghi file
Agent ghi file → Workspace FS
VaultInterceptor (AfterWrite)
EventBus: VaultDocUpserted
P0: Prepare
P1: Summarize
P2: Embed
P3: Classify
P4: Wikilinks

Read Path

Read Path — Agent tìm kiếm
VaultStore
0.4
FTS + Vector
EpisodicStore
0.3
Session summaries
KGStore
0.3
Entity similarity
Normalize
Dedup
Sort
Top N

Tenant & Scope Isolation

Mỗi document thuộc 1 phạm vi: personal (riêng agent), team (team workspace), shared (cross-agent, chưa triển khai). Documents của tenant A hoàn toàn tách biệt tenant B — kể cả links cũng không thể cross-tenant. Personal docs có thể link đến team docs.

03 — Data Model

vault_documents + vault_links

Document registry: metadata pointers. Content sống trên filesystem; DB giữ path, hash, embeddings.

vault_documents — schema
CREATE TABLE vault_documents ( id UUID PRIMARY KEY, tenant_id UUID NOT NULL, agent_id UUID, -- nullable: team/shared docs team_id UUID, -- team scoping scope TEXT DEFAULT 'personal', -- personal | team | shared path TEXT NOT NULL, -- workspace-relative title TEXT DEFAULT '', doc_type TEXT DEFAULT 'note', content_hash TEXT DEFAULT '', -- SHA-256 summary TEXT DEFAULT '', -- LLM-generated embedding vector(1536), -- pgvector cosine tsv tsvector GENERATED ALWAYS AS ( to_tsvector('simple', coalesce(title,'') || ' ' || coalesce(path,'') || ' ' || coalesce(summary,'')) ) STORED, metadata JSONB DEFAULT '{}', UNIQUE(tenant_id, COALESCE(agent_id, nil-uuid), COALESCE(team_id, nil-uuid), scope, path) );
COALESCE trick: nil-UUID placeholder cho phép nhiều docs cùng path khi agent_id NULL — giải quyết edge case team docs không thuộc agent cụ thể.

Indices

HNSW (Hierarchical Navigable Small World, m=16, ef=64) — index chuyên dụng cho vector search, tìm documents "gần nhau" về ngữ nghĩa. GIN (Generalized Inverted Index) — index cho full-text search, tìm nhanh documents chứa keyword cụ thể.

HNSW
Vector Index
GIN
FTS Index
m=16
HNSW M
ef=64
HNSW ef

vault_links

vault_links — bidirectional links
CREATE TABLE vault_links ( id UUID PRIMARY KEY, from_doc_id UUID REFERENCES vault_documents(id) ON DELETE CASCADE, to_doc_id UUID REFERENCES vault_documents(id) ON DELETE CASCADE, link_type TEXT DEFAULT 'wikilink', context TEXT DEFAULT '', UNIQUE(from_doc_id, to_doc_id, link_type) );

7 loại link: wikilink (tự động từ [[...]]), reference, depends_on, extends, related, supersedes, contradicts. Semantic links do LLM phân loại.

04 — Wikilinks

[[Links]] hai chiều

Bidirectional markdown links theo format [[target]] — giống Obsidian hay Notion.

internal/vault/links.go
var wikilinkRe = regexp.MustCompile(`\[\[([^\]|]+)(?:\|[^\]]+)?\]\]`) // [[path/to/file.md]] → path-based // [[name|display text]] → display text ignored // Context: ~25 chars before + after

Resolution Strategy

Exact pathGetDocument(tenantID, agentID, target)
Path + .md — Retry with .md suffix
Basename search — Indexed column path_basename
Basename + .md — Last resort. Unresolved = nil

Sync Strategy

SyncDocLinks() — replace strategy: Extract [[...]] → xóa outgoing wikilinks cũ → resolve targets → batch tạo mới. Semantic links (LLM-classified) không bị ảnh hưởng.

05 — Hybrid Search

FTS + Vector + Cross-Store Fan-Out

Tại sao cần "hybrid"?

Giả sử agent search "cách xác thực người dùng": FTS tìm đúng keyword nhưng bỏ sót docs dùng từ khác ("authentication flow"). Vector search hiểu nghĩa tương đương nhưng đôi khi trả kết quả "gần nghĩa" nhưng không liên quan. Kết hợp cả hai: FTS cho precision, vector cho recall.

Bước 1: FTS + Vector trong Vault

FTS — keyword match (ts_rank)
SELECT ..., ts_rank(tsv, plainto_tsquery('simple', $1)) AS score FROM vault_documents WHERE tenant_id = $2 AND tsv @@ plainto_tsquery('simple', $1) ORDER BY score DESC LIMIT $N
Vector — semantic match (pgvector cosine)
SELECT ..., 1 - (embedding <=> $1) AS score FROM vault_documents WHERE tenant_id = $2 AND embedding IS NOT NULL ORDER BY embedding <=> $1 LIMIT $N -- Score = 1 - cosine_distance (1.0 = identical)
Merge: FTS 0.4, Vector 0.6. Normalize theo max score → weighted sum. Document xuất hiện ở cả 2 → cộng scores.

Bước 2: Fan-Out qua 3 Sources

VaultSearchService.Search() — Parallel Fan-Out
VaultStore
0.4
FTS + Vector
EpisodicStore
0.3
Lịch sử hội thoại
KGStore
0.3
Knowledge graph
Normalize (max=1.0)
Loại trùng theo ID
Sort weighted DESC
Top N

Graceful degradation: Store nil → skip.

Overshooting: Mỗi store trả maxResults*2.

Team context: Từ RunContext — chống spoofing.

06 — Enrichment Pipeline

5-phase async worker

Khi document ghi vào workspace, chưa sẵn sàng cho search. EnrichWorker xử lý async qua 5 phase để biến raw file thành searchable document.

P0Prepare
P1Summarize
P2Embed
P3Classify
P4Wikilinks
Phase 0: Prepare

Dedup check (docID + hash) → batch fetch metadata → đọc file (max 4MB) → filter docs đã có summary.

Phase 1: Batch Summarize

Gom 5 docs vào 1 LLM call. Temp 0.2, max 1536 tokens. Output JSON: [{"idx":1,"summary":"..."}]. Giảm 5x LLM calls.

Phase 2: Embed

Ghép title + path + summary → embedding vector 1536 chiều. Biến text thành "tọa độ" trong không gian ngữ nghĩa.

Phase 3: Classify Links

FindSimilarDocs (cosine ≥ 0.7) → LLM classify thành 6 loại link. Temp 0.1. Output SKIP nếu không có mối quan hệ.

Phase 4: Wikilink Sync

Extract [[...]] → resolve targets → xóa wikilinks cũ → batch tạo mới. Dedup map bounded 10K entries, evict 25%.

Tuning Constants

5
Batch Size
3
Max Concurrent
3k
Runes/File
0.7
Cosine Min

Retry: Escalating timeouts 5→7→10 phút, backoffs 0→2→4s. BatchQueue: Lock-free producer-consumer per tenant:agent — ngăn thundering herd khi rescan.

07 — Filesystem Sync & Safety

Đồng bộ & bảo vệ workspace

Agent ghi file, nhưng file có thể bị sửa từ bên ngoài (user edit, git pull). Vault có 3 cơ chế đồng bộ:

VaultSyncWorker

fsnotify theo dõi workspace. Debounce 500ms → SHA-256 hash → so sánh DB → trigger EnrichWorker nếu thay đổi. Chỉ sync docs đã đăng ký.

SafeWalkWorkspace

Quét toàn bộ workspace với limits: 5K files, 500MB total, 50MB/file. Skip symlinks, node_modules, .git. Path traversal blocked.

Lazy Hash Sync

VaultInterceptor.BeforeRead() — khi agent đọc file, check hash FS vs DB. Catch external edits ngay cả khi watcher không chạy.

Ownership Inference

workspace/ → scope inference
workspace/ ├── agents/{agent_key}/... → scope="personal" ├── teams/{team_uuid}/... → scope="team" └── anything/else → scope="shared"
08 — Retriever Integration

Auto-inject vào agent context

VaultRetriever tự động inject relevant documents vào context trước khi agent suy nghĩ — agent không cần chủ động gọi vault_search.

RetrieverConfig
type RetrieverConfig struct { RelevanceThreshold float64 // 0.3 — loại kết quả quá thấp MaxL0Items int // 5 — giới hạn context size TenantID string }

User hỏi "cách thiết lập authentication" → vault tự inject docs/auth.md (score 0.92) + SOUL.md (score 0.45) vào context → agent trả lời chính xác hơn, không cần user chỉ file.

09 — Use Cases

Ứng dụng thực tế

Agent tự tổ chức workspace

Agent ghi notes, dùng [[wikilinks]] cross-reference. Vault tự phát hiện links, tạo backlinks, index nội dung. Search trả về cả file trực tiếp lẫn docs liên quan qua wikilinks.

Team knowledge sharing

Personal docs (agents/my-agent/) chỉ agent thấy. Team docs (teams/uuid/) mọi thành viên search được. Personal có thể [[link]] đến team docs.

Context-aware responses

VaultRetriever tự inject relevant docs trước khi agent trả lời. User hỏi "authentication?" → agent đã có docs/auth.md trong context, không cần chỉ dẫn.

10 — Áp Dụng Ngay

Mở Dashboard, dùng ngay

Knowledge Vault không cần cài đặt hay cấu hình gì thêm — mở Dashboard là dùng được ngay.

localhost:3000/vault
Knowledge Vault Dashboard

Mở Knowledge Vault

Sidebar trái → Vault (nhóm DATA). Giao diện 2 phần: danh sách documents (trái) + knowledge graph visualization (phải). Thanh lọc theo type (context, memory, note, skill, episodic, media) + dropdown lọc agent/team.

Upload Documents

Nhấn + (góc phải trên) → dialog "Upload to Vault" hiện lên → chọn phạm vi (Shared/Agent/Team) → kéo thả hoặc click để chọn files (.md, .txt, .json, .yaml, .csv, ...) → Upload. Enrichment pipeline tự chạy.

Rescan Workspace (tùy chọn)

Nhấn nút Rescan workspace (ngay cạnh nút +) → quét toàn bộ workspace, phát hiện files mới/thay đổi, tự suy luận scope (personal/team/shared).

Explore, Graph & Search

Sidebar duyệt documents theo type. Panel phải hiển thị knowledge graph — pan/zoom khám phá relationships giữa các docs. Search bar tìm kiếm thống nhất. Tạo manual links trong detail panel. Agent tự dùng vault trong hội thoại.

11 — Agent Tool

vault_search

Tool tìm kiếm thống nhất qua tất cả knowledge sources — agent gọi trực tiếp trong hội thoại khi cần tìm tài liệu.

ParamTypeRequiredMô tả
querystringNatural language search query
scopestringFilter: personal, team, shared (mặc định: all)
typesstringComma-separated: context, memory, note, skill, episodic (mặc định: all)
maxResultsnumberSố kết quả tối đa (mặc định: 10)
vault_search — ví dụ
{ "query": "authentication flow", "scope": "team", "types": "context,note", "maxResults": 10 } // User: "Tìm tài liệu về authentication" // Agent → vault_search(query="authentication") // → Top 10 từ vault + episodic + KG
12 — REST API

HTTP Endpoints

Documents

MethodEndpointChức năng
GET/v1/vault/documentsDanh sách documents (filter: scope, doc_type, team_id)
POST/v1/vault/documentsTạo document mới
GET/v1/vault/documents/{docID}Chi tiết 1 document
PUT/v1/vault/documents/{docID}Cập nhật metadata
DELETE/v1/vault/documents/{docID}Xóa document

Links

MethodEndpointChức năng
GET.../{docID}/linksOutbound + backlinks
POST/v1/vault/linksTạo link (from, to, type, context)
DELETE/v1/vault/links/{linkID}Xóa link
POST/v1/vault/links/batchBatch get links cho nhiều doc IDs

Search & Operations

MethodEndpointChức năng
POST/v1/vault/searchUnified cross-store search
POST/v1/vault/uploadUpload files (max 50 files, 50MB/file)
POST/v1/vault/rescanQuét lại workspace
GET...enrichment-statusTiến độ enrichment (JSON/SSE)

Per-agent endpoints: Tất cả cũng có bản scoped tại /v1/agents/{agentID}/vault/... (backward compatible).

Concurrency guard: Rescan chặn 2 scan song song cùng tenant. Non-owner: Chỉ thấy personal docs + teams mình thuộc về.

13 — Schema Evolution

4 migrations

MigrationNội dung
000038Initial: vault_documents, vault_links, vault_versions
000042Thêm summary, regenerate tsvector
000043Thêm team_id, custom_scope
000046Nullable agent_id, COALESCE constraint, trigger auto-scope
Migration 046: Trigger tự set scope='shared' khi agent bị xóa và doc không thuộc team — tránh orphaned documents.
14 — Tóm tắt kỹ thuật

File references

ComponentFileVai trò
Vault serviceinternal/vault/*.goSearch coordinator, enrichment, wikilinks, FS walk
PG storeinternal/store/pg/vault_*.goHybrid search (FTS + vector), link management
SQLite storeinternal/store/sqlitestore/vault_*.goLite edition: FTS-only
Toolsinternal/tools/vault_*.govault_search tool, VaultInterceptor hooks
HTTP handlersinternal/http/vault_*.goREST API, upload, rescan, enrichment status
Migrationsmigrations/000038-000046Schema evolution (4 iterations)

Design Trade-offs

Search Weights

FTS 0.4, Vector 0.6 — Vector ưu tiên semantic; FTS bổ sung keyword precision. Cross-store 0.4/0.3/0.3 — Vault curated content ưu tiên.

Batch Processing

5 docs/LLM call — Balance throughput vs quality. Cosine 0.7 — Chỉ classify truly similar, giảm noise.

Schema Flexibility

Nullable agent_id — Team docs không bắt buộc thuộc agent. Replace strategy cho wikilinks — đơn giản, idempotent.