Elffuss BraidHub

kikocis/utopia public

dev · 4.5 KiBRawPermalink
1//! Agent/对话记忆:episodes 快速路径。
2//!
3//! 设计(零新轮子):记忆空间 = 知识库本身;每条 episode = 隐式 "Memory" 来源下
4//! "Memory log" 文档上追加的一个 chunk(文本内嵌事发时间戳行)。于是全链路复用:
5//! chunk 进全文/向量索引(记忆可检索)、fact_evidence 指 chunk(记忆事实可溯源到
6//! 原话)、extracted_at 增量抽取只处理新 episode、事实 valid_from 取事发时间、
7//! 与既有 functional 事实矛盾时时态引擎自动闭合——"上月喜欢 A 本月改 B"自然
8//! 变成两段区间。账本纪律:episodes 只追加,永不改写。
9
10use chrono::{DateTime, Utc};
11use sqlx::PgPool;
12use utopia_core::AppResult;
13use uuid::Uuid;
14
15pub const MEMORY_SOURCE_KIND: &str = "memory";
16const MEMORY_DOC_KEY: &str = "memory:log";
17
18/// 每 KB 的隐式 Memory 来源(不可删;Library 里可见——记忆透明是特性)。
19pub async fn get_or_create_memory_source(pool: &PgPool, kb_id: Uuid) -> AppResult<Uuid> {
20 if let Some((id,)) = sqlx::query_as::<_, (Uuid,)>(
21 "SELECT id FROM sources WHERE kb_id = $1 AND kind = $2 LIMIT 1",
22 )
23 .bind(kb_id)
24 .bind(MEMORY_SOURCE_KIND)
25 .fetch_optional(pool)
26 .await?
27 {
28 return Ok(id);
29 }
30 let id = Uuid::now_v7();
31 sqlx::query(
32 "INSERT INTO sources (id, kb_id, kind, name, config) VALUES ($1, $2, $3, 'Memory', '{}')",
33 )
34 .bind(id)
35 .bind(kb_id)
36 .bind(MEMORY_SOURCE_KIND)
37 .execute(pool)
38 .await?;
39 Ok(id)
40}
41
42/// Memory log 文档(每 KB 一份)。绕开 documents::create 的同内容去重——
43/// 它不是内容寻址的文件,sha256 填哨兵值。
44pub async fn get_or_create_memory_doc(pool: &PgPool, kb_id: Uuid) -> AppResult<Uuid> {
45 if let Some((id,)) = sqlx::query_as::<_, (Uuid,)>(
46 "SELECT id FROM documents WHERE kb_id = $1 AND external_key = $2 LIMIT 1",
47 )
48 .bind(kb_id)
49 .bind(MEMORY_DOC_KEY)
50 .fetch_optional(pool)
51 .await?
52 {
53 return Ok(id);
54 }
55 let source_id = get_or_create_memory_source(pool, kb_id).await?;
56 let id = Uuid::now_v7();
57 sqlx::query(
58 "INSERT INTO documents
59 (id, kb_id, source_id, filename, mime, size_bytes, sha256,
60 status, graph_status, external_key, doc_time_source)
61 VALUES ($1, $2, $3, 'memory-log.md', 'text/markdown', 0, 'memory:log',
62 'ready', 'done', $4, 'none')",
63 )
64 .bind(id)
65 .bind(kb_id)
66 .bind(source_id)
67 .bind(MEMORY_DOC_KEY)
68 .execute(pool)
69 .await?;
70 Ok(id)
71}
72
73/// 追加一条 episode:新 chunk(extracted_at 空 → 增量抽取会拾起;embedding 空 →
74/// memory_ingest 会补)。事发时间内嵌进文本首行,抽取模型据此定 valid_from。
75pub async fn append_episode(
76 pool: &PgPool,
77 kb_id: Uuid,
78 text: &str,
79 occurred_at: DateTime<Utc>,
80) -> AppResult<(Uuid, Uuid)> {
81 let doc_id = get_or_create_memory_doc(pool, kb_id).await?;
82 let stamped = format!("[{}] {}", occurred_at.format("%Y-%m-%d %H:%M"), text.trim());
83 let chunk_id = Uuid::now_v7();
84 let mut tx = pool.begin().await?;
85 sqlx::query(
86 "INSERT INTO chunks (id, kb_id, document_id, seq, text, char_start, char_end, doc_version)
87 VALUES ($1, $2, $3,
88 (SELECT COALESCE(MAX(seq), -1) + 1 FROM chunks
89 WHERE document_id = $3 AND superseded_at IS NULL),
90 $4, 0, $5, 1)",
91 )
92 .bind(chunk_id)
93 .bind(kb_id)
94 .bind(doc_id)
95 .bind(&stamped)
96 .bind(stamped.chars().count() as i32)
97 .execute(&mut *tx)
98 .await?;
99 sqlx::query(
100 "UPDATE documents SET chunk_count = chunk_count + 1, size_bytes = size_bytes + $2,
101 updated_at = now() WHERE id = $1",
102 )
103 .bind(doc_id)
104 .bind(stamped.len() as i64)
105 .execute(&mut *tx)
106 .await?;
107 tx.commit().await?;
108 Ok((doc_id, chunk_id))
109}
110
111/// 这篇文档是不是记忆日志。
112///
113/// **抽取据此决定事实要不要人点头**(0015):记忆是人在对话里特意说的一句话,
114/// 一次一条、人就在现场,确认成本最低;而摄进来的文档一次上万条,逐条确认
115/// 是不可能的,那条路仍旧乐观写入 + 事后审阅。
116pub async fn is_memory_document(pool: &PgPool, document_id: Uuid) -> AppResult<bool> {
117 let found: Option<(i32,)> = sqlx::query_as(
118 "SELECT 1 FROM documents d JOIN sources s ON s.id = d.source_id
119 WHERE d.id = $1 AND s.kind = $2",
120 )
121 .bind(document_id)
122 .bind(MEMORY_SOURCE_KIND)
123 .fetch_optional(pool)
124 .await?;
125 Ok(found.is_some())
126}